body
stringlengths
26
98.2k
body_hash
int64
-9,222,864,604,528,158,000
9,221,803,474B
docstring
stringlengths
1
16.8k
path
stringlengths
5
230
name
stringlengths
1
96
repository_name
stringlengths
7
89
lang
stringclasses
1 value
body_without_docstring
stringlengths
20
98.2k
def test_keywordarg_passes_through_classicalnode(self, qubit_device_2_wires, tol): "Tests that qnodes' keyword arguments pass through classical nodes." def circuit(w, x=None): qml.RX(w, wires=[0]) qml.RX(x, wires=[1]) return (qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))) circuit = qml.QNode(circuit, qubit_device_2_wires).to_tf() def classnode(w, x=None): return circuit(w, x=x) c = classnode(tf.constant(0.0), x=np.pi) assert np.allclose(c.numpy(), [1.0, (- 1.0)], atol=tol, rtol=0)
-8,997,125,060,598,245,000
Tests that qnodes' keyword arguments pass through classical nodes.
artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#385/after/test_tf.py
test_keywordarg_passes_through_classicalnode
MattePalte/Bugs-Quantum-Computing-Platforms
python
def test_keywordarg_passes_through_classicalnode(self, qubit_device_2_wires, tol): def circuit(w, x=None): qml.RX(w, wires=[0]) qml.RX(x, wires=[1]) return (qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1))) circuit = qml.QNode(circuit, qubit_device_2_wires).to_tf() def classnode(w, x=None): return circuit(w, x=x) c = classnode(tf.constant(0.0), x=np.pi) assert np.allclose(c.numpy(), [1.0, (- 1.0)], atol=tol, rtol=0)
def test_keywordarg_gradient(self, qubit_device_2_wires, tol): "Tests that qnodes' keyword arguments work with gradients" def circuit(x, y, input_state=np.array([0, 0])): qml.BasisState(input_state, wires=[0, 1]) qml.RX(x, wires=[0]) qml.RY(y, wires=[0]) return qml.expval(qml.PauliZ(0)) circuit = qml.QNode(circuit, qubit_device_2_wires).to_tf() x = 0.543 y = 0.45632 expected_grad = np.array([(np.sin(x) * np.cos(y)), (np.sin(y) * np.cos(x))]) x_t = Variable(x) y_t = Variable(y) with tf.GradientTape() as tape: c = circuit(x_t, y_t, input_state=np.array([0, 0])) grads = np.array(tape.gradient(c, [x_t, y_t])) assert np.allclose(grads, (- expected_grad), atol=tol, rtol=0) with tf.GradientTape() as tape: c = circuit(x_t, y_t, input_state=np.array([1, 0])) grads = np.array(tape.gradient(c, [x_t, y_t])) assert np.allclose(grads, expected_grad, atol=tol, rtol=0) with tf.GradientTape() as tape: c = circuit(x_t, y_t) grads = np.array(tape.gradient(c, [x_t, y_t])) assert np.allclose(grads, (- expected_grad), atol=tol, rtol=0)
8,919,149,541,014,781,000
Tests that qnodes' keyword arguments work with gradients
artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#385/after/test_tf.py
test_keywordarg_gradient
MattePalte/Bugs-Quantum-Computing-Platforms
python
def test_keywordarg_gradient(self, qubit_device_2_wires, tol): def circuit(x, y, input_state=np.array([0, 0])): qml.BasisState(input_state, wires=[0, 1]) qml.RX(x, wires=[0]) qml.RY(y, wires=[0]) return qml.expval(qml.PauliZ(0)) circuit = qml.QNode(circuit, qubit_device_2_wires).to_tf() x = 0.543 y = 0.45632 expected_grad = np.array([(np.sin(x) * np.cos(y)), (np.sin(y) * np.cos(x))]) x_t = Variable(x) y_t = Variable(y) with tf.GradientTape() as tape: c = circuit(x_t, y_t, input_state=np.array([0, 0])) grads = np.array(tape.gradient(c, [x_t, y_t])) assert np.allclose(grads, (- expected_grad), atol=tol, rtol=0) with tf.GradientTape() as tape: c = circuit(x_t, y_t, input_state=np.array([1, 0])) grads = np.array(tape.gradient(c, [x_t, y_t])) assert np.allclose(grads, expected_grad, atol=tol, rtol=0) with tf.GradientTape() as tape: c = circuit(x_t, y_t) grads = np.array(tape.gradient(c, [x_t, y_t])) assert np.allclose(grads, (- expected_grad), atol=tol, rtol=0)
def test_qnode_evaluation_agrees(self, qubit_device_2_wires, tol): 'Tests that simple example is consistent.' @qml.qnode(qubit_device_2_wires, interface='autograd') def circuit(phi, theta): qml.RX(phi[0], wires=0) qml.RY(phi[1], wires=1) qml.CNOT(wires=[0, 1]) qml.PhaseShift(theta[0], wires=0) return qml.expval(qml.PauliZ(0)) @qml.qnode(qubit_device_2_wires, interface='tf') def circuit_tf(phi, theta): qml.RX(phi[0], wires=0) qml.RY(phi[1], wires=1) qml.CNOT(wires=[0, 1]) qml.PhaseShift(theta[0], wires=0) return qml.expval(qml.PauliZ(0)) phi = [0.5, 0.1] theta = [0.2] phi_t = Variable(phi) theta_t = Variable(theta) autograd_eval = circuit(phi, theta) tf_eval = circuit_tf(phi_t, theta_t) assert np.allclose(autograd_eval, tf_eval.numpy(), atol=tol, rtol=0)
4,092,149,334,003,494,000
Tests that simple example is consistent.
artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#385/after/test_tf.py
test_qnode_evaluation_agrees
MattePalte/Bugs-Quantum-Computing-Platforms
python
def test_qnode_evaluation_agrees(self, qubit_device_2_wires, tol): @qml.qnode(qubit_device_2_wires, interface='autograd') def circuit(phi, theta): qml.RX(phi[0], wires=0) qml.RY(phi[1], wires=1) qml.CNOT(wires=[0, 1]) qml.PhaseShift(theta[0], wires=0) return qml.expval(qml.PauliZ(0)) @qml.qnode(qubit_device_2_wires, interface='tf') def circuit_tf(phi, theta): qml.RX(phi[0], wires=0) qml.RY(phi[1], wires=1) qml.CNOT(wires=[0, 1]) qml.PhaseShift(theta[0], wires=0) return qml.expval(qml.PauliZ(0)) phi = [0.5, 0.1] theta = [0.2] phi_t = Variable(phi) theta_t = Variable(theta) autograd_eval = circuit(phi, theta) tf_eval = circuit_tf(phi_t, theta_t) assert np.allclose(autograd_eval, tf_eval.numpy(), atol=tol, rtol=0)
def test_qnode_gradient_agrees(self, qubit_device_2_wires, tol): 'Tests that simple gradient example is consistent.' @qml.qnode(qubit_device_2_wires, interface='autograd') def circuit(phi, theta): qml.RX(phi[0], wires=0) qml.RY(phi[1], wires=1) qml.CNOT(wires=[0, 1]) qml.PhaseShift(theta[0], wires=0) return qml.expval(qml.PauliZ(0)) @qml.qnode(qubit_device_2_wires, interface='tf') def circuit_tf(phi, theta): qml.RX(phi[0], wires=0) qml.RY(phi[1], wires=1) qml.CNOT(wires=[0, 1]) qml.PhaseShift(theta[0], wires=0) return qml.expval(qml.PauliZ(0)) phi = [0.5, 0.1] theta = [0.2] phi_t = Variable(phi) theta_t = Variable(theta) dcircuit = qml.grad(circuit, [0, 1]) autograd_grad = dcircuit(phi, theta) with tf.GradientTape() as g: g.watch([phi_t, theta_t]) y = circuit_tf(phi_t, theta_t) tf_grad = g.gradient(y, [phi_t, theta_t]) assert np.allclose(autograd_grad[0], tf_grad[0], atol=tol, rtol=0) assert np.allclose(autograd_grad[1], tf_grad[1], atol=tol, rtol=0)
-1,064,862,785,118,787,500
Tests that simple gradient example is consistent.
artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#385/after/test_tf.py
test_qnode_gradient_agrees
MattePalte/Bugs-Quantum-Computing-Platforms
python
def test_qnode_gradient_agrees(self, qubit_device_2_wires, tol): @qml.qnode(qubit_device_2_wires, interface='autograd') def circuit(phi, theta): qml.RX(phi[0], wires=0) qml.RY(phi[1], wires=1) qml.CNOT(wires=[0, 1]) qml.PhaseShift(theta[0], wires=0) return qml.expval(qml.PauliZ(0)) @qml.qnode(qubit_device_2_wires, interface='tf') def circuit_tf(phi, theta): qml.RX(phi[0], wires=0) qml.RY(phi[1], wires=1) qml.CNOT(wires=[0, 1]) qml.PhaseShift(theta[0], wires=0) return qml.expval(qml.PauliZ(0)) phi = [0.5, 0.1] theta = [0.2] phi_t = Variable(phi) theta_t = Variable(theta) dcircuit = qml.grad(circuit, [0, 1]) autograd_grad = dcircuit(phi, theta) with tf.GradientTape() as g: g.watch([phi_t, theta_t]) y = circuit_tf(phi_t, theta_t) tf_grad = g.gradient(y, [phi_t, theta_t]) assert np.allclose(autograd_grad[0], tf_grad[0], atol=tol, rtol=0) assert np.allclose(autograd_grad[1], tf_grad[1], atol=tol, rtol=0)
@pytest.fixture def qnodes(self): 'Two QNodes to be used for the gradient tests' dev = qml.device('default.qubit', wires=2) @qml.qnode(dev, interface='tf') def f(x): qml.RX(x, wires=0) return qml.expval(qml.PauliZ(0)) @qml.qnode(dev, interface='tf') def g(y): qml.RY(y, wires=0) return qml.expval(qml.PauliX(0)) return (f, g)
-7,397,888,158,913,202,000
Two QNodes to be used for the gradient tests
artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#385/after/test_tf.py
qnodes
MattePalte/Bugs-Quantum-Computing-Platforms
python
@pytest.fixture def qnodes(self): dev = qml.device('default.qubit', wires=2) @qml.qnode(dev, interface='tf') def f(x): qml.RX(x, wires=0) return qml.expval(qml.PauliZ(0)) @qml.qnode(dev, interface='tf') def g(y): qml.RY(y, wires=0) return qml.expval(qml.PauliX(0)) return (f, g)
@pytest.mark.parametrize('x, y', gradient_test_data) def test_addition_qnodes_gradient(self, qnodes, x, y): 'Test the gradient of addition of two QNode circuits' (f, g) = qnodes def add(a, b): return (a + b) xt = Variable(x) yt = Variable(y) with tf.GradientTape() as tape: tape.watch([xt, yt]) a = f(xt) b = g(yt) y = add(a, b) grad = tape.gradient(y, [a, b]) assert (grad[0].numpy() == 1.0) assert (grad[1].numpy() == 1.0) with tf.GradientTape() as tape: tape.watch([xt, yt]) a = f(xt) y = add(a, a) grad = tape.gradient(y, [a, a]) assert (grad[0].numpy() == 2.0) assert (grad[1].numpy() == 2.0) with tf.GradientTape() as tape: tape.watch([xt, yt]) a = f(xt) b = g(xt) y = add(a, b) grad = tape.gradient(y, [a, b]) assert (grad[0].numpy() == 1.0) assert (grad[1].numpy() == 1.0)
-4,094,283,874,855,288,300
Test the gradient of addition of two QNode circuits
artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#385/after/test_tf.py
test_addition_qnodes_gradient
MattePalte/Bugs-Quantum-Computing-Platforms
python
@pytest.mark.parametrize('x, y', gradient_test_data) def test_addition_qnodes_gradient(self, qnodes, x, y): (f, g) = qnodes def add(a, b): return (a + b) xt = Variable(x) yt = Variable(y) with tf.GradientTape() as tape: tape.watch([xt, yt]) a = f(xt) b = g(yt) y = add(a, b) grad = tape.gradient(y, [a, b]) assert (grad[0].numpy() == 1.0) assert (grad[1].numpy() == 1.0) with tf.GradientTape() as tape: tape.watch([xt, yt]) a = f(xt) y = add(a, a) grad = tape.gradient(y, [a, a]) assert (grad[0].numpy() == 2.0) assert (grad[1].numpy() == 2.0) with tf.GradientTape() as tape: tape.watch([xt, yt]) a = f(xt) b = g(xt) y = add(a, b) grad = tape.gradient(y, [a, b]) assert (grad[0].numpy() == 1.0) assert (grad[1].numpy() == 1.0)
@pytest.mark.parametrize('x, y', gradient_test_data) def test_subtraction_qnodes_gradient(self, qnodes, x, y): 'Test the gradient of subtraction of two QNode circuits' (f, g) = qnodes def subtract(a, b): return (a - b) xt = Variable(x) yt = Variable(y) with tf.GradientTape() as tape: tape.watch([xt, yt]) a = f(xt) b = g(yt) y = subtract(a, b) grad = tape.gradient(y, [a, b]) assert (grad[0].numpy() == 1.0) assert (grad[1].numpy() == (- 1.0))
2,051,418,203,866,679,300
Test the gradient of subtraction of two QNode circuits
artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#385/after/test_tf.py
test_subtraction_qnodes_gradient
MattePalte/Bugs-Quantum-Computing-Platforms
python
@pytest.mark.parametrize('x, y', gradient_test_data) def test_subtraction_qnodes_gradient(self, qnodes, x, y): (f, g) = qnodes def subtract(a, b): return (a - b) xt = Variable(x) yt = Variable(y) with tf.GradientTape() as tape: tape.watch([xt, yt]) a = f(xt) b = g(yt) y = subtract(a, b) grad = tape.gradient(y, [a, b]) assert (grad[0].numpy() == 1.0) assert (grad[1].numpy() == (- 1.0))
@pytest.mark.parametrize('x, y', gradient_test_data) def test_multiplication_qnodes_gradient(self, qnodes, x, y): 'Test the gradient of multiplication of two QNode circuits' (f, g) = qnodes def mult(a, b): return (a * b) xt = Variable(x) yt = Variable(y) with tf.GradientTape() as tape: tape.watch([xt, yt]) a = f(xt) b = g(yt) y = mult(a, b) grad = tape.gradient(y, [a, b]) assert (grad[0].numpy() == b.numpy()) assert (grad[1].numpy() == a.numpy())
-5,933,840,820,186,481,000
Test the gradient of multiplication of two QNode circuits
artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#385/after/test_tf.py
test_multiplication_qnodes_gradient
MattePalte/Bugs-Quantum-Computing-Platforms
python
@pytest.mark.parametrize('x, y', gradient_test_data) def test_multiplication_qnodes_gradient(self, qnodes, x, y): (f, g) = qnodes def mult(a, b): return (a * b) xt = Variable(x) yt = Variable(y) with tf.GradientTape() as tape: tape.watch([xt, yt]) a = f(xt) b = g(yt) y = mult(a, b) grad = tape.gradient(y, [a, b]) assert (grad[0].numpy() == b.numpy()) assert (grad[1].numpy() == a.numpy())
@pytest.mark.parametrize('x, y', gradient_test_data) def test_division_qnodes_gradient(self, qnodes, x, y, tol): 'Test the gradient of division of two QNode circuits' (f, g) = qnodes def div(a, b): return (a / b) xt = Variable(x) yt = Variable(y) with tf.GradientTape() as tape: tape.watch([xt, yt]) a = f(xt) b = g(yt) y = div(a, b) grad = tape.gradient(y, [a, b]) assert (grad[0].numpy() == (1 / b.numpy())) assert np.allclose(grad[1].numpy(), ((- a.numpy()) / (b.numpy() ** 2)), atol=tol, rtol=0)
-7,874,686,265,030,168,000
Test the gradient of division of two QNode circuits
artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#385/after/test_tf.py
test_division_qnodes_gradient
MattePalte/Bugs-Quantum-Computing-Platforms
python
@pytest.mark.parametrize('x, y', gradient_test_data) def test_division_qnodes_gradient(self, qnodes, x, y, tol): (f, g) = qnodes def div(a, b): return (a / b) xt = Variable(x) yt = Variable(y) with tf.GradientTape() as tape: tape.watch([xt, yt]) a = f(xt) b = g(yt) y = div(a, b) grad = tape.gradient(y, [a, b]) assert (grad[0].numpy() == (1 / b.numpy())) assert np.allclose(grad[1].numpy(), ((- a.numpy()) / (b.numpy() ** 2)), atol=tol, rtol=0)
@pytest.mark.parametrize('x, y', gradient_test_data) def test_composition_qnodes_gradient(self, qnodes, x, y): 'Test the gradient of composition of two QNode circuits' (f, g) = qnodes xt = Variable(x) yt = Variable(y) with tf.GradientTape() as tape: tape.watch([xt]) y = f(xt) grad1 = tape.gradient(y, xt) with tf.GradientTape() as tape: tape.watch([xt]) y = f(xt) grad2 = tape.gradient(y, xt) assert tf.equal(grad1, grad2) with tf.GradientTape() as tape: tape.watch([xt]) a = f(xt) y = f(a) grad1 = tape.gradient(y, a) with tf.GradientTape() as tape: tape.watch([xt]) a = f(xt) y = f(a) grad2 = tape.gradient(y, a) assert tf.equal(grad1, grad2) with tf.GradientTape() as tape: tape.watch([xt]) b = g(xt) y = g(b) grad1 = tape.gradient(y, b) with tf.GradientTape() as tape: tape.watch([xt]) b = g(xt) y = g(b) grad2 = tape.gradient(y, b) assert tf.equal(grad1, grad2)
5,884,952,253,218,689,000
Test the gradient of composition of two QNode circuits
artifacts/old_dataset_versions/minimal_commits/pennylane/pennylane#385/after/test_tf.py
test_composition_qnodes_gradient
MattePalte/Bugs-Quantum-Computing-Platforms
python
@pytest.mark.parametrize('x, y', gradient_test_data) def test_composition_qnodes_gradient(self, qnodes, x, y): (f, g) = qnodes xt = Variable(x) yt = Variable(y) with tf.GradientTape() as tape: tape.watch([xt]) y = f(xt) grad1 = tape.gradient(y, xt) with tf.GradientTape() as tape: tape.watch([xt]) y = f(xt) grad2 = tape.gradient(y, xt) assert tf.equal(grad1, grad2) with tf.GradientTape() as tape: tape.watch([xt]) a = f(xt) y = f(a) grad1 = tape.gradient(y, a) with tf.GradientTape() as tape: tape.watch([xt]) a = f(xt) y = f(a) grad2 = tape.gradient(y, a) assert tf.equal(grad1, grad2) with tf.GradientTape() as tape: tape.watch([xt]) b = g(xt) y = g(b) grad1 = tape.gradient(y, b) with tf.GradientTape() as tape: tape.watch([xt]) b = g(xt) y = g(b) grad2 = tape.gradient(y, b) assert tf.equal(grad1, grad2)
def tearDown(self): '\n Clean up all the event sources left behind by either directly by\n test methods or indirectly via some distrib API.\n ' dl = [defer.Deferred(), defer.Deferred()] if ((self.f1 is not None) and (self.f1.proto is not None)): self.f1.proto.notifyOnDisconnect((lambda : dl[0].callback(None))) else: dl[0].callback(None) if ((self.sub is not None) and (self.sub.publisher is not None)): self.sub.publisher.broker.notifyOnDisconnect((lambda : dl[1].callback(None))) self.sub.publisher.broker.transport.loseConnection() else: dl[1].callback(None) if (self.port1 is not None): dl.append(self.port1.stopListening()) if (self.port2 is not None): dl.append(self.port2.stopListening()) return defer.gatherResults(dl)
3,693,195,591,005,340,700
Clean up all the event sources left behind by either directly by test methods or indirectly via some distrib API.
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
tearDown
12123ads/learn_python3_spider
python
def tearDown(self): '\n Clean up all the event sources left behind by either directly by\n test methods or indirectly via some distrib API.\n ' dl = [defer.Deferred(), defer.Deferred()] if ((self.f1 is not None) and (self.f1.proto is not None)): self.f1.proto.notifyOnDisconnect((lambda : dl[0].callback(None))) else: dl[0].callback(None) if ((self.sub is not None) and (self.sub.publisher is not None)): self.sub.publisher.broker.notifyOnDisconnect((lambda : dl[1].callback(None))) self.sub.publisher.broker.transport.loseConnection() else: dl[1].callback(None) if (self.port1 is not None): dl.append(self.port1.stopListening()) if (self.port2 is not None): dl.append(self.port2.stopListening()) return defer.gatherResults(dl)
def _setupDistribServer(self, child): '\n Set up a resource on a distrib site using L{ResourcePublisher}.\n\n @param child: The resource to publish using distrib.\n\n @return: A tuple consisting of the host and port on which to contact\n the created site.\n ' distribRoot = resource.Resource() distribRoot.putChild(b'child', child) distribSite = server.Site(distribRoot) self.f1 = distribFactory = PBServerFactory(distrib.ResourcePublisher(distribSite)) distribPort = reactor.listenTCP(0, distribFactory, interface='127.0.0.1') self.addCleanup(distribPort.stopListening) addr = distribPort.getHost() self.sub = mainRoot = distrib.ResourceSubscription(addr.host, addr.port) mainSite = server.Site(mainRoot) mainPort = reactor.listenTCP(0, mainSite, interface='127.0.0.1') self.addCleanup(mainPort.stopListening) mainAddr = mainPort.getHost() return (mainPort, mainAddr)
-8,420,973,455,920,807,000
Set up a resource on a distrib site using L{ResourcePublisher}. @param child: The resource to publish using distrib. @return: A tuple consisting of the host and port on which to contact the created site.
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
_setupDistribServer
12123ads/learn_python3_spider
python
def _setupDistribServer(self, child): '\n Set up a resource on a distrib site using L{ResourcePublisher}.\n\n @param child: The resource to publish using distrib.\n\n @return: A tuple consisting of the host and port on which to contact\n the created site.\n ' distribRoot = resource.Resource() distribRoot.putChild(b'child', child) distribSite = server.Site(distribRoot) self.f1 = distribFactory = PBServerFactory(distrib.ResourcePublisher(distribSite)) distribPort = reactor.listenTCP(0, distribFactory, interface='127.0.0.1') self.addCleanup(distribPort.stopListening) addr = distribPort.getHost() self.sub = mainRoot = distrib.ResourceSubscription(addr.host, addr.port) mainSite = server.Site(mainRoot) mainPort = reactor.listenTCP(0, mainSite, interface='127.0.0.1') self.addCleanup(mainPort.stopListening) mainAddr = mainPort.getHost() return (mainPort, mainAddr)
def _requestTest(self, child, **kwargs): '\n Set up a resource on a distrib site using L{ResourcePublisher} and\n then retrieve it from a L{ResourceSubscription} via an HTTP client.\n\n @param child: The resource to publish using distrib.\n @param **kwargs: Extra keyword arguments to pass to L{Agent.request} when\n requesting the resource.\n\n @return: A L{Deferred} which fires with the result of the request.\n ' (mainPort, mainAddr) = self._setupDistribServer(child) agent = client.Agent(reactor) url = ('http://%s:%s/child' % (mainAddr.host, mainAddr.port)) url = url.encode('ascii') d = agent.request(b'GET', url, **kwargs) d.addCallback(client.readBody) return d
8,997,882,814,128,054,000
Set up a resource on a distrib site using L{ResourcePublisher} and then retrieve it from a L{ResourceSubscription} via an HTTP client. @param child: The resource to publish using distrib. @param **kwargs: Extra keyword arguments to pass to L{Agent.request} when requesting the resource. @return: A L{Deferred} which fires with the result of the request.
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
_requestTest
12123ads/learn_python3_spider
python
def _requestTest(self, child, **kwargs): '\n Set up a resource on a distrib site using L{ResourcePublisher} and\n then retrieve it from a L{ResourceSubscription} via an HTTP client.\n\n @param child: The resource to publish using distrib.\n @param **kwargs: Extra keyword arguments to pass to L{Agent.request} when\n requesting the resource.\n\n @return: A L{Deferred} which fires with the result of the request.\n ' (mainPort, mainAddr) = self._setupDistribServer(child) agent = client.Agent(reactor) url = ('http://%s:%s/child' % (mainAddr.host, mainAddr.port)) url = url.encode('ascii') d = agent.request(b'GET', url, **kwargs) d.addCallback(client.readBody) return d
def _requestAgentTest(self, child, **kwargs): '\n Set up a resource on a distrib site using L{ResourcePublisher} and\n then retrieve it from a L{ResourceSubscription} via an HTTP client.\n\n @param child: The resource to publish using distrib.\n @param **kwargs: Extra keyword arguments to pass to L{Agent.request} when\n requesting the resource.\n\n @return: A L{Deferred} which fires with a tuple consisting of a\n L{twisted.test.proto_helpers.AccumulatingProtocol} containing the\n body of the response and an L{IResponse} with the response itself.\n ' (mainPort, mainAddr) = self._setupDistribServer(child) url = 'http://{}:{}/child'.format(mainAddr.host, mainAddr.port) url = url.encode('ascii') d = client.Agent(reactor).request(b'GET', url, **kwargs) def cbCollectBody(response): protocol = proto_helpers.AccumulatingProtocol() response.deliverBody(protocol) d = protocol.closedDeferred = defer.Deferred() d.addCallback((lambda _: (protocol, response))) return d d.addCallback(cbCollectBody) return d
-3,814,017,065,179,760,000
Set up a resource on a distrib site using L{ResourcePublisher} and then retrieve it from a L{ResourceSubscription} via an HTTP client. @param child: The resource to publish using distrib. @param **kwargs: Extra keyword arguments to pass to L{Agent.request} when requesting the resource. @return: A L{Deferred} which fires with a tuple consisting of a L{twisted.test.proto_helpers.AccumulatingProtocol} containing the body of the response and an L{IResponse} with the response itself.
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
_requestAgentTest
12123ads/learn_python3_spider
python
def _requestAgentTest(self, child, **kwargs): '\n Set up a resource on a distrib site using L{ResourcePublisher} and\n then retrieve it from a L{ResourceSubscription} via an HTTP client.\n\n @param child: The resource to publish using distrib.\n @param **kwargs: Extra keyword arguments to pass to L{Agent.request} when\n requesting the resource.\n\n @return: A L{Deferred} which fires with a tuple consisting of a\n L{twisted.test.proto_helpers.AccumulatingProtocol} containing the\n body of the response and an L{IResponse} with the response itself.\n ' (mainPort, mainAddr) = self._setupDistribServer(child) url = 'http://{}:{}/child'.format(mainAddr.host, mainAddr.port) url = url.encode('ascii') d = client.Agent(reactor).request(b'GET', url, **kwargs) def cbCollectBody(response): protocol = proto_helpers.AccumulatingProtocol() response.deliverBody(protocol) d = protocol.closedDeferred = defer.Deferred() d.addCallback((lambda _: (protocol, response))) return d d.addCallback(cbCollectBody) return d
def test_requestHeaders(self): "\n The request headers are available on the request object passed to a\n distributed resource's C{render} method.\n " requestHeaders = {} logObserver = proto_helpers.EventLoggingObserver() globalLogPublisher.addObserver(logObserver) req = [None] class ReportRequestHeaders(resource.Resource): def render(self, request): req[0] = request requestHeaders.update(dict(request.requestHeaders.getAllRawHeaders())) return b'' def check_logs(): msgs = [e['log_format'] for e in logObserver] self.assertIn('connected to publisher', msgs) self.assertIn('could not connect to distributed web service: {msg}', msgs) self.assertIn(req[0], msgs) globalLogPublisher.removeObserver(logObserver) request = self._requestTest(ReportRequestHeaders(), headers=Headers({'foo': ['bar']})) def cbRequested(result): self.f1.proto.notifyOnDisconnect(check_logs) self.assertEqual(requestHeaders[b'Foo'], [b'bar']) request.addCallback(cbRequested) return request
6,032,571,273,442,479,000
The request headers are available on the request object passed to a distributed resource's C{render} method.
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
test_requestHeaders
12123ads/learn_python3_spider
python
def test_requestHeaders(self): "\n The request headers are available on the request object passed to a\n distributed resource's C{render} method.\n " requestHeaders = {} logObserver = proto_helpers.EventLoggingObserver() globalLogPublisher.addObserver(logObserver) req = [None] class ReportRequestHeaders(resource.Resource): def render(self, request): req[0] = request requestHeaders.update(dict(request.requestHeaders.getAllRawHeaders())) return b def check_logs(): msgs = [e['log_format'] for e in logObserver] self.assertIn('connected to publisher', msgs) self.assertIn('could not connect to distributed web service: {msg}', msgs) self.assertIn(req[0], msgs) globalLogPublisher.removeObserver(logObserver) request = self._requestTest(ReportRequestHeaders(), headers=Headers({'foo': ['bar']})) def cbRequested(result): self.f1.proto.notifyOnDisconnect(check_logs) self.assertEqual(requestHeaders[b'Foo'], [b'bar']) request.addCallback(cbRequested) return request
def test_requestResponseCode(self): "\n The response code can be set by the request object passed to a\n distributed resource's C{render} method.\n " class SetResponseCode(resource.Resource): def render(self, request): request.setResponseCode(200) return '' request = self._requestAgentTest(SetResponseCode()) def cbRequested(result): self.assertEqual(result[0].data, b'') self.assertEqual(result[1].code, 200) self.assertEqual(result[1].phrase, b'OK') request.addCallback(cbRequested) return request
1,863,444,923,536,960,300
The response code can be set by the request object passed to a distributed resource's C{render} method.
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
test_requestResponseCode
12123ads/learn_python3_spider
python
def test_requestResponseCode(self): "\n The response code can be set by the request object passed to a\n distributed resource's C{render} method.\n " class SetResponseCode(resource.Resource): def render(self, request): request.setResponseCode(200) return request = self._requestAgentTest(SetResponseCode()) def cbRequested(result): self.assertEqual(result[0].data, b) self.assertEqual(result[1].code, 200) self.assertEqual(result[1].phrase, b'OK') request.addCallback(cbRequested) return request
def test_requestResponseCodeMessage(self): "\n The response code and message can be set by the request object passed to\n a distributed resource's C{render} method.\n " class SetResponseCode(resource.Resource): def render(self, request): request.setResponseCode(200, b'some-message') return '' request = self._requestAgentTest(SetResponseCode()) def cbRequested(result): self.assertEqual(result[0].data, b'') self.assertEqual(result[1].code, 200) self.assertEqual(result[1].phrase, b'some-message') request.addCallback(cbRequested) return request
2,802,432,140,346,846,700
The response code and message can be set by the request object passed to a distributed resource's C{render} method.
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
test_requestResponseCodeMessage
12123ads/learn_python3_spider
python
def test_requestResponseCodeMessage(self): "\n The response code and message can be set by the request object passed to\n a distributed resource's C{render} method.\n " class SetResponseCode(resource.Resource): def render(self, request): request.setResponseCode(200, b'some-message') return request = self._requestAgentTest(SetResponseCode()) def cbRequested(result): self.assertEqual(result[0].data, b) self.assertEqual(result[1].code, 200) self.assertEqual(result[1].phrase, b'some-message') request.addCallback(cbRequested) return request
def test_largeWrite(self): '\n If a string longer than the Banana size limit is passed to the\n L{distrib.Request} passed to the remote resource, it is broken into\n smaller strings to be transported over the PB connection.\n ' class LargeWrite(resource.Resource): def render(self, request): request.write(((b'x' * SIZE_LIMIT) + b'y')) request.finish() return server.NOT_DONE_YET request = self._requestTest(LargeWrite()) request.addCallback(self.assertEqual, ((b'x' * SIZE_LIMIT) + b'y')) return request
-5,210,885,590,019,892,000
If a string longer than the Banana size limit is passed to the L{distrib.Request} passed to the remote resource, it is broken into smaller strings to be transported over the PB connection.
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
test_largeWrite
12123ads/learn_python3_spider
python
def test_largeWrite(self): '\n If a string longer than the Banana size limit is passed to the\n L{distrib.Request} passed to the remote resource, it is broken into\n smaller strings to be transported over the PB connection.\n ' class LargeWrite(resource.Resource): def render(self, request): request.write(((b'x' * SIZE_LIMIT) + b'y')) request.finish() return server.NOT_DONE_YET request = self._requestTest(LargeWrite()) request.addCallback(self.assertEqual, ((b'x' * SIZE_LIMIT) + b'y')) return request
def test_largeReturn(self): '\n Like L{test_largeWrite}, but for the case where C{render} returns a\n long string rather than explicitly passing it to L{Request.write}.\n ' class LargeReturn(resource.Resource): def render(self, request): return ((b'x' * SIZE_LIMIT) + b'y') request = self._requestTest(LargeReturn()) request.addCallback(self.assertEqual, ((b'x' * SIZE_LIMIT) + b'y')) return request
-9,676,789,066,152,152
Like L{test_largeWrite}, but for the case where C{render} returns a long string rather than explicitly passing it to L{Request.write}.
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
test_largeReturn
12123ads/learn_python3_spider
python
def test_largeReturn(self): '\n Like L{test_largeWrite}, but for the case where C{render} returns a\n long string rather than explicitly passing it to L{Request.write}.\n ' class LargeReturn(resource.Resource): def render(self, request): return ((b'x' * SIZE_LIMIT) + b'y') request = self._requestTest(LargeReturn()) request.addCallback(self.assertEqual, ((b'x' * SIZE_LIMIT) + b'y')) return request
def test_connectionLost(self): '\n If there is an error issuing the request to the remote publisher, an\n error response is returned.\n ' self.f1 = serverFactory = PBServerFactory(pb.Root()) self.port1 = serverPort = reactor.listenTCP(0, serverFactory) self.sub = subscription = distrib.ResourceSubscription('127.0.0.1', serverPort.getHost().port) request = DummyRequest([b'']) d = _render(subscription, request) def cbRendered(ignored): self.assertEqual(request.responseCode, 500) errors = self.flushLoggedErrors(pb.NoSuchMethod) self.assertEqual(len(errors), 1) expected = [b'', b'<html>', b' <head><title>500 - Server Connection Lost</title></head>', b' <body>', b' <h1>Server Connection Lost</h1>', b' <p>Connection to distributed server lost:<pre>[Failure instance: Traceback from remote host -- twisted.spread.flavors.NoSuchMethod: No such method: remote_request', b']</pre></p>', b' </body>', b'</html>', b''] self.assertEqual([b'\n'.join(expected)], request.written) d.addCallback(cbRendered) return d
-6,647,387,831,302,386,000
If there is an error issuing the request to the remote publisher, an error response is returned.
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
test_connectionLost
12123ads/learn_python3_spider
python
def test_connectionLost(self): '\n If there is an error issuing the request to the remote publisher, an\n error response is returned.\n ' self.f1 = serverFactory = PBServerFactory(pb.Root()) self.port1 = serverPort = reactor.listenTCP(0, serverFactory) self.sub = subscription = distrib.ResourceSubscription('127.0.0.1', serverPort.getHost().port) request = DummyRequest([b]) d = _render(subscription, request) def cbRendered(ignored): self.assertEqual(request.responseCode, 500) errors = self.flushLoggedErrors(pb.NoSuchMethod) self.assertEqual(len(errors), 1) expected = [b, b'<html>', b' <head><title>500 - Server Connection Lost</title></head>', b' <body>', b' <h1>Server Connection Lost</h1>', b' <p>Connection to distributed server lost:<pre>[Failure instance: Traceback from remote host -- twisted.spread.flavors.NoSuchMethod: No such method: remote_request', b']</pre></p>', b' </body>', b'</html>', b] self.assertEqual([b'\n'.join(expected)], request.written) d.addCallback(cbRendered) return d
def test_logFailed(self): '\n When a request fails, the string form of the failure is logged.\n ' logObserver = proto_helpers.EventLoggingObserver.createWithCleanup(self, globalLogPublisher) f = failure.Failure(ArbitraryError()) request = DummyRequest([b'']) issue = distrib.Issue(request) issue.failed(f) self.assertEquals(1, len(logObserver)) self.assertIn('Failure instance', logObserver[0]['log_format'])
117,272,590,343,925,780
When a request fails, the string form of the failure is logged.
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
test_logFailed
12123ads/learn_python3_spider
python
def test_logFailed(self): '\n \n ' logObserver = proto_helpers.EventLoggingObserver.createWithCleanup(self, globalLogPublisher) f = failure.Failure(ArbitraryError()) request = DummyRequest([b]) issue = distrib.Issue(request) issue.failed(f) self.assertEquals(1, len(logObserver)) self.assertIn('Failure instance', logObserver[0]['log_format'])
def test_requestFail(self): "\n When L{twisted.web.distrib.Request}'s fail is called, the failure\n is logged.\n " logObserver = proto_helpers.EventLoggingObserver.createWithCleanup(self, globalLogPublisher) err = ArbitraryError() f = failure.Failure(err) req = distrib.Request(DummyChannel()) req.fail(f) self.flushLoggedErrors(ArbitraryError) self.assertEquals(1, len(logObserver)) self.assertIs(logObserver[0]['log_failure'], f)
4,460,541,986,423,108,000
When L{twisted.web.distrib.Request}'s fail is called, the failure is logged.
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
test_requestFail
12123ads/learn_python3_spider
python
def test_requestFail(self): "\n When L{twisted.web.distrib.Request}'s fail is called, the failure\n is logged.\n " logObserver = proto_helpers.EventLoggingObserver.createWithCleanup(self, globalLogPublisher) err = ArbitraryError() f = failure.Failure(err) req = distrib.Request(DummyChannel()) req.fail(f) self.flushLoggedErrors(ArbitraryError) self.assertEquals(1, len(logObserver)) self.assertIs(logObserver[0]['log_failure'], f)
def test_interface(self): '\n L{UserDirectory} instances provide L{resource.IResource}.\n ' self.assertTrue(verifyObject(resource.IResource, self.directory))
2,984,908,371,918,376,400
L{UserDirectory} instances provide L{resource.IResource}.
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
test_interface
12123ads/learn_python3_spider
python
def test_interface(self): '\n \n ' self.assertTrue(verifyObject(resource.IResource, self.directory))
def _404Test(self, name): '\n Verify that requesting the C{name} child of C{self.directory} results\n in a 404 response.\n ' request = DummyRequest([name]) result = self.directory.getChild(name, request) d = _render(result, request) def cbRendered(ignored): self.assertEqual(request.responseCode, 404) d.addCallback(cbRendered) return d
-7,691,561,648,553,702,000
Verify that requesting the C{name} child of C{self.directory} results in a 404 response.
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
_404Test
12123ads/learn_python3_spider
python
def _404Test(self, name): '\n Verify that requesting the C{name} child of C{self.directory} results\n in a 404 response.\n ' request = DummyRequest([name]) result = self.directory.getChild(name, request) d = _render(result, request) def cbRendered(ignored): self.assertEqual(request.responseCode, 404) d.addCallback(cbRendered) return d
def test_getInvalidUser(self): '\n L{UserDirectory.getChild} returns a resource which renders a 404\n response when passed a string which does not correspond to any known\n user.\n ' return self._404Test('carol')
524,398,963,170,523,840
L{UserDirectory.getChild} returns a resource which renders a 404 response when passed a string which does not correspond to any known user.
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
test_getInvalidUser
12123ads/learn_python3_spider
python
def test_getInvalidUser(self): '\n L{UserDirectory.getChild} returns a resource which renders a 404\n response when passed a string which does not correspond to any known\n user.\n ' return self._404Test('carol')
def test_getUserWithoutResource(self): '\n L{UserDirectory.getChild} returns a resource which renders a 404\n response when passed a string which corresponds to a known user who has\n neither a user directory nor a user distrib socket.\n ' return self._404Test('alice')
2,095,579,798,873,494,500
L{UserDirectory.getChild} returns a resource which renders a 404 response when passed a string which corresponds to a known user who has neither a user directory nor a user distrib socket.
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
test_getUserWithoutResource
12123ads/learn_python3_spider
python
def test_getUserWithoutResource(self): '\n L{UserDirectory.getChild} returns a resource which renders a 404\n response when passed a string which corresponds to a known user who has\n neither a user directory nor a user distrib socket.\n ' return self._404Test('alice')
def test_getPublicHTMLChild(self): '\n L{UserDirectory.getChild} returns a L{static.File} instance when passed\n the name of a user with a home directory containing a I{public_html}\n directory.\n ' home = filepath.FilePath(self.bob[(- 2)]) public_html = home.child('public_html') public_html.makedirs() request = DummyRequest(['bob']) result = self.directory.getChild('bob', request) self.assertIsInstance(result, static.File) self.assertEqual(result.path, public_html.path)
8,963,394,596,767,200,000
L{UserDirectory.getChild} returns a L{static.File} instance when passed the name of a user with a home directory containing a I{public_html} directory.
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
test_getPublicHTMLChild
12123ads/learn_python3_spider
python
def test_getPublicHTMLChild(self): '\n L{UserDirectory.getChild} returns a L{static.File} instance when passed\n the name of a user with a home directory containing a I{public_html}\n directory.\n ' home = filepath.FilePath(self.bob[(- 2)]) public_html = home.child('public_html') public_html.makedirs() request = DummyRequest(['bob']) result = self.directory.getChild('bob', request) self.assertIsInstance(result, static.File) self.assertEqual(result.path, public_html.path)
def test_getDistribChild(self): '\n L{UserDirectory.getChild} returns a L{ResourceSubscription} instance\n when passed the name of a user suffixed with C{".twistd"} who has a\n home directory containing a I{.twistd-web-pb} socket.\n ' home = filepath.FilePath(self.bob[(- 2)]) home.makedirs() web = home.child('.twistd-web-pb') request = DummyRequest(['bob']) result = self.directory.getChild('bob.twistd', request) self.assertIsInstance(result, distrib.ResourceSubscription) self.assertEqual(result.host, 'unix') self.assertEqual(abspath(result.port), web.path)
2,114,948,889,774,105,000
L{UserDirectory.getChild} returns a L{ResourceSubscription} instance when passed the name of a user suffixed with C{".twistd"} who has a home directory containing a I{.twistd-web-pb} socket.
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
test_getDistribChild
12123ads/learn_python3_spider
python
def test_getDistribChild(self): '\n L{UserDirectory.getChild} returns a L{ResourceSubscription} instance\n when passed the name of a user suffixed with C{".twistd"} who has a\n home directory containing a I{.twistd-web-pb} socket.\n ' home = filepath.FilePath(self.bob[(- 2)]) home.makedirs() web = home.child('.twistd-web-pb') request = DummyRequest(['bob']) result = self.directory.getChild('bob.twistd', request) self.assertIsInstance(result, distrib.ResourceSubscription) self.assertEqual(result.host, 'unix') self.assertEqual(abspath(result.port), web.path)
def test_invalidMethod(self): '\n L{UserDirectory.render} raises L{UnsupportedMethod} in response to a\n non-I{GET} request.\n ' request = DummyRequest(['']) request.method = 'POST' self.assertRaises(server.UnsupportedMethod, self.directory.render, request)
6,040,538,577,880,428,000
L{UserDirectory.render} raises L{UnsupportedMethod} in response to a non-I{GET} request.
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
test_invalidMethod
12123ads/learn_python3_spider
python
def test_invalidMethod(self): '\n L{UserDirectory.render} raises L{UnsupportedMethod} in response to a\n non-I{GET} request.\n ' request = DummyRequest([]) request.method = 'POST' self.assertRaises(server.UnsupportedMethod, self.directory.render, request)
def test_render(self): '\n L{UserDirectory} renders a list of links to available user content\n in response to a I{GET} request.\n ' public_html = filepath.FilePath(self.alice[(- 2)]).child('public_html') public_html.makedirs() web = filepath.FilePath(self.bob[(- 2)]) web.makedirs() web.child('.twistd-web-pb').setContent(b'') request = DummyRequest(['']) result = _render(self.directory, request) def cbRendered(ignored): document = parseString(b''.join(request.written)) [alice, bob] = document.getElementsByTagName('li') self.assertEqual(alice.firstChild.tagName, 'a') self.assertEqual(alice.firstChild.getAttribute('href'), 'alice/') self.assertEqual(alice.firstChild.firstChild.data, 'Alice (file)') self.assertEqual(bob.firstChild.tagName, 'a') self.assertEqual(bob.firstChild.getAttribute('href'), 'bob.twistd/') self.assertEqual(bob.firstChild.firstChild.data, 'Bob (twistd)') result.addCallback(cbRendered) return result
-8,024,123,066,555,492,000
L{UserDirectory} renders a list of links to available user content in response to a I{GET} request.
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
test_render
12123ads/learn_python3_spider
python
def test_render(self): '\n L{UserDirectory} renders a list of links to available user content\n in response to a I{GET} request.\n ' public_html = filepath.FilePath(self.alice[(- 2)]).child('public_html') public_html.makedirs() web = filepath.FilePath(self.bob[(- 2)]) web.makedirs() web.child('.twistd-web-pb').setContent(b) request = DummyRequest([]) result = _render(self.directory, request) def cbRendered(ignored): document = parseString(b.join(request.written)) [alice, bob] = document.getElementsByTagName('li') self.assertEqual(alice.firstChild.tagName, 'a') self.assertEqual(alice.firstChild.getAttribute('href'), 'alice/') self.assertEqual(alice.firstChild.firstChild.data, 'Alice (file)') self.assertEqual(bob.firstChild.tagName, 'a') self.assertEqual(bob.firstChild.getAttribute('href'), 'bob.twistd/') self.assertEqual(bob.firstChild.firstChild.data, 'Bob (twistd)') result.addCallback(cbRendered) return result
def test_passwordDatabase(self): '\n If L{UserDirectory} is instantiated with no arguments, it uses the\n L{pwd} module as its password database.\n ' directory = distrib.UserDirectory() self.assertIdentical(directory._pwd, pwd)
-2,410,661,611,890,471,400
If L{UserDirectory} is instantiated with no arguments, it uses the L{pwd} module as its password database.
stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_distrib.py
test_passwordDatabase
12123ads/learn_python3_spider
python
def test_passwordDatabase(self): '\n If L{UserDirectory} is instantiated with no arguments, it uses the\n L{pwd} module as its password database.\n ' directory = distrib.UserDirectory() self.assertIdentical(directory._pwd, pwd)
def on_train_begin(self, **kwargs): 'Call watch method to log model topology, gradients & weights' super().on_train_begin() if (not WandbCallback._watch_called): WandbCallback._watch_called = True wandb.watch(self.learn.model, log=self.log)
8,583,803,843,895,094,000
Call watch method to log model topology, gradients & weights
wandb/fastai/__init__.py
on_train_begin
MPGek/client
python
def on_train_begin(self, **kwargs): super().on_train_begin() if (not WandbCallback._watch_called): WandbCallback._watch_called = True wandb.watch(self.learn.model, log=self.log)
def on_epoch_end(self, epoch, smooth_loss, last_metrics, **kwargs): 'Logs training loss, validation loss and custom metrics & log prediction samples & save model' if self.save_model: current = self.get_monitor_value() if ((current is not None) and self.operator(current, self.best)): print('Better model found at epoch {} with {} value: {}.'.format(epoch, self.monitor, current)) self.best = current with self.model_path.open('wb') as model_file: self.learn.save(model_file) if self.validation_data: try: self._wandb_log_predictions() except FastaiError as e: wandb.termwarn(e.message) self.validation_data = None except Exception as e: wandb.termwarn('Unable to log prediction samples.\n{}'.format(e)) self.validation_data = None logs = {name: stat for (name, stat) in list(zip(self.learn.recorder.names, ([epoch, smooth_loss] + last_metrics)))} wandb.log(logs)
-2,929,695,461,219,322,000
Logs training loss, validation loss and custom metrics & log prediction samples & save model
wandb/fastai/__init__.py
on_epoch_end
MPGek/client
python
def on_epoch_end(self, epoch, smooth_loss, last_metrics, **kwargs): if self.save_model: current = self.get_monitor_value() if ((current is not None) and self.operator(current, self.best)): print('Better model found at epoch {} with {} value: {}.'.format(epoch, self.monitor, current)) self.best = current with self.model_path.open('wb') as model_file: self.learn.save(model_file) if self.validation_data: try: self._wandb_log_predictions() except FastaiError as e: wandb.termwarn(e.message) self.validation_data = None except Exception as e: wandb.termwarn('Unable to log prediction samples.\n{}'.format(e)) self.validation_data = None logs = {name: stat for (name, stat) in list(zip(self.learn.recorder.names, ([epoch, smooth_loss] + last_metrics)))} wandb.log(logs)
def on_train_end(self, **kwargs): 'Load the best model.' if self.save_model: if self.model_path.is_file(): with self.model_path.open('rb') as model_file: self.learn.load(model_file, purge=False) print('Loaded best saved model from {}'.format(self.model_path))
-5,013,564,440,215,056,000
Load the best model.
wandb/fastai/__init__.py
on_train_end
MPGek/client
python
def on_train_end(self, **kwargs): if self.save_model: if self.model_path.is_file(): with self.model_path.open('rb') as model_file: self.learn.load(model_file, purge=False) print('Loaded best saved model from {}'.format(self.model_path))
def _wandb_log_predictions(self): 'Log prediction samples' pred_log = [] for (x, y) in self.validation_data: try: pred = self.learn.predict(x) except: raise FastaiError('Unable to run "predict" method from Learner to log prediction samples.') if (not pred[1].shape): pred_log.append(wandb.Image(x.data, caption='Ground Truth: {}\nPrediction: {}'.format(y, pred[0]))) elif hasattr(x, 'show'): pred_log.append(wandb.Image(x.data, caption='Input data', grouping=3)) for (im, capt) in ((pred[0], 'Prediction'), (y, 'Ground Truth')): my_dpi = 100 fig = plt.figure(frameon=False, dpi=my_dpi) (h, w) = x.size fig.set_size_inches((w / my_dpi), (h / my_dpi)) ax = plt.Axes(fig, [0.0, 0.0, 1.0, 1.0]) ax.set_axis_off() fig.add_axes(ax) x.show(ax=ax, y=im) pred_log.append(wandb.Image(fig, caption=capt)) plt.close(fig) elif (hasattr(y, 'shape') and ((len(y.shape) == 2) or ((len(y.shape) == 3) and (y.shape[0] in [1, 3, 4])))): pred_log.extend([wandb.Image(x.data, caption='Input data', grouping=3), wandb.Image(pred[0].data, caption='Prediction'), wandb.Image(y.data, caption='Ground Truth')]) else: pred_log.append(wandb.Image(x.data, caption='Input data')) wandb.log({'Prediction Samples': pred_log}, commit=False)
-7,904,175,559,029,698,000
Log prediction samples
wandb/fastai/__init__.py
_wandb_log_predictions
MPGek/client
python
def _wandb_log_predictions(self): pred_log = [] for (x, y) in self.validation_data: try: pred = self.learn.predict(x) except: raise FastaiError('Unable to run "predict" method from Learner to log prediction samples.') if (not pred[1].shape): pred_log.append(wandb.Image(x.data, caption='Ground Truth: {}\nPrediction: {}'.format(y, pred[0]))) elif hasattr(x, 'show'): pred_log.append(wandb.Image(x.data, caption='Input data', grouping=3)) for (im, capt) in ((pred[0], 'Prediction'), (y, 'Ground Truth')): my_dpi = 100 fig = plt.figure(frameon=False, dpi=my_dpi) (h, w) = x.size fig.set_size_inches((w / my_dpi), (h / my_dpi)) ax = plt.Axes(fig, [0.0, 0.0, 1.0, 1.0]) ax.set_axis_off() fig.add_axes(ax) x.show(ax=ax, y=im) pred_log.append(wandb.Image(fig, caption=capt)) plt.close(fig) elif (hasattr(y, 'shape') and ((len(y.shape) == 2) or ((len(y.shape) == 3) and (y.shape[0] in [1, 3, 4])))): pred_log.extend([wandb.Image(x.data, caption='Input data', grouping=3), wandb.Image(pred[0].data, caption='Prediction'), wandb.Image(y.data, caption='Ground Truth')]) else: pred_log.append(wandb.Image(x.data, caption='Input data')) wandb.log({'Prediction Samples': pred_log}, commit=False)
def find_in_path(name, path): 'Find a file in a search path' for dir in path.split(os.pathsep): binpath = pjoin(dir, name) if os.path.exists(binpath): return os.path.abspath(binpath) return None
-4,401,254,251,811,251,000
Find a file in a search path
swig_muesli/muesli/da/setup_da.py
find_in_path
NinaHerrmann/muesli2py
python
def find_in_path(name, path): for dir in path.split(os.pathsep): binpath = pjoin(dir, name) if os.path.exists(binpath): return os.path.abspath(binpath) return None
def length_normalize(matrix): 'Length normalize the matrix\n\n Args:\n matrix (np.ndarray): Input matrix that needs to be normalized\n\n Returns:\n Normalized matrix\n ' norms = np.sqrt(np.sum((matrix ** 2), axis=1)) norms[(norms == 0)] = 1 return (matrix / norms[:, np.newaxis])
-9,094,982,554,804,503,000
Length normalize the matrix Args: matrix (np.ndarray): Input matrix that needs to be normalized Returns: Normalized matrix
reco_utils/recommender/geoimc/geoimc_utils.py
length_normalize
154King154/recommenders
python
def length_normalize(matrix): 'Length normalize the matrix\n\n Args:\n matrix (np.ndarray): Input matrix that needs to be normalized\n\n Returns:\n Normalized matrix\n ' norms = np.sqrt(np.sum((matrix ** 2), axis=1)) norms[(norms == 0)] = 1 return (matrix / norms[:, np.newaxis])
def mean_center(matrix): 'Performs mean centering across axis 0\n\n Args:\n matrix (np.ndarray): Input matrix that needs to be mean centered\n ' avg = np.mean(matrix, axis=0) matrix -= avg
313,667,976,247,406,600
Performs mean centering across axis 0 Args: matrix (np.ndarray): Input matrix that needs to be mean centered
reco_utils/recommender/geoimc/geoimc_utils.py
mean_center
154King154/recommenders
python
def mean_center(matrix): 'Performs mean centering across axis 0\n\n Args:\n matrix (np.ndarray): Input matrix that needs to be mean centered\n ' avg = np.mean(matrix, axis=0) matrix -= avg
def reduce_dims(matrix, target_dim): 'Reduce dimensionality of the data using PCA.\n\n Args:\n matrix (np.ndarray): Matrix of the form (n_sampes, n_features)\n target_dim (uint): Dimension to which n_features should be reduced to.\n\n ' model = PCA(n_components=target_dim) model.fit(matrix) return model.transform(matrix)
8,133,367,132,709,024,000
Reduce dimensionality of the data using PCA. Args: matrix (np.ndarray): Matrix of the form (n_sampes, n_features) target_dim (uint): Dimension to which n_features should be reduced to.
reco_utils/recommender/geoimc/geoimc_utils.py
reduce_dims
154King154/recommenders
python
def reduce_dims(matrix, target_dim): 'Reduce dimensionality of the data using PCA.\n\n Args:\n matrix (np.ndarray): Matrix of the form (n_sampes, n_features)\n target_dim (uint): Dimension to which n_features should be reduced to.\n\n ' model = PCA(n_components=target_dim) model.fit(matrix) return model.transform(matrix)
def longestCommonSubsequence(self, text1: str, text2: str) -> int: '\n #最长连续公共子串\n l1=len(text1)\n l2=len(text2)\n\n if l1==0 or l2==0:\n return 0\n dp = [[0 for i in range(l2)] for i in range(l1)]\n res = 0\n if text1[0]==text2[0]:\n dp[0][0]=1\n res=1\n for i in range(1,l2):\n if text2[i]==text1[0]:\n dp[0][i]=1\n res=1\n for i in range(1,l1):\n if text1[i]==text2[0]:\n dp[i][0]=1\n res=1\n\n\n for i in range(1,l1):\n for j in range(1,l2):\n if text1[i]==text2[j]:\n dp[i][j]=dp[i-1][j-1]+1\n res=max(res,dp[i][j])\n\n return res\n ' '\n #最长子串(可不连续):其实就是在问text1[:i+1]和text2[:j+1]有多少个相同的字母\n l1 = len(text1)\n l2 = len(text2)\n\n if l1 == 0 or l2 == 0:\n return 0\n dp = [[0 for i in range(l2)] for i in range(l1)]\n if text1[0] == text2[0]:\n dp[0][0] = 1\n for i in range(1, l2):\n if text2[i] == text1[0] or dp[0][0]==1 or dp[0][i-1]==1:\n dp[0][i] = 1\n for i in range(1, l1):\n if text1[i] == text2[0] or dp[0][0]==1 or dp[i-1][0]==1:\n dp[i][0] = 1\n\n for i in range(1, l1):\n for j in range(1, l2):\n if text1[i] == text2[j]:\n dp[i][j] = dp[i - 1][j - 1] + 1\n else:\n dp[i][j]=max(dp[i][j-1],dp[i-1][j])\n\n return dp[-1][-1]\n ' if ((len(text1) == 0) or (len(text2) == 0)): return 0 if (text1[(- 1)] == text2[(- 1)]): return (1 + self.longestCommonSubsequence(text1[:(- 1)], text2[:(- 1)])) else: return max(self.longestCommonSubsequence(text1[:(- 1)], text2), self.longestCommonSubsequence(text1, text2[:(- 1)]))
-8,524,905,220,200,732,000
#最长连续公共子串 l1=len(text1) l2=len(text2) if l1==0 or l2==0: return 0 dp = [[0 for i in range(l2)] for i in range(l1)] res = 0 if text1[0]==text2[0]: dp[0][0]=1 res=1 for i in range(1,l2): if text2[i]==text1[0]: dp[0][i]=1 res=1 for i in range(1,l1): if text1[i]==text2[0]: dp[i][0]=1 res=1 for i in range(1,l1): for j in range(1,l2): if text1[i]==text2[j]: dp[i][j]=dp[i-1][j-1]+1 res=max(res,dp[i][j]) return res
DP/Leetcode1143.py
longestCommonSubsequence
Rylie-W/LeetRecord
python
def longestCommonSubsequence(self, text1: str, text2: str) -> int: '\n #最长连续公共子串\n l1=len(text1)\n l2=len(text2)\n\n if l1==0 or l2==0:\n return 0\n dp = [[0 for i in range(l2)] for i in range(l1)]\n res = 0\n if text1[0]==text2[0]:\n dp[0][0]=1\n res=1\n for i in range(1,l2):\n if text2[i]==text1[0]:\n dp[0][i]=1\n res=1\n for i in range(1,l1):\n if text1[i]==text2[0]:\n dp[i][0]=1\n res=1\n\n\n for i in range(1,l1):\n for j in range(1,l2):\n if text1[i]==text2[j]:\n dp[i][j]=dp[i-1][j-1]+1\n res=max(res,dp[i][j])\n\n return res\n ' '\n #最长子串(可不连续):其实就是在问text1[:i+1]和text2[:j+1]有多少个相同的字母\n l1 = len(text1)\n l2 = len(text2)\n\n if l1 == 0 or l2 == 0:\n return 0\n dp = [[0 for i in range(l2)] for i in range(l1)]\n if text1[0] == text2[0]:\n dp[0][0] = 1\n for i in range(1, l2):\n if text2[i] == text1[0] or dp[0][0]==1 or dp[0][i-1]==1:\n dp[0][i] = 1\n for i in range(1, l1):\n if text1[i] == text2[0] or dp[0][0]==1 or dp[i-1][0]==1:\n dp[i][0] = 1\n\n for i in range(1, l1):\n for j in range(1, l2):\n if text1[i] == text2[j]:\n dp[i][j] = dp[i - 1][j - 1] + 1\n else:\n dp[i][j]=max(dp[i][j-1],dp[i-1][j])\n\n return dp[-1][-1]\n ' if ((len(text1) == 0) or (len(text2) == 0)): return 0 if (text1[(- 1)] == text2[(- 1)]): return (1 + self.longestCommonSubsequence(text1[:(- 1)], text2[:(- 1)])) else: return max(self.longestCommonSubsequence(text1[:(- 1)], text2), self.longestCommonSubsequence(text1, text2[:(- 1)]))
def initialize_weights(model): '\n Initializes the weights of a model in place.\n\n :param model: An nn.Module.\n ' for param in model.parameters(): if (param.dim() > 1): nn.init.xavier_normal_(param)
-4,855,580,883,977,360,000
Initializes the weights of a model in place. :param model: An nn.Module.
Repeat/CoMPT/utils_node.py
initialize_weights
jcchan23/SAIL
python
def initialize_weights(model): '\n Initializes the weights of a model in place.\n\n :param model: An nn.Module.\n ' for param in model.parameters(): if (param.dim() > 1): nn.init.xavier_normal_(param)
def __init__(self, optimizer, warmup_epochs, total_epochs, steps_per_epoch, init_lr, max_lr, final_lr): '\n Initializes the learning rate scheduler.\n\n :param optimizer: A PyTorch optimizer.\n :param warmup_epochs: The number of epochs during which to linearly increase the learning rate.\n :param total_epochs: The total number of epochs.\n :param steps_per_epoch: The number of steps (batches) per epoch.\n :param init_lr: The initial learning rate.\n :param max_lr: The maximum learning rate (achieved after warmup_epochs).\n :param final_lr: The final learning rate (achieved after total_epochs).\n ' assert (len(optimizer.param_groups) == len(warmup_epochs) == len(total_epochs) == len(init_lr) == len(max_lr) == len(final_lr)) self.num_lrs = len(optimizer.param_groups) self.optimizer = optimizer self.warmup_epochs = np.array(warmup_epochs) self.total_epochs = np.array(total_epochs) self.steps_per_epoch = steps_per_epoch self.init_lr = np.array(init_lr) self.max_lr = np.array(max_lr) self.final_lr = np.array(final_lr) self.current_step = 0 self.lr = init_lr self.warmup_steps = (self.warmup_epochs * self.steps_per_epoch).astype(int) self.total_steps = (self.total_epochs * self.steps_per_epoch) self.linear_increment = ((self.max_lr - self.init_lr) / self.warmup_steps) self.exponential_gamma = ((self.final_lr / self.max_lr) ** (1 / (self.total_steps - self.warmup_steps))) super(NoamLR, self).__init__(optimizer)
8,412,762,859,212,071,000
Initializes the learning rate scheduler. :param optimizer: A PyTorch optimizer. :param warmup_epochs: The number of epochs during which to linearly increase the learning rate. :param total_epochs: The total number of epochs. :param steps_per_epoch: The number of steps (batches) per epoch. :param init_lr: The initial learning rate. :param max_lr: The maximum learning rate (achieved after warmup_epochs). :param final_lr: The final learning rate (achieved after total_epochs).
Repeat/CoMPT/utils_node.py
__init__
jcchan23/SAIL
python
def __init__(self, optimizer, warmup_epochs, total_epochs, steps_per_epoch, init_lr, max_lr, final_lr): '\n Initializes the learning rate scheduler.\n\n :param optimizer: A PyTorch optimizer.\n :param warmup_epochs: The number of epochs during which to linearly increase the learning rate.\n :param total_epochs: The total number of epochs.\n :param steps_per_epoch: The number of steps (batches) per epoch.\n :param init_lr: The initial learning rate.\n :param max_lr: The maximum learning rate (achieved after warmup_epochs).\n :param final_lr: The final learning rate (achieved after total_epochs).\n ' assert (len(optimizer.param_groups) == len(warmup_epochs) == len(total_epochs) == len(init_lr) == len(max_lr) == len(final_lr)) self.num_lrs = len(optimizer.param_groups) self.optimizer = optimizer self.warmup_epochs = np.array(warmup_epochs) self.total_epochs = np.array(total_epochs) self.steps_per_epoch = steps_per_epoch self.init_lr = np.array(init_lr) self.max_lr = np.array(max_lr) self.final_lr = np.array(final_lr) self.current_step = 0 self.lr = init_lr self.warmup_steps = (self.warmup_epochs * self.steps_per_epoch).astype(int) self.total_steps = (self.total_epochs * self.steps_per_epoch) self.linear_increment = ((self.max_lr - self.init_lr) / self.warmup_steps) self.exponential_gamma = ((self.final_lr / self.max_lr) ** (1 / (self.total_steps - self.warmup_steps))) super(NoamLR, self).__init__(optimizer)
def get_lr(self): 'Gets a list of the current learning rates.' return list(self.lr)
-3,543,556,912,278,854,700
Gets a list of the current learning rates.
Repeat/CoMPT/utils_node.py
get_lr
jcchan23/SAIL
python
def get_lr(self): return list(self.lr)
def step(self, current_step: int=None): '\n Updates the learning rate by taking a step.\n\n :param current_step: Optionally specify what step to set the learning rate to.\n If None, current_step = self.current_step + 1.\n ' if (current_step is not None): self.current_step = current_step else: self.current_step += 1 for i in range(self.num_lrs): if (self.current_step <= self.warmup_steps[i]): self.lr[i] = (self.init_lr[i] + (self.current_step * self.linear_increment[i])) elif (self.current_step <= self.total_steps[i]): self.lr[i] = (self.max_lr[i] * (self.exponential_gamma[i] ** (self.current_step - self.warmup_steps[i]))) else: self.lr[i] = self.final_lr[i] self.optimizer.param_groups[i]['lr'] = self.lr[i]
-2,704,965,584,552,467,000
Updates the learning rate by taking a step. :param current_step: Optionally specify what step to set the learning rate to. If None, current_step = self.current_step + 1.
Repeat/CoMPT/utils_node.py
step
jcchan23/SAIL
python
def step(self, current_step: int=None): '\n Updates the learning rate by taking a step.\n\n :param current_step: Optionally specify what step to set the learning rate to.\n If None, current_step = self.current_step + 1.\n ' if (current_step is not None): self.current_step = current_step else: self.current_step += 1 for i in range(self.num_lrs): if (self.current_step <= self.warmup_steps[i]): self.lr[i] = (self.init_lr[i] + (self.current_step * self.linear_increment[i])) elif (self.current_step <= self.total_steps[i]): self.lr[i] = (self.max_lr[i] * (self.exponential_gamma[i] ** (self.current_step - self.warmup_steps[i]))) else: self.lr[i] = self.final_lr[i] self.optimizer.param_groups[i]['lr'] = self.lr[i]
def setUp(self): 'Get all the PROTO files to be tested.' self.version = None with open(((((os.environ['WEBOTS_HOME'] + os.sep) + 'resources') + os.sep) + 'version.txt')) as file: content = file.read() self.version = content.splitlines()[0].strip().split()[0] self.files = [] for (rootPath, dirNames, fileNames) in os.walk(os.environ['WEBOTS_HOME']): dirNames[:] = [d for d in dirNames if (d not in skippedDirectories)] for fileName in fnmatch.filter(fileNames, '*.proto'): proto = os.path.join(rootPath, fileName) shouldIgnore = False for ignoredProto in ignoredProtos: path = ((os.environ['WEBOTS_HOME'] + os.sep) + ignoredProto.replace('/', os.sep)) if (proto == path): shouldIgnore = True break if (not shouldIgnore): self.files.append((proto, ('#VRML_SIM %s utf8' % self.version))) for (rootPath, dirNames, fileNames) in os.walk(os.environ['WEBOTS_HOME']): dirNames[:] = [d for d in dirNames if (d not in skippedDirectories)] for fileName in fnmatch.filter(fileNames, '*.wbt'): world = os.path.join(rootPath, fileName) self.files.append((world, ('#VRML_SIM %s utf8' % self.version))) for (rootPath, dirNames, fileNames) in os.walk(os.environ['WEBOTS_HOME']): dirNames[:] = [d for d in dirNames if (d not in skippedDirectories)] for fileName in fnmatch.filter(fileNames, '*.wbproj'): projFile = os.path.join(rootPath, fileName) self.files.append((projFile, ('Webots Project File version %s' % self.version)))
-3,331,968,831,251,895,300
Get all the PROTO files to be tested.
tests/sources/test_header_version.py
setUp
junjihashimoto/webots
python
def setUp(self): self.version = None with open(((((os.environ['WEBOTS_HOME'] + os.sep) + 'resources') + os.sep) + 'version.txt')) as file: content = file.read() self.version = content.splitlines()[0].strip().split()[0] self.files = [] for (rootPath, dirNames, fileNames) in os.walk(os.environ['WEBOTS_HOME']): dirNames[:] = [d for d in dirNames if (d not in skippedDirectories)] for fileName in fnmatch.filter(fileNames, '*.proto'): proto = os.path.join(rootPath, fileName) shouldIgnore = False for ignoredProto in ignoredProtos: path = ((os.environ['WEBOTS_HOME'] + os.sep) + ignoredProto.replace('/', os.sep)) if (proto == path): shouldIgnore = True break if (not shouldIgnore): self.files.append((proto, ('#VRML_SIM %s utf8' % self.version))) for (rootPath, dirNames, fileNames) in os.walk(os.environ['WEBOTS_HOME']): dirNames[:] = [d for d in dirNames if (d not in skippedDirectories)] for fileName in fnmatch.filter(fileNames, '*.wbt'): world = os.path.join(rootPath, fileName) self.files.append((world, ('#VRML_SIM %s utf8' % self.version))) for (rootPath, dirNames, fileNames) in os.walk(os.environ['WEBOTS_HOME']): dirNames[:] = [d for d in dirNames if (d not in skippedDirectories)] for fileName in fnmatch.filter(fileNames, '*.wbproj'): projFile = os.path.join(rootPath, fileName) self.files.append((projFile, ('Webots Project File version %s' % self.version)))
def test_header_version(self): 'Test that the PROTO and world files have the correct header.' for currentFile in self.files: fileToTest = currentFile[0] with open(fileToTest) as file: content = file.read() if (content == ''): continue line = content.splitlines()[0].strip() self.assertTrue(line.startswith(currentFile[1]), msg=('Wrong header in file: "%s"' % fileToTest))
-272,396,101,947,376,400
Test that the PROTO and world files have the correct header.
tests/sources/test_header_version.py
test_header_version
junjihashimoto/webots
python
def test_header_version(self): for currentFile in self.files: fileToTest = currentFile[0] with open(fileToTest) as file: content = file.read() if (content == ): continue line = content.splitlines()[0].strip() self.assertTrue(line.startswith(currentFile[1]), msg=('Wrong header in file: "%s"' % fileToTest))
def float_with_error(x): '\n some value in cif accompanies error like "1.234(5)\n ' if ('?' in x): return 0 pos = x.find('(') if (pos >= 0): x = x[:pos] return float(x)
-7,629,848,625,370,556,000
some value in cif accompanies error like "1.234(5)
cif_tools.py
float_with_error
cwaitt/zse
python
def float_with_error(x): '\n \n ' if ('?' in x): return 0 pos = x.find('(') if (pos >= 0): x = x[:pos] return float(x)
def get_indices(cif): '\n This is a tool that will read a CIF file and return the unique T-sites,\n their multiplicities, and an example atom index.\n\n It also does the same for the unique O-sites in the framework.\n\n This tool only works on CIFs that are formatted the same way as the IZA\n Structure Database CIFs.\n ' (tsites, tmults, osites, omults) = get_mults(cif) f = open(cif, 'r') alllines = f.read() f.close() for (i, line) in enumerate(alllines): if ('IT_coordinate_system_code' in line): fields = line.split() alllines[i] = '_symmetry_space_group_setting {0}'.format(fields[(- 1)]) atoms = read(cif) oinds = [atom.index for atom in atoms if (atom.symbol == 'O')] index = 0 first_os = [] for (i, m) in enumerate(omults): first_os.append(oinds[index]) index += m tinds = [atom.index for atom in atoms if (atom.symbol != 'O')] index = 0 first_ts = [] for (i, m) in enumerate(tmults): first_ts.append(tinds[index]) index += m return (tsites, tmults, first_ts, osites, omults, first_os)
-8,522,372,167,062,766,000
This is a tool that will read a CIF file and return the unique T-sites, their multiplicities, and an example atom index. It also does the same for the unique O-sites in the framework. This tool only works on CIFs that are formatted the same way as the IZA Structure Database CIFs.
cif_tools.py
get_indices
cwaitt/zse
python
def get_indices(cif): '\n This is a tool that will read a CIF file and return the unique T-sites,\n their multiplicities, and an example atom index.\n\n It also does the same for the unique O-sites in the framework.\n\n This tool only works on CIFs that are formatted the same way as the IZA\n Structure Database CIFs.\n ' (tsites, tmults, osites, omults) = get_mults(cif) f = open(cif, 'r') alllines = f.read() f.close() for (i, line) in enumerate(alllines): if ('IT_coordinate_system_code' in line): fields = line.split() alllines[i] = '_symmetry_space_group_setting {0}'.format(fields[(- 1)]) atoms = read(cif) oinds = [atom.index for atom in atoms if (atom.symbol == 'O')] index = 0 first_os = [] for (i, m) in enumerate(omults): first_os.append(oinds[index]) index += m tinds = [atom.index for atom in atoms if (atom.symbol != 'O')] index = 0 first_ts = [] for (i, m) in enumerate(tmults): first_ts.append(tinds[index]) index += m return (tsites, tmults, first_ts, osites, omults, first_os)
@classmethod def from_service_account_file(cls, filename, *args, **kwargs): 'Creates an instance of this client using the provided credentials\n file.\n\n Args:\n filename (str): The path to the service account private key json\n file.\n args: Additional arguments to pass to the constructor.\n kwargs: Additional arguments to pass to the constructor.\n\n Returns:\n TextToSpeechClient: The constructed client.\n ' credentials = service_account.Credentials.from_service_account_file(filename) kwargs['credentials'] = credentials return cls(*args, **kwargs)
8,165,111,019,497,557,000
Creates an instance of this client using the provided credentials file. Args: filename (str): The path to the service account private key json file. args: Additional arguments to pass to the constructor. kwargs: Additional arguments to pass to the constructor. Returns: TextToSpeechClient: The constructed client.
texttospeech/google/cloud/texttospeech_v1beta1/gapic/text_to_speech_client.py
from_service_account_file
Abd-Elrazek/google-cloud-python
python
@classmethod def from_service_account_file(cls, filename, *args, **kwargs): 'Creates an instance of this client using the provided credentials\n file.\n\n Args:\n filename (str): The path to the service account private key json\n file.\n args: Additional arguments to pass to the constructor.\n kwargs: Additional arguments to pass to the constructor.\n\n Returns:\n TextToSpeechClient: The constructed client.\n ' credentials = service_account.Credentials.from_service_account_file(filename) kwargs['credentials'] = credentials return cls(*args, **kwargs)
def __init__(self, transport=None, channel=None, credentials=None, client_config=None, client_info=None): "Constructor.\n\n Args:\n transport (Union[~.TextToSpeechGrpcTransport,\n Callable[[~.Credentials, type], ~.TextToSpeechGrpcTransport]): A transport\n instance, responsible for actually making the API calls.\n The default transport uses the gRPC protocol.\n This argument may also be a callable which returns a\n transport instance. Callables will be sent the credentials\n as the first argument and the default transport class as\n the second argument.\n channel (grpc.Channel): DEPRECATED. A ``Channel`` instance\n through which to make calls. This argument is mutually exclusive\n with ``credentials``; providing both will raise an exception.\n credentials (google.auth.credentials.Credentials): The\n authorization credentials to attach to requests. These\n credentials identify this application to the service. If none\n are specified, the client will attempt to ascertain the\n credentials from the environment.\n This argument is mutually exclusive with providing a\n transport instance to ``transport``; doing so will raise\n an exception.\n client_config (dict): DEPRECATED. A dictionary of call options for\n each method. If not specified, the default configuration is used.\n client_info (google.api_core.gapic_v1.client_info.ClientInfo):\n The client info used to send a user-agent string along with\n API requests. If ``None``, then default info will be used.\n Generally, you only need to set this if you're developing\n your own client library.\n " if (client_config is not None): warnings.warn('The `client_config` argument is deprecated.', PendingDeprecationWarning, stacklevel=2) else: client_config = text_to_speech_client_config.config if channel: warnings.warn('The `channel` argument is deprecated; use `transport` instead.', PendingDeprecationWarning, stacklevel=2) if transport: if callable(transport): self.transport = transport(credentials=credentials, default_class=text_to_speech_grpc_transport.TextToSpeechGrpcTransport) else: if credentials: raise ValueError('Received both a transport instance and credentials; these are mutually exclusive.') self.transport = transport else: self.transport = text_to_speech_grpc_transport.TextToSpeechGrpcTransport(address=self.SERVICE_ADDRESS, channel=channel, credentials=credentials) if (client_info is None): client_info = google.api_core.gapic_v1.client_info.ClientInfo(gapic_version=_GAPIC_LIBRARY_VERSION) else: client_info.gapic_version = _GAPIC_LIBRARY_VERSION self._client_info = client_info self._method_configs = google.api_core.gapic_v1.config.parse_method_configs(client_config['interfaces'][self._INTERFACE_NAME]) self._inner_api_calls = {}
-6,464,139,821,673,658,000
Constructor. Args: transport (Union[~.TextToSpeechGrpcTransport, Callable[[~.Credentials, type], ~.TextToSpeechGrpcTransport]): A transport instance, responsible for actually making the API calls. The default transport uses the gRPC protocol. This argument may also be a callable which returns a transport instance. Callables will be sent the credentials as the first argument and the default transport class as the second argument. channel (grpc.Channel): DEPRECATED. A ``Channel`` instance through which to make calls. This argument is mutually exclusive with ``credentials``; providing both will raise an exception. credentials (google.auth.credentials.Credentials): The authorization credentials to attach to requests. These credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. This argument is mutually exclusive with providing a transport instance to ``transport``; doing so will raise an exception. client_config (dict): DEPRECATED. A dictionary of call options for each method. If not specified, the default configuration is used. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library.
texttospeech/google/cloud/texttospeech_v1beta1/gapic/text_to_speech_client.py
__init__
Abd-Elrazek/google-cloud-python
python
def __init__(self, transport=None, channel=None, credentials=None, client_config=None, client_info=None): "Constructor.\n\n Args:\n transport (Union[~.TextToSpeechGrpcTransport,\n Callable[[~.Credentials, type], ~.TextToSpeechGrpcTransport]): A transport\n instance, responsible for actually making the API calls.\n The default transport uses the gRPC protocol.\n This argument may also be a callable which returns a\n transport instance. Callables will be sent the credentials\n as the first argument and the default transport class as\n the second argument.\n channel (grpc.Channel): DEPRECATED. A ``Channel`` instance\n through which to make calls. This argument is mutually exclusive\n with ``credentials``; providing both will raise an exception.\n credentials (google.auth.credentials.Credentials): The\n authorization credentials to attach to requests. These\n credentials identify this application to the service. If none\n are specified, the client will attempt to ascertain the\n credentials from the environment.\n This argument is mutually exclusive with providing a\n transport instance to ``transport``; doing so will raise\n an exception.\n client_config (dict): DEPRECATED. A dictionary of call options for\n each method. If not specified, the default configuration is used.\n client_info (google.api_core.gapic_v1.client_info.ClientInfo):\n The client info used to send a user-agent string along with\n API requests. If ``None``, then default info will be used.\n Generally, you only need to set this if you're developing\n your own client library.\n " if (client_config is not None): warnings.warn('The `client_config` argument is deprecated.', PendingDeprecationWarning, stacklevel=2) else: client_config = text_to_speech_client_config.config if channel: warnings.warn('The `channel` argument is deprecated; use `transport` instead.', PendingDeprecationWarning, stacklevel=2) if transport: if callable(transport): self.transport = transport(credentials=credentials, default_class=text_to_speech_grpc_transport.TextToSpeechGrpcTransport) else: if credentials: raise ValueError('Received both a transport instance and credentials; these are mutually exclusive.') self.transport = transport else: self.transport = text_to_speech_grpc_transport.TextToSpeechGrpcTransport(address=self.SERVICE_ADDRESS, channel=channel, credentials=credentials) if (client_info is None): client_info = google.api_core.gapic_v1.client_info.ClientInfo(gapic_version=_GAPIC_LIBRARY_VERSION) else: client_info.gapic_version = _GAPIC_LIBRARY_VERSION self._client_info = client_info self._method_configs = google.api_core.gapic_v1.config.parse_method_configs(client_config['interfaces'][self._INTERFACE_NAME]) self._inner_api_calls = {}
def list_voices(self, language_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): '\n Returns a list of ``Voice`` supported for synthesis.\n\n Example:\n >>> from google.cloud import texttospeech_v1beta1\n >>>\n >>> client = texttospeech_v1beta1.TextToSpeechClient()\n >>>\n >>> response = client.list_voices()\n\n Args:\n language_code (str): Optional (but recommended)\n `BCP-47 <https://www.rfc-editor.org/rfc/bcp/bcp47.txt>`__ language tag.\n If specified, the ListVoices call will only return voices that can be\n used to synthesize this language\\_code. E.g. when specifying "en-NZ",\n you will get supported "en-*" voices; when specifying "no", you will get\n supported "no-*" (Norwegian) and "nb-*" (Norwegian Bokmal) voices;\n specifying "zh" will also get supported "cmn-*" voices; specifying\n "zh-hk" will also get supported "yue-\\*" voices.\n retry (Optional[google.api_core.retry.Retry]): A retry object used\n to retry requests. If ``None`` is specified, requests will not\n be retried.\n timeout (Optional[float]): The amount of time, in seconds, to wait\n for the request to complete. Note that if ``retry`` is\n specified, the timeout applies to each individual attempt.\n metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n that is provided to the method.\n\n Returns:\n A :class:`~google.cloud.texttospeech_v1beta1.types.ListVoicesResponse` instance.\n\n Raises:\n google.api_core.exceptions.GoogleAPICallError: If the request\n failed for any reason.\n google.api_core.exceptions.RetryError: If the request failed due\n to a retryable error and retry attempts failed.\n ValueError: If the parameters are invalid.\n ' if ('list_voices' not in self._inner_api_calls): self._inner_api_calls['list_voices'] = google.api_core.gapic_v1.method.wrap_method(self.transport.list_voices, default_retry=self._method_configs['ListVoices'].retry, default_timeout=self._method_configs['ListVoices'].timeout, client_info=self._client_info) request = cloud_tts_pb2.ListVoicesRequest(language_code=language_code) return self._inner_api_calls['list_voices'](request, retry=retry, timeout=timeout, metadata=metadata)
3,337,317,461,552,284,700
Returns a list of ``Voice`` supported for synthesis. Example: >>> from google.cloud import texttospeech_v1beta1 >>> >>> client = texttospeech_v1beta1.TextToSpeechClient() >>> >>> response = client.list_voices() Args: language_code (str): Optional (but recommended) `BCP-47 <https://www.rfc-editor.org/rfc/bcp/bcp47.txt>`__ language tag. If specified, the ListVoices call will only return voices that can be used to synthesize this language\_code. E.g. when specifying "en-NZ", you will get supported "en-*" voices; when specifying "no", you will get supported "no-*" (Norwegian) and "nb-*" (Norwegian Bokmal) voices; specifying "zh" will also get supported "cmn-*" voices; specifying "zh-hk" will also get supported "yue-\*" voices. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.texttospeech_v1beta1.types.ListVoicesResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
texttospeech/google/cloud/texttospeech_v1beta1/gapic/text_to_speech_client.py
list_voices
Abd-Elrazek/google-cloud-python
python
def list_voices(self, language_code=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): '\n Returns a list of ``Voice`` supported for synthesis.\n\n Example:\n >>> from google.cloud import texttospeech_v1beta1\n >>>\n >>> client = texttospeech_v1beta1.TextToSpeechClient()\n >>>\n >>> response = client.list_voices()\n\n Args:\n language_code (str): Optional (but recommended)\n `BCP-47 <https://www.rfc-editor.org/rfc/bcp/bcp47.txt>`__ language tag.\n If specified, the ListVoices call will only return voices that can be\n used to synthesize this language\\_code. E.g. when specifying "en-NZ",\n you will get supported "en-*" voices; when specifying "no", you will get\n supported "no-*" (Norwegian) and "nb-*" (Norwegian Bokmal) voices;\n specifying "zh" will also get supported "cmn-*" voices; specifying\n "zh-hk" will also get supported "yue-\\*" voices.\n retry (Optional[google.api_core.retry.Retry]): A retry object used\n to retry requests. If ``None`` is specified, requests will not\n be retried.\n timeout (Optional[float]): The amount of time, in seconds, to wait\n for the request to complete. Note that if ``retry`` is\n specified, the timeout applies to each individual attempt.\n metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n that is provided to the method.\n\n Returns:\n A :class:`~google.cloud.texttospeech_v1beta1.types.ListVoicesResponse` instance.\n\n Raises:\n google.api_core.exceptions.GoogleAPICallError: If the request\n failed for any reason.\n google.api_core.exceptions.RetryError: If the request failed due\n to a retryable error and retry attempts failed.\n ValueError: If the parameters are invalid.\n ' if ('list_voices' not in self._inner_api_calls): self._inner_api_calls['list_voices'] = google.api_core.gapic_v1.method.wrap_method(self.transport.list_voices, default_retry=self._method_configs['ListVoices'].retry, default_timeout=self._method_configs['ListVoices'].timeout, client_info=self._client_info) request = cloud_tts_pb2.ListVoicesRequest(language_code=language_code) return self._inner_api_calls['list_voices'](request, retry=retry, timeout=timeout, metadata=metadata)
def synthesize_speech(self, input_, voice, audio_config, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): '\n Synthesizes speech synchronously: receive results after all text input\n has been processed.\n\n Example:\n >>> from google.cloud import texttospeech_v1beta1\n >>>\n >>> client = texttospeech_v1beta1.TextToSpeechClient()\n >>>\n >>> # TODO: Initialize `input_`:\n >>> input_ = {}\n >>>\n >>> # TODO: Initialize `voice`:\n >>> voice = {}\n >>>\n >>> # TODO: Initialize `audio_config`:\n >>> audio_config = {}\n >>>\n >>> response = client.synthesize_speech(input_, voice, audio_config)\n\n Args:\n input_ (Union[dict, ~google.cloud.texttospeech_v1beta1.types.SynthesisInput]): Required. The Synthesizer requires either plain text or SSML as input.\n\n If a dict is provided, it must be of the same form as the protobuf\n message :class:`~google.cloud.texttospeech_v1beta1.types.SynthesisInput`\n voice (Union[dict, ~google.cloud.texttospeech_v1beta1.types.VoiceSelectionParams]): Required. The desired voice of the synthesized audio.\n\n If a dict is provided, it must be of the same form as the protobuf\n message :class:`~google.cloud.texttospeech_v1beta1.types.VoiceSelectionParams`\n audio_config (Union[dict, ~google.cloud.texttospeech_v1beta1.types.AudioConfig]): Required. The configuration of the synthesized audio.\n\n If a dict is provided, it must be of the same form as the protobuf\n message :class:`~google.cloud.texttospeech_v1beta1.types.AudioConfig`\n retry (Optional[google.api_core.retry.Retry]): A retry object used\n to retry requests. If ``None`` is specified, requests will not\n be retried.\n timeout (Optional[float]): The amount of time, in seconds, to wait\n for the request to complete. Note that if ``retry`` is\n specified, the timeout applies to each individual attempt.\n metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n that is provided to the method.\n\n Returns:\n A :class:`~google.cloud.texttospeech_v1beta1.types.SynthesizeSpeechResponse` instance.\n\n Raises:\n google.api_core.exceptions.GoogleAPICallError: If the request\n failed for any reason.\n google.api_core.exceptions.RetryError: If the request failed due\n to a retryable error and retry attempts failed.\n ValueError: If the parameters are invalid.\n ' if ('synthesize_speech' not in self._inner_api_calls): self._inner_api_calls['synthesize_speech'] = google.api_core.gapic_v1.method.wrap_method(self.transport.synthesize_speech, default_retry=self._method_configs['SynthesizeSpeech'].retry, default_timeout=self._method_configs['SynthesizeSpeech'].timeout, client_info=self._client_info) request = cloud_tts_pb2.SynthesizeSpeechRequest(input=input_, voice=voice, audio_config=audio_config) return self._inner_api_calls['synthesize_speech'](request, retry=retry, timeout=timeout, metadata=metadata)
-245,552,770,767,781,020
Synthesizes speech synchronously: receive results after all text input has been processed. Example: >>> from google.cloud import texttospeech_v1beta1 >>> >>> client = texttospeech_v1beta1.TextToSpeechClient() >>> >>> # TODO: Initialize `input_`: >>> input_ = {} >>> >>> # TODO: Initialize `voice`: >>> voice = {} >>> >>> # TODO: Initialize `audio_config`: >>> audio_config = {} >>> >>> response = client.synthesize_speech(input_, voice, audio_config) Args: input_ (Union[dict, ~google.cloud.texttospeech_v1beta1.types.SynthesisInput]): Required. The Synthesizer requires either plain text or SSML as input. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.texttospeech_v1beta1.types.SynthesisInput` voice (Union[dict, ~google.cloud.texttospeech_v1beta1.types.VoiceSelectionParams]): Required. The desired voice of the synthesized audio. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.texttospeech_v1beta1.types.VoiceSelectionParams` audio_config (Union[dict, ~google.cloud.texttospeech_v1beta1.types.AudioConfig]): Required. The configuration of the synthesized audio. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.texttospeech_v1beta1.types.AudioConfig` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.texttospeech_v1beta1.types.SynthesizeSpeechResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
texttospeech/google/cloud/texttospeech_v1beta1/gapic/text_to_speech_client.py
synthesize_speech
Abd-Elrazek/google-cloud-python
python
def synthesize_speech(self, input_, voice, audio_config, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None): '\n Synthesizes speech synchronously: receive results after all text input\n has been processed.\n\n Example:\n >>> from google.cloud import texttospeech_v1beta1\n >>>\n >>> client = texttospeech_v1beta1.TextToSpeechClient()\n >>>\n >>> # TODO: Initialize `input_`:\n >>> input_ = {}\n >>>\n >>> # TODO: Initialize `voice`:\n >>> voice = {}\n >>>\n >>> # TODO: Initialize `audio_config`:\n >>> audio_config = {}\n >>>\n >>> response = client.synthesize_speech(input_, voice, audio_config)\n\n Args:\n input_ (Union[dict, ~google.cloud.texttospeech_v1beta1.types.SynthesisInput]): Required. The Synthesizer requires either plain text or SSML as input.\n\n If a dict is provided, it must be of the same form as the protobuf\n message :class:`~google.cloud.texttospeech_v1beta1.types.SynthesisInput`\n voice (Union[dict, ~google.cloud.texttospeech_v1beta1.types.VoiceSelectionParams]): Required. The desired voice of the synthesized audio.\n\n If a dict is provided, it must be of the same form as the protobuf\n message :class:`~google.cloud.texttospeech_v1beta1.types.VoiceSelectionParams`\n audio_config (Union[dict, ~google.cloud.texttospeech_v1beta1.types.AudioConfig]): Required. The configuration of the synthesized audio.\n\n If a dict is provided, it must be of the same form as the protobuf\n message :class:`~google.cloud.texttospeech_v1beta1.types.AudioConfig`\n retry (Optional[google.api_core.retry.Retry]): A retry object used\n to retry requests. If ``None`` is specified, requests will not\n be retried.\n timeout (Optional[float]): The amount of time, in seconds, to wait\n for the request to complete. Note that if ``retry`` is\n specified, the timeout applies to each individual attempt.\n metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n that is provided to the method.\n\n Returns:\n A :class:`~google.cloud.texttospeech_v1beta1.types.SynthesizeSpeechResponse` instance.\n\n Raises:\n google.api_core.exceptions.GoogleAPICallError: If the request\n failed for any reason.\n google.api_core.exceptions.RetryError: If the request failed due\n to a retryable error and retry attempts failed.\n ValueError: If the parameters are invalid.\n ' if ('synthesize_speech' not in self._inner_api_calls): self._inner_api_calls['synthesize_speech'] = google.api_core.gapic_v1.method.wrap_method(self.transport.synthesize_speech, default_retry=self._method_configs['SynthesizeSpeech'].retry, default_timeout=self._method_configs['SynthesizeSpeech'].timeout, client_info=self._client_info) request = cloud_tts_pb2.SynthesizeSpeechRequest(input=input_, voice=voice, audio_config=audio_config) return self._inner_api_calls['synthesize_speech'](request, retry=retry, timeout=timeout, metadata=metadata)
@noPosargs @permittedKwargs({}) def symbols_have_underscore_prefix_method(self, args, kwargs): '\n Check if the compiler prefixes _ (underscore) to global C symbols\n See: https://en.wikipedia.org/wiki/Name_mangling#C\n ' return self.compiler.symbols_have_underscore_prefix(self.environment)
362,288,032,390,152,640
Check if the compiler prefixes _ (underscore) to global C symbols See: https://en.wikipedia.org/wiki/Name_mangling#C
mesonbuild/interpreter.py
symbols_have_underscore_prefix_method
tolnaisz/meson
python
@noPosargs @permittedKwargs({}) def symbols_have_underscore_prefix_method(self, args, kwargs): '\n Check if the compiler prefixes _ (underscore) to global C symbols\n See: https://en.wikipedia.org/wiki/Name_mangling#C\n ' return self.compiler.symbols_have_underscore_prefix(self.environment)
@noPosargs @permittedKwargs({}) def unittest_args_method(self, args, kwargs): '\n This function is deprecated and should not be used.\n It can be removed in a future version of Meson.\n ' if (not hasattr(self.compiler, 'get_feature_args')): raise InterpreterException('This {} compiler has no feature arguments.'.format(self.compiler.get_display_language())) build_to_src = os.path.relpath(self.environment.get_source_dir(), self.environment.get_build_dir()) return self.compiler.get_feature_args({'unittest': 'true'}, build_to_src)
-1,227,826,540,872,375,300
This function is deprecated and should not be used. It can be removed in a future version of Meson.
mesonbuild/interpreter.py
unittest_args_method
tolnaisz/meson
python
@noPosargs @permittedKwargs({}) def unittest_args_method(self, args, kwargs): '\n This function is deprecated and should not be used.\n It can be removed in a future version of Meson.\n ' if (not hasattr(self.compiler, 'get_feature_args')): raise InterpreterException('This {} compiler has no feature arguments.'.format(self.compiler.get_display_language())) build_to_src = os.path.relpath(self.environment.get_source_dir(), self.environment.get_build_dir()) return self.compiler.get_feature_args({'unittest': 'true'}, build_to_src)
def _handle_featurenew_dependencies(self, name): 'Do a feature check on dependencies used by this subproject' if (name == 'mpi'): FeatureNew('MPI Dependency', '0.42.0').use(self.subproject) elif (name == 'pcap'): FeatureNew('Pcap Dependency', '0.42.0').use(self.subproject) elif (name == 'vulkan'): FeatureNew('Vulkan Dependency', '0.42.0').use(self.subproject) elif (name == 'libwmf'): FeatureNew('LibWMF Dependency', '0.44.0').use(self.subproject) elif (name == 'openmp'): FeatureNew('OpenMP Dependency', '0.46.0').use(self.subproject)
-4,183,288,055,773,951,000
Do a feature check on dependencies used by this subproject
mesonbuild/interpreter.py
_handle_featurenew_dependencies
tolnaisz/meson
python
def _handle_featurenew_dependencies(self, name): if (name == 'mpi'): FeatureNew('MPI Dependency', '0.42.0').use(self.subproject) elif (name == 'pcap'): FeatureNew('Pcap Dependency', '0.42.0').use(self.subproject) elif (name == 'vulkan'): FeatureNew('Vulkan Dependency', '0.42.0').use(self.subproject) elif (name == 'libwmf'): FeatureNew('LibWMF Dependency', '0.44.0').use(self.subproject) elif (name == 'openmp'): FeatureNew('OpenMP Dependency', '0.46.0').use(self.subproject)
def _func_custom_target_impl(self, node, args, kwargs): 'Implementation-only, without FeatureNew checks, for internal use' name = args[0] kwargs['install_mode'] = self._get_kwarg_install_mode(kwargs) if ('input' in kwargs): try: kwargs['input'] = self.source_strings_to_files(extract_as_list(kwargs, 'input')) except mesonlib.MesonException: mlog.warning(("Custom target input '%s' can't be converted to File object(s).\nThis will become a hard error in the future." % kwargs['input']), location=self.current_node) tg = CustomTargetHolder(build.CustomTarget(name, self.subdir, self.subproject, kwargs, backend=self.backend), self) self.add_target(name, tg.held_object) return tg
-1,760,694,228,567,836,000
Implementation-only, without FeatureNew checks, for internal use
mesonbuild/interpreter.py
_func_custom_target_impl
tolnaisz/meson
python
def _func_custom_target_impl(self, node, args, kwargs): name = args[0] kwargs['install_mode'] = self._get_kwarg_install_mode(kwargs) if ('input' in kwargs): try: kwargs['input'] = self.source_strings_to_files(extract_as_list(kwargs, 'input')) except mesonlib.MesonException: mlog.warning(("Custom target input '%s' can't be converted to File object(s).\nThis will become a hard error in the future." % kwargs['input']), location=self.current_node) tg = CustomTargetHolder(build.CustomTarget(name, self.subdir, self.subproject, kwargs, backend=self.backend), self) self.add_target(name, tg.held_object) return tg
def keras_convert_hdf5_model_to_tf_saved_model(model_path: InputPath('KerasModelHdf5'), converted_model_path: OutputPath('TensorflowSavedModel')): 'Converts Keras HDF5 model to Tensorflow SavedModel format.\n\n Args:\n model_path: Keras model in HDF5 format.\n converted_model_path: Keras model in Tensorflow SavedModel format.\n\n Annotations:\n author: Alexey Volkov <[email protected]>\n ' from pathlib import Path from tensorflow import keras model = keras.models.load_model(filepath=model_path) keras.models.save_model(model=model, filepath=converted_model_path, save_format='tf')
6,726,971,064,905,890,000
Converts Keras HDF5 model to Tensorflow SavedModel format. Args: model_path: Keras model in HDF5 format. converted_model_path: Keras model in Tensorflow SavedModel format. Annotations: author: Alexey Volkov <[email protected]>
components/_converters/KerasModelHdf5/to_TensorflowSavedModel/component.py
keras_convert_hdf5_model_to_tf_saved_model
9rince/kfp
python
def keras_convert_hdf5_model_to_tf_saved_model(model_path: InputPath('KerasModelHdf5'), converted_model_path: OutputPath('TensorflowSavedModel')): 'Converts Keras HDF5 model to Tensorflow SavedModel format.\n\n Args:\n model_path: Keras model in HDF5 format.\n converted_model_path: Keras model in Tensorflow SavedModel format.\n\n Annotations:\n author: Alexey Volkov <[email protected]>\n ' from pathlib import Path from tensorflow import keras model = keras.models.load_model(filepath=model_path) keras.models.save_model(model=model, filepath=converted_model_path, save_format='tf')
def __init__(self, Token, URL, get_all_field=False): '\n Create a project using PyCap\n :param Token:\n :param URL:\n :return:\n ' self.project = Project(URL, Token) fields_keyid = ['patientID', 'cf_p_cnnpatientui'] self.data = self.get_fields(fields_keyid) if get_all_field: self.data = self.project.export_records()
8,593,968,137,652,244,000
Create a project using PyCap :param Token: :param URL: :return:
query_CNFUN.py
__init__
CNBP/RCAPI
python
def __init__(self, Token, URL, get_all_field=False): '\n Create a project using PyCap\n :param Token:\n :param URL:\n :return:\n ' self.project = Project(URL, Token) fields_keyid = ['patientID', 'cf_p_cnnpatientui'] self.data = self.get_fields(fields_keyid) if get_all_field: self.data = self.project.export_records()
def filter_with_CNNPatientUI(self, CNNPatientUI: (str or List[str])): '\n Check the list, only retain the relevant records with matching PatientID are retained.\n :param dataset: CNBPIDs & record ID correspondence list.\n :param CNNPatientUI:\n :return:\n ' list_filtered = None filtered_field = 'cf_p_cnnpatientui' if (type(CNNPatientUI) is str): CNNPatientUI = [CNNPatientUI] list_filtered = filter_records(self.data, filtered_field, CNNPatientUI) return list_filtered
2,923,195,438,025,086,500
Check the list, only retain the relevant records with matching PatientID are retained. :param dataset: CNBPIDs & record ID correspondence list. :param CNNPatientUI: :return:
query_CNFUN.py
filter_with_CNNPatientUI
CNBP/RCAPI
python
def filter_with_CNNPatientUI(self, CNNPatientUI: (str or List[str])): '\n Check the list, only retain the relevant records with matching PatientID are retained.\n :param dataset: CNBPIDs & record ID correspondence list.\n :param CNNPatientUI:\n :return:\n ' list_filtered = None filtered_field = 'cf_p_cnnpatientui' if (type(CNNPatientUI) is str): CNNPatientUI = [CNNPatientUI] list_filtered = filter_records(self.data, filtered_field, CNNPatientUI) return list_filtered
def get_PatientID_with_CNNPatientUI(self, CNNPatientUI: (str or List[str])): '\n PatientID has 1:1 correspondence with CNNPatientUI which is the same as PatientUI from CNN Baby table.\n :return:\n ' if (type(CNNPatientUI) is str): CNNPatientUI = [CNNPatientUI] list_filtered_dict = self.filter_with_CNNPatientUI(CNNPatientUI) list_PatientID = [] for case in list_filtered_dict: list_PatientID.append(case['patientid']) return list_PatientID
6,397,022,490,869,362,000
PatientID has 1:1 correspondence with CNNPatientUI which is the same as PatientUI from CNN Baby table. :return:
query_CNFUN.py
get_PatientID_with_CNNPatientUI
CNBP/RCAPI
python
def get_PatientID_with_CNNPatientUI(self, CNNPatientUI: (str or List[str])): '\n PatientID has 1:1 correspondence with CNNPatientUI which is the same as PatientUI from CNN Baby table.\n :return:\n ' if (type(CNNPatientUI) is str): CNNPatientUI = [CNNPatientUI] list_filtered_dict = self.filter_with_CNNPatientUI(CNNPatientUI) list_PatientID = [] for case in list_filtered_dict: list_PatientID.append(case['patientid']) return list_PatientID
def get_records_CNFUN(self, PatientID: (str or List[str])): '\n Retrieve the cases based on their INDEX which is the\n :param cases:\n :return:\n ' if (type(PatientID) is str): PatientID = [PatientID] cases_data = self.project.export_records(records=PatientID) return cases_data
-8,302,587,750,901,383,000
Retrieve the cases based on their INDEX which is the :param cases: :return:
query_CNFUN.py
get_records_CNFUN
CNBP/RCAPI
python
def get_records_CNFUN(self, PatientID: (str or List[str])): '\n Retrieve the cases based on their INDEX which is the\n :param cases:\n :return:\n ' if (type(PatientID) is str): PatientID = [PatientID] cases_data = self.project.export_records(records=PatientID) return cases_data
def __init__(self, id=None, name=None, created_at=None, updated_at=None): '\n Role - a model defined in Swagger\n\n :param dict swaggerTypes: The key is attribute name\n and the value is attribute type.\n :param dict attributeMap: The key is attribute name\n and the value is json key in definition.\n ' self.swagger_types = {'id': 'int', 'name': 'str', 'created_at': 'datetime', 'updated_at': 'datetime'} self.attribute_map = {'id': 'id', 'name': 'name', 'created_at': 'created_at', 'updated_at': 'updated_at'} self._id = id self._name = name self._created_at = created_at self._updated_at = updated_at
-3,533,986,126,233,254,000
Role - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition.
esp_sdk/models/role.py
__init__
EvidentSecurity/esp-sdk-python
python
def __init__(self, id=None, name=None, created_at=None, updated_at=None): '\n Role - a model defined in Swagger\n\n :param dict swaggerTypes: The key is attribute name\n and the value is attribute type.\n :param dict attributeMap: The key is attribute name\n and the value is json key in definition.\n ' self.swagger_types = {'id': 'int', 'name': 'str', 'created_at': 'datetime', 'updated_at': 'datetime'} self.attribute_map = {'id': 'id', 'name': 'name', 'created_at': 'created_at', 'updated_at': 'updated_at'} self._id = id self._name = name self._created_at = created_at self._updated_at = updated_at
@property def id(self): '\n Gets the id of this Role.\n Unique ID\n\n :return: The id of this Role.\n :rtype: int\n ' return self._id
-4,175,835,661,677,043,700
Gets the id of this Role. Unique ID :return: The id of this Role. :rtype: int
esp_sdk/models/role.py
id
EvidentSecurity/esp-sdk-python
python
@property def id(self): '\n Gets the id of this Role.\n Unique ID\n\n :return: The id of this Role.\n :rtype: int\n ' return self._id
@id.setter def id(self, id): '\n Sets the id of this Role.\n Unique ID\n\n :param id: The id of this Role.\n :type: int\n ' self._id = id
-3,053,184,595,672,948,000
Sets the id of this Role. Unique ID :param id: The id of this Role. :type: int
esp_sdk/models/role.py
id
EvidentSecurity/esp-sdk-python
python
@id.setter def id(self, id): '\n Sets the id of this Role.\n Unique ID\n\n :param id: The id of this Role.\n :type: int\n ' self._id = id
@property def name(self): '\n Gets the name of this Role.\n The name of the role\n\n :return: The name of this Role.\n :rtype: str\n ' return self._name
-3,958,561,292,520,585,000
Gets the name of this Role. The name of the role :return: The name of this Role. :rtype: str
esp_sdk/models/role.py
name
EvidentSecurity/esp-sdk-python
python
@property def name(self): '\n Gets the name of this Role.\n The name of the role\n\n :return: The name of this Role.\n :rtype: str\n ' return self._name
@name.setter def name(self, name): '\n Sets the name of this Role.\n The name of the role\n\n :param name: The name of this Role.\n :type: str\n ' self._name = name
8,241,518,132,240,190,000
Sets the name of this Role. The name of the role :param name: The name of this Role. :type: str
esp_sdk/models/role.py
name
EvidentSecurity/esp-sdk-python
python
@name.setter def name(self, name): '\n Sets the name of this Role.\n The name of the role\n\n :param name: The name of this Role.\n :type: str\n ' self._name = name
@property def created_at(self): '\n Gets the created_at of this Role.\n ISO 8601 timestamp when the resource was created\n\n :return: The created_at of this Role.\n :rtype: datetime\n ' return self._created_at
5,446,404,519,584,327,000
Gets the created_at of this Role. ISO 8601 timestamp when the resource was created :return: The created_at of this Role. :rtype: datetime
esp_sdk/models/role.py
created_at
EvidentSecurity/esp-sdk-python
python
@property def created_at(self): '\n Gets the created_at of this Role.\n ISO 8601 timestamp when the resource was created\n\n :return: The created_at of this Role.\n :rtype: datetime\n ' return self._created_at
@created_at.setter def created_at(self, created_at): '\n Sets the created_at of this Role.\n ISO 8601 timestamp when the resource was created\n\n :param created_at: The created_at of this Role.\n :type: datetime\n ' self._created_at = created_at
7,548,933,885,825,973,000
Sets the created_at of this Role. ISO 8601 timestamp when the resource was created :param created_at: The created_at of this Role. :type: datetime
esp_sdk/models/role.py
created_at
EvidentSecurity/esp-sdk-python
python
@created_at.setter def created_at(self, created_at): '\n Sets the created_at of this Role.\n ISO 8601 timestamp when the resource was created\n\n :param created_at: The created_at of this Role.\n :type: datetime\n ' self._created_at = created_at
@property def updated_at(self): '\n Gets the updated_at of this Role.\n ISO 8601 timestamp when the resource was updated\n\n :return: The updated_at of this Role.\n :rtype: datetime\n ' return self._updated_at
107,710,952,778,185,120
Gets the updated_at of this Role. ISO 8601 timestamp when the resource was updated :return: The updated_at of this Role. :rtype: datetime
esp_sdk/models/role.py
updated_at
EvidentSecurity/esp-sdk-python
python
@property def updated_at(self): '\n Gets the updated_at of this Role.\n ISO 8601 timestamp when the resource was updated\n\n :return: The updated_at of this Role.\n :rtype: datetime\n ' return self._updated_at
@updated_at.setter def updated_at(self, updated_at): '\n Sets the updated_at of this Role.\n ISO 8601 timestamp when the resource was updated\n\n :param updated_at: The updated_at of this Role.\n :type: datetime\n ' self._updated_at = updated_at
2,238,393,510,890,466,300
Sets the updated_at of this Role. ISO 8601 timestamp when the resource was updated :param updated_at: The updated_at of this Role. :type: datetime
esp_sdk/models/role.py
updated_at
EvidentSecurity/esp-sdk-python
python
@updated_at.setter def updated_at(self, updated_at): '\n Sets the updated_at of this Role.\n ISO 8601 timestamp when the resource was updated\n\n :param updated_at: The updated_at of this Role.\n :type: datetime\n ' self._updated_at = updated_at
def to_dict(self): '\n Returns the model properties as a dict\n ' result = {} for (attr, _) in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value)) elif hasattr(value, 'to_dict'): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items())) else: result[attr] = value return result
2,191,974,537,531,847,000
Returns the model properties as a dict
esp_sdk/models/role.py
to_dict
EvidentSecurity/esp-sdk-python
python
def to_dict(self): '\n \n ' result = {} for (attr, _) in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map((lambda x: (x.to_dict() if hasattr(x, 'to_dict') else x)), value)) elif hasattr(value, 'to_dict'): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map((lambda item: ((item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item)), value.items())) else: result[attr] = value return result
def to_str(self): '\n Returns the string representation of the model\n ' return pformat(self.to_dict())
-3,531,024,894,346,511,000
Returns the string representation of the model
esp_sdk/models/role.py
to_str
EvidentSecurity/esp-sdk-python
python
def to_str(self): '\n \n ' return pformat(self.to_dict())
def __repr__(self): '\n For `print` and `pprint`\n ' return self.to_str()
5,853,962,500,611,353,000
For `print` and `pprint`
esp_sdk/models/role.py
__repr__
EvidentSecurity/esp-sdk-python
python
def __repr__(self): '\n \n ' return self.to_str()
def __eq__(self, other): '\n Returns true if both objects are equal\n ' if (not isinstance(other, Role)): return False return (self.__dict__ == other.__dict__)
-4,678,687,099,986,198,000
Returns true if both objects are equal
esp_sdk/models/role.py
__eq__
EvidentSecurity/esp-sdk-python
python
def __eq__(self, other): '\n \n ' if (not isinstance(other, Role)): return False return (self.__dict__ == other.__dict__)
def __ne__(self, other): '\n Returns true if both objects are not equal\n ' return (not (self == other))
3,600,423,175,817,510,400
Returns true if both objects are not equal
esp_sdk/models/role.py
__ne__
EvidentSecurity/esp-sdk-python
python
def __ne__(self, other): '\n \n ' return (not (self == other))
def testDashboard(self): 'Test Dashboard' pass
6,571,422,790,749,848,000
Test Dashboard
test/test_dashboard.py
testDashboard
PowerOlive/python-client
python
def testDashboard(self): pass
def get_gif(): 'Return gif.' gif = BytesIO(b'GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;') gif.name = 'image.gif' return gif
2,126,571,613,711,030,800
Return gif.
modoboa_webmail/tests/test_views.py
get_gif
modoboa/modoboa-webmail
python
def get_gif(): gif = BytesIO(b'GIF87a\x01\x00\x01\x00\x80\x01\x00\x00\x00\x00ccc,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;') gif.name = 'image.gif' return gif
@classmethod def setUpTestData(cls): 'Create some users.' super(WebmailTestCase, cls).setUpTestData() admin_factories.populate_database() cls.user = core_models.User.objects.get(username='[email protected]')
5,195,052,972,593,634,000
Create some users.
modoboa_webmail/tests/test_views.py
setUpTestData
modoboa/modoboa-webmail
python
@classmethod def setUpTestData(cls): super(WebmailTestCase, cls).setUpTestData() admin_factories.populate_database() cls.user = core_models.User.objects.get(username='[email protected]')
def setUp(self): 'Connect with a simpler user.' patcher = mock.patch('imaplib.IMAP4') self.mock_imap4 = patcher.start() self.mock_imap4.return_value = IMAP4Mock() self.addCleanup(patcher.stop) self.set_global_parameter('imap_port', 1435) self.workdir = tempfile.mkdtemp() os.mkdir('{}/webmail'.format(self.workdir)) self.set_global_parameter('update_scheme', False, app='core') url = reverse('core:login') data = {'username': self.user.username, 'password': 'toto'} self.client.post(url, data)
8,880,333,680,631,719,000
Connect with a simpler user.
modoboa_webmail/tests/test_views.py
setUp
modoboa/modoboa-webmail
python
def setUp(self): patcher = mock.patch('imaplib.IMAP4') self.mock_imap4 = patcher.start() self.mock_imap4.return_value = IMAP4Mock() self.addCleanup(patcher.stop) self.set_global_parameter('imap_port', 1435) self.workdir = tempfile.mkdtemp() os.mkdir('{}/webmail'.format(self.workdir)) self.set_global_parameter('update_scheme', False, app='core') url = reverse('core:login') data = {'username': self.user.username, 'password': 'toto'} self.client.post(url, data)
def tearDown(self): 'Cleanup.' shutil.rmtree(self.workdir)
6,105,586,400,696,134,000
Cleanup.
modoboa_webmail/tests/test_views.py
tearDown
modoboa/modoboa-webmail
python
def tearDown(self): shutil.rmtree(self.workdir)
def test_listmailbox(self): 'Check listmailbox action.' url = reverse('modoboa_webmail:index') response = self.client.get(url) self.assertEqual(response.status_code, 200) response = self.client.get('{}?action=listmailbox'.format(url), HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 200) self.assertIn('[email protected]', response.json()['listing']) response = self.client.get('{}?action=listmailbox&pattern=Réception&criteria=Subject'.format(url), HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 200) self.assertIn('[email protected]', response.json()['listing'])
-4,219,483,767,522,329,600
Check listmailbox action.
modoboa_webmail/tests/test_views.py
test_listmailbox
modoboa/modoboa-webmail
python
def test_listmailbox(self): url = reverse('modoboa_webmail:index') response = self.client.get(url) self.assertEqual(response.status_code, 200) response = self.client.get('{}?action=listmailbox'.format(url), HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 200) self.assertIn('[email protected]', response.json()['listing']) response = self.client.get('{}?action=listmailbox&pattern=Réception&criteria=Subject'.format(url), HTTP_X_REQUESTED_WITH='XMLHttpRequest') self.assertEqual(response.status_code, 200) self.assertIn('[email protected]', response.json()['listing'])
def test_attachments(self): 'Check attachments.' url = reverse('modoboa_webmail:index') response = self.client.get('{}?action=compose'.format(url)) self.assertEqual(response.status_code, 200) self.assertIn('compose_mail', self.client.session) url = reverse('modoboa_webmail:attachment_list') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.set_global_parameters({'max_attachment_size': '10'}) with self.settings(MEDIA_ROOT=self.workdir): response = self.client.post(url, {'attachment': get_gif()}) self.assertContains(response, 'Attachment is too big') self.set_global_parameters({'max_attachment_size': '10K'}) with self.settings(MEDIA_ROOT=self.workdir): response = self.client.post(url, {'attachment': get_gif()}) self.assertContains(response, 'upload_success') self.assertEqual(len(self.client.session['compose_mail']['attachments']), 1) name = self.client.session['compose_mail']['attachments'][0]['tmpname'] path = '{}/webmail/{}'.format(self.workdir, name) self.assertTrue(os.path.exists(path)) url = reverse('modoboa_webmail:attachment_delete') with self.settings(MEDIA_ROOT=self.workdir): self.ajax_get('{}?name={}'.format(url, name)) self.assertFalse(os.path.exists(path))
621,653,214,064,495,600
Check attachments.
modoboa_webmail/tests/test_views.py
test_attachments
modoboa/modoboa-webmail
python
def test_attachments(self): url = reverse('modoboa_webmail:index') response = self.client.get('{}?action=compose'.format(url)) self.assertEqual(response.status_code, 200) self.assertIn('compose_mail', self.client.session) url = reverse('modoboa_webmail:attachment_list') response = self.client.get(url) self.assertEqual(response.status_code, 200) self.set_global_parameters({'max_attachment_size': '10'}) with self.settings(MEDIA_ROOT=self.workdir): response = self.client.post(url, {'attachment': get_gif()}) self.assertContains(response, 'Attachment is too big') self.set_global_parameters({'max_attachment_size': '10K'}) with self.settings(MEDIA_ROOT=self.workdir): response = self.client.post(url, {'attachment': get_gif()}) self.assertContains(response, 'upload_success') self.assertEqual(len(self.client.session['compose_mail']['attachments']), 1) name = self.client.session['compose_mail']['attachments'][0]['tmpname'] path = '{}/webmail/{}'.format(self.workdir, name) self.assertTrue(os.path.exists(path)) url = reverse('modoboa_webmail:attachment_delete') with self.settings(MEDIA_ROOT=self.workdir): self.ajax_get('{}?name={}'.format(url, name)) self.assertFalse(os.path.exists(path))
def test_delattachment_errors(self): 'Check error cases.' url = reverse('modoboa_webmail:index') response = self.client.get('{}?action=compose'.format(url)) self.assertEqual(response.status_code, 200) self.assertIn('compose_mail', self.client.session) url = reverse('modoboa_webmail:attachment_delete') with self.settings(MEDIA_ROOT=self.workdir): response = self.ajax_get('{}?name='.format(url)) self.assertEqual(response['status'], 'ko') self.assertEqual(response['respmsg'], 'Bad query') with self.settings(MEDIA_ROOT=self.workdir): response = self.ajax_get('{}?name=test'.format(url)) self.assertEqual(response['status'], 'ko') self.assertEqual(response['respmsg'], 'Unknown attachment')
-4,068,887,393,520,834,600
Check error cases.
modoboa_webmail/tests/test_views.py
test_delattachment_errors
modoboa/modoboa-webmail
python
def test_delattachment_errors(self): url = reverse('modoboa_webmail:index') response = self.client.get('{}?action=compose'.format(url)) self.assertEqual(response.status_code, 200) self.assertIn('compose_mail', self.client.session) url = reverse('modoboa_webmail:attachment_delete') with self.settings(MEDIA_ROOT=self.workdir): response = self.ajax_get('{}?name='.format(url)) self.assertEqual(response['status'], 'ko') self.assertEqual(response['respmsg'], 'Bad query') with self.settings(MEDIA_ROOT=self.workdir): response = self.ajax_get('{}?name=test'.format(url)) self.assertEqual(response['status'], 'ko') self.assertEqual(response['respmsg'], 'Unknown attachment')
def test_send_mail(self): 'Check compose form.' url = '{}?action=compose'.format(reverse('modoboa_webmail:index')) response = self.client.get(url) self.assertEqual(response.status_code, 200) response = self.client.post(url, {'from_': self.user.email, 'to': '[email protected]', 'subject': 'test', 'body': 'Test'}) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].from_email, '[email protected]') self.user.first_name = 'Antoine' self.user.last_name = 'Nguyen' self.user.parameters.set_value('editor', 'html') self.user.save() response = self.client.get(url) self.assertEqual(response.status_code, 200) mail.outbox = [] response = self.client.post(url, {'from_': self.user.email, 'to': '[email protected]', 'subject': 'test', 'body': '<p>Test</p>'}) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].from_email, '"Antoine Nguyen" <[email protected]>')
-1,387,542,173,281,891,300
Check compose form.
modoboa_webmail/tests/test_views.py
test_send_mail
modoboa/modoboa-webmail
python
def test_send_mail(self): url = '{}?action=compose'.format(reverse('modoboa_webmail:index')) response = self.client.get(url) self.assertEqual(response.status_code, 200) response = self.client.post(url, {'from_': self.user.email, 'to': '[email protected]', 'subject': 'test', 'body': 'Test'}) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].from_email, '[email protected]') self.user.first_name = 'Antoine' self.user.last_name = 'Nguyen' self.user.parameters.set_value('editor', 'html') self.user.save() response = self.client.get(url) self.assertEqual(response.status_code, 200) mail.outbox = [] response = self.client.post(url, {'from_': self.user.email, 'to': '[email protected]', 'subject': 'test', 'body': '<p>Test</p>'}) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].from_email, '"Antoine Nguyen" <[email protected]>')
def test_signature(self): 'Check signature in different formats.' signature = 'Antoine Nguyen' self.user.parameters.set_value('signature', signature) self.user.save() response = self.client.get(reverse('modoboa_webmail:index')) self.assertEqual(response.status_code, 200) url = '{}?action=compose'.format(reverse('modoboa_webmail:index')) response = self.ajax_get(url) self.assertIn(signature, response['listing'])
848,823,360,628,905,700
Check signature in different formats.
modoboa_webmail/tests/test_views.py
test_signature
modoboa/modoboa-webmail
python
def test_signature(self): signature = 'Antoine Nguyen' self.user.parameters.set_value('signature', signature) self.user.save() response = self.client.get(reverse('modoboa_webmail:index')) self.assertEqual(response.status_code, 200) url = '{}?action=compose'.format(reverse('modoboa_webmail:index')) response = self.ajax_get(url) self.assertIn(signature, response['listing'])
def test_custom_js_in_preferences(self): 'Check that custom js is included.' url = reverse('core:user_index') response = self.client.get(url) self.assertContains(response, 'function toggleSignatureEditor()')
8,341,938,609,019,007,000
Check that custom js is included.
modoboa_webmail/tests/test_views.py
test_custom_js_in_preferences
modoboa/modoboa-webmail
python
def test_custom_js_in_preferences(self): url = reverse('core:user_index') response = self.client.get(url) self.assertContains(response, 'function toggleSignatureEditor()')
def test_send_mail_errors(self): 'Check error cases.' url = '{}?action=compose'.format(reverse('modoboa_webmail:index')) response = self.client.get(url) self.assertEqual(response.status_code, 200) response = self.ajax_post(url, {'to': '', 'subject': 'test', 'body': 'Test'}, 400) self.assertEqual(len(mail.outbox), 0)
-4,056,351,638,885,951,500
Check error cases.
modoboa_webmail/tests/test_views.py
test_send_mail_errors
modoboa/modoboa-webmail
python
def test_send_mail_errors(self): url = '{}?action=compose'.format(reverse('modoboa_webmail:index')) response = self.client.get(url) self.assertEqual(response.status_code, 200) response = self.ajax_post(url, {'to': , 'subject': 'test', 'body': 'Test'}, 400) self.assertEqual(len(mail.outbox), 0)
def test_new_folder(self): 'Test folder creation.' url = reverse('modoboa_webmail:folder_add') response = self.client.get(url) self.assertContains(response, 'Create a new folder') response = self.ajax_post(url, {'name': 'Test'}) self.assertIn('newmb', response)
5,715,399,611,297,225,000
Test folder creation.
modoboa_webmail/tests/test_views.py
test_new_folder
modoboa/modoboa-webmail
python
def test_new_folder(self): url = reverse('modoboa_webmail:folder_add') response = self.client.get(url) self.assertContains(response, 'Create a new folder') response = self.ajax_post(url, {'name': 'Test'}) self.assertIn('newmb', response)
def test_edit_folder(self): 'Test folder edition.' url = reverse('modoboa_webmail:folder_change') response = self.client.get(url) self.assertContains(response, 'Invalid request') url = '{}?name=Test'.format(url) response = self.client.get(url) self.assertContains(response, 'Edit folder') session = self.client.session session['webmail_navparams'] = {'inbox': 'Test'} session.save() response = self.ajax_post(url, {'oldname': 'Test', 'name': 'Toto'}) self.assertEqual(response['respmsg'], 'Folder updated')
-7,015,717,075,723,713,000
Test folder edition.
modoboa_webmail/tests/test_views.py
test_edit_folder
modoboa/modoboa-webmail
python
def test_edit_folder(self): url = reverse('modoboa_webmail:folder_change') response = self.client.get(url) self.assertContains(response, 'Invalid request') url = '{}?name=Test'.format(url) response = self.client.get(url) self.assertContains(response, 'Edit folder') session = self.client.session session['webmail_navparams'] = {'inbox': 'Test'} session.save() response = self.ajax_post(url, {'oldname': 'Test', 'name': 'Toto'}) self.assertEqual(response['respmsg'], 'Folder updated')
def test_delete_folder(self): 'Test folder removal.' url = reverse('modoboa_webmail:folder_delete') self.ajax_get(url, status=400) url = '{}?name=Test'.format(url) session = self.client.session session['webmail_navparams'] = {'inbox': 'Test'} session.save() self.ajax_get(url)
-7,600,897,677,307,676,000
Test folder removal.
modoboa_webmail/tests/test_views.py
test_delete_folder
modoboa/modoboa-webmail
python
def test_delete_folder(self): url = reverse('modoboa_webmail:folder_delete') self.ajax_get(url, status=400) url = '{}?name=Test'.format(url) session = self.client.session session['webmail_navparams'] = {'inbox': 'Test'} session.save() self.ajax_get(url)
def test_reply_to_email(self): 'Test reply form.' url = '{}?action=reply&mbox=INBOX&mailid=46931'.format(reverse('modoboa_webmail:index')) session = self.client.session session['lastaction'] = 'compose' session.save() response = self.ajax_get(url) self.assertIn('id="id_origmsgid"', response['listing']) response = self.client.post(url, {'from_': self.user.email, 'to': '[email protected]', 'subject': 'test', 'body': 'Test', 'origmsgid': '<id@localhost>'}) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].from_email, '[email protected]') self.assertIn('References', mail.outbox[0].extra_headers)
8,669,863,298,764,621,000
Test reply form.
modoboa_webmail/tests/test_views.py
test_reply_to_email
modoboa/modoboa-webmail
python
def test_reply_to_email(self): url = '{}?action=reply&mbox=INBOX&mailid=46931'.format(reverse('modoboa_webmail:index')) session = self.client.session session['lastaction'] = 'compose' session.save() response = self.ajax_get(url) self.assertIn('id="id_origmsgid"', response['listing']) response = self.client.post(url, {'from_': self.user.email, 'to': '[email protected]', 'subject': 'test', 'body': 'Test', 'origmsgid': '<id@localhost>'}) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].from_email, '[email protected]') self.assertIn('References', mail.outbox[0].extra_headers)
def test_forward_email(self): 'Test forward form.' url = '{}?action=forward&mbox=INBOX&mailid=46932'.format(reverse('modoboa_webmail:index')) session = self.client.session session['lastaction'] = 'compose' session.save() with self.settings(MEDIA_ROOT=self.workdir): response = self.client.get(url, HTTP_X_REQUESTED_WITH='XMLHttpRequest') response = response.json() self.assertIn('id="id_origmsgid"', response['listing']) self.assertEqual(len(self.client.session['compose_mail']['attachments']), 1) response = self.client.post(url, {'from_': self.user.email, 'to': '[email protected]', 'subject': 'test', 'body': 'Test', 'origmsgid': '<id@localhost>'}) self.assertEqual(len(mail.outbox), 1)
4,625,502,241,085,917,000
Test forward form.
modoboa_webmail/tests/test_views.py
test_forward_email
modoboa/modoboa-webmail
python
def test_forward_email(self): url = '{}?action=forward&mbox=INBOX&mailid=46932'.format(reverse('modoboa_webmail:index')) session = self.client.session session['lastaction'] = 'compose' session.save() with self.settings(MEDIA_ROOT=self.workdir): response = self.client.get(url, HTTP_X_REQUESTED_WITH='XMLHttpRequest') response = response.json() self.assertIn('id="id_origmsgid"', response['listing']) self.assertEqual(len(self.client.session['compose_mail']['attachments']), 1) response = self.client.post(url, {'from_': self.user.email, 'to': '[email protected]', 'subject': 'test', 'body': 'Test', 'origmsgid': '<id@localhost>'}) self.assertEqual(len(mail.outbox), 1)
def test_getmailcontent_empty_mail(self): 'Try to display an empty email.' url = '{}?action=reply&mbox=INBOX&mailid=33'.format(reverse('modoboa_webmail:mailcontent_get')) response = self.client.get(url) self.assertEqual(response.status_code, 200)
-5,638,293,346,663,087,000
Try to display an empty email.
modoboa_webmail/tests/test_views.py
test_getmailcontent_empty_mail
modoboa/modoboa-webmail
python
def test_getmailcontent_empty_mail(self): url = '{}?action=reply&mbox=INBOX&mailid=33'.format(reverse('modoboa_webmail:mailcontent_get')) response = self.client.get(url) self.assertEqual(response.status_code, 200)
def test_getmailsource(self): "Try to display a message's source." url = '{}?mbox=INBOX&mailid=133872'.format(reverse('modoboa_webmail:mailsource_get')) response = self.client.get(url) self.assertContains(response, 'Message-ID')
4,267,383,935,041,959,000
Try to display a message's source.
modoboa_webmail/tests/test_views.py
test_getmailsource
modoboa/modoboa-webmail
python
def test_getmailsource(self): url = '{}?mbox=INBOX&mailid=133872'.format(reverse('modoboa_webmail:mailsource_get')) response = self.client.get(url) self.assertContains(response, 'Message-ID')
def get_args(): ' Get script argument ' parser = argparse.ArgumentParser(description='Show current weather on polybar') parser.add_argument('log', nargs='?', help='Logging for debugging or not') parser.add_argument('-u', '--unit', default='metric', nargs='?', help='unit: metric or imperial. Default: metric') return parser.parse_args()
4,760,475,130,287,260,000
Get script argument
.config/polybar/weather/weather.py
get_args
NearHuscarl/dotfiles
python
def get_args(): ' ' parser = argparse.ArgumentParser(description='Show current weather on polybar') parser.add_argument('log', nargs='?', help='Logging for debugging or not') parser.add_argument('-u', '--unit', default='metric', nargs='?', help='unit: metric or imperial. Default: metric') return parser.parse_args()
def set_up_logging(): ' Set some logging parameter ' if importlib.util.find_spec('requests'): logging.getLogger('requests').setLevel(logging.WARNING) logging.getLogger('urllib3').setLevel(logging.WARNING) logging.basicConfig(format='[%(levelname)s] %(message)s', level=logging.DEBUG)
7,073,323,484,583,997,000
Set some logging parameter
.config/polybar/weather/weather.py
set_up_logging
NearHuscarl/dotfiles
python
def set_up_logging(): ' ' if importlib.util.find_spec('requests'): logging.getLogger('requests').setLevel(logging.WARNING) logging.getLogger('urllib3').setLevel(logging.WARNING) logging.basicConfig(format='[%(levelname)s] %(message)s', level=logging.DEBUG)
def get_day_or_night(): " return 'day' or 'night' based on current hour " hour = int(datetime.datetime.now().strftime('%H')) if ((hour >= 18) or (hour <= 5)): return 'night' return 'day'
9,053,619,928,646,817,000
return 'day' or 'night' based on current hour
.config/polybar/weather/weather.py
get_day_or_night
NearHuscarl/dotfiles
python
def get_day_or_night(): " " hour = int(datetime.datetime.now().strftime('%H')) if ((hour >= 18) or (hour <= 5)): return 'night' return 'day'
def get_weather_icon(weather_id): ' Get weather icon based on weather condition ' day_night_status = get_day_or_night() weather = {'thunderstorm': (200 <= weather_id <= 232), 'rain': (300 <= weather_id <= 531), 'snow': (600 <= weather_id <= 622), 'atmosphere': (701 <= weather_id <= 781), 'squall': (weather_id == 771), 'tornado': ((weather_id == 781) or (weather_id == 900)), 'clear_day': ((weather_id == 800) and (day_night_status == 'day')), 'clear_night': ((weather_id == 800) and (day_night_status == 'night')), 'tropical storm': (weather_id == 901), 'hurricane': (weather_id == 902), 'cold': (weather_id == 903), 'hot': (weather_id == 904), 'windy': (weather_id == 905), 'cloudy': (801 <= weather_id <= 804), 'hail': (weather_id == 906)} if weather['thunderstorm']: return '\uf0e7' elif weather['rain']: return '\uf043' elif (weather['snow'] or weather['cold']): return '\uf2dc' elif (weather['atmosphere'] or weather['windy']): return '\ue8de' elif (weather['squall'] or weather['tornado'] or weather['tropical storm'] or weather['hurricane']): return '\uf2dd' elif (weather['clear_day'] or weather['hot']): return '\ue430' elif weather['clear_night']: return '\uf186' elif weather['cloudy']: return '\uf0c2' elif weather['hail']: return '\ue3ea'
-2,874,299,759,056,601,600
Get weather icon based on weather condition
.config/polybar/weather/weather.py
get_weather_icon
NearHuscarl/dotfiles
python
def get_weather_icon(weather_id): ' ' day_night_status = get_day_or_night() weather = {'thunderstorm': (200 <= weather_id <= 232), 'rain': (300 <= weather_id <= 531), 'snow': (600 <= weather_id <= 622), 'atmosphere': (701 <= weather_id <= 781), 'squall': (weather_id == 771), 'tornado': ((weather_id == 781) or (weather_id == 900)), 'clear_day': ((weather_id == 800) and (day_night_status == 'day')), 'clear_night': ((weather_id == 800) and (day_night_status == 'night')), 'tropical storm': (weather_id == 901), 'hurricane': (weather_id == 902), 'cold': (weather_id == 903), 'hot': (weather_id == 904), 'windy': (weather_id == 905), 'cloudy': (801 <= weather_id <= 804), 'hail': (weather_id == 906)} if weather['thunderstorm']: return '\uf0e7' elif weather['rain']: return '\uf043' elif (weather['snow'] or weather['cold']): return '\uf2dc' elif (weather['atmosphere'] or weather['windy']): return '\ue8de' elif (weather['squall'] or weather['tornado'] or weather['tropical storm'] or weather['hurricane']): return '\uf2dd' elif (weather['clear_day'] or weather['hot']): return '\ue430' elif weather['clear_night']: return '\uf186' elif weather['cloudy']: return '\uf0c2' elif weather['hail']: return '\ue3ea'
def get_thermo_icon(temp_value, temp_unit): ' Get thermometer icon based on temperature ' if (temp_unit == 'F'): temp_value = convert_temp_unit(temp_unit, 'C') if (temp_value <= (- 15)): return '\uf2cb' elif ((- 15) < temp_value <= 0): return '\uf2ca' elif (0 < temp_value <= 15): return '\uf2c9' elif (15 < temp_value <= 30): return '\uf2c8' elif (temp_value > 30): return '\uf2c7'
-6,282,912,500,564,119,000
Get thermometer icon based on temperature
.config/polybar/weather/weather.py
get_thermo_icon
NearHuscarl/dotfiles
python
def get_thermo_icon(temp_value, temp_unit): ' ' if (temp_unit == 'F'): temp_value = convert_temp_unit(temp_unit, 'C') if (temp_value <= (- 15)): return '\uf2cb' elif ((- 15) < temp_value <= 0): return '\uf2ca' elif (0 < temp_value <= 15): return '\uf2c9' elif (15 < temp_value <= 30): return '\uf2c8' elif (temp_value > 30): return '\uf2c7'
def convert_temp_unit(temp_value, temp_unit): ' Convert current temp_value to temp_unit ' if (temp_unit == 'C'): return round(((temp_value - 32) / 1.8)) elif (temp_unit == 'F'): return round(((temp_value * 1.8) + 32))
-1,498,469,046,806,664,200
Convert current temp_value to temp_unit
.config/polybar/weather/weather.py
convert_temp_unit
NearHuscarl/dotfiles
python
def convert_temp_unit(temp_value, temp_unit): ' ' if (temp_unit == 'C'): return round(((temp_value - 32) / 1.8)) elif (temp_unit == 'F'): return round(((temp_value * 1.8) + 32))