ext
stringclasses 9
values | sha
stringlengths 40
40
| content
stringlengths 3
1.04M
|
---|---|---|
py | 1a455c223e8f3a30b4891e73862f716387444e6b | from dzTrafico.Consumers.RealTimeTrafficState import RealTimeTrafficStateConsumer
from dzTrafico.Consumers.SimulationCreationConsumer import SimulationCreationConsumer
from dzTrafico.Consumers.LaneChangeRecommendation import LaneChangeRecommendationConsumer
from dzTrafico.Consumers.VSLConsumer import VSLConsumer
from channels.routing import route_class
channel_routing = [
route_class(RealTimeTrafficStateConsumer, path=r"^/simulation/api/realtimetrafficstate/$"),
route_class(SimulationCreationConsumer, path=r"^/simulation/api/simulationcreation/$"),
route_class(LaneChangeRecommendationConsumer, path=r"^/simulation/api/lcrecommendations/$"),
route_class(VSLConsumer, path=r"^/simulation/api/vsl/$")
] |
py | 1a455c497218b1a7a498016eec04a784cc0122c4 | import os.path
try:
assert not os.path.exists(__file__ + 'c')
except AssertionError:
os.unlink(__file__ + 'c')
raise
|
py | 1a455cc2af1080b370ebd43db0b63ad5c714637a | from __future__ import absolute_import
import ctypes
from .._base import _LIB
from .. import ndarray as _nd
def CuDNN_softmax(in_arr, out_arr, stream = None):
assert isinstance(in_arr, _nd.NDArray)
assert isinstance(out_arr, _nd.NDArray)
_LIB.CuDNN_DLGpuSoftmax(in_arr.handle, out_arr.handle, stream.handle if stream else None)
def CuDNN_softmax_gradient(y_arr, grad_arr, out_arr, stream=None):
assert isinstance(y_arr, _nd.NDArray)
assert isinstance(grad_arr, _nd.NDArray)
assert isinstance(out_arr, _nd.NDArray)
_LIB.CuDNN_DLGpuSoftmaxGradient(y_arr.handle, grad_arr.handle, out_arr.handle, stream.handle if stream else None)
|
py | 1a455e0f867fe31642cf7842726d28fa32ea1cbb | """Testing InPort and OutPort classes."""
from collections import OrderedDict
import unittest
from deltalanguage.data_types import Float, Int, Optional, Union
from deltalanguage.wiring import InPort, OutPort, DeltaGraph, RealNode
class TestInPortOptional(unittest.TestCase):
"""This list of test shows that InPort accepts the expected data type
when created and does the following simplification:
if it's `Optional(t)`, the port type becomes just `t`.
"""
def test_non_Optional(self):
port = InPort(None,
Int(),
None,
0)
self.assertEqual(port.port_type, Int())
self.assertEqual(port.is_optional, False)
def test_Optional(self):
port = InPort(None,
Optional(Int()),
None,
0)
self.assertEqual(port.port_type, Int())
self.assertEqual(port.is_optional, True)
def test_Union_of_single(self):
"""Union of a single type is not converted to a single type."""
port = InPort(None,
Union([Int()]),
None,
0)
self.assertEqual(port.port_type, Union([Int()]))
self.assertEqual(port.is_optional, False)
def test_Union(self):
port = InPort(None,
Union([Int(), Float()]),
None,
0)
self.assertEqual(port.port_type, Union([Int(), Float()]))
self.assertEqual(port.is_optional, False)
def test_Optional_of_Union(self):
port = InPort(None,
Optional(Union([Int(), Float()])),
None,
0)
self.assertEqual(port.port_type, Union([Int(), Float()]))
self.assertEqual(port.is_optional, True)
class TestInPortEq(unittest.TestCase):
"""Test the equality function over in-ports, both for equivalent and
non-equivalent pairs of in-ports.
"""
def test_eq(self):
g1 = DeltaGraph()
n1 = RealNode(g1, [], OrderedDict([('a', int)]), OrderedDict())
in_p_1 = InPort('a', int, n1, 0)
self.assertEqual(in_p_1, in_p_1)
g2 = DeltaGraph()
n2 = RealNode(g2, [], OrderedDict([('a', int)]), OrderedDict())
in_p_2 = InPort('a', int, n2, 0)
self.assertEqual(in_p_1, in_p_2)
def test_eq_optional(self):
g1 = DeltaGraph()
n1 = RealNode(g1, [], OrderedDict(
[('a', Optional(int))]), OrderedDict())
in_p_1 = InPort('a', Optional(int), n1, 0)
self.assertEqual(in_p_1, in_p_1)
g2 = DeltaGraph()
n2 = RealNode(g2, [], OrderedDict(
[('a', Optional(int))]), OrderedDict())
in_p_2 = InPort('a', Optional(int), n2, 0)
self.assertEqual(in_p_1, in_p_2)
def test_neq_optional_diff(self):
g1 = DeltaGraph()
n1 = RealNode(g1, [], OrderedDict([('a', int)]), OrderedDict())
in_p_1 = InPort('a', int, n1, 0)
g2 = DeltaGraph()
n2 = RealNode(g2, [], OrderedDict(
[('a', Optional(int))]), OrderedDict())
in_p_2 = InPort('a', Optional(int), n2, 0)
self.assertNotEqual(in_p_1, in_p_2)
def test_neq_index_diff(self):
g1 = DeltaGraph()
n1 = RealNode(g1, [], OrderedDict([('b', int)]), OrderedDict())
in_p_1 = InPort('b', int, n1, 0)
g2 = DeltaGraph()
n2 = RealNode(g2, [], OrderedDict([('a', int)]), OrderedDict())
in_p_2 = InPort('a', int, n2, 0)
self.assertNotEqual(in_p_1, in_p_2)
def test_neq_type_diff(self):
g1 = DeltaGraph()
n1 = RealNode(g1, [], OrderedDict([('a', int)]), OrderedDict())
in_p_1 = InPort('a', int, n1, 0)
g2 = DeltaGraph()
n2 = RealNode(g2, [], OrderedDict([('a', float)]), OrderedDict())
in_p_2 = InPort('a', float, n2, 0)
self.assertNotEqual(in_p_1, in_p_2)
def test_neq_node_diff(self):
g1 = DeltaGraph()
n1 = RealNode(g1, [], OrderedDict([('a', int)]), OrderedDict())
in_p_1 = InPort('a', int, n1, 0)
g2 = DeltaGraph()
n2 = RealNode(g2, [], OrderedDict(
[('a', int), ('b', int)]), OrderedDict())
in_p_2 = InPort('a', int, n2, 0)
self.assertNotEqual(in_p_1, in_p_2)
def test_neq_size_diff(self):
g1 = DeltaGraph()
n1 = RealNode(g1, [], OrderedDict([('a', int)]), OrderedDict())
in_p_1 = InPort('a', int, n1, 0)
g2 = DeltaGraph()
n2 = RealNode(g2, [], OrderedDict([('a', int)]), OrderedDict())
in_p_2 = InPort('a', int, n2, 2)
self.assertNotEqual(in_p_1, in_p_2)
class TestOutPortEq(unittest.TestCase):
"""Test the equality function over out-ports, both for equivalent and
non-equivalent pairs of out-ports.
"""
def test_eq(self):
g1 = DeltaGraph()
n1 = RealNode(g1, [], OrderedDict(), OrderedDict([('out_a', int)]))
dest_n_1 = RealNode(g1, [], OrderedDict([('a', int)]), OrderedDict())
dest_1 = InPort('a', int, dest_n_1, 0)
out_p_1 = OutPort('out_a', int, dest_1, n1)
self.assertEqual(out_p_1, out_p_1)
g2 = DeltaGraph()
n2 = RealNode(g2, [], OrderedDict(), OrderedDict([('out_a', int)]))
dest_n_2 = RealNode(g2, [], OrderedDict([('a', int)]), OrderedDict())
dest_2 = InPort('a', int, dest_n_2, 0)
out_p_2 = OutPort('out_a', int, dest_2, n2)
self.assertEqual(out_p_1, out_p_2)
def test_neq_index_diff(self):
g1 = DeltaGraph()
n1 = RealNode(g1, [], OrderedDict(), OrderedDict([('out_a', int)]))
dest_n_1 = RealNode(g1, [], OrderedDict([('a', int)]), OrderedDict())
dest_1 = InPort('a', int, dest_n_1, 0)
out_p_1 = OutPort('out_a', int, dest_1, n1)
g2 = DeltaGraph()
n2 = RealNode(g2, [], OrderedDict(), OrderedDict([('out_a', int)]))
dest_n_2 = RealNode(g2, [], OrderedDict([('a', int)]), OrderedDict())
dest_2 = InPort('a', int, dest_n_2, 0)
out_p_2 = OutPort('out_b', int, dest_2, n2)
self.assertNotEqual(out_p_1, out_p_2)
def test_neq_type_diff(self):
g1 = DeltaGraph()
n1 = RealNode(g1, [], OrderedDict(), OrderedDict([('out_a', int)]))
dest_n_1 = RealNode(g1, [], OrderedDict([('a', int)]), OrderedDict())
dest_1 = InPort('a', int, dest_n_1, 0)
out_p_1 = OutPort('out_a', int, dest_1, n1)
g2 = DeltaGraph()
n2 = RealNode(g2, [], OrderedDict(), OrderedDict([('out_a', int)]))
dest_n_2 = RealNode(g2, [], OrderedDict([('a', int)]), OrderedDict())
dest_2 = InPort('a', int, dest_n_2, 0)
out_p_2 = OutPort('out_a', float, dest_2, n2)
self.assertNotEqual(out_p_1, out_p_2)
def test_neq_dest_diff(self):
g1 = DeltaGraph()
n1 = RealNode(g1, [], OrderedDict(), OrderedDict([('out_a', int)]))
dest_n_1 = RealNode(g1, [], OrderedDict([('a', int)]), OrderedDict())
dest_1 = InPort('a', int, dest_n_1, 0)
out_p_1 = OutPort('out_a', int, dest_1, n1)
g2 = DeltaGraph()
n2 = RealNode(g2, [], OrderedDict(), OrderedDict([('out_a', int)]))
dest_n_2 = RealNode(g2, [], OrderedDict([('a', int)]), OrderedDict())
dest_2 = InPort('b', int, dest_n_2, 0)
out_p_2 = OutPort('out_a', int, dest_2, n2)
self.assertNotEqual(out_p_1, out_p_2)
def test_neq_node_diff(self):
g1 = DeltaGraph()
n1 = RealNode(g1, [], OrderedDict(), OrderedDict([('out_a', int)]))
dest_n_1 = RealNode(g1, [], OrderedDict([('a', int)]), OrderedDict())
dest_1 = InPort('a', int, dest_n_1, 0)
out_p_1 = OutPort('out_a', int, dest_1, n1)
g2 = DeltaGraph()
n2 = RealNode(g2, [], OrderedDict([('c', bool)]), OrderedDict([('out_a', int)]))
dest_n_2 = RealNode(g2, [], OrderedDict([('a', int)]), OrderedDict())
dest_2 = InPort('a', int, dest_n_2, 0)
out_p_2 = OutPort('out_a', int, dest_2, n2)
self.assertNotEqual(out_p_1, out_p_2)
class TestOutPortOptional(unittest.TestCase):
"""This list of test shows that OutPort data type cannot be `Optional`."""
def test_non_Optional(self):
port = OutPort(None,
Int(),
None,
None)
self.assertEqual(port.port_type, Int())
def test_Optional(self):
port = OutPort(None,
Optional(Int()),
None,
None)
with self.assertRaises(TypeError):
dummy = port.port_type
if __name__ == "__main__":
unittest.main()
|
py | 1a455e234a56f5b1099997f65f4eb7806e30626b | from recipe_scrapers.heb import HEB
from tests import ScraperTest
class TestHEBScraper(ScraperTest):
scraper_class = HEB
def test_host(self):
self.assertEqual("heb.com", self.harvester_class.host())
def test_canonical_url(self):
self.assertEqual(
"https://www.heb.com/recipe/recipe-item/truffled-spaghetti-squash/1398755977632",
self.harvester_class.canonical_url(),
)
def test_title(self):
self.assertEqual("Truffled Spaghetti Squash", self.harvester_class.title())
def test_total_time(self):
self.assertEqual(60, self.harvester_class.total_time())
def test_yields(self):
self.assertEqual("8 servings", self.harvester_class.yields())
def test_ingredients(self):
self.assertEqual(
[
"1 large spaghetti squash",
"1 Tsp Sabatino Truffle salt",
"4 Tbsp unsalted butter",
"1 Tbsp Rustico Truffle Oil",
],
self.harvester_class.ingredients(),
)
def test_instructions(self):
self.assertEqual(
"\n".join(
[
"Preheat oven to 400˚F. Cut spaghetti squash in half from top to bottom (lengthwise).",
"Place the spaghetti squash halves, cut side down onto a sheet pan. Roast for 30-45 minutes or until a knife can pierce the outside of skin easily, like a baked potato.",
"Once Squash is fully cooked and soft remove it from oven and let it cool for 10 minutes before scooping out meat of squash. In a serving bowl scoop or with a fork scrape out squash and add truffle salt, butter and truffle oil.",
"Toss all ingredients together until butter is fully melted. Season to taste if needed and serve warm.",
]
),
self.harvester_class.instructions(),
)
def test_image(self):
self.assertEqual(
"https://images.heb.com/is/image/HEBGrocery/rcp-thumbnail/spicy-spaghetti-squash-boats-recipe.jpg",
self.harvester_class.image(),
)
|
py | 1a455e4e331df3e3a7e08e4ced9f794ddc6bc80f | import cStringIO
import logging
from datetime import datetime
from clarity_ext_scripts.covid.controls import controls_barcode_generator
from clarity_ext_scripts.covid.services.knm_service import KNMClientFromExtension
from clarity_ext_scripts.covid.create_samples.common import (
BaseRawSampleListFile, ValidatedSampleListFile,
BaseValidateRawSampleListExtension, BUTTON_TEXT_ASSIGN_UNREGISTERED_TO_ANONYMOUS
)
logger = logging.getLogger(__name__)
class RawSampleListColumns(object):
COLUMN_REFERENCE = "Sample Id"
COLUMN_POSITION = "Position"
COLUMN_USER_DEFINED1 = "USERDEFINED1"
COLUMN_USER_DEFINED5 = "USERDEFINED5"
HEADERS = ["Rack Id", "Cavity Id",
COLUMN_POSITION, COLUMN_REFERENCE,
"CONCENTRATION", "CONCENTRATIONUNIT", "VOLUME",
COLUMN_USER_DEFINED1,
"USERDEFINED2", "USERDEFINED3", "USERDEFINED4",
COLUMN_USER_DEFINED5, # Contains a control name or the integration test knm status
"PlateErrors", "SampleErrors", "SAMPLEINSTANCEID", "SAMPLEID"]
# The column from which we can get the fake status in integration tests
COLUMN_FAKE_STATUS = COLUMN_USER_DEFINED5
class RawSampleListFile(RawSampleListColumns, BaseRawSampleListFile):
"""
Describes the CSV file that hangs on the 'Raw sample list' file handle.
"""
@staticmethod
def filter_before_parse(file_like):
filtered = cStringIO.StringIO()
# Ignore everything at or after the line that contains this text:
stop_condition = "Sample Tracking Report Name"
for line in file_like:
if stop_condition in line:
break
filtered.write(line + "\n")
filtered.seek(0)
return filtered
class Extension(BaseValidateRawSampleListExtension):
"""
Validates all samples in a sample creation list.
Before execution of this script, a research engineer has uploaded a raw csv on the format:
barcode;well
to the `Raw sample list` file handle.
This script generates a new sample list. It's equivalent to the original sample
list, but also adds three new fields:
```
barcode: <barcode from csv>
well: <well from csv>
*status: <error | success>
*service_request_id: <the service request ID from KNM>
*comment: <details about the error, if any>
```
This will be the input for creating samples later on. That extension must require that there
are no errors in any of the rows. If there is an error, no sample should be created.
In the case of an error, the research engineer has these options:
* Edit the raw sample list and run validate again.
* Edit this script or request changes at KNM.
* In an extreme case, e.g. given manual confirmation, the research engineer can upload a new
validated file with manually edited information.
"""
def execute(self):
# Validate the 'Raw biobank file' exists and is in concordance with the 'Raw sample list'
# if not, abort script execution
from clarity_ext_scripts.covid.fetch_biobank_barcodes import FetchBiobankBarcodes
validator = FetchBiobankBarcodes(self.context)
validator.validate()
# 1. Get the ordering organizations URI
try:
ordering_org = self.context.current_step.udf_ordering_organization
except AttributeError:
self.usage_error("You must select an ordering organization")
# 2. Create an API client
# Make sure that there is a config at ~/.config/clarity-ext/clarity-ext.config
client = KNMClientFromExtension(self)
# 3. Read the raw sample list.
raw_sample_list = RawSampleListFile.create_from_context(self.context)
validated_sample_list = raw_sample_list.ValidatedSampleListFile()
# 4. Create the validated list
unregistered = list()
for ix, row in validated_sample_list.csv.iterrows():
barcode = row[validated_sample_list.COLUMN_REFERENCE]
well = row[validated_sample_list.COLUMN_POSITION]
# NOTE: The well is in the format "A01" etc
if len(well) != 3:
raise AssertionError(
"Expected the Position in the raw sample list to be on the format A01. "
"Got: {}".format(well))
plate_row = well[0]
plate_col = int(well[1:])
well = "{}:{}".format(plate_row, plate_col)
# TODO It seems that we always need controls here, which
# we need to check if that will always be the case.
is_control = controls_barcode_generator.parse(barcode)
if not is_control:
service_request_id, status, comment, org_uri = self._search_for_id(
validated_sample_list, client, ordering_org, row)
if status == "unregistered":
unregistered.append(barcode)
validated_sample_list.csv.loc[ix,
validated_sample_list.COLUMN_ORG_URI] = org_uri
else:
service_request_id = ""
status = ValidatedSampleListFile.STATUS_OK
comment = ""
validated_sample_list.csv.loc[ix,
validated_sample_list.COLUMN_SERVICE_REQUEST_ID] = service_request_id
validated_sample_list.csv.loc[ix,
validated_sample_list.COLUMN_STATUS] = status
validated_sample_list.csv.loc[ix, validated_sample_list.COLUMN_COMMENT] = comment.replace(
",", "<SC>") # If we have the separator in the comment
validated_sample_list_content = validated_sample_list.csv.to_csv(
index=False, sep=",")
timestamp = datetime.now().strftime("%y%m%dT%H%M%S")
file_name = "validated_sample_list_{}.csv".format(timestamp)
self.context.file_service.upload(
"Validated sample list", file_name, validated_sample_list_content,
self.context.file_service.FILE_PREFIX_NONE)
if len(unregistered) > 0:
self.usage_warning("The following sample are unregistered '{}'. Press '{}' "
"to change the 'Status' to anonymous"
"".format(unregistered, BUTTON_TEXT_ASSIGN_UNREGISTERED_TO_ANONYMOUS))
def integration_tests(self):
yield self.test("24-47136", commit=False)
|
py | 1a455e712b6350f8ce358c7d0ce8579906e3836b | #!/usr/bin/env python3
# Copyright (c) 2015-2016 The Deft developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test processing of unrequested blocks.
Setup: two nodes, node0+node1, not connected to each other. Node1 will have
nMinimumChainWork set to 0x10, so it won't process low-work unrequested blocks.
We have one NodeConn connection to node0 called test_node, and one to node1
called min_work_node.
The test:
1. Generate one block on each node, to leave IBD.
2. Mine a new block on each tip, and deliver to each node from node's peer.
The tip should advance for node0, but node1 should skip processing due to
nMinimumChainWork.
Node1 is unused in tests 3-7:
3. Mine a block that forks from the genesis block, and deliver to test_node.
Node0 should not process this block (just accept the header), because it
is unrequested and doesn't have more or equal work to the tip.
4a,b. Send another two blocks that build on the forking block.
Node0 should process the second block but be stuck on the shorter chain,
because it's missing an intermediate block.
4c.Send 288 more blocks on the longer chain (the number of blocks ahead
we currently store).
Node0 should process all but the last block (too far ahead in height).
5. Send a duplicate of the block in #3 to Node0.
Node0 should not process the block because it is unrequested, and stay on
the shorter chain.
6. Send Node0 an inv for the height 3 block produced in #4 above.
Node0 should figure out that Node0 has the missing height 2 block and send a
getdata.
7. Send Node0 the missing block again.
Node0 should process and the tip should advance.
8. Create a fork which is invalid at a height longer than the current chain
(ie to which the node will try to reorg) but which has headers built on top
of the invalid block. Check that we get disconnected if we send more headers
on the chain the node now knows to be invalid.
9. Test Node1 is able to sync when connected to node0 (which should have sufficient
work on its chain).
"""
from test_framework.mininode import *
from test_framework.test_framework import DeftTestFramework
from test_framework.util import *
import time
from test_framework.blocktools import create_block, create_coinbase, create_transaction
class AcceptBlockTest(DeftTestFramework):
def add_options(self, parser):
parser.add_option("--testbinary", dest="testbinary",
default=os.getenv("LITECOIND", "deftd"),
help="deftd binary to test")
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 2
self.extra_args = [[], ["-minimumchainwork=0x10"]]
def setup_network(self):
# Node0 will be used to test behavior of processing unrequested blocks
# from peers which are not whitelisted, while Node1 will be used for
# the whitelisted case.
# Node2 will be used for non-whitelisted peers to test the interaction
# with nMinimumChainWork.
self.setup_nodes()
def run_test(self):
# Setup the p2p connections and start up the network thread.
test_node = NodeConnCB() # connects to node0
min_work_node = NodeConnCB() # connects to node1
connections = []
connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node))
connections.append(NodeConn('127.0.0.1', p2p_port(1), self.nodes[1], min_work_node))
test_node.add_connection(connections[0])
min_work_node.add_connection(connections[1])
NetworkThread().start() # Start up network handling in another thread
# Test logic begins here
test_node.wait_for_verack()
min_work_node.wait_for_verack()
# 1. Have nodes mine a block (leave IBD)
[ n.generate(1) for n in self.nodes ]
tips = [ int("0x" + n.getbestblockhash(), 0) for n in self.nodes ]
# 2. Send one block that builds on each tip.
# This should be accepted by node0
blocks_h2 = [] # the height 2 blocks on each node's chain
block_time = int(time.time()) + 1
for i in range(2):
blocks_h2.append(create_block(tips[i], create_coinbase(2), block_time))
blocks_h2[i].solve()
block_time += 1
test_node.send_message(msg_block(blocks_h2[0]))
min_work_node.send_message(msg_block(blocks_h2[1]))
for x in [test_node, min_work_node]:
x.sync_with_ping()
assert_equal(self.nodes[0].getblockcount(), 2)
assert_equal(self.nodes[1].getblockcount(), 1)
self.log.info("First height 2 block accepted by node0; correctly rejected by node1")
# 3. Send another block that builds on genesis.
block_h1f = create_block(int("0x" + self.nodes[0].getblockhash(0), 0), create_coinbase(1), block_time)
block_time += 1
block_h1f.solve()
test_node.send_message(msg_block(block_h1f))
test_node.sync_with_ping()
tip_entry_found = False
for x in self.nodes[0].getchaintips():
if x['hash'] == block_h1f.hash:
assert_equal(x['status'], "headers-only")
tip_entry_found = True
assert(tip_entry_found)
assert_raises_rpc_error(-1, "Block not found on disk", self.nodes[0].getblock, block_h1f.hash)
# 4. Send another two block that build on the fork.
block_h2f = create_block(block_h1f.sha256, create_coinbase(2), block_time)
block_time += 1
block_h2f.solve()
test_node.send_message(msg_block(block_h2f))
test_node.sync_with_ping()
# Since the earlier block was not processed by node, the new block
# can't be fully validated.
tip_entry_found = False
for x in self.nodes[0].getchaintips():
if x['hash'] == block_h2f.hash:
assert_equal(x['status'], "headers-only")
tip_entry_found = True
assert(tip_entry_found)
# But this block should be accepted by node since it has equal work.
self.nodes[0].getblock(block_h2f.hash)
self.log.info("Second height 2 block accepted, but not reorg'ed to")
# 4b. Now send another block that builds on the forking chain.
block_h3 = create_block(block_h2f.sha256, create_coinbase(3), block_h2f.nTime+1)
block_h3.solve()
test_node.send_message(msg_block(block_h3))
test_node.sync_with_ping()
# Since the earlier block was not processed by node, the new block
# can't be fully validated.
tip_entry_found = False
for x in self.nodes[0].getchaintips():
if x['hash'] == block_h3.hash:
assert_equal(x['status'], "headers-only")
tip_entry_found = True
assert(tip_entry_found)
self.nodes[0].getblock(block_h3.hash)
# But this block should be accepted by node since it has more work.
self.nodes[0].getblock(block_h3.hash)
self.log.info("Unrequested more-work block accepted")
# 4c. Now mine 288 more blocks and deliver; all should be processed but
# the last (height-too-high) on node (as long as its not missing any headers)
tip = block_h3
all_blocks = []
for i in range(288):
next_block = create_block(tip.sha256, create_coinbase(i + 4), tip.nTime+1)
next_block.solve()
all_blocks.append(next_block)
tip = next_block
# Now send the block at height 5 and check that it wasn't accepted (missing header)
test_node.send_message(msg_block(all_blocks[1]))
test_node.sync_with_ping()
assert_raises_rpc_error(-5, "Block not found", self.nodes[0].getblock, all_blocks[1].hash)
assert_raises_rpc_error(-5, "Block not found", self.nodes[0].getblockheader, all_blocks[1].hash)
# The block at height 5 should be accepted if we provide the missing header, though
headers_message = msg_headers()
headers_message.headers.append(CBlockHeader(all_blocks[0]))
test_node.send_message(headers_message)
test_node.send_message(msg_block(all_blocks[1]))
test_node.sync_with_ping()
self.nodes[0].getblock(all_blocks[1].hash)
# Now send the blocks in all_blocks
for i in range(288):
test_node.send_message(msg_block(all_blocks[i]))
test_node.sync_with_ping()
# Blocks 1-287 should be accepted, block 288 should be ignored because it's too far ahead
for x in all_blocks[:-1]:
self.nodes[0].getblock(x.hash)
assert_raises_rpc_error(-1, "Block not found on disk", self.nodes[0].getblock, all_blocks[-1].hash)
# 5. Test handling of unrequested block on the node that didn't process
# Should still not be processed (even though it has a child that has more
# work).
# The node should have requested the blocks at some point, so
# disconnect/reconnect first
connections[0].disconnect_node()
test_node.wait_for_disconnect()
test_node = NodeConnCB() # connects to node (not whitelisted)
connections[0] = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node)
test_node.add_connection(connections[0])
test_node.wait_for_verack()
test_node.send_message(msg_block(block_h1f))
test_node.sync_with_ping()
assert_equal(self.nodes[0].getblockcount(), 2)
self.log.info("Unrequested block that would complete more-work chain was ignored")
# 6. Try to get node to request the missing block.
# Poke the node with an inv for block at height 3 and see if that
# triggers a getdata on block 2 (it should if block 2 is missing).
with mininode_lock:
# Clear state so we can check the getdata request
test_node.last_message.pop("getdata", None)
test_node.send_message(msg_inv([CInv(2, block_h3.sha256)]))
test_node.sync_with_ping()
with mininode_lock:
getdata = test_node.last_message["getdata"]
# Check that the getdata includes the right block
assert_equal(getdata.inv[0].hash, block_h1f.sha256)
self.log.info("Inv at tip triggered getdata for unprocessed block")
# 7. Send the missing block for the third time (now it is requested)
test_node.send_message(msg_block(block_h1f))
test_node.sync_with_ping()
assert_equal(self.nodes[0].getblockcount(), 290)
self.nodes[0].getblock(all_blocks[286].hash)
assert_equal(self.nodes[0].getbestblockhash(), all_blocks[286].hash)
assert_raises_rpc_error(-1, "Block not found on disk", self.nodes[0].getblock, all_blocks[287].hash)
self.log.info("Successfully reorged to longer chain from non-whitelisted peer")
# 8. Create a chain which is invalid at a height longer than the
# current chain, but which has more blocks on top of that
block_289f = create_block(all_blocks[284].sha256, create_coinbase(289), all_blocks[284].nTime+1)
block_289f.solve()
block_290f = create_block(block_289f.sha256, create_coinbase(290), block_289f.nTime+1)
block_290f.solve()
block_291 = create_block(block_290f.sha256, create_coinbase(291), block_290f.nTime+1)
# block_291 spends a coinbase below maturity!
block_291.vtx.append(create_transaction(block_290f.vtx[0], 0, b"42", 1))
block_291.hashMerkleRoot = block_291.calc_merkle_root()
block_291.solve()
block_292 = create_block(block_291.sha256, create_coinbase(292), block_291.nTime+1)
block_292.solve()
# Now send all the headers on the chain and enough blocks to trigger reorg
headers_message = msg_headers()
headers_message.headers.append(CBlockHeader(block_289f))
headers_message.headers.append(CBlockHeader(block_290f))
headers_message.headers.append(CBlockHeader(block_291))
headers_message.headers.append(CBlockHeader(block_292))
test_node.send_message(headers_message)
test_node.sync_with_ping()
tip_entry_found = False
for x in self.nodes[0].getchaintips():
if x['hash'] == block_292.hash:
assert_equal(x['status'], "headers-only")
tip_entry_found = True
assert(tip_entry_found)
assert_raises_rpc_error(-1, "Block not found on disk", self.nodes[0].getblock, block_292.hash)
test_node.send_message(msg_block(block_289f))
test_node.send_message(msg_block(block_290f))
test_node.sync_with_ping()
self.nodes[0].getblock(block_289f.hash)
self.nodes[0].getblock(block_290f.hash)
test_node.send_message(msg_block(block_291))
# At this point we've sent an obviously-bogus block, wait for full processing
# without assuming whether we will be disconnected or not
try:
# Only wait a short while so the test doesn't take forever if we do get
# disconnected
test_node.sync_with_ping(timeout=1)
except AssertionError:
test_node.wait_for_disconnect()
test_node = NodeConnCB() # connects to node (not whitelisted)
connections[0] = NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], test_node)
test_node.add_connection(connections[0])
NetworkThread().start() # Start up network handling in another thread
test_node.wait_for_verack()
# We should have failed reorg and switched back to 290 (but have block 291)
assert_equal(self.nodes[0].getblockcount(), 290)
assert_equal(self.nodes[0].getbestblockhash(), all_blocks[286].hash)
assert_equal(self.nodes[0].getblock(block_291.hash)["confirmations"], -1)
# Now send a new header on the invalid chain, indicating we're forked off, and expect to get disconnected
block_293 = create_block(block_292.sha256, create_coinbase(293), block_292.nTime+1)
block_293.solve()
headers_message = msg_headers()
headers_message.headers.append(CBlockHeader(block_293))
test_node.send_message(headers_message)
test_node.wait_for_disconnect()
# 9. Connect node1 to node0 and ensure it is able to sync
connect_nodes(self.nodes[0], 1)
sync_blocks([self.nodes[0], self.nodes[1]])
self.log.info("Successfully synced nodes 1 and 0")
[ c.disconnect_node() for c in connections ]
if __name__ == '__main__':
AcceptBlockTest().main()
|
py | 1a455e9327231e04ac55a0dc60a11137ce3c9100 | import os
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
settings_module = os.environ.setdefault('DJANGO_SETTINGS_MODULE', "settings.base")
application = Cling(get_wsgi_application())
|
py | 1a455e9a0726f3c1336b9ca30c3569cb0cf9fbf8 | """
Maximum removal of smoke and mirrors. This means:
* No fancy (though mostly unused) scripts here as in bitcoin. We stick to the core business: claiming by signing.
* There's no equivalent of a "bitcoin addresses", P2PKH or P2SH: just public keys and signatures.
One byte is reserved as a type_indicator if we ever want to offer more options (compressed public keys anyone?)
"""
from __future__ import annotations
import struct
from typing import Any, BinaryIO
import ecdsa # NOTE "This library was not designed with security in mind."
from .humans import human
from .serialization import Serializable, DeserializationError, safe_read
TYPE_SIGNABLE_EQUIVALENT = b'\x00'
TYPE_COINBASE_DATA = b'\x01'
TYPE_SECP256k1 = b'\x02'
class PublicKey(Serializable):
def __init__(self) -> None:
self.public_key: bytes
@classmethod
def stream_deserialize(cls, f: BinaryIO) -> SECP256k1PublicKey:
type_indicator = safe_read(f, 1)
if type_indicator == TYPE_SECP256k1:
return SECP256k1PublicKey.stream_deserialize(f)
raise DeserializationError("Non-supported public key type.")
class SECP256k1PublicKey(PublicKey):
"""We use the same curve as bitcoin because why not. Remember: the NIST curves were chosen by the lizard people!"""
def __init__(self, public_key: bytes):
if not len(public_key) == 64:
raise ValueError('SECP256k1 public key must be 64 bytes.')
self.public_key = public_key
def __repr__(self) -> str:
return "SECP256k1 Public Key %s" % human(self.public_key)
def __eq__(self, other: Any) -> bool:
return isinstance(other, SECP256k1PublicKey) and self.public_key == other.public_key
def __hash__(self) -> int:
return hash(self.serialize())
@classmethod
def stream_deserialize(cls, f: BinaryIO) -> SECP256k1PublicKey:
# type_indicator has been read already by the superclass at this point.
public_key: bytes = safe_read(f, 64)
return cls(public_key)
def stream_serialize(self, f: BinaryIO) -> None:
f.write(TYPE_SECP256k1)
f.write(self.public_key)
def validate(self, signature: Any, message: bytes) -> bool:
if not isinstance(signature, SECP256k1Signature):
return False
vk = ecdsa.VerifyingKey.from_string(self.public_key, curve=ecdsa.SECP256k1)
try:
vk.verify(signature.signature, message)
return True
except ecdsa.keys.BadSignatureError:
return False
class Signature(Serializable):
@classmethod
def stream_deserialize(cls, f: BinaryIO) -> Signature:
type_indicator = safe_read(f, 1)
if type_indicator == TYPE_SIGNABLE_EQUIVALENT:
return SignableEquivalent.stream_deserialize(f)
if type_indicator == TYPE_COINBASE_DATA:
return CoinbaseData.stream_deserialize(f)
if type_indicator == TYPE_SECP256k1:
return SECP256k1Signature.stream_deserialize(f)
raise DeserializationError("Non-supported signature type.")
def is_not_signature(self) -> bool:
"""In various places where signatures are expected, special-meaning placeholders can occur instead. Signatures
that may actually be used to verify public keys should return False here."""
return True
def validate(self, public_key: Any, message: bytes) -> bool:
raise NotImplementedError
class SignableEquivalent(Signature):
"""SignableEquivalent: when signing transactions you can't sign your own signature."""
def __repr__(self) -> str:
return "SignableEquivalent()"
def __eq__(self, other: Any) -> bool:
return isinstance(other, SignableEquivalent)
@classmethod
def stream_deserialize(cls, f: BinaryIO) -> SignableEquivalent:
# type_indicator has been read already by the superclass at this point.
return cls()
def stream_serialize(self, f: BinaryIO) -> None:
f.write(TYPE_SIGNABLE_EQUIVALENT)
class CoinbaseData(Signature):
"""In Coinbase transactions, some random data takes the place of the signature. This may be used by miners to
introduce extra randomness if the nonce is not enough, or to include pseudo-polical messages."""
def __init__(self, height: int, signature: bytes):
if not (0 <= height <= 0xFFFFFFFF):
raise ValueError("CoinbaseData height %d is out of range." % height)
if len(signature) > 256:
raise ValueError("Unserializable CoinbaseData")
# height is included to make guarantee Transaction uniqueness. (without height, mining a block with a single
# coinbase transaction with the same output address twice would lead to non-uniqueness).
self.height = height
self.signature = signature
def __repr__(self) -> str:
if all([32 <= b < 127 for b in self.signature]):
return 'CoinbaseData(%s, "%s")' % (self.height, str(self.signature, encoding="ascii"))
return 'CoinbaseData(%s, #%s)' % (self.height, human(self.signature))
def __eq__(self, other: Any) -> bool:
return isinstance(other, CoinbaseData) and self.signature == other.signature
@classmethod
def stream_deserialize(cls, f: BinaryIO) -> CoinbaseData:
# type_indicator has been read already by the superclass at this point.
(height,) = struct.unpack(b">I", safe_read(f, 4))
(length,) = struct.unpack(b"B", safe_read(f, 1))
signature = safe_read(f, length)
return cls(height, signature)
def stream_serialize(self, f: BinaryIO) -> None:
f.write(TYPE_COINBASE_DATA)
f.write(struct.pack(b">I", self.height))
f.write(struct.pack(b"B", len(self.signature)))
f.write(self.signature)
class SECP256k1Signature(Signature):
def __init__(self, signature: bytes):
if not len(signature) == 64:
raise ValueError('SECP256k1 signature must be 64 bytes.')
self.signature = signature
def __repr__(self) -> str:
return "SECP256k1 Signature %s" % human(self.signature)
def __eq__(self, other: Any) -> bool:
return isinstance(other, SECP256k1Signature) and self.signature == other.signature
@classmethod
def stream_deserialize(cls, f: BinaryIO) -> SECP256k1Signature:
# type_indicator has been read already by the superclass at this point.
signature = safe_read(f, 64)
return cls(signature)
def stream_serialize(self, f: BinaryIO) -> None:
f.write(TYPE_SECP256k1)
f.write(self.signature)
def validate(self, public_key: Any, message: bytes) -> bool:
if not isinstance(public_key, SECP256k1PublicKey):
return False
return public_key.validate(self, message)
def is_not_signature(self) -> bool:
return False
__all__ = [
"PublicKey",
"SECP256k1PublicKey",
"Signature",
"SignableEquivalent",
"CoinbaseData",
"SECP256k1Signature",
]
|
py | 1a455fa6d5a059bcaaf1edaab64ac84ac9e4ee23 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.28 on 2020-03-11 17:35
from django.db import migrations
from wagtail.core import blocks as core_blocks
from wagtail.core import fields as core_fields
class Migration(migrations.Migration):
dependencies = [
('mega_menu', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='menu',
name='submenus',
field=core_fields.StreamField((('submenu', core_blocks.StructBlock((('title', core_blocks.CharBlock()), ('overview_page', core_blocks.PageChooserBlock(required=False)), ('featured_links', core_blocks.ListBlock(core_blocks.StructBlock((('page', core_blocks.PageChooserBlock(required=False)), ('text', core_blocks.CharBlock(required=False)), ('url', core_blocks.CharBlock(required=False)))), default=[])), ('other_links', core_blocks.ListBlock(core_blocks.StructBlock((('page', core_blocks.PageChooserBlock(required=False)), ('text', core_blocks.CharBlock(required=False)), ('url', core_blocks.CharBlock(required=False)), ('icon', core_blocks.CharBlock()))), default=[])), ('columns', core_blocks.ListBlock(core_blocks.StructBlock((('heading', core_blocks.CharBlock(required=False)), ('links', core_blocks.ListBlock(core_blocks.StructBlock((('page', core_blocks.PageChooserBlock(required=False)), ('text', core_blocks.CharBlock(required=False)), ('url', core_blocks.CharBlock(required=False)))), default=[])))), default=[]))))),)),
),
]
|
py | 1a45606d67f31ed2d4b881c3efcce4f7a1a826d8 | # Generated by Django 3.2.4 on 2021-06-12 19:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("noauth", "0005_auto_20191026_2217")]
operations = [
migrations.AlterField(
model_name="user", name="first_name", field=models.CharField(blank=True, max_length=150, verbose_name="first name")
)
]
|
py | 1a456084d88aabd40f151923575a2797b95efa12 | info = {
"name": "ks",
"date_order": "MDY",
"january": [
"جنؤری"
],
"february": [
"فرؤری"
],
"march": [
"مارٕچ"
],
"april": [
"اپریل"
],
"may": [
"میٔ"
],
"june": [
"جوٗن"
],
"july": [
"جوٗلایی"
],
"august": [
"اگست"
],
"september": [
"ستمبر"
],
"october": [
"اکتوٗبر"
],
"november": [
"نومبر"
],
"december": [
"دسمبر"
],
"monday": [
"ژٔنٛدرٕروار",
"ژٔنٛدٕروار"
],
"tuesday": [
"بوٚموار"
],
"wednesday": [
"بودوار"
],
"thursday": [
"برٛٮ۪سوار"
],
"friday": [
"جُمہ"
],
"saturday": [
"بٹوار"
],
"sunday": [
"اَتھوار",
"آتھوار"
],
"am": [
"am"
],
"pm": [
"pm"
],
"year": [
"ؤری"
],
"month": [
"رٮ۪تھ"
],
"week": [
"ہفتہٕ"
],
"day": [
"دۄہ"
],
"hour": [
"گٲنٛٹہٕ"
],
"minute": [
"مِنَٹ"
],
"second": [
"سٮ۪کَنڑ"
],
"relative-type": {
"1 year ago": [
"last year"
],
"0 year ago": [
"this year"
],
"in 1 year": [
"next year"
],
"1 month ago": [
"last month"
],
"0 month ago": [
"this month"
],
"in 1 month": [
"next month"
],
"1 week ago": [
"last week"
],
"0 week ago": [
"this week"
],
"in 1 week": [
"next week"
],
"1 day ago": [
"راتھ"
],
"0 day ago": [
"اَز"
],
"in 1 day": [
"پگاہ"
],
"0 hour ago": [
"this hour"
],
"0 minute ago": [
"this minute"
],
"0 second ago": [
"now"
]
},
"locale_specific": {},
"skip": [
" ",
".",
",",
";",
"-",
"/",
"'",
"|",
"@",
"[",
"]",
","
]
}
|
py | 1a4560e6c15b32f07d918f4f5ee71a7ff0eeadff | import ntpath
from lead2gold.tools.tool import Tool
from lead2gold.util import pwm2consensus
from lead2gold.util import sequence2pwm
from lead2gold.motif import Motif
class EMD(Tool):
"""Class implementing a EMD search tool motif convertor.
"""
toolName = "EMD"
def __init__(self):
"""Initialize all class attributes with their default values.
"""
super(self.__class__, self).__init__(self.toolName)
def parse(self, motif_file, type=None):
"""Loads the searcher parameters specified in the configuration file.
Args:
motif_file: file containing one or more EMD motifs.
Returns:
[Motif()]
"""
basename=ntpath.basename(motif_file.name)
def get_section(line, section, order):
if len(line) < 2:
return "stop", 1
if "Motif " in line[0:8]:
return "name", 2
return section, order
def get_template():
return {
"start": [],
"stop": [],
"name": []
}
motifs = []
section = "start"
order = 0
t_motif = get_template()
for line in motif_file:
clean_line = line.strip()
section, order_new = get_section(line, section, order)
if order_new < order:
motifs.append(self._parse_motif(t_motif))
t_motif = get_template()
order = order_new
t_motif[section].append(clean_line)
motifs.append(self._parse_motif(t_motif))
return list(filter(None, motifs))
def _parse_motif(self, t_motif):
name = t_motif["name"].pop(0)
sequences = []
for row in t_motif["name"]:
row_values = row.split()
if len(row_values) == 4:
sequences.append(row_values[0])
counters, _ = sequence2pwm(sequences)
motif = Motif(identifier=name, counters=counters)
consensus = pwm2consensus(motif.get_PPM())
motif.set_number_of_sites(len(sequences))
motif.set_alternate_name(consensus)
return motif
|
py | 1a4561133f948831b9ca0d69821a3394f092fae7 | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from paddle.optimizer import lr
from paddle.optimizer.lr import LRScheduler
from ppcls.utils import logger
class Linear(object):
"""
Linear learning rate decay
Args:
lr (float): The initial learning rate. It is a python float number.
epochs(int): The decay step size. It determines the decay cycle.
end_lr(float, optional): The minimum final learning rate. Default: 0.0001.
power(float, optional): Power of polynomial. Default: 1.0.
warmup_epoch(int): The epoch numbers for LinearWarmup. Default: 0.
warmup_start_lr(float): Initial learning rate of warm up. Default: 0.0.
last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
"""
def __init__(self,
learning_rate,
epochs,
step_each_epoch,
end_lr=0.0,
power=1.0,
warmup_epoch=0,
warmup_start_lr=0.0,
last_epoch=-1,
**kwargs):
super().__init__()
if warmup_epoch >= epochs:
msg = f"When using warm up, the value of \"Global.epochs\" must be greater than value of \"Optimizer.lr.warmup_epoch\". The value of \"Optimizer.lr.warmup_epoch\" has been set to {epochs}."
logger.warning(msg)
warmup_epoch = epochs
self.learning_rate = learning_rate
self.steps = (epochs - warmup_epoch) * step_each_epoch
self.end_lr = end_lr
self.power = power
self.last_epoch = last_epoch
self.warmup_steps = round(warmup_epoch * step_each_epoch)
self.warmup_start_lr = warmup_start_lr
def __call__(self):
learning_rate = lr.PolynomialDecay(
learning_rate=self.learning_rate,
decay_steps=self.steps,
end_lr=self.end_lr,
power=self.power,
last_epoch=self.
last_epoch) if self.steps > 0 else self.learning_rate
if self.warmup_steps > 0:
learning_rate = lr.LinearWarmup(
learning_rate=learning_rate,
warmup_steps=self.warmup_steps,
start_lr=self.warmup_start_lr,
end_lr=self.learning_rate,
last_epoch=self.last_epoch)
return learning_rate
class Constant(LRScheduler):
"""
Constant learning rate
Args:
lr (float): The initial learning rate. It is a python float number.
last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
"""
def __init__(self, learning_rate, last_epoch=-1, **kwargs):
self.learning_rate = learning_rate
self.last_epoch = last_epoch
super().__init__()
def get_lr(self):
return self.learning_rate
class Cosine(object):
"""
Cosine learning rate decay
lr = 0.05 * (math.cos(epoch * (math.pi / epochs)) + 1)
Args:
lr(float): initial learning rate
step_each_epoch(int): steps each epoch
epochs(int): total training epochs
eta_min(float): Minimum learning rate. Default: 0.0.
warmup_epoch(int): The epoch numbers for LinearWarmup. Default: 0.
warmup_start_lr(float): Initial learning rate of warm up. Default: 0.0.
last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
"""
def __init__(self,
learning_rate,
step_each_epoch,
epochs,
eta_min=0.0,
warmup_epoch=0,
warmup_start_lr=0.0,
last_epoch=-1,
**kwargs):
super().__init__()
if warmup_epoch >= epochs:
msg = f"When using warm up, the value of \"Global.epochs\" must be greater than value of \"Optimizer.lr.warmup_epoch\". The value of \"Optimizer.lr.warmup_epoch\" has been set to {epochs}."
logger.warning(msg)
warmup_epoch = epochs
self.learning_rate = learning_rate
self.T_max = (epochs - warmup_epoch) * step_each_epoch
self.eta_min = eta_min
self.last_epoch = last_epoch
self.warmup_steps = round(warmup_epoch * step_each_epoch)
self.warmup_start_lr = warmup_start_lr
def __call__(self):
learning_rate = lr.CosineAnnealingDecay(
learning_rate=self.learning_rate,
T_max=self.T_max,
eta_min=self.eta_min,
last_epoch=self.
last_epoch) if self.T_max > 0 else self.learning_rate
if self.warmup_steps > 0:
learning_rate = lr.LinearWarmup(
learning_rate=learning_rate,
warmup_steps=self.warmup_steps,
start_lr=self.warmup_start_lr,
end_lr=self.learning_rate,
last_epoch=self.last_epoch)
return learning_rate
class Step(object):
"""
Piecewise learning rate decay
Args:
step_each_epoch(int): steps each epoch
learning_rate (float): The initial learning rate. It is a python float number.
step_size (int): the interval to update.
gamma (float, optional): The Ratio that the learning rate will be reduced. ``new_lr = origin_lr * gamma`` .
It should be less than 1.0. Default: 0.1.
warmup_epoch(int): The epoch numbers for LinearWarmup. Default: 0.
warmup_start_lr(float): Initial learning rate of warm up. Default: 0.0.
last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
"""
def __init__(self,
learning_rate,
step_size,
step_each_epoch,
epochs,
gamma,
warmup_epoch=0,
warmup_start_lr=0.0,
last_epoch=-1,
**kwargs):
super().__init__()
if warmup_epoch >= epochs:
msg = f"When using warm up, the value of \"Global.epochs\" must be greater than value of \"Optimizer.lr.warmup_epoch\". The value of \"Optimizer.lr.warmup_epoch\" has been set to {epochs}."
logger.warning(msg)
warmup_epoch = epochs
self.step_size = step_each_epoch * step_size
self.learning_rate = learning_rate
self.gamma = gamma
self.last_epoch = last_epoch
self.warmup_steps = round(warmup_epoch * step_each_epoch)
self.warmup_start_lr = warmup_start_lr
def __call__(self):
learning_rate = lr.StepDecay(
learning_rate=self.learning_rate,
step_size=self.step_size,
gamma=self.gamma,
last_epoch=self.last_epoch)
if self.warmup_steps > 0:
learning_rate = lr.LinearWarmup(
learning_rate=learning_rate,
warmup_steps=self.warmup_steps,
start_lr=self.warmup_start_lr,
end_lr=self.learning_rate,
last_epoch=self.last_epoch)
return learning_rate
class Piecewise(object):
"""
Piecewise learning rate decay
Args:
boundaries(list): A list of steps numbers. The type of element in the list is python int.
values(list): A list of learning rate values that will be picked during different epoch boundaries.
The type of element in the list is python float.
warmup_epoch(int): The epoch numbers for LinearWarmup. Default: 0.
warmup_start_lr(float): Initial learning rate of warm up. Default: 0.0.
by_epoch(bool): Whether lr decay by epoch. Default: False.
last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
"""
def __init__(self,
step_each_epoch,
decay_epochs,
values,
epochs,
warmup_epoch=0,
warmup_start_lr=0.0,
by_epoch=False,
last_epoch=-1,
**kwargs):
super().__init__()
if warmup_epoch >= epochs:
msg = f"When using warm up, the value of \"Global.epochs\" must be greater than value of \"Optimizer.lr.warmup_epoch\". The value of \"Optimizer.lr.warmup_epoch\" has been set to {epochs}."
logger.warning(msg)
warmup_epoch = epochs
self.boundaries_steps = [step_each_epoch * e for e in decay_epochs]
self.boundaries_epoch = decay_epochs
self.values = values
self.last_epoch = last_epoch
self.warmup_steps = round(warmup_epoch * step_each_epoch)
self.warmup_epoch = warmup_epoch
self.warmup_start_lr = warmup_start_lr
self.by_epoch = by_epoch
def __call__(self):
if self.by_epoch:
learning_rate = lr.PiecewiseDecay(
boundaries=self.boundaries_epoch,
values=self.values,
last_epoch=self.last_epoch)
if self.warmup_epoch > 0:
learning_rate = lr.LinearWarmup(
learning_rate=learning_rate,
warmup_steps=self.warmup_epoch,
start_lr=self.warmup_start_lr,
end_lr=self.values[0],
last_epoch=self.last_epoch)
else:
learning_rate = lr.PiecewiseDecay(
boundaries=self.boundaries_steps,
values=self.values,
last_epoch=self.last_epoch)
if self.warmup_steps > 0:
learning_rate = lr.LinearWarmup(
learning_rate=learning_rate,
warmup_steps=self.warmup_steps,
start_lr=self.warmup_start_lr,
end_lr=self.values[0],
last_epoch=self.last_epoch)
setattr(learning_rate, "by_epoch", self.by_epoch)
return learning_rate
class MultiStepDecay(LRScheduler):
"""
Update the learning rate by ``gamma`` once ``epoch`` reaches one of the milestones.
The algorithm can be described as the code below.
.. code-block:: text
learning_rate = 0.5
milestones = [30, 50]
gamma = 0.1
if epoch < 30:
learning_rate = 0.5
elif epoch < 50:
learning_rate = 0.05
else:
learning_rate = 0.005
Args:
learning_rate (float): The initial learning rate. It is a python float number.
milestones (tuple|list): List or tuple of each boundaries. Must be increasing.
gamma (float, optional): The Ratio that the learning rate will be reduced. ``new_lr = origin_lr * gamma`` .
It should be less than 1.0. Default: 0.1.
last_epoch (int, optional): The index of last epoch. Can be set to restart training. Default: -1, means initial learning rate.
verbose (bool, optional): If ``True``, prints a message to stdout for each update. Default: ``False`` .
Returns:
``MultiStepDecay`` instance to schedule learning rate.
Examples:
.. code-block:: python
import paddle
import numpy as np
# train on default dynamic graph mode
linear = paddle.nn.Linear(10, 10)
scheduler = paddle.optimizer.lr.MultiStepDecay(learning_rate=0.5, milestones=[2, 4, 6], gamma=0.8, verbose=True)
sgd = paddle.optimizer.SGD(learning_rate=scheduler, parameters=linear.parameters())
for epoch in range(20):
for batch_id in range(5):
x = paddle.uniform([10, 10])
out = linear(x)
loss = paddle.mean(out)
loss.backward()
sgd.step()
sgd.clear_gradients()
scheduler.step() # If you update learning rate each step
# scheduler.step() # If you update learning rate each epoch
# train on static graph mode
paddle.enable_static()
main_prog = paddle.static.Program()
start_prog = paddle.static.Program()
with paddle.static.program_guard(main_prog, start_prog):
x = paddle.static.data(name='x', shape=[None, 4, 5])
y = paddle.static.data(name='y', shape=[None, 4, 5])
z = paddle.static.nn.fc(x, 100)
loss = paddle.mean(z)
scheduler = paddle.optimizer.lr.MultiStepDecay(learning_rate=0.5, milestones=[2, 4, 6], gamma=0.8, verbose=True)
sgd = paddle.optimizer.SGD(learning_rate=scheduler)
sgd.minimize(loss)
exe = paddle.static.Executor()
exe.run(start_prog)
for epoch in range(20):
for batch_id in range(5):
out = exe.run(
main_prog,
feed={
'x': np.random.randn(3, 4, 5).astype('float32'),
'y': np.random.randn(3, 4, 5).astype('float32')
},
fetch_list=loss.name)
scheduler.step() # If you update learning rate each step
# scheduler.step() # If you update learning rate each epoch
"""
def __init__(self,
learning_rate,
milestones,
epochs,
step_each_epoch,
gamma=0.1,
last_epoch=-1,
verbose=False):
if not isinstance(milestones, (tuple, list)):
raise TypeError(
"The type of 'milestones' in 'MultiStepDecay' must be 'tuple, list', but received %s."
% type(milestones))
if not all([
milestones[i] < milestones[i + 1]
for i in range(len(milestones) - 1)
]):
raise ValueError('The elements of milestones must be incremented')
if gamma >= 1.0:
raise ValueError('gamma should be < 1.0.')
self.milestones = [x * step_each_epoch for x in milestones]
self.gamma = gamma
super().__init__(learning_rate, last_epoch, verbose)
def get_lr(self):
for i in range(len(self.milestones)):
if self.last_epoch < self.milestones[i]:
return self.base_lr * (self.gamma**i)
return self.base_lr * (self.gamma**len(self.milestones))
|
py | 1a45621e3b1520b3abcce3d6c91542d7d4e5fe74 | #
# -*- coding: utf-8 -*-
# Copyright 2019 Red Hat
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#############################################
# WARNING #
#############################################
#
# This file is auto generated by the resource
# module builder playbook.
#
# Do not edit this file manually.
#
# Changes to this file will be over written
# by the resource module builder.
#
# Changes should be made in the model used to
# generate this file or in the resource module
# builder template.
#
#############################################
"""
The arg spec for the eos_static_routes module
"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type
class Static_routesArgs(object):
"""The arg spec for the eos_static_routes module"""
def __init__(self, **kwargs):
pass
argument_spec = {
"config": {
"elements": "dict",
"options": {
"address_families": {
"elements": "dict",
"options": {
"afi": {
"choices": ["ipv4", "ipv6"],
"required": True,
"type": "str",
},
"routes": {
"elements": "dict",
"options": {
"dest": {"required": True, "type": "str"},
"next_hops": {
"elements": "dict",
"options": {
"admin_distance": {"type": "int"},
"description": {"type": "str"},
"forward_router_address": {
"type": "str"
},
"interface": {"type": "str"},
"nexthop_grp": {"type": "str"},
"mpls_label": {"type": "int"},
"tag": {"type": "int"},
"track": {"type": "str"},
"vrf": {"type": "str"},
},
"type": "list",
},
},
"type": "list",
},
},
"type": "list",
},
"vrf": {"type": "str"},
},
"type": "list",
},
"running_config": {"type": "str"},
"state": {
"choices": [
"deleted",
"merged",
"overridden",
"replaced",
"gathered",
"rendered",
"parsed",
],
"default": "merged",
"type": "str",
},
} # pylint: disable=C0301
|
py | 1a4562961dd1aa56575e61ad6ce42f8ddba08dc6 |
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if 0 > x:
return False
if 0 == x:
return True
s = str(x)
s.replace(" ","") #remove all spaces
if s == s[::-1]:
return True
else:
return False
def main():
x = 12321
solution = Solution()
print solution.isPalindrome(x)
if __name__ == '__main__':
main() |
py | 1a45629da491ab4c4073ea1191307e4cc3ddd8eb | #!/usr/bin/env python
import rospy
import actionlib
from actionlib_msgs.msg import *
from geometry_msgs.msg import Pose, Point, Quaternion, Twist
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
from tf.transformations import quaternion_from_euler
from visualization_msgs.msg import Marker
from math import radians, pi
class MoveBaseSquare():
def __init__(self):
rospy.init_node('box_client', anonymous=False)
rospy.on_shutdown(self.shutdown)
# Create a list to hold the waypoint poses
waypoints = list()
# Append each of the four waypoints to the list. Each waypoint
# is a pose consisting of a position and orientation in the map frame.
waypoints.append(Pose(Point(10.0, 0.62, 0.0), Quaternion(0,0,0,1)))
# Initialize the visualization markers for RViz
self.init_markers()
# Set a visualization marker at each waypoint
for waypoint in waypoints:
p = Point()
p = waypoint.position
self.markers.points.append(p)
# Subscribe to the move_base action server
self.move_base = actionlib.SimpleActionClient("move_base", MoveBaseAction)
rospy.loginfo("Waiting for move_base action server...")
# Wait 60 seconds for the action server to become available
self.move_base.wait_for_server(rospy.Duration(60))
rospy.loginfo("Connected to move base server")
rospy.loginfo("Starting navigation test")
# Initialize a counter to track waypoints
i = 0
# Cycle through the four waypoints
while i < len(waypoints) and not rospy.is_shutdown():
# Update the marker display
self.marker_pub.publish(self.markers)
# Intialize the waypoint goal
goal = MoveBaseGoal()
# Use the map frame to define goal poses
goal.target_pose.header.frame_id = 'map'
# Set the time stamp to "now"
goal.target_pose.header.stamp = rospy.Time.now()
# Set the goal pose to the i-th waypoint
goal.target_pose.pose = waypoints[i]
# Start the robot moving toward the goal
self.move(goal)
i += 1
def move(self, goal):
# Send the goal pose to the MoveBaseAction server
self.move_base.send_goal(goal)
# Allow 1 minute to get there
finished_within_time = self.move_base.wait_for_result(rospy.Duration(60))
# If we don't get there in time, abort the goal
if not finished_within_time:
self.move_base.cancel_goal()
rospy.loginfo("Timed out achieving goal")
else:
# We made it!
state = self.move_base.get_state()
if state == GoalStatus.SUCCEEDED:
rospy.loginfo("Goal succeeded!")
def init_markers(self):
# Set up our waypoint markers
marker_scale = 0.2
marker_lifetime = 0 # 0 is forever
marker_ns = 'waypoints'
marker_id = 0
marker_color = {'r': 1.0, 'g': 0.7, 'b': 1.0, 'a': 1.0}
# Define a marker publisher.
self.marker_pub = rospy.Publisher('waypoint_markers', Marker, queue_size=1)
# Initialize the marker points list.
self.markers = Marker()
self.markers.ns = marker_ns
self.markers.id = marker_id
self.markers.type = Marker.SPHERE_LIST
self.markers.action = Marker.ADD
self.markers.lifetime = rospy.Duration(marker_lifetime)
self.markers.scale.x = marker_scale
self.markers.scale.y = marker_scale
self.markers.color.r = marker_color['r']
self.markers.color.g = marker_color['g']
self.markers.color.b = marker_color['b']
self.markers.color.a = marker_color['a']
self.markers.header.frame_id = 'map'
self.markers.header.stamp = rospy.Time.now()
self.markers.points = list()
def shutdown(self):
rospy.loginfo("Stopping the robot...")
# Cancel any active goals
self.move_base.cancel_goal()
rospy.sleep(2)
if __name__ == '__main__':
try:
MoveBaseSquare()
except rospy.ROSInterruptException:
rospy.loginfo("Navigation test finished.")
|
py | 1a4562cc6eec7f0574e6c4491e39fac4f5240852 | #!/usr/bin/env python
import sys
import logging
import argparse
import json
from pds_pipelines.db import db_connect
from pds_pipelines.models.pds_models import Files
from pds_pipelines.RedisQueue import RedisQueue
from pds_pipelines.config import pds_log, pds_info, pds_db
class Args:
def __init__(self):
pass
def parse_args(self):
parser = argparse.ArgumentParser(description='UPC Queueing')
parser.add_argument('--archive', '-a', dest="archive", required=True,
help="Enter archive - archive to ingest")
parser.add_argument('--volume', '-v', dest="volume",
help="Enter volume to Ingest")
parser.add_argument('--search', '-s', dest="search",
help="Enter string to search for")
args = parser.parse_args()
self.archive = args.archive
self.volume = args.volume
self.search = args.search
def main():
# pdb.set_trace()
args = Args()
args.parse_args()
logger = logging.getLogger('UPC_Queueing.' + args.archive)
logger.setLevel(logging.INFO)
# logFileHandle = logging.FileHandler('/usgs/cdev/PDS/logs/Process.log')
logFileHandle = logging.FileHandler(pds_log + 'Process.log')
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s, %(message)s')
logFileHandle.setFormatter(formatter)
logger.addHandler(logFileHandle)
logger.info('Starting Process')
PDSinfoDICT = json.load(open(pds_info, 'r'))
try:
archiveID = PDSinfoDICT[args.archive]['archiveid']
except KeyError:
print("\nArchive '{}' not found in {}\n".format(args.archive, pds_info))
print("The following archives are available:")
for k in PDSinfoDICT.keys():
print("\t{}".format(k))
exit()
RQ = RedisQueue('UPC_ReadyQueue')
try:
session, _ = db_connect(pds_db)
print('Database Connection Success')
except Exception as e:
print(e)
print('Database Connection Error')
if args.volume:
volstr = '%' + args.volume + '%'
qOBJ = session.query(Files).filter(Files.archiveid == archiveID,
Files.filename.like(volstr),
Files.upc_required == 't')
else:
qOBJ = session.query(Files).filter(Files.archiveid == archiveID,
Files.upc_required == 't')
if qOBJ:
addcount = 0
for element in qOBJ:
fname = PDSinfoDICT[args.archive]['path'] + element.filename
fid = element.fileid
RQ.QueueAdd((fname, fid, args.archive))
addcount = addcount + 1
logger.info('Files Added to UPC Queue: %s', addcount)
print("Done")
if __name__ == "__main__":
sys.exit(main())
|
py | 1a4564af1c7e7f6f0fb59f018445a5e6a80122c5 | # -*- coding: utf-8 -*-
"""
requests.utils
~~~~~~~~~~~~~~
This module provides utlity functions that are used within Requests
that are also useful for external consumption.
"""
import cgi
import codecs
import http.cookiejar
import os
import random
import re
import zlib
from urllib2 import parse_http_list as _parse_list_header
def guess_filename(obj):
"""Tries to guess the filename of the given object."""
name = getattr(obj, 'name', None)
if name and name[0] != '<' and name[-1] != '>':
return name
# From mitsuhiko/werkzeug (used with permission).
def parse_list_header(value):
"""Parse lists as described by RFC 2068 Section 2.
In particular, parse comma-separated lists where the elements of
the list may include quoted-strings. A quoted-string could
contain a comma. A non-quoted string could have quotes in the
middle. Quotes are removed automatically after parsing.
It basically works like :func:`parse_set_header` just that items
may appear multiple times and case sensitivity is preserved.
The return value is a standard :class:`list`:
>>> parse_list_header('token, "quoted value"')
['token', 'quoted value']
To create a header from the :class:`list` again, use the
:func:`dump_header` function.
:param value: a string with a list header.
:return: :class:`list`
"""
result = []
for item in _parse_list_header(value):
if item[:1] == item[-1:] == '"':
item = unquote_header_value(item[1:-1])
result.append(item)
return result
# From mitsuhiko/werkzeug (used with permission).
def parse_dict_header(value):
"""Parse lists of key, value pairs as described by RFC 2068 Section 2 and
convert them into a python dict:
>>> d = parse_dict_header('foo="is a fish", bar="as well"')
>>> type(d) is dict
True
>>> sorted(d.items())
[('bar', 'as well'), ('foo', 'is a fish')]
If there is no value for a key it will be `None`:
>>> parse_dict_header('key_without_value')
{'key_without_value': None}
To create a header from the :class:`dict` again, use the
:func:`dump_header` function.
:param value: a string with a dict header.
:return: :class:`dict`
"""
result = {}
for item in _parse_list_header(value):
if '=' not in item:
result[item] = None
continue
name, value = item.split('=', 1)
if value[:1] == value[-1:] == '"':
value = unquote_header_value(value[1:-1])
result[name] = value
return result
# From mitsuhiko/werkzeug (used with permission).
def unquote_header_value(value, is_filename=False):
r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).
This does not use the real unquoting but what browsers are actually
using for quoting.
:param value: the header value to unquote.
"""
if value and value[0] == value[-1] == '"':
# this is not the real unquoting, but fixing this so that the
# RFC is met will result in bugs with internet explorer and
# probably some other browsers as well. IE for example is
# uploading files with "C:\foo\bar.txt" as filename
value = value[1:-1]
# if this is a filename and the starting characters look like
# a UNC path, then just return the value without quotes. Using the
# replace sequence below on a UNC path has the effect of turning
# the leading double slash into a single slash and then
# _fix_ie_filename() doesn't work correctly. See #458.
if not is_filename or value[:2] != '\\\\':
return value.replace('\\\\', '\\').replace('\\"', '"')
return value
def header_expand(headers):
"""Returns an HTTP Header value string from a dictionary.
Example expansion::
{'text/x-dvi': {'q': '.8', 'mxb': '100000', 'mxt': '5.0'}, 'text/x-c': {}}
# Accept: text/x-dvi; q=.8; mxb=100000; mxt=5.0, text/x-c
(('text/x-dvi', {'q': '.8', 'mxb': '100000', 'mxt': '5.0'}), ('text/x-c', {}))
# Accept: text/x-dvi; q=.8; mxb=100000; mxt=5.0, text/x-c
"""
collector = []
if isinstance(headers, dict):
headers = list(headers.items())
elif isinstance(headers, str):
return headers
for i, (value, params) in enumerate(headers):
_params = []
for (p_k, p_v) in list(params.items()):
_params.append('%s=%s' % (p_k, p_v))
collector.append(value)
collector.append('; ')
if len(params):
collector.append('; '.join(_params))
if not len(headers) == i+1:
collector.append(', ')
# Remove trailing separators.
if collector[-1] in (', ', '; '):
del collector[-1]
return ''.join(collector)
def randombytes(n):
"""Return n random bytes."""
# Use /dev/urandom if it is available. Fall back to random module
# if not. It might be worthwhile to extend this function to use
# other platform-specific mechanisms for getting random bytes.
if os.path.exists("/dev/urandom"):
f = open("/dev/urandom")
s = f.read(n)
f.close()
return s
else:
L = [chr(random.randrange(0, 256)) for i in range(n)]
return "".join(L)
def dict_from_cookiejar(cj):
"""Returns a key/value dictionary from a CookieJar.
:param cj: CookieJar object to extract cookies from.
"""
cookie_dict = {}
for _, cookies in list(cj._cookies.items()):
for _, cookies in list(cookies.items()):
for cookie in list(cookies.values()):
# print cookie
cookie_dict[cookie.name] = cookie.value
return cookie_dict
def cookiejar_from_dict(cookie_dict):
"""Returns a CookieJar from a key/value dictionary.
:param cookie_dict: Dict of key/values to insert into CookieJar.
"""
# return cookiejar if one was passed in
if isinstance(cookie_dict, http.cookiejar.CookieJar):
return cookie_dict
# create cookiejar
cj = http.cookiejar.CookieJar()
cj = add_dict_to_cookiejar(cj, cookie_dict)
return cj
def add_dict_to_cookiejar(cj, cookie_dict):
"""Returns a CookieJar from a key/value dictionary.
:param cj: CookieJar to insert cookies into.
:param cookie_dict: Dict of key/values to insert into CookieJar.
"""
for k, v in list(cookie_dict.items()):
cookie = http.cookiejar.Cookie(
version=0,
name=k,
value=v,
port=None,
port_specified=False,
domain='',
domain_specified=False,
domain_initial_dot=False,
path='/',
path_specified=True,
secure=False,
expires=None,
discard=True,
comment=None,
comment_url=None,
rest={'HttpOnly': None},
rfc2109=False
)
# add cookie to cookiejar
cj.set_cookie(cookie)
return cj
def get_encodings_from_content(content):
"""Returns encodings from given content string.
:param content: bytestring to extract encodings from.
"""
charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
return charset_re.findall(content)
def get_encoding_from_headers(headers):
"""Returns encodings from given HTTP Header Dict.
:param headers: dictionary to extract encoding from.
"""
content_type = headers.get('content-type')
if not content_type:
return None
content_type, params = cgi.parse_header(content_type)
if 'charset' in params:
return params['charset'].strip("'\"")
def unicode_from_html(content):
"""Attempts to decode an HTML string into unicode.
If unsuccessful, the original content is returned.
"""
encodings = get_encodings_from_content(content)
for encoding in encodings:
try:
return str(content, encoding)
except (UnicodeError, TypeError):
pass
return content
def stream_decode_response_unicode(iterator, r):
"""Stream decodes a iterator."""
encoding = get_encoding_from_headers(r.headers)
if encoding is None:
for item in iterator:
yield item
return
decoder = codecs.getincrementaldecoder(encoding)(errors='replace')
for chunk in iterator:
rv = decoder.decode(chunk)
if rv:
yield rv
rv = decoder.decode('', final=True)
if rv:
yield rv
def get_unicode_from_response(r):
"""Returns the requested content back in unicode.
:param r: Response object to get unicode content from.
Tried:
1. charset from content-type
2. every encodings from ``<meta ... charset=XXX>``
3. fall back and replace all unicode characters
"""
tried_encodings = []
# Try charset from content-type
encoding = get_encoding_from_headers(r.headers)
if encoding:
try:
return str(r.content, encoding)
except UnicodeError:
tried_encodings.append(encoding)
# Fall back:
try:
return str(r.content, encoding, errors='replace')
except TypeError:
return r.content
def decode_gzip(content):
"""Return gzip-decoded string.
:param content: bytestring to gzip-decode.
"""
return zlib.decompress(content, 16 + zlib.MAX_WBITS)
def stream_decode_gzip(iterator):
"""Stream decodes a gzip-encoded iterator"""
try:
dec = zlib.decompressobj(16 + zlib.MAX_WBITS)
for chunk in iterator:
rv = dec.decompress(chunk)
if rv:
yield rv
buf = dec.decompress('')
rv = buf + dec.flush()
if rv:
yield rv
except zlib.error:
pass
|
py | 1a4564ecc8679ba033c801270cb73e57f0dffc91 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django # noqa
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
# This allows easy placement of apps within the interior
# earsie_eats_blog directory.
current_path = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(current_path, "earsie_eats_blog"))
execute_from_command_line(sys.argv)
|
py | 1a456675dcce81a2f18f42da61837b39369aa2e6 | from enum import Enum
import random
import pampy
class Case(Enum):
Nominative = 1
Accusative = 2
Genitive = 3
Dative = 4
class Gender(Enum):
Female = 1
Masculine = 2
Neutral = 3
class Declension(Enum):
First = 1
Second = 2
Third = 3
class Number(Enum):
Single = 1
Dual = 2
Plural = 3
def decline_noun(stem: str, genitiveEnding: str, declension: Declension, gender: Gender, number: Number, case: Case) -> str:
input = [declension, gender, number]
return pampy.match(
input,
[Declension.First, Gender.Female, Number.Single],
decline_first_decl_female_singular(stem, genitiveEnding, case),
[Declension.First, Gender.Female, Number.Dual],
decline_first_decl_female_dual(stem, case),
[Declension.First, Gender.Female, Number.Plural],
decline_first_decl_female_dual(stem, case),
[str, str, Declension, Gender, Number, Case], ''
)
def decline_first_decl_female_singular(stem: str, genitiveEnding: str, case: Case):
return pampy.match(
case,
Case.Nominative, stem + 'α',
Case.Accusative, stem + 'αν',
Case.Genitive, stem + 'ᾱς',
Case.Dative, stem + 'ᾳ'
)
def decline_first_decl_female_plural(stem: str, case: Case):
return pampy.match(
case,
Case.Nominative, stem + 'αι',
Case.Accusative, stem + 'ᾱς',
Case.Genitive, stem + 'ων',
Case.Dative, stem + 'αις'
)
def decline_first_decl_female_dual(stem: str, case: Case):
return pampy.match(
case,
Case.Nominative, stem + 'ᾱ',
Case.Accusative, stem + 'ᾱ',
Case.Genitive, stem + 'αιν',
Case.Dative, stem + 'αιν'
)
all_cases = list(set(Case))
all_non_nominative_cases = list(set(all_cases) - set([Case.Nominative]))
all_genders = list(set(Gender))
all_declensions = list(set(Declension))
all_numbers = list(set(Number))
class Noun:
def __init__(self, stem: str, genitiveEnding: str, declension: Declension, gender: Gender):
self.stem = stem
self.genitiveEnding = genitiveEnding
self.declension = declension
self.gender = gender
def decline(self, number: Number, case: Case) -> str:
return decline_noun(self.stem, self.genitiveEnding, self.declension, self.gender, number, case)
def create_initial_form(self) -> str:
return self.decline(Number.Single, Case.Nominative)
def create_random_form(self) -> (str, Number, Case):
random_number = random.choice(all_numbers)
random_case = random.choice(all_non_nominative_cases)
declined_word = self.decline(random_number, random_case)
return (declined_word, random_number, random_case)
class Answer:
def __init__(self, value: str, isValid: bool) -> None:
self.value = value
self.isValid = isValid
class Question:
def __init__(self, question: str, answers: list) -> None:
self.question = question
self.answers = answers
def strNum(number: Number) -> str:
return pampy.match(number,
Number.Plural, 'множественном числе',
Number.Dual, 'двойственном числе',
Number.Single, 'единственном числе',
)
def strCase(c: Case) -> str:
return pampy.match(c,
Case.Nominative, 'номинативе',
Case.Accusative, 'аккузативе',
Case.Genitive, 'генитиве',
Case.Dative, 'дативе',
)
def create_question(word: Noun) -> Question:
(correct_form, number, case) = word.create_random_form()
forms = [correct_form]
while len(forms) < 4:
(new_answer, _, _) = word.create_random_form()
if new_answer not in forms:
forms.append(new_answer)
random.shuffle(forms)
answers = list(map(lambda x: Answer(x, x == correct_form), forms))
return Question(
question = f'{word.create_initial_form().capitalize()} в {strNum(number)} {strCase(case)}?',
answers = answers
)
|
py | 1a4566a38366309cae1200a417f1a10aff2dbdbb | from __future__ import print_function
import time
class Looper(object):
"""Represents the state of a loop of events."""
RECORD, PAUSE, PLAY = 'record', 'pause', 'play'
def __init__(self, state=PAUSE, events=None, loop_length=0):
self.state = state
if state == Looper.RECORD:
self.state = Looper.PAUSE
self.events = events or []
self.loop_length = loop_length
self.loop_start = 0
self.loop_index = 0
def event(self, key):
if self.state == Looper.RECORD:
self.events.append((time.time() - self.loop_start, key))
def clear(self):
self.state = Looper.PAUSE
self.events = []
def set_state(self, state):
if state != self.state:
t = time.time()
if self.state == Looper.RECORD:
self.loop_length = t - self.loop_start
self.loop_start = 0
self.loop_index = 0
elif self.state == Looper.PLAY:
self.loop_start = t - self.loop_start
self.state = state
if self.state == Looper.PLAY:
self.loop_start = t - self.loop_start
if self.state == Looper.RECORD:
self.events = []
self.loop_start = t
print('Entering state', self.state)
def record(self):
"""Toggle record."""
self.set_state(Looper.PLAY if self.state == Looper.RECORD
else Looper.RECORD)
def play(self):
self.set_state(Looper.PLAY if self.state == Looper.PAUSE
else Looper.PAUSE)
def step(self, callback):
def emit(dt):
while self.loop_index < len(self.events):
etime, key = self.events[self.loop_index]
if etime > dt:
break
callback(key)
self.loop_index += 1
if self.state == Looper.PLAY:
t = time.time()
dt = t - self.loop_start
emit(min(dt, self.loop_length))
if dt >= self.loop_length:
self.loop_index = 0
dt -= self.loop_length
self.loop_start = t - dt
emit(dt)
|
py | 1a4566aa9c3cee714a304c3bdb5740d92404cb71 | from . import BaseAction
from ..db.controllers import ServerController
class SetAdminRoleAction(BaseAction):
action_name = "imdb_tv_shows"
admin = True
controller = ServerController()
async def action(self, msg):
toggle_value = self.get_message_data(msg)
if not toggle_value:
await msg.channel.send(
"Must give value of on or off for imdb_tv_shows command"
)
return
toggle_value = toggle_value.lower()
if toggle_value == "on":
allow_tv_shows = True
elif toggle_value == "off":
allow_tv_shows = False
else:
await msg.channel.send(
f"Unknown value given. Value must be on or off, got {toggle_value}."
)
return
with self.controller.transaction():
server_row = self.controller.get_by_id(msg.guild.id)
server_row.allow_tv_shows = allow_tv_shows
self.controller.update(server_row)
await msg.channel.send(f"Allow IMDB tv show search turned {toggle_value}")
@property
def help_text(self):
return "Toggles whether to allow tv shows in the IMDB search results (on) or not (off)."
@property
def help_options(self):
return ["(on|off)"]
|
py | 1a4567bd656631e971b0bfb1af1626de97d1f572 | #!/usr/bin/env python
import unittest
import socket
from framework import VppTestCase, VppTestRunner
from vpp_ip_route import VppIpRoute, VppRoutePath, VppMplsRoute, \
VppMplsTable, VppIpMRoute, VppMRoutePath, VppIpTable, \
MRouteEntryFlags, MRouteItfFlags, MPLS_LABEL_INVALID, DpoProto
from vpp_bier import *
from scapy.packet import Raw
from scapy.layers.l2 import Ether
from scapy.layers.inet import IP, UDP, ICMP
from scapy.layers.inet6 import IPv6
from scapy.contrib.mpls import MPLS
from scapy.contrib.bier import *
class TestBFIB(VppTestCase):
""" BIER FIB Test Case """
def test_bfib(self):
""" BFIB Unit Tests """
error = self.vapi.cli("test bier")
if error:
self.logger.critical(error)
self.assertEqual(error.find("Failed"), -1)
class TestBier(VppTestCase):
""" BIER Test Case """
def setUp(self):
super(TestBier, self).setUp()
# create 2 pg interfaces
self.create_pg_interfaces(range(3))
# create the default MPLS table
self.tables = []
tbl = VppMplsTable(self, 0)
tbl.add_vpp_config()
self.tables.append(tbl)
tbl = VppIpTable(self, 10)
tbl.add_vpp_config()
self.tables.append(tbl)
# setup both interfaces
for i in self.pg_interfaces:
if i == self.pg2:
i.set_table_ip4(10)
i.admin_up()
i.config_ip4()
i.resolve_arp()
i.enable_mpls()
def tearDown(self):
for i in self.pg_interfaces:
i.disable_mpls()
i.unconfig_ip4()
i.set_table_ip4(0)
i.admin_down()
super(TestBier, self).tearDown()
def send_and_assert_no_replies(self, intf, pkts, remark):
intf.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
for i in self.pg_interfaces:
i.assert_nothing_captured(remark=remark)
def send_and_expect(self, input, pkts, output):
self.vapi.cli("trace add bier-mpls-lookup 10")
input.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = output.get_capture(len(pkts))
def test_bier_midpoint(self):
"""BIER midpoint"""
#
# Add a BIER table for sub-domain 0, set 0, and BSL 256
#
bti = VppBierTableID(0, 0, BIERLength.BIER_LEN_256)
bt = VppBierTable(self, bti, 77)
bt.add_vpp_config()
#
# A packet with no bits set gets dropped
#
p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
MPLS(label=77, ttl=255) /
BIER(length=BIERLength.BIER_LEN_256,
BitString=chr(0)*64) /
IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6) /
UDP(sport=1234, dport=1234) /
Raw())
pkts = [p]
self.send_and_assert_no_replies(self.pg0, pkts,
"Empty Bit-String")
#
# Add a BIER route for each bit-position in the table via a different
# next-hop. Testing whether the BIER walk and replicate forwarding
# function works for all bit posisitons.
#
nh_routes = []
bier_routes = []
for i in range(1, 256):
nh = "10.0.%d.%d" % (i / 255, i % 255)
nh_routes.append(VppIpRoute(self, nh, 32,
[VppRoutePath(self.pg1.remote_ip4,
self.pg1.sw_if_index,
labels=[2000+i])]))
nh_routes[-1].add_vpp_config()
bier_routes.append(VppBierRoute(self, bti, i, nh, 100+i))
bier_routes[-1].add_vpp_config()
#
# A packet with all bits set gets spat out to BP:1
#
p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
MPLS(label=77, ttl=255) /
BIER(length=BIERLength.BIER_LEN_256) /
IPv6(src=self.pg0.remote_ip6, dst=self.pg0.remote_ip6) /
UDP(sport=1234, dport=1234) /
Raw())
pkts = [p]
self.pg0.add_stream(pkts)
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = self.pg1.get_capture(255)
for rxp in rx:
#
# The packets are not required to be sent in bit-position order
# when we setup the routes above we used the bit-position to
# construct the out-label. so use that here to determine the BP
#
olabel = rxp[MPLS]
bp = olabel.label - 2000
blabel = olabel[MPLS].payload
self.assertEqual(blabel.label, 100+bp)
bier_hdr = blabel[MPLS].payload
self.assertEqual(bier_hdr.id, 5)
self.assertEqual(bier_hdr.version, 0)
self.assertEqual(bier_hdr.length, BIERLength.BIER_LEN_256)
self.assertEqual(bier_hdr.entropy, 0)
self.assertEqual(bier_hdr.OAM, 0)
self.assertEqual(bier_hdr.RSV, 0)
self.assertEqual(bier_hdr.DSCP, 0)
self.assertEqual(bier_hdr.Proto, 5)
# The bit-string should consist only of the BP given by i.
i = 0
bitstring = ""
bpi = bp - 1
while (i < bpi/8):
bitstring = chr(0) + bitstring
i += 1
bitstring = chr(1 << bpi % 8) + bitstring
while len(bitstring) < 32:
bitstring = chr(0) + bitstring
self.assertEqual(len(bitstring), len(bier_hdr.BitString))
self.assertEqual(bitstring, bier_hdr.BitString)
def test_bier_head(self):
"""BIER head"""
#
# Add a BIER table for sub-domain 0, set 0, and BSL 256
#
bti = VppBierTableID(0, 0, BIERLength.BIER_LEN_256)
bt = VppBierTable(self, bti, 77)
bt.add_vpp_config()
#
# 2 bit positions via two next hops
#
nh1 = "10.0.0.1"
nh2 = "10.0.0.2"
ip_route_1 = VppIpRoute(self, nh1, 32,
[VppRoutePath(self.pg1.remote_ip4,
self.pg1.sw_if_index,
labels=[2001])])
ip_route_2 = VppIpRoute(self, nh2, 32,
[VppRoutePath(self.pg1.remote_ip4,
self.pg1.sw_if_index,
labels=[2002])])
ip_route_1.add_vpp_config()
ip_route_2.add_vpp_config()
bier_route_1 = VppBierRoute(self, bti, 1, nh1, 101)
bier_route_2 = VppBierRoute(self, bti, 2, nh2, 102)
bier_route_1.add_vpp_config()
bier_route_2.add_vpp_config()
#
# An imposition object with both bit-positions set
#
bi = VppBierImp(self, bti, 333, chr(0x3) * 32)
bi.add_vpp_config()
#
# Add a multicast route that will forward into the BIER doamin
#
route_ing_232_1_1_1 = VppIpMRoute(
self,
"0.0.0.0",
"232.1.1.1", 32,
MRouteEntryFlags.MFIB_ENTRY_FLAG_NONE,
paths=[VppMRoutePath(self.pg0.sw_if_index,
MRouteItfFlags.MFIB_ITF_FLAG_ACCEPT),
VppMRoutePath(0xffffffff,
MRouteItfFlags.MFIB_ITF_FLAG_FORWARD,
proto=DpoProto.DPO_PROTO_BIER,
bier_imp=bi.bi_index)])
route_ing_232_1_1_1.add_vpp_config()
#
# inject a packet an IP. We expect it to be BIER encapped,
# replicated.
#
p = (Ether(dst=self.pg0.local_mac,
src=self.pg0.remote_mac) /
IP(src="1.1.1.1", dst="232.1.1.1") /
UDP(sport=1234, dport=1234))
self.pg0.add_stream([p])
self.pg_enable_capture(self.pg_interfaces)
self.pg_start()
rx = self.pg1.get_capture(2)
def test_bier_tail(self):
"""BIER Tail"""
#
# Add a BIER table for sub-domain 0, set 0, and BSL 256
#
bti = VppBierTableID(0, 0, BIERLength.BIER_LEN_256)
bt = VppBierTable(self, bti, 77)
bt.add_vpp_config()
#
# disposition table
#
bdt = VppBierDispTable(self, 8)
bdt.add_vpp_config()
#
# BIER route in table that's for-us
#
bier_route_1 = VppBierRoute(self, bti, 1, "0.0.0.0", 0,
disp_table=8)
bier_route_1.add_vpp_config()
#
# An entry in the disposition table
#
bier_de_1 = VppBierDispEntry(self, bdt.id, 99,
BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4,
"0.0.0.0", 0, rpf_id=8192)
bier_de_1.add_vpp_config()
#
# A multicast route to forward post BIER disposition
#
route_eg_232_1_1_1 = VppIpMRoute(
self,
"0.0.0.0",
"232.1.1.1", 32,
MRouteEntryFlags.MFIB_ENTRY_FLAG_NONE,
paths=[VppMRoutePath(self.pg1.sw_if_index,
MRouteItfFlags.MFIB_ITF_FLAG_FORWARD)])
route_eg_232_1_1_1.add_vpp_config()
route_eg_232_1_1_1.update_rpf_id(8192)
#
# A packet with all bits set gets spat out to BP:1
#
p = (Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac) /
MPLS(label=77, ttl=255) /
BIER(length=BIERLength.BIER_LEN_256, BFRID=99) /
IP(src="1.1.1.1", dst="232.1.1.1") /
UDP(sport=1234, dport=1234) /
Raw())
self.send_and_expect(self.pg0, [p], self.pg1)
def test_bier_e2e(self):
""" BIER end-to-end """
#
# Add a BIER table for sub-domain 0, set 0, and BSL 256
#
bti = VppBierTableID(0, 0, BIERLength.BIER_LEN_256)
bt = VppBierTable(self, bti, 77)
bt.add_vpp_config()
#
# Impostion Sets bit string 101010101....
# sender 333
#
bi = VppBierImp(self, bti, 333, chr(0x5) * 32)
bi.add_vpp_config()
#
# Add a multicast route that will forward into the BIER doamin
#
route_ing_232_1_1_1 = VppIpMRoute(
self,
"0.0.0.0",
"232.1.1.1", 32,
MRouteEntryFlags.MFIB_ENTRY_FLAG_NONE,
paths=[VppMRoutePath(self.pg0.sw_if_index,
MRouteItfFlags.MFIB_ITF_FLAG_ACCEPT),
VppMRoutePath(0xffffffff,
MRouteItfFlags.MFIB_ITF_FLAG_FORWARD,
proto=DpoProto.DPO_PROTO_BIER,
bier_imp=bi.bi_index)])
route_ing_232_1_1_1.add_vpp_config()
#
# disposition table 8
#
bdt = VppBierDispTable(self, 8)
bdt.add_vpp_config()
#
# BIER route in table that's for-us, resolving through
# disp table 8.
#
bier_route_1 = VppBierRoute(self, bti, 1, "0.0.0.0",
MPLS_LABEL_INVALID,
disp_table=8)
bier_route_1.add_vpp_config()
#
# An entry in the disposition table for sender 333
# lookup in VRF 10
#
bier_de_1 = VppBierDispEntry(self, bdt.id, 333,
BIER_HDR_PAYLOAD.BIER_HDR_PROTO_IPV4,
"0.0.0.0", 10, rpf_id=8192)
bier_de_1.add_vpp_config()
#
# Add a multicast route that will forward the traffic
# post-disposition
#
route_eg_232_1_1_1 = VppIpMRoute(
self,
"0.0.0.0",
"232.1.1.1", 32,
MRouteEntryFlags.MFIB_ENTRY_FLAG_NONE,
table_id=10,
paths=[VppMRoutePath(self.pg1.sw_if_index,
MRouteItfFlags.MFIB_ITF_FLAG_FORWARD)])
route_eg_232_1_1_1.add_vpp_config()
route_eg_232_1_1_1.update_rpf_id(8192)
#
# inject a packet in VRF-0. We expect it to be BIER encapped,
# replicated, then hit the disposition and be forwarded
# out of VRF 10, i.e. on pg1
#
p = (Ether(dst=self.pg0.local_mac,
src=self.pg0.remote_mac) /
IP(src="1.1.1.1", dst="232.1.1.1") /
UDP(sport=1234, dport=1234))
self.send_and_expect(self.pg0, p*65, self.pg1)
if __name__ == '__main__':
unittest.main(testRunner=VppTestRunner)
|
py | 1a45690edaa989ea9fe48b434329e7fcc54aec86 | from __future__ import unicode_literals
import arrow
import json
import unittest
import sys
from httmock import HTTMock
from nose.tools import eq_
from misfit import Misfit, MisfitGoal, MisfitSummary
from misfit.exceptions import MisfitException
from .mocks import MisfitHttMock
class TestMisfitAPI(unittest.TestCase):
def setUp(self):
self.misfit = Misfit('FAKE_ID', 'FAKE_SECRET', 'FAKE_TOKEN')
def test_goal(self):
""" Test retrieving a goal by date range """
goal_dict = {
"id": "51a4189acf12e53f81000001",
"date": "2014-10-05",
"points": 500,
"targetPoints": 1000,
"timeZoneOffset": -8
}
end_date = '2014-10-07'
with HTTMock(MisfitHttMock('goal').json_http):
goal_list = self.misfit.goal(start_date=goal_dict['date'],
end_date=end_date)
eq_(len(goal_list), 3)
goal = goal_list[0]
eq_(type(goal), MisfitGoal)
self.assert_misfit_string(goal, goal_dict)
eq_(goal_list[2].date, arrow.get(end_date))
eq_(goal.id, goal_dict['id'])
eq_(goal.date, arrow.get(goal_dict['date']))
eq_(goal.points, goal_dict['points'])
eq_(goal.targetPoints, goal_dict['targetPoints'])
eq_(goal.timeZoneOffset, goal_dict['timeZoneOffset'])
self.assertAlmostEqual(goal.percent_complete(), 50)
# Check that percent_complete is None if targetPoints is 0
goal.targetPoints = 0
assert goal.percent_complete() is None
def test_goal_single(self):
""" Test retrieving a goal by object_id """
goal_dict = {
"id": "51a4189acf12e53f81000001",
"date": "2014-10-05",
"points": 500,
"targetPoints": 1000,
"timeZoneOffset": -8
}
with HTTMock(MisfitHttMock('goal_single').json_http):
goal = self.misfit.goal(object_id=goal_dict['id'])
eq_(type(goal), MisfitGoal)
self.assert_misfit_string(goal, goal_dict)
eq_(goal.id, goal_dict['id'])
eq_(goal.date, arrow.get(goal_dict['date']))
eq_(goal.points, goal_dict['points'])
eq_(goal.targetPoints, goal_dict['targetPoints'])
eq_(goal.timeZoneOffset, goal_dict['timeZoneOffset'])
self.assertAlmostEqual(goal.percent_complete(), 50)
# Check that percent_complete is None if targetPoints is 0
goal.targetPoints = 0
assert goal.percent_complete() is None
def test_goal_object_date_exception(self):
"""
Check that an exception is raised when no date range or object id is
supplied to goal
"""
self.assertRaises(MisfitException, self.misfit.goal)
def test_summary(self):
""" Test retrieving a non-detail summary """
date_range = {'start_date': '2014-12-10', 'end_date': '2014-12-17'}
with HTTMock(MisfitHttMock('summary').json_http):
summary = self.misfit.summary(start_date='2014-12-10',
end_date='2014-12-17')
summ_dict = {
'activityCalories': 1449.2,
'calories': 16310.24,
'distance': 13.5227,
'points': 3550,
'steps': 34030
}
eq_(type(summary), MisfitSummary)
self.assert_misfit_string(summary, summ_dict)
eq_(summary.data, summ_dict)
eq_(summary.activityCalories, summ_dict['activityCalories'])
eq_(summary.calories, summ_dict['calories'])
eq_(summary.distance, summ_dict['distance'])
eq_(summary.points, summ_dict['points'])
eq_(summary.steps, summ_dict['steps'])
def test_summary_detail(self):
summ_dict = {
"date": "2014-10-05",
"points": 394.4,
"steps": 3650,
"calories": 1687.4735,
"activityCalories": 412.3124,
"distance": 1.18
}
end_date = "2014-10-07"
with HTTMock(MisfitHttMock('summary_detail').json_http):
summary_list = self.misfit.summary(
start_date=summ_dict['date'], end_date=end_date, detail=True)
eq_(len(summary_list), 3)
summary = summary_list[0]
eq_(type(summary), MisfitSummary)
self.assert_misfit_string(summary, summ_dict)
eq_(summary_list[2].date, arrow.get(end_date))
eq_(summary.data, summ_dict)
eq_(summary.date, arrow.get(summ_dict['date']))
eq_(summary.points, summ_dict['points'])
eq_(summary.steps, summ_dict['steps'])
eq_(summary.calories, summ_dict['calories'])
eq_(summary.activityCalories, summ_dict['activityCalories'])
eq_(summary.distance, summ_dict['distance'])
def assert_misfit_string(self, obj, data):
"""
The string representing the misfit object should be the classname,
followed by a ":", followed by the json data
"""
parts = ('%s' % obj).split(': ', 1)
eq_(parts[0], '%s' % type(obj))
eq_(json.loads(parts[1]), data)
|
py | 1a45696a691a0930f002b4e4ff582aea8ed54098 | from django.apps import AppConfig
class UsersConfig(AppConfig):
name = 'users'
def ready(self):
import users.signals
|
py | 1a456afbf8f14ece143726d6dd539f3266f563e8 | # Generated by Django 2.1.7 on 2019-04-03 10:41
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='CommentInfo',
fields=[
('_id', models.CharField(max_length=50, primary_key=True, serialize=False, verbose_name='评论的ID')),
('comment_user_id', models.CharField(max_length=50, verbose_name='评论的ID')),
('weibo_url', models.TextField(blank=True, verbose_name='weibo的URL')),
('content', models.TextField(blank=True, verbose_name='评论内容')),
('created_at', models.CharField(blank=True, max_length=30, verbose_name='评论创建时间')),
('crawl_time', models.DateTimeField(default=datetime.datetime.now, verbose_name='添加时间')),
],
options={
'verbose_name': '评论内容',
'verbose_name_plural': '评论内容',
},
),
migrations.CreateModel(
name='RelationshipsInfo',
fields=[
('_id', models.CharField(max_length=50, primary_key=True, serialize=False, verbose_name='用户关系ID')),
('fan_id', models.CharField(max_length=50, verbose_name='关注者的用户ID')),
('followed_id', models.CharField(max_length=50, verbose_name='被关注者的用户ID')),
('crawl_time', models.DateTimeField(default=datetime.datetime.now, verbose_name='添加时间')),
],
options={
'verbose_name': '用户关系',
'verbose_name_plural': '用户关系',
},
),
migrations.CreateModel(
name='Target',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('uid', models.CharField(max_length=20, verbose_name='爬取用户')),
('cookie', models.TextField(verbose_name='设置cookie')),
('add_time', models.DateTimeField(default=datetime.datetime.now, verbose_name='添加时间')),
],
options={
'verbose_name': '爬虫初始',
'verbose_name_plural': '爬虫初始',
},
),
migrations.CreateModel(
name='TweetsInfo',
fields=[
('_id', models.CharField(max_length=50, primary_key=True, serialize=False, verbose_name='微博ID')),
('user_id', models.CharField(max_length=200, verbose_name='用户信息')),
('content', models.TextField(verbose_name='微博内容')),
('created_at', models.DateTimeField(blank=True, verbose_name='发表时间')),
('weibo_url', models.TextField(blank=True, verbose_name='weibo的URL')),
('like_num', models.IntegerField(blank=True, default=0, verbose_name='点赞数')),
('comment_num', models.IntegerField(blank=True, default=0, verbose_name='评论数')),
('repost_num', models.IntegerField(blank=True, default=0, verbose_name='转载数')),
('crawl_time', models.DateTimeField(default=datetime.datetime.now, verbose_name='添加时间')),
],
options={
'verbose_name': '微博信息',
'verbose_name_plural': '微博信息',
},
),
migrations.CreateModel(
name='UserInfo',
fields=[
('_id', models.CharField(max_length=20, primary_key=True, serialize=False, verbose_name='用户id')),
('nick_name', models.CharField(max_length=30, verbose_name='昵称')),
('gender', models.CharField(choices=[('male', '男'), ('female', '女')], default='female', max_length=6, verbose_name='性别')),
('labels', models.CharField(blank=True, max_length=500, verbose_name='标签')),
('province', models.CharField(blank=True, max_length=30, verbose_name='所在省')),
('city', models.CharField(blank=True, max_length=30, verbose_name='所在城市')),
('brief_introduction', models.CharField(blank=True, max_length=500, verbose_name='简介')),
('birthday', models.DateField(blank=True, null=True, verbose_name='生日')),
('constellation', models.CharField(blank=True, max_length=30, verbose_name='星座')),
('tweets_num', models.IntegerField(default=0, verbose_name='微博数')),
('fans_num', models.IntegerField(default=0, verbose_name='关注数')),
('follows_num', models.IntegerField(blank=True, default=0, verbose_name='粉丝数')),
('sex_orientation', models.CharField(blank=True, max_length=30, verbose_name='性取向')),
('sentiment', models.CharField(blank=True, max_length=30, verbose_name='感情状况')),
('vip_level', models.CharField(blank=True, max_length=30, verbose_name='会员等级')),
('authentication', models.CharField(blank=True, max_length=30, verbose_name='认证')),
('person_url', models.CharField(blank=True, max_length=30, verbose_name='首页链接')),
('crawl_time', models.DateTimeField(default=datetime.datetime.now, verbose_name='添加时间')),
],
options={
'verbose_name': '用户信息',
'verbose_name_plural': '用户信息',
},
),
]
|
py | 1a456b0bc2c3ea32797f2da92bca0f716c918e08 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='ContactDetails',
fields=[
('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),
('home_address', models.CharField(max_length=255)),
('home_city', models.CharField(max_length=255)),
('home_state', models.CharField(default='TX', max_length=2)),
('home_zip', models.PositiveIntegerField()),
('postal_address', models.CharField(max_length=255)),
('postal_city', models.CharField(max_length=255)),
('postal_state', models.CharField(default='TX', max_length=2)),
('postal_zip', models.PositiveIntegerField()),
('home_phone', models.CharField(max_length=20)),
('work_phone', models.CharField(max_length=20)),
('mobile_phone', models.CharField(max_length=20)),
('fax', models.CharField(max_length=20)),
('email', models.EmailField(max_length=254)),
('occupation', models.CharField(max_length=255)),
('business_name', models.CharField(max_length=255)),
('business_address', models.CharField(max_length=255)),
('business_city', models.CharField(max_length=255)),
('business_state', models.CharField(default='TX', max_length=2)),
('business_zip', models.PositiveIntegerField()),
('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='OtherDetails',
fields=[
('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),
('previous_member_of_hodi', models.BooleanField()),
('previous_lodges', models.CharField(max_length=255)),
('relatives_member_of_hodi', models.BooleanField()),
('relatives_names_and_mother_lodges', models.TextField()),
('member_of_other_organizations', models.BooleanField()),
('other_organizations', models.TextField()),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='PersonalDetails',
fields=[
('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),
('date_of_birth', models.DateField()),
('city_of_birth', models.CharField(max_length=255)),
('country_of_birth', models.CharField(max_length=255)),
('is_jewish', models.BooleanField()),
('is_married', models.BooleanField()),
('date_of_marriage', models.DateField()),
('wife_name', models.CharField(max_length=255)),
('wife_email', models.EmailField(max_length=254)),
('place_of_marriage', models.CharField(max_length=255)),
('wife_mobile_phone', models.CharField(max_length=20)),
('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
],
options={
},
bases=(models.Model,),
),
]
|
py | 1a456bbe9284ae11b261e8725117957382946b79 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# keplerian documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 9 13:47:02 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
#
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import keplerian
# -- General configuration ---------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'keplerian'
copyright = u"2018, João Faria"
author = u"João Faria"
# The version info for the project you're documenting, acts as replacement
# for |version| and |release|, also used in various other places throughout
# the built documents.
#
# The short X.Y version.
version = keplerian.__version__
# The full version, including alpha/beta/rc tags.
release = keplerian.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output -------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a
# theme further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# -- Options for HTMLHelp output ---------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'kepleriandoc'
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto, manual, or own class]).
latex_documents = [
(master_doc, 'keplerian.tex',
u'keplerian Documentation',
u'João Faria', 'manual'),
]
# -- Options for manual page output ------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'keplerian',
u'keplerian Documentation',
[author], 1)
]
# -- Options for Texinfo output ----------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'keplerian',
u'keplerian Documentation',
author,
'keplerian',
'One line description of project.',
'Miscellaneous'),
]
|
py | 1a456d6288a6aff7fd765cd983e3230eb5241218 | ## This file is part of Scapy
## See http://www.secdev.org/projects/scapy for more informations
## Copyright (C) Philippe Biondi <[email protected]>
## This program is published under a GPLv2 license
"""
Classes that implement ASN.1 data structures.
"""
from asn1.asn1 import *
from asn1.ber import *
from volatile import *
from base_classes import BasePacket
#####################
#### ASN1 Fields ####
#####################
class ASN1F_badsequence(Exception):
pass
class ASN1F_element:
pass
class ASN1F_optionnal(ASN1F_element):
def __init__(self, field):
self._field=field
def __getattr__(self, attr):
return getattr(self._field,attr)
def dissect(self,pkt,s):
try:
return self._field.dissect(pkt,s)
except ASN1F_badsequence:
self._field.set_val(pkt,None)
return s
except BER_Decoding_Error:
self._field.set_val(pkt,None)
return s
def build(self, pkt):
if self._field.is_empty(pkt):
return ""
return self._field.build(pkt)
class ASN1F_field(ASN1F_element):
holds_packets=0
islist=0
ASN1_tag = ASN1_Class_UNIVERSAL.ANY
context=ASN1_Class_UNIVERSAL
def __init__(self, name, default, context=None):
if context is not None:
self.context = context
self.name = name
self.default = default
def i2repr(self, pkt, x):
return repr(x)
def i2h(self, pkt, x):
return x
def any2i(self, pkt, x):
return x
def m2i(self, pkt, x):
return self.ASN1_tag.get_codec(pkt.ASN1_codec).safedec(x, context=self.context)
def i2m(self, pkt, x):
if x is None:
x = 0
if isinstance(x, ASN1_Object):
if ( self.ASN1_tag == ASN1_Class_UNIVERSAL.ANY
or x.tag == ASN1_Class_UNIVERSAL.RAW
or x.tag == ASN1_Class_UNIVERSAL.ERROR
or self.ASN1_tag == x.tag ):
return x.enc(pkt.ASN1_codec)
else:
raise ASN1_Error("Encoding Error: got %r instead of an %r for field [%s]" % (x, self.ASN1_tag, self.name))
return self.ASN1_tag.get_codec(pkt.ASN1_codec).enc(x)
def do_copy(self, x):
if hasattr(x, "copy"):
return x.copy()
if type(x) is list:
x = x[:]
for i in xrange(len(x)):
if isinstance(x[i], BasePacket):
x[i] = x[i].copy()
return x
def build(self, pkt):
return self.i2m(pkt, getattr(pkt, self.name))
def set_val(self, pkt, val):
setattr(pkt, self.name, val)
def is_empty(self, pkt):
return getattr(pkt,self.name) is None
def dissect(self, pkt, s):
v,s = self.m2i(pkt, s)
self.set_val(pkt, v)
return s
def get_fields_list(self):
return [self]
def __hash__(self):
return hash(self.name)
def __str__(self):
return self.name
def __eq__(self, other):
return self.name == other
def __repr__(self):
return self.name
def randval(self):
return RandInt()
class ASN1F_INTEGER(ASN1F_field):
ASN1_tag= ASN1_Class_UNIVERSAL.INTEGER
def randval(self):
return RandNum(-2**64, 2**64-1)
class ASN1F_BOOLEAN(ASN1F_field):
ASN1_tag= ASN1_Class_UNIVERSAL.BOOLEAN
def randval(self):
return RandChoice(True,False)
class ASN1F_NULL(ASN1F_INTEGER):
ASN1_tag= ASN1_Class_UNIVERSAL.NULL
class ASN1F_SEP(ASN1F_NULL):
ASN1_tag= ASN1_Class_UNIVERSAL.SEP
class ASN1F_enum_INTEGER(ASN1F_INTEGER):
def __init__(self, name, default, enum):
ASN1F_INTEGER.__init__(self, name, default)
i2s = self.i2s = {}
s2i = self.s2i = {}
if type(enum) is list:
keys = xrange(len(enum))
else:
keys = enum.keys()
if filter(lambda x: type(x) is str, keys):
i2s,s2i = s2i,i2s
for k in keys:
i2s[k] = enum[k]
s2i[enum[k]] = k
def any2i_one(self, pkt, x):
if type(x) is str:
x = self.s2i[x]
return x
def i2repr_one(self, pkt, x):
return self.i2s.get(x, repr(x))
def any2i(self, pkt, x):
if type(x) is list:
return map(lambda z,pkt=pkt:self.any2i_one(pkt,z), x)
else:
return self.any2i_one(pkt,x)
def i2repr(self, pkt, x):
if type(x) is list:
return map(lambda z,pkt=pkt:self.i2repr_one(pkt,z), x)
else:
return self.i2repr_one(pkt,x)
class ASN1F_ENUMERATED(ASN1F_enum_INTEGER):
ASN1_tag = ASN1_Class_UNIVERSAL.ENUMERATED
class ASN1F_STRING(ASN1F_field):
ASN1_tag = ASN1_Class_UNIVERSAL.STRING
def randval(self):
return RandString(RandNum(0, 1000))
class ASN1F_PRINTABLE_STRING(ASN1F_STRING):
ASN1_tag = ASN1_Class_UNIVERSAL.PRINTABLE_STRING
class ASN1F_BIT_STRING(ASN1F_STRING):
ASN1_tag = ASN1_Class_UNIVERSAL.BIT_STRING
class ASN1F_IPADDRESS(ASN1F_STRING):
ASN1_tag = ASN1_Class_UNIVERSAL.IPADDRESS
class ASN1F_TIME_TICKS(ASN1F_INTEGER):
ASN1_tag = ASN1_Class_UNIVERSAL.TIME_TICKS
class ASN1F_UTC_TIME(ASN1F_STRING):
ASN1_tag = ASN1_Class_UNIVERSAL.UTC_TIME
class ASN1F_GENERALIZED_TIME(ASN1F_STRING):
ASN1_tag = ASN1_Class_UNIVERSAL.GENERALIZED_TIME
class ASN1F_OID(ASN1F_field):
ASN1_tag = ASN1_Class_UNIVERSAL.OID
def randval(self):
return RandOID()
class ASN1F_SEQUENCE(ASN1F_field):
ASN1_tag = ASN1_Class_UNIVERSAL.SEQUENCE
def __init__(self, *seq, **kargs):
if "ASN1_tag" in kargs:
self.ASN1_tag = kargs["ASN1_tag"]
self.seq = seq
def __repr__(self):
return "<%s%r>" % (self.__class__.__name__,self.seq,)
def set_val(self, pkt, val):
for f in self.seq:
f.set_val(pkt,val)
def is_empty(self, pkt):
for f in self.seq:
if not f.is_empty(pkt):
return False
return True
def get_fields_list(self):
return reduce(lambda x,y: x+y.get_fields_list(), self.seq, [])
def build(self, pkt):
s = reduce(lambda x,y: x+y.build(pkt), self.seq, "")
return self.i2m(pkt, s)
def dissect(self, pkt, s):
codec = self.ASN1_tag.get_codec(pkt.ASN1_codec)
try:
i,s,remain = codec.check_type_check_len(s)
for obj in self.seq:
s = obj.dissect(pkt,s)
if s:
warning("Too many bytes to decode sequence: [%r]" % s) # XXX not reversible!
return remain
except ASN1_Error,e:
raise ASN1F_badsequence(e)
class ASN1F_SET(ASN1F_SEQUENCE):
ASN1_tag = ASN1_Class_UNIVERSAL.SET
class ASN1F_SEQUENCE_OF(ASN1F_SEQUENCE):
holds_packets = 1
islist = 1
def __init__(self, name, default, asn1pkt, ASN1_tag=0x30):
self.asn1pkt = asn1pkt
self.tag = chr(ASN1_tag)
self.name = name
self.default = default
def i2repr(self, pkt, i):
if i is None:
return []
return i
def get_fields_list(self):
return [self]
def set_val(self, pkt, val):
ASN1F_field.set_val(self, pkt, val)
def is_empty(self, pkt):
return ASN1F_field.is_empty(self, pkt)
def build(self, pkt):
val = getattr(pkt, self.name)
if isinstance(val, ASN1_Object) and val.tag == ASN1_Class_UNIVERSAL.RAW:
s = val
elif val is None:
s = ""
else:
s = "".join(map(str, val ))
return self.i2m(pkt, s)
def dissect(self, pkt, s):
codec = self.ASN1_tag.get_codec(pkt.ASN1_codec)
i,s1,remain = codec.check_type_check_len(s)
lst = []
while s1:
try:
p = self.asn1pkt(s1)
except ASN1F_badsequence,e:
lst.append(packet.Raw(s1))
break
lst.append(p)
if packet.Raw in p:
s1 = p[packet.Raw].load
del(p[packet.Raw].underlayer.payload)
else:
break
self.set_val(pkt, lst)
return remain
def randval(self):
return fuzz(self.asn1pkt())
def __repr__(self):
return "<%s %s>" % (self.__class__.__name__,self.name)
class ASN1F_PACKET(ASN1F_field):
holds_packets = 1
def __init__(self, name, default, cls):
ASN1F_field.__init__(self, name, default)
self.cls = cls
def i2m(self, pkt, x):
if x is None:
x = ""
return str(x)
def extract_packet(self, cls, x):
try:
c = cls(x)
except ASN1F_badsequence:
c = packet.Raw(x)
cpad = c.getlayer(packet.Padding)
x = ""
if cpad is not None:
x = cpad.load
del(cpad.underlayer.payload)
return c,x
def m2i(self, pkt, x):
return self.extract_packet(self.cls, x)
class ASN1F_CHOICE(ASN1F_PACKET):
ASN1_tag = ASN1_Class_UNIVERSAL.NONE
def __init__(self, name, default, *args):
self.name=name
self.choice = {}
for p in args:
self.choice[p.ASN1_root.ASN1_tag] = p
# self.context=context
self.default=default
def m2i(self, pkt, x):
if len(x) == 0:
return packet.Raw(),""
raise ASN1_Error("ASN1F_CHOICE: got empty string")
if ord(x[0]) not in self.choice:
return packet.Raw(x),"" # XXX return RawASN1 packet ? Raise error
raise ASN1_Error("Decoding Error: choice [%i] not found in %r" % (ord(x[0]), self.choice.keys()))
z = ASN1F_PACKET.extract_packet(self, self.choice[ord(x[0])], x)
return z
def randval(self):
return RandChoice(*map(lambda x:fuzz(x()), self.choice.values()))
# This import must come in last to avoid problems with cyclic dependencies
import packet
|
py | 1a456ee583b34858307cc710ed4fb141ea349b07 | __doc__ = """
Independent Implementation of HCBS' Synaptic Partner Candidate Generation
See: https://github.com/paragt/EMSynConn/blob/master/vertebrate/candidate/generate_proposals.py
"""
import numpy as np
from scipy import spatial
from scipy.ndimage import distance_transform_edt
from ... import seg_utils
from .. import seg
def extract_prox_candidates(prox, seg, presyn_thresh=0.3, postsyn_thresh=-0.3,
term_sz_thresh=0, seg_sz_thresh=0,
centroid_dist_thr=200, sep_thr=50,
voxel_res=[40, 4, 4],
remove_self=False):
"""
Extract candidate synaptic pairs (and their locations) from
partner-signed proximity output
"""
presyn_terms, postsyn_terms = seg.find_prox_terminals(prox, seg,
presyn_thresh,
postsyn_thresh,
term_sz_thresh)
return extract_terminal_candidates(presyn_terms, postsyn_terms, seg,
term_sz_thresh, seg_sz_thresh,
centroid_dist_thr, sep_thr,
voxel_res=voxel_res,
remove_self=remove_self)
def extract_terminal_candidates(presyn_terms, postsyn_terms, seg,
seg_sz_thresh=0, centroid_dist_thresh=200,
sep_thresh=50, voxel_res=[40, 4, 4],
remove_self=False):
"""
Extract candidate synaptic pairs (and their locations) from segmented
terminals
"""
# Filter terminals by the segments with which they overlap
# (can't be too small)
presyn_terms, presyn_segs = filter_terminals(presyn_terms,
seg, seg_sz_thresh)
postsyn_terms, postsyn_segs = filter_terminals(postsyn_terms,
seg, seg_sz_thresh)
# Compute some useful stuff for later
presyn_centroids = seg_utils.centers_of_mass(presyn_terms)
postsyn_centroids = seg_utils.centers_of_mass(postsyn_terms)
# Consider the initial set within some distance
initial_pairs = pairs_within_dist(presyn_centroids, postsyn_centroids,
centroid_dist_thresh,
voxel_res=voxel_res)
# Filter set by their separation
candidates, locs = filter_by_separation(initial_pairs, sep_thresh,
presyn_terms, postsyn_terms,
voxel_res=voxel_res)
seg_pairs = list((presyn_segs[i], postsyn_segs[j])
for (i, j) in candidates)
if remove_self:
non_self_loops = [i for i in range(len(seg_pairs))
if seg_pairs[i][0] != seg_pairs[i][1]]
seg_pairs = [seg_pairs[i] for i in non_self_loops]
locs = [locs[i] for i in non_self_loops]
candidates = [candidates[i] for i in non_self_loops]
return seg_pairs, locs, candidates
def filter_terminals(terminals, seg, seg_sz_thresh):
"""
Remove terminal segments which overlap with segments with size
under a threshold
"""
seg_szs = seg_utils.segment_sizes(seg)
term_nonz = terminals[terminals != 0]
seg_nonz = seg[terminals != 0]
term_to_seg = dict(zip(term_nonz, seg_nonz))
terms_to_remove = [k for (k, v) in term_to_seg.items()
if v == 0 or seg_szs[v] < seg_sz_thresh]
term_to_seg = dict(filter(lambda p: p[0] not in terms_to_remove,
term_to_seg.items()))
terminals = seg_utils.filter_segs_by_id(terminals,
terms_to_remove, copy=False)
return terminals, term_to_seg
def pairs_within_dist(centroids1, centroids2, dist_thr, voxel_res=[40, 4, 4]):
"""
Return the keys within two centroid dictionaries which are within
a threshold distance of one another
"""
ids1 = list(centroids1.keys())
ids2 = list(centroids2.keys())
empty = np.zeros((0, 3), dtype=np.float32)
if len(centroids1) > 0:
cents1 = np.array([centroids1[i] for i in ids1]) * voxel_res
else:
cents1 = empty
if len(centroids2) > 0:
cents2 = np.array([centroids2[i] for i in ids2]) * voxel_res
else:
cents2 = empty
pairs = np.nonzero(spatial.distance.cdist(cents1, cents2) < dist_thr)
# converting to original ids
pairs = list((ids1[i], ids2[j]) for (i, j) in zip(*pairs))
return pairs
def filter_by_separation(candidates, sep_thr,
presyn_terms, postsyn_terms,
voxel_res=[40, 4, 4]):
"""
Filter candidate synaptic partners by the separation distance between
the relevant terminal segments
"""
presyn_bboxes = seg_utils.bounding_boxes(presyn_terms)
postsyn_bboxes = seg_utils.bounding_boxes(postsyn_terms)
filtered = list()
locs = list()
for (pre, post) in candidates:
bbox = presyn_bboxes[pre].merge(postsyn_bboxes[post])
pre_view = presyn_terms[bbox.index()]
post_view = postsyn_terms[bbox.index()]
edt = distance_transform_edt(post_view != post, sampling=voxel_res)
edt[pre_view != pre] = np.inf
if np.any(edt[pre_view == pre] < sep_thr):
filtered.append((pre, post))
# Find closest pt between terminals
local_loc = np.unravel_index(np.argmin(edt), edt.shape)
locs.append(tuple(local_loc + bbox.min()))
return filtered, locs
|
py | 1a456fc6dd8c4f73ad51f19c9b3d277110f26003 | """Errors and exceptions"""
class NotEncryptedError(Exception):
"""Raised when unencrypted data is used that should have been encrypted."""
pass
class NotSerializedError(Exception):
"""Raised when a message is not serialized."""
pass
class NotSignedError(Exception):
"""Raised when a message is not signed."""
pass
|
py | 1a457120eb9276a4b6eb8e09bb2e7ae960e25c26 | import time, traceback, json
import rethinkdb as r
TIX = 'tix' # DB
VENU = 'venu' # TABLE
ID = 'id' # COLUMN
TS = 'ts' # COLUMN
SMAP = 'smap' # COLUMN
UMAP = 'umap' # COLUMN
MAX = 'max' # COLUMN
CNT = 20 # number of seats
def init(conn, event):
# try to drop table (may or may not exist)
rv = ''
try:
r.db_drop(TIX).run(conn)
rv = 'dropped, then created'
except:
rv = 'created'
r.db_create(TIX).run(conn)
r.db(TIX).table_create(VENU).run(conn)
r.db(TIX).table(VENU).index_create(TS).run(conn)
smap = {}
umap = {}
for x in range(1, CNT + 1):
smap[str(x)] = 'free'
umap[str(x)] = ''
rv += str(r.db(TIX).table(VENU).insert({
ID: 0,
SMAP: smap,
UMAP: umap,
MAX: CNT,
TS: time.time()
}).run(conn))
return rv
def hold(conn, event):
snum = str(event.get('snum'))
unum = str(event.get('unum'))
smap = {}
umap = {}
smap = r.db(TIX).table(VENU).get(0).get_field(SMAP).run(conn)
umap = r.db(TIX).table(VENU).get(0).get_field(UMAP).run(conn)
smap[snum] = 'held'
umap[snum] = unum
result = r.db(TIX).table(VENU).get(0).update(lambda VENU:
r.branch(
VENU[SMAP][snum] == 'free',
{SMAP: smap, UMAP: umap, TS: time.time()},
{}
)
).run(conn)
if result:
return result
def book(conn, event):
unum = str(event.get('unum'))
smap = {}
umap = {}
smap = r.db(TIX).table(VENU).get(0).get_field(SMAP).run(conn)
umap = r.db(TIX).table(VENU).get(0).get_field(UMAP).run(conn)
for x in range (1, CNT + 1):
if smap[str(x)] == 'held' and umap[str(x)] == unum:
smap[str(x)] = 'booked'
result = r.db(TIX).table(VENU).get(0).update({
SMAP: smap,
TS: time.time()
}).run(conn)
if result:
return result
def updates(conn, event):
ts = event.get('ts', 0)
for row in (r.db(TIX).table(VENU).filter(r.row[TS] > ts).
changes(include_initial=True).run(conn)):
return row['new_val']
def handler(conn, event):
fn = {'init': init,
'hold': hold,
'book': book,
'updates': updates}.get(event['op'], None)
if fn != None:
try:
result = fn(conn, event)
return {'result': result}
except Exception:
return {'error': traceback.format_exc()}
else:
return {'error': 'bad op'}
|
py | 1a4571dc71fb9f8fe19d28839297ec212e122f79 | from functools import partial
class Dialog(object):
def __init__(self, path='', name='', transformConnection=''):
pass
def add(self):
"""
Add the transform to the catalog.
"""
pass
def build(self):
pass
def onDismissButton(self, data, msg):
pass
def onPathBrowse(self, data):
pass
def remove(self):
"""
Remove the transform from the catalog.
"""
pass
def show(self):
pass
__dict__ = None
__weakref__ = None
class OutputTransformDialog(Dialog):
def __init__(self, path='', name='', transformConnection=''):
pass
def apply(self):
pass
def direction(self):
pass
def title(self):
pass
def type(self):
pass
class InputTransformDialog(Dialog):
def __init__(self, path='', name='', transformConnection=''):
pass
def apply(self):
pass
def direction(self):
pass
def title(self):
pass
def type(self):
pass
class PlayblastOutputTransformDialog(Dialog):
def __init__(self, path='', name='', transformConnection=''):
pass
def apply(self):
pass
def direction(self):
pass
def title(self):
pass
def type(self):
pass
class ViewTransformDialog(Dialog):
def __init__(self, path='', name='', transformConnection=''):
pass
def apply(self):
pass
def direction(self):
pass
def title(self):
pass
def type(self):
pass
class RenderingSpaceDialog(Dialog):
def __init__(self, path='', name='', transformConnection=''):
pass
def apply(self):
pass
def direction(self):
pass
def title(self):
pass
def type(self):
pass
def dialogFactory(type):
pass
def addCustomTransformDialog(type):
"""
Add and return a user transform.
Return transform name, or empty string in case of error or cancel.
"""
pass
|
py | 1a45728560cde90ed68e8dd9c5a0c6386d25a4b0 | # Copyright 2002 Gary Strangman. All rights reserved
# Copyright 2002-2016 The SciPy Developers
#
# The original code from Gary Strangman was heavily adapted for
# use in SciPy by Travis Oliphant. The original code came with the
# following disclaimer:
#
# This software is provided "as-is". There are no expressed or implied
# warranties of any kind, including, but not limited to, the warranties
# of merchantability and fitness for a given application. In no event
# shall Gary Strangman be liable for any direct, indirect, incidental,
# special, exemplary or consequential damages (including, but not limited
# to, loss of use, data or profits, or business interruption) however
# caused and on any theory of liability, whether in contract, strict
# liability or tort (including negligence or otherwise) arising in any way
# out of the use of this software, even if advised of the possibility of
# such damage.
"""
A collection of basic statistical functions for Python. The function
names appear below.
Some scalar functions defined here are also available in the scipy.special
package where they work on arbitrary sized arrays.
Disclaimers: The function list is obviously incomplete and, worse, the
functions are not optimized. All functions have been tested (some more
so than others), but they are far from bulletproof. Thus, as with any
free software, no warranty or guarantee is expressed or implied. :-) A
few extra functions that don't appear in the list below can be found by
interested treasure-hunters. These functions don't necessarily have
both list and array versions but were deemed useful.
Central Tendency
----------------
.. autosummary::
:toctree: generated/
gmean
hmean
mode
Moments
-------
.. autosummary::
:toctree: generated/
moment
variation
skew
kurtosis
normaltest
Altered Versions
----------------
.. autosummary::
:toctree: generated/
tmean
tvar
tstd
tsem
describe
Frequency Stats
---------------
.. autosummary::
:toctree: generated/
itemfreq
scoreatpercentile
percentileofscore
cumfreq
relfreq
Variability
-----------
.. autosummary::
:toctree: generated/
obrientransform
sem
zmap
zscore
gstd
iqr
median_abs_deviation
Trimming Functions
------------------
.. autosummary::
:toctree: generated/
trimboth
trim1
Correlation Functions
---------------------
.. autosummary::
:toctree: generated/
pearsonr
fisher_exact
spearmanr
pointbiserialr
kendalltau
weightedtau
linregress
theilslopes
multiscale_graphcorr
Inferential Stats
-----------------
.. autosummary::
:toctree: generated/
ttest_1samp
ttest_ind
ttest_ind_from_stats
ttest_rel
chisquare
power_divergence
kstest
ks_1samp
ks_2samp
epps_singleton_2samp
mannwhitneyu
ranksums
wilcoxon
kruskal
friedmanchisquare
brunnermunzel
combine_pvalues
Statistical Distances
---------------------
.. autosummary::
:toctree: generated/
wasserstein_distance
energy_distance
ANOVA Functions
---------------
.. autosummary::
:toctree: generated/
f_oneway
Support Functions
-----------------
.. autosummary::
:toctree: generated/
rankdata
rvs_ratio_uniforms
References
----------
.. [CRCProbStat2000] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
Probability and Statistics Tables and Formulae. Chapman & Hall: New
York. 2000.
"""
import warnings
import math
from math import gcd
from collections import namedtuple
from itertools import permutations
import numpy as np
from numpy import array, asarray, ma
from scipy.spatial.distance import cdist
from scipy.ndimage import measurements
from scipy._lib._util import (_lazywhere, check_random_state, MapWrapper,
rng_integers, float_factorial)
import scipy.special as special
from scipy import linalg
from . import distributions
from . import mstats_basic
from ._stats_mstats_common import (_find_repeats, linregress, theilslopes,
siegelslopes)
from ._stats import (_kendall_dis, _toint64, _weightedrankedtau,
_local_correlations)
from ._rvs_sampling import rvs_ratio_uniforms
from ._hypotests import epps_singleton_2samp, cramervonmises
__all__ = ['find_repeats', 'gmean', 'hmean', 'mode', 'tmean', 'tvar',
'tmin', 'tmax', 'tstd', 'tsem', 'moment', 'variation',
'skew', 'kurtosis', 'describe', 'skewtest', 'kurtosistest',
'normaltest', 'jarque_bera', 'itemfreq',
'scoreatpercentile', 'percentileofscore',
'cumfreq', 'relfreq', 'obrientransform',
'sem', 'zmap', 'zscore', 'iqr', 'gstd', 'median_absolute_deviation',
'median_abs_deviation',
'sigmaclip', 'trimboth', 'trim1', 'trim_mean',
'f_oneway', 'F_onewayConstantInputWarning',
'F_onewayBadInputSizesWarning',
'PearsonRConstantInputWarning', 'PearsonRNearConstantInputWarning',
'pearsonr', 'fisher_exact', 'SpearmanRConstantInputWarning',
'spearmanr', 'pointbiserialr',
'kendalltau', 'weightedtau', 'multiscale_graphcorr',
'linregress', 'siegelslopes', 'theilslopes', 'ttest_1samp',
'ttest_ind', 'ttest_ind_from_stats', 'ttest_rel',
'kstest', 'ks_1samp', 'ks_2samp',
'chisquare', 'power_divergence', 'mannwhitneyu',
'tiecorrect', 'ranksums', 'kruskal', 'friedmanchisquare',
'rankdata', 'rvs_ratio_uniforms',
'combine_pvalues', 'wasserstein_distance', 'energy_distance',
'brunnermunzel', 'epps_singleton_2samp', 'cramervonmises']
def _contains_nan(a, nan_policy='propagate'):
policies = ['propagate', 'raise', 'omit']
if nan_policy not in policies:
raise ValueError("nan_policy must be one of {%s}" %
', '.join("'%s'" % s for s in policies))
try:
# Calling np.sum to avoid creating a huge array into memory
# e.g. np.isnan(a).any()
with np.errstate(invalid='ignore'):
contains_nan = np.isnan(np.sum(a))
except TypeError:
# This can happen when attempting to sum things which are not
# numbers (e.g. as in the function `mode`). Try an alternative method:
try:
contains_nan = np.nan in set(a.ravel())
except TypeError:
# Don't know what to do. Fall back to omitting nan values and
# issue a warning.
contains_nan = False
nan_policy = 'omit'
warnings.warn("The input array could not be properly checked for nan "
"values. nan values will be ignored.", RuntimeWarning)
if contains_nan and nan_policy == 'raise':
raise ValueError("The input contains nan values")
return contains_nan, nan_policy
def _chk_asarray(a, axis):
if axis is None:
a = np.ravel(a)
outaxis = 0
else:
a = np.asarray(a)
outaxis = axis
if a.ndim == 0:
a = np.atleast_1d(a)
return a, outaxis
def _chk2_asarray(a, b, axis):
if axis is None:
a = np.ravel(a)
b = np.ravel(b)
outaxis = 0
else:
a = np.asarray(a)
b = np.asarray(b)
outaxis = axis
if a.ndim == 0:
a = np.atleast_1d(a)
if b.ndim == 0:
b = np.atleast_1d(b)
return a, b, outaxis
def _shape_with_dropped_axis(a, axis):
"""
Given an array `a` and an integer `axis`, return the shape
of `a` with the `axis` dimension removed.
Examples
--------
>>> a = np.zeros((3, 5, 2))
>>> _shape_with_dropped_axis(a, 1)
(3, 2)
"""
shp = list(a.shape)
try:
del shp[axis]
except IndexError:
raise np.AxisError(axis, a.ndim) from None
return tuple(shp)
def _broadcast_shapes(shape1, shape2):
"""
Given two shapes (i.e. tuples of integers), return the shape
that would result from broadcasting two arrays with the given
shapes.
Examples
--------
>>> _broadcast_shapes((2, 1), (4, 1, 3))
(4, 2, 3)
"""
d = len(shape1) - len(shape2)
if d <= 0:
shp1 = (1,)*(-d) + shape1
shp2 = shape2
elif d > 0:
shp1 = shape1
shp2 = (1,)*d + shape2
shape = []
for n1, n2 in zip(shp1, shp2):
if n1 == 1:
n = n2
elif n2 == 1 or n1 == n2:
n = n1
else:
raise ValueError(f'shapes {shape1} and {shape2} could not be '
'broadcast together')
shape.append(n)
return tuple(shape)
def _broadcast_shapes_with_dropped_axis(a, b, axis):
"""
Given two arrays `a` and `b` and an integer `axis`, find the
shape of the broadcast result after dropping `axis` from the
shapes of `a` and `b`.
Examples
--------
>>> a = np.zeros((5, 2, 1))
>>> b = np.zeros((1, 9, 3))
>>> _broadcast_shapes_with_dropped_axis(a, b, 1)
(5, 3)
"""
shp1 = _shape_with_dropped_axis(a, axis)
shp2 = _shape_with_dropped_axis(b, axis)
try:
shp = _broadcast_shapes(shp1, shp2)
except ValueError:
raise ValueError(f'non-axis shapes {shp1} and {shp2} could not be '
'broadcast together') from None
return shp
def gmean(a, axis=0, dtype=None, weights=None):
"""
Compute the geometric mean along the specified axis.
Return the geometric average of the array elements.
That is: n-th root of (x1 * x2 * ... * xn)
Parameters
----------
a : array_like
Input array or object that can be converted to an array.
axis : int or None, optional
Axis along which the geometric mean is computed. Default is 0.
If None, compute over the whole array `a`.
dtype : dtype, optional
Type of the returned array and of the accumulator in which the
elements are summed. If dtype is not specified, it defaults to the
dtype of a, unless a has an integer dtype with a precision less than
that of the default platform integer. In that case, the default
platform integer is used.
weights : array_like, optional
The weights array can either be 1-D (in which case its length must be
the size of `a` along the given `axis`) or of the same shape as `a`.
Default is None, which gives each value a weight of 1.0.
Returns
-------
gmean : ndarray
See `dtype` parameter above.
See Also
--------
numpy.mean : Arithmetic average
numpy.average : Weighted average
hmean : Harmonic mean
Notes
-----
The geometric average is computed over a single dimension of the input
array, axis=0 by default, or all values in the array if axis=None.
float64 intermediate and return values are used for integer inputs.
Use masked arrays to ignore any non-finite values in the input or that
arise in the calculations such as Not a Number and infinity because masked
arrays automatically mask any non-finite values.
References
----------
.. [1] "Weighted Geometric Mean", *Wikipedia*, https://en.wikipedia.org/wiki/Weighted_geometric_mean.
Examples
--------
>>> from scipy.stats import gmean
>>> gmean([1, 4])
2.0
>>> gmean([1, 2, 3, 4, 5, 6, 7])
3.3800151591412964
"""
if not isinstance(a, np.ndarray):
# if not an ndarray object attempt to convert it
log_a = np.log(np.array(a, dtype=dtype))
elif dtype:
# Must change the default dtype allowing array type
if isinstance(a, np.ma.MaskedArray):
log_a = np.log(np.ma.asarray(a, dtype=dtype))
else:
log_a = np.log(np.asarray(a, dtype=dtype))
else:
log_a = np.log(a)
if weights is not None:
weights = np.asanyarray(weights, dtype=dtype)
return np.exp(np.average(log_a, axis=axis, weights=weights))
def hmean(a, axis=0, dtype=None):
"""
Calculate the harmonic mean along the specified axis.
That is: n / (1/x1 + 1/x2 + ... + 1/xn)
Parameters
----------
a : array_like
Input array, masked array or object that can be converted to an array.
axis : int or None, optional
Axis along which the harmonic mean is computed. Default is 0.
If None, compute over the whole array `a`.
dtype : dtype, optional
Type of the returned array and of the accumulator in which the
elements are summed. If `dtype` is not specified, it defaults to the
dtype of `a`, unless `a` has an integer `dtype` with a precision less
than that of the default platform integer. In that case, the default
platform integer is used.
Returns
-------
hmean : ndarray
See `dtype` parameter above.
See Also
--------
numpy.mean : Arithmetic average
numpy.average : Weighted average
gmean : Geometric mean
Notes
-----
The harmonic mean is computed over a single dimension of the input
array, axis=0 by default, or all values in the array if axis=None.
float64 intermediate and return values are used for integer inputs.
Use masked arrays to ignore any non-finite values in the input or that
arise in the calculations such as Not a Number and infinity.
Examples
--------
>>> from scipy.stats import hmean
>>> hmean([1, 4])
1.6000000000000001
>>> hmean([1, 2, 3, 4, 5, 6, 7])
2.6997245179063363
"""
if not isinstance(a, np.ndarray):
a = np.array(a, dtype=dtype)
if np.all(a >= 0):
# Harmonic mean only defined if greater than or equal to to zero.
if isinstance(a, np.ma.MaskedArray):
size = a.count(axis)
else:
if axis is None:
a = a.ravel()
size = a.shape[0]
else:
size = a.shape[axis]
with np.errstate(divide='ignore'):
return size / np.sum(1.0 / a, axis=axis, dtype=dtype)
else:
raise ValueError("Harmonic mean only defined if all elements greater "
"than or equal to zero")
ModeResult = namedtuple('ModeResult', ('mode', 'count'))
def mode(a, axis=0, nan_policy='propagate'):
"""
Return an array of the modal (most common) value in the passed array.
If there is more than one such value, only the smallest is returned.
The bin-count for the modal bins is also returned.
Parameters
----------
a : array_like
n-dimensional array of which to find mode(s).
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over
the whole array `a`.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
mode : ndarray
Array of modal values.
count : ndarray
Array of counts for each mode.
Examples
--------
>>> a = np.array([[6, 8, 3, 0],
... [3, 2, 1, 7],
... [8, 1, 8, 4],
... [5, 3, 0, 5],
... [4, 7, 5, 9]])
>>> from scipy import stats
>>> stats.mode(a)
ModeResult(mode=array([[3, 1, 0, 0]]), count=array([[1, 1, 1, 1]]))
To get mode of whole array, specify ``axis=None``:
>>> stats.mode(a, axis=None)
ModeResult(mode=array([3]), count=array([3]))
"""
a, axis = _chk_asarray(a, axis)
if a.size == 0:
return ModeResult(np.array([]), np.array([]))
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
a = ma.masked_invalid(a)
return mstats_basic.mode(a, axis)
if a.dtype == object and np.nan in set(a.ravel()):
# Fall back to a slower method since np.unique does not work with NaN
scores = set(np.ravel(a)) # get ALL unique values
testshape = list(a.shape)
testshape[axis] = 1
oldmostfreq = np.zeros(testshape, dtype=a.dtype)
oldcounts = np.zeros(testshape, dtype=int)
for score in scores:
template = (a == score)
counts = np.sum(template, axis, keepdims=True)
mostfrequent = np.where(counts > oldcounts, score, oldmostfreq)
oldcounts = np.maximum(counts, oldcounts)
oldmostfreq = mostfrequent
return ModeResult(mostfrequent, oldcounts)
def _mode1D(a):
vals, cnts = np.unique(a, return_counts=True)
return vals[cnts.argmax()], cnts.max()
# np.apply_along_axis will convert the _mode1D tuples to a numpy array, casting types in the process
# This recreates the results without that issue
# View of a, rotated so the requested axis is last
in_dims = list(range(a.ndim))
a_view = np.transpose(a, in_dims[:axis] + in_dims[axis+1:] + [axis])
inds = np.ndindex(a_view.shape[:-1])
modes = np.empty(a_view.shape[:-1], dtype=a.dtype)
counts = np.empty(a_view.shape[:-1], dtype=np.int_)
for ind in inds:
modes[ind], counts[ind] = _mode1D(a_view[ind])
newshape = list(a.shape)
newshape[axis] = 1
return ModeResult(modes.reshape(newshape), counts.reshape(newshape))
def _mask_to_limits(a, limits, inclusive):
"""Mask an array for values outside of given limits.
This is primarily a utility function.
Parameters
----------
a : array
limits : (float or None, float or None)
A tuple consisting of the (lower limit, upper limit). Values in the
input array less than the lower limit or greater than the upper limit
will be masked out. None implies no limit.
inclusive : (bool, bool)
A tuple consisting of the (lower flag, upper flag). These flags
determine whether values exactly equal to lower or upper are allowed.
Returns
-------
A MaskedArray.
Raises
------
A ValueError if there are no values within the given limits.
"""
lower_limit, upper_limit = limits
lower_include, upper_include = inclusive
am = ma.MaskedArray(a)
if lower_limit is not None:
if lower_include:
am = ma.masked_less(am, lower_limit)
else:
am = ma.masked_less_equal(am, lower_limit)
if upper_limit is not None:
if upper_include:
am = ma.masked_greater(am, upper_limit)
else:
am = ma.masked_greater_equal(am, upper_limit)
if am.count() == 0:
raise ValueError("No array values within given limits")
return am
def tmean(a, limits=None, inclusive=(True, True), axis=None):
"""
Compute the trimmed mean.
This function finds the arithmetic mean of given values, ignoring values
outside the given `limits`.
Parameters
----------
a : array_like
Array of values.
limits : None or (lower limit, upper limit), optional
Values in the input array less than the lower limit or greater than the
upper limit will be ignored. When limits is None (default), then all
values are used. Either of the limit values in the tuple can also be
None representing a half-open interval.
inclusive : (bool, bool), optional
A tuple consisting of the (lower flag, upper flag). These flags
determine whether values exactly equal to the lower or upper limits
are included. The default value is (True, True).
axis : int or None, optional
Axis along which to compute test. Default is None.
Returns
-------
tmean : float
Trimmed mean.
See Also
--------
trim_mean : Returns mean after trimming a proportion from both tails.
Examples
--------
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.tmean(x)
9.5
>>> stats.tmean(x, (3,17))
10.0
"""
a = asarray(a)
if limits is None:
return np.mean(a, None)
am = _mask_to_limits(a.ravel(), limits, inclusive)
return am.mean(axis=axis)
def tvar(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
"""
Compute the trimmed variance.
This function computes the sample variance of an array of values,
while ignoring values which are outside of given `limits`.
Parameters
----------
a : array_like
Array of values.
limits : None or (lower limit, upper limit), optional
Values in the input array less than the lower limit or greater than the
upper limit will be ignored. When limits is None, then all values are
used. Either of the limit values in the tuple can also be None
representing a half-open interval. The default value is None.
inclusive : (bool, bool), optional
A tuple consisting of the (lower flag, upper flag). These flags
determine whether values exactly equal to the lower or upper limits
are included. The default value is (True, True).
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over the
whole array `a`.
ddof : int, optional
Delta degrees of freedom. Default is 1.
Returns
-------
tvar : float
Trimmed variance.
Notes
-----
`tvar` computes the unbiased sample variance, i.e. it uses a correction
factor ``n / (n - 1)``.
Examples
--------
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.tvar(x)
35.0
>>> stats.tvar(x, (3,17))
20.0
"""
a = asarray(a)
a = a.astype(float)
if limits is None:
return a.var(ddof=ddof, axis=axis)
am = _mask_to_limits(a, limits, inclusive)
amnan = am.filled(fill_value=np.nan)
return np.nanvar(amnan, ddof=ddof, axis=axis)
def tmin(a, lowerlimit=None, axis=0, inclusive=True, nan_policy='propagate'):
"""
Compute the trimmed minimum.
This function finds the miminum value of an array `a` along the
specified axis, but only considering values greater than a specified
lower limit.
Parameters
----------
a : array_like
Array of values.
lowerlimit : None or float, optional
Values in the input array less than the given limit will be ignored.
When lowerlimit is None, then all values are used. The default value
is None.
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over the
whole array `a`.
inclusive : {True, False}, optional
This flag determines whether values exactly equal to the lower limit
are included. The default value is True.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
tmin : float, int or ndarray
Trimmed minimum.
Examples
--------
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.tmin(x)
0
>>> stats.tmin(x, 13)
13
>>> stats.tmin(x, 13, inclusive=False)
14
"""
a, axis = _chk_asarray(a, axis)
am = _mask_to_limits(a, (lowerlimit, None), (inclusive, False))
contains_nan, nan_policy = _contains_nan(am, nan_policy)
if contains_nan and nan_policy == 'omit':
am = ma.masked_invalid(am)
res = ma.minimum.reduce(am, axis).data
if res.ndim == 0:
return res[()]
return res
def tmax(a, upperlimit=None, axis=0, inclusive=True, nan_policy='propagate'):
"""
Compute the trimmed maximum.
This function computes the maximum value of an array along a given axis,
while ignoring values larger than a specified upper limit.
Parameters
----------
a : array_like
Array of values.
upperlimit : None or float, optional
Values in the input array greater than the given limit will be ignored.
When upperlimit is None, then all values are used. The default value
is None.
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over the
whole array `a`.
inclusive : {True, False}, optional
This flag determines whether values exactly equal to the upper limit
are included. The default value is True.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
tmax : float, int or ndarray
Trimmed maximum.
Examples
--------
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.tmax(x)
19
>>> stats.tmax(x, 13)
13
>>> stats.tmax(x, 13, inclusive=False)
12
"""
a, axis = _chk_asarray(a, axis)
am = _mask_to_limits(a, (None, upperlimit), (False, inclusive))
contains_nan, nan_policy = _contains_nan(am, nan_policy)
if contains_nan and nan_policy == 'omit':
am = ma.masked_invalid(am)
res = ma.maximum.reduce(am, axis).data
if res.ndim == 0:
return res[()]
return res
def tstd(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
"""
Compute the trimmed sample standard deviation.
This function finds the sample standard deviation of given values,
ignoring values outside the given `limits`.
Parameters
----------
a : array_like
Array of values.
limits : None or (lower limit, upper limit), optional
Values in the input array less than the lower limit or greater than the
upper limit will be ignored. When limits is None, then all values are
used. Either of the limit values in the tuple can also be None
representing a half-open interval. The default value is None.
inclusive : (bool, bool), optional
A tuple consisting of the (lower flag, upper flag). These flags
determine whether values exactly equal to the lower or upper limits
are included. The default value is (True, True).
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over the
whole array `a`.
ddof : int, optional
Delta degrees of freedom. Default is 1.
Returns
-------
tstd : float
Trimmed sample standard deviation.
Notes
-----
`tstd` computes the unbiased sample standard deviation, i.e. it uses a
correction factor ``n / (n - 1)``.
Examples
--------
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.tstd(x)
5.9160797830996161
>>> stats.tstd(x, (3,17))
4.4721359549995796
"""
return np.sqrt(tvar(a, limits, inclusive, axis, ddof))
def tsem(a, limits=None, inclusive=(True, True), axis=0, ddof=1):
"""
Compute the trimmed standard error of the mean.
This function finds the standard error of the mean for given
values, ignoring values outside the given `limits`.
Parameters
----------
a : array_like
Array of values.
limits : None or (lower limit, upper limit), optional
Values in the input array less than the lower limit or greater than the
upper limit will be ignored. When limits is None, then all values are
used. Either of the limit values in the tuple can also be None
representing a half-open interval. The default value is None.
inclusive : (bool, bool), optional
A tuple consisting of the (lower flag, upper flag). These flags
determine whether values exactly equal to the lower or upper limits
are included. The default value is (True, True).
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over the
whole array `a`.
ddof : int, optional
Delta degrees of freedom. Default is 1.
Returns
-------
tsem : float
Trimmed standard error of the mean.
Notes
-----
`tsem` uses unbiased sample standard deviation, i.e. it uses a
correction factor ``n / (n - 1)``.
Examples
--------
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.tsem(x)
1.3228756555322954
>>> stats.tsem(x, (3,17))
1.1547005383792515
"""
a = np.asarray(a).ravel()
if limits is None:
return a.std(ddof=ddof) / np.sqrt(a.size)
am = _mask_to_limits(a, limits, inclusive)
sd = np.sqrt(np.ma.var(am, ddof=ddof, axis=axis))
return sd / np.sqrt(am.count())
#####################################
# MOMENTS #
#####################################
def moment(a, moment=1, axis=0, nan_policy='propagate'):
r"""
Calculate the nth moment about the mean for a sample.
A moment is a specific quantitative measure of the shape of a set of
points. It is often used to calculate coefficients of skewness and kurtosis
due to its close relationship with them.
Parameters
----------
a : array_like
Input array.
moment : int or array_like of ints, optional
Order of central moment that is returned. Default is 1.
axis : int or None, optional
Axis along which the central moment is computed. Default is 0.
If None, compute over the whole array `a`.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
n-th central moment : ndarray or float
The appropriate moment along the given axis or over all values if axis
is None. The denominator for the moment calculation is the number of
observations, no degrees of freedom correction is done.
See Also
--------
kurtosis, skew, describe
Notes
-----
The k-th central moment of a data sample is:
.. math::
m_k = \frac{1}{n} \sum_{i = 1}^n (x_i - \bar{x})^k
Where n is the number of samples and x-bar is the mean. This function uses
exponentiation by squares [1]_ for efficiency.
References
----------
.. [1] https://eli.thegreenplace.net/2009/03/21/efficient-integer-exponentiation-algorithms
Examples
--------
>>> from scipy.stats import moment
>>> moment([1, 2, 3, 4, 5], moment=1)
0.0
>>> moment([1, 2, 3, 4, 5], moment=2)
2.0
"""
a, axis = _chk_asarray(a, axis)
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
a = ma.masked_invalid(a)
return mstats_basic.moment(a, moment, axis)
if a.size == 0:
# empty array, return nan(s) with shape matching `moment`
if np.isscalar(moment):
return np.nan
else:
return np.full(np.asarray(moment).shape, np.nan, dtype=np.float64)
# for array_like moment input, return a value for each.
if not np.isscalar(moment):
mmnt = [_moment(a, i, axis) for i in moment]
return np.array(mmnt)
else:
return _moment(a, moment, axis)
def _moment(a, moment, axis):
if np.abs(moment - np.round(moment)) > 0:
raise ValueError("All moment parameters must be integers")
if moment == 0:
# When moment equals 0, the result is 1, by definition.
shape = list(a.shape)
del shape[axis]
if shape:
# return an actual array of the appropriate shape
return np.ones(shape, dtype=float)
else:
# the input was 1D, so return a scalar instead of a rank-0 array
return 1.0
elif moment == 1:
# By definition the first moment about the mean is 0.
shape = list(a.shape)
del shape[axis]
if shape:
# return an actual array of the appropriate shape
return np.zeros(shape, dtype=float)
else:
# the input was 1D, so return a scalar instead of a rank-0 array
return np.float64(0.0)
else:
# Exponentiation by squares: form exponent sequence
n_list = [moment]
current_n = moment
while current_n > 2:
if current_n % 2:
current_n = (current_n - 1) / 2
else:
current_n /= 2
n_list.append(current_n)
# Starting point for exponentiation by squares
a_zero_mean = a - np.mean(a, axis, keepdims=True)
if n_list[-1] == 1:
s = a_zero_mean.copy()
else:
s = a_zero_mean**2
# Perform multiplications
for n in n_list[-2::-1]:
s = s**2
if n % 2:
s *= a_zero_mean
return np.mean(s, axis)
def variation(a, axis=0, nan_policy='propagate', ddof=0):
"""
Compute the coefficient of variation.
The coefficient of variation is the standard deviation divided by the
mean. This function is equivalent to::
np.std(x, axis=axis, ddof=ddof) / np.mean(x)
The default for ``ddof`` is 0, but many definitions of the coefficient
of variation use the square root of the unbiased sample variance
for the sample standard deviation, which corresponds to ``ddof=1``.
Parameters
----------
a : array_like
Input array.
axis : int or None, optional
Axis along which to calculate the coefficient of variation. Default
is 0. If None, compute over the whole array `a`.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
ddof : int, optional
Delta degrees of freedom. Default is 0.
Returns
-------
variation : ndarray
The calculated variation along the requested axis.
References
----------
.. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
Probability and Statistics Tables and Formulae. Chapman & Hall: New
York. 2000.
Examples
--------
>>> from scipy.stats import variation
>>> variation([1, 2, 3, 4, 5])
0.47140452079103173
"""
a, axis = _chk_asarray(a, axis)
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
a = ma.masked_invalid(a)
return mstats_basic.variation(a, axis, ddof)
return a.std(axis, ddof=ddof) / a.mean(axis)
def skew(a, axis=0, bias=True, nan_policy='propagate'):
r"""
Compute the sample skewness of a data set.
For normally distributed data, the skewness should be about zero. For
unimodal continuous distributions, a skewness value greater than zero means
that there is more weight in the right tail of the distribution. The
function `skewtest` can be used to determine if the skewness value
is close enough to zero, statistically speaking.
Parameters
----------
a : ndarray
Input array.
axis : int or None, optional
Axis along which skewness is calculated. Default is 0.
If None, compute over the whole array `a`.
bias : bool, optional
If False, then the calculations are corrected for statistical bias.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
skewness : ndarray
The skewness of values along an axis, returning 0 where all values are
equal.
Notes
-----
The sample skewness is computed as the Fisher-Pearson coefficient
of skewness, i.e.
.. math::
g_1=\frac{m_3}{m_2^{3/2}}
where
.. math::
m_i=\frac{1}{N}\sum_{n=1}^N(x[n]-\bar{x})^i
is the biased sample :math:`i\texttt{th}` central moment, and :math:`\bar{x}` is
the sample mean. If ``bias`` is False, the calculations are
corrected for bias and the value computed is the adjusted
Fisher-Pearson standardized moment coefficient, i.e.
.. math::
G_1=\frac{k_3}{k_2^{3/2}}=
\frac{\sqrt{N(N-1)}}{N-2}\frac{m_3}{m_2^{3/2}}.
References
----------
.. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
Probability and Statistics Tables and Formulae. Chapman & Hall: New
York. 2000.
Section 2.2.24.1
Examples
--------
>>> from scipy.stats import skew
>>> skew([1, 2, 3, 4, 5])
0.0
>>> skew([2, 8, 0, 4, 1, 9, 9, 0])
0.2650554122698573
"""
a, axis = _chk_asarray(a, axis)
n = a.shape[axis]
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
a = ma.masked_invalid(a)
return mstats_basic.skew(a, axis, bias)
m2 = moment(a, 2, axis)
m3 = moment(a, 3, axis)
with np.errstate(all='ignore'):
zero = (m2 <= (np.finfo(m2.dtype).resolution * a.mean(axis))**2)
vals = np.where(zero, 0, m3 / m2**1.5)
if not bias:
can_correct = ~zero & (n > 2)
if can_correct.any():
m2 = np.extract(can_correct, m2)
m3 = np.extract(can_correct, m3)
nval = np.sqrt((n - 1.0) * n) / (n - 2.0) * m3 / m2**1.5
np.place(vals, can_correct, nval)
if vals.ndim == 0:
return vals.item()
return vals
def kurtosis(a, axis=0, fisher=True, bias=True, nan_policy='propagate'):
"""
Compute the kurtosis (Fisher or Pearson) of a dataset.
Kurtosis is the fourth central moment divided by the square of the
variance. If Fisher's definition is used, then 3.0 is subtracted from
the result to give 0.0 for a normal distribution.
If bias is False then the kurtosis is calculated using k statistics to
eliminate bias coming from biased moment estimators
Use `kurtosistest` to see if result is close enough to normal.
Parameters
----------
a : array
Data for which the kurtosis is calculated.
axis : int or None, optional
Axis along which the kurtosis is calculated. Default is 0.
If None, compute over the whole array `a`.
fisher : bool, optional
If True, Fisher's definition is used (normal ==> 0.0). If False,
Pearson's definition is used (normal ==> 3.0).
bias : bool, optional
If False, then the calculations are corrected for statistical bias.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan. 'propagate' returns nan,
'raise' throws an error, 'omit' performs the calculations ignoring nan
values. Default is 'propagate'.
Returns
-------
kurtosis : array
The kurtosis of values along an axis. If all values are equal,
return -3 for Fisher's definition and 0 for Pearson's definition.
References
----------
.. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
Probability and Statistics Tables and Formulae. Chapman & Hall: New
York. 2000.
Examples
--------
In Fisher's definiton, the kurtosis of the normal distribution is zero.
In the following example, the kurtosis is close to zero, because it was
calculated from the dataset, not from the continuous distribution.
>>> from scipy.stats import norm, kurtosis
>>> data = norm.rvs(size=1000, random_state=3)
>>> kurtosis(data)
-0.06928694200380558
The distribution with a higher kurtosis has a heavier tail.
The zero valued kurtosis of the normal distribution in Fisher's definition
can serve as a reference point.
>>> import matplotlib.pyplot as plt
>>> import scipy.stats as stats
>>> from scipy.stats import kurtosis
>>> x = np.linspace(-5, 5, 100)
>>> ax = plt.subplot()
>>> distnames = ['laplace', 'norm', 'uniform']
>>> for distname in distnames:
... if distname == 'uniform':
... dist = getattr(stats, distname)(loc=-2, scale=4)
... else:
... dist = getattr(stats, distname)
... data = dist.rvs(size=1000)
... kur = kurtosis(data, fisher=True)
... y = dist.pdf(x)
... ax.plot(x, y, label="{}, {}".format(distname, round(kur, 3)))
... ax.legend()
The Laplace distribution has a heavier tail than the normal distribution.
The uniform distribution (which has negative kurtosis) has the thinnest
tail.
"""
a, axis = _chk_asarray(a, axis)
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
a = ma.masked_invalid(a)
return mstats_basic.kurtosis(a, axis, fisher, bias)
n = a.shape[axis]
m2 = moment(a, 2, axis)
m4 = moment(a, 4, axis)
with np.errstate(all='ignore'):
zero = (m2 <= (np.finfo(m2.dtype).resolution * a.mean(axis))**2)
vals = np.where(zero, 0, m4 / m2**2.0)
if not bias:
can_correct = ~zero & (n > 3)
if can_correct.any():
m2 = np.extract(can_correct, m2)
m4 = np.extract(can_correct, m4)
nval = 1.0/(n-2)/(n-3) * ((n**2-1.0)*m4/m2**2.0 - 3*(n-1)**2.0)
np.place(vals, can_correct, nval + 3.0)
if vals.ndim == 0:
vals = vals.item() # array scalar
return vals - 3 if fisher else vals
DescribeResult = namedtuple('DescribeResult',
('nobs', 'minmax', 'mean', 'variance', 'skewness',
'kurtosis'))
def describe(a, axis=0, ddof=1, bias=True, nan_policy='propagate'):
"""
Compute several descriptive statistics of the passed array.
Parameters
----------
a : array_like
Input data.
axis : int or None, optional
Axis along which statistics are calculated. Default is 0.
If None, compute over the whole array `a`.
ddof : int, optional
Delta degrees of freedom (only for variance). Default is 1.
bias : bool, optional
If False, then the skewness and kurtosis calculations are corrected
for statistical bias.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
nobs : int or ndarray of ints
Number of observations (length of data along `axis`).
When 'omit' is chosen as nan_policy, the length along each axis
slice is counted separately.
minmax: tuple of ndarrays or floats
Minimum and maximum value of `a` along the given axis.
mean : ndarray or float
Arithmetic mean of `a` along the given axis.
variance : ndarray or float
Unbiased variance of `a` along the given axis; denominator is number
of observations minus one.
skewness : ndarray or float
Skewness of `a` along the given axis, based on moment calculations
with denominator equal to the number of observations, i.e. no degrees
of freedom correction.
kurtosis : ndarray or float
Kurtosis (Fisher) of `a` along the given axis. The kurtosis is
normalized so that it is zero for the normal distribution. No
degrees of freedom are used.
See Also
--------
skew, kurtosis
Examples
--------
>>> from scipy import stats
>>> a = np.arange(10)
>>> stats.describe(a)
DescribeResult(nobs=10, minmax=(0, 9), mean=4.5,
variance=9.166666666666666, skewness=0.0,
kurtosis=-1.2242424242424244)
>>> b = [[1, 2], [3, 4]]
>>> stats.describe(b)
DescribeResult(nobs=2, minmax=(array([1, 2]), array([3, 4])),
mean=array([2., 3.]), variance=array([2., 2.]),
skewness=array([0., 0.]), kurtosis=array([-2., -2.]))
"""
a, axis = _chk_asarray(a, axis)
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
a = ma.masked_invalid(a)
return mstats_basic.describe(a, axis, ddof, bias)
if a.size == 0:
raise ValueError("The input must not be empty.")
n = a.shape[axis]
mm = (np.min(a, axis=axis), np.max(a, axis=axis))
m = np.mean(a, axis=axis)
v = np.var(a, axis=axis, ddof=ddof)
sk = skew(a, axis, bias=bias)
kurt = kurtosis(a, axis, bias=bias)
return DescribeResult(n, mm, m, v, sk, kurt)
#####################################
# NORMALITY TESTS #
#####################################
SkewtestResult = namedtuple('SkewtestResult', ('statistic', 'pvalue'))
def skewtest(a, axis=0, nan_policy='propagate'):
"""
Test whether the skew is different from the normal distribution.
This function tests the null hypothesis that the skewness of
the population that the sample was drawn from is the same
as that of a corresponding normal distribution.
Parameters
----------
a : array
The data to be tested.
axis : int or None, optional
Axis along which statistics are calculated. Default is 0.
If None, compute over the whole array `a`.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
statistic : float
The computed z-score for this test.
pvalue : float
Two-sided p-value for the hypothesis test.
Notes
-----
The sample size must be at least 8.
References
----------
.. [1] R. B. D'Agostino, A. J. Belanger and R. B. D'Agostino Jr.,
"A suggestion for using powerful and informative tests of
normality", American Statistician 44, pp. 316-321, 1990.
Examples
--------
>>> from scipy.stats import skewtest
>>> skewtest([1, 2, 3, 4, 5, 6, 7, 8])
SkewtestResult(statistic=1.0108048609177787, pvalue=0.3121098361421897)
>>> skewtest([2, 8, 0, 4, 1, 9, 9, 0])
SkewtestResult(statistic=0.44626385374196975, pvalue=0.6554066631275459)
>>> skewtest([1, 2, 3, 4, 5, 6, 7, 8000])
SkewtestResult(statistic=3.571773510360407, pvalue=0.0003545719905823133)
>>> skewtest([100, 100, 100, 100, 100, 100, 100, 101])
SkewtestResult(statistic=3.5717766638478072, pvalue=0.000354567720281634)
"""
a, axis = _chk_asarray(a, axis)
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
a = ma.masked_invalid(a)
return mstats_basic.skewtest(a, axis)
if axis is None:
a = np.ravel(a)
axis = 0
b2 = skew(a, axis)
n = a.shape[axis]
if n < 8:
raise ValueError(
"skewtest is not valid with less than 8 samples; %i samples"
" were given." % int(n))
y = b2 * math.sqrt(((n + 1) * (n + 3)) / (6.0 * (n - 2)))
beta2 = (3.0 * (n**2 + 27*n - 70) * (n+1) * (n+3) /
((n-2.0) * (n+5) * (n+7) * (n+9)))
W2 = -1 + math.sqrt(2 * (beta2 - 1))
delta = 1 / math.sqrt(0.5 * math.log(W2))
alpha = math.sqrt(2.0 / (W2 - 1))
y = np.where(y == 0, 1, y)
Z = delta * np.log(y / alpha + np.sqrt((y / alpha)**2 + 1))
return SkewtestResult(Z, 2 * distributions.norm.sf(np.abs(Z)))
KurtosistestResult = namedtuple('KurtosistestResult', ('statistic', 'pvalue'))
def kurtosistest(a, axis=0, nan_policy='propagate'):
"""
Test whether a dataset has normal kurtosis.
This function tests the null hypothesis that the kurtosis
of the population from which the sample was drawn is that
of the normal distribution: ``kurtosis = 3(n-1)/(n+1)``.
Parameters
----------
a : array
Array of the sample data.
axis : int or None, optional
Axis along which to compute test. Default is 0. If None,
compute over the whole array `a`.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
statistic : float
The computed z-score for this test.
pvalue : float
The two-sided p-value for the hypothesis test.
Notes
-----
Valid only for n>20. This function uses the method described in [1]_.
References
----------
.. [1] see e.g. F. J. Anscombe, W. J. Glynn, "Distribution of the kurtosis
statistic b2 for normal samples", Biometrika, vol. 70, pp. 227-234, 1983.
Examples
--------
>>> from scipy.stats import kurtosistest
>>> kurtosistest(list(range(20)))
KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.08804338332528348)
>>> np.random.seed(28041990)
>>> s = np.random.normal(0, 1, 1000)
>>> kurtosistest(s)
KurtosistestResult(statistic=1.2317590987707365, pvalue=0.21803908613450895)
"""
a, axis = _chk_asarray(a, axis)
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
a = ma.masked_invalid(a)
return mstats_basic.kurtosistest(a, axis)
n = a.shape[axis]
if n < 5:
raise ValueError(
"kurtosistest requires at least 5 observations; %i observations"
" were given." % int(n))
if n < 20:
warnings.warn("kurtosistest only valid for n>=20 ... continuing "
"anyway, n=%i" % int(n))
b2 = kurtosis(a, axis, fisher=False)
E = 3.0*(n-1) / (n+1)
varb2 = 24.0*n*(n-2)*(n-3) / ((n+1)*(n+1.)*(n+3)*(n+5)) # [1]_ Eq. 1
x = (b2-E) / np.sqrt(varb2) # [1]_ Eq. 4
# [1]_ Eq. 2:
sqrtbeta1 = 6.0*(n*n-5*n+2)/((n+7)*(n+9)) * np.sqrt((6.0*(n+3)*(n+5)) /
(n*(n-2)*(n-3)))
# [1]_ Eq. 3:
A = 6.0 + 8.0/sqrtbeta1 * (2.0/sqrtbeta1 + np.sqrt(1+4.0/(sqrtbeta1**2)))
term1 = 1 - 2/(9.0*A)
denom = 1 + x*np.sqrt(2/(A-4.0))
term2 = np.sign(denom) * np.where(denom == 0.0, np.nan,
np.power((1-2.0/A)/np.abs(denom), 1/3.0))
if np.any(denom == 0):
msg = "Test statistic not defined in some cases due to division by " \
"zero. Return nan in that case..."
warnings.warn(msg, RuntimeWarning)
Z = (term1 - term2) / np.sqrt(2/(9.0*A)) # [1]_ Eq. 5
if Z.ndim == 0:
Z = Z[()]
# zprob uses upper tail, so Z needs to be positive
return KurtosistestResult(Z, 2 * distributions.norm.sf(np.abs(Z)))
NormaltestResult = namedtuple('NormaltestResult', ('statistic', 'pvalue'))
def normaltest(a, axis=0, nan_policy='propagate'):
"""
Test whether a sample differs from a normal distribution.
This function tests the null hypothesis that a sample comes
from a normal distribution. It is based on D'Agostino and
Pearson's [1]_, [2]_ test that combines skew and kurtosis to
produce an omnibus test of normality.
Parameters
----------
a : array_like
The array containing the sample to be tested.
axis : int or None, optional
Axis along which to compute test. Default is 0. If None,
compute over the whole array `a`.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
statistic : float or array
``s^2 + k^2``, where ``s`` is the z-score returned by `skewtest` and
``k`` is the z-score returned by `kurtosistest`.
pvalue : float or array
A 2-sided chi squared probability for the hypothesis test.
References
----------
.. [1] D'Agostino, R. B. (1971), "An omnibus test of normality for
moderate and large sample size", Biometrika, 58, 341-348
.. [2] D'Agostino, R. and Pearson, E. S. (1973), "Tests for departure from
normality", Biometrika, 60, 613-622
Examples
--------
>>> from scipy import stats
>>> pts = 1000
>>> np.random.seed(28041990)
>>> a = np.random.normal(0, 1, size=pts)
>>> b = np.random.normal(2, 1, size=pts)
>>> x = np.concatenate((a, b))
>>> k2, p = stats.normaltest(x)
>>> alpha = 1e-3
>>> print("p = {:g}".format(p))
p = 3.27207e-11
>>> if p < alpha: # null hypothesis: x comes from a normal distribution
... print("The null hypothesis can be rejected")
... else:
... print("The null hypothesis cannot be rejected")
The null hypothesis can be rejected
"""
a, axis = _chk_asarray(a, axis)
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
a = ma.masked_invalid(a)
return mstats_basic.normaltest(a, axis)
s, _ = skewtest(a, axis)
k, _ = kurtosistest(a, axis)
k2 = s*s + k*k
return NormaltestResult(k2, distributions.chi2.sf(k2, 2))
Jarque_beraResult = namedtuple('Jarque_beraResult', ('statistic', 'pvalue'))
def jarque_bera(x):
"""
Perform the Jarque-Bera goodness of fit test on sample data.
The Jarque-Bera test tests whether the sample data has the skewness and
kurtosis matching a normal distribution.
Note that this test only works for a large enough number of data samples
(>2000) as the test statistic asymptotically has a Chi-squared distribution
with 2 degrees of freedom.
Parameters
----------
x : array_like
Observations of a random variable.
Returns
-------
jb_value : float
The test statistic.
p : float
The p-value for the hypothesis test.
References
----------
.. [1] Jarque, C. and Bera, A. (1980) "Efficient tests for normality,
homoscedasticity and serial independence of regression residuals",
6 Econometric Letters 255-259.
Examples
--------
>>> from scipy import stats
>>> np.random.seed(987654321)
>>> x = np.random.normal(0, 1, 100000)
>>> jarque_bera_test = stats.jarque_bera(x)
>>> jarque_bera_test
Jarque_beraResult(statistic=4.716570798957913, pvalue=0.0945822550304295)
>>> jarque_bera_test.statistic
4.716570798957913
>>> jarque_bera_test.pvalue
0.0945822550304295
"""
x = np.asarray(x)
n = x.size
if n == 0:
raise ValueError('At least one observation is required.')
mu = x.mean()
diffx = x - mu
skewness = (1 / n * np.sum(diffx**3)) / (1 / n * np.sum(diffx**2))**(3 / 2.)
kurtosis = (1 / n * np.sum(diffx**4)) / (1 / n * np.sum(diffx**2))**2
jb_value = n / 6 * (skewness**2 + (kurtosis - 3)**2 / 4)
p = 1 - distributions.chi2.cdf(jb_value, 2)
return Jarque_beraResult(jb_value, p)
#####################################
# FREQUENCY FUNCTIONS #
#####################################
# deindent to work around numpy/gh-16202
@np.deprecate(
message="`itemfreq` is deprecated and will be removed in a "
"future version. Use instead `np.unique(..., return_counts=True)`")
def itemfreq(a):
"""
Return a 2-D array of item frequencies.
Parameters
----------
a : (N,) array_like
Input array.
Returns
-------
itemfreq : (K, 2) ndarray
A 2-D frequency table. Column 1 contains sorted, unique values from
`a`, column 2 contains their respective counts.
Examples
--------
>>> from scipy import stats
>>> a = np.array([1, 1, 5, 0, 1, 2, 2, 0, 1, 4])
>>> stats.itemfreq(a)
array([[ 0., 2.],
[ 1., 4.],
[ 2., 2.],
[ 4., 1.],
[ 5., 1.]])
>>> np.bincount(a)
array([2, 4, 2, 0, 1, 1])
>>> stats.itemfreq(a/10.)
array([[ 0. , 2. ],
[ 0.1, 4. ],
[ 0.2, 2. ],
[ 0.4, 1. ],
[ 0.5, 1. ]])
"""
items, inv = np.unique(a, return_inverse=True)
freq = np.bincount(inv)
return np.array([items, freq]).T
def scoreatpercentile(a, per, limit=(), interpolation_method='fraction',
axis=None):
"""
Calculate the score at a given percentile of the input sequence.
For example, the score at `per=50` is the median. If the desired quantile
lies between two data points, we interpolate between them, according to
the value of `interpolation`. If the parameter `limit` is provided, it
should be a tuple (lower, upper) of two values.
Parameters
----------
a : array_like
A 1-D array of values from which to extract score.
per : array_like
Percentile(s) at which to extract score. Values should be in range
[0,100].
limit : tuple, optional
Tuple of two scalars, the lower and upper limits within which to
compute the percentile. Values of `a` outside
this (closed) interval will be ignored.
interpolation_method : {'fraction', 'lower', 'higher'}, optional
Specifies the interpolation method to use,
when the desired quantile lies between two data points `i` and `j`
The following options are available (default is 'fraction'):
* 'fraction': ``i + (j - i) * fraction`` where ``fraction`` is the
fractional part of the index surrounded by ``i`` and ``j``
* 'lower': ``i``
* 'higher': ``j``
axis : int, optional
Axis along which the percentiles are computed. Default is None. If
None, compute over the whole array `a`.
Returns
-------
score : float or ndarray
Score at percentile(s).
See Also
--------
percentileofscore, numpy.percentile
Notes
-----
This function will become obsolete in the future.
For NumPy 1.9 and higher, `numpy.percentile` provides all the functionality
that `scoreatpercentile` provides. And it's significantly faster.
Therefore it's recommended to use `numpy.percentile` for users that have
numpy >= 1.9.
Examples
--------
>>> from scipy import stats
>>> a = np.arange(100)
>>> stats.scoreatpercentile(a, 50)
49.5
"""
# adapted from NumPy's percentile function. When we require numpy >= 1.8,
# the implementation of this function can be replaced by np.percentile.
a = np.asarray(a)
if a.size == 0:
# empty array, return nan(s) with shape matching `per`
if np.isscalar(per):
return np.nan
else:
return np.full(np.asarray(per).shape, np.nan, dtype=np.float64)
if limit:
a = a[(limit[0] <= a) & (a <= limit[1])]
sorted_ = np.sort(a, axis=axis)
if axis is None:
axis = 0
return _compute_qth_percentile(sorted_, per, interpolation_method, axis)
# handle sequence of per's without calling sort multiple times
def _compute_qth_percentile(sorted_, per, interpolation_method, axis):
if not np.isscalar(per):
score = [_compute_qth_percentile(sorted_, i,
interpolation_method, axis)
for i in per]
return np.array(score)
if not (0 <= per <= 100):
raise ValueError("percentile must be in the range [0, 100]")
indexer = [slice(None)] * sorted_.ndim
idx = per / 100. * (sorted_.shape[axis] - 1)
if int(idx) != idx:
# round fractional indices according to interpolation method
if interpolation_method == 'lower':
idx = int(np.floor(idx))
elif interpolation_method == 'higher':
idx = int(np.ceil(idx))
elif interpolation_method == 'fraction':
pass # keep idx as fraction and interpolate
else:
raise ValueError("interpolation_method can only be 'fraction', "
"'lower' or 'higher'")
i = int(idx)
if i == idx:
indexer[axis] = slice(i, i + 1)
weights = array(1)
sumval = 1.0
else:
indexer[axis] = slice(i, i + 2)
j = i + 1
weights = array([(j - idx), (idx - i)], float)
wshape = [1] * sorted_.ndim
wshape[axis] = 2
weights.shape = wshape
sumval = weights.sum()
# Use np.add.reduce (== np.sum but a little faster) to coerce data type
return np.add.reduce(sorted_[tuple(indexer)] * weights, axis=axis) / sumval
def percentileofscore(a, score, kind='rank'):
"""
Compute the percentile rank of a score relative to a list of scores.
A `percentileofscore` of, for example, 80% means that 80% of the
scores in `a` are below the given score. In the case of gaps or
ties, the exact definition depends on the optional keyword, `kind`.
Parameters
----------
a : array_like
Array of scores to which `score` is compared.
score : int or float
Score that is compared to the elements in `a`.
kind : {'rank', 'weak', 'strict', 'mean'}, optional
Specifies the interpretation of the resulting score.
The following options are available (default is 'rank'):
* 'rank': Average percentage ranking of score. In case of multiple
matches, average the percentage rankings of all matching scores.
* 'weak': This kind corresponds to the definition of a cumulative
distribution function. A percentileofscore of 80% means that 80%
of values are less than or equal to the provided score.
* 'strict': Similar to "weak", except that only values that are
strictly less than the given score are counted.
* 'mean': The average of the "weak" and "strict" scores, often used
in testing. See https://en.wikipedia.org/wiki/Percentile_rank
Returns
-------
pcos : float
Percentile-position of score (0-100) relative to `a`.
See Also
--------
numpy.percentile
Examples
--------
Three-quarters of the given values lie below a given score:
>>> from scipy import stats
>>> stats.percentileofscore([1, 2, 3, 4], 3)
75.0
With multiple matches, note how the scores of the two matches, 0.6
and 0.8 respectively, are averaged:
>>> stats.percentileofscore([1, 2, 3, 3, 4], 3)
70.0
Only 2/5 values are strictly less than 3:
>>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='strict')
40.0
But 4/5 values are less than or equal to 3:
>>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='weak')
80.0
The average between the weak and the strict scores is:
>>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='mean')
60.0
"""
if np.isnan(score):
return np.nan
a = np.asarray(a)
n = len(a)
if n == 0:
return 100.0
if kind == 'rank':
left = np.count_nonzero(a < score)
right = np.count_nonzero(a <= score)
pct = (right + left + (1 if right > left else 0)) * 50.0/n
return pct
elif kind == 'strict':
return np.count_nonzero(a < score) / n * 100
elif kind == 'weak':
return np.count_nonzero(a <= score) / n * 100
elif kind == 'mean':
pct = (np.count_nonzero(a < score) + np.count_nonzero(a <= score)) / n * 50
return pct
else:
raise ValueError("kind can only be 'rank', 'strict', 'weak' or 'mean'")
HistogramResult = namedtuple('HistogramResult',
('count', 'lowerlimit', 'binsize', 'extrapoints'))
def _histogram(a, numbins=10, defaultlimits=None, weights=None, printextras=False):
"""
Create a histogram.
Separate the range into several bins and return the number of instances
in each bin.
Parameters
----------
a : array_like
Array of scores which will be put into bins.
numbins : int, optional
The number of bins to use for the histogram. Default is 10.
defaultlimits : tuple (lower, upper), optional
The lower and upper values for the range of the histogram.
If no value is given, a range slightly larger than the range of the
values in a is used. Specifically ``(a.min() - s, a.max() + s)``,
where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``.
weights : array_like, optional
The weights for each value in `a`. Default is None, which gives each
value a weight of 1.0
printextras : bool, optional
If True, if there are extra points (i.e. the points that fall outside
the bin limits) a warning is raised saying how many of those points
there are. Default is False.
Returns
-------
count : ndarray
Number of points (or sum of weights) in each bin.
lowerlimit : float
Lowest value of histogram, the lower limit of the first bin.
binsize : float
The size of the bins (all bins have the same size).
extrapoints : int
The number of points outside the range of the histogram.
See Also
--------
numpy.histogram
Notes
-----
This histogram is based on numpy's histogram but has a larger range by
default if default limits is not set.
"""
a = np.ravel(a)
if defaultlimits is None:
if a.size == 0:
# handle empty arrays. Undetermined range, so use 0-1.
defaultlimits = (0, 1)
else:
# no range given, so use values in `a`
data_min = a.min()
data_max = a.max()
# Have bins extend past min and max values slightly
s = (data_max - data_min) / (2. * (numbins - 1.))
defaultlimits = (data_min - s, data_max + s)
# use numpy's histogram method to compute bins
hist, bin_edges = np.histogram(a, bins=numbins, range=defaultlimits,
weights=weights)
# hist are not always floats, convert to keep with old output
hist = np.array(hist, dtype=float)
# fixed width for bins is assumed, as numpy's histogram gives
# fixed width bins for int values for 'bins'
binsize = bin_edges[1] - bin_edges[0]
# calculate number of extra points
extrapoints = len([v for v in a
if defaultlimits[0] > v or v > defaultlimits[1]])
if extrapoints > 0 and printextras:
warnings.warn("Points outside given histogram range = %s"
% extrapoints)
return HistogramResult(hist, defaultlimits[0], binsize, extrapoints)
CumfreqResult = namedtuple('CumfreqResult',
('cumcount', 'lowerlimit', 'binsize',
'extrapoints'))
def cumfreq(a, numbins=10, defaultreallimits=None, weights=None):
"""
Return a cumulative frequency histogram, using the histogram function.
A cumulative histogram is a mapping that counts the cumulative number of
observations in all of the bins up to the specified bin.
Parameters
----------
a : array_like
Input array.
numbins : int, optional
The number of bins to use for the histogram. Default is 10.
defaultreallimits : tuple (lower, upper), optional
The lower and upper values for the range of the histogram.
If no value is given, a range slightly larger than the range of the
values in `a` is used. Specifically ``(a.min() - s, a.max() + s)``,
where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``.
weights : array_like, optional
The weights for each value in `a`. Default is None, which gives each
value a weight of 1.0
Returns
-------
cumcount : ndarray
Binned values of cumulative frequency.
lowerlimit : float
Lower real limit
binsize : float
Width of each bin.
extrapoints : int
Extra points.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from scipy import stats
>>> x = [1, 4, 2, 1, 3, 1]
>>> res = stats.cumfreq(x, numbins=4, defaultreallimits=(1.5, 5))
>>> res.cumcount
array([ 1., 2., 3., 3.])
>>> res.extrapoints
3
Create a normal distribution with 1000 random values
>>> rng = np.random.RandomState(seed=12345)
>>> samples = stats.norm.rvs(size=1000, random_state=rng)
Calculate cumulative frequencies
>>> res = stats.cumfreq(samples, numbins=25)
Calculate space of values for x
>>> x = res.lowerlimit + np.linspace(0, res.binsize*res.cumcount.size,
... res.cumcount.size)
Plot histogram and cumulative histogram
>>> fig = plt.figure(figsize=(10, 4))
>>> ax1 = fig.add_subplot(1, 2, 1)
>>> ax2 = fig.add_subplot(1, 2, 2)
>>> ax1.hist(samples, bins=25)
>>> ax1.set_title('Histogram')
>>> ax2.bar(x, res.cumcount, width=res.binsize)
>>> ax2.set_title('Cumulative histogram')
>>> ax2.set_xlim([x.min(), x.max()])
>>> plt.show()
"""
h, l, b, e = _histogram(a, numbins, defaultreallimits, weights=weights)
cumhist = np.cumsum(h * 1, axis=0)
return CumfreqResult(cumhist, l, b, e)
RelfreqResult = namedtuple('RelfreqResult',
('frequency', 'lowerlimit', 'binsize',
'extrapoints'))
def relfreq(a, numbins=10, defaultreallimits=None, weights=None):
"""
Return a relative frequency histogram, using the histogram function.
A relative frequency histogram is a mapping of the number of
observations in each of the bins relative to the total of observations.
Parameters
----------
a : array_like
Input array.
numbins : int, optional
The number of bins to use for the histogram. Default is 10.
defaultreallimits : tuple (lower, upper), optional
The lower and upper values for the range of the histogram.
If no value is given, a range slightly larger than the range of the
values in a is used. Specifically ``(a.min() - s, a.max() + s)``,
where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``.
weights : array_like, optional
The weights for each value in `a`. Default is None, which gives each
value a weight of 1.0
Returns
-------
frequency : ndarray
Binned values of relative frequency.
lowerlimit : float
Lower real limit.
binsize : float
Width of each bin.
extrapoints : int
Extra points.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from scipy import stats
>>> a = np.array([2, 4, 1, 2, 3, 2])
>>> res = stats.relfreq(a, numbins=4)
>>> res.frequency
array([ 0.16666667, 0.5 , 0.16666667, 0.16666667])
>>> np.sum(res.frequency) # relative frequencies should add up to 1
1.0
Create a normal distribution with 1000 random values
>>> rng = np.random.RandomState(seed=12345)
>>> samples = stats.norm.rvs(size=1000, random_state=rng)
Calculate relative frequencies
>>> res = stats.relfreq(samples, numbins=25)
Calculate space of values for x
>>> x = res.lowerlimit + np.linspace(0, res.binsize*res.frequency.size,
... res.frequency.size)
Plot relative frequency histogram
>>> fig = plt.figure(figsize=(5, 4))
>>> ax = fig.add_subplot(1, 1, 1)
>>> ax.bar(x, res.frequency, width=res.binsize)
>>> ax.set_title('Relative frequency histogram')
>>> ax.set_xlim([x.min(), x.max()])
>>> plt.show()
"""
a = np.asanyarray(a)
h, l, b, e = _histogram(a, numbins, defaultreallimits, weights=weights)
h = h / a.shape[0]
return RelfreqResult(h, l, b, e)
#####################################
# VARIABILITY FUNCTIONS #
#####################################
def obrientransform(*args):
"""
Compute the O'Brien transform on input data (any number of arrays).
Used to test for homogeneity of variance prior to running one-way stats.
Each array in ``*args`` is one level of a factor.
If `f_oneway` is run on the transformed data and found significant,
the variances are unequal. From Maxwell and Delaney [1]_, p.112.
Parameters
----------
args : tuple of array_like
Any number of arrays.
Returns
-------
obrientransform : ndarray
Transformed data for use in an ANOVA. The first dimension
of the result corresponds to the sequence of transformed
arrays. If the arrays given are all 1-D of the same length,
the return value is a 2-D array; otherwise it is a 1-D array
of type object, with each element being an ndarray.
References
----------
.. [1] S. E. Maxwell and H. D. Delaney, "Designing Experiments and
Analyzing Data: A Model Comparison Perspective", Wadsworth, 1990.
Examples
--------
We'll test the following data sets for differences in their variance.
>>> x = [10, 11, 13, 9, 7, 12, 12, 9, 10]
>>> y = [13, 21, 5, 10, 8, 14, 10, 12, 7, 15]
Apply the O'Brien transform to the data.
>>> from scipy.stats import obrientransform
>>> tx, ty = obrientransform(x, y)
Use `scipy.stats.f_oneway` to apply a one-way ANOVA test to the
transformed data.
>>> from scipy.stats import f_oneway
>>> F, p = f_oneway(tx, ty)
>>> p
0.1314139477040335
If we require that ``p < 0.05`` for significance, we cannot conclude
that the variances are different.
"""
TINY = np.sqrt(np.finfo(float).eps)
# `arrays` will hold the transformed arguments.
arrays = []
sLast = None
for arg in args:
a = np.asarray(arg)
n = len(a)
mu = np.mean(a)
sq = (a - mu)**2
sumsq = sq.sum()
# The O'Brien transform.
t = ((n - 1.5) * n * sq - 0.5 * sumsq) / ((n - 1) * (n - 2))
# Check that the mean of the transformed data is equal to the
# original variance.
var = sumsq / (n - 1)
if abs(var - np.mean(t)) > TINY:
raise ValueError('Lack of convergence in obrientransform.')
arrays.append(t)
sLast = a.shape
if sLast:
for arr in arrays[:-1]:
if sLast != arr.shape:
return np.array(arrays, dtype=object)
return np.array(arrays)
def sem(a, axis=0, ddof=1, nan_policy='propagate'):
"""
Compute standard error of the mean.
Calculate the standard error of the mean (or standard error of
measurement) of the values in the input array.
Parameters
----------
a : array_like
An array containing the values for which the standard error is
returned.
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over
the whole array `a`.
ddof : int, optional
Delta degrees-of-freedom. How many degrees of freedom to adjust
for bias in limited samples relative to the population estimate
of variance. Defaults to 1.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
s : ndarray or float
The standard error of the mean in the sample(s), along the input axis.
Notes
-----
The default value for `ddof` is different to the default (0) used by other
ddof containing routines, such as np.std and np.nanstd.
Examples
--------
Find standard error along the first axis:
>>> from scipy import stats
>>> a = np.arange(20).reshape(5,4)
>>> stats.sem(a)
array([ 2.8284, 2.8284, 2.8284, 2.8284])
Find standard error across the whole array, using n degrees of freedom:
>>> stats.sem(a, axis=None, ddof=0)
1.2893796958227628
"""
a, axis = _chk_asarray(a, axis)
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
a = ma.masked_invalid(a)
return mstats_basic.sem(a, axis, ddof)
n = a.shape[axis]
s = np.std(a, axis=axis, ddof=ddof) / np.sqrt(n)
return s
def _isconst(x):
"""
Check if all values in x are the same. nans are ignored.
x must be a 1d array.
The return value is a 1d array with length 1, so it can be used
in np.apply_along_axis.
"""
y = x[~np.isnan(x)]
if y.size == 0:
return np.array([True])
else:
return (y[0] == y).all(keepdims=True)
def _quiet_nanmean(x):
"""
Compute nanmean for the 1d array x, but quietly return nan if x is all nan.
The return value is a 1d array with length 1, so it can be used
in np.apply_along_axis.
"""
y = x[~np.isnan(x)]
if y.size == 0:
return np.array([np.nan])
else:
return np.mean(y, keepdims=True)
def _quiet_nanstd(x, ddof=0):
"""
Compute nanstd for the 1d array x, but quietly return nan if x is all nan.
The return value is a 1d array with length 1, so it can be used
in np.apply_along_axis.
"""
y = x[~np.isnan(x)]
if y.size == 0:
return np.array([np.nan])
else:
return np.std(y, keepdims=True, ddof=ddof)
def zscore(a, axis=0, ddof=0, nan_policy='propagate'):
"""
Compute the z score.
Compute the z score of each value in the sample, relative to the
sample mean and standard deviation.
Parameters
----------
a : array_like
An array like object containing the sample data.
axis : int or None, optional
Axis along which to operate. Default is 0. If None, compute over
the whole array `a`.
ddof : int, optional
Degrees of freedom correction in the calculation of the
standard deviation. Default is 0.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan. 'propagate' returns nan,
'raise' throws an error, 'omit' performs the calculations ignoring nan
values. Default is 'propagate'. Note that when the value is 'omit',
nans in the input also propagate to the output, but they do not affect
the z-scores computed for the non-nan values.
Returns
-------
zscore : array_like
The z-scores, standardized by mean and standard deviation of
input array `a`.
Notes
-----
This function preserves ndarray subclasses, and works also with
matrices and masked arrays (it uses `asanyarray` instead of
`asarray` for parameters).
Examples
--------
>>> a = np.array([ 0.7972, 0.0767, 0.4383, 0.7866, 0.8091,
... 0.1954, 0.6307, 0.6599, 0.1065, 0.0508])
>>> from scipy import stats
>>> stats.zscore(a)
array([ 1.1273, -1.247 , -0.0552, 1.0923, 1.1664, -0.8559, 0.5786,
0.6748, -1.1488, -1.3324])
Computing along a specified axis, using n-1 degrees of freedom
(``ddof=1``) to calculate the standard deviation:
>>> b = np.array([[ 0.3148, 0.0478, 0.6243, 0.4608],
... [ 0.7149, 0.0775, 0.6072, 0.9656],
... [ 0.6341, 0.1403, 0.9759, 0.4064],
... [ 0.5918, 0.6948, 0.904 , 0.3721],
... [ 0.0921, 0.2481, 0.1188, 0.1366]])
>>> stats.zscore(b, axis=1, ddof=1)
array([[-0.19264823, -1.28415119, 1.07259584, 0.40420358],
[ 0.33048416, -1.37380874, 0.04251374, 1.00081084],
[ 0.26796377, -1.12598418, 1.23283094, -0.37481053],
[-0.22095197, 0.24468594, 1.19042819, -1.21416216],
[-0.82780366, 1.4457416 , -0.43867764, -0.1792603 ]])
An example with `nan_policy='omit'`:
>>> x = np.array([[25.11, 30.10, np.nan, 32.02, 43.15],
... [14.95, 16.06, 121.25, 94.35, 29.81]])
>>> stats.zscore(x, axis=1, nan_policy='omit')
array([[-1.13490897, -0.37830299, nan, -0.08718406, 1.60039602],
[-0.91611681, -0.89090508, 1.4983032 , 0.88731639, -0.5785977 ]])
"""
return zmap(a, a, axis=axis, ddof=ddof, nan_policy=nan_policy)
def zmap(scores, compare, axis=0, ddof=0, nan_policy='propagate'):
"""
Calculate the relative z-scores.
Return an array of z-scores, i.e., scores that are standardized to
zero mean and unit variance, where mean and variance are calculated
from the comparison array.
Parameters
----------
scores : array_like
The input for which z-scores are calculated.
compare : array_like
The input from which the mean and standard deviation of the
normalization are taken; assumed to have the same dimension as
`scores`.
axis : int or None, optional
Axis over which mean and variance of `compare` are calculated.
Default is 0. If None, compute over the whole array `scores`.
ddof : int, optional
Degrees of freedom correction in the calculation of the
standard deviation. Default is 0.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle the occurrence of nans in `compare`.
'propagate' returns nan, 'raise' raises an exception, 'omit'
performs the calculations ignoring nan values. Default is
'propagate'. Note that when the value is 'omit', nans in `scores`
also propagate to the output, but they do not affect the z-scores
computed for the non-nan values.
Returns
-------
zscore : array_like
Z-scores, in the same shape as `scores`.
Notes
-----
This function preserves ndarray subclasses, and works also with
matrices and masked arrays (it uses `asanyarray` instead of
`asarray` for parameters).
Examples
--------
>>> from scipy.stats import zmap
>>> a = [0.5, 2.0, 2.5, 3]
>>> b = [0, 1, 2, 3, 4]
>>> zmap(a, b)
array([-1.06066017, 0. , 0.35355339, 0.70710678])
"""
a = np.asanyarray(compare)
if a.size == 0:
return np.empty(a.shape)
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
if axis is None:
mn = _quiet_nanmean(a.ravel())
std = _quiet_nanstd(a.ravel(), ddof=ddof)
isconst = _isconst(a.ravel())
else:
mn = np.apply_along_axis(_quiet_nanmean, axis, a)
std = np.apply_along_axis(_quiet_nanstd, axis, a, ddof=ddof)
isconst = np.apply_along_axis(_isconst, axis, a)
else:
mn = a.mean(axis=axis, keepdims=True)
std = a.std(axis=axis, ddof=ddof, keepdims=True)
if axis is None:
isconst = (a.item(0) == a).all()
else:
isconst = (_first(a, axis) == a).all(axis=axis, keepdims=True)
# Set std deviations that are 0 to 1 to avoid division by 0.
std[isconst] = 1.0
z = (scores - mn) / std
# Set the outputs associated with a constant input to nan.
z[np.broadcast_to(isconst, z.shape)] = np.nan
return z
def gstd(a, axis=0, ddof=1):
"""
Calculate the geometric standard deviation of an array.
The geometric standard deviation describes the spread of a set of numbers
where the geometric mean is preferred. It is a multiplicative factor, and
so a dimensionless quantity.
It is defined as the exponent of the standard deviation of ``log(a)``.
Mathematically the population geometric standard deviation can be
evaluated as::
gstd = exp(std(log(a)))
.. versionadded:: 1.3.0
Parameters
----------
a : array_like
An array like object containing the sample data.
axis : int, tuple or None, optional
Axis along which to operate. Default is 0. If None, compute over
the whole array `a`.
ddof : int, optional
Degree of freedom correction in the calculation of the
geometric standard deviation. Default is 1.
Returns
-------
ndarray or float
An array of the geometric standard deviation. If `axis` is None or `a`
is a 1d array a float is returned.
Notes
-----
As the calculation requires the use of logarithms the geometric standard
deviation only supports strictly positive values. Any non-positive or
infinite values will raise a `ValueError`.
The geometric standard deviation is sometimes confused with the exponent of
the standard deviation, ``exp(std(a))``. Instead the geometric standard
deviation is ``exp(std(log(a)))``.
The default value for `ddof` is different to the default value (0) used
by other ddof containing functions, such as ``np.std`` and ``np.nanstd``.
Examples
--------
Find the geometric standard deviation of a log-normally distributed sample.
Note that the standard deviation of the distribution is one, on a
log scale this evaluates to approximately ``exp(1)``.
>>> from scipy.stats import gstd
>>> np.random.seed(123)
>>> sample = np.random.lognormal(mean=0, sigma=1, size=1000)
>>> gstd(sample)
2.7217860664589946
Compute the geometric standard deviation of a multidimensional array and
of a given axis.
>>> a = np.arange(1, 25).reshape(2, 3, 4)
>>> gstd(a, axis=None)
2.2944076136018947
>>> gstd(a, axis=2)
array([[1.82424757, 1.22436866, 1.13183117],
[1.09348306, 1.07244798, 1.05914985]])
>>> gstd(a, axis=(1,2))
array([2.12939215, 1.22120169])
The geometric standard deviation further handles masked arrays.
>>> a = np.arange(1, 25).reshape(2, 3, 4)
>>> ma = np.ma.masked_where(a > 16, a)
>>> ma
masked_array(
data=[[[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]],
[[13, 14, 15, 16],
[--, --, --, --],
[--, --, --, --]]],
mask=[[[False, False, False, False],
[False, False, False, False],
[False, False, False, False]],
[[False, False, False, False],
[ True, True, True, True],
[ True, True, True, True]]],
fill_value=999999)
>>> gstd(ma, axis=2)
masked_array(
data=[[1.8242475707663655, 1.2243686572447428, 1.1318311657788478],
[1.0934830582350938, --, --]],
mask=[[False, False, False],
[False, True, True]],
fill_value=999999)
"""
a = np.asanyarray(a)
log = ma.log if isinstance(a, ma.MaskedArray) else np.log
try:
with warnings.catch_warnings():
warnings.simplefilter("error", RuntimeWarning)
return np.exp(np.std(log(a), axis=axis, ddof=ddof))
except RuntimeWarning as w:
if np.isinf(a).any():
raise ValueError(
'Infinite value encountered. The geometric standard deviation '
'is defined for strictly positive values only.'
) from w
a_nan = np.isnan(a)
a_nan_any = a_nan.any()
# exclude NaN's from negativity check, but
# avoid expensive masking for arrays with no NaN
if ((a_nan_any and np.less_equal(np.nanmin(a), 0)) or
(not a_nan_any and np.less_equal(a, 0).any())):
raise ValueError(
'Non positive value encountered. The geometric standard '
'deviation is defined for strictly positive values only.'
) from w
elif 'Degrees of freedom <= 0 for slice' == str(w):
raise ValueError(w) from w
else:
# Remaining warnings don't need to be exceptions.
return np.exp(np.std(log(a, where=~a_nan), axis=axis, ddof=ddof))
except TypeError as e:
raise ValueError(
'Invalid array input. The inputs could not be '
'safely coerced to any supported types') from e
# Private dictionary initialized only once at module level
# See https://en.wikipedia.org/wiki/Robust_measures_of_scale
_scale_conversions = {'raw': 1.0,
'normal': special.erfinv(0.5) * 2.0 * math.sqrt(2.0)}
def iqr(x, axis=None, rng=(25, 75), scale=1.0, nan_policy='propagate',
interpolation='linear', keepdims=False):
r"""
Compute the interquartile range of the data along the specified axis.
The interquartile range (IQR) is the difference between the 75th and
25th percentile of the data. It is a measure of the dispersion
similar to standard deviation or variance, but is much more robust
against outliers [2]_.
The ``rng`` parameter allows this function to compute other
percentile ranges than the actual IQR. For example, setting
``rng=(0, 100)`` is equivalent to `numpy.ptp`.
The IQR of an empty array is `np.nan`.
.. versionadded:: 0.18.0
Parameters
----------
x : array_like
Input array or object that can be converted to an array.
axis : int or sequence of int, optional
Axis along which the range is computed. The default is to
compute the IQR for the entire array.
rng : Two-element sequence containing floats in range of [0,100] optional
Percentiles over which to compute the range. Each must be
between 0 and 100, inclusive. The default is the true IQR:
`(25, 75)`. The order of the elements is not important.
scale : scalar or str, optional
The numerical value of scale will be divided out of the final
result. The following string values are recognized:
* 'raw' : No scaling, just return the raw IQR.
**Deprecated!** Use `scale=1` instead.
* 'normal' : Scale by
:math:`2 \sqrt{2} erf^{-1}(\frac{1}{2}) \approx 1.349`.
The default is 1.0. The use of scale='raw' is deprecated.
Array-like scale is also allowed, as long
as it broadcasts correctly to the output such that
``out / scale`` is a valid operation. The output dimensions
depend on the input array, `x`, the `axis` argument, and the
`keepdims` flag.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}, optional
Specifies the interpolation method to use when the percentile
boundaries lie between two data points `i` and `j`.
The following options are available (default is 'linear'):
* 'linear': `i + (j - i) * fraction`, where `fraction` is the
fractional part of the index surrounded by `i` and `j`.
* 'lower': `i`.
* 'higher': `j`.
* 'nearest': `i` or `j` whichever is nearest.
* 'midpoint': `(i + j) / 2`.
keepdims : bool, optional
If this is set to `True`, the reduced axes are left in the
result as dimensions with size one. With this option, the result
will broadcast correctly against the original array `x`.
Returns
-------
iqr : scalar or ndarray
If ``axis=None``, a scalar is returned. If the input contains
integers or floats of smaller precision than ``np.float64``, then the
output data-type is ``np.float64``. Otherwise, the output data-type is
the same as that of the input.
See Also
--------
numpy.std, numpy.var
Notes
-----
This function is heavily dependent on the version of `numpy` that is
installed. Versions greater than 1.11.0b3 are highly recommended, as they
include a number of enhancements and fixes to `numpy.percentile` and
`numpy.nanpercentile` that affect the operation of this function. The
following modifications apply:
Below 1.10.0 : `nan_policy` is poorly defined.
The default behavior of `numpy.percentile` is used for 'propagate'. This
is a hybrid of 'omit' and 'propagate' that mostly yields a skewed
version of 'omit' since NaNs are sorted to the end of the data. A
warning is raised if there are NaNs in the data.
Below 1.9.0: `numpy.nanpercentile` does not exist.
This means that `numpy.percentile` is used regardless of `nan_policy`
and a warning is issued. See previous item for a description of the
behavior.
Below 1.9.0: `keepdims` and `interpolation` are not supported.
The keywords get ignored with a warning if supplied with non-default
values. However, multiple axes are still supported.
References
----------
.. [1] "Interquartile range" https://en.wikipedia.org/wiki/Interquartile_range
.. [2] "Robust measures of scale" https://en.wikipedia.org/wiki/Robust_measures_of_scale
.. [3] "Quantile" https://en.wikipedia.org/wiki/Quantile
Examples
--------
>>> from scipy.stats import iqr
>>> x = np.array([[10, 7, 4], [3, 2, 1]])
>>> x
array([[10, 7, 4],
[ 3, 2, 1]])
>>> iqr(x)
4.0
>>> iqr(x, axis=0)
array([ 3.5, 2.5, 1.5])
>>> iqr(x, axis=1)
array([ 3., 1.])
>>> iqr(x, axis=1, keepdims=True)
array([[ 3.],
[ 1.]])
"""
x = asarray(x)
# This check prevents percentile from raising an error later. Also, it is
# consistent with `np.var` and `np.std`.
if not x.size:
return np.nan
# An error may be raised here, so fail-fast, before doing lengthy
# computations, even though `scale` is not used until later
if isinstance(scale, str):
scale_key = scale.lower()
if scale_key not in _scale_conversions:
raise ValueError("{0} not a valid scale for `iqr`".format(scale))
if scale_key == 'raw':
warnings.warn(
"use of scale='raw' is deprecated, use scale=1.0 instead",
np.VisibleDeprecationWarning
)
scale = _scale_conversions[scale_key]
# Select the percentile function to use based on nans and policy
contains_nan, nan_policy = _contains_nan(x, nan_policy)
if contains_nan and nan_policy == 'omit':
percentile_func = np.nanpercentile
else:
percentile_func = np.percentile
if len(rng) != 2:
raise TypeError("quantile range must be two element sequence")
if np.isnan(rng).any():
raise ValueError("range must not contain NaNs")
rng = sorted(rng)
pct = percentile_func(x, rng, axis=axis, interpolation=interpolation,
keepdims=keepdims)
out = np.subtract(pct[1], pct[0])
if scale != 1.0:
out /= scale
return out
def _mad_1d(x, center, nan_policy):
# Median absolute deviation for 1-d array x.
# This is a helper function for `median_abs_deviation`; it assumes its
# arguments have been validated already. In particular, x must be a
# 1-d numpy array, center must be callable, and if nan_policy is not
# 'propagate', it is assumed to be 'omit', because 'raise' is handled
# in `median_abs_deviation`.
# No warning is generated if x is empty or all nan.
isnan = np.isnan(x)
if isnan.any():
if nan_policy == 'propagate':
return np.nan
x = x[~isnan]
if x.size == 0:
# MAD of an empty array is nan.
return np.nan
# Edge cases have been handled, so do the basic MAD calculation.
med = center(x)
mad = np.median(np.abs(x - med))
return mad
def median_abs_deviation(x, axis=0, center=np.median, scale=1.0,
nan_policy='propagate'):
r"""
Compute the median absolute deviation of the data along the given axis.
The median absolute deviation (MAD, [1]_) computes the median over the
absolute deviations from the median. It is a measure of dispersion
similar to the standard deviation but more robust to outliers [2]_.
The MAD of an empty array is ``np.nan``.
.. versionadded:: 1.5.0
Parameters
----------
x : array_like
Input array or object that can be converted to an array.
axis : int or None, optional
Axis along which the range is computed. Default is 0. If None, compute
the MAD over the entire array.
center : callable, optional
A function that will return the central value. The default is to use
np.median. Any user defined function used will need to have the
function signature ``func(arr, axis)``.
scale : scalar or str, optional
The numerical value of scale will be divided out of the final
result. The default is 1.0. The string "normal" is also accepted,
and results in `scale` being the inverse of the standard normal
quantile function at 0.75, which is approximately 0.67449.
Array-like scale is also allowed, as long as it broadcasts correctly
to the output such that ``out / scale`` is a valid operation. The
output dimensions depend on the input array, `x`, and the `axis`
argument.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
mad : scalar or ndarray
If ``axis=None``, a scalar is returned. If the input contains
integers or floats of smaller precision than ``np.float64``, then the
output data-type is ``np.float64``. Otherwise, the output data-type is
the same as that of the input.
See Also
--------
numpy.std, numpy.var, numpy.median, scipy.stats.iqr, scipy.stats.tmean,
scipy.stats.tstd, scipy.stats.tvar
Notes
-----
The `center` argument only affects the calculation of the central value
around which the MAD is calculated. That is, passing in ``center=np.mean``
will calculate the MAD around the mean - it will not calculate the *mean*
absolute deviation.
The input array may contain `inf`, but if `center` returns `inf`, the
corresponding MAD for that data will be `nan`.
References
----------
.. [1] "Median absolute deviation",
https://en.wikipedia.org/wiki/Median_absolute_deviation
.. [2] "Robust measures of scale",
https://en.wikipedia.org/wiki/Robust_measures_of_scale
Examples
--------
When comparing the behavior of `median_abs_deviation` with ``np.std``,
the latter is affected when we change a single value of an array to have an
outlier value while the MAD hardly changes:
>>> from scipy import stats
>>> x = stats.norm.rvs(size=100, scale=1, random_state=123456)
>>> x.std()
0.9973906394005013
>>> stats.median_abs_deviation(x)
0.82832610097857
>>> x[0] = 345.6
>>> x.std()
34.42304872314415
>>> stats.median_abs_deviation(x)
0.8323442311590675
Axis handling example:
>>> x = np.array([[10, 7, 4], [3, 2, 1]])
>>> x
array([[10, 7, 4],
[ 3, 2, 1]])
>>> stats.median_abs_deviation(x)
array([3.5, 2.5, 1.5])
>>> stats.median_abs_deviation(x, axis=None)
2.0
Scale normal example:
>>> x = stats.norm.rvs(size=1000000, scale=2, random_state=123456)
>>> stats.median_abs_deviation(x)
1.3487398527041636
>>> stats.median_abs_deviation(x, scale='normal')
1.9996446978061115
"""
if not callable(center):
raise TypeError("The argument 'center' must be callable. The given "
f"value {repr(center)} is not callable.")
# An error may be raised here, so fail-fast, before doing lengthy
# computations, even though `scale` is not used until later
if isinstance(scale, str):
if scale.lower() == 'normal':
scale = 0.6744897501960817 # special.ndtri(0.75)
else:
raise ValueError(f"{scale} is not a valid scale value.")
x = asarray(x)
# Consistent with `np.var` and `np.std`.
if not x.size:
if axis is None:
return np.nan
nan_shape = tuple(item for i, item in enumerate(x.shape) if i != axis)
if nan_shape == ():
# Return nan, not array(nan)
return np.nan
return np.full(nan_shape, np.nan)
contains_nan, nan_policy = _contains_nan(x, nan_policy)
if contains_nan:
if axis is None:
mad = _mad_1d(x.ravel(), center, nan_policy)
else:
mad = np.apply_along_axis(_mad_1d, axis, x, center, nan_policy)
else:
if axis is None:
med = center(x, axis=None)
mad = np.median(np.abs(x - med))
else:
# Wrap the call to center() in expand_dims() so it acts like
# keepdims=True was used.
med = np.expand_dims(center(x, axis=axis), axis)
mad = np.median(np.abs(x - med), axis=axis)
return mad / scale
# Keep the top newline so that the message does not show up on the stats page
_median_absolute_deviation_deprec_msg = """
To preserve the existing default behavior, use
`scipy.stats.median_abs_deviation(..., scale=1/1.4826)`.
The value 1.4826 is not numerically precise for scaling
with a normal distribution. For a numerically precise value, use
`scipy.stats.median_abs_deviation(..., scale='normal')`.
"""
# Due to numpy/gh-16349 we need to unindent the entire docstring
@np.deprecate(old_name='median_absolute_deviation',
new_name='median_abs_deviation',
message=_median_absolute_deviation_deprec_msg)
def median_absolute_deviation(x, axis=0, center=np.median, scale=1.4826,
nan_policy='propagate'):
r"""
Compute the median absolute deviation of the data along the given axis.
The median absolute deviation (MAD, [1]_) computes the median over the
absolute deviations from the median. It is a measure of dispersion
similar to the standard deviation but more robust to outliers [2]_.
The MAD of an empty array is ``np.nan``.
.. versionadded:: 1.3.0
Parameters
----------
x : array_like
Input array or object that can be converted to an array.
axis : int or None, optional
Axis along which the range is computed. Default is 0. If None, compute
the MAD over the entire array.
center : callable, optional
A function that will return the central value. The default is to use
np.median. Any user defined function used will need to have the function
signature ``func(arr, axis)``.
scale : int, optional
The scaling factor applied to the MAD. The default scale (1.4826)
ensures consistency with the standard deviation for normally distributed
data.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
mad : scalar or ndarray
If ``axis=None``, a scalar is returned. If the input contains
integers or floats of smaller precision than ``np.float64``, then the
output data-type is ``np.float64``. Otherwise, the output data-type is
the same as that of the input.
See Also
--------
numpy.std, numpy.var, numpy.median, scipy.stats.iqr, scipy.stats.tmean,
scipy.stats.tstd, scipy.stats.tvar
Notes
-----
The `center` argument only affects the calculation of the central value
around which the MAD is calculated. That is, passing in ``center=np.mean``
will calculate the MAD around the mean - it will not calculate the *mean*
absolute deviation.
References
----------
.. [1] "Median absolute deviation",
https://en.wikipedia.org/wiki/Median_absolute_deviation
.. [2] "Robust measures of scale",
https://en.wikipedia.org/wiki/Robust_measures_of_scale
Examples
--------
When comparing the behavior of `median_absolute_deviation` with ``np.std``,
the latter is affected when we change a single value of an array to have an
outlier value while the MAD hardly changes:
>>> from scipy import stats
>>> x = stats.norm.rvs(size=100, scale=1, random_state=123456)
>>> x.std()
0.9973906394005013
>>> stats.median_absolute_deviation(x)
1.2280762773108278
>>> x[0] = 345.6
>>> x.std()
34.42304872314415
>>> stats.median_absolute_deviation(x)
1.2340335571164334
Axis handling example:
>>> x = np.array([[10, 7, 4], [3, 2, 1]])
>>> x
array([[10, 7, 4],
[ 3, 2, 1]])
>>> stats.median_absolute_deviation(x)
array([5.1891, 3.7065, 2.2239])
>>> stats.median_absolute_deviation(x, axis=None)
2.9652
"""
if isinstance(scale, str):
if scale.lower() == 'raw':
warnings.warn(
"use of scale='raw' is deprecated, use scale=1.0 instead",
np.VisibleDeprecationWarning
)
scale = 1.0
if not isinstance(scale, str):
scale = 1 / scale
return median_abs_deviation(x, axis=axis, center=center, scale=scale,
nan_policy=nan_policy)
#####################################
# TRIMMING FUNCTIONS #
#####################################
SigmaclipResult = namedtuple('SigmaclipResult', ('clipped', 'lower', 'upper'))
def sigmaclip(a, low=4., high=4.):
"""
Perform iterative sigma-clipping of array elements.
Starting from the full sample, all elements outside the critical range are
removed, i.e. all elements of the input array `c` that satisfy either of
the following conditions::
c < mean(c) - std(c)*low
c > mean(c) + std(c)*high
The iteration continues with the updated sample until no
elements are outside the (updated) range.
Parameters
----------
a : array_like
Data array, will be raveled if not 1-D.
low : float, optional
Lower bound factor of sigma clipping. Default is 4.
high : float, optional
Upper bound factor of sigma clipping. Default is 4.
Returns
-------
clipped : ndarray
Input array with clipped elements removed.
lower : float
Lower threshold value use for clipping.
upper : float
Upper threshold value use for clipping.
Examples
--------
>>> from scipy.stats import sigmaclip
>>> a = np.concatenate((np.linspace(9.5, 10.5, 31),
... np.linspace(0, 20, 5)))
>>> fact = 1.5
>>> c, low, upp = sigmaclip(a, fact, fact)
>>> c
array([ 9.96666667, 10. , 10.03333333, 10. ])
>>> c.var(), c.std()
(0.00055555555555555165, 0.023570226039551501)
>>> low, c.mean() - fact*c.std(), c.min()
(9.9646446609406727, 9.9646446609406727, 9.9666666666666668)
>>> upp, c.mean() + fact*c.std(), c.max()
(10.035355339059327, 10.035355339059327, 10.033333333333333)
>>> a = np.concatenate((np.linspace(9.5, 10.5, 11),
... np.linspace(-100, -50, 3)))
>>> c, low, upp = sigmaclip(a, 1.8, 1.8)
>>> (c == np.linspace(9.5, 10.5, 11)).all()
True
"""
c = np.asarray(a).ravel()
delta = 1
while delta:
c_std = c.std()
c_mean = c.mean()
size = c.size
critlower = c_mean - c_std * low
critupper = c_mean + c_std * high
c = c[(c >= critlower) & (c <= critupper)]
delta = size - c.size
return SigmaclipResult(c, critlower, critupper)
def trimboth(a, proportiontocut, axis=0):
"""
Slice off a proportion of items from both ends of an array.
Slice off the passed proportion of items from both ends of the passed
array (i.e., with `proportiontocut` = 0.1, slices leftmost 10% **and**
rightmost 10% of scores). The trimmed values are the lowest and
highest ones.
Slice off less if proportion results in a non-integer slice index (i.e.
conservatively slices off `proportiontocut`).
Parameters
----------
a : array_like
Data to trim.
proportiontocut : float
Proportion (in range 0-1) of total data set to trim of each end.
axis : int or None, optional
Axis along which to trim data. Default is 0. If None, compute over
the whole array `a`.
Returns
-------
out : ndarray
Trimmed version of array `a`. The order of the trimmed content
is undefined.
See Also
--------
trim_mean
Examples
--------
>>> from scipy import stats
>>> a = np.arange(20)
>>> b = stats.trimboth(a, 0.1)
>>> b.shape
(16,)
"""
a = np.asarray(a)
if a.size == 0:
return a
if axis is None:
a = a.ravel()
axis = 0
nobs = a.shape[axis]
lowercut = int(proportiontocut * nobs)
uppercut = nobs - lowercut
if (lowercut >= uppercut):
raise ValueError("Proportion too big.")
atmp = np.partition(a, (lowercut, uppercut - 1), axis)
sl = [slice(None)] * atmp.ndim
sl[axis] = slice(lowercut, uppercut)
return atmp[tuple(sl)]
def trim1(a, proportiontocut, tail='right', axis=0):
"""
Slice off a proportion from ONE end of the passed array distribution.
If `proportiontocut` = 0.1, slices off 'leftmost' or 'rightmost'
10% of scores. The lowest or highest values are trimmed (depending on
the tail).
Slice off less if proportion results in a non-integer slice index
(i.e. conservatively slices off `proportiontocut` ).
Parameters
----------
a : array_like
Input array.
proportiontocut : float
Fraction to cut off of 'left' or 'right' of distribution.
tail : {'left', 'right'}, optional
Defaults to 'right'.
axis : int or None, optional
Axis along which to trim data. Default is 0. If None, compute over
the whole array `a`.
Returns
-------
trim1 : ndarray
Trimmed version of array `a`. The order of the trimmed content is
undefined.
"""
a = np.asarray(a)
if axis is None:
a = a.ravel()
axis = 0
nobs = a.shape[axis]
# avoid possible corner case
if proportiontocut >= 1:
return []
if tail.lower() == 'right':
lowercut = 0
uppercut = nobs - int(proportiontocut * nobs)
elif tail.lower() == 'left':
lowercut = int(proportiontocut * nobs)
uppercut = nobs
atmp = np.partition(a, (lowercut, uppercut - 1), axis)
return atmp[lowercut:uppercut]
def trim_mean(a, proportiontocut, axis=0):
"""
Return mean of array after trimming distribution from both tails.
If `proportiontocut` = 0.1, slices off 'leftmost' and 'rightmost' 10% of
scores. The input is sorted before slicing. Slices off less if proportion
results in a non-integer slice index (i.e., conservatively slices off
`proportiontocut` ).
Parameters
----------
a : array_like
Input array.
proportiontocut : float
Fraction to cut off of both tails of the distribution.
axis : int or None, optional
Axis along which the trimmed means are computed. Default is 0.
If None, compute over the whole array `a`.
Returns
-------
trim_mean : ndarray
Mean of trimmed array.
See Also
--------
trimboth
tmean : Compute the trimmed mean ignoring values outside given `limits`.
Examples
--------
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.trim_mean(x, 0.1)
9.5
>>> x2 = x.reshape(5, 4)
>>> x2
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18, 19]])
>>> stats.trim_mean(x2, 0.25)
array([ 8., 9., 10., 11.])
>>> stats.trim_mean(x2, 0.25, axis=1)
array([ 1.5, 5.5, 9.5, 13.5, 17.5])
"""
a = np.asarray(a)
if a.size == 0:
return np.nan
if axis is None:
a = a.ravel()
axis = 0
nobs = a.shape[axis]
lowercut = int(proportiontocut * nobs)
uppercut = nobs - lowercut
if (lowercut > uppercut):
raise ValueError("Proportion too big.")
atmp = np.partition(a, (lowercut, uppercut - 1), axis)
sl = [slice(None)] * atmp.ndim
sl[axis] = slice(lowercut, uppercut)
return np.mean(atmp[tuple(sl)], axis=axis)
F_onewayResult = namedtuple('F_onewayResult', ('statistic', 'pvalue'))
class F_onewayConstantInputWarning(RuntimeWarning):
"""
Warning generated by `f_oneway` when an input is constant, e.g.
each of the samples provided is a constant array.
"""
def __init__(self, msg=None):
if msg is None:
msg = ("Each of the input arrays is constant;"
"the F statistic is not defined or infinite")
self.args = (msg,)
class F_onewayBadInputSizesWarning(RuntimeWarning):
"""
Warning generated by `f_oneway` when an input has length 0,
or if all the inputs have length 1.
"""
pass
def _create_f_oneway_nan_result(shape, axis):
"""
This is a helper function for f_oneway for creating the return values
in certain degenerate conditions. It creates return values that are
all nan with the appropriate shape for the given `shape` and `axis`.
"""
axis = np.core.multiarray.normalize_axis_index(axis, len(shape))
shp = shape[:axis] + shape[axis+1:]
if shp == ():
f = np.nan
prob = np.nan
else:
f = np.full(shp, fill_value=np.nan)
prob = f.copy()
return F_onewayResult(f, prob)
def _first(arr, axis):
"""
Return arr[..., 0:1, ...] where 0:1 is in the `axis` position.
"""
return np.take_along_axis(arr, np.array(0, ndmin=arr.ndim), axis)
def f_oneway(*args, axis=0):
"""
Perform one-way ANOVA.
The one-way ANOVA tests the null hypothesis that two or more groups have
the same population mean. The test is applied to samples from two or
more groups, possibly with differing sizes.
Parameters
----------
sample1, sample2, ... : array_like
The sample measurements for each group. There must be at least
two arguments. If the arrays are multidimensional, then all the
dimensions of the array must be the same except for `axis`.
axis : int, optional
Axis of the input arrays along which the test is applied.
Default is 0.
Returns
-------
statistic : float
The computed F statistic of the test.
pvalue : float
The associated p-value from the F distribution.
Warns
-----
F_onewayConstantInputWarning
Raised if each of the input arrays is constant array.
In this case the F statistic is either infinite or isn't defined,
so ``np.inf`` or ``np.nan`` is returned.
F_onewayBadInputSizesWarning
Raised if the length of any input array is 0, or if all the input
arrays have length 1. ``np.nan`` is returned for the F statistic
and the p-value in these cases.
Notes
-----
The ANOVA test has important assumptions that must be satisfied in order
for the associated p-value to be valid.
1. The samples are independent.
2. Each sample is from a normally distributed population.
3. The population standard deviations of the groups are all equal. This
property is known as homoscedasticity.
If these assumptions are not true for a given set of data, it may still
be possible to use the Kruskal-Wallis H-test (`scipy.stats.kruskal`)
although with some loss of power.
The length of each group must be at least one, and there must be at
least one group with length greater than one. If these conditions
are not satisfied, a warning is generated and (``np.nan``, ``np.nan``)
is returned.
If each group contains constant values, and there exist at least two
groups with different values, the function generates a warning and
returns (``np.inf``, 0).
If all values in all groups are the same, function generates a warning
and returns (``np.nan``, ``np.nan``).
The algorithm is from Heiman [2]_, pp.394-7.
References
----------
.. [1] R. Lowry, "Concepts and Applications of Inferential Statistics",
Chapter 14, 2014, http://vassarstats.net/textbook/
.. [2] G.W. Heiman, "Understanding research methods and statistics: An
integrated introduction for psychology", Houghton, Mifflin and
Company, 2001.
.. [3] G.H. McDonald, "Handbook of Biological Statistics", One-way ANOVA.
http://www.biostathandbook.com/onewayanova.html
Examples
--------
>>> from scipy.stats import f_oneway
Here are some data [3]_ on a shell measurement (the length of the anterior
adductor muscle scar, standardized by dividing by length) in the mussel
Mytilus trossulus from five locations: Tillamook, Oregon; Newport, Oregon;
Petersburg, Alaska; Magadan, Russia; and Tvarminne, Finland, taken from a
much larger data set used in McDonald et al. (1991).
>>> tillamook = [0.0571, 0.0813, 0.0831, 0.0976, 0.0817, 0.0859, 0.0735,
... 0.0659, 0.0923, 0.0836]
>>> newport = [0.0873, 0.0662, 0.0672, 0.0819, 0.0749, 0.0649, 0.0835,
... 0.0725]
>>> petersburg = [0.0974, 0.1352, 0.0817, 0.1016, 0.0968, 0.1064, 0.105]
>>> magadan = [0.1033, 0.0915, 0.0781, 0.0685, 0.0677, 0.0697, 0.0764,
... 0.0689]
>>> tvarminne = [0.0703, 0.1026, 0.0956, 0.0973, 0.1039, 0.1045]
>>> f_oneway(tillamook, newport, petersburg, magadan, tvarminne)
F_onewayResult(statistic=7.121019471642447, pvalue=0.0002812242314534544)
`f_oneway` accepts multidimensional input arrays. When the inputs
are multidimensional and `axis` is not given, the test is performed
along the first axis of the input arrays. For the following data, the
test is performed three times, once for each column.
>>> a = np.array([[9.87, 9.03, 6.81],
... [7.18, 8.35, 7.00],
... [8.39, 7.58, 7.68],
... [7.45, 6.33, 9.35],
... [6.41, 7.10, 9.33],
... [8.00, 8.24, 8.44]])
>>> b = np.array([[6.35, 7.30, 7.16],
... [6.65, 6.68, 7.63],
... [5.72, 7.73, 6.72],
... [7.01, 9.19, 7.41],
... [7.75, 7.87, 8.30],
... [6.90, 7.97, 6.97]])
>>> c = np.array([[3.31, 8.77, 1.01],
... [8.25, 3.24, 3.62],
... [6.32, 8.81, 5.19],
... [7.48, 8.83, 8.91],
... [8.59, 6.01, 6.07],
... [3.07, 9.72, 7.48]])
>>> F, p = f_oneway(a, b, c)
>>> F
array([1.75676344, 0.03701228, 3.76439349])
>>> p
array([0.20630784, 0.96375203, 0.04733157])
"""
if len(args) < 2:
raise TypeError(f'at least two inputs are required; got {len(args)}.')
args = [np.asarray(arg, dtype=float) for arg in args]
# ANOVA on N groups, each in its own array
num_groups = len(args)
# We haven't explicitly validated axis, but if it is bad, this call of
# np.concatenate will raise np.AxisError. The call will raise ValueError
# if the dimensions of all the arrays, except the axis dimension, are not
# the same.
alldata = np.concatenate(args, axis=axis)
bign = alldata.shape[axis]
# Check this after forming alldata, so shape errors are detected
# and reported before checking for 0 length inputs.
if any(arg.shape[axis] == 0 for arg in args):
warnings.warn(F_onewayBadInputSizesWarning('at least one input '
'has length 0'))
return _create_f_oneway_nan_result(alldata.shape, axis)
# Must have at least one group with length greater than 1.
if all(arg.shape[axis] == 1 for arg in args):
msg = ('all input arrays have length 1. f_oneway requires that at '
'least one input has length greater than 1.')
warnings.warn(F_onewayBadInputSizesWarning(msg))
return _create_f_oneway_nan_result(alldata.shape, axis)
# Check if the values within each group are constant, and if the common
# value in at least one group is different from that in another group.
# Based on https://github.com/scipy/scipy/issues/11669
# If axis=0, say, and the groups have shape (n0, ...), (n1, ...), ...,
# then is_const is a boolean array with shape (num_groups, ...).
# It is True if the groups along the axis slice are each consant.
# In the typical case where each input array is 1-d, is_const is a
# 1-d array with length num_groups.
is_const = np.concatenate([(_first(a, axis) == a).all(axis=axis,
keepdims=True)
for a in args], axis=axis)
# all_const is a boolean array with shape (...) (see previous comment).
# It is True if the values within each group along the axis slice are
# the same (e.g. [[3, 3, 3], [5, 5, 5, 5], [4, 4, 4]]).
all_const = is_const.all(axis=axis)
if all_const.any():
warnings.warn(F_onewayConstantInputWarning())
# all_same_const is True if all the values in the groups along the axis=0
# slice are the same (e.g. [[3, 3, 3], [3, 3, 3, 3], [3, 3, 3]]).
all_same_const = (_first(alldata, axis) == alldata).all(axis=axis)
# Determine the mean of the data, and subtract that from all inputs to a
# variance (via sum_of_sq / sq_of_sum) calculation. Variance is invariant
# to a shift in location, and centering all data around zero vastly
# improves numerical stability.
offset = alldata.mean(axis=axis, keepdims=True)
alldata -= offset
normalized_ss = _square_of_sums(alldata, axis=axis) / bign
sstot = _sum_of_squares(alldata, axis=axis) - normalized_ss
ssbn = 0
for a in args:
ssbn += _square_of_sums(a - offset, axis=axis) / a.shape[axis]
# Naming: variables ending in bn/b are for "between treatments", wn/w are
# for "within treatments"
ssbn -= normalized_ss
sswn = sstot - ssbn
dfbn = num_groups - 1
dfwn = bign - num_groups
msb = ssbn / dfbn
msw = sswn / dfwn
with np.errstate(divide='ignore', invalid='ignore'):
f = msb / msw
prob = special.fdtrc(dfbn, dfwn, f) # equivalent to stats.f.sf
# Fix any f values that should be inf or nan because the corresponding
# inputs were constant.
if np.isscalar(f):
if all_same_const:
f = np.nan
prob = np.nan
elif all_const:
f = np.inf
prob = 0.0
else:
f[all_const] = np.inf
prob[all_const] = 0.0
f[all_same_const] = np.nan
prob[all_same_const] = np.nan
return F_onewayResult(f, prob)
class PearsonRConstantInputWarning(RuntimeWarning):
"""Warning generated by `pearsonr` when an input is constant."""
def __init__(self, msg=None):
if msg is None:
msg = ("An input array is constant; the correlation coefficent "
"is not defined.")
self.args = (msg,)
class PearsonRNearConstantInputWarning(RuntimeWarning):
"""Warning generated by `pearsonr` when an input is nearly constant."""
def __init__(self, msg=None):
if msg is None:
msg = ("An input array is nearly constant; the computed "
"correlation coefficent may be inaccurate.")
self.args = (msg,)
def pearsonr(x, y):
r"""
Pearson correlation coefficient and p-value for testing non-correlation.
The Pearson correlation coefficient [1]_ measures the linear relationship
between two datasets. The calculation of the p-value relies on the
assumption that each dataset is normally distributed. (See Kowalski [3]_
for a discussion of the effects of non-normality of the input on the
distribution of the correlation coefficient.) Like other correlation
coefficients, this one varies between -1 and +1 with 0 implying no
correlation. Correlations of -1 or +1 imply an exact linear relationship.
Positive correlations imply that as x increases, so does y. Negative
correlations imply that as x increases, y decreases.
The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Pearson correlation at least as extreme
as the one computed from these datasets.
Parameters
----------
x : (N,) array_like
Input array.
y : (N,) array_like
Input array.
Returns
-------
r : float
Pearson's correlation coefficient.
p-value : float
Two-tailed p-value.
Warns
-----
PearsonRConstantInputWarning
Raised if an input is a constant array. The correlation coefficient
is not defined in this case, so ``np.nan`` is returned.
PearsonRNearConstantInputWarning
Raised if an input is "nearly" constant. The array ``x`` is considered
nearly constant if ``norm(x - mean(x)) < 1e-13 * abs(mean(x))``.
Numerical errors in the calculation ``x - mean(x)`` in this case might
result in an inaccurate calculation of r.
See Also
--------
spearmanr : Spearman rank-order correlation coefficient.
kendalltau : Kendall's tau, a correlation measure for ordinal data.
Notes
-----
The correlation coefficient is calculated as follows:
.. math::
r = \frac{\sum (x - m_x) (y - m_y)}
{\sqrt{\sum (x - m_x)^2 \sum (y - m_y)^2}}
where :math:`m_x` is the mean of the vector :math:`x` and :math:`m_y` is
the mean of the vector :math:`y`.
Under the assumption that :math:`x` and :math:`m_y` are drawn from
independent normal distributions (so the population correlation coefficient
is 0), the probability density function of the sample correlation
coefficient :math:`r` is ([1]_, [2]_):
.. math::
f(r) = \frac{{(1-r^2)}^{n/2-2}}{\mathrm{B}(\frac{1}{2},\frac{n}{2}-1)}
where n is the number of samples, and B is the beta function. This
is sometimes referred to as the exact distribution of r. This is
the distribution that is used in `pearsonr` to compute the p-value.
The distribution is a beta distribution on the interval [-1, 1],
with equal shape parameters a = b = n/2 - 1. In terms of SciPy's
implementation of the beta distribution, the distribution of r is::
dist = scipy.stats.beta(n/2 - 1, n/2 - 1, loc=-1, scale=2)
The p-value returned by `pearsonr` is a two-sided p-value. For a
given sample with correlation coefficient r, the p-value is
the probability that abs(r') of a random sample x' and y' drawn from
the population with zero correlation would be greater than or equal
to abs(r). In terms of the object ``dist`` shown above, the p-value
for a given r and length n can be computed as::
p = 2*dist.cdf(-abs(r))
When n is 2, the above continuous distribution is not well-defined.
One can interpret the limit of the beta distribution as the shape
parameters a and b approach a = b = 0 as a discrete distribution with
equal probability masses at r = 1 and r = -1. More directly, one
can observe that, given the data x = [x1, x2] and y = [y1, y2], and
assuming x1 != x2 and y1 != y2, the only possible values for r are 1
and -1. Because abs(r') for any sample x' and y' with length 2 will
be 1, the two-sided p-value for a sample of length 2 is always 1.
References
----------
.. [1] "Pearson correlation coefficient", Wikipedia,
https://en.wikipedia.org/wiki/Pearson_correlation_coefficient
.. [2] Student, "Probable error of a correlation coefficient",
Biometrika, Volume 6, Issue 2-3, 1 September 1908, pp. 302-310.
.. [3] C. J. Kowalski, "On the Effects of Non-Normality on the Distribution
of the Sample Product-Moment Correlation Coefficient"
Journal of the Royal Statistical Society. Series C (Applied
Statistics), Vol. 21, No. 1 (1972), pp. 1-12.
Examples
--------
>>> from scipy import stats
>>> a = np.array([0, 0, 0, 1, 1, 1, 1])
>>> b = np.arange(7)
>>> stats.pearsonr(a, b)
(0.8660254037844386, 0.011724811003954649)
>>> stats.pearsonr([1, 2, 3, 4, 5], [10, 9, 2.5, 6, 4])
(-0.7426106572325057, 0.1505558088534455)
"""
n = len(x)
if n != len(y):
raise ValueError('x and y must have the same length.')
if n < 2:
raise ValueError('x and y must have length at least 2.')
x = np.asarray(x)
y = np.asarray(y)
# If an input is constant, the correlation coefficient is not defined.
if (x == x[0]).all() or (y == y[0]).all():
warnings.warn(PearsonRConstantInputWarning())
return np.nan, np.nan
# dtype is the data type for the calculations. This expression ensures
# that the data type is at least 64 bit floating point. It might have
# more precision if the input is, for example, np.longdouble.
dtype = type(1.0 + x[0] + y[0])
if n == 2:
return dtype(np.sign(x[1] - x[0])*np.sign(y[1] - y[0])), 1.0
xmean = x.mean(dtype=dtype)
ymean = y.mean(dtype=dtype)
# By using `astype(dtype)`, we ensure that the intermediate calculations
# use at least 64 bit floating point.
xm = x.astype(dtype) - xmean
ym = y.astype(dtype) - ymean
# Unlike np.linalg.norm or the expression sqrt((xm*xm).sum()),
# scipy.linalg.norm(xm) does not overflow if xm is, for example,
# [-5e210, 5e210, 3e200, -3e200]
normxm = linalg.norm(xm)
normym = linalg.norm(ym)
threshold = 1e-13
if normxm < threshold*abs(xmean) or normym < threshold*abs(ymean):
# If all the values in x (likewise y) are very close to the mean,
# the loss of precision that occurs in the subtraction xm = x - xmean
# might result in large errors in r.
warnings.warn(PearsonRNearConstantInputWarning())
r = np.dot(xm/normxm, ym/normym)
# Presumably, if abs(r) > 1, then it is only some small artifact of
# floating point arithmetic.
r = max(min(r, 1.0), -1.0)
# As explained in the docstring, the p-value can be computed as
# p = 2*dist.cdf(-abs(r))
# where dist is the beta distribution on [-1, 1] with shape parameters
# a = b = n/2 - 1. `special.btdtr` is the CDF for the beta distribution
# on [0, 1]. To use it, we make the transformation x = (r + 1)/2; the
# shape parameters do not change. Then -abs(r) used in `cdf(-abs(r))`
# becomes x = (-abs(r) + 1)/2 = 0.5*(1 - abs(r)). (r is cast to float64
# to avoid a TypeError raised by btdtr when r is higher precision.)
ab = n/2 - 1
prob = 2*special.btdtr(ab, ab, 0.5*(1 - abs(np.float64(r))))
return r, prob
def fisher_exact(table, alternative='two-sided'):
"""
Perform a Fisher exact test on a 2x2 contingency table.
Parameters
----------
table : array_like of ints
A 2x2 contingency table. Elements should be non-negative integers.
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available (default is 'two-sided'):
* 'two-sided'
* 'less': one-sided
* 'greater': one-sided
Returns
-------
oddsratio : float
This is prior odds ratio and not a posterior estimate.
p_value : float
P-value, the probability of obtaining a distribution at least as
extreme as the one that was actually observed, assuming that the
null hypothesis is true.
See Also
--------
chi2_contingency : Chi-square test of independence of variables in a
contingency table.
Notes
-----
The calculated odds ratio is different from the one R uses. This scipy
implementation returns the (more common) "unconditional Maximum
Likelihood Estimate", while R uses the "conditional Maximum Likelihood
Estimate".
For tables with large numbers, the (inexact) chi-square test implemented
in the function `chi2_contingency` can also be used.
Examples
--------
Say we spend a few days counting whales and sharks in the Atlantic and
Indian oceans. In the Atlantic ocean we find 8 whales and 1 shark, in the
Indian ocean 2 whales and 5 sharks. Then our contingency table is::
Atlantic Indian
whales 8 2
sharks 1 5
We use this table to find the p-value:
>>> import scipy.stats as stats
>>> oddsratio, pvalue = stats.fisher_exact([[8, 2], [1, 5]])
>>> pvalue
0.0349...
The probability that we would observe this or an even more imbalanced ratio
by chance is about 3.5%. A commonly used significance level is 5%--if we
adopt that, we can therefore conclude that our observed imbalance is
statistically significant; whales prefer the Atlantic while sharks prefer
the Indian ocean.
"""
hypergeom = distributions.hypergeom
c = np.asarray(table, dtype=np.int64) # int32 is not enough for the algorithm
if not c.shape == (2, 2):
raise ValueError("The input `table` must be of shape (2, 2).")
if np.any(c < 0):
raise ValueError("All values in `table` must be nonnegative.")
if 0 in c.sum(axis=0) or 0 in c.sum(axis=1):
# If both values in a row or column are zero, the p-value is 1 and
# the odds ratio is NaN.
return np.nan, 1.0
if c[1, 0] > 0 and c[0, 1] > 0:
oddsratio = c[0, 0] * c[1, 1] / (c[1, 0] * c[0, 1])
else:
oddsratio = np.inf
n1 = c[0, 0] + c[0, 1]
n2 = c[1, 0] + c[1, 1]
n = c[0, 0] + c[1, 0]
def binary_search(n, n1, n2, side):
"""Binary search for where to begin halves in two-sided test."""
if side == "upper":
minval = mode
maxval = n
else:
minval = 0
maxval = mode
guess = -1
while maxval - minval > 1:
if maxval == minval + 1 and guess == minval:
guess = maxval
else:
guess = (maxval + minval) // 2
pguess = hypergeom.pmf(guess, n1 + n2, n1, n)
if side == "upper":
ng = guess - 1
else:
ng = guess + 1
if pguess <= pexact < hypergeom.pmf(ng, n1 + n2, n1, n):
break
elif pguess < pexact:
maxval = guess
else:
minval = guess
if guess == -1:
guess = minval
if side == "upper":
while guess > 0 and hypergeom.pmf(guess, n1 + n2, n1, n) < pexact * epsilon:
guess -= 1
while hypergeom.pmf(guess, n1 + n2, n1, n) > pexact / epsilon:
guess += 1
else:
while hypergeom.pmf(guess, n1 + n2, n1, n) < pexact * epsilon:
guess += 1
while guess > 0 and hypergeom.pmf(guess, n1 + n2, n1, n) > pexact / epsilon:
guess -= 1
return guess
if alternative == 'less':
pvalue = hypergeom.cdf(c[0, 0], n1 + n2, n1, n)
elif alternative == 'greater':
# Same formula as the 'less' case, but with the second column.
pvalue = hypergeom.cdf(c[0, 1], n1 + n2, n1, c[0, 1] + c[1, 1])
elif alternative == 'two-sided':
mode = int((n + 1) * (n1 + 1) / (n1 + n2 + 2))
pexact = hypergeom.pmf(c[0, 0], n1 + n2, n1, n)
pmode = hypergeom.pmf(mode, n1 + n2, n1, n)
epsilon = 1 - 1e-4
if np.abs(pexact - pmode) / np.maximum(pexact, pmode) <= 1 - epsilon:
return oddsratio, 1.
elif c[0, 0] < mode:
plower = hypergeom.cdf(c[0, 0], n1 + n2, n1, n)
if hypergeom.pmf(n, n1 + n2, n1, n) > pexact / epsilon:
return oddsratio, plower
guess = binary_search(n, n1, n2, "upper")
pvalue = plower + hypergeom.sf(guess - 1, n1 + n2, n1, n)
else:
pupper = hypergeom.sf(c[0, 0] - 1, n1 + n2, n1, n)
if hypergeom.pmf(0, n1 + n2, n1, n) > pexact / epsilon:
return oddsratio, pupper
guess = binary_search(n, n1, n2, "lower")
pvalue = pupper + hypergeom.cdf(guess, n1 + n2, n1, n)
else:
msg = "`alternative` should be one of {'two-sided', 'less', 'greater'}"
raise ValueError(msg)
pvalue = min(pvalue, 1.0)
return oddsratio, pvalue
class SpearmanRConstantInputWarning(RuntimeWarning):
"""Warning generated by `spearmanr` when an input is constant."""
def __init__(self, msg=None):
if msg is None:
msg = ("An input array is constant; the correlation coefficent "
"is not defined.")
self.args = (msg,)
SpearmanrResult = namedtuple('SpearmanrResult', ('correlation', 'pvalue'))
def spearmanr(a, b=None, axis=0, nan_policy='propagate'):
"""
Calculate a Spearman correlation coefficient with associated p-value.
The Spearman rank-order correlation coefficient is a nonparametric measure
of the monotonicity of the relationship between two datasets. Unlike the
Pearson correlation, the Spearman correlation does not assume that both
datasets are normally distributed. Like other correlation coefficients,
this one varies between -1 and +1 with 0 implying no correlation.
Correlations of -1 or +1 imply an exact monotonic relationship. Positive
correlations imply that as x increases, so does y. Negative correlations
imply that as x increases, y decreases.
The p-value roughly indicates the probability of an uncorrelated system
producing datasets that have a Spearman correlation at least as extreme
as the one computed from these datasets. The p-values are not entirely
reliable but are probably reasonable for datasets larger than 500 or so.
Parameters
----------
a, b : 1D or 2D array_like, b is optional
One or two 1-D or 2-D arrays containing multiple variables and
observations. When these are 1-D, each represents a vector of
observations of a single variable. For the behavior in the 2-D case,
see under ``axis``, below.
Both arrays need to have the same length in the ``axis`` dimension.
axis : int or None, optional
If axis=0 (default), then each column represents a variable, with
observations in the rows. If axis=1, the relationship is transposed:
each row represents a variable, while the columns contain observations.
If axis=None, then both arrays will be raveled.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
correlation : float or ndarray (2-D square)
Spearman correlation matrix or correlation coefficient (if only 2
variables are given as parameters. Correlation matrix is square with
length equal to total number of variables (columns or rows) in ``a``
and ``b`` combined.
pvalue : float
The two-sided p-value for a hypothesis test whose null hypothesis is
that two sets of data are uncorrelated, has same dimension as rho.
References
----------
.. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
Probability and Statistics Tables and Formulae. Chapman & Hall: New
York. 2000.
Section 14.7
Examples
--------
>>> from scipy import stats
>>> stats.spearmanr([1,2,3,4,5], [5,6,7,8,7])
(0.82078268166812329, 0.088587005313543798)
>>> np.random.seed(1234321)
>>> x2n = np.random.randn(100, 2)
>>> y2n = np.random.randn(100, 2)
>>> stats.spearmanr(x2n)
(0.059969996999699973, 0.55338590803773591)
>>> stats.spearmanr(x2n[:,0], x2n[:,1])
(0.059969996999699973, 0.55338590803773591)
>>> rho, pval = stats.spearmanr(x2n, y2n)
>>> rho
array([[ 1. , 0.05997 , 0.18569457, 0.06258626],
[ 0.05997 , 1. , 0.110003 , 0.02534653],
[ 0.18569457, 0.110003 , 1. , 0.03488749],
[ 0.06258626, 0.02534653, 0.03488749, 1. ]])
>>> pval
array([[ 0. , 0.55338591, 0.06435364, 0.53617935],
[ 0.55338591, 0. , 0.27592895, 0.80234077],
[ 0.06435364, 0.27592895, 0. , 0.73039992],
[ 0.53617935, 0.80234077, 0.73039992, 0. ]])
>>> rho, pval = stats.spearmanr(x2n.T, y2n.T, axis=1)
>>> rho
array([[ 1. , 0.05997 , 0.18569457, 0.06258626],
[ 0.05997 , 1. , 0.110003 , 0.02534653],
[ 0.18569457, 0.110003 , 1. , 0.03488749],
[ 0.06258626, 0.02534653, 0.03488749, 1. ]])
>>> stats.spearmanr(x2n, y2n, axis=None)
(0.10816770419260482, 0.1273562188027364)
>>> stats.spearmanr(x2n.ravel(), y2n.ravel())
(0.10816770419260482, 0.1273562188027364)
>>> xint = np.random.randint(10, size=(100, 2))
>>> stats.spearmanr(xint)
(0.052760927029710199, 0.60213045837062351)
"""
if axis is not None and axis > 1:
raise ValueError("spearmanr only handles 1-D or 2-D arrays, supplied axis argument {}, please use only values 0, 1 or None for axis".format(axis))
a, axisout = _chk_asarray(a, axis)
if a.ndim > 2:
raise ValueError("spearmanr only handles 1-D or 2-D arrays")
if b is None:
if a.ndim < 2:
raise ValueError("`spearmanr` needs at least 2 variables to compare")
else:
# Concatenate a and b, so that we now only have to handle the case
# of a 2-D `a`.
b, _ = _chk_asarray(b, axis)
if axisout == 0:
a = np.column_stack((a, b))
else:
a = np.row_stack((a, b))
n_vars = a.shape[1 - axisout]
n_obs = a.shape[axisout]
if n_obs <= 1:
# Handle empty arrays or single observations.
return SpearmanrResult(np.nan, np.nan)
if axisout == 0:
if (a[:, 0][0] == a[:, 0]).all() or (a[:, 1][0] == a[:, 1]).all():
# If an input is constant, the correlation coefficient is not defined.
warnings.warn(SpearmanRConstantInputWarning())
return SpearmanrResult(np.nan, np.nan)
else: # case when axisout == 1 b/c a is 2 dim only
if (a[0, :][0] == a[0, :]).all() or (a[1, :][0] == a[1, :]).all():
# If an input is constant, the correlation coefficient is not defined.
warnings.warn(SpearmanRConstantInputWarning())
return SpearmanrResult(np.nan, np.nan)
a_contains_nan, nan_policy = _contains_nan(a, nan_policy)
variable_has_nan = np.zeros(n_vars, dtype=bool)
if a_contains_nan:
if nan_policy == 'omit':
return mstats_basic.spearmanr(a, axis=axis, nan_policy=nan_policy)
elif nan_policy == 'propagate':
if a.ndim == 1 or n_vars <= 2:
return SpearmanrResult(np.nan, np.nan)
else:
# Keep track of variables with NaNs, set the outputs to NaN
# only for those variables
variable_has_nan = np.isnan(a).any(axis=axisout)
a_ranked = np.apply_along_axis(rankdata, axisout, a)
rs = np.corrcoef(a_ranked, rowvar=axisout)
dof = n_obs - 2 # degrees of freedom
# rs can have elements equal to 1, so avoid zero division warnings
with np.errstate(divide='ignore'):
# clip the small negative values possibly caused by rounding
# errors before taking the square root
t = rs * np.sqrt((dof/((rs+1.0)*(1.0-rs))).clip(0))
prob = 2 * distributions.t.sf(np.abs(t), dof)
# For backwards compatibility, return scalars when comparing 2 columns
if rs.shape == (2, 2):
return SpearmanrResult(rs[1, 0], prob[1, 0])
else:
rs[variable_has_nan, :] = np.nan
rs[:, variable_has_nan] = np.nan
return SpearmanrResult(rs, prob)
PointbiserialrResult = namedtuple('PointbiserialrResult',
('correlation', 'pvalue'))
def pointbiserialr(x, y):
r"""
Calculate a point biserial correlation coefficient and its p-value.
The point biserial correlation is used to measure the relationship
between a binary variable, x, and a continuous variable, y. Like other
correlation coefficients, this one varies between -1 and +1 with 0
implying no correlation. Correlations of -1 or +1 imply a determinative
relationship.
This function uses a shortcut formula but produces the same result as
`pearsonr`.
Parameters
----------
x : array_like of bools
Input array.
y : array_like
Input array.
Returns
-------
correlation : float
R value.
pvalue : float
Two-sided p-value.
Notes
-----
`pointbiserialr` uses a t-test with ``n-1`` degrees of freedom.
It is equivalent to `pearsonr`.
The value of the point-biserial correlation can be calculated from:
.. math::
r_{pb} = \frac{\overline{Y_{1}} -
\overline{Y_{0}}}{s_{y}}\sqrt{\frac{N_{1} N_{2}}{N (N - 1))}}
Where :math:`Y_{0}` and :math:`Y_{1}` are means of the metric
observations coded 0 and 1 respectively; :math:`N_{0}` and :math:`N_{1}`
are number of observations coded 0 and 1 respectively; :math:`N` is the
total number of observations and :math:`s_{y}` is the standard
deviation of all the metric observations.
A value of :math:`r_{pb}` that is significantly different from zero is
completely equivalent to a significant difference in means between the two
groups. Thus, an independent groups t Test with :math:`N-2` degrees of
freedom may be used to test whether :math:`r_{pb}` is nonzero. The
relation between the t-statistic for comparing two independent groups and
:math:`r_{pb}` is given by:
.. math::
t = \sqrt{N - 2}\frac{r_{pb}}{\sqrt{1 - r^{2}_{pb}}}
References
----------
.. [1] J. Lev, "The Point Biserial Coefficient of Correlation", Ann. Math.
Statist., Vol. 20, no.1, pp. 125-126, 1949.
.. [2] R.F. Tate, "Correlation Between a Discrete and a Continuous
Variable. Point-Biserial Correlation.", Ann. Math. Statist., Vol. 25,
np. 3, pp. 603-607, 1954.
.. [3] D. Kornbrot "Point Biserial Correlation", In Wiley StatsRef:
Statistics Reference Online (eds N. Balakrishnan, et al.), 2014.
:doi:`10.1002/9781118445112.stat06227`
Examples
--------
>>> from scipy import stats
>>> a = np.array([0, 0, 0, 1, 1, 1, 1])
>>> b = np.arange(7)
>>> stats.pointbiserialr(a, b)
(0.8660254037844386, 0.011724811003954652)
>>> stats.pearsonr(a, b)
(0.86602540378443871, 0.011724811003954626)
>>> np.corrcoef(a, b)
array([[ 1. , 0.8660254],
[ 0.8660254, 1. ]])
"""
rpb, prob = pearsonr(x, y)
return PointbiserialrResult(rpb, prob)
KendalltauResult = namedtuple('KendalltauResult', ('correlation', 'pvalue'))
def kendalltau(x, y, initial_lexsort=None, nan_policy='propagate',
method='auto', variant='b'):
"""
Calculate Kendall's tau, a correlation measure for ordinal data.
Kendall's tau is a measure of the correspondence between two rankings.
Values close to 1 indicate strong agreement, and values close to -1
indicate strong disagreement. This implements two variants of Kendall's
tau: tau-b (the default) and tau-c (also known as Stuart's tau-c). These
differ only in how they are normalized to lie within the range -1 to 1;
the hypothesis tests (their p-values) are identical. Kendall's original
tau-a is not implemented separately because both tau-b and tau-c reduce
to tau-a in the absence of ties.
Parameters
----------
x, y : array_like
Arrays of rankings, of the same shape. If arrays are not 1-D, they
will be flattened to 1-D.
initial_lexsort : bool, optional
Unused (deprecated).
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
method : {'auto', 'asymptotic', 'exact'}, optional
Defines which method is used to calculate the p-value [5]_.
The following options are available (default is 'auto'):
* 'auto': selects the appropriate method based on a trade-off
between speed and accuracy
* 'asymptotic': uses a normal approximation valid for large samples
* 'exact': computes the exact p-value, but can only be used if no ties
are present. As the sample size increases, the 'exact' computation
time may grow and the result may lose some precision.
variant: {'b', 'c'}, optional
Defines which variant of Kendall's tau is returned. Default is 'b'.
Returns
-------
correlation : float
The tau statistic.
pvalue : float
The two-sided p-value for a hypothesis test whose null hypothesis is
an absence of association, tau = 0.
See Also
--------
spearmanr : Calculates a Spearman rank-order correlation coefficient.
theilslopes : Computes the Theil-Sen estimator for a set of points (x, y).
weightedtau : Computes a weighted version of Kendall's tau.
Notes
-----
The definition of Kendall's tau that is used is [2]_::
tau_b = (P - Q) / sqrt((P + Q + T) * (P + Q + U))
tau_c = 2 (P - Q) / (n**2 * (m - 1) / m)
where P is the number of concordant pairs, Q the number of discordant
pairs, T the number of ties only in `x`, and U the number of ties only in
`y`. If a tie occurs for the same pair in both `x` and `y`, it is not
added to either T or U. n is the total number of samples, and m is the
number of unique values in either `x` or `y`, whichever is smaller.
References
----------
.. [1] Maurice G. Kendall, "A New Measure of Rank Correlation", Biometrika
Vol. 30, No. 1/2, pp. 81-93, 1938.
.. [2] Maurice G. Kendall, "The treatment of ties in ranking problems",
Biometrika Vol. 33, No. 3, pp. 239-251. 1945.
.. [3] Gottfried E. Noether, "Elements of Nonparametric Statistics", John
Wiley & Sons, 1967.
.. [4] Peter M. Fenwick, "A new data structure for cumulative frequency
tables", Software: Practice and Experience, Vol. 24, No. 3,
pp. 327-336, 1994.
.. [5] Maurice G. Kendall, "Rank Correlation Methods" (4th Edition),
Charles Griffin & Co., 1970.
Examples
--------
>>> from scipy import stats
>>> x1 = [12, 2, 1, 12, 2]
>>> x2 = [1, 4, 7, 1, 0]
>>> tau, p_value = stats.kendalltau(x1, x2)
>>> tau
-0.47140452079103173
>>> p_value
0.2827454599327748
"""
x = np.asarray(x).ravel()
y = np.asarray(y).ravel()
if x.size != y.size:
raise ValueError("All inputs to `kendalltau` must be of the same "
f"size, found x-size {x.size} and y-size {y.size}")
elif not x.size or not y.size:
# Return NaN if arrays are empty
return KendalltauResult(np.nan, np.nan)
# check both x and y
cnx, npx = _contains_nan(x, nan_policy)
cny, npy = _contains_nan(y, nan_policy)
contains_nan = cnx or cny
if npx == 'omit' or npy == 'omit':
nan_policy = 'omit'
if contains_nan and nan_policy == 'propagate':
return KendalltauResult(np.nan, np.nan)
elif contains_nan and nan_policy == 'omit':
x = ma.masked_invalid(x)
y = ma.masked_invalid(y)
if variant == 'b':
return mstats_basic.kendalltau(x, y, method=method, use_ties=True)
else:
raise ValueError("Only variant 'b' is supported for masked arrays")
if initial_lexsort is not None: # deprecate to drop!
warnings.warn('"initial_lexsort" is gone!')
def count_rank_tie(ranks):
cnt = np.bincount(ranks).astype('int64', copy=False)
cnt = cnt[cnt > 1]
return ((cnt * (cnt - 1) // 2).sum(),
(cnt * (cnt - 1.) * (cnt - 2)).sum(),
(cnt * (cnt - 1.) * (2*cnt + 5)).sum())
size = x.size
perm = np.argsort(y) # sort on y and convert y to dense ranks
x, y = x[perm], y[perm]
y = np.r_[True, y[1:] != y[:-1]].cumsum(dtype=np.intp)
# stable sort on x and convert x to dense ranks
perm = np.argsort(x, kind='mergesort')
x, y = x[perm], y[perm]
x = np.r_[True, x[1:] != x[:-1]].cumsum(dtype=np.intp)
dis = _kendall_dis(x, y) # discordant pairs
obs = np.r_[True, (x[1:] != x[:-1]) | (y[1:] != y[:-1]), True]
cnt = np.diff(np.nonzero(obs)[0]).astype('int64', copy=False)
ntie = (cnt * (cnt - 1) // 2).sum() # joint ties
xtie, x0, x1 = count_rank_tie(x) # ties in x, stats
ytie, y0, y1 = count_rank_tie(y) # ties in y, stats
tot = (size * (size - 1)) // 2
if xtie == tot or ytie == tot:
return KendalltauResult(np.nan, np.nan)
# Note that tot = con + dis + (xtie - ntie) + (ytie - ntie) + ntie
# = con + dis + xtie + ytie - ntie
con_minus_dis = tot - xtie - ytie + ntie - 2 * dis
if variant == 'b':
tau = con_minus_dis / np.sqrt(tot - xtie) / np.sqrt(tot - ytie)
elif variant == 'c':
minclasses = min(len(set(x)), len(set(y)))
tau = 2*con_minus_dis / (size**2 * (minclasses-1)/minclasses)
else:
raise ValueError(f"Unknown variant of the method chosen: {variant}. "
"variant must be 'b' or 'c'.")
# Limit range to fix computational errors
tau = min(1., max(-1., tau))
# The p-value calculation is the same for all variants since the p-value
# depends only on con_minus_dis.
if method == 'exact' and (xtie != 0 or ytie != 0):
raise ValueError("Ties found, exact method cannot be used.")
if method == 'auto':
if (xtie == 0 and ytie == 0) and (size <= 33 or
min(dis, tot-dis) <= 1):
method = 'exact'
else:
method = 'asymptotic'
if xtie == 0 and ytie == 0 and method == 'exact':
pvalue = mstats_basic._kendall_p_exact(size, min(dis, tot-dis))
elif method == 'asymptotic':
# con_minus_dis is approx normally distributed with this variance [3]_
m = size * (size - 1.)
var = ((m * (2*size + 5) - x1 - y1) / 18 +
(2 * xtie * ytie) / m + x0 * y0 / (9 * m * (size - 2)))
pvalue = (special.erfc(np.abs(con_minus_dis) /
np.sqrt(var) / np.sqrt(2)))
else:
raise ValueError(f"Unknown method {method} specified. Use 'auto', "
"'exact' or 'asymptotic'.")
return KendalltauResult(tau, pvalue)
WeightedTauResult = namedtuple('WeightedTauResult', ('correlation', 'pvalue'))
def weightedtau(x, y, rank=True, weigher=None, additive=True):
r"""
Compute a weighted version of Kendall's :math:`\tau`.
The weighted :math:`\tau` is a weighted version of Kendall's
:math:`\tau` in which exchanges of high weight are more influential than
exchanges of low weight. The default parameters compute the additive
hyperbolic version of the index, :math:`\tau_\mathrm h`, which has
been shown to provide the best balance between important and
unimportant elements [1]_.
The weighting is defined by means of a rank array, which assigns a
nonnegative rank to each element (higher importance ranks being
associated with smaller values, e.g., 0 is the highest possible rank),
and a weigher function, which assigns a weight based on the rank to
each element. The weight of an exchange is then the sum or the product
of the weights of the ranks of the exchanged elements. The default
parameters compute :math:`\tau_\mathrm h`: an exchange between
elements with rank :math:`r` and :math:`s` (starting from zero) has
weight :math:`1/(r+1) + 1/(s+1)`.
Specifying a rank array is meaningful only if you have in mind an
external criterion of importance. If, as it usually happens, you do
not have in mind a specific rank, the weighted :math:`\tau` is
defined by averaging the values obtained using the decreasing
lexicographical rank by (`x`, `y`) and by (`y`, `x`). This is the
behavior with default parameters. Note that the convention used
here for ranking (lower values imply higher importance) is opposite
to that used by other SciPy statistical functions.
Parameters
----------
x, y : array_like
Arrays of scores, of the same shape. If arrays are not 1-D, they will
be flattened to 1-D.
rank : array_like of ints or bool, optional
A nonnegative rank assigned to each element. If it is None, the
decreasing lexicographical rank by (`x`, `y`) will be used: elements of
higher rank will be those with larger `x`-values, using `y`-values to
break ties (in particular, swapping `x` and `y` will give a different
result). If it is False, the element indices will be used
directly as ranks. The default is True, in which case this
function returns the average of the values obtained using the
decreasing lexicographical rank by (`x`, `y`) and by (`y`, `x`).
weigher : callable, optional
The weigher function. Must map nonnegative integers (zero
representing the most important element) to a nonnegative weight.
The default, None, provides hyperbolic weighing, that is,
rank :math:`r` is mapped to weight :math:`1/(r+1)`.
additive : bool, optional
If True, the weight of an exchange is computed by adding the
weights of the ranks of the exchanged elements; otherwise, the weights
are multiplied. The default is True.
Returns
-------
correlation : float
The weighted :math:`\tau` correlation index.
pvalue : float
Presently ``np.nan``, as the null statistics is unknown (even in the
additive hyperbolic case).
See Also
--------
kendalltau : Calculates Kendall's tau.
spearmanr : Calculates a Spearman rank-order correlation coefficient.
theilslopes : Computes the Theil-Sen estimator for a set of points (x, y).
Notes
-----
This function uses an :math:`O(n \log n)`, mergesort-based algorithm
[1]_ that is a weighted extension of Knight's algorithm for Kendall's
:math:`\tau` [2]_. It can compute Shieh's weighted :math:`\tau` [3]_
between rankings without ties (i.e., permutations) by setting
`additive` and `rank` to False, as the definition given in [1]_ is a
generalization of Shieh's.
NaNs are considered the smallest possible score.
.. versionadded:: 0.19.0
References
----------
.. [1] Sebastiano Vigna, "A weighted correlation index for rankings with
ties", Proceedings of the 24th international conference on World
Wide Web, pp. 1166-1176, ACM, 2015.
.. [2] W.R. Knight, "A Computer Method for Calculating Kendall's Tau with
Ungrouped Data", Journal of the American Statistical Association,
Vol. 61, No. 314, Part 1, pp. 436-439, 1966.
.. [3] Grace S. Shieh. "A weighted Kendall's tau statistic", Statistics &
Probability Letters, Vol. 39, No. 1, pp. 17-24, 1998.
Examples
--------
>>> from scipy import stats
>>> x = [12, 2, 1, 12, 2]
>>> y = [1, 4, 7, 1, 0]
>>> tau, p_value = stats.weightedtau(x, y)
>>> tau
-0.56694968153682723
>>> p_value
nan
>>> tau, p_value = stats.weightedtau(x, y, additive=False)
>>> tau
-0.62205716951801038
NaNs are considered the smallest possible score:
>>> x = [12, 2, 1, 12, 2]
>>> y = [1, 4, 7, 1, np.nan]
>>> tau, _ = stats.weightedtau(x, y)
>>> tau
-0.56694968153682723
This is exactly Kendall's tau:
>>> x = [12, 2, 1, 12, 2]
>>> y = [1, 4, 7, 1, 0]
>>> tau, _ = stats.weightedtau(x, y, weigher=lambda x: 1)
>>> tau
-0.47140452079103173
>>> x = [12, 2, 1, 12, 2]
>>> y = [1, 4, 7, 1, 0]
>>> stats.weightedtau(x, y, rank=None)
WeightedTauResult(correlation=-0.4157652301037516, pvalue=nan)
>>> stats.weightedtau(y, x, rank=None)
WeightedTauResult(correlation=-0.7181341329699028, pvalue=nan)
"""
x = np.asarray(x).ravel()
y = np.asarray(y).ravel()
if x.size != y.size:
raise ValueError("All inputs to `weightedtau` must be of the same size, "
"found x-size %s and y-size %s" % (x.size, y.size))
if not x.size:
return WeightedTauResult(np.nan, np.nan) # Return NaN if arrays are empty
# If there are NaNs we apply _toint64()
if np.isnan(np.sum(x)):
x = _toint64(x)
if np.isnan(np.sum(y)):
y = _toint64(y)
# Reduce to ranks unsupported types
if x.dtype != y.dtype:
if x.dtype != np.int64:
x = _toint64(x)
if y.dtype != np.int64:
y = _toint64(y)
else:
if x.dtype not in (np.int32, np.int64, np.float32, np.float64):
x = _toint64(x)
y = _toint64(y)
if rank is True:
return WeightedTauResult((
_weightedrankedtau(x, y, None, weigher, additive) +
_weightedrankedtau(y, x, None, weigher, additive)
) / 2, np.nan)
if rank is False:
rank = np.arange(x.size, dtype=np.intp)
elif rank is not None:
rank = np.asarray(rank).ravel()
if rank.size != x.size:
raise ValueError("All inputs to `weightedtau` must be of the same size, "
"found x-size %s and rank-size %s" % (x.size, rank.size))
return WeightedTauResult(_weightedrankedtau(x, y, rank, weigher, additive), np.nan)
# FROM MGCPY: https://github.com/neurodata/mgcpy
class _ParallelP(object):
"""
Helper function to calculate parallel p-value.
"""
def __init__(self, x, y, random_states):
self.x = x
self.y = y
self.random_states = random_states
def __call__(self, index):
order = self.random_states[index].permutation(self.y.shape[0])
permy = self.y[order][:, order]
# calculate permuted stats, store in null distribution
perm_stat = _mgc_stat(self.x, permy)[0]
return perm_stat
def _perm_test(x, y, stat, reps=1000, workers=-1, random_state=None):
r"""
Helper function that calculates the p-value. See below for uses.
Parameters
----------
x, y : ndarray
`x` and `y` have shapes `(n, p)` and `(n, q)`.
stat : float
The sample test statistic.
reps : int, optional
The number of replications used to estimate the null when using the
permutation test. The default is 1000 replications.
workers : int or map-like callable, optional
If `workers` is an int the population is subdivided into `workers`
sections and evaluated in parallel (uses
`multiprocessing.Pool <multiprocessing>`). Supply `-1` to use all cores
available to the Process. Alternatively supply a map-like callable,
such as `multiprocessing.Pool.map` for evaluating the population in
parallel. This evaluation is carried out as `workers(func, iterable)`.
Requires that `func` be pickleable.
random_state : int or np.random.RandomState instance, optional
If already a RandomState instance, use it.
If seed is an int, return a new RandomState instance seeded with seed.
If None, use np.random.RandomState. Default is None.
Returns
-------
pvalue : float
The sample test p-value.
null_dist : list
The approximated null distribution.
"""
# generate seeds for each rep (change to new parallel random number
# capabilities in numpy >= 1.17+)
random_state = check_random_state(random_state)
random_states = [np.random.RandomState(rng_integers(random_state, 1 << 32,
size=4, dtype=np.uint32)) for _ in range(reps)]
# parallelizes with specified workers over number of reps and set seeds
parallelp = _ParallelP(x=x, y=y, random_states=random_states)
with MapWrapper(workers) as mapwrapper:
null_dist = np.array(list(mapwrapper(parallelp, range(reps))))
# calculate p-value and significant permutation map through list
pvalue = (null_dist >= stat).sum() / reps
# correct for a p-value of 0. This is because, with bootstrapping
# permutations, a p-value of 0 is incorrect
if pvalue == 0:
pvalue = 1 / reps
return pvalue, null_dist
def _euclidean_dist(x):
return cdist(x, x)
MGCResult = namedtuple('MGCResult', ('stat', 'pvalue', 'mgc_dict'))
def multiscale_graphcorr(x, y, compute_distance=_euclidean_dist, reps=1000,
workers=1, is_twosamp=False, random_state=None):
r"""
Computes the Multiscale Graph Correlation (MGC) test statistic.
Specifically, for each point, MGC finds the :math:`k`-nearest neighbors for
one property (e.g. cloud density), and the :math:`l`-nearest neighbors for
the other property (e.g. grass wetness) [1]_. This pair :math:`(k, l)` is
called the "scale". A priori, however, it is not know which scales will be
most informative. So, MGC computes all distance pairs, and then efficiently
computes the distance correlations for all scales. The local correlations
illustrate which scales are relatively informative about the relationship.
The key, therefore, to successfully discover and decipher relationships
between disparate data modalities is to adaptively determine which scales
are the most informative, and the geometric implication for the most
informative scales. Doing so not only provides an estimate of whether the
modalities are related, but also provides insight into how the
determination was made. This is especially important in high-dimensional
data, where simple visualizations do not reveal relationships to the
unaided human eye. Characterizations of this implementation in particular
have been derived from and benchmarked within in [2]_.
Parameters
----------
x, y : ndarray
If ``x`` and ``y`` have shapes ``(n, p)`` and ``(n, q)`` where `n` is
the number of samples and `p` and `q` are the number of dimensions,
then the MGC independence test will be run. Alternatively, ``x`` and
``y`` can have shapes ``(n, n)`` if they are distance or similarity
matrices, and ``compute_distance`` must be sent to ``None``. If ``x``
and ``y`` have shapes ``(n, p)`` and ``(m, p)``, an unpaired
two-sample MGC test will be run.
compute_distance : callable, optional
A function that computes the distance or similarity among the samples
within each data matrix. Set to ``None`` if ``x`` and ``y`` are
already distance matrices. The default uses the euclidean norm metric.
If you are calling a custom function, either create the distance
matrix before-hand or create a function of the form
``compute_distance(x)`` where `x` is the data matrix for which
pairwise distances are calculated.
reps : int, optional
The number of replications used to estimate the null when using the
permutation test. The default is ``1000``.
workers : int or map-like callable, optional
If ``workers`` is an int the population is subdivided into ``workers``
sections and evaluated in parallel (uses ``multiprocessing.Pool
<multiprocessing>``). Supply ``-1`` to use all cores available to the
Process. Alternatively supply a map-like callable, such as
``multiprocessing.Pool.map`` for evaluating the p-value in parallel.
This evaluation is carried out as ``workers(func, iterable)``.
Requires that `func` be pickleable. The default is ``1``.
is_twosamp : bool, optional
If `True`, a two sample test will be run. If ``x`` and ``y`` have
shapes ``(n, p)`` and ``(m, p)``, this optional will be overriden and
set to ``True``. Set to ``True`` if ``x`` and ``y`` both have shapes
``(n, p)`` and a two sample test is desired. The default is ``False``.
Note that this will not run if inputs are distance matrices.
random_state : int or np.random.RandomState instance, optional
If already a RandomState instance, use it.
If seed is an int, return a new RandomState instance seeded with seed.
If None, use np.random.RandomState. Default is None.
Returns
-------
stat : float
The sample MGC test statistic within `[-1, 1]`.
pvalue : float
The p-value obtained via permutation.
mgc_dict : dict
Contains additional useful additional returns containing the following
keys:
- mgc_map : ndarray
A 2D representation of the latent geometry of the relationship.
of the relationship.
- opt_scale : (int, int)
The estimated optimal scale as a `(x, y)` pair.
- null_dist : list
The null distribution derived from the permuted matrices
See Also
--------
pearsonr : Pearson correlation coefficient and p-value for testing
non-correlation.
kendalltau : Calculates Kendall's tau.
spearmanr : Calculates a Spearman rank-order correlation coefficient.
Notes
-----
A description of the process of MGC and applications on neuroscience data
can be found in [1]_. It is performed using the following steps:
#. Two distance matrices :math:`D^X` and :math:`D^Y` are computed and
modified to be mean zero columnwise. This results in two
:math:`n \times n` distance matrices :math:`A` and :math:`B` (the
centering and unbiased modification) [3]_.
#. For all values :math:`k` and :math:`l` from :math:`1, ..., n`,
* The :math:`k`-nearest neighbor and :math:`l`-nearest neighbor graphs
are calculated for each property. Here, :math:`G_k (i, j)` indicates
the :math:`k`-smallest values of the :math:`i`-th row of :math:`A`
and :math:`H_l (i, j)` indicates the :math:`l` smallested values of
the :math:`i`-th row of :math:`B`
* Let :math:`\circ` denotes the entry-wise matrix product, then local
correlations are summed and normalized using the following statistic:
.. math::
c^{kl} = \frac{\sum_{ij} A G_k B H_l}
{\sqrt{\sum_{ij} A^2 G_k \times \sum_{ij} B^2 H_l}}
#. The MGC test statistic is the smoothed optimal local correlation of
:math:`\{ c^{kl} \}`. Denote the smoothing operation as :math:`R(\cdot)`
(which essentially set all isolated large correlations) as 0 and
connected large correlations the same as before, see [3]_.) MGC is,
.. math::
MGC_n (x, y) = \max_{(k, l)} R \left(c^{kl} \left( x_n, y_n \right)
\right)
The test statistic returns a value between :math:`(-1, 1)` since it is
normalized.
The p-value returned is calculated using a permutation test. This process
is completed by first randomly permuting :math:`y` to estimate the null
distribution and then calculating the probability of observing a test
statistic, under the null, at least as extreme as the observed test
statistic.
MGC requires at least 5 samples to run with reliable results. It can also
handle high-dimensional data sets.
In addition, by manipulating the input data matrices, the two-sample
testing problem can be reduced to the independence testing problem [4]_.
Given sample data :math:`U` and :math:`V` of sizes :math:`p \times n`
:math:`p \times m`, data matrix :math:`X` and :math:`Y` can be created as
follows:
.. math::
X = [U | V] \in \mathcal{R}^{p \times (n + m)}
Y = [0_{1 \times n} | 1_{1 \times m}] \in \mathcal{R}^{(n + m)}
Then, the MGC statistic can be calculated as normal. This methodology can
be extended to similar tests such as distance correlation [4]_.
.. versionadded:: 1.4.0
References
----------
.. [1] Vogelstein, J. T., Bridgeford, E. W., Wang, Q., Priebe, C. E.,
Maggioni, M., & Shen, C. (2019). Discovering and deciphering
relationships across disparate data modalities. ELife.
.. [2] Panda, S., Palaniappan, S., Xiong, J., Swaminathan, A.,
Ramachandran, S., Bridgeford, E. W., ... Vogelstein, J. T. (2019).
mgcpy: A Comprehensive High Dimensional Independence Testing Python
Package. :arXiv:`1907.02088`
.. [3] Shen, C., Priebe, C.E., & Vogelstein, J. T. (2019). From distance
correlation to multiscale graph correlation. Journal of the American
Statistical Association.
.. [4] Shen, C. & Vogelstein, J. T. (2018). The Exact Equivalence of
Distance and Kernel Methods for Hypothesis Testing.
:arXiv:`1806.05514`
Examples
--------
>>> from scipy.stats import multiscale_graphcorr
>>> x = np.arange(100)
>>> y = x
>>> stat, pvalue, _ = multiscale_graphcorr(x, y, workers=-1)
>>> '%.1f, %.3f' % (stat, pvalue)
'1.0, 0.001'
Alternatively,
>>> x = np.arange(100)
>>> y = x
>>> mgc = multiscale_graphcorr(x, y)
>>> '%.1f, %.3f' % (mgc.stat, mgc.pvalue)
'1.0, 0.001'
To run an unpaired two-sample test,
>>> x = np.arange(100)
>>> y = np.arange(79)
>>> mgc = multiscale_graphcorr(x, y, random_state=1)
>>> '%.3f, %.2f' % (mgc.stat, mgc.pvalue)
'0.033, 0.02'
or, if shape of the inputs are the same,
>>> x = np.arange(100)
>>> y = x
>>> mgc = multiscale_graphcorr(x, y, is_twosamp=True)
>>> '%.3f, %.1f' % (mgc.stat, mgc.pvalue)
'-0.008, 1.0'
"""
if not isinstance(x, np.ndarray) or not isinstance(y, np.ndarray):
raise ValueError("x and y must be ndarrays")
# convert arrays of type (n,) to (n, 1)
if x.ndim == 1:
x = x[:, np.newaxis]
elif x.ndim != 2:
raise ValueError("Expected a 2-D array `x`, found shape "
"{}".format(x.shape))
if y.ndim == 1:
y = y[:, np.newaxis]
elif y.ndim != 2:
raise ValueError("Expected a 2-D array `y`, found shape "
"{}".format(y.shape))
nx, px = x.shape
ny, py = y.shape
# check for NaNs
_contains_nan(x, nan_policy='raise')
_contains_nan(y, nan_policy='raise')
# check for positive or negative infinity and raise error
if np.sum(np.isinf(x)) > 0 or np.sum(np.isinf(y)) > 0:
raise ValueError("Inputs contain infinities")
if nx != ny:
if px == py:
# reshape x and y for two sample testing
is_twosamp = True
else:
raise ValueError("Shape mismatch, x and y must have shape [n, p] "
"and [n, q] or have shape [n, p] and [m, p].")
if nx < 5 or ny < 5:
raise ValueError("MGC requires at least 5 samples to give reasonable "
"results.")
# convert x and y to float
x = x.astype(np.float64)
y = y.astype(np.float64)
# check if compute_distance_matrix if a callable()
if not callable(compute_distance) and compute_distance is not None:
raise ValueError("Compute_distance must be a function.")
# check if number of reps exists, integer, or > 0 (if under 1000 raises
# warning)
if not isinstance(reps, int) or reps < 0:
raise ValueError("Number of reps must be an integer greater than 0.")
elif reps < 1000:
msg = ("The number of replications is low (under 1000), and p-value "
"calculations may be unreliable. Use the p-value result, with "
"caution!")
warnings.warn(msg, RuntimeWarning)
if is_twosamp:
if compute_distance is None:
raise ValueError("Cannot run if inputs are distance matrices")
x, y = _two_sample_transform(x, y)
if compute_distance is not None:
# compute distance matrices for x and y
x = compute_distance(x)
y = compute_distance(y)
# calculate MGC stat
stat, stat_dict = _mgc_stat(x, y)
stat_mgc_map = stat_dict["stat_mgc_map"]
opt_scale = stat_dict["opt_scale"]
# calculate permutation MGC p-value
pvalue, null_dist = _perm_test(x, y, stat, reps=reps, workers=workers,
random_state=random_state)
# save all stats (other than stat/p-value) in dictionary
mgc_dict = {"mgc_map": stat_mgc_map,
"opt_scale": opt_scale,
"null_dist": null_dist}
return MGCResult(stat, pvalue, mgc_dict)
def _mgc_stat(distx, disty):
r"""
Helper function that calculates the MGC stat. See above for use.
Parameters
----------
x, y : ndarray
`x` and `y` have shapes `(n, p)` and `(n, q)` or `(n, n)` and `(n, n)`
if distance matrices.
Returns
-------
stat : float
The sample MGC test statistic within `[-1, 1]`.
stat_dict : dict
Contains additional useful additional returns containing the following
keys:
- stat_mgc_map : ndarray
MGC-map of the statistics.
- opt_scale : (float, float)
The estimated optimal scale as a `(x, y)` pair.
"""
# calculate MGC map and optimal scale
stat_mgc_map = _local_correlations(distx, disty, global_corr='mgc')
n, m = stat_mgc_map.shape
if m == 1 or n == 1:
# the global scale at is the statistic calculated at maximial nearest
# neighbors. There is not enough local scale to search over, so
# default to global scale
stat = stat_mgc_map[m - 1][n - 1]
opt_scale = m * n
else:
samp_size = len(distx) - 1
# threshold to find connected region of significant local correlations
sig_connect = _threshold_mgc_map(stat_mgc_map, samp_size)
# maximum within the significant region
stat, opt_scale = _smooth_mgc_map(sig_connect, stat_mgc_map)
stat_dict = {"stat_mgc_map": stat_mgc_map,
"opt_scale": opt_scale}
return stat, stat_dict
def _threshold_mgc_map(stat_mgc_map, samp_size):
r"""
Finds a connected region of significance in the MGC-map by thresholding.
Parameters
----------
stat_mgc_map : ndarray
All local correlations within `[-1,1]`.
samp_size : int
The sample size of original data.
Returns
-------
sig_connect : ndarray
A binary matrix with 1's indicating the significant region.
"""
m, n = stat_mgc_map.shape
# 0.02 is simply an empirical threshold, this can be set to 0.01 or 0.05
# with varying levels of performance. Threshold is based on a beta
# approximation.
per_sig = 1 - (0.02 / samp_size) # Percentile to consider as significant
threshold = samp_size * (samp_size - 3)/4 - 1/2 # Beta approximation
threshold = distributions.beta.ppf(per_sig, threshold, threshold) * 2 - 1
# the global scale at is the statistic calculated at maximial nearest
# neighbors. Threshold is the maximium on the global and local scales
threshold = max(threshold, stat_mgc_map[m - 1][n - 1])
# find the largest connected component of significant correlations
sig_connect = stat_mgc_map > threshold
if np.sum(sig_connect) > 0:
sig_connect, _ = measurements.label(sig_connect)
_, label_counts = np.unique(sig_connect, return_counts=True)
# skip the first element in label_counts, as it is count(zeros)
max_label = np.argmax(label_counts[1:]) + 1
sig_connect = sig_connect == max_label
else:
sig_connect = np.array([[False]])
return sig_connect
def _smooth_mgc_map(sig_connect, stat_mgc_map):
"""
Finds the smoothed maximal within the significant region R.
If area of R is too small it returns the last local correlation. Otherwise,
returns the maximum within significant_connected_region.
Parameters
----------
sig_connect: ndarray
A binary matrix with 1's indicating the significant region.
stat_mgc_map: ndarray
All local correlations within `[-1, 1]`.
Returns
-------
stat : float
The sample MGC statistic within `[-1, 1]`.
opt_scale: (float, float)
The estimated optimal scale as an `(x, y)` pair.
"""
m, n = stat_mgc_map.shape
# the global scale at is the statistic calculated at maximial nearest
# neighbors. By default, statistic and optimal scale are global.
stat = stat_mgc_map[m - 1][n - 1]
opt_scale = [m, n]
if np.linalg.norm(sig_connect) != 0:
# proceed only when the connected region's area is sufficiently large
# 0.02 is simply an empirical threshold, this can be set to 0.01 or 0.05
# with varying levels of performance
if np.sum(sig_connect) >= np.ceil(0.02 * max(m, n)) * min(m, n):
max_corr = max(stat_mgc_map[sig_connect])
# find all scales within significant_connected_region that maximize
# the local correlation
max_corr_index = np.where((stat_mgc_map >= max_corr) & sig_connect)
if max_corr >= stat:
stat = max_corr
k, l = max_corr_index
one_d_indices = k * n + l # 2D to 1D indexing
k = np.max(one_d_indices) // n
l = np.max(one_d_indices) % n
opt_scale = [k+1, l+1] # adding 1s to match R indexing
return stat, opt_scale
def _two_sample_transform(u, v):
"""
Helper function that concatenates x and y for two sample MGC stat. See
above for use.
Parameters
----------
u, v : ndarray
`u` and `v` have shapes `(n, p)` and `(m, p)`.
Returns
-------
x : ndarray
Concatenate `u` and `v` along the `axis = 0`. `x` thus has shape
`(2n, p)`.
y : ndarray
Label matrix for `x` where 0 refers to samples that comes from `u` and
1 refers to samples that come from `v`. `y` thus has shape `(2n, 1)`.
"""
nx = u.shape[0]
ny = v.shape[0]
x = np.concatenate([u, v], axis=0)
y = np.concatenate([np.zeros(nx), np.ones(ny)], axis=0).reshape(-1, 1)
return x, y
#####################################
# INFERENTIAL STATISTICS #
#####################################
Ttest_1sampResult = namedtuple('Ttest_1sampResult', ('statistic', 'pvalue'))
def ttest_1samp(a, popmean, axis=0, nan_policy='propagate',
alternative="two-sided"):
"""
Calculate the T-test for the mean of ONE group of scores.
This is a two-sided test for the null hypothesis that the expected value
(mean) of a sample of independent observations `a` is equal to the given
population mean, `popmean`.
Parameters
----------
a : array_like
Sample observation.
popmean : float or array_like
Expected value in null hypothesis. If array_like, then it must have the
same shape as `a` excluding the axis dimension.
axis : int or None, optional
Axis along which to compute test; default is 0. If None, compute over
the whole array `a`.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available (default is 'two-sided'):
* 'two-sided'
* 'less': one-sided
* 'greater': one-sided
.. versionadded:: 1.6.0
Returns
-------
statistic : float or array
t-statistic.
pvalue : float or array
Two-sided p-value.
Examples
--------
>>> from scipy import stats
>>> np.random.seed(7654567) # fix seed to get the same result
>>> rvs = stats.norm.rvs(loc=5, scale=10, size=(50,2))
Test if mean of random sample is equal to true mean, and different mean.
We reject the null hypothesis in the second case and don't reject it in
the first case.
>>> stats.ttest_1samp(rvs,5.0)
(array([-0.68014479, -0.04323899]), array([ 0.49961383, 0.96568674]))
>>> stats.ttest_1samp(rvs,0.0)
(array([ 2.77025808, 4.11038784]), array([ 0.00789095, 0.00014999]))
Examples using axis and non-scalar dimension for population mean.
>>> result = stats.ttest_1samp(rvs, [5.0, 0.0])
>>> result.statistic
array([-0.68014479, 4.11038784]),
>>> result.pvalue
array([4.99613833e-01, 1.49986458e-04])
>>> result = stats.ttest_1samp(rvs.T, [5.0, 0.0], axis=1)
>>> result.statistic
array([-0.68014479, 4.11038784])
>>> result.pvalue
array([4.99613833e-01, 1.49986458e-04])
>>> result = stats.ttest_1samp(rvs, [[5.0], [0.0]])
>>> result.statistic
array([[-0.68014479, -0.04323899],
[ 2.77025808, 4.11038784]])
>>> result.pvalue
array([[4.99613833e-01, 9.65686743e-01],
[7.89094663e-03, 1.49986458e-04]])
"""
a, axis = _chk_asarray(a, axis)
contains_nan, nan_policy = _contains_nan(a, nan_policy)
if contains_nan and nan_policy == 'omit':
if alternative != 'two-sided':
raise ValueError("nan-containing/masked inputs with "
"nan_policy='omit' are currently not "
"supported by one-sided alternatives.")
a = ma.masked_invalid(a)
return mstats_basic.ttest_1samp(a, popmean, axis)
n = a.shape[axis]
df = n - 1
d = np.mean(a, axis) - popmean
v = np.var(a, axis, ddof=1)
denom = np.sqrt(v / n)
with np.errstate(divide='ignore', invalid='ignore'):
t = np.divide(d, denom)
t, prob = _ttest_finish(df, t, alternative)
return Ttest_1sampResult(t, prob)
def _ttest_finish(df, t, alternative):
"""Common code between all 3 t-test functions."""
if alternative == 'less':
prob = distributions.t.cdf(t, df)
elif alternative == 'greater':
prob = distributions.t.sf(t, df)
elif alternative == 'two-sided':
prob = 2 * distributions.t.sf(np.abs(t), df)
else:
raise ValueError("alternative must be "
"'less', 'greater' or 'two-sided'")
if t.ndim == 0:
t = t[()]
return t, prob
def _ttest_ind_from_stats(mean1, mean2, denom, df, alternative):
d = mean1 - mean2
with np.errstate(divide='ignore', invalid='ignore'):
t = np.divide(d, denom)
t, prob = _ttest_finish(df, t, alternative)
return (t, prob)
def _unequal_var_ttest_denom(v1, n1, v2, n2):
vn1 = v1 / n1
vn2 = v2 / n2
with np.errstate(divide='ignore', invalid='ignore'):
df = (vn1 + vn2)**2 / (vn1**2 / (n1 - 1) + vn2**2 / (n2 - 1))
# If df is undefined, variances are zero (assumes n1 > 0 & n2 > 0).
# Hence it doesn't matter what df is as long as it's not NaN.
df = np.where(np.isnan(df), 1, df)
denom = np.sqrt(vn1 + vn2)
return df, denom
def _equal_var_ttest_denom(v1, n1, v2, n2):
df = n1 + n2 - 2.0
svar = ((n1 - 1) * v1 + (n2 - 1) * v2) / df
denom = np.sqrt(svar * (1.0 / n1 + 1.0 / n2))
return df, denom
Ttest_indResult = namedtuple('Ttest_indResult', ('statistic', 'pvalue'))
def ttest_ind_from_stats(mean1, std1, nobs1, mean2, std2, nobs2,
equal_var=True, alternative="two-sided"):
r"""
T-test for means of two independent samples from descriptive statistics.
This is a two-sided test for the null hypothesis that two independent
samples have identical average (expected) values.
Parameters
----------
mean1 : array_like
The mean(s) of sample 1.
std1 : array_like
The standard deviation(s) of sample 1.
nobs1 : array_like
The number(s) of observations of sample 1.
mean2 : array_like
The mean(s) of sample 2.
std2 : array_like
The standard deviations(s) of sample 2.
nobs2 : array_like
The number(s) of observations of sample 2.
equal_var : bool, optional
If True (default), perform a standard independent 2 sample test
that assumes equal population variances [1]_.
If False, perform Welch's t-test, which does not assume equal
population variance [2]_.
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available (default is 'two-sided'):
* 'two-sided'
* 'less': one-sided
* 'greater': one-sided
.. versionadded:: 1.6.0
Returns
-------
statistic : float or array
The calculated t-statistics.
pvalue : float or array
The two-tailed p-value.
See Also
--------
scipy.stats.ttest_ind
Notes
-----
.. versionadded:: 0.16.0
References
----------
.. [1] https://en.wikipedia.org/wiki/T-test#Independent_two-sample_t-test
.. [2] https://en.wikipedia.org/wiki/Welch%27s_t-test
Examples
--------
Suppose we have the summary data for two samples, as follows::
Sample Sample
Size Mean Variance
Sample 1 13 15.0 87.5
Sample 2 11 12.0 39.0
Apply the t-test to this data (with the assumption that the population
variances are equal):
>>> from scipy.stats import ttest_ind_from_stats
>>> ttest_ind_from_stats(mean1=15.0, std1=np.sqrt(87.5), nobs1=13,
... mean2=12.0, std2=np.sqrt(39.0), nobs2=11)
Ttest_indResult(statistic=0.9051358093310269, pvalue=0.3751996797581487)
For comparison, here is the data from which those summary statistics
were taken. With this data, we can compute the same result using
`scipy.stats.ttest_ind`:
>>> a = np.array([1, 3, 4, 6, 11, 13, 15, 19, 22, 24, 25, 26, 26])
>>> b = np.array([2, 4, 6, 9, 11, 13, 14, 15, 18, 19, 21])
>>> from scipy.stats import ttest_ind
>>> ttest_ind(a, b)
Ttest_indResult(statistic=0.905135809331027, pvalue=0.3751996797581486)
Suppose we instead have binary data and would like to apply a t-test to
compare the proportion of 1s in two independent groups::
Number of Sample Sample
Size ones Mean Variance
Sample 1 150 30 0.2 0.16
Sample 2 200 45 0.225 0.174375
The sample mean :math:`\hat{p}` is the proportion of ones in the sample
and the variance for a binary observation is estimated by
:math:`\hat{p}(1-\hat{p})`.
>>> ttest_ind_from_stats(mean1=0.2, std1=np.sqrt(0.16), nobs1=150,
... mean2=0.225, std2=np.sqrt(0.17437), nobs2=200)
Ttest_indResult(statistic=-0.564327545549774, pvalue=0.5728947691244874)
For comparison, we could compute the t statistic and p-value using
arrays of 0s and 1s and `scipy.stat.ttest_ind`, as above.
>>> group1 = np.array([1]*30 + [0]*(150-30))
>>> group2 = np.array([1]*45 + [0]*(200-45))
>>> ttest_ind(group1, group2)
Ttest_indResult(statistic=-0.5627179589855622, pvalue=0.573989277115258)
"""
mean1 = np.asarray(mean1)
std1 = np.asarray(std1)
mean2 = np.asarray(mean2)
std2 = np.asarray(std2)
if equal_var:
df, denom = _equal_var_ttest_denom(std1**2, nobs1, std2**2, nobs2)
else:
df, denom = _unequal_var_ttest_denom(std1**2, nobs1,
std2**2, nobs2)
res = _ttest_ind_from_stats(mean1, mean2, denom, df, alternative)
return Ttest_indResult(*res)
def _ttest_nans(a, b, axis, namedtuple_type):
"""
Generate an array of `nan`, with shape determined by `a`, `b` and `axis`.
This function is used by ttest_ind and ttest_rel to create the return
value when one of the inputs has size 0.
The shapes of the arrays are determined by dropping `axis` from the
shapes of `a` and `b` and broadcasting what is left.
The return value is a named tuple of the type given in `namedtuple_type`.
Examples
--------
>>> a = np.zeros((9, 2))
>>> b = np.zeros((5, 1))
>>> _ttest_nans(a, b, 0, Ttest_indResult)
Ttest_indResult(statistic=array([nan, nan]), pvalue=array([nan, nan]))
>>> a = np.zeros((3, 0, 9))
>>> b = np.zeros((1, 10))
>>> stat, p = _ttest_nans(a, b, -1, Ttest_indResult)
>>> stat
array([], shape=(3, 0), dtype=float64)
>>> p
array([], shape=(3, 0), dtype=float64)
>>> a = np.zeros(10)
>>> b = np.zeros(7)
>>> _ttest_nans(a, b, 0, Ttest_indResult)
Ttest_indResult(statistic=nan, pvalue=nan)
"""
shp = _broadcast_shapes_with_dropped_axis(a, b, axis)
if len(shp) == 0:
t = np.nan
p = np.nan
else:
t = np.full(shp, fill_value=np.nan)
p = t.copy()
return namedtuple_type(t, p)
def ttest_ind(a, b, axis=0, equal_var=True, nan_policy='propagate',
permutations=None, random_state=None, alternative="two-sided"):
"""
Calculate the T-test for the means of *two independent* samples of scores.
This is a two-sided test for the null hypothesis that 2 independent samples
have identical average (expected) values. This test assumes that the
populations have identical variances by default.
Parameters
----------
a, b : array_like
The arrays must have the same shape, except in the dimension
corresponding to `axis` (the first, by default).
axis : int or None, optional
Axis along which to compute test. If None, compute over the whole
arrays, `a`, and `b`.
equal_var : bool, optional
If True (default), perform a standard independent 2 sample test
that assumes equal population variances [1]_.
If False, perform Welch's t-test, which does not assume equal
population variance [2]_.
.. versionadded:: 0.11.0
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
The 'omit' option is not currently available for permutation tests or
one-sided asympyotic tests.
permutations : int or None (default), optional
The number of random permutations that will be used to estimate
p-values using a permutation test. If `permutations` equals or exceeds
the number of distinct permutations, an exact test is performed
instead (i.e. each distinct permutation is used exactly once).
If None (default), use the t-distribution to calculate p-values.
.. versionadded:: 1.7.0
random_state : int, RandomState, or Generator, optional
Pseudorandom number generator state used to generate permutations
(used only when `permutations` is not None).
.. versionadded:: 1.7.0
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available (default is 'two-sided'):
* 'two-sided'
* 'less': one-sided
* 'greater': one-sided
.. versionadded:: 1.6.0
Returns
-------
statistic : float or array
The calculated t-statistic.
pvalue : float or array
The two-tailed p-value.
Notes
-----
Suppose we observe two independent samples, e.g. flower petal lengths, and
we are considering whether the two samples were drawn from the same
population (e.g. the same species of flower or two species with similar
petal characteristics) or two different populations.
The t-test quantifies the difference between the arithmetic means
of the two samples. The p-value quantifies the probability of observing
as or more extreme values assuming the null hypothesis, that the
samples are drawn from populations with the same population means, is true.
A p-value larger than a chosen threshold (e.g. 5% or 1%) indicates that
our observation is not so unlikely to have occurred by chance. Therefore,
we do not reject the null hypothesis of equal population means.
If the p-value is smaller than our threshold, then we have evidence
against the null hypothesis of equal population means.
By default, the p-value is determined by comparing the t-statistic of the
observed data against a theoretical t-distribution, which assumes that the
populations are normally distributed.
When ``1 < permutations < factorial(n)``, where ``n`` is the total
number of data, the data are randomly assigned to either group `a`
or `b`, and the t-statistic is calculated. This process is performed
repeatedly (`permutation` times), generating a distribution of the
t-statistic under the null hypothesis, and the t-statistic of the observed
data is compared to this distribution to determine the p-value. When
``permutations >= factorial(n)``, an exact test is performed: the data are
permuted within and between the groups in each distinct way exactly once.
The permutation test can be computationally expensive and not necessarily
more accurate than the analytical test, but it does not make strong
assumptions about the shape of the underlying distribution.
References
----------
.. [1] https://en.wikipedia.org/wiki/T-test#Independent_two-sample_t-test
.. [2] https://en.wikipedia.org/wiki/Welch%27s_t-test
.. [3] http://en.wikipedia.org/wiki/Resampling_%28statistics%29
Examples
--------
>>> from scipy import stats
>>> np.random.seed(12345678)
Test with sample with identical means:
>>> rvs1 = stats.norm.rvs(loc=5, scale=10, size=500)
>>> rvs2 = stats.norm.rvs(loc=5, scale=10, size=500)
>>> stats.ttest_ind(rvs1, rvs2)
(0.26833823296239279, 0.78849443369564776)
>>> stats.ttest_ind(rvs1, rvs2, equal_var=False)
(0.26833823296239279, 0.78849452749500748)
`ttest_ind` underestimates p for unequal variances:
>>> rvs3 = stats.norm.rvs(loc=5, scale=20, size=500)
>>> stats.ttest_ind(rvs1, rvs3)
(-0.46580283298287162, 0.64145827413436174)
>>> stats.ttest_ind(rvs1, rvs3, equal_var=False)
(-0.46580283298287162, 0.64149646246569292)
When ``n1 != n2``, the equal variance t-statistic is no longer equal to the
unequal variance t-statistic:
>>> rvs4 = stats.norm.rvs(loc=5, scale=20, size=100)
>>> stats.ttest_ind(rvs1, rvs4)
(-0.99882539442782481, 0.3182832709103896)
>>> stats.ttest_ind(rvs1, rvs4, equal_var=False)
(-0.69712570584654099, 0.48716927725402048)
T-test with different means, variance, and n:
>>> rvs5 = stats.norm.rvs(loc=8, scale=20, size=100)
>>> stats.ttest_ind(rvs1, rvs5)
(-1.4679669854490653, 0.14263895620529152)
>>> stats.ttest_ind(rvs1, rvs5, equal_var=False)
(-0.94365973617132992, 0.34744170334794122)
When performing a permutation test, more permutations typically yields
more accurate results. Use a ``np.random.Generator`` to ensure
reproducibility:
>>> stats.ttest_ind(rvs1, rvs5, permutations=10000,
... random_state=np.random.default_rng(12345))
(-1.467966985449, 0.14)
"""
a, b, axis = _chk2_asarray(a, b, axis)
# check both a and b
cna, npa = _contains_nan(a, nan_policy)
cnb, npb = _contains_nan(b, nan_policy)
contains_nan = cna or cnb
if npa == 'omit' or npb == 'omit':
nan_policy = 'omit'
if contains_nan and nan_policy == 'omit':
if permutations or alternative != 'two-sided':
raise ValueError("nan-containing/masked inputs with "
"nan_policy='omit' are currently not "
"supported by permutation tests or one-sided"
"asymptotic tests.")
a = ma.masked_invalid(a)
b = ma.masked_invalid(b)
return mstats_basic.ttest_ind(a, b, axis, equal_var)
if a.size == 0 or b.size == 0:
return _ttest_nans(a, b, axis, Ttest_indResult)
if permutations:
if int(permutations) != permutations or permutations < 0:
raise ValueError("Permutations must be a positive integer.")
res = _permutation_ttest(a, b, permutations=permutations,
axis=axis, equal_var=equal_var,
nan_policy=nan_policy,
random_state=random_state,
alternative=alternative)
else:
v1 = np.var(a, axis, ddof=1)
v2 = np.var(b, axis, ddof=1)
n1 = a.shape[axis]
n2 = b.shape[axis]
if equal_var:
df, denom = _equal_var_ttest_denom(v1, n1, v2, n2)
else:
df, denom = _unequal_var_ttest_denom(v1, n1, v2, n2)
res = _ttest_ind_from_stats(np.mean(a, axis), np.mean(b, axis),
denom, df, alternative)
return Ttest_indResult(*res)
def _broadcast_concatenate(xs, axis):
"""Concatenate arrays along an axis with broadcasting"""
# move the axis we're concatenating along to the end
xs = [np.swapaxes(x, axis, -1) for x in xs]
# determine final shape of all but the last axis
shape = np.broadcast(*[x[..., 0] for x in xs]).shape
# broadcast along all but the last axis
xs = [np.broadcast_to(x, shape + (x.shape[-1],)) for x in xs]
# concatenate along last axis
res = np.concatenate(xs, axis = -1)
# move the last axis back to where it was
res = np.swapaxes(res, axis, -1)
return res
def _data_permutations(data, n, axis=-1, random_state=None):
"""Vectorized permutation of data, assumes `random_state` is already checked"""
random_state = check_random_state(random_state)
if axis < 0: # we'll be adding a new dimension at the end
axis = data.ndim + axis
# prepare permutation indices
m = data.shape[axis]
n_max = float_factorial(m) # number of distinct permutations
if n < n_max:
indices = np.array([random_state.permutation(m) for i in range(n)]).T
else:
n = n_max
indices = np.array(list(permutations(range(m)))).T
data = data.swapaxes(axis, -1) # so we can index along a new dimension
data = data[..., indices] # generate permutations
data = data.swapaxes(-2, axis) # restore original axis order
data = np.moveaxis(data, -1, 0) # permutations indexed along axis 0
return data, n
def _calc_t_stat(a, b, equal_var, axis=-1):
"""Calculate the t statistic along the given dimension"""
na = a.shape[axis]
nb = b.shape[axis]
avg_a = np.mean(a, axis=axis)
avg_b = np.mean(b, axis=axis)
var_a = np.var(a, axis=axis, ddof=1)
var_b = np.var(b, axis=axis, ddof=1)
if not equal_var:
denom = _unequal_var_ttest_denom(var_a, na, var_b, nb)[1]
else:
denom = _equal_var_ttest_denom(var_a, na, var_b, nb)[1]
return (avg_a-avg_b)/denom
def _permutation_ttest(a, b, permutations, axis=0, equal_var=True,
nan_policy='propagate', random_state=None,
alternative="two-sided"):
"""
Calculates the T-test for the means of TWO INDEPENDENT samples of scores
using permutation methods
This test is similar to `stats.ttest_ind`, except it doesn't rely on an
approximate normality assumption since it uses a permutation test.
This function is only called from ttest_ind when permutations is not None.
Parameters
----------
a, b : array_like
The arrays must be broadcastable, except along the dimension
corresponding to `axis` (the zeroth, by default).
axis : int, optional
The axis over which to operate on a and b.
permutations: int, optional
Number of permutations used to calculate p-value. If greater than or
equal to the number of distinct permutations, perform an exact test.
equal_var: bool, optional
If False, an equal variance (Welch's) t-test is conducted. Otherwise,
an ordinary t-test is conducted.
random_state : int, RandomState, or Generator, optional
Pseudorandom number generator state used for generating random
permutations.
Returns
-------
statistic : float or array
The calculated t-statistic.
pvalue : float or array
The two-tailed p-value.
"""
random_state = check_random_state(random_state)
t_stat_observed = _calc_t_stat(a, b, equal_var, axis=axis)
na = a.shape[axis]
mat = _broadcast_concatenate((a, b), axis=axis)
mat = np.moveaxis(mat, axis, -1)
mat_perm, permutations = _data_permutations(mat, n=permutations,
random_state=random_state)
a = mat_perm[..., :na]
b = mat_perm[..., na:]
t_stat = _calc_t_stat(a, b, equal_var)
compare = {"less": np.less_equal,
"greater": np.greater_equal,
"two-sided": lambda x, y: (x <= -np.abs(y)) | (x >= np.abs(y))}
# Calculate the p-values
cmps = compare[alternative](t_stat, t_stat_observed)
pvalues = cmps.sum(axis=0) / permutations
# nans propagate naturally in statistic calculation, but need to be
# propagated manually into pvalues
if nan_policy == 'propagate' and np.isnan(t_stat_observed).any():
if np.ndim(pvalues) == 0:
pvalues = np.float64(np.nan)
else:
pvalues[np.isnan(t_stat_observed)] = np.nan
return (t_stat_observed, pvalues)
def _get_len(a, axis, msg):
try:
n = a.shape[axis]
except IndexError:
raise np.AxisError(axis, a.ndim, msg) from None
return n
Ttest_relResult = namedtuple('Ttest_relResult', ('statistic', 'pvalue'))
def ttest_rel(a, b, axis=0, nan_policy='propagate', alternative="two-sided"):
"""
Calculate the t-test on TWO RELATED samples of scores, a and b.
This is a two-sided test for the null hypothesis that 2 related or
repeated samples have identical average (expected) values.
Parameters
----------
a, b : array_like
The arrays must have the same shape.
axis : int or None, optional
Axis along which to compute test. If None, compute over the whole
arrays, `a`, and `b`.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available (default is 'two-sided'):
* 'two-sided'
* 'less': one-sided
* 'greater': one-sided
.. versionadded:: 1.6.0
Returns
-------
statistic : float or array
t-statistic.
pvalue : float or array
Two-sided p-value.
Notes
-----
Examples for use are scores of the same set of student in
different exams, or repeated sampling from the same units. The
test measures whether the average score differs significantly
across samples (e.g. exams). If we observe a large p-value, for
example greater than 0.05 or 0.1 then we cannot reject the null
hypothesis of identical average scores. If the p-value is smaller
than the threshold, e.g. 1%, 5% or 10%, then we reject the null
hypothesis of equal averages. Small p-values are associated with
large t-statistics.
References
----------
https://en.wikipedia.org/wiki/T-test#Dependent_t-test_for_paired_samples
Examples
--------
>>> from scipy import stats
>>> np.random.seed(12345678) # fix random seed to get same numbers
>>> rvs1 = stats.norm.rvs(loc=5,scale=10,size=500)
>>> rvs2 = (stats.norm.rvs(loc=5,scale=10,size=500) +
... stats.norm.rvs(scale=0.2,size=500))
>>> stats.ttest_rel(rvs1,rvs2)
(0.24101764965300962, 0.80964043445811562)
>>> rvs3 = (stats.norm.rvs(loc=8,scale=10,size=500) +
... stats.norm.rvs(scale=0.2,size=500))
>>> stats.ttest_rel(rvs1,rvs3)
(-3.9995108708727933, 7.3082402191726459e-005)
"""
a, b, axis = _chk2_asarray(a, b, axis)
cna, npa = _contains_nan(a, nan_policy)
cnb, npb = _contains_nan(b, nan_policy)
contains_nan = cna or cnb
if npa == 'omit' or npb == 'omit':
nan_policy = 'omit'
if contains_nan and nan_policy == 'omit':
if alternative != 'two-sided':
raise ValueError("nan-containing/masked inputs with "
"nan_policy='omit' are currently not "
"supported by one-sided alternatives.")
a = ma.masked_invalid(a)
b = ma.masked_invalid(b)
m = ma.mask_or(ma.getmask(a), ma.getmask(b))
aa = ma.array(a, mask=m, copy=True)
bb = ma.array(b, mask=m, copy=True)
return mstats_basic.ttest_rel(aa, bb, axis)
na = _get_len(a, axis, "first argument")
nb = _get_len(b, axis, "second argument")
if na != nb:
raise ValueError('unequal length arrays')
if na == 0:
return _ttest_nans(a, b, axis, Ttest_relResult)
n = a.shape[axis]
df = n - 1
d = (a - b).astype(np.float64)
v = np.var(d, axis, ddof=1)
dm = np.mean(d, axis)
denom = np.sqrt(v / n)
with np.errstate(divide='ignore', invalid='ignore'):
t = np.divide(dm, denom)
t, prob = _ttest_finish(df, t, alternative)
return Ttest_relResult(t, prob)
# Map from names to lambda_ values used in power_divergence().
_power_div_lambda_names = {
"pearson": 1,
"log-likelihood": 0,
"freeman-tukey": -0.5,
"mod-log-likelihood": -1,
"neyman": -2,
"cressie-read": 2/3,
}
def _count(a, axis=None):
"""
Count the number of non-masked elements of an array.
This function behaves like np.ma.count(), but is much faster
for ndarrays.
"""
if hasattr(a, 'count'):
num = a.count(axis=axis)
if isinstance(num, np.ndarray) and num.ndim == 0:
# In some cases, the `count` method returns a scalar array (e.g.
# np.array(3)), but we want a plain integer.
num = int(num)
else:
if axis is None:
num = a.size
else:
num = a.shape[axis]
return num
def _m_broadcast_to(a, shape):
if np.ma.isMaskedArray(a):
return np.ma.masked_array(np.broadcast_to(a, shape),
mask=np.broadcast_to(a.mask, shape))
return np.broadcast_to(a, shape, subok=True)
Power_divergenceResult = namedtuple('Power_divergenceResult',
('statistic', 'pvalue'))
def power_divergence(f_obs, f_exp=None, ddof=0, axis=0, lambda_=None):
"""
Cressie-Read power divergence statistic and goodness of fit test.
This function tests the null hypothesis that the categorical data
has the given frequencies, using the Cressie-Read power divergence
statistic.
Parameters
----------
f_obs : array_like
Observed frequencies in each category.
f_exp : array_like, optional
Expected frequencies in each category. By default the categories are
assumed to be equally likely.
ddof : int, optional
"Delta degrees of freedom": adjustment to the degrees of freedom
for the p-value. The p-value is computed using a chi-squared
distribution with ``k - 1 - ddof`` degrees of freedom, where `k`
is the number of observed frequencies. The default value of `ddof`
is 0.
axis : int or None, optional
The axis of the broadcast result of `f_obs` and `f_exp` along which to
apply the test. If axis is None, all values in `f_obs` are treated
as a single data set. Default is 0.
lambda_ : float or str, optional
The power in the Cressie-Read power divergence statistic. The default
is 1. For convenience, `lambda_` may be assigned one of the following
strings, in which case the corresponding numerical value is used::
String Value Description
"pearson" 1 Pearson's chi-squared statistic.
In this case, the function is
equivalent to `stats.chisquare`.
"log-likelihood" 0 Log-likelihood ratio. Also known as
the G-test [3]_.
"freeman-tukey" -1/2 Freeman-Tukey statistic.
"mod-log-likelihood" -1 Modified log-likelihood ratio.
"neyman" -2 Neyman's statistic.
"cressie-read" 2/3 The power recommended in [5]_.
Returns
-------
statistic : float or ndarray
The Cressie-Read power divergence test statistic. The value is
a float if `axis` is None or if` `f_obs` and `f_exp` are 1-D.
pvalue : float or ndarray
The p-value of the test. The value is a float if `ddof` and the
return value `stat` are scalars.
See Also
--------
chisquare
Notes
-----
This test is invalid when the observed or expected frequencies in each
category are too small. A typical rule is that all of the observed
and expected frequencies should be at least 5.
Also, the sum of the observed and expected frequencies must be the same
for the test to be valid; `power_divergence` raises an error if the sums
do not agree within a relative tolerance of ``1e-8``.
When `lambda_` is less than zero, the formula for the statistic involves
dividing by `f_obs`, so a warning or error may be generated if any value
in `f_obs` is 0.
Similarly, a warning or error may be generated if any value in `f_exp` is
zero when `lambda_` >= 0.
The default degrees of freedom, k-1, are for the case when no parameters
of the distribution are estimated. If p parameters are estimated by
efficient maximum likelihood then the correct degrees of freedom are
k-1-p. If the parameters are estimated in a different way, then the
dof can be between k-1-p and k-1. However, it is also possible that
the asymptotic distribution is not a chisquare, in which case this
test is not appropriate.
This function handles masked arrays. If an element of `f_obs` or `f_exp`
is masked, then data at that position is ignored, and does not count
towards the size of the data set.
.. versionadded:: 0.13.0
References
----------
.. [1] Lowry, Richard. "Concepts and Applications of Inferential
Statistics". Chapter 8.
https://web.archive.org/web/20171015035606/http://faculty.vassar.edu/lowry/ch8pt1.html
.. [2] "Chi-squared test", https://en.wikipedia.org/wiki/Chi-squared_test
.. [3] "G-test", https://en.wikipedia.org/wiki/G-test
.. [4] Sokal, R. R. and Rohlf, F. J. "Biometry: the principles and
practice of statistics in biological research", New York: Freeman
(1981)
.. [5] Cressie, N. and Read, T. R. C., "Multinomial Goodness-of-Fit
Tests", J. Royal Stat. Soc. Series B, Vol. 46, No. 3 (1984),
pp. 440-464.
Examples
--------
(See `chisquare` for more examples.)
When just `f_obs` is given, it is assumed that the expected frequencies
are uniform and given by the mean of the observed frequencies. Here we
perform a G-test (i.e. use the log-likelihood ratio statistic):
>>> from scipy.stats import power_divergence
>>> power_divergence([16, 18, 16, 14, 12, 12], lambda_='log-likelihood')
(2.006573162632538, 0.84823476779463769)
The expected frequencies can be given with the `f_exp` argument:
>>> power_divergence([16, 18, 16, 14, 12, 12],
... f_exp=[16, 16, 16, 16, 16, 8],
... lambda_='log-likelihood')
(3.3281031458963746, 0.6495419288047497)
When `f_obs` is 2-D, by default the test is applied to each column.
>>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T
>>> obs.shape
(6, 2)
>>> power_divergence(obs, lambda_="log-likelihood")
(array([ 2.00657316, 6.77634498]), array([ 0.84823477, 0.23781225]))
By setting ``axis=None``, the test is applied to all data in the array,
which is equivalent to applying the test to the flattened array.
>>> power_divergence(obs, axis=None)
(23.31034482758621, 0.015975692534127565)
>>> power_divergence(obs.ravel())
(23.31034482758621, 0.015975692534127565)
`ddof` is the change to make to the default degrees of freedom.
>>> power_divergence([16, 18, 16, 14, 12, 12], ddof=1)
(2.0, 0.73575888234288467)
The calculation of the p-values is done by broadcasting the
test statistic with `ddof`.
>>> power_divergence([16, 18, 16, 14, 12, 12], ddof=[0,1,2])
(2.0, array([ 0.84914504, 0.73575888, 0.5724067 ]))
`f_obs` and `f_exp` are also broadcast. In the following, `f_obs` has
shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting
`f_obs` and `f_exp` has shape (2, 6). To compute the desired chi-squared
statistics, we must use ``axis=1``:
>>> power_divergence([16, 18, 16, 14, 12, 12],
... f_exp=[[16, 16, 16, 16, 16, 8],
... [8, 20, 20, 16, 12, 12]],
... axis=1)
(array([ 3.5 , 9.25]), array([ 0.62338763, 0.09949846]))
"""
# Convert the input argument `lambda_` to a numerical value.
if isinstance(lambda_, str):
if lambda_ not in _power_div_lambda_names:
names = repr(list(_power_div_lambda_names.keys()))[1:-1]
raise ValueError("invalid string for lambda_: {0!r}. Valid strings "
"are {1}".format(lambda_, names))
lambda_ = _power_div_lambda_names[lambda_]
elif lambda_ is None:
lambda_ = 1
f_obs = np.asanyarray(f_obs)
f_obs_float = f_obs.astype(np.float64)
if f_exp is not None:
f_exp = np.asanyarray(f_exp)
bshape = _broadcast_shapes(f_obs_float.shape, f_exp.shape)
f_obs_float = _m_broadcast_to(f_obs_float, bshape)
f_exp = _m_broadcast_to(f_exp, bshape)
rtol = 1e-8 # to pass existing tests
with np.errstate(invalid='ignore'):
f_obs_sum = f_obs_float.sum(axis=axis)
f_exp_sum = f_exp.sum(axis=axis)
relative_diff = (np.abs(f_obs_sum - f_exp_sum) /
np.minimum(f_obs_sum, f_exp_sum))
diff_gt_tol = (relative_diff > rtol).any()
if diff_gt_tol:
msg = (f"For each axis slice, the sum of the observed "
f"frequencies must agree with the sum of the "
f"expected frequencies to a relative tolerance "
f"of {rtol}, but the percent differences are:\n"
f"{relative_diff}")
raise ValueError(msg)
else:
# Ignore 'invalid' errors so the edge case of a data set with length 0
# is handled without spurious warnings.
with np.errstate(invalid='ignore'):
f_exp = f_obs.mean(axis=axis, keepdims=True)
# `terms` is the array of terms that are summed along `axis` to create
# the test statistic. We use some specialized code for a few special
# cases of lambda_.
if lambda_ == 1:
# Pearson's chi-squared statistic
terms = (f_obs_float - f_exp)**2 / f_exp
elif lambda_ == 0:
# Log-likelihood ratio (i.e. G-test)
terms = 2.0 * special.xlogy(f_obs, f_obs / f_exp)
elif lambda_ == -1:
# Modified log-likelihood ratio
terms = 2.0 * special.xlogy(f_exp, f_exp / f_obs)
else:
# General Cressie-Read power divergence.
terms = f_obs * ((f_obs / f_exp)**lambda_ - 1)
terms /= 0.5 * lambda_ * (lambda_ + 1)
stat = terms.sum(axis=axis)
num_obs = _count(terms, axis=axis)
ddof = asarray(ddof)
p = distributions.chi2.sf(stat, num_obs - 1 - ddof)
return Power_divergenceResult(stat, p)
def chisquare(f_obs, f_exp=None, ddof=0, axis=0):
"""
Calculate a one-way chi-square test.
The chi-square test tests the null hypothesis that the categorical data
has the given frequencies.
Parameters
----------
f_obs : array_like
Observed frequencies in each category.
f_exp : array_like, optional
Expected frequencies in each category. By default the categories are
assumed to be equally likely.
ddof : int, optional
"Delta degrees of freedom": adjustment to the degrees of freedom
for the p-value. The p-value is computed using a chi-squared
distribution with ``k - 1 - ddof`` degrees of freedom, where `k`
is the number of observed frequencies. The default value of `ddof`
is 0.
axis : int or None, optional
The axis of the broadcast result of `f_obs` and `f_exp` along which to
apply the test. If axis is None, all values in `f_obs` are treated
as a single data set. Default is 0.
Returns
-------
chisq : float or ndarray
The chi-squared test statistic. The value is a float if `axis` is
None or `f_obs` and `f_exp` are 1-D.
p : float or ndarray
The p-value of the test. The value is a float if `ddof` and the
return value `chisq` are scalars.
See Also
--------
scipy.stats.power_divergence
Notes
-----
This test is invalid when the observed or expected frequencies in each
category are too small. A typical rule is that all of the observed
and expected frequencies should be at least 5.
Also, the sum of the observed and expected frequencies must be the same
for the test to be valid; `chisquare` raises an error if the sums do not
agree within a relative tolerance of ``1e-8``.
The default degrees of freedom, k-1, are for the case when no parameters
of the distribution are estimated. If p parameters are estimated by
efficient maximum likelihood then the correct degrees of freedom are
k-1-p. If the parameters are estimated in a different way, then the
dof can be between k-1-p and k-1. However, it is also possible that
the asymptotic distribution is not chi-square, in which case this test
is not appropriate.
References
----------
.. [1] Lowry, Richard. "Concepts and Applications of Inferential
Statistics". Chapter 8.
https://web.archive.org/web/20171022032306/http://vassarstats.net:80/textbook/ch8pt1.html
.. [2] "Chi-squared test", https://en.wikipedia.org/wiki/Chi-squared_test
Examples
--------
When just `f_obs` is given, it is assumed that the expected frequencies
are uniform and given by the mean of the observed frequencies.
>>> from scipy.stats import chisquare
>>> chisquare([16, 18, 16, 14, 12, 12])
(2.0, 0.84914503608460956)
With `f_exp` the expected frequencies can be given.
>>> chisquare([16, 18, 16, 14, 12, 12], f_exp=[16, 16, 16, 16, 16, 8])
(3.5, 0.62338762774958223)
When `f_obs` is 2-D, by default the test is applied to each column.
>>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T
>>> obs.shape
(6, 2)
>>> chisquare(obs)
(array([ 2. , 6.66666667]), array([ 0.84914504, 0.24663415]))
By setting ``axis=None``, the test is applied to all data in the array,
which is equivalent to applying the test to the flattened array.
>>> chisquare(obs, axis=None)
(23.31034482758621, 0.015975692534127565)
>>> chisquare(obs.ravel())
(23.31034482758621, 0.015975692534127565)
`ddof` is the change to make to the default degrees of freedom.
>>> chisquare([16, 18, 16, 14, 12, 12], ddof=1)
(2.0, 0.73575888234288467)
The calculation of the p-values is done by broadcasting the
chi-squared statistic with `ddof`.
>>> chisquare([16, 18, 16, 14, 12, 12], ddof=[0,1,2])
(2.0, array([ 0.84914504, 0.73575888, 0.5724067 ]))
`f_obs` and `f_exp` are also broadcast. In the following, `f_obs` has
shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting
`f_obs` and `f_exp` has shape (2, 6). To compute the desired chi-squared
statistics, we use ``axis=1``:
>>> chisquare([16, 18, 16, 14, 12, 12],
... f_exp=[[16, 16, 16, 16, 16, 8], [8, 20, 20, 16, 12, 12]],
... axis=1)
(array([ 3.5 , 9.25]), array([ 0.62338763, 0.09949846]))
"""
return power_divergence(f_obs, f_exp=f_exp, ddof=ddof, axis=axis,
lambda_="pearson")
KstestResult = namedtuple('KstestResult', ('statistic', 'pvalue'))
def _compute_dplus(cdfvals):
"""Computes D+ as used in the Kolmogorov-Smirnov test.
Parameters
----------
cdfvals: array_like
Sorted array of CDF values between 0 and 1
Returns
-------
Maximum distance of the CDF values below Uniform(0, 1)
"""
n = len(cdfvals)
return (np.arange(1.0, n + 1) / n - cdfvals).max()
def _compute_dminus(cdfvals):
"""Computes D- as used in the Kolmogorov-Smirnov test.
Parameters
----------
cdfvals: array_like
Sorted array of CDF values between 0 and 1
Returns
-------
Maximum distance of the CDF values above Uniform(0, 1)
"""
n = len(cdfvals)
return (cdfvals - np.arange(0.0, n)/n).max()
def ks_1samp(x, cdf, args=(), alternative='two-sided', mode='auto'):
"""
Performs the Kolmogorov-Smirnov test for goodness of fit.
This performs a test of the distribution F(x) of an observed
random variable against a given distribution G(x). Under the null
hypothesis, the two distributions are identical, F(x)=G(x). The
alternative hypothesis can be either 'two-sided' (default), 'less'
or 'greater'. The KS test is only valid for continuous distributions.
Parameters
----------
x : array_like
a 1-D array of observations of iid random variables.
cdf : callable
callable used to calculate the cdf.
args : tuple, sequence, optional
Distribution parameters, used with `cdf`.
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available (default is 'two-sided'):
* 'two-sided'
* 'less': one-sided, see explanation in Notes
* 'greater': one-sided, see explanation in Notes
mode : {'auto', 'exact', 'approx', 'asymp'}, optional
Defines the distribution used for calculating the p-value.
The following options are available (default is 'auto'):
* 'auto' : selects one of the other options.
* 'exact' : uses the exact distribution of test statistic.
* 'approx' : approximates the two-sided probability with twice the one-sided probability
* 'asymp': uses asymptotic distribution of test statistic
Returns
-------
statistic : float
KS test statistic, either D, D+ or D- (depending on the value of 'alternative')
pvalue : float
One-tailed or two-tailed p-value.
See Also
--------
ks_2samp, kstest
Notes
-----
In the one-sided test, the alternative is that the empirical
cumulative distribution function of the random variable is "less"
or "greater" than the cumulative distribution function G(x) of the
hypothesis, ``F(x)<=G(x)``, resp. ``F(x)>=G(x)``.
Examples
--------
>>> from scipy import stats
>>> x = np.linspace(-15, 15, 9)
>>> stats.ks_1samp(x, stats.norm.cdf)
(0.44435602715924361, 0.038850142705171065)
>>> np.random.seed(987654321) # set random seed to get the same result
>>> stats.ks_1samp(stats.norm.rvs(size=100), stats.norm.cdf)
(0.058352892479417884, 0.8653960860778898)
*Test against one-sided alternative hypothesis*
Shift distribution to larger values, so that `` CDF(x) < norm.cdf(x)``:
>>> np.random.seed(987654321)
>>> x = stats.norm.rvs(loc=0.2, size=100)
>>> stats.ks_1samp(x, stats.norm.cdf, alternative='less')
(0.12464329735846891, 0.040989164077641749)
Reject equal distribution against alternative hypothesis: less
>>> stats.ks_1samp(x, stats.norm.cdf, alternative='greater')
(0.0072115233216311081, 0.98531158590396395)
Don't reject equal distribution against alternative hypothesis: greater
>>> stats.ks_1samp(x, stats.norm.cdf)
(0.12464329735846891, 0.08197335233541582)
Don't reject equal distribution against alternative hypothesis: two-sided
*Testing t distributed random variables against normal distribution*
With 100 degrees of freedom the t distribution looks close to the normal
distribution, and the K-S test does not reject the hypothesis that the
sample came from the normal distribution:
>>> np.random.seed(987654321)
>>> stats.ks_1samp(stats.t.rvs(100,size=100), stats.norm.cdf)
(0.072018929165471257, 0.6505883498379312)
With 3 degrees of freedom the t distribution looks sufficiently different
from the normal distribution, that we can reject the hypothesis that the
sample came from the normal distribution at the 10% level:
>>> np.random.seed(987654321)
>>> stats.ks_1samp(stats.t.rvs(3,size=100), stats.norm.cdf)
(0.131016895759829, 0.058826222555312224)
"""
alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get(
alternative.lower()[0], alternative)
if alternative not in ['two-sided', 'greater', 'less']:
raise ValueError("Unexpected alternative %s" % alternative)
if np.ma.is_masked(x):
x = x.compressed()
N = len(x)
x = np.sort(x)
cdfvals = cdf(x, *args)
if alternative == 'greater':
Dplus = _compute_dplus(cdfvals)
return KstestResult(Dplus, distributions.ksone.sf(Dplus, N))
if alternative == 'less':
Dminus = _compute_dminus(cdfvals)
return KstestResult(Dminus, distributions.ksone.sf(Dminus, N))
# alternative == 'two-sided':
Dplus = _compute_dplus(cdfvals)
Dminus = _compute_dminus(cdfvals)
D = np.max([Dplus, Dminus])
if mode == 'auto': # Always select exact
mode = 'exact'
if mode == 'exact':
prob = distributions.kstwo.sf(D, N)
elif mode == 'asymp':
prob = distributions.kstwobign.sf(D * np.sqrt(N))
else:
# mode == 'approx'
prob = 2 * distributions.ksone.sf(D, N)
prob = np.clip(prob, 0, 1)
return KstestResult(D, prob)
Ks_2sampResult = KstestResult
def _compute_prob_inside_method(m, n, g, h):
"""
Count the proportion of paths that stay strictly inside two diagonal lines.
Parameters
----------
m : integer
m > 0
n : integer
n > 0
g : integer
g is greatest common divisor of m and n
h : integer
0 <= h <= lcm(m,n)
Returns
-------
p : float
The proportion of paths that stay inside the two lines.
Count the integer lattice paths from (0, 0) to (m, n) which satisfy
|x/m - y/n| < h / lcm(m, n).
The paths make steps of size +1 in either positive x or positive y directions.
We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk.
Hodges, J.L. Jr.,
"The Significance Probability of the Smirnov Two-Sample Test,"
Arkiv fiur Matematik, 3, No. 43 (1958), 469-86.
"""
# Probability is symmetrical in m, n. Computation below uses m >= n.
if m < n:
m, n = n, m
mg = m // g
ng = n // g
# Count the integer lattice paths from (0, 0) to (m, n) which satisfy
# |nx/g - my/g| < h.
# Compute matrix A such that:
# A(x, 0) = A(0, y) = 1
# A(x, y) = A(x, y-1) + A(x-1, y), for x,y>=1, except that
# A(x, y) = 0 if |x/m - y/n|>= h
# Probability is A(m, n)/binom(m+n, n)
# Optimizations exist for m==n, m==n*p.
# Only need to preserve a single column of A, and only a sliding window of it.
# minj keeps track of the slide.
minj, maxj = 0, min(int(np.ceil(h / mg)), n + 1)
curlen = maxj - minj
# Make a vector long enough to hold maximum window needed.
lenA = min(2 * maxj + 2, n + 1)
# This is an integer calculation, but the entries are essentially
# binomial coefficients, hence grow quickly.
# Scaling after each column is computed avoids dividing by a
# large binomial coefficent at the end, but is not sufficient to avoid
# the large dyanamic range which appears during the calculation.
# Instead we rescale based on the magnitude of the right most term in
# the column and keep track of an exponent separately and apply
# it at the end of the calculation. Similarly when multiplying by
# the binomial coefficint
dtype = np.float64
A = np.zeros(lenA, dtype=dtype)
# Initialize the first column
A[minj:maxj] = 1
expnt = 0
for i in range(1, m + 1):
# Generate the next column.
# First calculate the sliding window
lastminj, lastlen = minj, curlen
minj = max(int(np.floor((ng * i - h) / mg)) + 1, 0)
minj = min(minj, n)
maxj = min(int(np.ceil((ng * i + h) / mg)), n + 1)
if maxj <= minj:
return 0
# Now fill in the values
A[0:maxj - minj] = np.cumsum(A[minj - lastminj:maxj - lastminj])
curlen = maxj - minj
if lastlen > curlen:
# Set some carried-over elements to 0
A[maxj - minj:maxj - minj + (lastlen - curlen)] = 0
# Rescale if the right most value is over 2**900
val = A[maxj - minj - 1]
_, valexpt = math.frexp(val)
if valexpt > 900:
# Scaling to bring down to about 2**800 appears
# sufficient for sizes under 10000.
valexpt -= 800
A = np.ldexp(A, -valexpt)
expnt += valexpt
val = A[maxj - minj - 1]
# Now divide by the binomial (m+n)!/m!/n!
for i in range(1, n + 1):
val = (val * i) / (m + i)
_, valexpt = math.frexp(val)
if valexpt < -128:
val = np.ldexp(val, -valexpt)
expnt += valexpt
# Finally scale if needed.
return np.ldexp(val, expnt)
def _compute_prob_outside_square(n, h):
"""
Compute the proportion of paths that pass outside the two diagonal lines.
Parameters
----------
n : integer
n > 0
h : integer
0 <= h <= n
Returns
-------
p : float
The proportion of paths that pass outside the lines x-y = +/-h.
"""
# Compute Pr(D_{n,n} >= h/n)
# Prob = 2 * ( binom(2n, n-h) - binom(2n, n-2a) + binom(2n, n-3a) - ... ) / binom(2n, n)
# This formulation exhibits subtractive cancellation.
# Instead divide each term by binom(2n, n), then factor common terms
# and use a Horner-like algorithm
# P = 2 * A0 * (1 - A1*(1 - A2*(1 - A3*(1 - A4*(...)))))
P = 0.0
k = int(np.floor(n / h))
while k >= 0:
p1 = 1.0
# Each of the Ai terms has numerator and denominator with h simple terms.
for j in range(h):
p1 = (n - k * h - j) * p1 / (n + k * h + j + 1)
P = p1 * (1.0 - P)
k -= 1
return 2 * P
def _count_paths_outside_method(m, n, g, h):
"""
Count the number of paths that pass outside the specified diagonal.
Parameters
----------
m : integer
m > 0
n : integer
n > 0
g : integer
g is greatest common divisor of m and n
h : integer
0 <= h <= lcm(m,n)
Returns
-------
p : float
The number of paths that go low.
The calculation may overflow - check for a finite answer.
Raises
------
FloatingPointError: Raised if the intermediate computation goes outside
the range of a float.
Notes
-----
Count the integer lattice paths from (0, 0) to (m, n), which at some
point (x, y) along the path, satisfy:
m*y <= n*x - h*g
The paths make steps of size +1 in either positive x or positive y directions.
We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk.
Hodges, J.L. Jr.,
"The Significance Probability of the Smirnov Two-Sample Test,"
Arkiv fiur Matematik, 3, No. 43 (1958), 469-86.
"""
# Compute #paths which stay lower than x/m-y/n = h/lcm(m,n)
# B(x, y) = #{paths from (0,0) to (x,y) without previously crossing the boundary}
# = binom(x, y) - #{paths which already reached the boundary}
# Multiply by the number of path extensions going from (x, y) to (m, n)
# Sum.
# Probability is symmetrical in m, n. Computation below assumes m >= n.
if m < n:
m, n = n, m
mg = m // g
ng = n // g
# Not every x needs to be considered.
# xj holds the list of x values to be checked.
# Wherever n*x/m + ng*h crosses an integer
lxj = n + (mg-h)//mg
xj = [(h + mg * j + ng-1)//ng for j in range(lxj)]
# B is an array just holding a few values of B(x,y), the ones needed.
# B[j] == B(x_j, j)
if lxj == 0:
return np.round(special.binom(m + n, n))
B = np.zeros(lxj)
B[0] = 1
# Compute the B(x, y) terms
# The binomial coefficient is an integer, but special.binom() may return a float.
# Round it to the nearest integer.
for j in range(1, lxj):
Bj = np.round(special.binom(xj[j] + j, j))
if not np.isfinite(Bj):
raise FloatingPointError()
for i in range(j):
bin = np.round(special.binom(xj[j] - xj[i] + j - i, j-i))
Bj -= bin * B[i]
B[j] = Bj
if not np.isfinite(Bj):
raise FloatingPointError()
# Compute the number of path extensions...
num_paths = 0
for j in range(lxj):
bin = np.round(special.binom((m-xj[j]) + (n - j), n-j))
term = B[j] * bin
if not np.isfinite(term):
raise FloatingPointError()
num_paths += term
return np.round(num_paths)
def _attempt_exact_2kssamp(n1, n2, g, d, alternative):
"""Attempts to compute the exact 2sample probability.
n1, n2 are the sample sizes
g is the gcd(n1, n2)
d is the computed max difference in ECDFs
Returns (success, d, probability)
"""
lcm = (n1 // g) * n2
h = int(np.round(d * lcm))
d = h * 1.0 / lcm
if h == 0:
return True, d, 1.0
saw_fp_error, prob = False, np.nan
try:
if alternative == 'two-sided':
if n1 == n2:
prob = _compute_prob_outside_square(n1, h)
else:
prob = 1 - _compute_prob_inside_method(n1, n2, g, h)
else:
if n1 == n2:
# prob = binom(2n, n-h) / binom(2n, n)
# Evaluating in that form incurs roundoff errors
# from special.binom. Instead calculate directly
jrange = np.arange(h)
prob = np.prod((n1 - jrange) / (n1 + jrange + 1.0))
else:
num_paths = _count_paths_outside_method(n1, n2, g, h)
bin = special.binom(n1 + n2, n1)
if not np.isfinite(bin) or not np.isfinite(num_paths) or num_paths > bin:
saw_fp_error = True
else:
prob = num_paths / bin
except FloatingPointError:
saw_fp_error = True
if saw_fp_error:
return False, d, np.nan
if not (0 <= prob <= 1):
return False, d, prob
return True, d, prob
def ks_2samp(data1, data2, alternative='two-sided', mode='auto'):
"""
Compute the Kolmogorov-Smirnov statistic on 2 samples.
This is a two-sided test for the null hypothesis that 2 independent samples
are drawn from the same continuous distribution. The alternative hypothesis
can be either 'two-sided' (default), 'less' or 'greater'.
Parameters
----------
data1, data2 : array_like, 1-Dimensional
Two arrays of sample observations assumed to be drawn from a continuous
distribution, sample sizes can be different.
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available (default is 'two-sided'):
* 'two-sided'
* 'less': one-sided, see explanation in Notes
* 'greater': one-sided, see explanation in Notes
mode : {'auto', 'exact', 'asymp'}, optional
Defines the method used for calculating the p-value.
The following options are available (default is 'auto'):
* 'auto' : use 'exact' for small size arrays, 'asymp' for large
* 'exact' : use exact distribution of test statistic
* 'asymp' : use asymptotic distribution of test statistic
Returns
-------
statistic : float
KS statistic.
pvalue : float
Two-tailed p-value.
See Also
--------
kstest, ks_1samp, epps_singleton_2samp, anderson_ksamp
Notes
-----
This tests whether 2 samples are drawn from the same distribution. Note
that, like in the case of the one-sample KS test, the distribution is
assumed to be continuous.
In the one-sided test, the alternative is that the empirical
cumulative distribution function F(x) of the data1 variable is "less"
or "greater" than the empirical cumulative distribution function G(x)
of the data2 variable, ``F(x)<=G(x)``, resp. ``F(x)>=G(x)``.
If the KS statistic is small or the p-value is high, then we cannot
reject the hypothesis that the distributions of the two samples
are the same.
If the mode is 'auto', the computation is exact if the sample sizes are
less than 10000. For larger sizes, the computation uses the
Kolmogorov-Smirnov distributions to compute an approximate value.
The 'two-sided' 'exact' computation computes the complementary probability
and then subtracts from 1. As such, the minimum probability it can return
is about 1e-16. While the algorithm itself is exact, numerical
errors may accumulate for large sample sizes. It is most suited to
situations in which one of the sample sizes is only a few thousand.
We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk [1]_.
References
----------
.. [1] Hodges, J.L. Jr., "The Significance Probability of the Smirnov
Two-Sample Test," Arkiv fiur Matematik, 3, No. 43 (1958), 469-86.
Examples
--------
>>> from scipy import stats
>>> np.random.seed(12345678) #fix random seed to get the same result
>>> n1 = 200 # size of first sample
>>> n2 = 300 # size of second sample
For a different distribution, we can reject the null hypothesis since the
pvalue is below 1%:
>>> rvs1 = stats.norm.rvs(size=n1, loc=0., scale=1)
>>> rvs2 = stats.norm.rvs(size=n2, loc=0.5, scale=1.5)
>>> stats.ks_2samp(rvs1, rvs2)
(0.20833333333333334, 5.129279597781977e-05)
For a slightly different distribution, we cannot reject the null hypothesis
at a 10% or lower alpha since the p-value at 0.144 is higher than 10%
>>> rvs3 = stats.norm.rvs(size=n2, loc=0.01, scale=1.0)
>>> stats.ks_2samp(rvs1, rvs3)
(0.10333333333333333, 0.14691437867433876)
For an identical distribution, we cannot reject the null hypothesis since
the p-value is high, 41%:
>>> rvs4 = stats.norm.rvs(size=n2, loc=0.0, scale=1.0)
>>> stats.ks_2samp(rvs1, rvs4)
(0.07999999999999996, 0.41126949729859719)
"""
if mode not in ['auto', 'exact', 'asymp']:
raise ValueError(f'Invalid value for mode: {mode}')
alternative = {'t': 'two-sided', 'g': 'greater', 'l': 'less'}.get(
alternative.lower()[0], alternative)
if alternative not in ['two-sided', 'less', 'greater']:
raise ValueError(f'Invalid value for alternative: {alternative}')
MAX_AUTO_N = 10000 # 'auto' will attempt to be exact if n1,n2 <= MAX_AUTO_N
if np.ma.is_masked(data1):
data1 = data1.compressed()
if np.ma.is_masked(data2):
data2 = data2.compressed()
data1 = np.sort(data1)
data2 = np.sort(data2)
n1 = data1.shape[0]
n2 = data2.shape[0]
if min(n1, n2) == 0:
raise ValueError('Data passed to ks_2samp must not be empty')
data_all = np.concatenate([data1, data2])
# using searchsorted solves equal data problem
cdf1 = np.searchsorted(data1, data_all, side='right') / n1
cdf2 = np.searchsorted(data2, data_all, side='right') / n2
cddiffs = cdf1 - cdf2
minS = np.clip(-np.min(cddiffs), 0, 1) # Ensure sign of minS is not negative.
maxS = np.max(cddiffs)
alt2Dvalue = {'less': minS, 'greater': maxS, 'two-sided': max(minS, maxS)}
d = alt2Dvalue[alternative]
g = gcd(n1, n2)
n1g = n1 // g
n2g = n2 // g
prob = -np.inf
original_mode = mode
if mode == 'auto':
mode = 'exact' if max(n1, n2) <= MAX_AUTO_N else 'asymp'
elif mode == 'exact':
# If lcm(n1, n2) is too big, switch from exact to asymp
if n1g >= np.iinfo(np.int_).max / n2g:
mode = 'asymp'
warnings.warn(
f"Exact ks_2samp calculation not possible with samples sizes "
f"{n1} and {n2}. Switching to 'asymp'.", RuntimeWarning)
if mode == 'exact':
success, d, prob = _attempt_exact_2kssamp(n1, n2, g, d, alternative)
if not success:
mode = 'asymp'
if original_mode == 'exact':
warnings.warn(f"ks_2samp: Exact calculation unsuccessful. "
f"Switching to mode={mode}.", RuntimeWarning)
if mode == 'asymp':
# The product n1*n2 is large. Use Smirnov's asymptoptic formula.
# Ensure float to avoid overflow in multiplication
# sorted because the one-sided formula is not symmetric in n1, n2
m, n = sorted([float(n1), float(n2)], reverse=True)
en = m * n / (m + n)
if alternative == 'two-sided':
prob = distributions.kstwo.sf(d, np.round(en))
else:
z = np.sqrt(en) * d
# Use Hodges' suggested approximation Eqn 5.3
# Requires m to be the larger of (n1, n2)
expt = -2 * z**2 - 2 * z * (m + 2*n)/np.sqrt(m*n*(m+n))/3.0
prob = np.exp(expt)
prob = np.clip(prob, 0, 1)
return KstestResult(d, prob)
def _parse_kstest_args(data1, data2, args, N):
# kstest allows many different variations of arguments.
# Pull out the parsing into a separate function
# (xvals, yvals, ) # 2sample
# (xvals, cdf function,..)
# (xvals, name of distribution, ...)
# (name of distribution, name of distribution, ...)
# Returns xvals, yvals, cdf
# where cdf is a cdf function, or None
# and yvals is either an array_like of values, or None
# and xvals is array_like.
rvsfunc, cdf = None, None
if isinstance(data1, str):
rvsfunc = getattr(distributions, data1).rvs
elif callable(data1):
rvsfunc = data1
if isinstance(data2, str):
cdf = getattr(distributions, data2).cdf
data2 = None
elif callable(data2):
cdf = data2
data2 = None
data1 = np.sort(rvsfunc(*args, size=N) if rvsfunc else data1)
return data1, data2, cdf
def kstest(rvs, cdf, args=(), N=20, alternative='two-sided', mode='auto'):
"""
Performs the (one sample or two samples) Kolmogorov-Smirnov test for goodness of fit.
The one-sample test performs a test of the distribution F(x) of an observed
random variable against a given distribution G(x). Under the null
hypothesis, the two distributions are identical, F(x)=G(x). The
alternative hypothesis can be either 'two-sided' (default), 'less'
or 'greater'. The KS test is only valid for continuous distributions.
The two-sample test tests whether the two independent samples are drawn
from the same continuous distribution.
Parameters
----------
rvs : str, array_like, or callable
If an array, it should be a 1-D array of observations of random
variables.
If a callable, it should be a function to generate random variables;
it is required to have a keyword argument `size`.
If a string, it should be the name of a distribution in `scipy.stats`,
which will be used to generate random variables.
cdf : str, array_like or callable
If array_like, it should be a 1-D array of observations of random
variables, and the two-sample test is performed (and rvs must be array_like)
If a callable, that callable is used to calculate the cdf.
If a string, it should be the name of a distribution in `scipy.stats`,
which will be used as the cdf function.
args : tuple, sequence, optional
Distribution parameters, used if `rvs` or `cdf` are strings or callables.
N : int, optional
Sample size if `rvs` is string or callable. Default is 20.
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available (default is 'two-sided'):
* 'two-sided'
* 'less': one-sided, see explanation in Notes
* 'greater': one-sided, see explanation in Notes
mode : {'auto', 'exact', 'approx', 'asymp'}, optional
Defines the distribution used for calculating the p-value.
The following options are available (default is 'auto'):
* 'auto' : selects one of the other options.
* 'exact' : uses the exact distribution of test statistic.
* 'approx' : approximates the two-sided probability with twice the one-sided probability
* 'asymp': uses asymptotic distribution of test statistic
Returns
-------
statistic : float
KS test statistic, either D, D+ or D-.
pvalue : float
One-tailed or two-tailed p-value.
See Also
--------
ks_2samp
Notes
-----
In the one-sided test, the alternative is that the empirical
cumulative distribution function of the random variable is "less"
or "greater" than the cumulative distribution function G(x) of the
hypothesis, ``F(x)<=G(x)``, resp. ``F(x)>=G(x)``.
Examples
--------
>>> from scipy import stats
>>> x = np.linspace(-15, 15, 9)
>>> stats.kstest(x, 'norm')
(0.44435602715924361, 0.038850142705171065)
>>> np.random.seed(987654321) # set random seed to get the same result
>>> stats.kstest(stats.norm.rvs(size=100), stats.norm.cdf)
(0.058352892479417884, 0.8653960860778898)
The above lines are equivalent to:
>>> np.random.seed(987654321)
>>> stats.kstest(stats.norm.rvs, 'norm', N=100)
(0.058352892479417884, 0.8653960860778898)
*Test against one-sided alternative hypothesis*
Shift distribution to larger values, so that ``CDF(x) < norm.cdf(x)``:
>>> np.random.seed(987654321)
>>> x = stats.norm.rvs(loc=0.2, size=100)
>>> stats.kstest(x, 'norm', alternative='less')
(0.12464329735846891, 0.040989164077641749)
Reject equal distribution against alternative hypothesis: less
>>> stats.kstest(x, 'norm', alternative='greater')
(0.0072115233216311081, 0.98531158590396395)
Don't reject equal distribution against alternative hypothesis: greater
>>> stats.kstest(x, 'norm')
(0.12464329735846891, 0.08197335233541582)
*Testing t distributed random variables against normal distribution*
With 100 degrees of freedom the t distribution looks close to the normal
distribution, and the K-S test does not reject the hypothesis that the
sample came from the normal distribution:
>>> np.random.seed(987654321)
>>> stats.kstest(stats.t.rvs(100, size=100), 'norm')
(0.072018929165471257, 0.6505883498379312)
With 3 degrees of freedom the t distribution looks sufficiently different
from the normal distribution, that we can reject the hypothesis that the
sample came from the normal distribution at the 10% level:
>>> np.random.seed(987654321)
>>> stats.kstest(stats.t.rvs(3, size=100), 'norm')
(0.131016895759829, 0.058826222555312224)
"""
# to not break compatibility with existing code
if alternative == 'two_sided':
alternative = 'two-sided'
if alternative not in ['two-sided', 'greater', 'less']:
raise ValueError("Unexpected alternative %s" % alternative)
xvals, yvals, cdf = _parse_kstest_args(rvs, cdf, args, N)
if cdf:
return ks_1samp(xvals, cdf, args=args, alternative=alternative, mode=mode)
return ks_2samp(xvals, yvals, alternative=alternative, mode=mode)
def tiecorrect(rankvals):
"""
Tie correction factor for Mann-Whitney U and Kruskal-Wallis H tests.
Parameters
----------
rankvals : array_like
A 1-D sequence of ranks. Typically this will be the array
returned by `~scipy.stats.rankdata`.
Returns
-------
factor : float
Correction factor for U or H.
See Also
--------
rankdata : Assign ranks to the data
mannwhitneyu : Mann-Whitney rank test
kruskal : Kruskal-Wallis H test
References
----------
.. [1] Siegel, S. (1956) Nonparametric Statistics for the Behavioral
Sciences. New York: McGraw-Hill.
Examples
--------
>>> from scipy.stats import tiecorrect, rankdata
>>> tiecorrect([1, 2.5, 2.5, 4])
0.9
>>> ranks = rankdata([1, 3, 2, 4, 5, 7, 2, 8, 4])
>>> ranks
array([ 1. , 4. , 2.5, 5.5, 7. , 8. , 2.5, 9. , 5.5])
>>> tiecorrect(ranks)
0.9833333333333333
"""
arr = np.sort(rankvals)
idx = np.nonzero(np.r_[True, arr[1:] != arr[:-1], True])[0]
cnt = np.diff(idx).astype(np.float64)
size = np.float64(arr.size)
return 1.0 if size < 2 else 1.0 - (cnt**3 - cnt).sum() / (size**3 - size)
MannwhitneyuResult = namedtuple('MannwhitneyuResult', ('statistic', 'pvalue'))
def mannwhitneyu(x, y, use_continuity=True, alternative=None):
"""
Compute the Mann-Whitney rank test on samples x and y.
Parameters
----------
x, y : array_like
Array of samples, should be one-dimensional.
use_continuity : bool, optional
Whether a continuity correction (1/2.) should be taken into
account. Default is True.
alternative : {None, 'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available (default is None):
* None: computes p-value half the size of the 'two-sided' p-value and
a different U statistic. The default behavior is not the same as
using 'less' or 'greater'; it only exists for backward compatibility
and is deprecated.
* 'two-sided'
* 'less': one-sided
* 'greater': one-sided
Use of the None option is deprecated.
Returns
-------
statistic : float
The Mann-Whitney U statistic, equal to min(U for x, U for y) if
`alternative` is equal to None (deprecated; exists for backward
compatibility), and U for y otherwise.
pvalue : float
p-value assuming an asymptotic normal distribution. One-sided or
two-sided, depending on the choice of `alternative`.
Notes
-----
Use only when the number of observation in each sample is > 20 and
you have 2 independent samples of ranks. Mann-Whitney U is
significant if the u-obtained is LESS THAN or equal to the critical
value of U.
This test corrects for ties and by default uses a continuity correction.
References
----------
.. [1] https://en.wikipedia.org/wiki/Mann-Whitney_U_test
.. [2] H.B. Mann and D.R. Whitney, "On a Test of Whether one of Two Random
Variables is Stochastically Larger than the Other," The Annals of
Mathematical Statistics, vol. 18, no. 1, pp. 50-60, 1947.
"""
if alternative is None:
warnings.warn("Calling `mannwhitneyu` without specifying "
"`alternative` is deprecated.", DeprecationWarning)
x = np.asarray(x)
y = np.asarray(y)
n1 = len(x)
n2 = len(y)
ranked = rankdata(np.concatenate((x, y)))
rankx = ranked[0:n1] # get the x-ranks
u1 = n1*n2 + (n1*(n1+1))/2.0 - np.sum(rankx, axis=0) # calc U for x
u2 = n1*n2 - u1 # remainder is U for y
T = tiecorrect(ranked)
if T == 0:
raise ValueError('All numbers are identical in mannwhitneyu')
sd = np.sqrt(T * n1 * n2 * (n1+n2+1) / 12.0)
meanrank = n1*n2/2.0 + 0.5 * use_continuity
if alternative is None or alternative == 'two-sided':
bigu = max(u1, u2)
elif alternative == 'less':
bigu = u1
elif alternative == 'greater':
bigu = u2
else:
raise ValueError("alternative should be None, 'less', 'greater' "
"or 'two-sided'")
z = (bigu - meanrank) / sd
if alternative is None:
# This behavior, equal to half the size of the two-sided
# p-value, is deprecated.
p = distributions.norm.sf(abs(z))
elif alternative == 'two-sided':
p = 2 * distributions.norm.sf(abs(z))
else:
p = distributions.norm.sf(z)
u = u2
# This behavior is deprecated.
if alternative is None:
u = min(u1, u2)
return MannwhitneyuResult(u, p)
RanksumsResult = namedtuple('RanksumsResult', ('statistic', 'pvalue'))
def ranksums(x, y):
"""
Compute the Wilcoxon rank-sum statistic for two samples.
The Wilcoxon rank-sum test tests the null hypothesis that two sets
of measurements are drawn from the same distribution. The alternative
hypothesis is that values in one sample are more likely to be
larger than the values in the other sample.
This test should be used to compare two samples from continuous
distributions. It does not handle ties between measurements
in x and y. For tie-handling and an optional continuity correction
see `scipy.stats.mannwhitneyu`.
Parameters
----------
x,y : array_like
The data from the two samples.
Returns
-------
statistic : float
The test statistic under the large-sample approximation that the
rank sum statistic is normally distributed.
pvalue : float
The two-sided p-value of the test.
References
----------
.. [1] https://en.wikipedia.org/wiki/Wilcoxon_rank-sum_test
Examples
--------
We can test the hypothesis that two independent unequal-sized samples are
drawn from the same distribution with computing the Wilcoxon rank-sum
statistic.
>>> from scipy.stats import ranksums
>>> sample1 = np.random.uniform(-1, 1, 200)
>>> sample2 = np.random.uniform(-0.5, 1.5, 300) # a shifted distribution
>>> ranksums(sample1, sample2)
RanksumsResult(statistic=-7.887059, pvalue=3.09390448e-15) # may vary
The p-value of less than ``0.05`` indicates that this test rejects the
hypothesis at the 5% significance level.
"""
x, y = map(np.asarray, (x, y))
n1 = len(x)
n2 = len(y)
alldata = np.concatenate((x, y))
ranked = rankdata(alldata)
x = ranked[:n1]
s = np.sum(x, axis=0)
expected = n1 * (n1+n2+1) / 2.0
z = (s - expected) / np.sqrt(n1*n2*(n1+n2+1)/12.0)
prob = 2 * distributions.norm.sf(abs(z))
return RanksumsResult(z, prob)
KruskalResult = namedtuple('KruskalResult', ('statistic', 'pvalue'))
def kruskal(*args, nan_policy='propagate'):
"""
Compute the Kruskal-Wallis H-test for independent samples.
The Kruskal-Wallis H-test tests the null hypothesis that the population
median of all of the groups are equal. It is a non-parametric version of
ANOVA. The test works on 2 or more independent samples, which may have
different sizes. Note that rejecting the null hypothesis does not
indicate which of the groups differs. Post hoc comparisons between
groups are required to determine which groups are different.
Parameters
----------
sample1, sample2, ... : array_like
Two or more arrays with the sample measurements can be given as
arguments. Samples must be one-dimensional.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
statistic : float
The Kruskal-Wallis H statistic, corrected for ties.
pvalue : float
The p-value for the test using the assumption that H has a chi
square distribution. The p-value returned is the survival function of
the chi square distribution evaluated at H.
See Also
--------
f_oneway : 1-way ANOVA.
mannwhitneyu : Mann-Whitney rank test on two samples.
friedmanchisquare : Friedman test for repeated measurements.
Notes
-----
Due to the assumption that H has a chi square distribution, the number
of samples in each group must not be too small. A typical rule is
that each sample must have at least 5 measurements.
References
----------
.. [1] W. H. Kruskal & W. W. Wallis, "Use of Ranks in
One-Criterion Variance Analysis", Journal of the American Statistical
Association, Vol. 47, Issue 260, pp. 583-621, 1952.
.. [2] https://en.wikipedia.org/wiki/Kruskal-Wallis_one-way_analysis_of_variance
Examples
--------
>>> from scipy import stats
>>> x = [1, 3, 5, 7, 9]
>>> y = [2, 4, 6, 8, 10]
>>> stats.kruskal(x, y)
KruskalResult(statistic=0.2727272727272734, pvalue=0.6015081344405895)
>>> x = [1, 1, 1]
>>> y = [2, 2, 2]
>>> z = [2, 2]
>>> stats.kruskal(x, y, z)
KruskalResult(statistic=7.0, pvalue=0.0301973834223185)
"""
args = list(map(np.asarray, args))
num_groups = len(args)
if num_groups < 2:
raise ValueError("Need at least two groups in stats.kruskal()")
for arg in args:
if arg.size == 0:
return KruskalResult(np.nan, np.nan)
elif arg.ndim != 1:
raise ValueError("Samples must be one-dimensional.")
n = np.asarray(list(map(len, args)))
if nan_policy not in ('propagate', 'raise', 'omit'):
raise ValueError("nan_policy must be 'propagate', 'raise' or 'omit'")
contains_nan = False
for arg in args:
cn = _contains_nan(arg, nan_policy)
if cn[0]:
contains_nan = True
break
if contains_nan and nan_policy == 'omit':
for a in args:
a = ma.masked_invalid(a)
return mstats_basic.kruskal(*args)
if contains_nan and nan_policy == 'propagate':
return KruskalResult(np.nan, np.nan)
alldata = np.concatenate(args)
ranked = rankdata(alldata)
ties = tiecorrect(ranked)
if ties == 0:
raise ValueError('All numbers are identical in kruskal')
# Compute sum^2/n for each group and sum
j = np.insert(np.cumsum(n), 0, 0)
ssbn = 0
for i in range(num_groups):
ssbn += _square_of_sums(ranked[j[i]:j[i+1]]) / n[i]
totaln = np.sum(n, dtype=float)
h = 12.0 / (totaln * (totaln + 1)) * ssbn - 3 * (totaln + 1)
df = num_groups - 1
h /= ties
return KruskalResult(h, distributions.chi2.sf(h, df))
FriedmanchisquareResult = namedtuple('FriedmanchisquareResult',
('statistic', 'pvalue'))
def friedmanchisquare(*args):
"""
Compute the Friedman test for repeated measurements.
The Friedman test tests the null hypothesis that repeated measurements of
the same individuals have the same distribution. It is often used
to test for consistency among measurements obtained in different ways.
For example, if two measurement techniques are used on the same set of
individuals, the Friedman test can be used to determine if the two
measurement techniques are consistent.
Parameters
----------
measurements1, measurements2, measurements3... : array_like
Arrays of measurements. All of the arrays must have the same number
of elements. At least 3 sets of measurements must be given.
Returns
-------
statistic : float
The test statistic, correcting for ties.
pvalue : float
The associated p-value assuming that the test statistic has a chi
squared distribution.
Notes
-----
Due to the assumption that the test statistic has a chi squared
distribution, the p-value is only reliable for n > 10 and more than
6 repeated measurements.
References
----------
.. [1] https://en.wikipedia.org/wiki/Friedman_test
"""
k = len(args)
if k < 3:
raise ValueError('At least 3 sets of measurements must be given for Friedman test, got {}.'.format(k))
n = len(args[0])
for i in range(1, k):
if len(args[i]) != n:
raise ValueError('Unequal N in friedmanchisquare. Aborting.')
# Rank data
data = np.vstack(args).T
data = data.astype(float)
for i in range(len(data)):
data[i] = rankdata(data[i])
# Handle ties
ties = 0
for i in range(len(data)):
replist, repnum = find_repeats(array(data[i]))
for t in repnum:
ties += t * (t*t - 1)
c = 1 - ties / (k*(k*k - 1)*n)
ssbn = np.sum(data.sum(axis=0)**2)
chisq = (12.0 / (k*n*(k+1)) * ssbn - 3*n*(k+1)) / c
return FriedmanchisquareResult(chisq, distributions.chi2.sf(chisq, k - 1))
BrunnerMunzelResult = namedtuple('BrunnerMunzelResult',
('statistic', 'pvalue'))
def brunnermunzel(x, y, alternative="two-sided", distribution="t",
nan_policy='propagate'):
"""
Compute the Brunner-Munzel test on samples x and y.
The Brunner-Munzel test is a nonparametric test of the null hypothesis that
when values are taken one by one from each group, the probabilities of
getting large values in both groups are equal.
Unlike the Wilcoxon-Mann-Whitney's U test, this does not require the
assumption of equivariance of two groups. Note that this does not assume
the distributions are same. This test works on two independent samples,
which may have different sizes.
Parameters
----------
x, y : array_like
Array of samples, should be one-dimensional.
alternative : {'two-sided', 'less', 'greater'}, optional
Defines the alternative hypothesis.
The following options are available (default is 'two-sided'):
* 'two-sided'
* 'less': one-sided
* 'greater': one-sided
distribution : {'t', 'normal'}, optional
Defines how to get the p-value.
The following options are available (default is 't'):
* 't': get the p-value by t-distribution
* 'normal': get the p-value by standard normal distribution.
nan_policy : {'propagate', 'raise', 'omit'}, optional
Defines how to handle when input contains nan.
The following options are available (default is 'propagate'):
* 'propagate': returns nan
* 'raise': throws an error
* 'omit': performs the calculations ignoring nan values
Returns
-------
statistic : float
The Brunner-Munzer W statistic.
pvalue : float
p-value assuming an t distribution. One-sided or
two-sided, depending on the choice of `alternative` and `distribution`.
See Also
--------
mannwhitneyu : Mann-Whitney rank test on two samples.
Notes
-----
Brunner and Munzel recommended to estimate the p-value by t-distribution
when the size of data is 50 or less. If the size is lower than 10, it would
be better to use permuted Brunner Munzel test (see [2]_).
References
----------
.. [1] Brunner, E. and Munzel, U. "The nonparametric Benhrens-Fisher
problem: Asymptotic theory and a small-sample approximation".
Biometrical Journal. Vol. 42(2000): 17-25.
.. [2] Neubert, K. and Brunner, E. "A studentized permutation test for the
non-parametric Behrens-Fisher problem". Computational Statistics and
Data Analysis. Vol. 51(2007): 5192-5204.
Examples
--------
>>> from scipy import stats
>>> x1 = [1,2,1,1,1,1,1,1,1,1,2,4,1,1]
>>> x2 = [3,3,4,3,1,2,3,1,1,5,4]
>>> w, p_value = stats.brunnermunzel(x1, x2)
>>> w
3.1374674823029505
>>> p_value
0.0057862086661515377
"""
x = np.asarray(x)
y = np.asarray(y)
# check both x and y
cnx, npx = _contains_nan(x, nan_policy)
cny, npy = _contains_nan(y, nan_policy)
contains_nan = cnx or cny
if npx == "omit" or npy == "omit":
nan_policy = "omit"
if contains_nan and nan_policy == "propagate":
return BrunnerMunzelResult(np.nan, np.nan)
elif contains_nan and nan_policy == "omit":
x = ma.masked_invalid(x)
y = ma.masked_invalid(y)
return mstats_basic.brunnermunzel(x, y, alternative, distribution)
nx = len(x)
ny = len(y)
if nx == 0 or ny == 0:
return BrunnerMunzelResult(np.nan, np.nan)
rankc = rankdata(np.concatenate((x, y)))
rankcx = rankc[0:nx]
rankcy = rankc[nx:nx+ny]
rankcx_mean = np.mean(rankcx)
rankcy_mean = np.mean(rankcy)
rankx = rankdata(x)
ranky = rankdata(y)
rankx_mean = np.mean(rankx)
ranky_mean = np.mean(ranky)
Sx = np.sum(np.power(rankcx - rankx - rankcx_mean + rankx_mean, 2.0))
Sx /= nx - 1
Sy = np.sum(np.power(rankcy - ranky - rankcy_mean + ranky_mean, 2.0))
Sy /= ny - 1
wbfn = nx * ny * (rankcy_mean - rankcx_mean)
wbfn /= (nx + ny) * np.sqrt(nx * Sx + ny * Sy)
if distribution == "t":
df_numer = np.power(nx * Sx + ny * Sy, 2.0)
df_denom = np.power(nx * Sx, 2.0) / (nx - 1)
df_denom += np.power(ny * Sy, 2.0) / (ny - 1)
df = df_numer / df_denom
p = distributions.t.cdf(wbfn, df)
elif distribution == "normal":
p = distributions.norm.cdf(wbfn)
else:
raise ValueError(
"distribution should be 't' or 'normal'")
if alternative == "greater":
pass
elif alternative == "less":
p = 1 - p
elif alternative == "two-sided":
p = 2 * np.min([p, 1-p])
else:
raise ValueError(
"alternative should be 'less', 'greater' or 'two-sided'")
return BrunnerMunzelResult(wbfn, p)
def combine_pvalues(pvalues, method='fisher', weights=None):
"""
Combine p-values from independent tests bearing upon the same hypothesis.
Parameters
----------
pvalues : array_like, 1-D
Array of p-values assumed to come from independent tests.
method : {'fisher', 'pearson', 'tippett', 'stouffer', 'mudholkar_george'}, optional
Name of method to use to combine p-values.
The following methods are available (default is 'fisher'):
* 'fisher': Fisher's method (Fisher's combined probability test), the
sum of the logarithm of the p-values
* 'pearson': Pearson's method (similar to Fisher's but uses sum of the
complement of the p-values inside the logarithms)
* 'tippett': Tippett's method (minimum of p-values)
* 'stouffer': Stouffer's Z-score method
* 'mudholkar_george': the difference of Fisher's and Pearson's methods
divided by 2
weights : array_like, 1-D, optional
Optional array of weights used only for Stouffer's Z-score method.
Returns
-------
statistic: float
The statistic calculated by the specified method.
pval: float
The combined p-value.
Notes
-----
Fisher's method (also known as Fisher's combined probability test) [1]_ uses
a chi-squared statistic to compute a combined p-value. The closely related
Stouffer's Z-score method [2]_ uses Z-scores rather than p-values. The
advantage of Stouffer's method is that it is straightforward to introduce
weights, which can make Stouffer's method more powerful than Fisher's
method when the p-values are from studies of different size [6]_ [7]_.
The Pearson's method uses :math:`log(1-p_i)` inside the sum whereas Fisher's
method uses :math:`log(p_i)` [4]_. For Fisher's and Pearson's method, the
sum of the logarithms is multiplied by -2 in the implementation. This
quantity has a chi-square distribution that determines the p-value. The
`mudholkar_george` method is the difference of the Fisher's and Pearson's
test statistics, each of which include the -2 factor [4]_. However, the
`mudholkar_george` method does not include these -2 factors. The test
statistic of `mudholkar_george` is the sum of logisitic random variables and
equation 3.6 in [3]_ is used to approximate the p-value based on Student's
t-distribution.
Fisher's method may be extended to combine p-values from dependent tests
[5]_. Extensions such as Brown's method and Kost's method are not currently
implemented.
.. versionadded:: 0.15.0
References
----------
.. [1] https://en.wikipedia.org/wiki/Fisher%27s_method
.. [2] https://en.wikipedia.org/wiki/Fisher%27s_method#Relation_to_Stouffer.27s_Z-score_method
.. [3] George, E. O., and G. S. Mudholkar. "On the convolution of logistic
random variables." Metrika 30.1 (1983): 1-13.
.. [4] Heard, N. and Rubin-Delanchey, P. "Choosing between methods of
combining p-values." Biometrika 105.1 (2018): 239-246.
.. [5] Whitlock, M. C. "Combining probability from independent tests: the
weighted Z-method is superior to Fisher's approach." Journal of
Evolutionary Biology 18, no. 5 (2005): 1368-1373.
.. [6] Zaykin, Dmitri V. "Optimally weighted Z-test is a powerful method
for combining probabilities in meta-analysis." Journal of
Evolutionary Biology 24, no. 8 (2011): 1836-1841.
.. [7] https://en.wikipedia.org/wiki/Extensions_of_Fisher%27s_method
"""
pvalues = np.asarray(pvalues)
if pvalues.ndim != 1:
raise ValueError("pvalues is not 1-D")
if method == 'fisher':
statistic = -2 * np.sum(np.log(pvalues))
pval = distributions.chi2.sf(statistic, 2 * len(pvalues))
elif method == 'pearson':
statistic = -2 * np.sum(np.log1p(-pvalues))
pval = distributions.chi2.sf(statistic, 2 * len(pvalues))
elif method == 'mudholkar_george':
normalizing_factor = np.sqrt(3/len(pvalues))/np.pi
statistic = -np.sum(np.log(pvalues)) + np.sum(np.log1p(-pvalues))
nu = 5 * len(pvalues) + 4
approx_factor = np.sqrt(nu / (nu - 2))
pval = distributions.t.sf(statistic * normalizing_factor * approx_factor, nu)
elif method == 'tippett':
statistic = np.min(pvalues)
pval = distributions.beta.sf(statistic, 1, len(pvalues))
elif method == 'stouffer':
if weights is None:
weights = np.ones_like(pvalues)
elif len(weights) != len(pvalues):
raise ValueError("pvalues and weights must be of the same size.")
weights = np.asarray(weights)
if weights.ndim != 1:
raise ValueError("weights is not 1-D")
Zi = distributions.norm.isf(pvalues)
statistic = np.dot(weights, Zi) / np.linalg.norm(weights)
pval = distributions.norm.sf(statistic)
else:
raise ValueError(
"Invalid method '%s'. Options are 'fisher', 'pearson', \
'mudholkar_george', 'tippett', 'or 'stouffer'", method)
return (statistic, pval)
#####################################
# STATISTICAL DISTANCES #
#####################################
def wasserstein_distance(u_values, v_values, u_weights=None, v_weights=None):
r"""
Compute the first Wasserstein distance between two 1D distributions.
This distance is also known as the earth mover's distance, since it can be
seen as the minimum amount of "work" required to transform :math:`u` into
:math:`v`, where "work" is measured as the amount of distribution weight
that must be moved, multiplied by the distance it has to be moved.
.. versionadded:: 1.0.0
Parameters
----------
u_values, v_values : array_like
Values observed in the (empirical) distribution.
u_weights, v_weights : array_like, optional
Weight for each value. If unspecified, each value is assigned the same
weight.
`u_weights` (resp. `v_weights`) must have the same length as
`u_values` (resp. `v_values`). If the weight sum differs from 1, it
must still be positive and finite so that the weights can be normalized
to sum to 1.
Returns
-------
distance : float
The computed distance between the distributions.
Notes
-----
The first Wasserstein distance between the distributions :math:`u` and
:math:`v` is:
.. math::
l_1 (u, v) = \inf_{\pi \in \Gamma (u, v)} \int_{\mathbb{R} \times
\mathbb{R}} |x-y| \mathrm{d} \pi (x, y)
where :math:`\Gamma (u, v)` is the set of (probability) distributions on
:math:`\mathbb{R} \times \mathbb{R}` whose marginals are :math:`u` and
:math:`v` on the first and second factors respectively.
If :math:`U` and :math:`V` are the respective CDFs of :math:`u` and
:math:`v`, this distance also equals to:
.. math::
l_1(u, v) = \int_{-\infty}^{+\infty} |U-V|
See [2]_ for a proof of the equivalence of both definitions.
The input distributions can be empirical, therefore coming from samples
whose values are effectively inputs of the function, or they can be seen as
generalized functions, in which case they are weighted sums of Dirac delta
functions located at the specified values.
References
----------
.. [1] "Wasserstein metric", https://en.wikipedia.org/wiki/Wasserstein_metric
.. [2] Ramdas, Garcia, Cuturi "On Wasserstein Two Sample Testing and Related
Families of Nonparametric Tests" (2015). :arXiv:`1509.02237`.
Examples
--------
>>> from scipy.stats import wasserstein_distance
>>> wasserstein_distance([0, 1, 3], [5, 6, 8])
5.0
>>> wasserstein_distance([0, 1], [0, 1], [3, 1], [2, 2])
0.25
>>> wasserstein_distance([3.4, 3.9, 7.5, 7.8], [4.5, 1.4],
... [1.4, 0.9, 3.1, 7.2], [3.2, 3.5])
4.0781331438047861
"""
return _cdf_distance(1, u_values, v_values, u_weights, v_weights)
def energy_distance(u_values, v_values, u_weights=None, v_weights=None):
r"""
Compute the energy distance between two 1D distributions.
.. versionadded:: 1.0.0
Parameters
----------
u_values, v_values : array_like
Values observed in the (empirical) distribution.
u_weights, v_weights : array_like, optional
Weight for each value. If unspecified, each value is assigned the same
weight.
`u_weights` (resp. `v_weights`) must have the same length as
`u_values` (resp. `v_values`). If the weight sum differs from 1, it
must still be positive and finite so that the weights can be normalized
to sum to 1.
Returns
-------
distance : float
The computed distance between the distributions.
Notes
-----
The energy distance between two distributions :math:`u` and :math:`v`, whose
respective CDFs are :math:`U` and :math:`V`, equals to:
.. math::
D(u, v) = \left( 2\mathbb E|X - Y| - \mathbb E|X - X'| -
\mathbb E|Y - Y'| \right)^{1/2}
where :math:`X` and :math:`X'` (resp. :math:`Y` and :math:`Y'`) are
independent random variables whose probability distribution is :math:`u`
(resp. :math:`v`).
As shown in [2]_, for one-dimensional real-valued variables, the energy
distance is linked to the non-distribution-free version of the Cramér-von
Mises distance:
.. math::
D(u, v) = \sqrt{2} l_2(u, v) = \left( 2 \int_{-\infty}^{+\infty} (U-V)^2
\right)^{1/2}
Note that the common Cramér-von Mises criterion uses the distribution-free
version of the distance. See [2]_ (section 2), for more details about both
versions of the distance.
The input distributions can be empirical, therefore coming from samples
whose values are effectively inputs of the function, or they can be seen as
generalized functions, in which case they are weighted sums of Dirac delta
functions located at the specified values.
References
----------
.. [1] "Energy distance", https://en.wikipedia.org/wiki/Energy_distance
.. [2] Szekely "E-statistics: The energy of statistical samples." Bowling
Green State University, Department of Mathematics and Statistics,
Technical Report 02-16 (2002).
.. [3] Rizzo, Szekely "Energy distance." Wiley Interdisciplinary Reviews:
Computational Statistics, 8(1):27-38 (2015).
.. [4] Bellemare, Danihelka, Dabney, Mohamed, Lakshminarayanan, Hoyer,
Munos "The Cramer Distance as a Solution to Biased Wasserstein
Gradients" (2017). :arXiv:`1705.10743`.
Examples
--------
>>> from scipy.stats import energy_distance
>>> energy_distance([0], [2])
2.0000000000000004
>>> energy_distance([0, 8], [0, 8], [3, 1], [2, 2])
1.0000000000000002
>>> energy_distance([0.7, 7.4, 2.4, 6.8], [1.4, 8. ],
... [2.1, 4.2, 7.4, 8. ], [7.6, 8.8])
0.88003340976158217
"""
return np.sqrt(2) * _cdf_distance(2, u_values, v_values,
u_weights, v_weights)
def _cdf_distance(p, u_values, v_values, u_weights=None, v_weights=None):
r"""
Compute, between two one-dimensional distributions :math:`u` and
:math:`v`, whose respective CDFs are :math:`U` and :math:`V`, the
statistical distance that is defined as:
.. math::
l_p(u, v) = \left( \int_{-\infty}^{+\infty} |U-V|^p \right)^{1/p}
p is a positive parameter; p = 1 gives the Wasserstein distance, p = 2
gives the energy distance.
Parameters
----------
u_values, v_values : array_like
Values observed in the (empirical) distribution.
u_weights, v_weights : array_like, optional
Weight for each value. If unspecified, each value is assigned the same
weight.
`u_weights` (resp. `v_weights`) must have the same length as
`u_values` (resp. `v_values`). If the weight sum differs from 1, it
must still be positive and finite so that the weights can be normalized
to sum to 1.
Returns
-------
distance : float
The computed distance between the distributions.
Notes
-----
The input distributions can be empirical, therefore coming from samples
whose values are effectively inputs of the function, or they can be seen as
generalized functions, in which case they are weighted sums of Dirac delta
functions located at the specified values.
References
----------
.. [1] Bellemare, Danihelka, Dabney, Mohamed, Lakshminarayanan, Hoyer,
Munos "The Cramer Distance as a Solution to Biased Wasserstein
Gradients" (2017). :arXiv:`1705.10743`.
"""
u_values, u_weights = _validate_distribution(u_values, u_weights)
v_values, v_weights = _validate_distribution(v_values, v_weights)
u_sorter = np.argsort(u_values)
v_sorter = np.argsort(v_values)
all_values = np.concatenate((u_values, v_values))
all_values.sort(kind='mergesort')
# Compute the differences between pairs of successive values of u and v.
deltas = np.diff(all_values)
# Get the respective positions of the values of u and v among the values of
# both distributions.
u_cdf_indices = u_values[u_sorter].searchsorted(all_values[:-1], 'right')
v_cdf_indices = v_values[v_sorter].searchsorted(all_values[:-1], 'right')
# Calculate the CDFs of u and v using their weights, if specified.
if u_weights is None:
u_cdf = u_cdf_indices / u_values.size
else:
u_sorted_cumweights = np.concatenate(([0],
np.cumsum(u_weights[u_sorter])))
u_cdf = u_sorted_cumweights[u_cdf_indices] / u_sorted_cumweights[-1]
if v_weights is None:
v_cdf = v_cdf_indices / v_values.size
else:
v_sorted_cumweights = np.concatenate(([0],
np.cumsum(v_weights[v_sorter])))
v_cdf = v_sorted_cumweights[v_cdf_indices] / v_sorted_cumweights[-1]
# Compute the value of the integral based on the CDFs.
# If p = 1 or p = 2, we avoid using np.power, which introduces an overhead
# of about 15%.
if p == 1:
return np.sum(np.multiply(np.abs(u_cdf - v_cdf), deltas))
if p == 2:
return np.sqrt(np.sum(np.multiply(np.square(u_cdf - v_cdf), deltas)))
return np.power(np.sum(np.multiply(np.power(np.abs(u_cdf - v_cdf), p),
deltas)), 1/p)
def _validate_distribution(values, weights):
"""
Validate the values and weights from a distribution input of `cdf_distance`
and return them as ndarray objects.
Parameters
----------
values : array_like
Values observed in the (empirical) distribution.
weights : array_like
Weight for each value.
Returns
-------
values : ndarray
Values as ndarray.
weights : ndarray
Weights as ndarray.
"""
# Validate the value array.
values = np.asarray(values, dtype=float)
if len(values) == 0:
raise ValueError("Distribution can't be empty.")
# Validate the weight array, if specified.
if weights is not None:
weights = np.asarray(weights, dtype=float)
if len(weights) != len(values):
raise ValueError('Value and weight array-likes for the same '
'empirical distribution must be of the same size.')
if np.any(weights < 0):
raise ValueError('All weights must be non-negative.')
if not 0 < np.sum(weights) < np.inf:
raise ValueError('Weight array-like sum must be positive and '
'finite. Set as None for an equal distribution of '
'weight.')
return values, weights
return values, None
#####################################
# SUPPORT FUNCTIONS #
#####################################
RepeatedResults = namedtuple('RepeatedResults', ('values', 'counts'))
def find_repeats(arr):
"""
Find repeats and repeat counts.
Parameters
----------
arr : array_like
Input array. This is cast to float64.
Returns
-------
values : ndarray
The unique values from the (flattened) input that are repeated.
counts : ndarray
Number of times the corresponding 'value' is repeated.
Notes
-----
In numpy >= 1.9 `numpy.unique` provides similar functionality. The main
difference is that `find_repeats` only returns repeated values.
Examples
--------
>>> from scipy import stats
>>> stats.find_repeats([2, 1, 2, 3, 2, 2, 5])
RepeatedResults(values=array([2.]), counts=array([4]))
>>> stats.find_repeats([[10, 20, 1, 2], [5, 5, 4, 4]])
RepeatedResults(values=array([4., 5.]), counts=array([2, 2]))
"""
# Note: always copies.
return RepeatedResults(*_find_repeats(np.array(arr, dtype=np.float64)))
def _sum_of_squares(a, axis=0):
"""
Square each element of the input array, and return the sum(s) of that.
Parameters
----------
a : array_like
Input array.
axis : int or None, optional
Axis along which to calculate. Default is 0. If None, compute over
the whole array `a`.
Returns
-------
sum_of_squares : ndarray
The sum along the given axis for (a**2).
See Also
--------
_square_of_sums : The square(s) of the sum(s) (the opposite of
`_sum_of_squares`).
"""
a, axis = _chk_asarray(a, axis)
return np.sum(a*a, axis)
def _square_of_sums(a, axis=0):
"""
Sum elements of the input array, and return the square(s) of that sum.
Parameters
----------
a : array_like
Input array.
axis : int or None, optional
Axis along which to calculate. Default is 0. If None, compute over
the whole array `a`.
Returns
-------
square_of_sums : float or ndarray
The square of the sum over `axis`.
See Also
--------
_sum_of_squares : The sum of squares (the opposite of `square_of_sums`).
"""
a, axis = _chk_asarray(a, axis)
s = np.sum(a, axis)
if not np.isscalar(s):
return s.astype(float) * s
else:
return float(s) * s
def rankdata(a, method='average', *, axis=None):
"""
Assign ranks to data, dealing with ties appropriately.
By default (``axis=None``), the data array is first flattened, and a flat
array of ranks is returned. Separately reshape the rank array to the
shape of the data array if desired (see Examples).
Ranks begin at 1. The `method` argument controls how ranks are assigned
to equal values. See [1]_ for further discussion of ranking methods.
Parameters
----------
a : array_like
The array of values to be ranked.
method : {'average', 'min', 'max', 'dense', 'ordinal'}, optional
The method used to assign ranks to tied elements.
The following methods are available (default is 'average'):
* 'average': The average of the ranks that would have been assigned to
all the tied values is assigned to each value.
* 'min': The minimum of the ranks that would have been assigned to all
the tied values is assigned to each value. (This is also
referred to as "competition" ranking.)
* 'max': The maximum of the ranks that would have been assigned to all
the tied values is assigned to each value.
* 'dense': Like 'min', but the rank of the next highest element is
assigned the rank immediately after those assigned to the tied
elements.
* 'ordinal': All values are given a distinct rank, corresponding to
the order that the values occur in `a`.
axis : {None, int}, optional
Axis along which to perform the ranking. If ``None``, the data array
is first flattened.
Returns
-------
ranks : ndarray
An array of size equal to the size of `a`, containing rank
scores.
References
----------
.. [1] "Ranking", https://en.wikipedia.org/wiki/Ranking
Examples
--------
>>> from scipy.stats import rankdata
>>> rankdata([0, 2, 3, 2])
array([ 1. , 2.5, 4. , 2.5])
>>> rankdata([0, 2, 3, 2], method='min')
array([ 1, 2, 4, 2])
>>> rankdata([0, 2, 3, 2], method='max')
array([ 1, 3, 4, 3])
>>> rankdata([0, 2, 3, 2], method='dense')
array([ 1, 2, 3, 2])
>>> rankdata([0, 2, 3, 2], method='ordinal')
array([ 1, 2, 4, 3])
>>> rankdata([[0, 2], [3, 2]]).reshape(2,2)
array([[1. , 2.5],
[4. , 2.5]])
>>> rankdata([[0, 2, 2], [3, 2, 5]], axis=1)
array([[1. , 2.5, 2.5],
[2. , 1. , 3. ]])
"""
if method not in ('average', 'min', 'max', 'dense', 'ordinal'):
raise ValueError('unknown method "{0}"'.format(method))
if axis is not None:
a = np.asarray(a)
if a.size == 0:
# The return values of `normalize_axis_index` are ignored. The
# call validates `axis`, even though we won't use it.
# use scipy._lib._util._normalize_axis_index when available
np.core.multiarray.normalize_axis_index(axis, a.ndim)
dt = np.float64 if method == 'average' else np.int_
return np.empty(a.shape, dtype=dt)
return np.apply_along_axis(rankdata, axis, a, method)
arr = np.ravel(np.asarray(a))
algo = 'mergesort' if method == 'ordinal' else 'quicksort'
sorter = np.argsort(arr, kind=algo)
inv = np.empty(sorter.size, dtype=np.intp)
inv[sorter] = np.arange(sorter.size, dtype=np.intp)
if method == 'ordinal':
return inv + 1
arr = arr[sorter]
obs = np.r_[True, arr[1:] != arr[:-1]]
dense = obs.cumsum()[inv]
if method == 'dense':
return dense
# cumulative counts of each unique value
count = np.r_[np.nonzero(obs)[0], len(obs)]
if method == 'max':
return count[dense]
if method == 'min':
return count[dense - 1] + 1
# average method
return .5 * (count[dense] + count[dense - 1] + 1)
|
py | 1a457302d55b6bb708c1041674504aa80eb90bbc | #****************************************************#
# This file is part of OPTALG. #
# #
# Copyright (c) 2019, Tomas Tinoco De Rubira. #
# #
# OPTALG is released under the BSD 2-clause license. #
#****************************************************#
from __future__ import print_function
import numpy as np
from functools import reduce
from .opt_solver_error import *
from .problem import cast_problem, OptProblem
from .opt_solver import OptSolver
from optalg.lin_solver import new_linsolver
from scipy.sparse import bmat,eye,coo_matrix,tril
class OptSolverAugL(OptSolver):
parameters = {'beta_large' : 0.9, # for decreasing sigma when progress
'beta_med' : 0.5, # for decreasing sigma when forcing
'beta_small' : 0.1, # for decreasing sigma
'feastol' : 1e-4, # feasibility tolerance
'optol' : 1e-4, # optimality tolerance
'gamma' : 0.1, # for determining required decrease in ||f||
'tau' : 0.1, # for reductions in ||GradF||
'kappa' : 1e-2, # for initializing sigma
'maxiter' : 1000, # maximum iterations
'sigma_min' : 1e-12, # minimum sigma
'sigma_init_min' : 1e-3, # minimum initial sigma
'sigma_init_max' : 1e8, # maximum initial sigma
'theta_min' : 1e-6, # minimum barrier parameter
'theta_max' : 1e0 , # maximum initial barrier parameter
'lam_reg' : 1e-4, # regularization of first order dual update
'subprob_force' : 10, # for periodic sigma decrease
'subprob_maxiter' : 150, # maximum subproblem iterations
'linsolver' : 'default', # linear solver
'quiet' : False} # flag for omitting output
def __init__(self):
"""
Augmented Lagrangian algorithm.
"""
OptSolver.__init__(self)
self.parameters = OptSolverAugL.parameters.copy()
self.linsolver1 = None
self.linsolver2 = None
self.barrier = None
def supports_properties(self, properties):
for p in properties:
if p not in [OptProblem.PROP_CURV_LINEAR,
OptProblem.PROP_CURV_QUADRATIC,
OptProblem.PROP_CURV_NONLINEAR,
OptProblem.PROP_VAR_CONTINUOUS,
OptProblem.PROP_TYPE_FEASIBILITY,
OptProblem.PROP_TYPE_OPTIMIZATION]:
return False
return True
def solve(self, problem):
# Local vars
norm2 = self.norm2
norminf = self.norminf
params = self.parameters
# Parameters
tau = params['tau']
gamma = params['gamma']
kappa = params['kappa']
optol = params['optol']
feastol = params['feastol']
beta_small = params['beta_small']
beta_large = params['beta_large']
sigma_init_min = params['sigma_init_min']
sigma_init_max = params['sigma_init_max']
theta_max = params['theta_max']
theta_min = params['theta_min']
# Problem
problem = cast_problem(problem)
self.problem = problem
# Linear solver
self.linsolver1 = new_linsolver(params['linsolver'],'symmetric')
self.linsolver2 = new_linsolver(params['linsolver'],'symmetric')
# Reset
self.reset()
# Barrier
self.barrier = AugLBarrier(problem.get_num_primal_variables(),
problem.l,
problem.u,
eps=feastol/10.)
# Init primal
if problem.x is not None:
self.x = self.barrier.to_interior(problem.x.copy(),
eps=feastol/10.)
else:
self.x = (self.barrier.umax+self.barrier.umin)/2.
assert(np.all(self.x > self.barrier.umin))
assert(np.all(self.x < self.barrier.umax))
# Init dual
if problem.lam is not None:
self.lam = problem.lam.copy()
else:
self.lam = np.zeros(problem.b.size)
if problem.nu is not None:
self.nu = problem.nu.copy()
else:
self.nu = np.zeros(problem.f.size)
try:
if problem.pi is not None:
self.pi = problem.pi.copy()
else:
self.pi = np.zeros(self.x.size)
except AttributeError:
self.pi = np.zeros(self.x.size)
try:
if problem.mu is not None:
self.mu = problem.mu.copy()
else:
self.mu = np.zeros(self.x.size)
except AttributeError:
self.mu = np.zeros(self.x.size)
# Constants
self.sigma = 0.
self.theta = 0.
self.code = ''
self.nx = self.x.size
self.na = problem.b.size
self.nf = problem.f.size
self.ox = np.zeros(self.nx)
self.oa = np.zeros(self.na)
self.of = np.zeros(self.nf)
self.Ixx = eye(self.nx,format='coo')
self.Iff = eye(self.nf,format='coo')
self.Iaa = eye(self.na,format='coo')
# Objective scaling
fdata = self.func(self.x)
self.obj_sca = np.maximum(np.abs(fdata.phi)/100.,1.)
fdata = self.func(self.x)
# Init penalty and barrier parameters
self.sigma = kappa*norm2(fdata.GradF)/np.maximum(norm2(fdata.gphi),1.)
self.sigma = np.minimum(np.maximum(self.sigma,sigma_init_min),sigma_init_max)
self.theta = kappa*norm2(fdata.GradF)/(self.sigma*np.maximum(norm2(fdata.gphiB),1.))
self.theta = np.minimum(np.maximum(self.theta,theta_min),theta_max)
fdata = self.func(self.x)
# Init residuals
pres_prev = norminf(fdata.pres)
gLmax_prev = norminf(fdata.GradF)
# Init dual update
if pres_prev <= feastol:
self.update_multiplier_estimates()
fdata = self.func(self.x)
# Outer iterations
self.k = 0
self.useH = False
self.code = list('----')
while True:
# Solve subproblem
self.solve_subproblem(tau*gLmax_prev)
# Check done
if self.is_status_solved():
return
# Measure progress
pres = norminf(fdata.pres)
dres = norminf(fdata.dres)
gLmax = norminf(fdata.GradF)
# Penaly update
if pres <= np.maximum(gamma*pres_prev,feastol):
self.sigma *= beta_large
self.code[1] = 'p'
else:
self.sigma *= beta_small
self.code[1] = 'n'
# Dual update
self.update_multiplier_estimates()
# Barrier update
self.theta = np.maximum(self.theta*beta_small,theta_min)
# Update refs
pres_prev = pres
gLmax_prev = gLmax
# Update iters
self.k += 1
def solve_subproblem(self,delta):
# Local vars
norm2 = self.norm2
norminf = self.norminf
params = self.parameters
problem = self.problem
barrier = self.barrier
# Params
quiet = params['quiet']
maxiter = params['maxiter']
feastol = params['feastol']
optol = params['optol']
maxiter = params['maxiter']
theta_min = params['theta_min']
sigma_min = params['sigma_min']
beta_large = params['beta_large']
beta_med = params['beta_med']
beta_small = params['beta_small']
subprob_force = params['subprob_force']
subprob_maxiter = params['subprob_maxiter']
# Print header
self.print_header()
# Init eval
fdata = self.func(self.x)
# Inner iterations
i = 0
j = 0
alpha = 0.
while True:
# Compute info
pres = norminf(fdata.pres)
dres = norminf(fdata.dres)
dmax = max(map(norminf,[self.lam,self.nu,self.mu,self.pi]))
gLmax = norminf(fdata.GradF)
# Show info
if not quiet:
print('{0:^4d}'.format(self.k),end=' ')
print('{0:^9.2e}'.format(problem.phi),end=' ')
print('{0:^9.2e}'.format(pres),end=' ')
print('{0:^9.2e}'.format(dres),end=' ')
print('{0:^9.2e}'.format(gLmax),end=' ')
print('{0:^8.1e}'.format(dmax),end=' ')
print('{0:^8.1e}'.format(alpha),end=' ')
print('{0:^7.1e}'.format(self.sigma),end=' ')
print('{0:^7.1e}'.format(self.theta),end=' ')
print('{0:^7s}'.format(reduce(lambda x,y: x+y,self.code)),end=' ')
if self.info_printer:
self.info_printer(self,False)
else:
print('')
# Clear code
self.code = list('----')
# Check solved
if pres <= feastol and dres <= optol and self.theta <= theta_min:
self.set_status(self.STATUS_SOLVED)
self.set_error_msg('')
return
# Check only theta missing
if pres <= feastol and dres <= optol:
return
# Check subproblem solved
if gLmax <= delta:
return
# Check total maxiters
if self.k >= maxiter:
raise OptSolverError_MaxIters(self)
# Check penalty
if self.sigma < sigma_min:
raise OptSolverError_SmallPenalty(self)
# Check custom terminations
for t in self.terminations:
t(self)
# Search direction
p = self.compute_search_direction(self.useH)
# Max steplength
ppos = p > 1e-15
pneg = p < -1e-15
a1 = np.min(((barrier.umax-self.x)[ppos])/(p[ppos])) if ppos.sum() else np.inf
a2 = np.min(((barrier.umin-self.x)[pneg])/(p[pneg])) if pneg.sum() else np.inf
alpha_max = 0.98*min([a1,a2])
if not alpha_max:
raise OptSolverError_NumProblems(self)
try:
# Line search
alpha,fdata = self.line_search(self.x,p,fdata.F,fdata.GradF,self.func,alpha_max)
# Update x
self.x += alpha*p
except OptSolverError_LineSearch:
# Update
self.sigma *= beta_large
fdata = self.func(self.x)
self.code[3] = 'b'
if self.useH:
self.useH = False
i = 0
alpha = 0.
# Update iter count
self.k += 1
i += 1
j += 1
# Periodic force
if i >= subprob_force:
self.sigma *= beta_large
fdata = self.func(self.x)
self.code[2] = 'f'
self.useH = True
i = 0
# Periodic maxiter
if j >= subprob_maxiter:
self.sigma *= beta_med
self.update_multiplier_estimates()
fdata = self.func(self.x)
self.code[2] = 'm'
j = 0
def compute_search_direction(self,useH):
fdata = self.fdata
problem = self.problem
barrier = self.barrier
sigma = self.sigma
theta = self.theta
problem.combine_H(-sigma*self.nu+problem.f,not useH)
self.code[0] = 'h' if useH else 'g'
Hfsigma = problem.H_combined/sigma
Hphi = fdata.Hphi
HphiB = fdata.HphiB
G = coo_matrix((np.concatenate((Hphi.data,theta*HphiB.data,Hfsigma.data)),
(np.concatenate((Hphi.row,HphiB.row,Hfsigma.row)),
np.concatenate((Hphi.col,HphiB.col,Hfsigma.col)))))
if problem.A.size:
W = bmat([[G,None,None],
[problem.J,-sigma*self.Iff,None],
[problem.A,None,-sigma*self.Iaa]])
else:
W = bmat([[G,None],
[problem.J,-sigma*self.Iff]])
b = np.hstack((-fdata.GradF/sigma,
self.of,
self.oa))
if not self.linsolver1.is_analyzed():
self.linsolver1.analyze(W)
try:
return self.linsolver1.factorize_and_solve(W,b)[:self.x.size]
except Exception:
return np.zeros(self.x.size)
def func(self,x):
# Norm
norm = self.norminf
# Multipliers
lam = self.lam
nu = self.nu
# Penalty
sigma = self.sigma
theta = self.theta
# Objects
p = self.problem
fdata = self.fdata
barrier = self.barrier
# Eval
p.eval(x)
barrier.eval(x)
# Problem data
phi = p.phi/self.obj_sca
gphi = p.gphi/self.obj_sca
Hphi = p.Hphi/self.obj_sca
f = p.f
J = p.J
A = p.A
r = A*x-p.b
# Barrier data
phiB = barrier.phi
gphiB = barrier.gphi
HphiB = barrier.Hphi
# Intermediate
nuTf = np.dot(nu,f)
y = (sigma*nu-f)
JT = J.T
JTnu = JT*nu
JTy = JT*y
# Intermediate
lamTr = np.dot(lam,r)
z = (sigma*lam-r)
AT = A.T
ATlam = AT*lam
ATz = AT*z
pres = np.hstack((r,f))
dres = gphi+theta*gphiB-ATlam-JTnu
dres_den = 1.+norm(gphi)+theta*norm(gphiB)+norm(A.data)*norm(lam)+norm(J.data)*norm(nu)
fdata.ATlam = ATlam
fdata.JTnu = JTnu
fdata.r = r
fdata.f = f
fdata.F = sigma*phi + sigma*theta*phiB - sigma*(nuTf+lamTr) + 0.5*np.dot(pres,pres)
fdata.GradF = sigma*gphi + sigma*theta*gphiB - JTy - ATz
fdata.pres = pres
fdata.dres = dres/dres_den
fdata.phi = phi
fdata.gphi = gphi
fdata.Hphi = Hphi
fdata.phiB = phiB
fdata.gphiB = gphiB
fdata.HphiB = HphiB
return fdata
def print_header(self):
# Local vars
params = self.parameters
quiet = params['quiet']
if not quiet:
if self.k == 0:
print('\nSolver: augL')
print('------------')
print('{0:^4}'.format('k'), end=' ')
print('{0:^9}'.format('phi'), end=' ')
print('{0:^9}'.format('pres'), end=' ')
print('{0:^9}'.format('dres'), end=' ')
print('{0:^9}'.format('gLmax'), end=' ')
print('{0:^8}'.format('dmax'), end=' ')
print('{0:^8}'.format('alpha'), end=' ')
print('{0:^7}'.format('sigma'), end=' ')
print('{0:^7}'.format('theta'), end=' ')
print('{0:^7}'.format('code'), end=' ')
if self.info_printer:
self.info_printer(self,True)
else:
print('')
else:
print('')
def update_multiplier_estimates(self):
# Local variables
params = self.parameters
problem = self.problem
barrier = self.barrier
fdata = self.fdata
# Parameters
lam_reg = params['lam_reg']
sigma = self.sigma
theta = self.theta
eta = lam_reg
# Eval
fdata = self.func(self.x)
A = problem.A
J = problem.J
AT = A.T
JT = J.T
t = fdata.gphi+theta*fdata.gphiB-fdata.ATlam-fdata.JTnu
if problem.A.size:
W = bmat([[eta*self.Iaa,None,None],
[None,eta*self.Iff,None],
[AT,JT,-self.Ixx]],format='coo')
else:
W = bmat([[eta*self.Iff,None],
[JT,-self.Ixx]],format='coo')
b = np.hstack((A*t,
J*t,
self.ox))
if W.size:
if not self.linsolver2.is_analyzed():
self.linsolver2.analyze(W)
sol = self.linsolver2.factorize_and_solve(W,b)
self.lam += sol[:self.na]
self.nu += sol[self.na:self.na+self.nf]
self.mu = theta/(barrier.umax-self.x)
self.pi = theta/(self.x-barrier.umin)
class AugLBarrier:
"""
Class for handling bounds using barrier.
"""
def __init__(self, n, umin=None, umax=None, eps=1e-5, inf=1e8):
assert(n >= 0)
assert(inf > 0)
if umin is None or not umin.size:
umin = -inf*np.ones(n)
if umax is None or not umax.size:
umax = inf*np.ones(n)
assert(np.all(umin <= umax))
if n > 0:
umax = umax+eps
umin = umin-eps
assert(umin.size == n)
assert(umin.size == umax.size)
assert(np.all(umin < umax))
self.n = n
self.inf = inf
self.umin = umin
self.umax = umax
self.phi = 0
self.gphi = np.zeros(n)
self.Hphi_row = np.array(range(n))
self.Hphi_col = np.array(range(n))
self.Hphi_data = np.zeros(n)
self.Hphi = coo_matrix((self.Hphi_data,(self.Hphi_row,self.Hphi_col)),shape=(n,n))
def eval(self,u):
assert(u.size == self.n)
dumax = np.maximum(self.umax-u,1e-12)
dumin = np.maximum(u-self.umin,1e-12)
self.phi = -np.sum(np.log(dumax)+np.log(dumin))
self.gphi[:] = -1./dumin+1./dumax
self.Hphi_data[:] = 1./np.square(dumin)+1./np.square(dumax)
def to_interior(self,x, eps=1e-5):
return np.maximum(np.minimum(x, self.umax-eps), self.umin+eps)
|
py | 1a45733108cfa0d02f084ac300784d18ef12cf59 | """
urls for homepage
"""
import django
from django.conf.urls import url, include
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^$', views.homepage, name='homepage'),
url(r"^", include("profiles.urls", namespace="profiles")),
url(r"^admin/", include("applications.admin_urls", namespace="admin")),
url(r"^django/admin/", admin.site.urls),
# url(r"^accounts/", include("django.contrib.auth.urls")),
url(r"^requests/", include("applications.requests_urls", namespace="requests")),
url(r"^documents/", include("documents.urls", namespace="documents")),
url(r"^", include("applications.urls", namespace="applications")),
url(r'^settings/$', views.user_settings, name='user_settings'),
url(r'^resources/$', views.user_resources, name='user_resources'),
url(r"^settings/", include("applications.settings_urls", namespace="settings")),
url(r'^password-reset/$', django.contrib.auth.views.password_reset, name='password_reset'),
url(r'^password-reset/done/$', django.contrib.auth.views.password_reset_done, name='password_reset_done'),
url(r'^password-reset/confirm/(?P<uidb64>[-\w]+)/(?P<token>[-\w]+)/$',
django.contrib.auth.views.password_reset_confirm, name='password_reset_confirm'),
url(r'^password-reset/complete/$', django.contrib.auth.views.password_reset_complete,
name='password_reset_complete'),
]
|
py | 1a45760dffff868da4c8f2f75b159b9418c2eacd | # 2020 CCC PROBLEM J1'S SOLUTION:
# declaring variables for the treat sizes.
SMALL_TREATS = int(input())
MEDIUM_TREATS = int(input())
LARGE_TREATS = int(input())
# arithmetic calculation for the determinant.
determinant = (1 * SMALL_TREATS) + (2 * MEDIUM_TREATS) + (3 * LARGE_TREATS)
# determining whether the dog is happy based on the determinant.
if determinant >= 10:
print("happy")
else:
print("sad") |
py | 1a45764066f09ca86fbd1aa27513c31fb2f9e45b | import logging
from django.core.management.base import BaseCommand
from django.db import connection, connections
from django.conf import settings
from usaspending.common.helpers import timer
logger = logging.getLogger('console')
# Website columns need for update from financial_accounts_by_program_activity_object_class
financial_accounts_oc = [
('broker_submission_id', 'sub'),
('allocation_transfer_agency_id', 'tas'),
('agency_id', 'tas'),
('beginning_period_of_availability', 'tas'),
('ending_period_of_availability', 'tas'),
('availability_type_code', 'tas'),
('main_account_code', 'tas'),
('sub_account_code', 'tas'),
('object_class', 'oc'),
('program_activity_code', 'pa'),
('direct_reimbursable', 'oc'),
('ussgl498100_upward_adjust_pri_deliv_orders_oblig_unpaid_cpe', 'ds_file_table'),
('ussgl488100_upward_adjust_pri_undeliv_order_oblig_unpaid_cpe', 'ds_file_table')
]
# Website columns need for update from financial_accounts_by_awards (Adds fain, uri, and piid columns)
financial_accounts_awards = [
('fain', ' ds_file_table'),
('uri', ' ds_file_table'),
('piid', ' ds_file_table')
] + financial_accounts_oc[:]
# website -> broker mappings with specific mappings different from settings.py mappings
broker_website_cols_mapping = {
'broker_submission_id': 'db_file_table.submission_id',
"allocation_transfer_agency_id": "COALESCE(allocation_transfer_agency, '''')",
'agency_id': 'agency_identifier',
'object_class': 'object_class',
'program_activity_code': 'program_activity_code',
'beginning_period_of_availability': "COALESCE(beginning_period_of_availa, '''')",
'ending_period_of_availability': "COALESCE(ending_period_of_availabil, '''')",
'availability_type_code': "COALESCE(availability_type_code, '''')",
'direct_reimbursable': "CASE WHEN by_direct_reimbursable_fun = ''D'' then 1" +
"WHEN by_direct_reimbursable_fun = ''R'' then 2 ELSE NULL END"
}
class Command(BaseCommand):
help = "Fix File B and File C mappings due to invalid database column mappings"
@staticmethod
def get_list_of_submissions():
# Gets a list from broker of the submissions that are certified (type 2) and not updated
broker_connection = connections['data_broker'].cursor()
broker_connection.execute('SELECT submission_id from submission sub ' +
'WHERE sub.publish_status_id = 2 ORDER BY submission_id;')
return broker_connection.fetchall()
@staticmethod
def get_list_of_broker_cols(website_cols):
# Returns sql string statement to pull columns from broker
# First looks at broker_website_cols_translation that have a specific website to broker mapping
# Then looks at settings.py for the overall website website->broker mapping
return ",".join([
broker_website_cols_mapping.get(column, settings.LONG_TO_TERSE_LABELS.get(column))
for column, table in website_cols])
@staticmethod
def get_list_of_broker_cols_types(website_cols):
# Returns sql string statement to create table to compare to website type
# Needs to add a type (text or numeric) in order to match it to the website
return ",".join([
"{column} {type}".format(column=column, type='text' if column not in [
'ussgl498100_upward_adjust_pri_deliv_orders_oblig_unpaid_cpe',
'ussgl488100_upward_adjust_pri_undeliv_order_oblig_unpaid_cpe',
'broker_submission_id'] else "numeric")
for column, table in website_cols
])
@staticmethod
def get_website_row_formatted(website_cols):
# Return sql string with website columns formatted for select statement
return ",".join(['{0}.{1}'.format(table, column)
for column, table in website_cols])
@staticmethod
def get_cols_to_update(website_cols):
# Returning sql string of columns that will be updated in SET statement
# Ensures only columns that are not used as identifiers in the database are included
return ",".join(['{0} = broker.{0} * -1'.format(column) for column, table in website_cols
if table == 'ds_file_table' and column not in ['fain', 'uri', 'piid']])
@staticmethod
def get_file_table_joins(website_cols):
# Returns table joins according to identifier columns based on the file type
return " AND ".join(['broker.{0} = {1}.{0}'.format(column, table)
for column, table in website_cols
if table != 'ds_file_table' or column in ['fain', 'uri', 'piid']])
@staticmethod
def get_rows_to_update(file_type, submission_id, broker_cols, broker_cols_type, website_cols):
# Creates table with rows necessary to update
query_arguments = {'submission_id': submission_id,
'broker_cols': broker_cols,
'dblink_cols_type': broker_cols_type,
'website_cols': website_cols
}
if file_type == 'C':
query_arguments['broker_table'] = 'award_financial'
query_arguments['website_table'] = 'financial_accounts_by_awards'
query_arguments['broker_tmp_table'] = 'file_c_rows_to_update'
else:
query_arguments['broker_table'] = 'object_class_program_activity'
query_arguments['website_table'] = 'financial_accounts_by_program_activity_object_class'
query_arguments['broker_tmp_table'] = 'file_b_rows_to_update'
sql_statement = """
CREATE TEMPORARY TABLE {broker_tmp_table} AS
SELECT * from dblink(
'broker_server',
'SELECT
{broker_cols}
FROM {broker_table} db_file_table
INNER JOIN submission sub
ON db_file_table.submission_id = sub.submission_id
WHERE sub.publish_status_id = 2
AND db_file_table.submission_id = {submission_id};'
) AS (
{dblink_cols_type}
)
EXCEPT
SELECT
{website_cols}
from {website_table} ds_file_table
LEFT OUTER JOIN object_class oc
ON ds_file_table.object_class_id = oc.id
LEFT OUTER JOIN ref_program_activity pa
ON ds_file_table.program_activity_id = pa.id
LEFT OUTER JOIN treasury_appropriation_account tas
ON ds_file_table.treasury_account_id = tas.treasury_account_identifier
INNER JOIN submission_attributes sub
ON ds_file_table.submission_id = sub.submission_id
where sub.broker_submission_id = {submission_id};
""".format(**query_arguments)
return sql_statement
@staticmethod
def update_website_rows(ds_file_table, broker_tmp_table, set_statement, table_joins):
sql_statement = """
UPDATE {ds_file_table} ds_file_table
SET {set_statement}
FROM
{broker_tmp_table} broker,
object_class oc,
ref_program_activity pa,
treasury_appropriation_account tas,
submission_attributes sub
where ds_file_table.object_class_id = oc.id
AND ds_file_table.program_activity_id = pa.id
AND ds_file_table.treasury_account_id = tas.treasury_account_identifier
AND ds_file_table.submission_id = sub.submission_id
AND {table_joins}
;
""".format(ds_file_table=ds_file_table, broker_tmp_table=broker_tmp_table, table_mappings=table_joins,
set_statement=set_statement, table_joins=table_joins)
return sql_statement
def handle(self, *args, **options):
"""
Updates the column ussgl498100_upward_adjust_pri_deliv_orders_oblig_unpaid_cpe due to the incorrect
mapping in settings.py
"""
ds_cursor = connection.cursor()
logger.info('Begin updating file B and C')
broker_cols_b = self.get_list_of_broker_cols(financial_accounts_oc)
broker_cols_type_b = self.get_list_of_broker_cols_types(financial_accounts_oc)
website_cols_b = self.get_website_row_formatted(financial_accounts_oc)
website_update_text_b = self.get_cols_to_update(financial_accounts_oc)
website_cols_joins_b = self.get_file_table_joins(financial_accounts_oc)
broker_cols_c = self.get_list_of_broker_cols(financial_accounts_awards)
broker_cols_type_c = self.get_list_of_broker_cols_types(financial_accounts_awards)
website_cols_c = self.get_website_row_formatted(financial_accounts_awards)
website_update_text_c = self.get_cols_to_update(financial_accounts_awards)
website_cols_joins_c = self.get_file_table_joins(financial_accounts_awards)
with timer('getting submission ids to update', logger.info):
submissions_to_update = self.get_list_of_submissions()
for submission in submissions_to_update:
submission_id = submission[0]
# File B Updates
logger.info('loading rows data to update File B submission {}'.format(submission_id))
with timer('retrieving rows to update for File B submission {}'.format(submission_id), logger.info):
get_rows_to_update_query = self.get_rows_to_update('B', submission_id,
broker_cols_b, broker_cols_type_b,
website_cols_b)
ds_cursor.execute(get_rows_to_update_query)
with timer('updating rows for File B submission {}'.format(submission_id), logger.info):
update_rows = self.update_website_rows(
'financial_accounts_by_program_activity_object_class',
'file_b_rows_to_update', website_update_text_b, website_cols_joins_b
)
ds_cursor.execute(update_rows)
# File C updates
with timer('retrieving rows to update for File C submission {}'.format(submission_id), logger.info):
get_rows_to_update_query = self.get_rows_to_update(
'C',
submission_id,
broker_cols_c,
broker_cols_type_c,
website_cols_c)
ds_cursor.execute(get_rows_to_update_query)
with timer('updating rows for File C submission {}'.format(submission_id), logger.info):
update_rows = self.update_website_rows(
'financial_accounts_by_awards', 'file_c_rows_to_update', website_update_text_c, website_cols_joins_c
)
ds_cursor.execute(update_rows)
ds_cursor.execute("DROP TABLE file_b_rows_to_update")
ds_cursor.execute("DROP TABLE file_c_rows_to_update")
logger.info('Done updating file B and C mappings')
|
py | 1a4576d001dc1aa1de9b29ba538c19bc85882731 | """Base actions for the players to take."""
from csrv.model.actions import action
from csrv.model import appropriations
from csrv.model import cost
from csrv.model import errors
from csrv.model import events
from csrv.model import game_object
from csrv.model import parameters
from csrv.model.cards import card_info
class InstallProgram(action.Action):
DESCRIPTION = '[click]: Install a program'
COST_CLASS = cost.InstallProgramCost
REQUEST_CLASS = parameters.InstallProgramRequest
def __init__(self, game, player, card=None, cost=None):
action.Action.__init__(self, game, player, card=card, cost=cost)
self.cost.appropriations.append(appropriations.INSTALL_PROGRAMS)
if card_info.VIRUS in card.KEYWORDS:
self.cost.appropriations.append(appropriations.INSTALL_VIRUSES)
def resolve(self, response=None, ignore_clicks=False, ignore_all_costs=False):
if (not ignore_all_costs and
not self.cost.can_pay(response, ignore_clicks)):
raise errors.CostNotSatisfied(
'Not enough credits to install in that location.')
if response and response.programs_to_trash:
for program in response.programs_to_trash:
if program.location != self.game.runner.rig:
raise errors.InvalidResponse("You can't trash that")
program.trash()
if response and response.host:
if not response.host in self.card.install_host_targets():
raise errors.InvalidResponse(
'Cannot host this type of card')
if not response.host.meets_memory_limits(self.card):
raise errors.InvalidResponse(
'Host does not have enough memory free')
response.host.host_card(self.card)
action.Action.resolve(self, response,
ignore_clicks=ignore_clicks,
ignore_all_costs=ignore_all_costs)
self.player.rig.add(self.card)
@property
def description(self):
return 'Install %s' % self.card.NAME
|
py | 1a4577a4058b2fc494ca19fce590fb06f9ecb01d | #-*- coding: utf-8 -*-
from dbmodel.entity import *
class AcompanhanteCompra(Entity):
__primary_key__ = ['id']
# FIELDS
@Int(pk=True, auto_increment=True, not_null=True, precision = 10, scale=0)
def id(self): pass
@Int(fk=True, not_null=True, precision = 10, scale=0)
def id_acompanhante(self): pass
@DateTime(not_null=True)
def compra_data(self): pass
@String(max=100)
def compra_wc_order_id(self): pass
@String(max=100)
def compra_wc_payment_id(self): pass
@String(max=100)
def compra_wc_customer_id(self): pass
@String(max=65535)
def compra_wc_cc_hash(self): pass
@String(max=45)
def compra_wc_holder_name(self): pass
@DateTime()
def compra_wc_holder_birthday(self): pass
@String(max=11)
def compra_wc_holder_phone(self): pass
@String(max=11)
def compra_wc_holder_cpf(self): pass
@String(max=155)
def compra_wc_status(self): pass
@String(max=155)
def fin_descricao(self): pass
@Decimal(precision = 19, scale=2)
def fin_valor_servico(self): pass
@Decimal(precision = 19, scale=2)
def fin_tx_servico(self): pass
@Decimal(precision = 19, scale=2)
def fin_desconto(self): pass
@Decimal(precision = 19, scale=2)
def fin_valor_a_pagar(self): pass
@Decimal(precision = 19, scale=2)
def fin_valor_pago(self): pass
@Int(fk=True, not_null=True, precision = 10, scale=0)
def id_status_pagamento(self): pass
@Int(fk=True, not_null=True, precision = 10, scale=0)
def id_forma_pagamento(self): pass
@Int(fk=True, not_null=True, precision = 10, scale=0)
def id_tipo_desconto(self): pass
@Int(fk=True, not_null=True, precision = 10, scale=0)
def id_servico(self): pass
@Int(fk=True, precision = 10, scale=0)
def id_financeiro(self): pass
# One-to-One
@Object(name="FinanceiroStatusPagamento", key="id", reference="id_status_pagamento", table="financeiros_status_pagamentos")
def financeiros_status_pagamentos(self):pass
@Object(name="Acompanhante", key="id", reference="id_acompanhante", table="acompanhantes")
def acompanhantes(self):pass
@Object(name="Financeiro", key="id", reference="id_financeiro", table="financeiros")
def financeiros(self):pass
@Object(name="FinanceiroTipoDesconto", key="id", reference="id_tipo_desconto", table="financeiros_tipos_descontos")
def financeiros_tipos_descontos(self):pass
@Object(name="FinanceiroFormaPagamento", key="id", reference="id_forma_pagamento", table="financeiros_formas_pagamentos")
def financeiros_formas_pagamentos(self):pass
@Object(name="FinanceiroServico", key="id", reference="id_servico", table="financeiros_servicos")
def financeiros_servicos(self):pass |
py | 1a45780b002ffec3e529f57a2b27c9239f404860 | import retrying
# import urllib.parse
# import urllib
import urllib.request
import requests
import logging
from abc import abstractmethod, ABCMeta
from libs.dictionary.base import DictBase
class HJDict_Base(DictBase, metaclass=ABCMeta):
headers = {"User-Agent":
"Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) "
"AppleWebKit/536.26 (KHTML, like Gecko) "
"Version/6.0 Mobile/10A5376e Safari/8536.25",
}
@retrying.retry(stop_max_attempt_number=5)
def look_up(self, word):
req_url = self.get_req_url(word)
logging.debug("Connecting: {}".format(req_url))
data = self.additional_data(word)
headers = self.additional_header(word)
for k, v in headers.items():
self.headers[k] = v
r = requests.post(req_url, data=data, headers=self.headers)
page = r.text
parsed_result = self.parse_page(page)
return parsed_result
def encode_query(self, q):
# requests.utils.requote_uri
# TODO: delete
quoted = urllib.parse.quote(q, encoding='utf-8')
return quoted
@abstractmethod
def get_req_url(self, word):
pass
@abstractmethod
def parse_page(self, page):
pass
def additional_header(self, word):
return {}
def additional_data(self, word):
return {}
|
py | 1a45783f4f84f0d55cd51f1476541407c1f1cb0d | import json
import os
from typing import Optional
from eth_abi import encode_abi
from web3 import Web3, HTTPProvider
from web3.contract import Contract
try:
from web3.utils.abi import get_constructor_abi, merge_args_and_kwargs
from web3.utils.events import get_event_data
from web3.utils.filters import construct_event_filter_params
from web3.utils.contracts import encode_abi
from web3.middleware import geth_poa_middleware
except ImportError:
from web3._utils.abi import get_constructor_abi, merge_args_and_kwargs
from web3._utils.events import get_event_data
from web3._utils.filters import construct_event_filter_params
from web3._utils.contracts import encode_abi
from web3.middleware import geth_poa_middleware
from eth_utils import (
keccak,
is_hex_address,
is_checksum_address,
to_hex
)
class NoNodeConfigured(Exception):
pass
class NeedPrivateKey(Exception):
pass
def check_good_node_url(node_url: str):
if not node_url:
raise NoNodeConfigured("You need to give --ethereum-node-url command line option or set it up in a config file")
def get_abi():
abi_file = os.path.join(os.path.dirname(__file__), "erc20.abi.json")
with open(abi_file, "rt") as inp:
return json.load(inp)
def create_web3(url: str) -> Web3:
"""Web3 initializer."""
if isinstance(url, Web3):
# Shortcut for testing
url.middleware_onion.inject(geth_poa_middleware, layer=0)
return url
else:
w3 = Web3(HTTPProvider(url))
w3.middleware_onion.inject(geth_poa_middleware, layer=0)
return w3
def integer_hash(number: int):
return int(keccak(number).hex(), 16)
def validate_ethereum_address(address: str):
"""Clever Ethereum address validator.
Assume all lowercase addresses are not checksummed.
"""
if len(address) < 42:
raise ValueError("Not an Ethereum address: {}".format(address))
try:
if not is_hex_address(address):
raise ValueError("Not an Ethereum address: {}".format(address))
except UnicodeEncodeError:
raise ValueError("Could not decode: {}".format(address))
# Check if checksummed address if any of the letters is upper case
if any([c.isupper() for c in address]):
if not is_checksum_address(address):
raise ValueError("Not a checksummed Ethereum address: {}".format(address))
def get_constructor_arguments(contract: Contract, args: Optional[list] = None, kwargs: Optional[dict] = None):
"""Get constructor arguments for Etherscan verify.
https://etherscanio.freshdesk.com/support/solutions/articles/16000053599-contract-verification-constructor-arguments
"""
# return contract._encode_constructor_data(args=args, kwargs=kwargs)
constructor_abi = get_constructor_abi(contract.abi)
# constructor_abi can be none in case of libraries
if constructor_abi is None:
return to_hex(contract.bytecode)
if args is not None:
return contract.encodeABI(constructor_abi['name'], args)[2:] # No 0x
else:
constructor_abi = get_constructor_abi(contract.abi)
kwargs = kwargs or {}
arguments = merge_args_and_kwargs(constructor_abi, [], kwargs)
# deploy_data = add_0x_prefix(
# contract._encode_abi(constructor_abi, arguments)
# )
# TODO: Looks like recent Web3.py ABI change
deploy_data = encode_abi(contract.web3, constructor_abi, arguments)
return deploy_data
def getLogs(self,
argument_filters=None,
fromBlock=None,
toBlock="latest",
address=None,
topics=None):
"""Get events using eth_getLogs API.
This is a stateless method, as opposite to createFilter.
It can be safely called against nodes which do not provide eth_newFilter API, like Infura.
:param argument_filters:
:param fromBlock:
:param toBlock:
:param address:
:param topics:
:return:
"""
if fromBlock is None:
raise TypeError("Missing mandatory keyword argument to getLogs: fromBlock")
abi = self._get_event_abi()
argument_filters = dict()
_filters = dict(**argument_filters)
# Construct JSON-RPC raw filter presentation based on human readable Python descriptions
# Namely, convert event names to their keccak signatures
data_filter_set, event_filter_params = construct_event_filter_params(
abi,
abi_codec=self.web3.codec,
contract_address=self.address,
argument_filters=_filters,
fromBlock=fromBlock,
toBlock=toBlock,
address=address,
topics=topics,
)
# Call JSON-RPC API
logs = self.web3.eth.getLogs(event_filter_params)
# Convert raw binary data to Python proxy objects as described by ABI
for entry in logs:
yield get_event_data(self.web3.codec, abi, entry)
|
py | 1a457882dec6bc27200d588fa3d054f83e3e25f7 | #!/usr/bin/env python3
"""
Example: Write the contents of a Buffer to disk.
"""
from supercollider import Server, Synth, Buffer, HEADER_FORMAT_WAV
import math
OUTPUT_FILE = "/tmp/440.wav"
#-------------------------------------------------------------------------------
# Create connection to default server on localhost:57110
#-------------------------------------------------------------------------------
server = Server()
#-------------------------------------------------------------------------------
# Create a Buffer, generate a 440Hz sine, and write to a .wav.
#-------------------------------------------------------------------------------
length = 1024
server_status = server.get_status()
sample_rate = server_status["sample_rate_nominal"]
buf = Buffer.alloc(server, length)
buf.set([ math.sin(n * math.pi * 2.0 * 440.0 / sample_rate) for n in range(int(length)) ])
buf.write(OUTPUT_FILE, HEADER_FORMAT_WAV)
print("Written buffer to %s" % OUTPUT_FILE)
|
py | 1a4578d5e76f16374dca4c4841539453c72afd4a | # -*- coding: utf-8 -*-
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import unicode_literals
from dirty_period_finding.extensions import BasicMathGateEx, SelfInverseGateEx
class PivotFlipGate(BasicMathGateEx, SelfInverseGateEx):
def __init__(self):
SelfInverseGateEx.__init__(self)
BasicMathGateEx.__init__(self)
def do_operation(self, pivot, x):
if x >= pivot:
return pivot, x
return pivot, pivot - x - 1
def __eq__(self, other):
return isinstance(other, PivotFlipGate)
def __hash__(self):
return hash(PivotFlipGate)
def __repr__(self):
return 'PivotFlip'
def __str__(self):
return 'Flip<A'
def ascii_register_labels(self):
return ['A', 'Flip<A']
class ConstPivotFlipGate(BasicMathGateEx, SelfInverseGateEx):
def __init__(self, pivot):
SelfInverseGateEx.__init__(self)
BasicMathGateEx.__init__(self)
self.pivot = pivot
def do_operation(self, x):
if x >= self.pivot:
return x,
return self.pivot - x - 1,
def __eq__(self, other):
return (isinstance(other, ConstPivotFlipGate) and
self.pivot == other.pivot)
def __hash__(self):
return hash((ConstPivotFlipGate, self.pivot))
def __repr__(self):
return 'ConstPivotFlipGate({})'.format(self.pivot)
def __str__(self):
return 'Flip<{}'.format(self.pivot)
PivotFlip = PivotFlipGate()
|
py | 1a457c7d3afa2690c76fbca83096a871fceb7efc | from random import randint
"""
Найти наименьшее натуральное число, записываемое в десятичной системе счисления только с помощью цифр 0 и 1,
которое делится без остатка на заданное число К (2 ≤ К ≤ 100).
"""
def first_exercise(numbers, divider):
array = [number for number in numbers if number % divider == 0]
if len(array) != 0:
return min(array)
else:
return "Список пустой!"
numbers = [int("".join([str(randint(0, 1)) for _ in range(0, 10)])) for _ in range(100)]
divider = int(input("Введите делитель: "))
print(first_exercise(numbers, divider))
|
py | 1a457d06b13e67c2c35976e865302f40dd5e100b | import os
import posixpath
import string
from pathlib import PurePath
from shutil import copyfileobj, rmtree
import boto3
from flask import current_app, redirect, send_file
from flask.helpers import safe_join
from werkzeug.utils import secure_filename
from CTFd.utils import get_app_config
from CTFd.utils.encoding import hexencode
class BaseUploader(object):
def __init__(self):
raise NotImplementedError
def store(self, fileobj, filename):
raise NotImplementedError
def upload(self, file_obj, filename):
raise NotImplementedError
def download(self, filename):
raise NotImplementedError
def delete(self, filename):
raise NotImplementedError
def sync(self):
raise NotImplementedError
class FilesystemUploader(BaseUploader):
def __init__(self, base_path=None):
super(BaseUploader, self).__init__()
self.base_path = base_path or current_app.config.get("UPLOAD_FOLDER")
def store(self, fileobj, filename):
location = os.path.join(self.base_path, filename)
directory = os.path.dirname(location)
if not os.path.exists(directory):
os.makedirs(directory)
with open(location, "wb") as dst:
copyfileobj(fileobj, dst, 16384)
return filename
def upload(self, file_obj, filename):
if len(filename) == 0:
raise Exception("Empty filenames cannot be used")
filename = secure_filename(filename)
md5hash = hexencode(os.urandom(16))
file_path = posixpath.join(md5hash, filename)
return self.store(file_obj, file_path)
def download(self, filename):
return send_file(safe_join(self.base_path, filename), as_attachment=True)
def delete(self, filename):
if os.path.exists(os.path.join(self.base_path, filename)):
file_path = PurePath(filename).parts[0]
rmtree(os.path.join(self.base_path, file_path))
return True
return False
def sync(self):
pass
class S3Uploader(BaseUploader):
def __init__(self):
super(BaseUploader, self).__init__()
self.s3 = self._get_s3_connection()
self.bucket = get_app_config("AWS_S3_BUCKET")
def _get_s3_connection(self):
access_key = get_app_config("AWS_ACCESS_KEY_ID")
secret_key = get_app_config("AWS_SECRET_ACCESS_KEY")
endpoint = get_app_config("AWS_S3_ENDPOINT_URL")
client = boto3.client(
"s3",
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
endpoint_url=endpoint,
)
return client
def _clean_filename(self, c):
if c in string.ascii_letters + string.digits + "-" + "_" + ".":
return True
def store(self, fileobj, filename):
self.s3.upload_fileobj(fileobj, self.bucket, filename)
return filename
def upload(self, file_obj, filename):
filename = filter(
self._clean_filename, secure_filename(filename).replace(" ", "_")
)
filename = "".join(filename)
if len(filename) <= 0:
return False
md5hash = hexencode(os.urandom(16))
dst = md5hash + "/" + filename
self.s3.upload_fileobj(file_obj, self.bucket, dst)
return dst
def download(self, filename):
key = filename
filename = filename.split("/").pop()
url = self.s3.generate_presigned_url(
"get_object",
Params={
"Bucket": self.bucket,
"Key": key,
"ResponseContentDisposition": "attachment; filename={}".format(
filename
),
},
)
return redirect(url)
def delete(self, filename):
self.s3.delete_object(Bucket=self.bucket, Key=filename)
return True
def sync(self):
local_folder = current_app.config.get("UPLOAD_FOLDER")
# If the bucket is empty then Contents will not be in the response
bucket_list = self.s3.list_objects(Bucket=self.bucket).get("Contents", [])
for s3_key in bucket_list:
s3_object = s3_key["Key"]
# We don't want to download any directories
if s3_object.endswith("/") is False:
local_path = os.path.join(local_folder, s3_object)
directory = os.path.dirname(local_path)
if not os.path.exists(directory):
os.makedirs(directory)
self.s3.download_file(self.bucket, s3_object, local_path)
|
py | 1a457df399ed4da4ee2d3b1243c2b8e3e4a84156 | # coding: utf-8
"""
Cisco Intersight OpenAPI specification.
The Cisco Intersight OpenAPI specification.
OpenAPI spec version: 1.0.9-1461
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class HyperflexDeploySoftwareVmTaskRef(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'object_type': 'str',
'moid': 'str',
'selector': 'str'
}
attribute_map = {
'object_type': 'ObjectType',
'moid': 'Moid',
'selector': 'Selector'
}
def __init__(self, object_type=None, moid=None, selector=None):
"""
HyperflexDeploySoftwareVmTaskRef - a model defined in Swagger
"""
self._object_type = None
self._moid = None
self._selector = None
if object_type is not None:
self.object_type = object_type
if moid is not None:
self.moid = moid
if selector is not None:
self.selector = selector
@property
def object_type(self):
"""
Gets the object_type of this HyperflexDeploySoftwareVmTaskRef.
The Object Type of the referenced REST resource.
:return: The object_type of this HyperflexDeploySoftwareVmTaskRef.
:rtype: str
"""
return self._object_type
@object_type.setter
def object_type(self, object_type):
"""
Sets the object_type of this HyperflexDeploySoftwareVmTaskRef.
The Object Type of the referenced REST resource.
:param object_type: The object_type of this HyperflexDeploySoftwareVmTaskRef.
:type: str
"""
self._object_type = object_type
@property
def moid(self):
"""
Gets the moid of this HyperflexDeploySoftwareVmTaskRef.
The Moid of the referenced REST resource.
:return: The moid of this HyperflexDeploySoftwareVmTaskRef.
:rtype: str
"""
return self._moid
@moid.setter
def moid(self, moid):
"""
Sets the moid of this HyperflexDeploySoftwareVmTaskRef.
The Moid of the referenced REST resource.
:param moid: The moid of this HyperflexDeploySoftwareVmTaskRef.
:type: str
"""
self._moid = moid
@property
def selector(self):
"""
Gets the selector of this HyperflexDeploySoftwareVmTaskRef.
An OData $filter expression which describes the REST resource to be referenced. This field may be set instead of 'moid' by clients. If 'moid' is set this field is ignored. If 'selector' is set and 'moid' is empty/absent from the request, Intersight will determine the Moid of the resource matching the filter expression and populate it in the MoRef that is part of the object instance being inserted/updated to fulfill the REST request. An error is returned if the filter matches zero or more than one REST resource. An example filter string is: Serial eq '3AA8B7T11'.
:return: The selector of this HyperflexDeploySoftwareVmTaskRef.
:rtype: str
"""
return self._selector
@selector.setter
def selector(self, selector):
"""
Sets the selector of this HyperflexDeploySoftwareVmTaskRef.
An OData $filter expression which describes the REST resource to be referenced. This field may be set instead of 'moid' by clients. If 'moid' is set this field is ignored. If 'selector' is set and 'moid' is empty/absent from the request, Intersight will determine the Moid of the resource matching the filter expression and populate it in the MoRef that is part of the object instance being inserted/updated to fulfill the REST request. An error is returned if the filter matches zero or more than one REST resource. An example filter string is: Serial eq '3AA8B7T11'.
:param selector: The selector of this HyperflexDeploySoftwareVmTaskRef.
:type: str
"""
self._selector = selector
def to_dict(self):
"""
Returns the model properties as a dict
"""
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):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, HyperflexDeploySoftwareVmTaskRef):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
|
py | 1a457e052330f4fd1c5e92fecbc6d5a052559fb0 | # -*- coding:utf-8 -*-
# pylint: disable=C0103, C0413
"""
Initializing telegram bot
"""
from os import environ
from telebot import TeleBot, types
from config import DEFAULT_LANGUAGE, EN
TOKEN = environ.get("TELEGRAM_BOT_TOKEN")
APP_SITE = environ.get("APP_SITE")
DEFAULT_PARSE_MODE = "HTML"
MESSAGE_NOT_FOUND = "Sorry, but nothing was found for <b>%s</b>."
MESSAGE_SPECIFY_LOGLAN_WORD = (
"You need to specify the Loglan word you would like to find."
)
MESSAGE_SPECIFY_ENGLISH_WORD = (
"You need to specify the English word you would like to find."
)
MIN_NUMBER_OF_BUTTONS = 50
bot = TeleBot(TOKEN)
ADMIN = int(environ.get("TELEGRAM_ADMIN_ID"))
cbq = types.CallbackQuery
msg = types.Message
from bot import processor
|
py | 1a457ef5863807710702a0643120d447e7ba7bc3 | # -*- coding: utf-8 -*-
"""
Paystack API wrapper.
@author Bernard Ojengwa.
Copyright (c) 2015, Bernard Ojengwa
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OF
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
# from paystack.resource import (TransactionResource,
# CustomerResource,
# PlanResource)
# from paystack.version import VERSION as __version__
# __all__ = [
# 'TransactionResource',
# 'CustomerResource',
# 'PlanResource',
# '__version__'
# ]
|
py | 1a457f11a6513d1307cde03e1149e6beb563e414 | import os
import glob
import pandas as pd
game_files = glob.glob(os.path.join(os.getcwd(), 'games', '*.EVE'))
game_files.sort()
game_frames = []
for game_file in game_files:
game_frame = pd.read_csv(game_file, names=['type', 'multi2', 'multi3', 'multi4', 'multi5', 'multi6', 'event'])
game_frames.append(game_frame)
games = pd.concat(game_frames)
games.loc[games['multi5'] == '??', 'multi5'] = ''
identifiers = games['multi2'].str.extract(r'(.LS(\d{4})\d{5})')
identifiers = identifiers.fillna(method='ffill')
identifiers.columns = ['game_id', 'year']
games = pd.concat([games, identifiers], axis=1, sort=False)
games = games.fillna(' ')
games.loc[:, 'type'] = pd.Categorical(games.loc[:, 'type'])
print(games.head())
|
py | 1a457fa712b98d92b68f597bc2c1e9bec53816de | """
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 2.0.13.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '&2i)tc+x_$)t52=%!@417*0eyox9v9%exd22ucr+kn$a*0xmvr'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['127.0.0.1','.pythonanywhere.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Europe/Berlin'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
|
py | 1a4580626d99da1606d0d175648f84f8a3b182eb | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2016-12-03 03:57
from django.db import migrations
def forwards(apps, schema_editor):
Deck = apps.get_model('flashcards', 'Deck')
for deck in Deck.objects.all().iterator():
deck.save()
class Migration(migrations.Migration):
dependencies = [
('flashcards', '0026_add_deck_slug'),
]
operations = [
migrations.RunPython(forwards)
]
|
py | 1a45811f463e3b46ce374f358f337b479531f953 | # Generated by Django 2.2a1 on 2019-02-10 00:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vk_apps_users', '0002_auto_20190202_0104'),
]
operations = [
migrations.AlterModelOptions(
name='vkappsuser',
options={'verbose_name': 'VK Apps User', 'verbose_name_plural': 'VK Apps Users'},
),
migrations.AlterField(
model_name='vkappsuser',
name='vk_id',
field=models.IntegerField(primary_key=True, serialize=False, unique=True, verbose_name='VK ID'),
),
]
|
py | 1a45826f50cb286d4a66b9f335acccd7c99a2cd7 | import sys
import pygame
from bullet import Bullet
def check_keydown_events(event, ai_settings, screen, ship, bullets):
"""Respond to keypresses."""
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
elif event.key == pygame.K_SPACE:
fire_bullet(ai_settings, screen, ship, bullets)
def check_keyup_events(event, ship):
"""Respond to key releases."""
if event.key == pygame.K_RIGHT:
ship.moving_right = False
elif event.key == pygame.K_LEFT:
ship.moving_left = False
def check_events(ai_settings, screen, ship, bullets):
"""Respond to keypresses and mouse events."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
check_keydown_events(event, ai_settings, screen, ship, bullets)
elif event.type == pygame.KEYUP:
check_keyup_events(event, ship)
def fire_bullet(ai_settings, screen, ship, bullets):
"""Fire a bullet, if limit not reached yet."""
# Create a new bullet, add to bullets group.
if len(bullets) < ai_settings.bullets_allowed:
new_bullet = Bullet(ai_settings, screen, ship)
bullets.add(new_bullet)
def update_screen(ai_settings, screen, ship, bullets):
"""Update images on the screen, and flip to the new screen."""
# Redraw the screen, each pass through the loop.
screen.fill(ai_settings.bg_color)
# Redraw all bullets, behind ship and aliens.
for bullet in bullets.sprites():
bullet.draw_bullet()
ship.blitme()
# Make the most recently drawn screen visible.
pygame.display.flip()
def update_bullets(bullets):
"""Update position of bullets, and get rid of old bullets."""
# Update bullet positions.
bullets.update()
# Get rid of bullets that have disappeared.
for bullet in bullets.copy():
if bullet.rect.bottom <= 0:
bullets.remove(bullet) |
py | 1a4582e85d2ba0e366ffbede4e4c23fa4f828e79 | # Copyright (C) 2006-2007 Robey Pointer <[email protected]>
#
# This file is part of paramiko.
#
# Paramiko is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later version.
#
# Paramiko is distrubuted in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Paramiko; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
"""
L{SSHClient}.
"""
from binascii import hexlify
import getpass
import os
import socket
from paramiko.agent import Agent
from paramiko.common import *
from paramiko.dsskey import DSSKey
from paramiko.hostkeys import HostKeys
from paramiko.resource import ResourceManager
from paramiko.rsakey import RSAKey
from paramiko.ssh_exception import SSHException, BadHostKeyException
from paramiko.transport import Transport
class MissingHostKeyPolicy (object):
"""
Interface for defining the policy that L{SSHClient} should use when the
SSH server's hostname is not in either the system host keys or the
application's keys. Pre-made classes implement policies for automatically
adding the key to the application's L{HostKeys} object (L{AutoAddPolicy}),
and for automatically rejecting the key (L{RejectPolicy}).
This function may be used to ask the user to verify the key, for example.
"""
def missing_host_key(self, client, hostname, key):
"""
Called when an L{SSHClient} receives a server key for a server that
isn't in either the system or local L{HostKeys} object. To accept
the key, simply return. To reject, raised an exception (which will
be passed to the calling application).
"""
pass
class AutoAddPolicy (MissingHostKeyPolicy):
"""
Policy for automatically adding the hostname and new host key to the
local L{HostKeys} object, and saving it. This is used by L{SSHClient}.
"""
def missing_host_key(self, client, hostname, key):
client._host_keys.add(hostname, key.get_name(), key)
if client._host_keys_filename is not None:
client.save_host_keys(client._host_keys_filename)
client._log(DEBUG, 'Adding %s host key for %s: %s' %
(key.get_name(), hostname, hexlify(key.get_fingerprint())))
class RejectPolicy (MissingHostKeyPolicy):
"""
Policy for automatically rejecting the unknown hostname & key. This is
used by L{SSHClient}.
"""
def missing_host_key(self, client, hostname, key):
client._log(DEBUG, 'Rejecting %s host key for %s: %s' %
(key.get_name(), hostname, hexlify(key.get_fingerprint())))
raise SSHException('Unknown server %s' % hostname)
class SSHClient (object):
"""
A high-level representation of a session with an SSH server. This class
wraps L{Transport}, L{Channel}, and L{SFTPClient} to take care of most
aspects of authenticating and opening channels. A typical use case is::
client = SSHClient()
client.load_system_host_keys()
client.connect('ssh.example.com')
stdin, stdout, stderr = client.exec_command('ls -l')
You may pass in explicit overrides for authentication and server host key
checking. The default mechanism is to try to use local key files or an
SSH agent (if one is running).
@since: 1.6
"""
def __init__(self):
"""
Create a new SSHClient.
"""
self._system_host_keys = HostKeys()
self._host_keys = HostKeys()
self._host_keys_filename = None
self._log_channel = None
self._policy = RejectPolicy()
self._transport = None
def load_system_host_keys(self, filename=None):
"""
Load host keys from a system (read-only) file. Host keys read with
this method will not be saved back by L{save_host_keys}.
This method can be called multiple times. Each new set of host keys
will be merged with the existing set (new replacing old if there are
conflicts).
If C{filename} is left as C{None}, an attempt will be made to read
keys from the user's local "known hosts" file, as used by OpenSSH,
and no exception will be raised if the file can't be read. This is
probably only useful on posix.
@param filename: the filename to read, or C{None}
@type filename: str
@raise IOError: if a filename was provided and the file could not be
read
"""
if filename is None:
# try the user's .ssh key file, and mask exceptions
filename = os.path.expanduser('~/.ssh/known_hosts')
try:
self._system_host_keys.load(filename)
except IOError:
pass
return
self._system_host_keys.load(filename)
def load_host_keys(self, filename):
"""
Load host keys from a local host-key file. Host keys read with this
method will be checked I{after} keys loaded via L{load_system_host_keys},
but will be saved back by L{save_host_keys} (so they can be modified).
The missing host key policy L{AutoAddPolicy} adds keys to this set and
saves them, when connecting to a previously-unknown server.
This method can be called multiple times. Each new set of host keys
will be merged with the existing set (new replacing old if there are
conflicts). When automatically saving, the last hostname is used.
@param filename: the filename to read
@type filename: str
@raise IOError: if the filename could not be read
"""
self._host_keys_filename = filename
self._host_keys.load(filename)
def save_host_keys(self, filename):
"""
Save the host keys back to a file. Only the host keys loaded with
L{load_host_keys} (plus any added directly) will be saved -- not any
host keys loaded with L{load_system_host_keys}.
@param filename: the filename to save to
@type filename: str
@raise IOError: if the file could not be written
"""
f = open(filename, 'w')
f.write('# SSH host keys collected by paramiko\n')
for hostname, keys in self._host_keys.iteritems():
for keytype, key in keys.iteritems():
f.write('%s %s %s\n' % (hostname, keytype, key.get_base64()))
f.close()
def get_host_keys(self):
"""
Get the local L{HostKeys} object. This can be used to examine the
local host keys or change them.
@return: the local host keys
@rtype: L{HostKeys}
"""
return self._host_keys
def set_log_channel(self, name):
"""
Set the channel for logging. The default is C{"paramiko.transport"}
but it can be set to anything you want.
@param name: new channel name for logging
@type name: str
"""
self._log_channel = name
def set_missing_host_key_policy(self, policy):
"""
Set the policy to use when connecting to a server that doesn't have a
host key in either the system or local L{HostKeys} objects. The
default policy is to reject all unknown servers (using L{RejectPolicy}).
You may substitute L{AutoAddPolicy} or write your own policy class.
@param policy: the policy to use when receiving a host key from a
previously-unknown server
@type policy: L{MissingHostKeyPolicy}
"""
self._policy = policy
def connect(self, hostname, port=22, username=None, password=None, pkey=None,
key_filename=None, timeout=None):
"""
Connect to an SSH server and authenticate to it. The server's host key
is checked against the system host keys (see L{load_system_host_keys})
and any local host keys (L{load_host_keys}). If the server's hostname
is not found in either set of host keys, the missing host key policy
is used (see L{set_missing_host_key_policy}). The default policy is
to reject the key and raise an L{SSHException}.
Authentication is attempted in the following order of priority:
- The C{pkey} or C{key_filename} passed in (if any)
- Any key we can find through an SSH agent
- Any "id_rsa" or "id_dsa" key discoverable in C{~/.ssh/}
- Plain username/password auth, if a password was given
If a private key requires a password to unlock it, and a password is
passed in, that password will be used to attempt to unlock the key.
@param hostname: the server to connect to
@type hostname: str
@param port: the server port to connect to
@type port: int
@param username: the username to authenticate as (defaults to the
current local username)
@type username: str
@param password: a password to use for authentication or for unlocking
a private key
@type password: str
@param pkey: an optional private key to use for authentication
@type pkey: L{PKey}
@param key_filename: the filename of an optional private key to use
for authentication
@type key_filename: str
@param timeout: an optional timeout (in seconds) for the TCP connect
@type timeout: float
@raise BadHostKeyException: if the server's host key could not be
verified
@raise AuthenticationException: if authentication failed
@raise SSHException: if there was any other error connecting or
establishing an SSH session
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if timeout is not None:
try:
sock.settimeout(timeout)
except:
pass
sock.connect((hostname, port))
t = self._transport = Transport(sock)
if self._log_channel is not None:
t.set_log_channel(self._log_channel)
t.start_client()
ResourceManager.register(self, t)
server_key = t.get_remote_server_key()
keytype = server_key.get_name()
our_server_key = self._system_host_keys.get(hostname, {}).get(keytype, None)
if our_server_key is None:
our_server_key = self._host_keys.get(hostname, {}).get(keytype, None)
if our_server_key is None:
# will raise exception if the key is rejected; let that fall out
self._policy.missing_host_key(self, hostname, server_key)
# if the callback returns, assume the key is ok
our_server_key = server_key
if server_key != our_server_key:
raise BadHostKeyException(hostname, server_key, our_server_key)
if username is None:
username = getpass.getuser()
self._auth(username, password, pkey, key_filename)
def close(self):
"""
Close this SSHClient and its underlying L{Transport}.
"""
self._transport.close()
self._transport = None
def exec_command(self, command):
"""
Execute a command on the SSH server. A new L{Channel} is opened and
the requested command is executed. The command's input and output
streams are returned as python C{file}-like objects representing
stdin, stdout, and stderr.
@param command: the command to execute
@type command: str
@return: the stdin, stdout, and stderr of the executing command
@rtype: tuple(L{ChannelFile}, L{ChannelFile}, L{ChannelFile})
@raise SSHException: if the server fails to execute the command
"""
chan = self._transport.open_session()
chan.exec_command(command)
stdin = chan.makefile('wb')
stdout = chan.makefile('rb')
stderr = chan.makefile_stderr('rb')
return stdin, stdout, stderr
def invoke_shell(self, term='vt100', width=80, height=24):
"""
Start an interactive shell session on the SSH server. A new L{Channel}
is opened and connected to a pseudo-terminal using the requested
terminal type and size.
@param term: the terminal type to emulate (for example, C{"vt100"})
@type term: str
@param width: the width (in characters) of the terminal window
@type width: int
@param height: the height (in characters) of the terminal window
@type height: int
@return: a new channel connected to the remote shell
@rtype: L{Channel}
@raise SSHException: if the server fails to invoke a shell
"""
chan = self._transport.open_session()
chan.get_pty(term, width, height)
chan.invoke_shell()
return chan
def open_sftp(self):
"""
Open an SFTP session on the SSH server.
@return: a new SFTP session object
@rtype: L{SFTPClient}
"""
return self._transport.open_sftp_client()
def _auth(self, username, password, pkey, key_filename):
"""
Try, in order:
- The key passed in, if one was passed in.
- Any key we can find through an SSH agent.
- Any "id_rsa" or "id_dsa" key discoverable in ~/.ssh/.
- Plain username/password auth, if a password was given.
(The password might be needed to unlock a private key.)
"""
saved_exception = None
if pkey is not None:
try:
self._log(DEBUG, 'Trying SSH key %s' % hexlify(pkey.get_fingerprint()))
self._transport.auth_publickey(username, pkey)
return
except SSHException, e:
saved_exception = e
if key_filename is not None:
for pkey_class in (RSAKey, DSSKey):
try:
key = pkey_class.from_private_key_file(key_filename, password)
self._log(DEBUG, 'Trying key %s from %s' % (hexlify(key.get_fingerprint()), key_filename))
self._transport.auth_publickey(username, key)
return
except SSHException, e:
saved_exception = e
for key in Agent().get_keys():
try:
self._log(DEBUG, 'Trying SSH agent key %s' % hexlify(key.get_fingerprint()))
self._transport.auth_publickey(username, key)
return
except SSHException, e:
saved_exception = e
keyfiles = []
rsa_key = os.path.expanduser('~/.ssh/id_rsa')
dsa_key = os.path.expanduser('~/.ssh/id_dsa')
if os.path.isfile(rsa_key):
keyfiles.append((RSAKey, rsa_key))
if os.path.isfile(dsa_key):
keyfiles.append((DSSKey, dsa_key))
for pkey_class, filename in keyfiles:
try:
key = pkey_class.from_private_key_file(filename, password)
self._log(DEBUG, 'Trying discovered key %s in %s' % (hexlify(key.get_fingerprint()), filename))
self._transport.auth_publickey(username, key)
return
except SSHException, e:
saved_exception = e
except IOError, e:
saved_exception = e
if password is not None:
try:
self._transport.auth_password(username, password)
return
except SSHException, e:
saved_exception = e
# if we got an auth-failed exception earlier, re-raise it
if saved_exception is not None:
raise saved_exception
raise SSHException('No authentication methods available')
def _log(self, level, msg):
self._transport._log(level, msg)
|
py | 1a45830e1a79f61a3748db005c2a7efbc27fc80f | # Auto generated by generator.py. Delete this line if you make modification.
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
XPATH = {
'name' : "//h1[@class='product_name']",
'price' : "//tr/td/p[@class='price']",
'category' : "//div[@class='content_right']/div[@class='directory']/div[@class='directory_content']/a",
'description' : "",
'images' : "//img[@class='image_of_product']/@src",
'canonical' : "",
'base_url' : "",
'brand' : ""
}
name = 'thoitranghanquoc.vn'
allowed_domains = ['thoitranghanquoc.vn']
start_urls = ['http://thoitranghanquoc.vn']
tracking_url = ''
sitemap_urls = ['']
sitemap_rules = [('', 'parse_item')]
sitemap_follow = []
rules = [
Rule(LinkExtractor(allow=['/[a-zA-Z0-9-]+-\d+\.htm$']), 'parse_item'),
Rule(LinkExtractor(allow=['/\d+/']), 'parse'),
#Rule(LinkExtractor(), 'parse_item_and_links'),
]
|
py | 1a45849cffb818d81178ec62bd2a02c4fbb9be96 | # Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import argparse
import llnl.util.tty as tty
import spack.cmd
import spack.environment as ev
import spack.repo
import spack.store
import spack.spec
import spack.binary_distribution as bindist
description = "create, download and install binary packages"
section = "packaging"
level = "long"
def setup_parser(subparser):
setup_parser.parser = subparser
subparsers = subparser.add_subparsers(help='buildcache sub-commands')
create = subparsers.add_parser('create', help=createtarball.__doc__)
create.add_argument('-r', '--rel', action='store_true',
help="make all rpaths relative" +
" before creating tarballs.")
create.add_argument('-f', '--force', action='store_true',
help="overwrite tarball if it exists.")
create.add_argument('-u', '--unsigned', action='store_true',
help="create unsigned buildcache" +
" tarballs for testing")
create.add_argument('-a', '--allow-root', action='store_true',
help="allow install root string in binary files " +
"after RPATH substitution")
create.add_argument('-k', '--key', metavar='key',
type=str, default=None,
help="Key for signing.")
create.add_argument('-d', '--directory', metavar='directory',
type=str, default='.',
help="directory in which to save the tarballs.")
create.add_argument(
'packages', nargs=argparse.REMAINDER,
help="specs of packages to create buildcache for")
create.set_defaults(func=createtarball)
install = subparsers.add_parser('install', help=installtarball.__doc__)
install.add_argument('-f', '--force', action='store_true',
help="overwrite install directory if it exists.")
install.add_argument('-m', '--multiple', action='store_true',
help="allow all matching packages ")
install.add_argument('-a', '--allow-root', action='store_true',
help="allow install root string in binary files " +
"after RPATH substitution")
install.add_argument('-u', '--unsigned', action='store_true',
help="install unsigned buildcache" +
" tarballs for testing")
install.add_argument(
'packages', nargs=argparse.REMAINDER,
help="specs of packages to install buildcache for")
install.set_defaults(func=installtarball)
listcache = subparsers.add_parser('list', help=listspecs.__doc__)
listcache.add_argument('-f', '--force', action='store_true',
help="force new download of specs")
listcache.add_argument(
'packages', nargs=argparse.REMAINDER,
help="specs of packages to search for")
listcache.set_defaults(func=listspecs)
dlkeys = subparsers.add_parser('keys', help=getkeys.__doc__)
dlkeys.add_argument(
'-i', '--install', action='store_true',
help="install Keys pulled from mirror")
dlkeys.add_argument(
'-t', '--trust', action='store_true',
help="trust all downloaded keys")
dlkeys.add_argument('-f', '--force', action='store_true',
help="force new download of keys")
dlkeys.set_defaults(func=getkeys)
def find_matching_specs(
pkgs, allow_multiple_matches=False, force=False, env=None):
"""Returns a list of specs matching the not necessarily
concretized specs given from cli
Args:
specs: list of specs to be matched against installed packages
allow_multiple_matches : if True multiple matches are admitted
Return:
list of specs
"""
hashes = env.all_hashes() if env else None
# List of specs that match expressions given via command line
specs_from_cli = []
has_errors = False
specs = spack.cmd.parse_specs(pkgs)
for spec in specs:
matching = spack.store.db.query(spec, hashes=hashes)
# For each spec provided, make sure it refers to only one package.
# Fail and ask user to be unambiguous if it doesn't
if not allow_multiple_matches and len(matching) > 1:
tty.error('%s matches multiple installed packages:' % spec)
for match in matching:
tty.msg('"%s"' % match.format())
has_errors = True
# No installed package matches the query
if len(matching) == 0 and spec is not any:
tty.error('{0} does not match any installed packages.'.format(
spec))
has_errors = True
specs_from_cli.extend(matching)
if has_errors:
tty.die('use one of the matching specs above')
return specs_from_cli
def match_downloaded_specs(pkgs, allow_multiple_matches=False, force=False):
"""Returns a list of specs matching the not necessarily
concretized specs given from cli
Args:
specs: list of specs to be matched against buildcaches on mirror
allow_multiple_matches : if True multiple matches are admitted
Return:
list of specs
"""
# List of specs that match expressions given via command line
specs_from_cli = []
has_errors = False
specs = bindist.get_specs(force)
for pkg in pkgs:
matches = []
tty.msg("buildcache spec(s) matching %s \n" % pkg)
for spec in sorted(specs):
if pkg.startswith('/'):
pkghash = pkg.replace('/', '')
if spec.dag_hash().startswith(pkghash):
matches.append(spec)
else:
if spec.satisfies(pkg):
matches.append(spec)
# For each pkg provided, make sure it refers to only one package.
# Fail and ask user to be unambiguous if it doesn't
if not allow_multiple_matches and len(matches) > 1:
tty.error('%s matches multiple downloaded packages:' % pkg)
for match in matches:
tty.msg('"%s"' % match.format())
has_errors = True
# No downloaded package matches the query
if len(matches) == 0:
tty.error('%s does not match any downloaded packages.' % pkg)
has_errors = True
specs_from_cli.extend(matches)
if has_errors:
tty.die('use one of the matching specs above')
return specs_from_cli
def createtarball(args):
"""create a binary package from an existing install"""
if not args.packages:
tty.die("build cache file creation requires at least one" +
" installed package argument")
pkgs = set(args.packages)
specs = set()
outdir = '.'
if args.directory:
outdir = args.directory
signkey = None
if args.key:
signkey = args.key
# restrict matching to current environment if one is active
env = ev.get_env(args, 'buildcache create')
matches = find_matching_specs(pkgs, False, False, env=env)
for match in matches:
if match.external or match.virtual:
tty.msg('skipping external or virtual spec %s' %
match.format())
else:
tty.msg('adding matching spec %s' % match.format())
specs.add(match)
tty.msg('recursing dependencies')
for d, node in match.traverse(order='post',
depth=True,
deptype=('link', 'run')):
if node.external or node.virtual:
tty.msg('skipping external or virtual dependency %s' %
node.format())
else:
tty.msg('adding dependency %s' % node.format())
specs.add(node)
tty.msg('writing tarballs to %s/build_cache' % outdir)
for spec in specs:
tty.msg('creating binary cache file for package %s ' % spec.format())
bindist.build_tarball(spec, outdir, args.force, args.rel,
args.unsigned, args.allow_root, signkey)
def installtarball(args):
"""install from a binary package"""
if not args.packages:
tty.die("build cache file installation requires" +
" at least one package spec argument")
pkgs = set(args.packages)
matches = match_downloaded_specs(pkgs, args.multiple, args.force)
for match in matches:
install_tarball(match, args)
def install_tarball(spec, args):
s = spack.spec.Spec(spec)
if s.external or s.virtual:
tty.warn("Skipping external or virtual package %s" % spec.format())
return
for d in s.dependencies(deptype=('link', 'run')):
tty.msg("Installing buildcache for dependency spec %s" % d)
install_tarball(d, args)
package = spack.repo.get(spec)
if s.concrete and package.installed and not args.force:
tty.warn("Package for spec %s already installed." % spec.format())
else:
tarball = bindist.download_tarball(spec)
if tarball:
tty.msg('Installing buildcache for spec %s' % spec.format())
bindist.extract_tarball(spec, tarball, args.allow_root,
args.unsigned, args.force)
spack.hooks.post_install(spec)
spack.store.store.reindex()
else:
tty.die('Download of binary cache file for spec %s failed.' %
spec.format())
def listspecs(args):
"""list binary packages available from mirrors"""
specs = bindist.get_specs(args.force)
if args.packages:
pkgs = set(args.packages)
for pkg in pkgs:
tty.msg("buildcache spec(s) matching " +
"%s and commands to install them" % pkgs)
for spec in sorted(specs):
if spec.satisfies(pkg):
tty.msg('Enter\nspack buildcache install /%s\n' %
spec.dag_hash(7) +
' to install "%s"' %
spec.format())
else:
tty.msg("buildcache specs and commands to install them")
for spec in sorted(specs):
tty.msg('Enter\nspack buildcache install /%s\n' %
spec.dag_hash(7) +
' to install "%s"' %
spec.format())
def getkeys(args):
"""get public keys available on mirrors"""
bindist.get_keys(args.install, args.trust, args.force)
def buildcache(parser, args):
if args.func:
args.func(args)
|
py | 1a45849f66585604f3d6c1455c692b234b9da5c5 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsLogger.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'Tim Sutton'
__date__ = '20/08/2012'
__copyright__ = 'Copyright 2012, The QGIS Project'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '176c06ceefb5f555205e72b20c962740cc0ec183'
import qgis # NOQA
import tempfile
import os
(myFileHandle, myFilename) = tempfile.mkstemp()
os.environ['QGIS_DEBUG'] = '2'
os.environ['QGIS_LOG_FILE'] = myFilename
from qgis.core import QgsLogger
from qgis.testing import unittest
# Convenience instances in case you may need them
# not used in this test
# from qgis.testing import start_app
# start_app()
class TestQgsLogger(unittest.TestCase):
def testLogger(self):
try:
myFile = os.fdopen(myFileHandle, "w")
myFile.write("QGIS Logger Unit Test\n")
myFile.close()
myLogger = QgsLogger()
myLogger.debug('This is a debug')
myLogger.warning('This is a warning')
myLogger.critical('This is critical')
# myLogger.fatal('Aaaargh...fatal'); #kills QGIS not testable
myFile = open(myFilename, 'rt')
myText = myFile.readlines()
myFile.close()
myExpectedText = ['QGIS Logger Unit Test\n',
'This is a debug\n',
'This is a warning\n',
'This is critical\n']
myMessage = ('Expected:\n---\n%s\n---\nGot:\n---\n%s\n---\n' %
(myExpectedText, myText))
self.assertEqual(myText, myExpectedText, myMessage)
finally:
pass
os.remove(myFilename)
if __name__ == '__main__':
unittest.main()
|
py | 1a4584de28e9ddba2ec47661d12c1191b064f67b | # coding: utf-8
"""Unit tests for sending e-mails."""
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.contrib.auth.models import User
from django.core import mail
from django.core.urlresolvers import clear_url_caches, reverse
from django.test.utils import override_settings
from django.utils import six
from django.utils.datastructures import MultiValueDict
from django.utils.six.moves import range
from djblets.mail.testing import DmarcDnsTestsMixin
from djblets.mail.utils import (build_email_address,
build_email_address_for_user)
from djblets.siteconfig.models import SiteConfiguration
from djblets.testing.decorators import add_fixtures
from kgb import SpyAgency
from reviewboard.accounts.models import ReviewRequestVisit
from reviewboard.admin.server import build_server_url, get_server_url
from reviewboard.admin.siteconfig import load_site_config, settings_map
from reviewboard.diffviewer.models import FileDiff
from reviewboard.notifications.email.message import (
prepare_base_review_request_mail,
logger as messageLogger)
from reviewboard.notifications.email.utils import (
get_email_addresses_for_group,
send_email)
from reviewboard.reviews.models import (Group,
Review,
ReviewRequest,
ReviewRequestDraft)
from reviewboard.scmtools.core import PRE_CREATION
from reviewboard.site.models import LocalSite
from reviewboard.testing import TestCase
from reviewboard.webapi.models import WebAPIToken
_CONSOLE_EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
urlpatterns = [
url(r'^site-root/', include('reviewboard.urls')),
]
class SiteRootURLTestsMixin(object):
"""A mixin for TestCases that helps test URLs generated with site roots.
This mixin provides some settings for unit tests to help ensure that URLs
generated in e-mails are done so correctly and to test that the site root
is only present in those e-mails once.
.. seealso:: `Bug 4612`_
.. _Bug 4612: https://reviews.reviewboard.org/r/9448/bugs/4612/
"""
CUSTOM_SITE_ROOT = '/site-root/'
BAD_SITE_ROOT = '/site-root//site-root/'
CUSTOM_SITE_ROOT_SETTINGS = {
'SITE_ROOT': '/site-root/',
'ROOT_URLCONF': 'reviewboard.notifications.tests.test_email_sending',
}
@classmethod
def setUpClass(cls):
super(SiteRootURLTestsMixin, cls).setUpClass()
clear_url_caches()
def tearDown(self):
super(SiteRootURLTestsMixin, self).tearDown()
clear_url_caches()
class EmailTestHelper(object):
email_siteconfig_settings = {}
def setUp(self):
super(EmailTestHelper, self).setUp()
mail.outbox = []
self.sender = '[email protected]'
self._old_email_settings = {}
if self.email_siteconfig_settings:
siteconfig = SiteConfiguration.objects.get_current()
needs_reload = False
for key, value in six.iteritems(self.email_siteconfig_settings):
old_value = siteconfig.get(key)
if old_value != value:
self._old_email_settings[key] = old_value
siteconfig.set(key, value)
if key in settings_map:
needs_reload = True
if self._old_email_settings:
siteconfig.save()
if needs_reload:
load_site_config()
def tearDown(self):
super(EmailTestHelper, self).tearDown()
if self._old_email_settings:
siteconfig = SiteConfiguration.objects.get_current()
needs_reload = False
for key, value in six.iteritems(self._old_email_settings):
self._old_email_settings[key] = siteconfig.get(key)
siteconfig.set(key, value)
if key in settings_map:
needs_reload = True
siteconfig.save()
if needs_reload:
load_site_config()
def assertValidRecipients(self, user_list, group_list=[]):
recipient_list = mail.outbox[0].to + mail.outbox[0].cc
self.assertEqual(len(recipient_list), len(user_list) + len(group_list))
for user in user_list:
self.assertTrue(build_email_address_for_user(
User.objects.get(username=user)) in recipient_list,
"user %s was not found in the recipient list" % user)
groups = Group.objects.filter(name__in=group_list, local_site=None)
for group in groups:
for address in get_email_addresses_for_group(group):
self.assertTrue(
address in recipient_list,
"group %s was not found in the recipient list" % address)
class UserEmailTestsMixin(EmailTestHelper):
"""A mixin for user-related e-mail tests."""
email_siteconfig_settings = {
'mail_send_new_user_mail': True,
}
def _register(self, username='NewUser', password1='password',
password2='password', email='[email protected]',
first_name='New', last_name='User'):
fields = {
'username': username,
'password1': password1,
'password2': password2,
'email': email,
'first_name': first_name,
'last_name': last_name,
}
register_url = reverse('register')
# We have to first get the register page so that the CSRF cookie is
# set.
self.client.get(register_url)
self.client.post(register_url, fields)
class UserEmailTests(UserEmailTestsMixin, TestCase):
"""User e-mail tests."""
def test_new_user_email(self):
"""Testing sending an e-mail after a new user has successfully
registered
"""
self._register()
siteconfig = SiteConfiguration.objects.get_current()
admin_name = siteconfig.get('site_admin_name')
admin_email_addr = siteconfig.get('site_admin_email')
self.assertEqual(len(mail.outbox), 1)
email = mail.outbox[0]
self.assertEqual(email.subject,
"New Review Board user registration for NewUser")
self.assertEqual(email.from_email, self.sender)
self.assertEqual(email.extra_headers['From'],
settings.DEFAULT_FROM_EMAIL)
self.assertEqual(email.to[0],
build_email_address(full_name=admin_name,
email=admin_email_addr))
class UserEmailSiteRootURLTests(SiteRootURLTestsMixin, UserEmailTestsMixin,
TestCase):
"""Tests for Bug 4612 related to user e-mails.
User account e-mails do not include anything with a Local Site, so there
is no reason to tests the Local Site case.
"""
@override_settings(**SiteRootURLTestsMixin.CUSTOM_SITE_ROOT_SETTINGS)
def test_new_user_email_site_root_custom(self):
"""Testing new user e-mail includes site root in e-mails only once with
custom site root
"""
self._register()
self.assertEqual(len(mail.outbox), 1)
email = mail.outbox[0]
self.assertNotIn(self.BAD_SITE_ROOT, email.body)
for alternative in email.alternatives:
self.assertNotIn(self.BAD_SITE_ROOT, alternative[0])
def test_new_user_email_site_root_default(self):
"""Testing new user e-mail includes site root in e-mails only once with
default site root
"""
self._register()
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertNotIn('example.com//', message.body)
for alternative in message.alternatives:
self.assertNotIn('example.com//', alternative[0])
class ReviewRequestEmailTestsMixin(EmailTestHelper):
"""A mixin for review request-related and review-related e-mail tests."""
fixtures = ['test_users']
email_siteconfig_settings = {
'mail_send_review_mail': True,
'mail_default_from': '[email protected]',
'mail_from_spoofing': 'smart',
}
class ReviewRequestEmailTests(ReviewRequestEmailTestsMixin, DmarcDnsTestsMixin,
SpyAgency, TestCase):
"""Tests for review and review request e-mails."""
def test_new_review_request_email(self):
"""Testing sending an e-mail when creating a new review request"""
review_request = self.create_review_request(
summary='My test review request')
review_request.target_people.add(User.objects.get(username='grumpy'))
review_request.target_people.add(User.objects.get(username='doc'))
review_request.publish(review_request.submitter)
from_email = build_email_address_for_user(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].from_email, self.sender)
self.assertEqual(mail.outbox[0].extra_headers['From'], from_email)
self.assertEqual(mail.outbox[0].subject,
'Review Request %s: My test review request'
% review_request.pk)
self.assertValidRecipients(['grumpy', 'doc'])
message = mail.outbox[0].message()
self.assertEqual(message['Sender'],
self._get_sender(review_request.submitter))
def test_new_review_request_with_from_spoofing_always(self):
"""Testing sending an e-mail when creating a new review request with
mail_from_spoofing=always
"""
self.dmarc_txt_records['_dmarc.example.com'] = 'v=DMARC1; p=reject;'
review_request = self.create_review_request(
summary='My test review request')
review_request.target_people.add(
*User.objects.filter(username__in=('doc', 'grumpy')))
settings = {
'mail_from_spoofing': 'always',
}
with self.siteconfig_settings(settings):
review_request.publish(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].from_email, self.sender)
self.assertEqual(mail.outbox[0].extra_headers['From'],
'Doc Dwarf <[email protected]>')
self.assertEqual(mail.outbox[0].subject,
'Review Request %s: My test review request'
% review_request.pk)
self.assertValidRecipients(['grumpy', 'doc'])
message = mail.outbox[0].message()
self.assertEqual(message['Sender'],
self._get_sender(review_request.submitter))
def test_new_review_request_with_from_spoofing_never(self):
"""Testing sending an e-mail when creating a new review request with
mail_from_spoofing=never
"""
review_request = self.create_review_request(
summary='My test review request')
review_request.target_people.add(
*User.objects.filter(username__in=('doc', 'grumpy')))
settings = {
'mail_from_spoofing': 'never',
}
with self.siteconfig_settings(settings):
review_request.publish(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].from_email, self.sender)
self.assertEqual(mail.outbox[0].extra_headers['From'],
'Doc Dwarf via Review Board <[email protected]>')
self.assertEqual(mail.outbox[0].subject,
'Review Request %s: My test review request'
% review_request.pk)
self.assertValidRecipients(['grumpy', 'doc'])
message = mail.outbox[0].message()
self.assertEqual(message['Sender'],
self._get_sender(review_request.submitter))
def test_new_review_request_email_with_from_spoofing_auto(self):
"""Testing sending an e-mail when creating a new review request with
mail_from_spoofing=auto and allowed by DMARC
"""
self.dmarc_txt_records['_dmarc.example.com'] = 'v=DMARC1; p=none;'
review_request = self.create_review_request(
summary='My test review request')
review_request.target_people.add(
*User.objects.filter(username__in=('doc', 'grumpy')))
review_request.publish(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].from_email, self.sender)
self.assertEqual(mail.outbox[0].extra_headers['From'],
'Doc Dwarf <[email protected]>')
self.assertEqual(mail.outbox[0].subject,
'Review Request %s: My test review request'
% review_request.pk)
self.assertValidRecipients(['grumpy', 'doc'])
message = mail.outbox[0].message()
self.assertEqual(message['Sender'],
self._get_sender(review_request.submitter))
def test_new_review_request_email_with_from_spoofing_auto_dmarc_deny(self):
"""Testing sending an e-mail when creating a new review request with
mail_from_spoofing=auto and denied by DMARC
"""
self.dmarc_txt_records['_dmarc.example.com'] = 'v=DMARC1; p=reject;'
review_request = self.create_review_request(
summary='My test review request')
review_request.target_people.add(
*User.objects.filter(username__in=('doc', 'grumpy')))
review_request.publish(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].from_email, self.sender)
self.assertEqual(mail.outbox[0].extra_headers['From'],
'Doc Dwarf via Review Board <[email protected]>')
self.assertEqual(mail.outbox[0].subject,
'Review Request %s: My test review request'
% review_request.pk)
self.assertValidRecipients(['grumpy', 'doc'])
message = mail.outbox[0].message()
self.assertEqual(message['Sender'],
self._get_sender(review_request.submitter))
def test_review_request_email_local_site_group(self):
"""Testing sending email when a group member is part of a Local Site"""
# This was bug 3581.
local_site = LocalSite.objects.create(name=self.local_site_name)
group = self.create_review_group()
user = User.objects.get(username='grumpy')
local_site.users.add(user)
local_site.admins.add(user)
local_site.save()
group.users.add(user)
group.save()
review_request = self.create_review_request()
review_request.target_groups.add(group)
review_request.publish(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
self.assertValidRecipients(['doc', 'grumpy'])
def test_review_email(self):
"""Testing sending an e-mail when replying to a review request"""
review_request = self.create_review_request(
summary='My test review request')
review_request.target_people.add(User.objects.get(username='grumpy'))
review_request.target_people.add(User.objects.get(username='doc'))
review_request.publish(review_request.submitter)
# Clear the outbox.
mail.outbox = []
review = self.create_review(review_request=review_request)
review.publish()
from_email = build_email_address_for_user(review.user)
self.assertEqual(len(mail.outbox), 1)
email = mail.outbox[0]
self.assertEqual(email.from_email, self.sender)
self.assertEqual(email.extra_headers['From'], from_email)
self.assertEqual(email._headers['X-ReviewBoard-URL'],
'http://example.com/')
self.assertEqual(email._headers['X-ReviewRequest-URL'],
'http://example.com/r/%s/'
% review_request.display_id)
self.assertEqual(email.subject,
'Re: Review Request %s: My test review request'
% review_request.display_id)
self.assertValidRecipients([
review_request.submitter.username,
'grumpy',
'doc',
])
message = email.message()
self.assertEqual(message['Sender'], self._get_sender(review.user))
def test_review_email_with_from_spoofing_always(self):
"""Testing sending an e-mail when replying to a review request with
mail_from_spoofing=always
"""
self.dmarc_txt_records['_dmarc.example.com'] = 'v=DMARC1; p=reject;'
review_request = self.create_review_request(
summary='My test review request')
review_request.target_people.add(
*User.objects.filter(username__in=('doc', 'grumpy')))
review_request.publish(review_request.submitter)
review = self.create_review(review_request=review_request)
# Clear the outbox.
mail.outbox = []
settings = {
'mail_from_spoofing': 'always',
}
with self.siteconfig_settings(settings):
review.publish()
self.assertEqual(len(mail.outbox), 1)
email = mail.outbox[0]
self.assertEqual(email.from_email, self.sender)
self.assertEqual(email.extra_headers['From'],
'Dopey Dwarf <[email protected]>')
self.assertEqual(email._headers['X-ReviewBoard-URL'],
'http://example.com/')
self.assertEqual(email._headers['X-ReviewRequest-URL'],
'http://example.com/r/%s/'
% review_request.display_id)
self.assertEqual(email.subject,
'Re: Review Request %s: My test review request'
% review_request.display_id)
self.assertValidRecipients([
review_request.submitter.username,
'grumpy',
'doc',
])
message = email.message()
self.assertEqual(message['Sender'], self._get_sender(review.user))
def test_review_email_with_from_spoofing_never(self):
"""Testing sending an e-mail when replying to a review request with
mail_from_spoofing=never
"""
review_request = self.create_review_request(
summary='My test review request')
review_request.target_people.add(
*User.objects.filter(username__in=('doc', 'grumpy')))
review_request.publish(review_request.submitter)
review = self.create_review(review_request=review_request)
# Clear the outbox.
mail.outbox = []
settings = {
'mail_from_spoofing': 'never',
}
with self.siteconfig_settings(settings):
review.publish()
self.assertEqual(len(mail.outbox), 1)
email = mail.outbox[0]
self.assertEqual(email.from_email, self.sender)
self.assertEqual(email.extra_headers['From'],
'Dopey Dwarf via Review Board <[email protected]>')
self.assertEqual(email._headers['X-ReviewBoard-URL'],
'http://example.com/')
self.assertEqual(email._headers['X-ReviewRequest-URL'],
'http://example.com/r/%s/'
% review_request.display_id)
self.assertEqual(email.subject,
'Re: Review Request %s: My test review request'
% review_request.display_id)
self.assertValidRecipients([
review_request.submitter.username,
'grumpy',
'doc',
])
message = email.message()
self.assertEqual(message['Sender'], self._get_sender(review.user))
def test_review_email_with_from_spoofing_auto(self):
"""Testing sending an e-mail when replying to a review request with
mail_from_spoofing=auto and allowed by DMARC
"""
self.dmarc_txt_records['_dmarc.example.com'] = 'v=DMARC1; p=none;'
review_request = self.create_review_request(
summary='My test review request')
review_request.target_people.add(
*User.objects.filter(username__in=('doc', 'grumpy')))
review_request.publish(review_request.submitter)
# Clear the outbox.
mail.outbox = []
review = self.create_review(review_request=review_request)
review.publish()
self.assertEqual(len(mail.outbox), 1)
email = mail.outbox[0]
self.assertEqual(email.from_email, self.sender)
self.assertEqual(email.extra_headers['From'],
'Dopey Dwarf <[email protected]>')
self.assertEqual(email._headers['X-ReviewBoard-URL'],
'http://example.com/')
self.assertEqual(email._headers['X-ReviewRequest-URL'],
'http://example.com/r/%s/'
% review_request.display_id)
self.assertEqual(email.subject,
'Re: Review Request %s: My test review request'
% review_request.display_id)
self.assertValidRecipients([
review_request.submitter.username,
'grumpy',
'doc',
])
message = email.message()
self.assertEqual(message['Sender'], self._get_sender(review.user))
def test_review_email_with_from_spoofing_auto_dmarc_deny(self):
"""Testing sending an e-mail when replying to a review request with
mail_from_spoofing=auto and denied by DMARC
"""
self.dmarc_txt_records['_dmarc.example.com'] = 'v=DMARC1; p=reject;'
review_request = self.create_review_request(
summary='My test review request')
review_request.target_people.add(
*User.objects.filter(username__in=('doc', 'grumpy')))
review_request.publish(review_request.submitter)
# Clear the outbox.
mail.outbox = []
review = self.create_review(review_request=review_request)
review.publish()
self.assertEqual(len(mail.outbox), 1)
email = mail.outbox[0]
self.assertEqual(email.from_email, self.sender)
self.assertEqual(email.extra_headers['From'],
'Dopey Dwarf via Review Board <[email protected]>')
self.assertEqual(email._headers['X-ReviewBoard-URL'],
'http://example.com/')
self.assertEqual(email._headers['X-ReviewRequest-URL'],
'http://example.com/r/%s/'
% review_request.display_id)
self.assertEqual(email.subject,
'Re: Review Request %s: My test review request'
% review_request.display_id)
self.assertValidRecipients([
review_request.submitter.username,
'grumpy',
'doc',
])
message = email.message()
self.assertEqual(message['Sender'], self._get_sender(review.user))
@add_fixtures(['test_site'])
def test_review_email_with_site(self):
"""Testing sending an e-mail when replying to a review request
on a Local Site
"""
review_request = self.create_review_request(
summary='My test review request',
with_local_site=True)
review_request.target_people.add(User.objects.get(username='grumpy'))
review_request.target_people.add(User.objects.get(username='doc'))
review_request.publish(review_request.submitter)
# Ensure all the reviewers are on the site.
site = review_request.local_site
site.users.add(*list(review_request.target_people.all()))
# Clear the outbox.
mail.outbox = []
review = self.create_review(review_request=review_request)
review.publish()
from_email = build_email_address_for_user(review.user)
self.assertEqual(len(mail.outbox), 1)
email = mail.outbox[0]
self.assertEqual(email.from_email, self.sender)
self.assertEqual(email.extra_headers['From'], from_email)
self.assertEqual(email._headers['X-ReviewBoard-URL'],
'http://example.com/s/local-site-1/')
self.assertEqual(email._headers['X-ReviewRequest-URL'],
'http://example.com/s/local-site-1/r/%s/'
% review_request.display_id)
self.assertEqual(email.subject,
'Re: Review Request %s: My test review request'
% review_request.display_id)
self.assertValidRecipients([
review_request.submitter.username,
'grumpy',
'doc',
])
message = email.message()
self.assertEqual(message['Sender'], self._get_sender(review.user))
def test_profile_should_send_email_setting(self):
"""Testing the Profile.should_send_email setting"""
grumpy = User.objects.get(username='grumpy')
profile = grumpy.get_profile()
profile.should_send_email = False
profile.save(update_fields=('should_send_email',))
review_request = self.create_review_request(
summary='My test review request')
review_request.target_people.add(grumpy)
review_request.target_people.add(User.objects.get(username='doc'))
review_request.publish(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
self.assertValidRecipients(['doc'])
def test_review_request_closed_no_email(self):
"""Tests e-mail is not generated when a review request is closed and
e-mail setting is False
"""
review_request = self.create_review_request()
review_request.publish(review_request.submitter)
# Clear the outbox.
mail.outbox = []
review_request.close(ReviewRequest.SUBMITTED, review_request.submitter)
# Verify that no email is generated as option is false by default
self.assertEqual(len(mail.outbox), 0)
def test_review_request_closed_with_email(self):
"""Tests e-mail is generated when a review request is closed and
e-mail setting is True
"""
with self.siteconfig_settings({'mail_send_review_close_mail': True},
reload_settings=False):
review_request = self.create_review_request()
review_request.publish(review_request.submitter)
# Clear the outbox.
mail.outbox = []
review_request.close(ReviewRequest.SUBMITTED,
review_request.submitter)
from_email = build_email_address_for_user(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].from_email, self.sender)
self.assertEqual(mail.outbox[0].extra_headers['From'], from_email)
message = mail.outbox[0].message()
self.assertTrue('This change has been marked as submitted'
in message.as_string())
def test_review_request_close_with_email_and_dmarc_deny(self):
"""Tests e-mail is generated when a review request is closed and
e-mail setting is True and From spoofing blocked by DMARC
"""
self.dmarc_txt_records['_dmarc.example.com'] = 'v=DMARC1; p=reject;'
with self.siteconfig_settings({'mail_send_review_close_mail': True},
reload_settings=False):
review_request = self.create_review_request()
review_request.publish(review_request.submitter)
# Clear the outbox.
mail.outbox = []
review_request.close(ReviewRequest.SUBMITTED,
review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].from_email, self.sender)
self.assertEqual(mail.outbox[0].extra_headers['From'],
'Doc Dwarf via Review Board '
'<[email protected]>')
message = mail.outbox[0].message()
self.assertTrue('This change has been marked as submitted'
in message.as_string())
def test_review_to_owner_only(self):
"""Test that e-mails from reviews published to the submitter only will
only go to the submitter and the reviewer
"""
review_request = self.create_review_request(public=True, publish=False)
review_request.target_people.add(User.objects.get(username='grumpy'))
review = self.create_review(review_request=review_request,
publish=False)
with self.siteconfig_settings({'mail_send_review_mail': True},
reload_settings=False):
review.publish(to_owner_only=True)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertEqual(message.cc, [])
self.assertEqual(len(message.to), 2)
self.assertEqual(
set(message.to),
set([build_email_address_for_user(review.user),
build_email_address_for_user(review_request.submitter)]))
def test_review_reply_email(self):
"""Testing sending an e-mail when replying to a review"""
review_request = self.create_review_request(
summary='My test review request')
review_request.publish(review_request.submitter)
base_review = self.create_review(review_request=review_request)
base_review.publish()
# Clear the outbox.
mail.outbox = []
reply = self.create_reply(base_review)
reply.publish()
from_email = build_email_address_for_user(reply.user)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].from_email, self.sender)
self.assertEqual(mail.outbox[0].extra_headers['From'], from_email)
self.assertEqual(mail.outbox[0].subject,
'Re: Review Request %s: My test review request'
% review_request.pk)
self.assertValidRecipients([
review_request.submitter.username,
base_review.user.username,
reply.user.username,
])
message = mail.outbox[0].message()
self.assertEqual(message['Sender'], self._get_sender(reply.user))
def test_review_reply_email_with_dmarc_deny(self):
"""Testing sending an e-mail when replying to a review with From
spoofing blocked by DMARC
"""
self.dmarc_txt_records['_dmarc.example.com'] = 'v=DMARC1; p=reject;'
review_request = self.create_review_request(
summary='My test review request')
review_request.publish(review_request.submitter)
base_review = self.create_review(review_request=review_request)
base_review.publish()
# Clear the outbox.
mail.outbox = []
reply = self.create_reply(base_review)
reply.publish()
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].from_email, self.sender)
self.assertEqual(mail.outbox[0].extra_headers['From'],
'Grumpy Dwarf via Review Board <[email protected]>')
self.assertEqual(mail.outbox[0].subject,
'Re: Review Request %s: My test review request'
% review_request.pk)
self.assertValidRecipients([
review_request.submitter.username,
base_review.user.username,
reply.user.username,
])
message = mail.outbox[0].message()
self.assertEqual(message['Sender'], self._get_sender(reply.user))
def test_update_review_request_email(self):
"""Testing sending an e-mail when updating a review request"""
group = Group.objects.create(name='devgroup',
mailing_list='[email protected]')
review_request = self.create_review_request(
summary='My test review request')
review_request.target_groups.add(group)
review_request.email_message_id = "junk"
review_request.publish(review_request.submitter)
from_email = build_email_address_for_user(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].from_email, self.sender)
self.assertEqual(mail.outbox[0].extra_headers['From'], from_email)
self.assertEqual(mail.outbox[0].subject,
'Re: Review Request %s: My test review request'
% review_request.pk)
self.assertValidRecipients([review_request.submitter.username],
['devgroup'])
message = mail.outbox[0].message()
self.assertEqual(message['Sender'],
self._get_sender(review_request.submitter))
def test_update_review_request_email_with_dmarc_deny(self):
"""Testing sending an e-mail when updating a review request with
From spoofing blocked by DMARC
"""
self.dmarc_txt_records['_dmarc.example.com'] = 'v=DMARC1; p=reject;'
group = Group.objects.create(name='devgroup',
mailing_list='[email protected]')
review_request = self.create_review_request(
summary='My test review request')
review_request.target_groups.add(group)
review_request.email_message_id = "junk"
review_request.publish(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].from_email, self.sender)
self.assertEqual(mail.outbox[0].extra_headers['From'],
'Doc Dwarf via Review Board <[email protected]>')
self.assertEqual(mail.outbox[0].subject,
'Re: Review Request %s: My test review request'
% review_request.pk)
self.assertValidRecipients([review_request.submitter.username],
['devgroup'])
message = mail.outbox[0].message()
self.assertEqual(message['Sender'],
self._get_sender(review_request.submitter))
def test_add_reviewer_review_request_email(self):
"""Testing limited e-mail recipients
when adding a reviewer to an existing review request
"""
review_request = self.create_review_request(
summary='My test review request',
public=True)
review_request.email_message_id = "junk"
review_request.target_people.add(User.objects.get(username='dopey'))
review_request.save()
draft = ReviewRequestDraft.create(review_request)
draft.target_people.add(User.objects.get(username='grumpy'))
draft.publish(user=review_request.submitter)
from_email = build_email_address_for_user(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].from_email, self.sender)
self.assertEqual(mail.outbox[0].extra_headers['From'], from_email)
self.assertEqual(mail.outbox[0].subject,
'Re: Review Request %s: My test review request'
% review_request.pk)
# The only included users should be the submitter and 'grumpy' (not
# 'dopey', since he was already included on the review request earlier)
self.assertValidRecipients([review_request.submitter.username,
'grumpy'])
message = mail.outbox[0].message()
self.assertEqual(message['Sender'],
self._get_sender(review_request.submitter))
def test_add_group_review_request_email(self):
"""Testing limited e-mail recipients
when adding a group to an existing review request
"""
existing_group = Group.objects.create(
name='existing', mailing_list='[email protected]')
review_request = self.create_review_request(
summary='My test review request',
public=True)
review_request.email_message_id = "junk"
review_request.target_groups.add(existing_group)
review_request.target_people.add(User.objects.get(username='dopey'))
review_request.save()
new_group = Group.objects.create(name='devgroup',
mailing_list='[email protected]')
draft = ReviewRequestDraft.create(review_request)
draft.target_groups.add(new_group)
draft.publish(user=review_request.submitter)
from_email = build_email_address_for_user(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].from_email, self.sender)
self.assertEqual(mail.outbox[0].extra_headers['From'], from_email)
self.assertEqual(mail.outbox[0].subject,
'Re: Review Request %s: My test review request'
% review_request.pk)
# The only included users should be the submitter and 'devgroup' (not
# 'dopey' or 'existing', since they were already included on the
# review request earlier)
self.assertValidRecipients([review_request.submitter.username],
['devgroup'])
message = mail.outbox[0].message()
self.assertEqual(message['Sender'],
self._get_sender(review_request.submitter))
def test_limited_recipients_other_fields(self):
"""Testing that recipient limiting only happens when adding reviewers
"""
review_request = self.create_review_request(
summary='My test review request',
public=True)
review_request.email_message_id = "junk"
review_request.target_people.add(User.objects.get(username='dopey'))
review_request.save()
draft = ReviewRequestDraft.create(review_request)
draft.summary = 'Changed summary'
draft.target_people.add(User.objects.get(username='grumpy'))
draft.publish(user=review_request.submitter)
from_email = build_email_address_for_user(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].from_email, self.sender)
self.assertEqual(mail.outbox[0].extra_headers['From'], from_email)
self.assertEqual(mail.outbox[0].subject,
'Re: Review Request %s: Changed summary'
% review_request.pk)
self.assertValidRecipients([review_request.submitter.username,
'dopey', 'grumpy'])
message = mail.outbox[0].message()
self.assertEqual(message['Sender'],
self._get_sender(review_request.submitter))
def test_recipients_with_muted_review_requests(self):
"""Testing e-mail recipients when users mute a review request"""
dopey = User.objects.get(username='dopey')
admin = User.objects.get(username='admin')
group = Group.objects.create(name='group')
group.users.add(admin)
group.save()
review_request = self.create_review_request(
summary='My test review request',
public=True)
review_request.target_people.add(dopey)
review_request.target_people.add(User.objects.get(username='grumpy'))
review_request.target_groups.add(group)
review_request.save()
visit = self.create_visit(review_request, ReviewRequestVisit.MUTED,
dopey)
visit.save()
visit = self.create_visit(review_request, ReviewRequestVisit.MUTED,
admin)
visit.save()
draft = ReviewRequestDraft.create(review_request)
draft.summary = 'Summary changed'
draft.publish(user=review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
self.assertValidRecipients(['doc', 'grumpy'])
def test_group_member_not_receive_email(self):
"""Testing sending review e-mails and filtering out the review
submitter when they are part of a review group assigned to the request
"""
# See issue 3985.
submitter = User.objects.get(username='doc')
profile = submitter.get_profile()
profile.should_send_own_updates = False
profile.save(update_fields=('should_send_own_updates',))
reviewer = User.objects.get(username='dopey')
group = self.create_review_group()
group.users.add(submitter)
review_request = self.create_review_request(public=True)
review_request.target_groups.add(group)
review_request.target_people.add(reviewer)
review_request.save()
review = self.create_review(review_request, user=submitter)
review.publish()
self.assertEqual(len(mail.outbox), 1)
msg = mail.outbox[0]
self.assertListEqual(
msg.to,
[build_email_address_for_user(reviewer)])
self.assertListEqual(msg.cc, [])
def test_local_site_user_filters(self):
"""Testing sending e-mails and filtering out users not on a local site
"""
test_site = LocalSite.objects.create(name=self.local_site_name)
site_user1 = User.objects.create_user(username='site_user1',
email='[email protected]')
site_user2 = User.objects.create_user(username='site_user2',
email='[email protected]')
site_user3 = User.objects.create_user(username='site_user3',
email='[email protected]')
site_user4 = User.objects.create_user(username='site_user4',
email='[email protected]')
site_user5 = User.objects.create_user(username='site_user5',
email='[email protected]')
non_site_user1 = User.objects.create_user(
username='non_site_user1',
email='[email protected]')
non_site_user2 = User.objects.create_user(
username='non_site_user2',
email='[email protected]')
non_site_user3 = User.objects.create_user(
username='non_site_user3',
email='[email protected]')
test_site.admins.add(site_user1)
test_site.users.add(site_user2)
test_site.users.add(site_user3)
test_site.users.add(site_user4)
test_site.users.add(site_user5)
group = Group.objects.create(name='my-group',
display_name='My Group',
local_site=test_site)
group.users.add(site_user5)
group.users.add(non_site_user3)
review_request = self.create_review_request(with_local_site=True,
local_id=123)
review_request.email_message_id = "junk"
review_request.target_people = [site_user1, site_user2, site_user3,
non_site_user1]
review_request.target_groups = [group]
review = Review.objects.create(review_request=review_request,
user=site_user4)
review.publish()
review = Review.objects.create(review_request=review_request,
user=non_site_user2)
review.publish()
from_email = build_email_address_for_user(review_request.submitter)
# Now that we're set up, send another e-mail.
mail.outbox = []
review_request.publish(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].from_email, self.sender)
self.assertEqual(mail.outbox[0].extra_headers['From'], from_email)
self.assertValidRecipients(
['site_user1', 'site_user2', 'site_user3', 'site_user4',
'site_user5', review_request.submitter.username], [])
message = mail.outbox[0].message()
self.assertEqual(message['Sender'],
self._get_sender(review_request.submitter))
def test_review_request_email_with_unicode_from(self):
"""Testing sending a review request e-mail with a Unicode From"""
self.spy_on(messageLogger.exception)
review_request = self.create_review_request()
owner = review_request.owner
owner.first_name = 'Tést'
owner.last_name = 'Üser'
owner.save(update_fields=('first_name', 'last_name'))
review_request.publish(review_request.submitter)
self.assertIsNotNone(review_request.email_message_id)
self.assertFalse(messageLogger.exception.spy.called)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0].message()
self.assertEqual(message['Sender'],
'=?utf-8?b?VMOpc3Qgw5xzZXI=?= <[email protected]>')
self.assertEqual(message['From'],
'=?utf-8?b?VMOpc3Qgw5xzZXI=?= <[email protected]>')
self.assertEqual(
message['X-Sender'],
'=?utf-8?b?VMOpc3Qgw5xzZXIgPG5vcmVwbHlAZXhhbXBsZS5jb20+?=')
# Make sure this doesn't crash.
message.as_bytes()
def test_review_request_email_with_unicode_summary(self):
"""Testing sending a review request e-mail with a Unicode subject"""
self.spy_on(messageLogger.exception)
review_request = self.create_review_request()
review_request.summary = '\U0001f600'
review_request.publish(review_request.submitter)
self.assertIsNotNone(review_request.email_message_id)
self.assertFalse(messageLogger.exception.spy.called)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0].message()
self.assertEqual(message['Subject'],
'=?utf-8?q?Review_Request_1=3A_=F0=9F=98=80?=')
# Make sure this doesn't crash.
message.as_bytes()
def test_review_request_email_with_unicode_description(self):
"""Testing sending a review request e-mail with a Unicode
description
"""
self.spy_on(messageLogger.exception)
review_request = self.create_review_request()
review_request.summary = '\U0001f600'
review_request.description = '\U0001f600'
owner = review_request.owner
owner.first_name = 'Tést'
owner.last_name = 'Üser'
owner.save(update_fields=('first_name', 'last_name'))
review_request.publish(review_request.submitter)
self.assertIsNotNone(review_request.email_message_id)
self.assertFalse(messageLogger.exception.spy.called)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0].message()
self.assertIn('\U0001f600'.encode('utf-8'), message.as_bytes())
# Make sure this doesn't crash.
message.as_bytes()
@add_fixtures(['test_scmtools'])
def test_review_request_email_with_added_file(self):
"""Testing sending a review request e-mail with added files in the
diffset
"""
repository = self.create_repository(tool_name='Test')
review_request = self.create_review_request(repository=repository)
diffset = self.create_diffset(review_request=review_request)
filediff = self.create_filediff(diffset=diffset,
source_file='/dev/null',
source_revision=PRE_CREATION)
review_request.publish(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertTrue('X-ReviewBoard-Diff-For' in message._headers)
diff_headers = message._headers.getlist('X-ReviewBoard-Diff-For')
self.assertEqual(len(diff_headers), 1)
self.assertFalse(filediff.source_file in diff_headers)
self.assertTrue(filediff.dest_file in diff_headers)
@add_fixtures(['test_scmtools'])
def test_review_request_email_with_added_files_over_header_limit(self):
"""Testing sending a review request e-mail with added files in the
diffset such that the filename headers take up more than 8192
characters
"""
self.spy_on(messageLogger.warning)
self.maxDiff = None
repository = self.create_repository(tool_name='Test')
review_request = self.create_review_request(repository=repository)
diffset = self.create_diffset(review_request=review_request)
prefix = 'X' * 97
filediffs = []
# Each filename is 100 characters long. For each header we add 26
# characters: the key, a ': ', and the terminating '\r\n'.
# 8192 / (100 + 26) rounds down to 65. We'll bump it up to 70 just
# to be careful.
for i in range(70):
filename = '%s%#03d' % (prefix, i)
self.assertEqual(len(filename), 100)
filediffs.append(self.create_filediff(
diffset=diffset,
source_file=filename,
dest_file=filename,
source_revision=PRE_CREATION,
diff=b'',
save=False))
FileDiff.objects.bulk_create(filediffs)
review_request.publish(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertIn('X-ReviewBoard-Diff-For', message._headers)
diff_headers = message._headers.getlist('X-ReviewBoard-Diff-For')
self.assertEqual(len(messageLogger.warning.spy.calls), 1)
self.assertEqual(len(diff_headers), 65)
self.assertEqual(
messageLogger.warning.spy.calls[0].args,
('Unable to store all filenames in the X-ReviewBoard-Diff-For '
'headers when sending e-mail for review request %s: The header '
'size exceeds the limit of %s. Remaining headers have been '
'omitted.',
1,
8192))
@add_fixtures(['test_scmtools'])
def test_review_request_email_with_deleted_file(self):
"""Testing sending a review request e-mail with deleted files in the
diffset
"""
repository = self.create_repository(tool_name='Test')
review_request = self.create_review_request(repository=repository)
diffset = self.create_diffset(review_request=review_request)
filediff = self.create_filediff(diffset=diffset,
dest_file='/dev/null',
status=FileDiff.DELETED)
review_request.publish(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertTrue('X-ReviewBoard-Diff-For' in message._headers)
diff_headers = message._headers.getlist('X-ReviewBoard-Diff-For')
self.assertEqual(len(diff_headers), 1)
self.assertTrue(filediff.source_file in diff_headers)
self.assertFalse(filediff.dest_file in diff_headers)
@add_fixtures(['test_scmtools'])
def test_review_request_email_with_moved_file(self):
"""Testing sending a review request e-mail with moved files in the
diffset
"""
repository = self.create_repository(tool_name='Test')
review_request = self.create_review_request(repository=repository)
diffset = self.create_diffset(review_request=review_request)
filediff = self.create_filediff(diffset=diffset,
source_file='foo',
dest_file='bar',
status=FileDiff.MOVED)
review_request.publish(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertTrue('X-ReviewBoard-Diff-For' in message._headers)
diff_headers = message._headers.getlist('X-ReviewBoard-Diff-For')
self.assertEqual(len(diff_headers), 2)
self.assertTrue(filediff.source_file in diff_headers)
self.assertTrue(filediff.dest_file in diff_headers)
@add_fixtures(['test_scmtools'])
def test_review_request_email_with_copied_file(self):
"""Testing sending a review request e-mail with copied files in the
diffset
"""
repository = self.create_repository(tool_name='Test')
review_request = self.create_review_request(repository=repository)
diffset = self.create_diffset(review_request=review_request)
filediff = self.create_filediff(diffset=diffset,
source_file='foo',
dest_file='bar',
status=FileDiff.COPIED)
review_request.publish(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertTrue('X-ReviewBoard-Diff-For' in message._headers)
diff_headers = message._headers.getlist('X-ReviewBoard-Diff-For')
self.assertEqual(len(diff_headers), 2)
self.assertTrue(filediff.source_file in diff_headers)
self.assertTrue(filediff.dest_file in diff_headers)
@add_fixtures(['test_scmtools'])
def test_review_request_email_with_modified_file(self):
"""Testing sending a review request e-mail with modified files in
the diffset
"""
# Bug #4572 reported that the 'X-ReviewBoard-Diff-For' header appeared
# only for newly created files and moved files. This test is to check
# that the header appears for modified files as well.
repository = self.create_repository(tool_name='Test')
review_request = self.create_review_request(repository=repository)
diffset = self.create_diffset(review_request=review_request)
filediff = self.create_filediff(diffset=diffset,
source_file='foo',
dest_file='bar',
status=FileDiff.MODIFIED)
review_request.publish(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertIn('X-ReviewBoard-Diff-For', message._headers)
diff_headers = message._headers.getlist('X-ReviewBoard-Diff-For')
self.assertEqual(len(diff_headers), 2)
self.assertIn(filediff.source_file, diff_headers)
self.assertIn(filediff.dest_file, diff_headers)
@add_fixtures(['test_scmtools'])
def test_review_request_email_with_multiple_files(self):
"""Testing sending a review request e-mail with multiple files in the
diffset
"""
repository = self.create_repository(tool_name='Test')
review_request = self.create_review_request(repository=repository)
diffset = self.create_diffset(review_request=review_request)
filediffs = [
self.create_filediff(diffset=diffset,
source_file='foo',
dest_file='bar',
status=FileDiff.MOVED),
self.create_filediff(diffset=diffset,
source_file='baz',
dest_file='/dev/null',
status=FileDiff.DELETED)
]
review_request.publish(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertTrue('X-ReviewBoard-Diff-For' in message._headers)
diff_headers = message._headers.getlist('X-ReviewBoard-Diff-For')
self.assertEqual(
set(diff_headers),
{
filediffs[0].source_file,
filediffs[0].dest_file,
filediffs[1].source_file,
})
def test_extra_headers_dict(self):
"""Testing sending extra headers as a dict with an e-mail message"""
review_request = self.create_review_request()
submitter = review_request.submitter
send_email(prepare_base_review_request_mail,
user=submitter,
review_request=review_request,
subject='Foo',
in_reply_to=None,
to_field=[submitter],
cc_field=[],
template_name_base='notifications/review_request_email',
extra_headers={'X-Foo': 'Bar'})
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertIn('X-Foo', message._headers)
self.assertEqual(message._headers['X-Foo'], 'Bar')
def test_extra_headers_multivalue_dict(self):
"""Testing sending extra headers as a MultiValueDict with an e-mail
message
"""
header_values = ['Bar', 'Baz']
review_request = self.create_review_request()
submitter = review_request.submitter
send_email(prepare_base_review_request_mail,
user=review_request.submitter,
review_request=review_request,
subject='Foo',
in_reply_to=None,
to_field=[submitter],
cc_field=[],
template_name_base='notifications/review_request_email',
extra_headers=MultiValueDict({'X-Foo': header_values}))
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertIn('X-Foo', message._headers)
self.assertEqual(set(message._headers.getlist('X-Foo')),
set(header_values))
def test_review_no_shipit_headers(self):
"""Testing sending a review e-mail without a 'Ship It!'"""
review_request = self.create_review_request(public=True)
self.create_review(review_request,
body_top=Review.SHIP_IT_TEXT,
body_bottom='',
publish=True)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertNotIn('X-ReviewBoard-ShipIt', message._headers)
self.assertNotIn('X-ReviewBoard-ShipIt-Only', message._headers)
self.assertFalse(Review.FIX_IT_THEN_SHIP_IT_TEXT in
message.message().as_string())
def test_review_shipit_only_headers(self):
"""Testing sending a review e-mail with only a 'Ship It!'"""
review_request = self.create_review_request(public=True)
self.create_review(review_request,
body_top=Review.SHIP_IT_TEXT,
body_bottom='',
ship_it=True,
publish=True)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertIn('X-ReviewBoard-ShipIt', message._headers)
self.assertIn('X-ReviewBoard-ShipIt-Only', message._headers)
self.assertFalse(Review.FIX_IT_THEN_SHIP_IT_TEXT in
message.message().as_string())
def test_review_shipit_only_headers_no_text(self):
"""Testing sending a review e-mail with only a 'Ship It!' and no text
"""
review_request = self.create_review_request(public=True)
self.create_review(review_request,
body_top='',
body_bottom='',
ship_it=True,
publish=True)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertIn('X-ReviewBoard-ShipIt', message._headers)
self.assertIn('X-ReviewBoard-ShipIt-Only', message._headers)
self.assertFalse(Review.FIX_IT_THEN_SHIP_IT_TEXT in
message.message().as_string())
def test_review_shipit_headers_custom_top_text(self):
"""Testing sending a review e-mail with a 'Ship It' and custom top text
"""
review_request = self.create_review_request(public=True)
self.create_review(review_request,
body_top='Some general information.',
body_bottom='',
ship_it=True,
publish=True)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertIn('X-ReviewBoard-ShipIt', message._headers)
self.assertNotIn('X-ReviewBoard-ShipIt-Only', message._headers)
self.assertFalse(Review.FIX_IT_THEN_SHIP_IT_TEXT in
message.message().as_string())
def test_review_shipit_headers_bottom_text(self):
"""Testing sending a review e-mail with a 'Ship It' and bottom text"""
review_request = self.create_review_request(public=True)
self.create_review(review_request,
body_top=Review.SHIP_IT_TEXT,
body_bottom='Some comments',
ship_it=True,
publish=True)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertIn('X-ReviewBoard-ShipIt', message._headers)
self.assertNotIn('X-ReviewBoard-ShipIt-Only', message._headers)
self.assertFalse(Review.FIX_IT_THEN_SHIP_IT_TEXT in
message.message().as_string())
@add_fixtures(['test_scmtools'])
def test_review_shipit_headers_comments(self):
"""Testing sending a review e-mail with a 'Ship It' and diff comments
"""
repository = self.create_repository(tool_name='Test')
review_request = self.create_review_request(repository=repository,
public=True)
diffset = self.create_diffset(review_request)
filediff = self.create_filediff(diffset)
review = self.create_review(review_request,
body_top=Review.SHIP_IT_TEXT,
body_bottom='',
ship_it=True,
publish=False)
self.create_diff_comment(review, filediff)
review.publish()
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertIn('X-ReviewBoard-ShipIt', message._headers)
self.assertNotIn('X-ReviewBoard-ShipIt-Only', message._headers)
self.assertFalse(Review.FIX_IT_THEN_SHIP_IT_TEXT in
message.message().as_string())
@add_fixtures(['test_scmtools'])
def test_review_shipit_headers_comments_opened_issue(self):
"""Testing sending a review e-mail with a 'Ship It' and diff comments
with opened issue
"""
repository = self.create_repository(tool_name='Test')
review_request = self.create_review_request(repository=repository,
public=True)
diffset = self.create_diffset(review_request)
filediff = self.create_filediff(diffset)
review = self.create_review(review_request,
body_top=Review.SHIP_IT_TEXT,
body_bottom='',
ship_it=True,
publish=False)
self.create_diff_comment(review, filediff, issue_opened=True)
review.publish()
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertIn('X-ReviewBoard-ShipIt', message._headers)
self.assertNotIn('X-ReviewBoard-ShipIt-Only', message._headers)
self.assertTrue(Review.FIX_IT_THEN_SHIP_IT_TEXT in
message.message().as_string())
def test_review_shipit_headers_attachment_comments(self):
"""Testing sending a review e-mail with a 'Ship It' and file attachment
comments
"""
review_request = self.create_review_request(public=True)
file_attachment = self.create_file_attachment(review_request)
review = self.create_review(review_request,
body_top=Review.SHIP_IT_TEXT,
body_bottom='',
ship_it=True,
publish=False)
self.create_file_attachment_comment(review, file_attachment)
review.publish()
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertIn('X-ReviewBoard-ShipIt', message._headers)
self.assertNotIn('X-ReviewBoard-ShipIt-Only', message._headers)
self.assertFalse(Review.FIX_IT_THEN_SHIP_IT_TEXT in
message.message().as_string())
def test_review_shipit_headers_attachment_comments_opened_issue(self):
"""Testing sending a review e-mail with a 'Ship It' and file attachment
comments with opened issue
"""
review_request = self.create_review_request(public=True)
file_attachment = self.create_file_attachment(review_request)
review = self.create_review(review_request,
body_top=Review.SHIP_IT_TEXT,
body_bottom='',
ship_it=True,
publish=False)
self.create_file_attachment_comment(review, file_attachment,
issue_opened=True)
review.publish()
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertIn('X-ReviewBoard-ShipIt', message._headers)
self.assertNotIn('X-ReviewBoard-ShipIt-Only', message._headers)
self.assertTrue(Review.FIX_IT_THEN_SHIP_IT_TEXT in
message.message().as_string())
def test_review_shipit_headers_screenshot_comments(self):
"""Testing sending a review e-mail with a 'Ship It' and screenshot
comments
"""
review_request = self.create_review_request(public=True)
screenshot = self.create_screenshot(review_request)
review = self.create_review(review_request,
body_top=Review.SHIP_IT_TEXT,
body_bottom='',
ship_it=True,
publish=False)
self.create_screenshot_comment(review, screenshot)
review.publish()
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertIn('X-ReviewBoard-ShipIt', message._headers)
self.assertNotIn('X-ReviewBoard-ShipIt-Only', message._headers)
self.assertFalse(Review.FIX_IT_THEN_SHIP_IT_TEXT in
message.message().as_string())
def test_review_shipit_headers_screenshot_comments_opened_issue(self):
"""Testing sending a review e-mail with a 'Ship It' and screenshot
comments with opened issue
"""
review_request = self.create_review_request(public=True)
screenshot = self.create_screenshot(review_request)
review = self.create_review(review_request,
body_top=Review.SHIP_IT_TEXT,
body_bottom='',
ship_it=True,
publish=False)
self.create_screenshot_comment(review, screenshot, issue_opened=True)
review.publish()
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertIn('X-ReviewBoard-ShipIt', message._headers)
self.assertNotIn('X-ReviewBoard-ShipIt-Only', message._headers)
self.assertTrue(Review.FIX_IT_THEN_SHIP_IT_TEXT in
message.message().as_string())
def test_review_shipit_headers_general_comments(self):
"""Testing sending a review e-mail with a 'Ship It' and general
comments
"""
review_request = self.create_review_request(public=True)
review = self.create_review(review_request,
body_top=Review.SHIP_IT_TEXT,
body_bottom='',
ship_it=True,
publish=False)
self.create_general_comment(review)
review.publish()
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertIn('X-ReviewBoard-ShipIt', message._headers)
self.assertNotIn('X-ReviewBoard-ShipIt-Only', message._headers)
self.assertFalse(Review.FIX_IT_THEN_SHIP_IT_TEXT in
message.message().as_string())
def test_review_shipit_headers_general_comments_opened_issue(self):
"""Testing sending a review e-mail with a 'Ship It' and general
comments with opened issue
"""
review_request = self.create_review_request(public=True)
review = self.create_review(review_request,
body_top=Review.SHIP_IT_TEXT,
body_bottom='',
ship_it=True,
publish=False)
self.create_general_comment(review, issue_opened=True)
review.publish()
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertIn('X-ReviewBoard-ShipIt', message._headers)
self.assertNotIn('X-ReviewBoard-ShipIt-Only', message._headers)
self.assertTrue(Review.FIX_IT_THEN_SHIP_IT_TEXT in
message.message().as_string())
def test_change_ownership_email(self):
"""Testing sending a review request e-mail when the owner is being
changed
"""
admin_user = User.objects.get(username='admin')
admin_email = build_email_address_for_user(admin_user)
review_request = self.create_review_request(public=True)
submitter = review_request.submitter
submitter_email = build_email_address_for_user(submitter)
draft = ReviewRequestDraft.create(review_request)
draft.target_people = [submitter, admin_user]
draft.owner = admin_user
draft.save()
review_request.publish(submitter)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertEqual(message.extra_headers['From'], submitter_email)
self.assertSetEqual(set(message.to),
{admin_email, submitter_email})
def test_change_ownership_email_not_submitter(self):
"""Testing sending a review request e-mail when the owner is being
changed by someone else
"""
admin_user = User.objects.get(username='admin')
admin_email = build_email_address_for_user(admin_user)
review_request = self.create_review_request(public=True)
submitter = review_request.submitter
submitter_email = build_email_address_for_user(submitter)
draft = ReviewRequestDraft.create(review_request)
# Before publishing, target_people must be added.
draft.target_people = [admin_user, submitter]
draft.owner = admin_user
draft.save()
review_request.publish(admin_user)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertEqual(message.extra_headers['From'], admin_email)
self.assertSetEqual(set(message.to),
{admin_email, submitter_email})
def _get_sender(self, user):
return build_email_address(full_name=user.get_full_name(),
email=self.sender)
class ReviewRequestSiteRootURLTests(SiteRootURLTestsMixin,
ReviewRequestEmailTestsMixin, TestCase):
"""Tests for Bug 4612 related to review request and review e-mails."""
@override_settings(**SiteRootURLTestsMixin.CUSTOM_SITE_ROOT_SETTINGS)
def test_review_request_email_site_root_custom(self):
"""Testing review request e-mail includes site root only once with
custom site root
"""
review_request = self.create_review_request()
review_request.publish(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
absolute_url = review_request.get_absolute_url()
review_request_url = build_server_url(absolute_url)
bad_review_request_url = '%s%s' % (get_server_url(), absolute_url)
self.assertNotIn(self.BAD_SITE_ROOT, review_request_url)
self.assertIn(self.BAD_SITE_ROOT, bad_review_request_url)
self.assertIn(review_request_url, message.body)
self.assertNotIn(bad_review_request_url, message.body)
for alternative in message.alternatives:
self.assertNotIn(bad_review_request_url, alternative)
def test_review_request_email_site_root_default(self):
"""Testing review request e-mail includes site root only once with
default site root
"""
review_request = self.create_review_request()
review_request.publish(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertNotIn('example.com//', message.body)
for alternative in message.alternatives:
self.assertNotIn('example.com//', alternative[0])
@add_fixtures(['test_site'])
@override_settings(**SiteRootURLTestsMixin.CUSTOM_SITE_ROOT_SETTINGS)
def test_review_request_email_site_root_custom_with_localsite(self):
"""Testing review request e-mail includes site root only once with
custom site root and a LocalSite
"""
review_request = self.create_review_request(with_local_site=True)
with self.settings(SITE_ROOT='/foo/'):
review_request.publish(review_request.submitter)
absolute_url = review_request.get_absolute_url()
bad_review_request_url = '%s%s' % (get_server_url(), absolute_url)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
review_request_url = build_server_url(absolute_url)
self.assertNotIn(self.BAD_SITE_ROOT, review_request_url)
self.assertIn(self.BAD_SITE_ROOT, bad_review_request_url)
self.assertIn(review_request_url, message.body)
self.assertNotIn(bad_review_request_url, message.body)
for alternative in message.alternatives:
self.assertNotIn(bad_review_request_url, alternative[0])
@add_fixtures(['test_site'])
def test_review_request_email_site_root_default_with_localsite(self):
"""Testing review request e-mail includes site root only once with
default site root and a LocalSite
"""
review_request = self.create_review_request()
review_request.publish(review_request.submitter)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertNotIn('example.com//', message.body)
for alternative in message.alternatives:
self.assertNotIn('example.com//', alternative[0])
@override_settings(**SiteRootURLTestsMixin.CUSTOM_SITE_ROOT_SETTINGS)
def test_review_email_site_root_custom(self):
"""Testing review e-mail includes site root only once with custom site
root
"""
review_request = self.create_review_request(public=True)
review = self.create_review(review_request=review_request)
review.publish(review.user)
review_url = build_server_url(review.get_absolute_url())
bad_review_url = '%s%s' % (get_server_url(), review.get_absolute_url())
self.assertNotIn(self.BAD_SITE_ROOT, review_url)
self.assertIn(self.BAD_SITE_ROOT, bad_review_url)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertNotIn(bad_review_url, message.body)
for alternative in message.alternatives:
self.assertNotIn(bad_review_url, alternative[0])
def test_review_email_site_root_default(self):
"""Testing review e-mail includes site root only once with default site
root
"""
review_request = self.create_review_request(public=True)
review = self.create_review(review_request=review_request)
review.publish(review.user)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertNotIn('example.com//', message.body)
for alternative in message.alternatives:
self.assertNotIn('example.com//', alternative[0])
@add_fixtures(['test_site'])
@override_settings(**SiteRootURLTestsMixin.CUSTOM_SITE_ROOT_SETTINGS)
def test_review_email_site_root_custom_with_localsite(self):
"""Testing review e-mail includes site root only once with custom site
root and a LocalSite
"""
review_request = self.create_review_request(public=True,
with_local_site=True)
review = self.create_review(review_request=review_request)
review.publish(review.user)
review_url = build_server_url(review.get_absolute_url())
bad_review_url = '%s%s' % (get_server_url(), review.get_absolute_url())
self.assertNotIn(self.BAD_SITE_ROOT, review_url)
self.assertIn(self.BAD_SITE_ROOT, bad_review_url)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertNotIn(bad_review_url, message.body)
for alternative in message.alternatives:
self.assertNotIn(bad_review_url, alternative[0])
@add_fixtures(['test_site'])
def test_review_email_site_root_default_with_localsite(self):
"""Testing review e-mail includes site root only once with default site
root and a LocalSite
"""
review_request = self.create_review_request(public=True,
with_local_site=True)
review = self.create_review(review_request=review_request)
review.publish(review.user)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertNotIn('example.com//', message.body)
for alternative in message.alternatives:
self.assertNotIn('example.com//', alternative[0])
class WebAPITokenEmailTestsMixin(EmailTestHelper):
"""A mixin for web hook-related e-mail tests."""
email_siteconfig_settings = {
'mail_send_new_user_mail': False,
}
def setUp(self):
super(WebAPITokenEmailTestsMixin, self).setUp()
self.user = User.objects.create_user(username='test-user',
first_name='Sample',
last_name='User',
email='[email protected]')
self.assertEqual(len(mail.outbox), 0)
class WebAPITokenEmailTests(WebAPITokenEmailTestsMixin, TestCase):
"""Unit tests for WebAPIToken creation e-mails."""
def test_create_token(self):
"""Testing sending e-mail when a new API Token is created"""
webapi_token = WebAPIToken.objects.generate_token(user=self.user,
note='Test',
policy={})
self.assertEqual(len(mail.outbox), 1)
email = mail.outbox[0]
html_body = email.alternatives[0][0]
partial_token = '%s...' % webapi_token.token[:10]
self.assertEqual(email.subject, 'New Review Board API token created')
self.assertEqual(email.from_email, self.sender)
self.assertEqual(email.extra_headers['From'],
settings.DEFAULT_FROM_EMAIL)
self.assertEqual(email.to[0], build_email_address_for_user(self.user))
self.assertNotIn(webapi_token.token, email.body)
self.assertNotIn(webapi_token.token, html_body)
self.assertIn(partial_token, email.body)
self.assertIn(partial_token, html_body)
self.assertIn('A new API token has been added to your Review Board '
'account',
email.body)
self.assertIn('A new API token has been added to your Review Board '
'account',
html_body)
def test_create_token_no_email(self):
"""Testing WebAPIToken.objects.generate_token does not send e-mail
when auto_generated is True
"""
WebAPIToken.objects.generate_token(user=self.user,
note='Test',
policy={},
auto_generated=True)
self.assertEqual(len(mail.outbox), 0)
def test_update_token(self):
"""Testing sending e-mail when an existing API Token is updated"""
webapi_token = WebAPIToken.objects.generate_token(user=self.user,
note='Test',
policy={})
mail.outbox = []
webapi_token.save()
self.assertEqual(len(mail.outbox), 1)
email = mail.outbox[0]
html_body = email.alternatives[0][0]
partial_token = '%s...' % webapi_token.token[:10]
self.assertEqual(email.subject, 'Review Board API token updated')
self.assertEqual(email.from_email, self.sender)
self.assertEqual(email.extra_headers['From'],
settings.DEFAULT_FROM_EMAIL)
self.assertEqual(email.to[0], build_email_address_for_user(self.user))
self.assertNotIn(webapi_token.token, email.body)
self.assertNotIn(webapi_token.token, html_body)
self.assertIn(partial_token, email.body)
self.assertIn(partial_token, html_body)
self.assertIn('One of your API tokens has been updated on your '
'Review Board account',
email.body)
self.assertIn('One of your API tokens has been updated on your '
'Review Board account',
html_body)
def test_delete_token(self):
"""Testing sending e-mail when an existing API Token is deleted"""
webapi_token = WebAPIToken.objects.generate_token(user=self.user,
note='Test',
policy={})
mail.outbox = []
webapi_token.delete()
self.assertEqual(len(mail.outbox), 1)
email = mail.outbox[0]
html_body = email.alternatives[0][0]
self.assertEqual(email.subject, 'Review Board API token deleted')
self.assertEqual(email.from_email, self.sender)
self.assertEqual(email.extra_headers['From'],
settings.DEFAULT_FROM_EMAIL)
self.assertEqual(email.to[0], build_email_address_for_user(self.user))
self.assertIn(webapi_token.token, email.body)
self.assertIn(webapi_token.token, html_body)
self.assertIn('One of your API tokens has been deleted from your '
'Review Board account',
email.body)
self.assertIn('One of your API tokens has been deleted from your '
'Review Board account',
html_body)
class WebAPITokenSiteRootURLTests(SiteRootURLTestsMixin,
WebAPITokenEmailTestsMixin, TestCase):
"""Tests for Bug 4612 related to web API token e-mails."""
@override_settings(**SiteRootURLTestsMixin.CUSTOM_SITE_ROOT_SETTINGS)
def test_create_token_site_root_custom(self):
"""Testing WebAPI Token e-mails include site root only once with custom
site root
"""
WebAPIToken.objects.generate_token(user=self.user, note='Test',
policy={})
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertNotIn(self.BAD_SITE_ROOT, message.body)
for alternative in message.alternatives:
self.assertNotIn(self.BAD_SITE_ROOT, alternative[0])
def test_create_token_site_root_default(self):
"""Testing WebAPI Token e-mails include site root only once with
default site root
"""
WebAPIToken.objects.generate_token(user=self.user, note='Test',
policy={})
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertNotIn('example.com//', message.body)
for alternative in message.alternatives:
self.assertNotIn('example.com//', alternative[0])
@add_fixtures(['test_site'])
@override_settings(**SiteRootURLTestsMixin.CUSTOM_SITE_ROOT_SETTINGS)
def test_create_token_site_root_custom_with_localsite(self):
"""Testing WebAPI Token e-mails include site root only once with custom
site root and a LocalSite
"""
local_site = LocalSite.objects.get(pk=1)
WebAPIToken.objects.generate_token(user=self.user, note='Test',
policy={}, local_site=local_site)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertNotIn(self.BAD_SITE_ROOT, message.body)
for alternative in message.alternatives:
self.assertNotIn(self.BAD_SITE_ROOT, alternative[0])
@add_fixtures(['test_site'])
def test_create_token_site_root_default_with_localsite(self):
"""Testing WebAPI Token e-mails include site root only once with
default site root and a LocalSite
"""
local_site = LocalSite.objects.get(pk=1)
WebAPIToken.objects.generate_token(user=self.user, note='Test',
policy={}, local_site=local_site)
self.assertEqual(len(mail.outbox), 1)
message = mail.outbox[0]
self.assertNotIn('example.com//', message.body)
for alternative in message.alternatives:
self.assertNotIn('example.com//', alternative[0])
|
py | 1a4585eab22cc9d6f3e979145b9b0ed630fe69c1 | # DFS Traversal Function
def dfs(l, start_node, goal_node):
visited = [0]*10
visited[start_node] = 1
print('DFS : ', end = " ")
print(start_node, end = " ")
s = []
while start_node != goal_node:
p = -1
for i in l[start_node]:
k = 0
p += 1
if i == 1 and visited[p] != 1:
k += 1
visited[p] = 1
s.append(start_node)
start_node = p
print('-->', end = " ")
print(start_node, end = " ")
break
if k == 0:
start_node = s.pop()
## main program
# Graph Declaration
l = [[0,0,0,1,0,1,1,0,1,1],
[0,0,1,1,1,1,1,1,0,1],
[0,1,0,0,1,1,0,1,1,1],
[1,1,0,0,0,0,1,0,0,0],
[0,1,1,0,0,0,1,0,1,1],
[1,1,1,0,0,0,1,0,0,1],
[1,1,0,1,1,1,0,1,0,1],
[0,1,1,0,0,0,1,0,1,1],
[1,0,1,0,1,0,0,1,0,0],
[1,1,1,0,1,1,1,1,0,0]]
# DFS Traversal
start_node = 0
goal_node = 4
dfs(l, start_node, goal_node)
print()
|
py | 1a4586daa4ad912a5298d7061263630d59d6bffd | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 13 17:22:08 2019
@author: Chenghai Li
"""
import math
import time
import torch
import torch.nn as nn
import numpy as np
from torchdiffeq import odeint_adjoint as odeint
import matplotlib.pyplot as plt
from scipy import interpolate
device = torch.device('cuda:0')
file = open('3.txt','r')
x3 = []
y3 = []
for row in file.readlines():
row = row.split()
row[0] = float(row[0])
row[1] = float(row[1])
x3.append(row[0])
y3.append(row[1])
file.close()
E = interpolate.interp1d(x3, y3, kind="cubic")
file = open('pr.txt','r')
p = []
r = []
for row in file.readlines():
row = row.split()
row[0] = float(row[0])
row[1] = float(row[1])
p.append(row[0])
r.append(row[1])
file.close()
pr_pre = interpolate.interp1d(p, r, kind="cubic")
def pr(p):
if p>0.1001:
return pr_pre(p)
else:
return [0.8043390]
file = open('2_1.txt','r')
x2_1 = []
y2_1 = []
for row in file.readlines():
row = row.split()
row[0] = float(row[0])
row[1] = float(row[1])
x2_1.append(row[0])
y2_1.append(row[1])
file.close()
l2_1 = interpolate.interp1d(x2_1, y2_1, kind="cubic")
file = open('2_2.txt','r')
x2_2 = []
y2_2 = []
for row in file.readlines():
row = row.split()
row[0] = float(row[0])
row[1] = float(row[1])
x2_2.append(row[0])
y2_2.append(row[1])
file.close()
l2_2 = interpolate.interp1d(x2_2, y2_2, kind="cubic")
def l(x):
x = (x -12.5) % 100
if x < 0.45:
return torch.tensor(l2_1(x), dtype = torch.double)
if 0.45 <= x <= 2:
return torch.tensor([2], dtype = torch.double)
if 2 < x < 2.45:
return torch.tensor(l2_2(x), dtype = torch.double)
if 2.45 <= x <= 100:
return torch.tensor([0], dtype = torch.double)
A = 0.7*0.7*math.pi
v = 500*5*5*math.pi
omiga = math.pi/111
def v0(t):
return torch.tensor([-(-2.413 * math.sin( omiga * t + math.pi/2 ) + 4.826) * math.pi * 2.5 * 2.5 + 162.1374326208532], dtype = torch.double)
def v0t(t):
return torch.tensor([omiga * 2.413 * math.cos ( omiga * t + math.pi/2 ) * math.pi * 2.5 * 2.5], dtype = torch.double)
class func(nn.Module):
def forward(self, t, w):
p0, p1= w
tr = t % 100
if p0 >= p1 and v0t(t) < 0:
Q0 = 0.85 * A * math.sqrt(2 * ( p0 - p1 ) / torch.tensor(pr(p0), dtype = torch.double) )
else:
Q0 = torch.tensor([0], dtype = torch.double)
if p0 < 0.5 and v0t(t) > 0:
r0t = torch.tensor([0], dtype = torch.double)
p0t = torch.tensor([0], dtype = torch.double)
else:
r0t = (-Q0 * torch.tensor(pr(p0), dtype = torch.double) * v0(t) - v0(t) * torch.tensor(pr(p0), dtype = torch.double) * v0t(t)) / (v0(t) ** 2)
p0t = torch.tensor(E(p0), dtype = torch.double) / torch.tensor(pr(p0), dtype = torch.double) * r0t
A1 = math.pi * l(tr) * math.sin( math.pi / 20 ) * (4 * 1.25 + l(tr) * math.sin( math.pi / 20 ) * math.cos( math.pi / 20 ) )
A2 = math.pi * 0.7 * 0.7
Q1 = 0.85 * min(A1, A2) * math.sqrt(2 * p1 / torch.tensor(pr(p1), dtype = torch.double))
r1t = (Q0 * torch.tensor(pr(p0), dtype = torch.double) - Q1 * torch.tensor(pr(p1), dtype = torch.double)) / v
p1t = torch.tensor(E(p1), dtype = torch.double) / torch.tensor(pr(p1), dtype = torch.double) * r1t
return torch.tensor([p0t, p1t],dtype=torch.double)
time_range = 20
step_length = 0.01
time_start=time.time()
t = torch.tensor( np.arange(0, time_range, step_length), dtype=torch.double)
y0 = torch.tensor([0.5, 100], dtype=torch.double)
track1 = odeint(func(), y0, t, method='rk4')
time_end=time.time()
print('totally cost',time_end-time_start)
'''
show = []
for i in range(len(track1)):
show.append(track1[i][0])
plt.plot(show)
'''
|
py | 1a45876119b4878a86bda9ff3b527364ca1ea3b7 | from django.urls import path
from .views import post_comment_create_and_list_view, like_unlike_post, PostDeleteView, PostUpdateView
app_name = 'posts'
urlpatterns = [
path('', post_comment_create_and_list_view, name='main-post-view'),
path('liked/', like_unlike_post, name='like-post-view'),
path('<pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('<pk>/update/', PostUpdateView.as_view(), name='post-update'),
]
|
py | 1a45878e7da84949140e016e5dd4284e696f7edc | #!/usr/bin/env python
"""
SyntaxError - There's something wrong with how you wrote the surrounding code.
Check your parentheses, and make sure there are colons where needed.
"""
while True
print "Where's the colon at?" |
py | 1a45895c98cf4cdf7550f2ca0dcfe82f8210c3c5 | import characterquests
from characterutil import *
def sz_01_05_Gilneas_City(count,datatree,openfile):
characterquests.charquestheaderfaction(count,"01-05: Gilneas City","alliance",openfile)
characterquests.charquestprintfactionrace(count,datatree,openfile,14078,"Lockdown!","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14091,"Something's Amiss","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14093,"All Hell Breaks Loose","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14094,"Salvage the Supplies","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14098,"Evacuate the Merchant Square","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14099,"Royal Orders","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14154,"By the Skin of His Teeth","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14157,"Old Divisions","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14159,"The Rebel Lord's Arsenal","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14204,"From the Shadows","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14212,"Sacrifices","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14214,"Message to Greymane","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14218,"By Blood and Ash","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14221,"Never Surrender, Sometimes Retreat","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14222,"Last Stand","alliance","race_worgen_female")
characterquests.charquestprintfactionclassrace(count,datatree,openfile,14280,"The Winds Know Your Name... Apparently","alliance","class_druid","race_worgen_female")
characterquests.charquestprintfactionclassrace(count,datatree,openfile,14291,"Safety in Numbers","alliance","class_druid","race_worgen_female")
characterquests.charquestprintfactionclassrace(count,datatree,openfile,14275,"Someone's Keeping Track of You","alliance","class_hunter","race_worgen_female")
characterquests.charquestprintfactionclassrace(count,datatree,openfile,14290,"Safety in Numbers","alliance","class_hunter","race_worgen_female")
characterquests.charquestprintfactionclassrace(count,datatree,openfile,14277,"Arcane Inquiries","alliance","class_mage","race_worgen_female")
characterquests.charquestprintfactionclassrace(count,datatree,openfile,14288,"Safety in Numbers","alliance","class_mage","race_worgen_female")
characterquests.charquestprintfactionclassrace(count,datatree,openfile,14278,"Seek the Sister","alliance","class_priest","race_worgen_female")
characterquests.charquestprintfactionclassrace(count,datatree,openfile,14289,"Safety in Numbers","alliance","class_priest","race_worgen_female")
characterquests.charquestprintfactionclassrace(count,datatree,openfile,14269,"Someone's Looking for You","alliance","class_rogue","race_worgen_female")
characterquests.charquestprintfactionclassrace(count,datatree,openfile,14285,"Safety in Numbers","alliance","class_rogue","race_worgen_female")
characterquests.charquestprintfactionclassrace(count,datatree,openfile,14273,"Shady Associates","alliance","class_warlock","race_worgen_female")
characterquests.charquestprintfactionclassrace(count,datatree,openfile,14287,"Safety in Numbers","alliance","class_warlock","race_worgen_female")
characterquests.charquestprintfactionclassrace(count,datatree,openfile,14265,"Your Instructor","alliance","class_warrior","race_worgen_female")
characterquests.charquestprintfactionclassrace(count,datatree,openfile,14286,"Safety in Numbers","alliance","class_warrior","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14293,"Save Krennan Aranas","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14294,"Time to Regroup","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14467,"Alas, Gilneas!","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24930,"While You're At It","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,26129,"Brothers In Arms","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,28850,"The Prison Rooftop","alliance","race_worgen_female")
def sz_01_20_Gilneas(count,datatree,openfile):
characterquests.charquestheaderfaction(count,"01-20: Gilneas","alliance",openfile)
characterquests.charquestprintfactionrace(count,datatree,openfile,14220,"This Is the End","alliance","race_worgen_female")
characterquests.charquestprintfactionclassrace(count,datatree,openfile,14272,"Eviscerate","alliance","class_rogue","race_worgen_female")
characterquests.charquestprintfactionclassrace(count,datatree,openfile,14274,"Corruption","alliance","class_warlock","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14313,"Among Humans Again","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14319,"Further Treatment","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14320,"In Need of Ingredients","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14321,"Invasion","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14336,"Kill or Be Killed","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14347,"Hold the Line","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14348,"You Can't Take 'Em Alone","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14366,"Holding Steady","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14367,"The Allens' Storm Cellar","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14368,"Save the Children!","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14369,"Unleash the Beast","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14375,"Last Chance at Humanity","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14382,"Two By Sea","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14386,"Leader of the Pack","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14395,"Gasping for Breath","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14396,"As the Land Shatters","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14397,"Evacuation","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14398,"Grandma Wahl","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14399,"Grandma's Lost It Alright","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14400,"I Can't Wear This","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14401,"Grandma's Cat","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14402,"Ready to Go","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14403,"The Hayward Brothers","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14404,"Not Quite Shipshape","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14405,"Escape By Sea","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14406,"The Crowley Orchard","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14412,"Washed Up","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14416,"The Hungry Ettin","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14463,"Horses for Duskhaven","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14465,"To Greymane Manor","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14466,"The King's Observatory","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24438,"Exodus","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24468,"Stranded at the Marsh","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24472,"Introductions Are in Order","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24483,"Stormglen","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24484,"Pest Control","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24495,"Pieces of the Past","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24501,"Queen-Sized Troubles","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24575,"Liberation Day","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24578,"The Blackwald","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24592,"Betrayal at Tempest's Reach","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24593,"Neither Human Nor Beast","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24602,"Laid to Rest","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24616,"Losing Your Tail","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24617,"Tal'doren, the Wild Home","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24627,"At Our Doorstep","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24628,"Preparations","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24646,"Take Back What's Ours","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24672,"Onwards and Upwards","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24673,"Return to Stormglen","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24674,"Slaves to No One","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24675,"Last Meal","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24676,"Push Them Out","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24677,"Flank the Forsaken","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24678,"Knee-Deep","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24679,"Patriarch's Blessing","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24680,"Keel Harbor","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24681,"They Have Allies, But So Do We","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24902,"The Hunt For Sylvanas","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24903,"Vengeance or Survival","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24904,"The Battle for Gilneas City","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24920,"Slowing the Inevitable","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,26706,"Endgame","alliance","race_worgen_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14434,"Rut'theran Village","alliance","race_worgen_female")
def sz_10_60_Ruins_of_Gilneas(count,datatree,openfile):
characterquests.charquestheaderfaction(count,"10:60 Ruins of Gilneas","horde",openfile)
characterquests.charquestprintfaction(count,datatree,openfile,27290,"To Forsaken Forward Command","horde")
characterquests.charquestprint(count,datatree,openfile,27322,"Korok the Colossus")
characterquests.charquestprintfaction(count,datatree,openfile,27333,"Losing Ground","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27342,"In Time, All Will Be Revealed","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27345,"The F.C.D.","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27349,"Break in Communications: Dreadwatch Outpost","horde")
characterquests.charquestprint(count,datatree,openfile,27350,"Break in Communications: Rutsak's Guard")
characterquests.charquestprintfaction(count,datatree,openfile,27360,"Vengeance for Our Soldiers","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27364,"On Whose Orders?","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27401,"What Tomorrow Brings","horde")
characterquests.charquestprint(count,datatree,openfile,27405,"Fall Back!")
characterquests.charquestprintfaction(count,datatree,openfile,27406,"A Man Named Godfrey","horde")
characterquests.charquestprint(count,datatree,openfile,27423,"Resistance is Futile")
def sz_01_05_Kezan(count,datatree,openfile):
characterquests.charquestheaderfaction(count,"01-05: Kezan","horde",openfile)
characterquests.charquestprintfactionrace(count,datatree,openfile,14069,"Good Help is Hard to Find","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14070,"Do it Yourself","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14071,"Rolling with my Homies","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14075,"Trouble in the Mines","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14109,"The New You","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14110,"The New You","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14113,"Life of the Party","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14115,"Pirate Party Crashers","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14116,"The Uninvited Guest","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14120,"A Bazillion Macaroons?!","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14121,"Robbing Hoods","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14122,"The Great Bank Heist","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14123,"Waltz Right In","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14124,"Liberate the Kaja'mite","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14125,"447","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14126,"Life Savings","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14138,"Taking Care of Business","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14153,"Life of the Party","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24488,"The Replacements","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24502,"Necessary Roughness","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24503,"Fourth and Goal","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24520,"Give Sassy the News","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24567,"Report for Tryouts","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25473,"Kaja'Cola","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,26711,"Off to the Bank","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,26712,"Off to the Bank","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,28349,"Megs in Marketing","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,28414,"Fourth and Goal","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,28606,"The Keys to the Hot Rod","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,28607,"The Keys to the Hot Rod","horde","race_goblin_female")
def sz_01_10_Lost_Isles(count,datatree,openfile):
characterquests.charquestheaderfaction(count,"01-20: Lost Isles","horde",openfile)
characterquests.charquestprintfactionrace(count,datatree,openfile,14001,"Goblin Escape Pods","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14014,"Get Our Stuff Back!","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14019,"Monkey Business","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14021,"Miner Troubles","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14031,"Capturing the Unknown","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14233,"Orcs Can Write?","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14234,"The Enemy of My Enemy","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14235,"The Vicious Vale","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14236,"Weed Whacker","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14237,"Forward Movement","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14238,"Infrared = Infradead","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14239,"Don't Go Into the Light!","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14240,"To the Cliffs","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14241,"Get to the Gyrochoppa!","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14242,"Precious Cargo","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14243,"Warchief's Revenge","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14244,"Up, Up & Away!","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14245,"It's a Town-In-A-Box","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14248,"Help Wanted","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14303,"Back to Aggra","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14326,"Meet Me Up Top","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14445,"Farewell, For Now","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14473,"It's Our Problem Now","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,14474,"Goblin Escape Pods","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24671,"Cluster Cluck","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24741,"Trading Up","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24744,"The Biggest Egg Ever","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24816,"Who's Top of the Food Chain Now?","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24817,"A Goblin in Shark's Clothing","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24856,"Invasion Imminent!","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24858,"Bilgewater Cartel Represent","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24859,"Naga Hide","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24864,"Irresistible Pool Pony","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24868,"Surrender or Else!","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24897,"Get Back to Town","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24901,"Town-In-A-Box: Under Attack","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24924,"Oomlot Village","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24925,"Free the Captives","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24929,"Send a Message","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24937,"Oomlot Dealt With","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24940,"Up the Volcano","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24942,"Zombies vs. Super Booster Rocket Boots","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24945,"Three Little Pygmies","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24946,"Rockin' Powder","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24952,"Rocket Boot Boost","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24954,"Children of a Turtle God","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,24958,"Volcanoth!","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25023,"Old Friends","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25024,"Repel the Paratroopers","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25058,"Mine Disposal, the Goblin Way","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25066,"The Pride of Kezan","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25093,"The Heads of the SI:7","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25098,"The Warchief Wants You","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25099,"Borrow Bastia","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25100,"Let's Ride","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25109,"The Gallywix Labor Mine","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25110,"Kaja'Cola Gives You IDEAS! (TM)","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25122,"Morale Boost","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25123,"Throw It On the Ground!","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25125,"Light at the End of the Tunnel","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25184,"Wild Mine Cart Ride","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25200,"Shredder Shutdown","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25201,"The Ultimate Footbomb Uniform","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25202,"The Fastest Way to His Heart","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25203,"What Kind of Name is Chip, Anyway?","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25204,"Release the Valves","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25207,"Good-bye, Sweet Oil","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25213,"The Slave Pits","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25214,"Escape Velocity","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25243,"She Loves Me, She Loves Me NOT!","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25244,"What Kind of Name is Candy, Anyway?","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25251,"Final Confrontation","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,25265,"Victory!","horde","race_goblin_female")
characterquests.charquestprintfactionrace(count,datatree,openfile,27139,"Hobart Needs You","horde","race_goblin_female")
def z_80_90_Mount_Hyjal(count,datatree,openfile):
characterquests.charquestheader(count,"80-90: Mount Hyjal: Intro",openfile)
characterquests.charquestprintfaction(count,datatree,openfile,27726,"Hero's Call: Mount Hyjal!","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27721,"Warchief's Command: Mount Hyjal!","horde")
characterquests.charquestprint(count,datatree,openfile,25316,"As Hyjal Burns")
characterquests.charquestprint(count,datatree,openfile,25370,"Inciting the Elements")
characterquests.charquestprint(count,datatree,openfile,25460,"The Earth Rises")
characterquests.charquestprint(count,datatree,openfile,25574,"Flames from Above")
characterquests.charquestprint(count,datatree,openfile,25317,"Protect the World Tree")
characterquests.charquestprint(count,datatree,openfile,25319,"War on the Twilight's Hammer")
characterquests.charquestprint(count,datatree,openfile,25323,"Flamebreaker")
characterquests.charquestprint(count,datatree,openfile,25464,"The Return of Baron Geddon")
characterquests.charquestprint(count,datatree,openfile,25430,"Emerald Allies")
characterquests.charquestprint(count,datatree,openfile,25320,"The Captured Scout")
characterquests.charquestprint(count,datatree,openfile,25321,"Twilight Captivity")
characterquests.charquestprint(count,datatree,openfile,25424,"Return to Alysra")
characterquests.charquestprint(count,datatree,openfile,25324,"A Prisoner of Interest")
characterquests.charquestprint(count,datatree,openfile,25325,"Through the Dream")
characterquests.charquestprint(count,datatree,openfile,25578,"Return to Nordrassil")
characterquests.charquestheader(count,"80-90: Mount Hyjal: Shrine of Goldrinn",openfile)
characterquests.charquestprint(count,datatree,openfile,25584,"The Return of the Ancients")
characterquests.charquestprint(count,datatree,openfile,25233,"End of the Supply Line")
characterquests.charquestprint(count,datatree,openfile,25234,"In the Rear With the Gear")
characterquests.charquestprint(count,datatree,openfile,25255,"Harrying the Hunters")
characterquests.charquestprintfaction(count,datatree,openfile,25268,"The Voice of Goldrinn","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,25269,"The Voice of Lo'Gosh","horde")
characterquests.charquestprintfaction(count,datatree,openfile,25271,"Goldrinn's Ferocity","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,25270,"Howling Mad","horde")
characterquests.charquestprintfaction(count,datatree,openfile,25273,"Lycanthoth the Corruptor","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,25272,"Lycanthoth the Corruptor","horde")
characterquests.charquestprintfaction(count,datatree,openfile,25280,"The Shrine Reclaimed","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,25279,"The Shrine Reclaimed","horde")
characterquests.charquestprintfaction(count,datatree,openfile,25278,"Cleaning House","alliance")
characterquests.charquestprint(count,datatree,openfile,25297,"From the Mouth of Madness")
characterquests.charquestprint(count,datatree,openfile,25298,"Free Your Mind, the Rest Follows")
characterquests.charquestheader(count,"80-90: Mount Hyjal: (Unsorted)",openfile)
characterquests.charquestprint(count,datatree,openfile,25223,"Trial By Fire")
characterquests.charquestprint(count,datatree,openfile,25224,"In Bloom")
characterquests.charquestprint(count,datatree,openfile,25274,"Signed in Blood")
characterquests.charquestprint(count,datatree,openfile,25276,"Your New Identity")
characterquests.charquestprint(count,datatree,openfile,25291,"Twilight Training")
characterquests.charquestprint(count,datatree,openfile,25294,"Walking the Dog")
characterquests.charquestprint(count,datatree,openfile,25296,"Gather the Intelligence")
characterquests.charquestprint(count,datatree,openfile,25299,"Mental Training: Speaking the Truth to Power")
characterquests.charquestprint(count,datatree,openfile,25308,"Seeds of Discord")
characterquests.charquestprint(count,datatree,openfile,25309,"Spiritual Training: Mercy is for the Weak")
characterquests.charquestprint(count,datatree,openfile,25310,"The Greater of Two Evils")
characterquests.charquestprint(count,datatree,openfile,25311,"Twilight Territory")
characterquests.charquestprint(count,datatree,openfile,25314,"Speech Writing for Dummies")
characterquests.charquestprint(count,datatree,openfile,25315,"Graduation Speech")
characterquests.charquestprint(count,datatree,openfile,25330,"Waste of Flesh")
characterquests.charquestprint(count,datatree,openfile,25372,"Aessina's Miracle")
characterquests.charquestprint(count,datatree,openfile,25381,"Fighting Fire With ... Anything")
characterquests.charquestprint(count,datatree,openfile,25382,"Disrupting the Rituals")
characterquests.charquestprint(count,datatree,openfile,25385,"Save the Wee Animals")
characterquests.charquestprint(count,datatree,openfile,25392,"Oh, Deer!")
characterquests.charquestprint(count,datatree,openfile,25404,"If You're Not Against Us...")
characterquests.charquestprint(count,datatree,openfile,25408,"Seeds of Their Demise")
characterquests.charquestprint(count,datatree,openfile,25411,"A New Master")
characterquests.charquestprint(count,datatree,openfile,25412,"The Name Never Spoken")
characterquests.charquestprint(count,datatree,openfile,25428,"Black Heart of Flame")
characterquests.charquestprint(count,datatree,openfile,25462,"The Bears Up There")
characterquests.charquestprint(count,datatree,openfile,25472,"The Flameseer's Staff")
characterquests.charquestprint(count,datatree,openfile,25490,"Smashing Through Ashes")
characterquests.charquestprint(count,datatree,openfile,25491,"Durable Seeds")
characterquests.charquestprint(count,datatree,openfile,25492,"Firebreak")
characterquests.charquestprint(count,datatree,openfile,25493,"Fresh Bait")
characterquests.charquestprint(count,datatree,openfile,25494,"A Champion's Collar")
characterquests.charquestprint(count,datatree,openfile,25496,"Grudge Match")
characterquests.charquestprint(count,datatree,openfile,25499,"Agility Training: Run Like Hell!")
characterquests.charquestprint(count,datatree,openfile,25502,"Prepping the Soil")
characterquests.charquestprint(count,datatree,openfile,25507,"Hell's Shells")
characterquests.charquestprint(count,datatree,openfile,25509,"Physical Training: Forced Labor")
characterquests.charquestprint(count,datatree,openfile,25510,"Tortolla Speaks")
characterquests.charquestprint(count,datatree,openfile,25514,"Breaking the Bonds")
characterquests.charquestprint(count,datatree,openfile,25519,"Children of Tortolla")
characterquests.charquestprint(count,datatree,openfile,25520,"An Ancient Awakens")
characterquests.charquestprint(count,datatree,openfile,25523,"Flight in the Firelands")
characterquests.charquestprint(count,datatree,openfile,25525,"Wave One")
characterquests.charquestprint(count,datatree,openfile,25531,"Twilight Riot")
characterquests.charquestprint(count,datatree,openfile,25544,"Wave Two")
characterquests.charquestprint(count,datatree,openfile,25548,"Might of the Firelord")
characterquests.charquestprint(count,datatree,openfile,25549,"The Sanctum of the Prophets")
characterquests.charquestprint(count,datatree,openfile,25554,"Secrets of the Flame")
characterquests.charquestprint(count,datatree,openfile,25560,"Egg Wave")
characterquests.charquestprint(count,datatree,openfile,25597,"Commander Jarod Shadowsong")
characterquests.charquestprint(count,datatree,openfile,25601,"Head of the Class")
characterquests.charquestprint(count,datatree,openfile,25608,"Slash and Burn")
characterquests.charquestprint(count,datatree,openfile,25653,"The Ancients are With Us")
characterquests.charquestprint(count,datatree,openfile,25655,"The Wormwing Problem")
characterquests.charquestprint(count,datatree,openfile,25656,"Scrambling for Eggs")
characterquests.charquestprint(count,datatree,openfile,25663,"An Offering for Aviana")
characterquests.charquestprint(count,datatree,openfile,25664,"A Prayer and a Wing")
characterquests.charquestprint(count,datatree,openfile,25665,"A Plea From Beyond")
characterquests.charquestprint(count,datatree,openfile,25731,"A Bird in Hand")
characterquests.charquestprint(count,datatree,openfile,25740,"Fact-Finding Mission")
characterquests.charquestprint(count,datatree,openfile,25746,"Sethria's Brood")
characterquests.charquestprint(count,datatree,openfile,25758,"A Gap in Their Armor")
characterquests.charquestprint(count,datatree,openfile,25761,"Disassembly")
characterquests.charquestprint(count,datatree,openfile,25763,"The Codex of Shadows")
characterquests.charquestprint(count,datatree,openfile,25764,"Egg Hunt")
characterquests.charquestprint(count,datatree,openfile,25776,"Sethria's Demise")
characterquests.charquestprint(count,datatree,openfile,25795,"Return to the Shrine")
characterquests.charquestprint(count,datatree,openfile,25807,"An Ancient Reborn")
characterquests.charquestprint(count,datatree,openfile,25810,"The Hatchery Must Burn")
characterquests.charquestprint(count,datatree,openfile,25830,"The Last Living Lorekeeper")
characterquests.charquestprint(count,datatree,openfile,25832,"Return to Aviana")
characterquests.charquestprint(count,datatree,openfile,25842,"Firefight")
characterquests.charquestprint(count,datatree,openfile,25843,"Tortolla's Revenge")
characterquests.charquestprint(count,datatree,openfile,25881,"Lost Wardens")
characterquests.charquestprint(count,datatree,openfile,25886,"Pressing the Advantage")
characterquests.charquestprint(count,datatree,openfile,25899,"Breakthrough")
characterquests.charquestprint(count,datatree,openfile,25901,"Hyjal Recycling Program")
characterquests.charquestprint(count,datatree,openfile,25904,"The Hammer and the Key")
characterquests.charquestprint(count,datatree,openfile,25906,"The Third Flamegate")
characterquests.charquestprint(count,datatree,openfile,25910,"The Time for Mercy has Passed")
characterquests.charquestprint(count,datatree,openfile,25915,"The Strength of Tortolla")
characterquests.charquestprint(count,datatree,openfile,25923,"Finish Nemesis")
characterquests.charquestprint(count,datatree,openfile,25928,"Tortolla's Triumph")
characterquests.charquestprint(count,datatree,openfile,25940,"Last Stand at Whistling Grove")
characterquests.charquestprint(count,datatree,openfile,25985,"Wings Over Mount Hyjal")
characterquests.charquestprint(count,datatree,openfile,27874,"Aviana's Legacy")
characterquests.charquestprint(count,datatree,openfile,29066,"Good News... and Bad News")
characterquests.charquestprint(count,datatree,openfile,25550,"Magma Monarch")
characterquests.charquestprint(count,datatree,openfile,25551,"The Firelord")
characterquests.charquestprint(count,datatree,openfile,25552,"Brood of Evil")
characterquests.charquestprint(count,datatree,openfile,25553,"Death to the Broodmother")
characterquests.charquestprint(count,datatree,openfile,25555,"The Gatekeeper")
characterquests.charquestprint(count,datatree,openfile,25644,"The Twilight Egg")
characterquests.charquestprint(count,datatree,openfile,29234,"Delegation")
characterquests.charquestprint(count,datatree,openfile,29437,"The Fallen Guardian")
def z_80_90_Vashjir(count,datatree,openfile):
characterquests.charquestheader(count,"Vash'jir: Kelp'thar Forest",openfile)
characterquests.charquestprintfaction(count,datatree,openfile,28825,"A Personal Summons","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,28790,"A Personal Summons","horde")
characterquests.charquestprintfaction(count,datatree,openfile,28826,"The Eye of the Storm","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,28805,"The Eye of the Storm","horde")
characterquests.charquestprintfaction(count,datatree,openfile,14481,"Into The Abyss","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27724,"Hero's Call: Vashj'ir!","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27718,"Warchief's Command: Vashj'ir!","horde")
characterquests.charquestprintfaction(count,datatree,openfile,28827,"To the Depths","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,28816,"To the Depths","horde")
characterquests.charquestprintfaction(count,datatree,openfile,14482,"Call of Duty","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,25924,"Call of Duty","horde")
characterquests.charquestprintfaction(count,datatree,openfile,24432,"Sea Legs","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,25929,"Sea Legs","horde")
characterquests.charquestprintfaction(count,datatree,openfile,25281,"Pay It Forward","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,25936,"Pay It Forward","horde")
characterquests.charquestprintfaction(count,datatree,openfile,25405,"Rest For the Weary","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,25941,"Rest For the Weary","horde")
characterquests.charquestprintfaction(count,datatree,openfile,25357,"Buy Us Some Time","alliance")
characterquests.charquestprint(count,datatree,openfile,25358,"Nerve Tonic")
characterquests.charquestprint(count,datatree,openfile,25371,"The Abyssal Ride")
characterquests.charquestprint(count,datatree,openfile,25377,"The Horde's Hoard")
characterquests.charquestprint(count,datatree,openfile,25384,"Raw Materials")
characterquests.charquestprint(count,datatree,openfile,25388,"A Case of Crabs")
characterquests.charquestprint(count,datatree,openfile,25389,"A Taste For Tail")
characterquests.charquestprint(count,datatree,openfile,25390,"A Girl's Best Friend")
characterquests.charquestprint(count,datatree,openfile,25413,"Change of Plans")
characterquests.charquestprint(count,datatree,openfile,25419,"Lady La-La's Medallion")
characterquests.charquestprint(count,datatree,openfile,25459,"Ophidophobia")
characterquests.charquestprint(count,datatree,openfile,25467,"Kliklak's Craw")
characterquests.charquestprint(count,datatree,openfile,25477,"Better Late Than Dead")
characterquests.charquestprint(count,datatree,openfile,25497,"Back in the Saddle")
characterquests.charquestprint(count,datatree,openfile,25498,"Shark Bait")
characterquests.charquestprint(count,datatree,openfile,25503,"Blackfin's Booty")
characterquests.charquestprintfaction(count,datatree,openfile,25545,"To Arms!","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,25546,"Traveling on Our Stomachs","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,25547,"On Our Own Terms","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,25558,"All or Nothing","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,25564,"Stormwind Elite Aquatic and Land Forces","alliance")
characterquests.charquestprint(count,datatree,openfile,25587,"Gimme Shelter!")
characterquests.charquestprint(count,datatree,openfile,25598,"Ain't Too Proud to Beg")
characterquests.charquestprint(count,datatree,openfile,25602,"Can't Start a Fire Without a Spark")
characterquests.charquestprint(count,datatree,openfile,25636,"Starve a Fever, Feed a Cold")
characterquests.charquestprint(count,datatree,openfile,25638,"A Desperate Plea")
characterquests.charquestprint(count,datatree,openfile,25651,"Oh, the Insanity!")
characterquests.charquestprint(count,datatree,openfile,25657,"Dah, Nunt... Dah, Nunt...")
characterquests.charquestprint(count,datatree,openfile,25666,"Getting Your Hands Dirty")
characterquests.charquestprint(count,datatree,openfile,25670,"DUN-dun-DUN-dun-DUN-dun")
characterquests.charquestprint(count,datatree,openfile,25732,"A Bone to Pick")
characterquests.charquestprint(count,datatree,openfile,25737,"Tenuous Negotiations")
characterquests.charquestprint(count,datatree,openfile,25738,"Shallow End of the Gene Pool")
characterquests.charquestprint(count,datatree,openfile,25742,"What? This Old Thing?")
characterquests.charquestprint(count,datatree,openfile,25743,"Decisions, Decisions")
characterquests.charquestprint(count,datatree,openfile,25794,"Undersea Sanctuary")
characterquests.charquestprintfaction(count,datatree,openfile,25812,"Spelunking","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,25824,"Debriefing","alliance")
characterquests.charquestprint(count,datatree,openfile,25883,"How Disarming")
characterquests.charquestprint(count,datatree,openfile,25884,"Come Hell or High Water")
characterquests.charquestprintfaction(count,datatree,openfile,25885,"What? What? In My Gut...?","alliance")
characterquests.charquestprint(count,datatree,openfile,25887,"Wake of Destruction")
characterquests.charquestprintfaction(count,datatree,openfile,25888,"Decompression","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,25942,"Buy Us Some Time","horde")
characterquests.charquestprintfaction(count,datatree,openfile,25943,"Traveling on Our Stomachs","horde")
characterquests.charquestprintfaction(count,datatree,openfile,25944,"Girding Our Loins","horde")
characterquests.charquestprintfaction(count,datatree,openfile,25946,"Helm's Deep","horde")
characterquests.charquestprintfaction(count,datatree,openfile,25947,"Finders, Keepers","horde")
characterquests.charquestprintfaction(count,datatree,openfile,25948,"Bring It On!","horde")
characterquests.charquestprintfaction(count,datatree,openfile,25949,"Blood and Thunder!","horde")
characterquests.charquestprintfaction(count,datatree,openfile,26000,"Spelunking","horde")
characterquests.charquestprintfaction(count,datatree,openfile,26007,"Debriefing","horde")
characterquests.charquestprintfaction(count,datatree,openfile,26008,"Decompression","horde")
characterquests.charquestprintfaction(count,datatree,openfile,26040,"What? What? In My Gut...?","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27668,"Pay Attention!","horde")
characterquests.charquestprint(count,datatree,openfile,27685,"Good Deed Left Undone")
characterquests.charquestprint(count,datatree,openfile,27687,"An Opened Can of Whoop Gnash")
characterquests.charquestprint(count,datatree,openfile,27699,"Shark Weak")
characterquests.charquestprint(count,datatree,openfile,27708,"The Warden's Time")
characterquests.charquestprint(count,datatree,openfile,27729,"Once More, With Eeling")
characterquests.charquestheader(count,"Vash'jir: Abyssal Depths",openfile)
characterquests.charquestprintfaction(count,datatree,openfile,25950,"Sira'kess Slaying","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,25974,"Sira'kess Slaying","horde")
characterquests.charquestprintfaction(count,datatree,openfile,25975,"Treasure Reclamation","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,25976,"Treasure Reclamation","horde")
characterquests.charquestprintfaction(count,datatree,openfile,25977,"A Standard Day for Azrajar","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,25980,"A Standard Day for Azrajar","horde")
characterquests.charquestprintfaction(count,datatree,openfile,25981,"Those Aren't Masks","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,25982,"Those Aren't Masks","horde")
characterquests.charquestprintfaction(count,datatree,openfile,25983,"Promontory Point","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,25984,"Promontory Point","horde")
characterquests.charquestprintfaction(count,datatree,openfile,25987,"Put It On","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,25988,"Put It On","horde")
characterquests.charquestprintfaction(count,datatree,openfile,26014,"The Brothers Digsong","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,26015,"Phosphora Hunting","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,26017,"A Lure","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,26018,"Coldlights Out","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,26019,"Enormous Eel Egg","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,26021,"The Brothers Digsong 2: Eel-Egg-Trick Boogaloo","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,26056,"The Wavespeaker","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,26057,"The Wavespeaker","horde")
characterquests.charquestprint(count,datatree,openfile,26065,"Free Wil'hai")
characterquests.charquestprintfaction(count,datatree,openfile,26070,"Clearing the Defiled","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,26071,"Clearing the Defiled","horde")
characterquests.charquestprint(count,datatree,openfile,26072,"Into the Totem")
characterquests.charquestprintfaction(count,datatree,openfile,26080,"One Last Favor","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,26086,"Orako","horde")
characterquests.charquestprintfaction(count,datatree,openfile,26087,"Glow-Juice","horde")
characterquests.charquestprintfaction(count,datatree,openfile,26088,"Here Fishie Fishie","horde")
characterquests.charquestprintfaction(count,datatree,openfile,26089,"Die Fishman Die","horde")
characterquests.charquestprintfaction(count,datatree,openfile,26090,"I Brought You This Egg","horde")
characterquests.charquestprintfaction(count,datatree,openfile,26091,"Here Fishie Fishie 2: Eel-Egg-Trick Boogaloo","horde")
characterquests.charquestprintfaction(count,datatree,openfile,26092,"Orako's Report","horde")
characterquests.charquestprint(count,datatree,openfile,26096,"Scalding Shrooms")
characterquests.charquestprintfaction(count,datatree,openfile,26103,"Bio-Fuel","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,26105,"Claim Korthun's End","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,26106,"Fuel-ology 101","alliance")
characterquests.charquestprint(count,datatree,openfile,26111,"... It Will Come")
characterquests.charquestprintfaction(count,datatree,openfile,26121,"Claim Korthun's End","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,26122,"Environmental Awareness","horde")
characterquests.charquestprintfaction(count,datatree,openfile,26124,"Secure Seabrush","horde")
characterquests.charquestprintfaction(count,datatree,openfile,26125,"Secure Seabrush","horde")
characterquests.charquestprintfaction(count,datatree,openfile,26126,"The Perfect Fuel","horde")
characterquests.charquestprint(count,datatree,openfile,26130,"Unplug L'ghorek")
characterquests.charquestprintfaction(count,datatree,openfile,26132,"Fiends from the Netherworld","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,26133,"Fiends from the Netherworld","horde")
characterquests.charquestprint(count,datatree,openfile,26140,"Communing with the Ancient")
characterquests.charquestprint(count,datatree,openfile,26141,"Runestones of Binding")
characterquests.charquestprint(count,datatree,openfile,26142,"Ascend No More!")
characterquests.charquestprint(count,datatree,openfile,26143,"All that Rises")
characterquests.charquestprintfaction(count,datatree,openfile,26144,"Prisoners","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,26149,"Prisoners","horde")
characterquests.charquestprint(count,datatree,openfile,26154,"Twilight Extermination")
characterquests.charquestprintfaction(count,datatree,openfile,26181,"Back to Darkbreak Cove","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,26182,"Back to the Tenebrous Cavern","horde")
characterquests.charquestprintfaction(count,datatree,openfile,26193,"Defending the Rift","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,26194,"Defending the Rift","horde")
def z_82_90_Deepholm(count,datatree,openfile):
characterquests.charquestheader(count,"82-90: Deepholm: Intro",openfile)
characterquests.charquestprintfaction(count,datatree,openfile,27722,"Warchief's Command: Deepholm!","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27722,"Hero's Call: Deepholm!","alliance")
characterquests.charquestprint(count,datatree,openfile,27203,"The Maelstrom")
characterquests.charquestprint(count,datatree,openfile,27123,"Deepholm, Realm of Earth")
characterquests.charquestheader(count,"82-90: Deepholm: Upper World Pillar Fragment",openfile)
characterquests.charquestprint(count,datatree,openfile,26245,"Gunship Down")
characterquests.charquestprint(count,datatree,openfile,26246,"Captain's Log")
characterquests.charquestprint(count,datatree,openfile,27136,"Elemental Energy")
characterquests.charquestprint(count,datatree,openfile,26244,"The Earth Claims All")
characterquests.charquestprint(count,datatree,openfile,26247,"Diplomacy First")
characterquests.charquestprint(count,datatree,openfile,26248,"All Our Friends Are Dead")
characterquests.charquestprint(count,datatree,openfile,26249,"The Admiral's Cabin")
characterquests.charquestprint(count,datatree,openfile,26427,"Without a Captain or Crew")
characterquests.charquestprint(count,datatree,openfile,26251,"Take No Prisoners")
characterquests.charquestprint(count,datatree,openfile,26250,"On Second Thought, Take One Prisoner")
characterquests.charquestprint(count,datatree,openfile,26254,"Some Spraining to Do")
characterquests.charquestprint(count,datatree,openfile,26255,"Return to the Temple of Earth")
characterquests.charquestprint(count,datatree,openfile,26258,"Deathwing's Fall")
characterquests.charquestprint(count,datatree,openfile,26259,"Blood of the Earthwarder")
characterquests.charquestprint(count,datatree,openfile,26256,"Bleed the Bloodshaper")
characterquests.charquestprint(count,datatree,openfile,26261,"Question the Slaves")
characterquests.charquestprint(count,datatree,openfile,26260,"The Forgemaster's Log")
characterquests.charquestprint(count,datatree,openfile,27007,"Silvermarsh Rendezvous")
characterquests.charquestprint(count,datatree,openfile,27010,"Quicksilver Submersion")
characterquests.charquestprint(count,datatree,openfile,27100,"Twilight Research")
characterquests.charquestprint(count,datatree,openfile,27101,"Maziel's Revelation")
characterquests.charquestprint(count,datatree,openfile,27102,"Maziel's Ascendancy")
characterquests.charquestprint(count,datatree,openfile,27061,"The Twilight Overlook")
characterquests.charquestprint(count,datatree,openfile,26766,"Big Game, Big Bait")
characterquests.charquestprint(count,datatree,openfile,26768,"To Catch a Dragon")
characterquests.charquestprint(count,datatree,openfile,26771,"Testing the Trap")
characterquests.charquestprint(count,datatree,openfile,26857,"Abyssion's Minions")
characterquests.charquestprint(count,datatree,openfile,26861,"Block the Gates")
characterquests.charquestprint(count,datatree,openfile,26876,"The World Pillar Fragment")
characterquests.charquestheader(count,"82-90: Deepholm: Middle World Pillar Fragment",openfile)
characterquests.charquestprint(count,datatree,openfile,26409,"Where's Goldmine?")
characterquests.charquestprint(count,datatree,openfile,26410,"Explosive Bonding Compound")
characterquests.charquestprint(count,datatree,openfile,27135,"Something that Burns")
characterquests.charquestprint(count,datatree,openfile,26411,"Apply and Flash Dry")
characterquests.charquestprint(count,datatree,openfile,26413,"Take Him to the Earthcaller")
characterquests.charquestprint(count,datatree,openfile,26484,"To Stonehearth's Aid")
characterquests.charquestprint(count,datatree,openfile,27931,"The Quaking Fields")
characterquests.charquestprint(count,datatree,openfile,27932,"The Axe of Earthly Sundering")
characterquests.charquestprint(count,datatree,openfile,27933,"Elemental Ore")
characterquests.charquestprint(count,datatree,openfile,27934,"One With the Ground")
characterquests.charquestprint(count,datatree,openfile,27935,"Bring Down the Avalanche")
characterquests.charquestprint(count,datatree,openfile,26499,"Stonefather's Boon")
characterquests.charquestprint(count,datatree,openfile,26501,"Sealing the Way")
characterquests.charquestprint(count,datatree,openfile,26500,"We're Surrounded")
characterquests.charquestprint(count,datatree,openfile,26502,"Thunder Stones")
characterquests.charquestprint(count,datatree,openfile,26537,"Shatter Them!")
characterquests.charquestprint(count,datatree,openfile,26564,"Fixer Upper")
characterquests.charquestprint(count,datatree,openfile,26591,"Battlefront Triage")
characterquests.charquestprint(count,datatree,openfile,26625,"Troggzor the Earthinator")
characterquests.charquestprint(count,datatree,openfile,27126,"Rush Delivery")
characterquests.charquestprint(count,datatree,openfile,26632,"Close Escort")
characterquests.charquestprint(count,datatree,openfile,26755,"Keep Them off the Front")
characterquests.charquestprint(count,datatree,openfile,26762,"Reactivate the Constructs")
characterquests.charquestprint(count,datatree,openfile,26770,"Mystic Masters")
characterquests.charquestprint(count,datatree,openfile,26834,"Down Into the Chasm")
characterquests.charquestprint(count,datatree,openfile,26791,"Sprout No More")
characterquests.charquestprint(count,datatree,openfile,26792,"Fungal Monstrosities")
characterquests.charquestprint(count,datatree,openfile,26835,"A Slight Problem")
characterquests.charquestprint(count,datatree,openfile,26836,"Rescue the Stonefather... and Flint")
characterquests.charquestprint(count,datatree,openfile,27937,"The Hero Returns")
characterquests.charquestprint(count,datatree,openfile,27938,"The Middle Fragment")
characterquests.charquestheader(count,"82-90: Deepholm: Lower World Pillar Fragment",openfile)
characterquests.charquestprint(count,datatree,openfile,26326,"The Very Earth Beneath Our Feet")
characterquests.charquestprint(count,datatree,openfile,26312,"Crumbling Defenses")
characterquests.charquestprint(count,datatree,openfile,26313,"Core of Our Troubles")
characterquests.charquestprint(count,datatree,openfile,26314,"On Even Ground")
characterquests.charquestprint(count,datatree,openfile,26315,"Imposing Confrontation")
characterquests.charquestprint(count,datatree,openfile,26328,"Rocky Relations")
characterquests.charquestprint(count,datatree,openfile,26375,"Loose Stones")
characterquests.charquestprint(count,datatree,openfile,26376,"Hatred Runs Deep")
characterquests.charquestprint(count,datatree,openfile,26377,"Unsolid Ground")
characterquests.charquestprint(count,datatree,openfile,26426,"Violent Gale")
characterquests.charquestprint(count,datatree,openfile,26869,"Depth of the Depths")
characterquests.charquestprint(count,datatree,openfile,26871,"A Rock Amongst Many")
characterquests.charquestprint(count,datatree,openfile,26436,"Entrenched")
characterquests.charquestprint(count,datatree,openfile,26437,"Making Things Crystal Clear")
characterquests.charquestprint(count,datatree,openfile,26438,"Intervention")
characterquests.charquestprint(count,datatree,openfile,26439,"Putting the Pieces Together")
characterquests.charquestprint(count,datatree,openfile,28869,"Pebble")
characterquests.charquestprint(count,datatree,openfile,26440,"Clingy")
characterquests.charquestprint(count,datatree,openfile,26441,"So Big, So Round...")
characterquests.charquestprint(count,datatree,openfile,26575,"Rock Bottom")
characterquests.charquestprint(count,datatree,openfile,26507,"Petrified Delicacies")
characterquests.charquestprint(count,datatree,openfile,26576,"Steady Hand")
characterquests.charquestprint(count,datatree,openfile,26656,"Don't. Stop. Moving.")
characterquests.charquestprint(count,datatree,openfile,26657,"Hard Falls")
characterquests.charquestprint(count,datatree,openfile,26658,"Fragile Values")
characterquests.charquestprint(count,datatree,openfile,26659,"Resonating Blow")
characterquests.charquestprint(count,datatree,openfile,26577,"Rocky Upheaval")
characterquests.charquestprint(count,datatree,openfile,26578,"Doomshrooms")
characterquests.charquestprint(count,datatree,openfile,26579,"Gone Soft")
characterquests.charquestprint(count,datatree,openfile,26580,"Familiar Intruders")
characterquests.charquestprint(count,datatree,openfile,26581,"A Head Full of Wind")
characterquests.charquestprint(count,datatree,openfile,26582,"Unnatural Causes")
characterquests.charquestprint(count,datatree,openfile,26583,"Wrath of the Fungalmancer")
characterquests.charquestprint(count,datatree,openfile,26584,"Shaken and Stirred")
characterquests.charquestprint(count,datatree,openfile,26585,"Corruption Destruction")
characterquests.charquestprint(count,datatree,openfile,26750,"At the Stonemother's Call")
characterquests.charquestprint(count,datatree,openfile,26752,"Audience with the Stonemother")
characterquests.charquestprint(count,datatree,openfile,26827,"Rallying the Earthen Ring")
characterquests.charquestprint(count,datatree,openfile,26828,"Our Part of the Bargain")
characterquests.charquestprint(count,datatree,openfile,26829,"The Stone March")
characterquests.charquestprint(count,datatree,openfile,26832,"Therazane's Mercy")
characterquests.charquestprint(count,datatree,openfile,26831,"The Twilight Flight")
characterquests.charquestprint(count,datatree,openfile,26833,"Word In Stone")
characterquests.charquestprint(count,datatree,openfile,26875,"Undying Twilight")
characterquests.charquestprint(count,datatree,openfile,26971,"The Binding")
characterquests.charquestprint(count,datatree,openfile,26709,"The Stone Throne")
characterquests.charquestheaderfaction(count,"82-90: Deepholm: To Uldum","alliance",openfile)
characterquests.charquestprint(count,datatree,openfile,27952,"The Explorers")
characterquests.charquestprint(count,datatree,openfile,27004,"The Twilight Plot")
characterquests.charquestprint(count,datatree,openfile,27006,"Fly Over")
characterquests.charquestprint(count,datatree,openfile,27040,"Decryption Made Easy")
characterquests.charquestprint(count,datatree,openfile,27042,"Fight Fire and Water and Air with...")
characterquests.charquestprint(count,datatree,openfile,27058,"The Wrong Sequence")
characterquests.charquestprint(count,datatree,openfile,28292,"That's No Pyramid!")
characterquests.charquestheaderfaction(count,"82-90: Deepholm: To Uldum","horde",openfile)
characterquests.charquestprint(count,datatree,openfile,27953,"The Reliquary")
characterquests.charquestprint(count,datatree,openfile,27005,"The Twilight Plot")
characterquests.charquestprint(count,datatree,openfile,27008,"Fly Over")
characterquests.charquestprint(count,datatree,openfile,27041,"Decryption Made Easy")
characterquests.charquestprint(count,datatree,openfile,27043,"Fight Fire and Water and Air with...")
characterquests.charquestprint(count,datatree,openfile,27059,"The Wrong Sequence")
characterquests.charquestprint(count,datatree,openfile,28293,"That's No Pyramid!")
def z_83_90_Uldum(count,datatree,openfile):
characterquests.charquestheader(count,"83-90: Uldum (Unsorted)",openfile)
characterquests.charquestprint(count,datatree,openfile,27003,"Easy Money")
characterquests.charquestprint(count,datatree,openfile,27141,"Premature Explosionation")
characterquests.charquestprint(count,datatree,openfile,27176,"Just the Tip")
characterquests.charquestprint(count,datatree,openfile,27179,"Field Work")
characterquests.charquestprint(count,datatree,openfile,27187,"Do the World a Favor")
characterquests.charquestprint(count,datatree,openfile,27196,"On to Something")
characterquests.charquestprint(count,datatree,openfile,27431,"Tipping the Balance")
characterquests.charquestprint(count,datatree,openfile,27511,"The Thrill of Discovery")
characterquests.charquestprint(count,datatree,openfile,27517,"Be Prepared")
characterquests.charquestprint(count,datatree,openfile,27519,"Under the Choking Sands")
characterquests.charquestprint(count,datatree,openfile,27520,"Minions of Al'Akir")
characterquests.charquestprint(count,datatree,openfile,27541,"Lessons From the Past")
characterquests.charquestprint(count,datatree,openfile,27549,"By the Light of the Stars")
characterquests.charquestprint(count,datatree,openfile,27595,"The Prophet Hadassi")
characterquests.charquestprint(count,datatree,openfile,27602,"The Prophet's Dying Words")
characterquests.charquestprint(count,datatree,openfile,27623,"Colossal Guardians")
characterquests.charquestprint(count,datatree,openfile,27624,"After the Fall")
characterquests.charquestprint(count,datatree,openfile,27627,"Just a Fancy Cockroach")
characterquests.charquestprint(count,datatree,openfile,27628,"Send Word to Phaoris")
characterquests.charquestprint(count,datatree,openfile,27630,"The High Priest's Vote")
characterquests.charquestprint(count,datatree,openfile,27631,"The High Commander's Vote")
characterquests.charquestprint(count,datatree,openfile,27632,"Tanotep's Son")
characterquests.charquestprint(count,datatree,openfile,27669,"Do the Honors")
characterquests.charquestprint(count,datatree,openfile,27706,"The Scepter of Orsis")
characterquests.charquestprint(count,datatree,openfile,27707,"Neferset Prison")
characterquests.charquestprint(count,datatree,openfile,27738,"The Pit of Scales")
characterquests.charquestprint(count,datatree,openfile,27748,"Fortune and Glory")
characterquests.charquestprint(count,datatree,openfile,27755,"The Curse of the Tombs")
characterquests.charquestprint(count,datatree,openfile,27760,"Artificial Intelligence")
characterquests.charquestprint(count,datatree,openfile,27761,"A Disarming Distraction")
characterquests.charquestprint(count,datatree,openfile,27777,"Core Access Codes")
characterquests.charquestprint(count,datatree,openfile,27778,"Hacking the Wibson")
characterquests.charquestprint(count,datatree,openfile,27779,"Gnomebliteration")
characterquests.charquestprint(count,datatree,openfile,27836,"Stopping the Spread")
characterquests.charquestprint(count,datatree,openfile,27837,"Trespassers in the Water")
characterquests.charquestprint(count,datatree,openfile,27838,"The Root of the Corruption")
characterquests.charquestprint(count,datatree,openfile,27839,"Ancient Weapons")
characterquests.charquestprint(count,datatree,openfile,27899,"That Gleam in his Eye")
characterquests.charquestprint(count,datatree,openfile,27900,"I've Got This Guy")
characterquests.charquestprint(count,datatree,openfile,27901,"They Don't Know What They've Got Here")
characterquests.charquestprint(count,datatree,openfile,27903,"Ignition")
characterquests.charquestprint(count,datatree,openfile,27905,"Tailgunner!")
characterquests.charquestprint(count,datatree,openfile,27922,"Traitors!")
characterquests.charquestprint(count,datatree,openfile,27923,"Smoke in Their Eyes")
characterquests.charquestprint(count,datatree,openfile,27924,"Budd's Plan")
characterquests.charquestprint(count,datatree,openfile,27926,"Eastern Hospitality")
characterquests.charquestprint(count,datatree,openfile,27928,"A Favor for the Furrier")
characterquests.charquestprint(count,datatree,openfile,27939,"The Desert Fox")
characterquests.charquestprint(count,datatree,openfile,27941,"Fashionism")
characterquests.charquestprint(count,datatree,openfile,27942,"Idolatry")
characterquests.charquestprint(count,datatree,openfile,27943,"Angered Spirits")
characterquests.charquestprint(count,datatree,openfile,27950,"Gobbles!")
characterquests.charquestprint(count,datatree,openfile,27969,"Make Yourself Useful")
characterquests.charquestprint(count,datatree,openfile,27990,"Battlezone")
characterquests.charquestprint(count,datatree,openfile,27993,"Take it to 'Em!")
characterquests.charquestprint(count,datatree,openfile,28002,"Crisis Management")
characterquests.charquestprint(count,datatree,openfile,28105,"Kavem the Callous")
characterquests.charquestprint(count,datatree,openfile,28112,"Escape From the Lost City")
characterquests.charquestprint(count,datatree,openfile,28132,"Efficient Excavations")
characterquests.charquestprint(count,datatree,openfile,28134,"Impending Retribution")
characterquests.charquestprint(count,datatree,openfile,28135,"Al'Akir's Vengeance")
characterquests.charquestprint(count,datatree,openfile,28141,"Relics of the Sun King")
characterquests.charquestprint(count,datatree,openfile,28145,"Venomblood Antidote")
characterquests.charquestprint(count,datatree,openfile,28187,"Missed Me By Zhat Much!")
characterquests.charquestprint(count,datatree,openfile,28193,"Lockdown!")
characterquests.charquestprint(count,datatree,openfile,28194,"The Great Escape")
characterquests.charquestprint(count,datatree,openfile,28195,"Sending a Message")
characterquests.charquestprint(count,datatree,openfile,28198,"The Weakest Link")
characterquests.charquestprint(count,datatree,openfile,28200,"The Element of Supplies")
characterquests.charquestprint(count,datatree,openfile,28201,"Ploughshares to Swords")
characterquests.charquestprint(count,datatree,openfile,28210,"Shaping Up")
characterquests.charquestprint(count,datatree,openfile,28267,"Firing Squad")
characterquests.charquestprint(count,datatree,openfile,28269,"Meet Me In Vir'sar")
characterquests.charquestprint(count,datatree,openfile,28271,"Reduced Productivity")
characterquests.charquestprint(count,datatree,openfile,28272,"Missing Pieces")
characterquests.charquestprint(count,datatree,openfile,28273,"Friend of a Friend")
characterquests.charquestprint(count,datatree,openfile,28274,"Two Tents")
characterquests.charquestprint(count,datatree,openfile,28276,"Salhet's Secret")
characterquests.charquestprint(count,datatree,openfile,28277,"Salhet the Tactician")
characterquests.charquestprint(count,datatree,openfile,28291,"Return to Camp")
characterquests.charquestprint(count,datatree,openfile,28350,"Master Trapper")
characterquests.charquestprint(count,datatree,openfile,28351,"Unlimited Potential")
characterquests.charquestprint(count,datatree,openfile,28352,"Camel Tow")
characterquests.charquestprint(count,datatree,openfile,28353,"Jonesy Sent For You")
characterquests.charquestprint(count,datatree,openfile,28363,"Stirred the Hornet's Nest")
characterquests.charquestprint(count,datatree,openfile,28367,"Shroud of the Makers")
characterquests.charquestprint(count,datatree,openfile,28376,"Myzerian's Head")
characterquests.charquestprint(count,datatree,openfile,28402,"Schnottz So Fast")
characterquests.charquestprint(count,datatree,openfile,28403,"Bad Datas")
characterquests.charquestprint(count,datatree,openfile,28404,"I'll Do It By Hand")
characterquests.charquestprint(count,datatree,openfile,28482,"Sullah's Gift")
characterquests.charquestprint(count,datatree,openfile,28497,"Fire From the Sky")
characterquests.charquestprint(count,datatree,openfile,28602,"Be Prepared")
characterquests.charquestprint(count,datatree,openfile,28621,"Put That Baby in the Cradle!")
characterquests.charquestprint(count,datatree,openfile,28622,"Three if by Air")
characterquests.charquestprint(count,datatree,openfile,28633,"The Coffer of Promise")
characterquests.charquestprint(count,datatree,openfile,27629,"The Vizier's Vote")
characterquests.charquestprint(count,datatree,openfile,28480,"Lieutenants of Darkness")
characterquests.charquestprint(count,datatree,openfile,28483,"Bleeding the Enemy")
characterquests.charquestprint(count,datatree,openfile,28486,"Salhet's Gambit")
characterquests.charquestprint(count,datatree,openfile,28498,"The Secret of Nahom")
characterquests.charquestprint(count,datatree,openfile,28499,"Punish the Trespassers")
characterquests.charquestprint(count,datatree,openfile,28500,"The Cypher of Keset")
characterquests.charquestprint(count,datatree,openfile,28501,"The Defense of Nahom")
characterquests.charquestprint(count,datatree,openfile,28502,"The Bandit Warlord")
characterquests.charquestprint(count,datatree,openfile,28520,"The Fall of Neferset City")
characterquests.charquestprint(count,datatree,openfile,28533,"The High Council's Decision")
characterquests.charquestprint(count,datatree,openfile,28561,"Nahom Must Hold")
characterquests.charquestprint(count,datatree,openfile,28611,"The Defilers' Ritual")
characterquests.charquestprint(count,datatree,openfile,28623,"The Push Westward")
def z_84_90_Twilight_Highlands(count,datatree,openfile):
characterquests.charquestheaderfaction(count,"84-90: Twilight Highlands: Intro","horde",openfile)
characterquests.charquestprint(count,datatree,openfile,28909,"Sauranok Will Point the Way")
characterquests.charquestprint(count,datatree,openfile,26311,"Unfamiliar Waters")
characterquests.charquestprint(count,datatree,openfile,28717,"Warchief's Command: Twilight Highlands!")
characterquests.charquestprint(count,datatree,openfile,26293,"Machines of War")
characterquests.charquestprint(count,datatree,openfile,26294,"Weapons of Mass Dysfunction")
characterquests.charquestprint(count,datatree,openfile,26324,"Where Is My Warfleet?")
characterquests.charquestprint(count,datatree,openfile,26374,"Ready the Ground Troops")
characterquests.charquestprint(count,datatree,openfile,26335,"Ready the Navy")
characterquests.charquestprint(count,datatree,openfile,26337,"Beating the Market")
characterquests.charquestprint(count,datatree,openfile,26358,"Ready the Air Force")
characterquests.charquestprint(count,datatree,openfile,26361,"Smoot's Samophlange")
characterquests.charquestprint(count,datatree,openfile,26372,"Pre-Flight Checklist")
characterquests.charquestprint(count,datatree,openfile,28849,"Twilight Skies")
characterquests.charquestprint(count,datatree,openfile,26388,"Twilight Skies")
characterquests.charquestheaderfaction(count,"84-90: Twilight Highlands: The Dragonmaw Clan and the Horde","horde",openfile)
characterquests.charquestprint(count,datatree,openfile,26539,"Stalled Negotiations")
characterquests.charquestprint(count,datatree,openfile,26539,"Stalled Negotiations")
characterquests.charquestprint(count,datatree,openfile,26549,"Madness")
characterquests.charquestprint(count,datatree,openfile,26608,"Negotiations Terminated")
characterquests.charquestprint(count,datatree,openfile,26538,"Emergency Aid")
characterquests.charquestprint(count,datatree,openfile,26540,"Dangerous Compassion")
characterquests.charquestprint(count,datatree,openfile,26619,"You Say You Want a Revolution")
characterquests.charquestprint(count,datatree,openfile,26621,"Insurrection")
characterquests.charquestprint(count,datatree,openfile,26622,"Death to Mor'ghor")
characterquests.charquestprint(count,datatree,openfile,26786,"Securing the Beach Head")
characterquests.charquestprint(count,datatree,openfile,26784,"Muddied Waters")
characterquests.charquestprint(count,datatree,openfile,26788,"Cementing Our Victory")
characterquests.charquestprint(count,datatree,openfile,26798,"Saurfang Will be Pleased")
characterquests.charquestprint(count,datatree,openfile,26830,"Traitor's Bait")
characterquests.charquestprint(count,datatree,openfile,26840,"Return to the Highlands")
characterquests.charquestheaderfaction(count,"84-90: Twilight Highlands: The Southern Flank","horde",openfile)
characterquests.charquestprint(count,datatree,openfile,27607,"The Southern Flank")
characterquests.charquestprint(count,datatree,openfile,27610,"Scouting the Shore")
characterquests.charquestprint(count,datatree,openfile,27611,"Blood on the Sand")
characterquests.charquestprint(count,datatree,openfile,27622,"Mo' Better Shredder")
characterquests.charquestheaderfaction(count,"84-90: Twilight Highlands: Krazzworks","horde",openfile)
characterquests.charquestprint(count,datatree,openfile,28583,"Krazzworks")
characterquests.charquestprint(count,datatree,openfile,28584,"Quality Construction")
characterquests.charquestprint(count,datatree,openfile,28586,"Pool Pony Rescue")
characterquests.charquestprint(count,datatree,openfile,28588,"Wildhammer Infestation")
characterquests.charquestprint(count,datatree,openfile,28589,"Everything But the Kitchen Sink")
characterquests.charquestprint(count,datatree,openfile,28590,"Reprisal")
characterquests.charquestprint(count,datatree,openfile,28591,"Off The Wall")
characterquests.charquestprint(count,datatree,openfile,28592,"Parting Packages")
characterquests.charquestprint(count,datatree,openfile,28593,"Of Utmost Importance")
characterquests.charquestprint(count,datatree,openfile,28594,"Highbank, Crybank")
characterquests.charquestprint(count,datatree,openfile,28595,"Krazz Works!")
characterquests.charquestheaderfaction(count,"84-90: Twilight Highlands: The Northern Flank","horde",openfile)
characterquests.charquestprint(count,datatree,openfile,27583,"The Northern Flank")
characterquests.charquestprint(count,datatree,openfile,27584,"Blood in the Surf")
characterquests.charquestprint(count,datatree,openfile,27586,"Shells on the Sea Shore")
characterquests.charquestprint(count,datatree,openfile,27606,"Blast Him!")
characterquests.charquestheaderfaction(count,"84-90: Twilight Highlands: Bloodgulch","horde",openfile)
characterquests.charquestprint(count,datatree,openfile,27690,"Narkrall, the Drake-Tamer")
characterquests.charquestprint(count,datatree,openfile,27751,"Crushing the Wildhammer")
characterquests.charquestprint(count,datatree,openfile,27929,"Drag 'em Down")
characterquests.charquestprint(count,datatree,openfile,27747,"Total War")
characterquests.charquestprint(count,datatree,openfile,27750,"War Forage")
characterquests.charquestprint(count,datatree,openfile,27947,"A Vision of Twilight")
characterquests.charquestprint(count,datatree,openfile,27951,"We All Must Sacrifice")
characterquests.charquestprint(count,datatree,openfile,27954,"The Eyes Have It")
characterquests.charquestprint(count,datatree,openfile,27955,"Eye Spy")
characterquests.charquestprint(count,datatree,openfile,28041,"Bait and Throttle")
characterquests.charquestprint(count,datatree,openfile,28043,"How to Maim Your Dragon")
characterquests.charquestprint(count,datatree,openfile,28123,"The Demon Chain")
characterquests.charquestprint(count,datatree,openfile,28133,"Fury Unbound")
characterquests.charquestprint(count,datatree,openfile,28147,"Purple is Your Color")
characterquests.charquestprint(count,datatree,openfile,28151,"Dressed to Kill")
characterquests.charquestprint(count,datatree,openfile,28149,"Whispers in the Wind")
characterquests.charquestprint(count,datatree,openfile,28166,"Thog's Nightlight")
characterquests.charquestprint(count,datatree,openfile,28170,"Night Terrors")
characterquests.charquestheader(count,"84-90: Twilight Highlands: The Maw of Madness",openfile)
characterquests.charquestprintfaction(count,datatree,openfile,27945,"Paint it Black","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27375,"The Weeping Wound","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27374,"The Maw of Madness","alliance")
characterquests.charquestprint(count,datatree,openfile,27299,"Torn Ground")
characterquests.charquestprint(count,datatree,openfile,27300,"Pushing Back")
characterquests.charquestprint(count,datatree,openfile,27302,"Simple Solutions")
characterquests.charquestprint(count,datatree,openfile,27301,"Unbroken")
characterquests.charquestprint(count,datatree,openfile,27303,"Mercy for the Bound")
characterquests.charquestprint(count,datatree,openfile,27376,"The Maw of Iso'rath")
characterquests.charquestprint(count,datatree,openfile,27377,"Devoured")
characterquests.charquestprint(count,datatree,openfile,27378,"The Worldbreaker")
characterquests.charquestprint(count,datatree,openfile,27379,"The Terrors of Iso'rath")
characterquests.charquestprint(count,datatree,openfile,27380,"Nightmare")
characterquests.charquestheader(count,"84-90: Twilight Highlands: Vermillion Redoubt",openfile)
characterquests.charquestprintfaction(count,datatree,openfile,27485,"Warm Welcome","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27486,"Warm Welcome","horde")
characterquests.charquestprint(count,datatree,openfile,27504,"Even Dragons Bleed")
characterquests.charquestprint(count,datatree,openfile,27505,"Draconic Mending")
characterquests.charquestprint(count,datatree,openfile,27506,"Life from Death")
characterquests.charquestprint(count,datatree,openfile,27564,"In Defense of the Redoubt")
characterquests.charquestprint(count,datatree,openfile,27507,"Encroaching Twilight")
characterquests.charquestprint(count,datatree,openfile,27508,"Far from the Nest")
characterquests.charquestprint(count,datatree,openfile,27509,"Breach in the Defenses")
characterquests.charquestprintfaction(count,datatree,openfile,28101,"Mathias' Command","alliance")
characterquests.charquestprint(count,datatree,openfile,27576,"Patchwork Command")
characterquests.charquestprintfaction(count,datatree,openfile,28091,"Easy Pickings","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,28103,"Easy Pickings","horde")
characterquests.charquestprintfaction(count,datatree,openfile,28090,"Precious Goods","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,28104,"Precious Goods","horde")
characterquests.charquestprintfaction(count,datatree,openfile,28097,"The Gates of Grim Batol","horde")
characterquests.charquestprintfaction(count,datatree,openfile,28108,"If The Key Fits","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,28092,"If The Key Fits","horde")
characterquests.charquestprintfaction(count,datatree,openfile,28107,"Paving the Way","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,28094,"Paving the Way","horde")
characterquests.charquestprintfaction(count,datatree,openfile,28109,"Pressing Forward","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,28093,"Pressing Forward","horde")
characterquests.charquestprint(count,datatree,openfile,28712,"Enter the Dragon Queen")
characterquests.charquestprint(count,datatree,openfile,28758,"Battle of Life and Death")
characterquests.charquestprint(count,datatree,openfile,28171,"And the Sky Streaked Red")
characterquests.charquestprint(count,datatree,openfile,28191,"A Fitting End")
characterquests.charquestprint(count,datatree,openfile,28173,"Blackout")
characterquests.charquestprint(count,datatree,openfile,28175,"Shining Through the Dark")
characterquests.charquestprint(count,datatree,openfile,28176,"Following the Young Home")
characterquests.charquestprint(count,datatree,openfile,28247,"Last of Her Kind")
characterquests.charquestheader(count,"84-90: Twilight Highlands: Twilight Rising",openfile)
characterquests.charquestprintfaction(count,datatree,openfile,28248,"Victors' Point","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,28249,"Crushblow","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27492,"Ogres & Ettins","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27493,"Ogres & Ettins","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27496,"Call in the Artillery","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27497,"Call in the Artillery","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27490,"SI:7 Drop","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27491,"Kor'kron Drop","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27494,"Move the Mountain","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27495,"Move the Mountain","horde")
characterquests.charquestprint(count,datatree,openfile,27498,"Signal the Attack")
characterquests.charquestprint(count,datatree,openfile,27499,"Signal the Attack")
characterquests.charquestprintfaction(count,datatree,openfile,27500,"Four Heads are Better than None","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27501,"Four Heads are Better than None","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27502,"Up to the Citadel","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27503,"Up to the Citadel","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27636,"Just You and Mathias","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27638,"Just You and Garona","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27652,"Dark Assassins","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27653,"Dark Assassins","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27654,"Bring the Hammer Down","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27655,"Bring the Hammer Down","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27688,"Distract Them for Me","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27689,"Distract Them for Me","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27695,"The Elementium Axe","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27696,"The Elementium Axe","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27700,"Dragon, Unchained","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27701,"Dragon, Unchained","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27702,"Coup de Grace","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27703,"Coup de Grace","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27657,"Help from the Earthcaller","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27658,"Help from the Earthcaller","horde")
characterquests.charquestprint(count,datatree,openfile,27660,"Spirit of the Loch")
characterquests.charquestprint(count,datatree,openfile,27659,"Portal Overload")
characterquests.charquestprint(count,datatree,openfile,27662,"Unbinding")
characterquests.charquestprint(count,datatree,openfile,27661,"Fire the Cannon")
characterquests.charquestprintfaction(count,datatree,openfile,27719,"Water of Life","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27798,"Water of Life","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27711,"Back to the Elementium Depths","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27712,"Back to the Elementium Depths","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27720,"Mr. Goldmine's Wild Ride","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,28885,"Mr. Goldmine's Wild Ride","horde")
characterquests.charquestprint(count,datatree,openfile,27742,"A Little on the Side")
characterquests.charquestprint(count,datatree,openfile,27743,"While We're Here")
characterquests.charquestprint(count,datatree,openfile,27744,"Rune Ruination")
characterquests.charquestprint(count,datatree,openfile,27745,"A Fiery Reunion")
characterquests.charquestprint(count,datatree,openfile,27782,"Mathias Needs You")
characterquests.charquestprint(count,datatree,openfile,27783,"Garona Needs You")
characterquests.charquestprintfaction(count,datatree,openfile,27784,"The Hammer of Twilight","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27786,"The Hammer of Twilight","horde")
characterquests.charquestprintfaction(count,datatree,openfile,27787,"Skullcrusher the Mountain","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27788,"Skullcrusher the Mountain","horde")
characterquests.charquestheader(count,"84-90: Twilight Highlands: The Crucible of Carnage",openfile)
characterquests.charquestprint(count,datatree,openfile,28038,"Blood in the Highlands")
characterquests.charquestprint(count,datatree,openfile,27861,"The Crucible of Carnage: The Bloodeye Bruiser!")
characterquests.charquestprint(count,datatree,openfile,27862,"The Crucible of Carnage: The Bloodeye Bruiser!")
characterquests.charquestprint(count,datatree,openfile,27863,"The Crucible of Carnage: The Bloodeye Bruiser!")
characterquests.charquestprintfaction(count,datatree,openfile,27864,"The Crucible of Carnage: The Deadly Dragonmaw!","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,27865,"The Crucible of Carnage: The Wayward Wildhammer!","horde")
characterquests.charquestprint(count,datatree,openfile,27866,"The Crucible of Carnage: Calder's Creation!")
characterquests.charquestprint(count,datatree,openfile,27867,"The Crucible of Carnage: The Earl of Evisceration!")
characterquests.charquestprint(count,datatree,openfile,27868,"The Crucible of Carnage: The Twilight Terror!")
def z_85_Molten_Front(count,datatree,openfile):
characterquests.charquestheader(count,"85: Molten Front: The Invasion",openfile)
characterquests.charquestprintfaction(count,datatree,openfile,29391,"Guardians of Hyjal: Call of the Ancients","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,29390,"Guardians of Hyjal: Call of the Ancients","horde")
characterquests.charquestprintfaction(count,datatree,openfile,29387,"Guardians of Hyjal: Firelands Invasion!","alliance")
characterquests.charquestprintfaction(count,datatree,openfile,29388,"Guardians of Hyjal: Firelands Invasion!","horde")
characterquests.charquestprint(count,datatree,openfile,29145,"Opening the Door")
characterquests.charquestprint(count,datatree,openfile,29195,"A Ritual of Flame")
characterquests.charquestprint(count,datatree,openfile,29196,"To the Sanctuary!")
characterquests.charquestprint(count,datatree,openfile,29197,"Caught Unawares")
characterquests.charquestprint(count,datatree,openfile,29198,"The Sanctuary Must Not Fall")
characterquests.charquestheader(count,"85: Molten Front: The Sanctuary of Malorn",openfile)
characterquests.charquestprint(count,datatree,openfile,29199,"Calling for Reinforcements")
characterquests.charquestprint(count,datatree,openfile,29200,"Leyara")
characterquests.charquestprint(count,datatree,openfile,29201,"Through the Gates of Hell")
characterquests.charquestheader(count,"85: Molten Front: Druids of the Talon",openfile)
characterquests.charquestprint(count,datatree,openfile,29181,"Druids of the Talon")
characterquests.charquestprint(count,datatree,openfile,29182,"Flight of the Storm Crows")
characterquests.charquestprint(count,datatree,openfile,29272,"Need... Water... Badly...")
characterquests.charquestheader(count,"85: Molten Front: The Shadow Wardens",openfile)
characterquests.charquestprint(count,datatree,openfile,29214,"The Shadow Wardens")
characterquests.charquestprint(count,datatree,openfile,29215,"The Hunt Begins")
characterquests.charquestprint(count,datatree,openfile,29245,"The Mysterious Seed")
characterquests.charquestprint(count,datatree,openfile,29249,"Planting Season")
characterquests.charquestprint(count,datatree,openfile,29254,"Little Lasher")
characterquests.charquestheader(count,"85: Molten Front: Additional Armaments",openfile)
characterquests.charquestprint(count,datatree,openfile,29281,"Additional Armaments")
characterquests.charquestprint(count,datatree,openfile,29282,"Well Armed")
characterquests.charquestheader(count,"85: Molten Front: Calling the Ancients",openfile)
characterquests.charquestprint(count,datatree,openfile,29283,"Calling the Ancients")
characterquests.charquestprint(count,datatree,openfile,29284,"Aid of the Ancients")
characterquests.charquestheader(count,"85: Molten Front: Filling the Moonwell",openfile)
characterquests.charquestprint(count,datatree,openfile,29279,"Filling the Moonwell")
characterquests.charquestprint(count,datatree,openfile,29280,"Nourishing Waters")
characterquests.charquestprint(count,datatree,openfile,29203,"Into the Depths")
characterquests.charquestprint(count,datatree,openfile,29298,"A Smoke-Stained Locket")
characterquests.charquestprint(count,datatree,openfile,29302,"Unlocking the Secrets Within")
characterquests.charquestprint(count,datatree,openfile,29303,"Tragedy and Family")
characterquests.charquestprint(count,datatree,openfile,29310,"The Tipping Point")
characterquests.charquestprint(count,datatree,openfile,29311,"The Rest is History")
|
py | 1a4589d0a70145a18f0fba084cd6502e779dd1f7 | #!/bin/env python
#===============================================================================
# NAME: SerialHVisitor.py
#
# DESCRIPTION: A visitor responsible for the generation of header file
# for each serializable class.
#
# AUTHOR: reder
# EMAIL: [email protected]
# DATE CREATED : June 4, 2007
#
# Copyright 2013, California Institute of Technology.
# ALL RIGHTS RESERVED. U.S. Government Sponsorship acknowledged.
#===============================================================================
#
# Python standard modules
#
import logging
import os
import sys
import time
import datetime
from optparse import OptionParser
#
# Python extention modules and custom interfaces
#
#from Cheetah import Template
#from fprime_ac.utils import version
from fprime_ac.utils import ConfigManager
#from fprime_ac.utils import DiffAndRename
from fprime_ac.generators.visitors import AbstractVisitor
from fprime_ac.generators import formatters
#
# Import precompiled templates here
#
from fprime_ac.generators.templates.serialize import startSerialH
from fprime_ac.generators.templates.serialize import includes1SerialH
from fprime_ac.generators.templates.serialize import includes2SerialH
from fprime_ac.generators.templates.serialize import namespaceSerialH
from fprime_ac.generators.templates.serialize import publicSerialH
from fprime_ac.generators.templates.serialize import protectedSerialH
from fprime_ac.generators.templates.serialize import privateSerialH
from fprime_ac.generators.templates.serialize import finishSerialH
#
# Universal globals used within module go here.
# (DO NOT USE MANY!)
#
# Global logger init. below.
PRINT = logging.getLogger('output')
DEBUG = logging.getLogger('debug')
typelist = ['U8','I8','U16','I16','U32','I32','U64','I64','F32','F64',"bool"]
#
# Module class or classes go here.
class SerialHVisitor(AbstractVisitor.AbstractVisitor):
"""
A visitor class responsible for generation of component header
classes in C++.
"""
__instance = None
__config = None
__fp = None
__form = None
__form_comment = None
def __init__(self):
"""
Constructor.
"""
self.__config = ConfigManager.ConfigManager.getInstance()
self.__form = formatters.Formatters()
self.__form_comment = formatters.CommentFormatters()
DEBUG.info("SerialHVisitor: Instanced.")
self.bodytext = ""
self.prototypetext = ""
def _get_args_string(self, obj):
"""
Return a string of (type, name) args, comma seperated
for use in templates that generate prototypes.
"""
arg_str = ""
for (name,mtype,size,format,comment) in obj.get_members():
typename = mtype
if type(mtype) == type(tuple()):
typename = mtype[0][1]
arg_str += "%s %s, "%(mtype[0][1],name)
elif mtype == "string":
arg_str += "const %s::%sString& %s, " % (obj.get_name(),name, name)
elif mtype not in typelist and size is None:
arg_str += "const %s& %s, " %(mtype,name)
elif size != None:
arg_str += "const %s* %s, " % (mtype, name)
arg_str += "NATIVE_INT_TYPE %sSize, " % (name)
else:
arg_str += "%s %s" % (mtype, name)
arg_str += ", "
arg_str = arg_str.strip(', ')
return arg_str
def _get_conv_mem_list(self, obj):
"""
Return a list of port argument tuples
"""
arg_list = list()
for (name,mtype,size,format,comment) in obj.get_members():
typeinfo = None
if type(mtype) == type(tuple()):
mtype = mtype[0][1]
typeinfo = "enum"
elif mtype == "string":
mtype = "%s::%sString" %(obj.get_name(),name)
typeinfo = "string"
elif mtype not in typelist:
typeinfo = "extern"
arg_list.append((name,mtype,size,format,comment,typeinfo))
return arg_list
def _get_enum_string_list(self, enum_list):
"""
"""
enum_tuple = enum_list[0]
enum_list = enum_list[1]
enum_str_list = []
for e in enum_list:
# No value, No comment
if (e[1] == None) and (e[2] == None):
s = "%s," % (e[0])
# No value, With comment
elif (e[1] == None) and (e[2] != None):
s = "%s, // %s" % (e[0],e[2])
# With value, No comment
elif (e[1] != None) and (e[2] == None):
s = "%s = %s," % (e[0],e[1])
# With value and comment
elif (e[1] != None) and (e[2] != None):
s = "%s = %s, // %s" % (e)
else:
pass
enum_str_list.append(s)
return (enum_tuple, enum_str_list)
def _writeTmpl(self, c, visit_str):
"""
Wrapper to write tmpl to files desc.
"""
DEBUG.debug('SerialHVisitor:%s' % visit_str)
DEBUG.debug('===================================')
DEBUG.debug(c)
self.__fp.writelines(c.__str__())
DEBUG.debug('===================================')
def initFilesVisit(self, obj):
"""
Defined to generate files for generated code products.
@parms obj: the instance of the concrete element to operation on.
"""
# Build filename here...
if self.__config.get("serialize","XMLDefaultFileName") == "True":
namespace = "".join(obj.get_namespace().split('::'))
filename = namespace + obj.get_name() + self.__config.get("serialize","SerializableH")
PRINT.info("Generating code filename: %s, using XML namespace and name attributes..." % filename)
else:
xml_file = obj.get_xml_filename()
x = xml_file.split(".")
s = self.__config.get("serialize","SerializableXML").split(".")
l = len(s[0])
#
if (x[0][-l:] == s[0]) & (x[1] == s[1]):
filename = x[0].split(s[0])[0] + self.__config.get("serialize","SerializableH")
PRINT.info("Generating code filename: %s, using default XML filename prefix..." % filename)
else:
msg = "XML file naming format not allowed (must be XXXSerializableAi.xml), Filename: %s" % xml_file
PRINT.info(msg)
sys.exit(-1)
# Open file for writting here...
DEBUG.info('Open file: %s' % filename)
self.__fp = open(filename,'w')
if self.__fp == None:
raise Exception("Could not open %s file.") % filename
DEBUG.info('Completed')
def startSourceFilesVisit(self, obj):
"""
Defined to generate starting static code within files.
"""
c = startSerialH.startSerialH()
c.name = obj.get_name()
if obj.get_namespace() == None:
c.namespace_list = None
else:
c.namespace_list = obj.get_namespace().split('::')
d = datetime.datetime.now()
c.date = d.strftime("%A, %d %B %Y")
c.user = os.environ['USER']
self._writeTmpl(c, "startSourceFilesVisit")
def includes1Visit(self, obj):
"""
Defined to generate includes within a file.
Usually used for the base classes but also for Serial types
@parms args: the instance of the concrete element to operation on.
"""
c = includes1SerialH.includes1SerialH()
self._writeTmpl(c, "includes1Visit")
def includes2Visit(self, obj):
"""
Defined to generate internal includes within a file.
Usually used for data type includes and system includes.
@parms args: the instance of the concrete element to operation on.
"""
c = includes2SerialH.includes2SerialH()
c.xml_includes_list = obj.get_xml_includes()
if False in [x[-6:] == 'Ai.xml' for x in c.xml_includes_list]:
PRINT.info("ERROR: Only Ai.xml files can be given within <import_serializable_type> tag!!!")
sys.exit(-1)
c.xml_includes_list = [x.replace('Ai.xml','Ac.hpp') for x in c.xml_includes_list]
c.c_includes_list = obj.get_c_includes()
if False in [x[-3:] == 'hpp' or x[-1:] == 'h' for x in c.c_includes_list]:
PRINT.info("ERROR: Only .hpp or .h files can be given within <include_header> tag!!!")
sys.exit(-1)
#
self._writeTmpl(c, "includes2Visit")
def namespaceVisit(self, obj):
"""
Defined to generate namespace code within a file.
Also any pre-condition code is generated.
@parms args: the instance of the concrete element to operation on.
"""
c = namespaceSerialH.namespaceSerialH()
if obj.get_namespace() == None:
c.namespace_list = None
else:
c.namespace_list = obj.get_namespace().split('::')
c.enum_type_list = []
t = [x[1] for x in obj.get_members()]
enum_list = [x for x in t if type(x) == type(tuple())]
for e in enum_list:
c.enum_type_list.append(self._get_enum_string_list(e))
c.mem_list = obj.get_members()
c.name = obj.get_name()
self._writeTmpl(c, "namespaceVisit")
def publicVisit(self, obj):
"""
Defined to generate public stuff within a class.
@parms args: the instance of the concrete element to operation on.
"""
c = publicSerialH.publicSerialH()
c.name = obj.get_name()
c.args_proto = self._get_args_string(obj)
c.members = self._get_conv_mem_list(obj)
self._writeTmpl(c, "publicVisit")
def protectedVisit(self, obj):
"""
Defined to generate protected stuff within a class.
@parms args: the instance of the concrete element to operation on.
"""
c = protectedSerialH.protectedSerialH()
c.uuid = obj.get_typeid()
c.name = obj.get_name()
c.members = self._get_conv_mem_list(obj)
self._writeTmpl(c, "protectedVisit")
def privateVisit(self, obj):
"""
Defined to generate private stuff within a class.
@parms args: the instance of the concrete element to operation on.
"""
c = privateSerialH.privateSerialH()
self._writeTmpl(c, "privateVisit")
def finishSourceFilesVisit(self, obj):
"""
Defined to generate ending static code within files.
"""
c = finishSerialH.finishSerialH()
c.name = obj.get_name()
if obj.get_namespace() == None:
c.namespace_list = None
else:
c.namespace_list = obj.get_namespace().split('::')
self._writeTmpl(c, "finishSourceFilesVisit")
self.__fp.close()
if __name__ == '__main__':
pass
|
py | 1a4589dfecc8ab0531580629e92938a7d0810ea1 | # This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Test Qiskit's Result class."""
import numpy as np
from qiskit.result import models
from qiskit.result import marginal_counts
from qiskit.result import Result
from qiskit.qobj import QobjExperimentHeader
from qiskit.test import QiskitTestCase
class TestResultOperations(QiskitTestCase):
"""Result operations methods."""
def setUp(self):
self.base_result_args = dict(backend_name='test_backend',
backend_version='1.0.0',
qobj_id='id-123',
job_id='job-123',
success=True)
super().setUp()
def test_counts_no_header(self):
"""Test that counts are extracted properly without header."""
raw_counts = {'0x0': 4, '0x2': 10}
no_header_processed_counts = {bin(int(bs[2:], 16))[2:]: counts for
(bs, counts) in raw_counts.items()}
data = models.ExperimentResultData(counts=dict(**raw_counts))
exp_result = models.ExperimentResult(shots=14, success=True, meas_level=2, data=data)
result = Result(results=[exp_result], **self.base_result_args)
self.assertEqual(result.get_counts(0), no_header_processed_counts)
def test_counts_header(self):
"""Test that counts are extracted properly with header."""
raw_counts = {'0x0': 4, '0x2': 10}
processed_counts = {'0 0 00': 4, '0 0 10': 10}
data = models.ExperimentResultData(counts=dict(**raw_counts))
exp_result_header = QobjExperimentHeader(
creg_sizes=[['c0', 2], ['c0', 1], ['c1', 1]], memory_slots=4)
exp_result = models.ExperimentResult(shots=14, success=True, meas_level=2,
data=data, header=exp_result_header)
result = Result(results=[exp_result], **self.base_result_args)
self.assertEqual(result.get_counts(0), processed_counts)
def test_counts_duplicate_name(self):
"""Test results containing multiple entries of a single name will warn."""
data = models.ExperimentResultData(counts=dict())
exp_result_header = QobjExperimentHeader(name='foo')
exp_result = models.ExperimentResult(shots=14, success=True,
data=data, header=exp_result_header)
result = Result(results=[exp_result] * 2, **self.base_result_args)
with self.assertWarnsRegex(UserWarning, r'multiple.*foo'):
result.get_counts('foo')
def test_result_repr(self):
"""Test that repr is contstructed correctly for a results object."""
raw_counts = {'0x0': 4, '0x2': 10}
data = models.ExperimentResultData(counts=dict(**raw_counts))
exp_result_header = QobjExperimentHeader(
creg_sizes=[['c0', 2], ['c0', 1], ['c1', 1]], memory_slots=4)
exp_result = models.ExperimentResult(shots=14, success=True, meas_level=2,
data=data, header=exp_result_header)
result = Result(results=[exp_result], **self.base_result_args)
expected = ("Result(backend_name='1.0.0', backend_version='1.0.0', "
"qobj_id='id-123', job_id='job-123', success=True, "
"results=[ExperimentResult(shots=14, success=True, "
"meas_level=2, data=ExperimentResultData(counts={'0x0': 4,"
" '0x2': 10}), header=QobjExperimentHeader(creg_sizes="
"[['c0', 2], ['c0', 1], ['c1', 1]], memory_slots=4))])")
self.assertEqual(expected, repr(result))
def test_multiple_circuits_counts(self):
""""
Test that counts are returned either as a list or a single item.
Counts are returned as a list when multiple experiments are executed
and get_counts() is called with no arguments. In all the other cases
get_counts() returns a single item containing the counts for a
single experiment.
"""
raw_counts_1 = {'0x0': 5, '0x3': 12, '0x5': 9, '0xD': 6, '0xE': 2}
processed_counts_1 = {'0000': 5, '0011': 12, '0101': 9, '1101': 6, '1110': 2}
data_1 = models.ExperimentResultData(counts=dict(**raw_counts_1))
exp_result_header_1 = QobjExperimentHeader(creg_sizes=[['c0', 4]], memory_slots=4)
exp_result_1 = models.ExperimentResult(shots=14, success=True, meas_level=2, data=data_1,
header=exp_result_header_1)
raw_counts_2 = {'0x1': 0, '0x4': 3, '0x6': 6, '0xA': 1, '0xB': 2}
processed_counts_2 = {'0001': 0, '0100': 3, '0110': 6, '1010': 1, '1011': 2}
data_2 = models.ExperimentResultData(counts=dict(**raw_counts_2))
exp_result_header_2 = QobjExperimentHeader(creg_sizes=[['c0', 4]], memory_slots=4)
exp_result_2 = models.ExperimentResult(shots=14, success=True, meas_level=2, data=data_2,
header=exp_result_header_2)
raw_counts_3 = {'0xC': 27, '0xF': 20}
processed_counts_3 = {'1100': 27, '1111': 20}
data_3 = models.ExperimentResultData(counts=dict(**raw_counts_3))
exp_result_header_3 = QobjExperimentHeader(creg_sizes=[['c0', 4]], memory_slots=4)
exp_result_3 = models.ExperimentResult(shots=14, success=True, meas_level=2, data=data_3,
header=exp_result_header_3)
mult_result = Result(results=[exp_result_1, exp_result_2, exp_result_3],
**self.base_result_args)
sing_result = Result(results=[exp_result_1], **self.base_result_args)
self.assertEqual(mult_result.get_counts(), [processed_counts_1, processed_counts_2,
processed_counts_3])
self.assertEqual(sing_result.get_counts(), processed_counts_1)
def test_marginal_counts(self):
"""Test that counts are marginalized correctly."""
raw_counts = {'0x0': 4, '0x1': 7, '0x2': 10, '0x6': 5, '0x9': 11, '0xD': 9, '0xE': 8}
data = models.ExperimentResultData(counts=dict(**raw_counts))
exp_result_header = QobjExperimentHeader(creg_sizes=[['c0', 4]],
memory_slots=4)
exp_result = models.ExperimentResult(shots=54, success=True, data=data,
header=exp_result_header)
result = Result(results=[exp_result], **self.base_result_args)
expected_marginal_counts = {'00': 4, '01': 27, '10': 23}
self.assertEqual(marginal_counts(result.get_counts(), [0, 1]), expected_marginal_counts)
self.assertEqual(marginal_counts(result.get_counts(), [1, 0]), expected_marginal_counts)
def test_marginal_counts_result(self):
"""Test that a Result object containing counts marginalizes correctly."""
raw_counts_1 = {'0x0': 4, '0x1': 7, '0x2': 10, '0x6': 5, '0x9': 11, '0xD': 9, '0xE': 8}
data_1 = models.ExperimentResultData(counts=dict(**raw_counts_1))
exp_result_header_1 = QobjExperimentHeader(creg_sizes=[['c0', 4]], memory_slots=4)
exp_result_1 = models.ExperimentResult(shots=54, success=True, data=data_1,
header=exp_result_header_1)
raw_counts_2 = {'0x2': 5, '0x3': 8}
data_2 = models.ExperimentResultData(counts=dict(**raw_counts_2))
exp_result_header_2 = QobjExperimentHeader(creg_sizes=[['c0', 2]], memory_slots=2)
exp_result_2 = models.ExperimentResult(shots=13, success=True, data=data_2,
header=exp_result_header_2)
result = Result(results=[exp_result_1, exp_result_2], **self.base_result_args)
expected_marginal_counts_1 = {'00': 4, '01': 27, '10': 23}
expected_marginal_counts_2 = {'0': 5, '1': 8}
self.assertEqual(marginal_counts(result, [0, 1]).get_counts(0),
expected_marginal_counts_1)
self.assertEqual(marginal_counts(result, [0]).get_counts(1),
expected_marginal_counts_2)
def test_marginal_counts_inplace_true(self):
"""Test marginal_counts(Result, inplace = True)
"""
raw_counts_1 = {'0x0': 4, '0x1': 7, '0x2': 10, '0x6': 5, '0x9': 11, '0xD': 9, '0xE': 8}
data_1 = models.ExperimentResultData(counts=dict(**raw_counts_1))
exp_result_header_1 = QobjExperimentHeader(creg_sizes=[['c0', 4]], memory_slots=4)
exp_result_1 = models.ExperimentResult(shots=54, success=True, data=data_1,
header=exp_result_header_1)
raw_counts_2 = {'0x2': 5, '0x3': 8}
data_2 = models.ExperimentResultData(counts=dict(**raw_counts_2))
exp_result_header_2 = QobjExperimentHeader(creg_sizes=[['c0', 2]], memory_slots=2)
exp_result_2 = models.ExperimentResult(shots=13, success=True, data=data_2,
header=exp_result_header_2)
result = Result(results=[exp_result_1, exp_result_2], **self.base_result_args)
expected_marginal_counts = {'0': 27, '1': 27}
self.assertEqual(marginal_counts(result, [0], inplace=True).get_counts(0),
expected_marginal_counts)
self.assertEqual(result.get_counts(0),
expected_marginal_counts)
def test_marginal_counts_inplace_false(self):
"""Test marginal_counts(Result, inplace=False) """
raw_counts_1 = {'0x0': 4, '0x1': 7, '0x2': 10, '0x6': 5, '0x9': 11, '0xD': 9, '0xE': 8}
data_1 = models.ExperimentResultData(counts=dict(**raw_counts_1))
exp_result_header_1 = QobjExperimentHeader(creg_sizes=[['c0', 4]], memory_slots=4)
exp_result_1 = models.ExperimentResult(shots=54, success=True, data=data_1,
header=exp_result_header_1)
raw_counts_2 = {'0x2': 5, '0x3': 8}
data_2 = models.ExperimentResultData(counts=dict(**raw_counts_2))
exp_result_header_2 = QobjExperimentHeader(creg_sizes=[['c0', 2]], memory_slots=2)
exp_result_2 = models.ExperimentResult(shots=13, success=True, data=data_2,
header=exp_result_header_2)
result = Result(results=[exp_result_1, exp_result_2], **self.base_result_args)
expected_marginal_counts = {'0': 27, '1': 27}
self.assertEqual(marginal_counts(result, [0], inplace=False).get_counts(0),
expected_marginal_counts)
self.assertNotEqual(result.get_counts(0),
expected_marginal_counts)
def test_marginal_counts_with_dict(self):
"""Test the marginal_counts method with dictionary instead of Result object.
"""
dict_counts_1 = {'0000': 4, '0001': 7, '0010': 10, '0110': 5,
'1001': 11, '1101': 9, '1110': 8}
dict_counts_2 = {'10': 5, '11': 8}
expected_marginal_counts_1 = {'00': 4, '01': 27, '10': 23}
expected_marginal_counts_2 = {'0': 5, '1': 8}
self.assertEqual(marginal_counts(dict_counts_1, [0, 1]),
expected_marginal_counts_1)
self.assertEqual(marginal_counts(dict_counts_2, [0], inplace=True),
expected_marginal_counts_2)
self.assertNotEqual(dict_counts_2, expected_marginal_counts_2)
self.assertRaises(AttributeError,
lambda: marginal_counts(dict_counts_1, [0, 1]).get_counts(0))
def test_memory_counts_no_header(self):
"""Test that memory bitstrings are extracted properly without header."""
raw_memory = ['0x0', '0x0', '0x2', '0x2', '0x2', '0x2', '0x2']
no_header_processed_memory = [bin(int(bs[2:], 16))[2:] for bs in raw_memory]
data = models.ExperimentResultData(memory=raw_memory)
exp_result = models.ExperimentResult(shots=14, success=True, meas_level=2,
memory=True, data=data)
result = Result(results=[exp_result], **self.base_result_args)
self.assertEqual(result.get_memory(0), no_header_processed_memory)
def test_memory_counts_header(self):
"""Test that memory bitstrings are extracted properly with header."""
raw_memory = ['0x0', '0x0', '0x2', '0x2', '0x2', '0x2', '0x2']
no_header_processed_memory = ['0 0 00', '0 0 00', '0 0 10', '0 0 10',
'0 0 10', '0 0 10', '0 0 10']
data = models.ExperimentResultData(memory=raw_memory)
exp_result_header = QobjExperimentHeader(
creg_sizes=[['c0', 2], ['c0', 1], ['c1', 1]], memory_slots=4)
exp_result = models.ExperimentResult(shots=14, success=True, meas_level=2,
memory=True, data=data,
header=exp_result_header)
result = Result(results=[exp_result], **self.base_result_args)
self.assertEqual(result.get_memory(0), no_header_processed_memory)
def test_meas_level_1_avg(self):
"""Test measurement level 1 average result."""
# 3 qubits
raw_memory = [[0., 1.], [1., 0.], [0.5, 0.5]]
processed_memory = np.array([1.j, 1., 0.5+0.5j], dtype=np.complex_)
data = models.ExperimentResultData(memory=raw_memory)
exp_result = models.ExperimentResult(shots=2, success=True, meas_level=1,
meas_return='avg', data=data)
result = Result(results=[exp_result], **self.base_result_args)
memory = result.get_memory(0)
self.assertEqual(memory.shape, (3,))
self.assertEqual(memory.dtype, np.complex_)
np.testing.assert_almost_equal(memory, processed_memory)
def test_meas_level_1_single(self):
"""Test measurement level 1 single result."""
# 3 qubits
raw_memory = [[[0., 1.], [1., 0.], [0.5, 0.5]],
[[0.5, 0.5], [1., 0.], [0., 1.]]]
processed_memory = np.array([[1.j, 1., 0.5+0.5j],
[0.5+0.5j, 1., 1.j]], dtype=np.complex_)
data = models.ExperimentResultData(memory=raw_memory)
exp_result = models.ExperimentResult(shots=2, success=True, meas_level=1,
meas_return='single', data=data)
result = Result(results=[exp_result], **self.base_result_args)
memory = result.get_memory(0)
self.assertEqual(memory.shape, (2, 3))
self.assertEqual(memory.dtype, np.complex_)
np.testing.assert_almost_equal(memory, processed_memory)
def test_meas_level_0_avg(self):
"""Test measurement level 0 average result."""
# 3 qubits
raw_memory = [[[0., 1.], [0., 1.], [0., 1.]],
[[1., 0.], [1., 0.], [1., 0.]]]
processed_memory = np.array([[1.j, 1.j, 1.j],
[1., 1., 1.]], dtype=np.complex_)
data = models.ExperimentResultData(memory=raw_memory)
exp_result = models.ExperimentResult(shots=2, success=True, meas_level=0,
meas_return='avg', data=data)
result = Result(results=[exp_result], **self.base_result_args)
memory = result.get_memory(0)
self.assertEqual(memory.shape, (2, 3))
self.assertEqual(memory.dtype, np.complex_)
np.testing.assert_almost_equal(memory, processed_memory)
def test_meas_level_0_single(self):
"""Test measurement level 0 single result."""
# 3 qubits
raw_memory = [[[[0., 1.], [0., 1.], [0., 1.]],
[[1., 0.], [1., 0.], [1., 0.]]],
[[[0., 1.], [0., 1.], [0., 1.]],
[[1., 0.], [1., 0.], [1., 0.]]]]
processed_memory = np.array([[[1.j, 1.j, 1.j],
[1., 1., 1.]],
[[1.j, 1.j, 1.j],
[1., 1., 1.]]], dtype=np.complex_)
data = models.ExperimentResultData(memory=raw_memory)
exp_result = models.ExperimentResult(shots=2, success=True, meas_level=0,
meas_return='single', data=data)
result = Result(results=[exp_result], **self.base_result_args)
memory = result.get_memory(0)
self.assertEqual(memory.shape, (2, 2, 3))
self.assertEqual(memory.dtype, np.complex_)
np.testing.assert_almost_equal(memory, processed_memory)
|
py | 1a458ae073a01eb36ffd38f9f9052b7e96218d21 | import PyPDF2
# This code will add the watermark file on each of the files from super_pdf
template = PyPDF2.PdfFileReader(open('super_pdf', 'rb'))
watermark = PyPDF2.PdfFileReader(open('wtr.pdf', 'rb'))
output = PyPDF2.PdfFileWriter()
for i in range(template.getNumPages()):
page = template.getPage(i)
page.mergePage(watermark.getPage(0))
output.addPage(page)
with open('watermarked_output.pdf', 'wb') as file:
output.write(file) |
py | 1a458b4862833541640fbc73fbef47620609a110 | # Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from dashboard.api import api_request_handler
from dashboard.pinpoint.models import change
class Commit(api_request_handler.ApiRequestHandler):
def _CheckUser(self):
pass
def Post(self):
git_hash = self.request.get('git_hash')
try:
c = change.Commit.FromDict({
'repository': 'chromium',
'git_hash': git_hash,
})
return c.AsDict()
except KeyError:
raise api_request_handler.BadRequestError(
'Unknown git hash: %s' % git_hash)
|
py | 1a458c63913cce0b3f01b802946ecd42bb0dfc53 | import os
import subprocess
from platform import system
from time import sleep
try:
from psutil import NoSuchProcess, Process
except ImportError:
""" Don't make psutil a strict requirement, but use if available. """
Process = None
def kill_pid(pid, use_psutil=True):
if use_psutil and Process:
_psutil_kill_pid(pid)
else:
_stock_kill_pid(pid)
def _psutil_kill_pid(pid):
"""
http://stackoverflow.com/questions/1230669/subprocess-deleting-child-processes-in-windows
"""
try:
parent = Process(pid)
for child in parent.get_children(recursive=True):
child.kill()
parent.kill()
except NoSuchProcess:
return
def _stock_kill_pid(pid):
is_windows = system() == 'Windows'
if is_windows:
__kill_windows(pid)
else:
__kill_posix(pid)
def __kill_windows(pid):
try:
subprocess.check_call(['taskkill', '/F', '/T', '/PID', pid])
except subprocess.CalledProcessError:
pass
def __kill_posix(pid):
def __check_pid():
try:
os.kill(pid, 0)
return True
except OSError:
return False
if __check_pid():
for sig in [15, 9]:
try:
os.killpg(pid, sig)
except OSError:
return
sleep(1)
if not __check_pid():
return
|
py | 1a458c7af50f2b5fce4eea6b07e088bfee0d0c6c | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: salvo
# @Date: 2015-05-18 17:34:56
# @Last Modified by: salvo
# @Last Modified time: 2015-05-24 20:24:21
# add external folder to import path
if __name__ == '__main__' and __package__ is None:
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from user_files.escape_velocity import escape_velocity
class Planet(object):
def __init__(self, name, mass, radius, velocity):
super(Planet, self).__init__()
self.name = name
self.mass = mass
self.radius = radius
self.velocity = velocity
PLANETS = [
Planet('Mercury', 3.3 * (10 ** 23), 2440, 4435),
Planet('Hearth', 6.0 * (10 ** 24), 6378, 11200),
Planet('Jupiter', 1.9 * (10 ** 27), 71492, 59600)]
for planet in PLANETS:
try:
v = escape_velocity(planet.mass, planet.radius)
err = abs(1 - v / planet.velocity)
assert err < 0.05
except:
print 'Fails to calculate for planet: %s, result: %s' % (planet.name, v)
sys.exit(0)
print 'Nice job.'
|
py | 1a458cabb260ae20416fbe23e2815a7724763599 | SECRET_KEY = '-dummy-key-'
INSTALLED_APPS = [
'pgcomments',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
},
}
|
py | 1a458d84e76030eb5d215b273045713b23d2f1a4 | # Demonstrates the IPTC Media Topics document classification capability of the (Cloud based) expert.ai Natural Language API
from expertai.nlapi.cloud.client import ExpertAiClient
client = ExpertAiClient()
text = "Michael Jordan was one of the best basketball players of all time. Scoring was Jordan's stand-out skill, but he still holds a defensive NBA record, with eight steals in a half."
taxonomy = 'behavioral-traits'
language= 'en'
output = client.classification(body={"document": {"text": text}}, params={'taxonomy': taxonomy, 'language': language})
print("Tab separated list of categories:")
for category in output.categories:
print(category.id_, category.hierarchy, sep="\t")
|
py | 1a458d9d9e38f7e5c55d05820e81e9b3b34e98f2 | import logging
import sys
# Make sure a NullHandler is available
# This was added in Python 2.7/3.2
try:
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
# Make sure that dictConfig is available
# This was added in Python 2.7/3.2
try:
from logging.config import dictConfig
except ImportError:
from snaptastic.utils.dictconfig import dictConfig
if sys.version_info < (2, 5):
class LoggerCompat(object):
def __init__(self, logger):
self._logger = logger
def __getattr__(self, name):
val = getattr(self._logger, name)
if callable(val):
def _wrapper(*args, **kwargs):
# Python 2.4 logging module doesn't support 'extra' parameter to
# methods of Logger
kwargs.pop('extra', None)
return val(*args, **kwargs)
return _wrapper
else:
return val
def getLogger(name=None):
return LoggerCompat(logging.getLogger(name=name))
else:
getLogger = logging.getLogger
# Ensure the creation of the Django logger
# with a null handler. This ensures we don't get any
# 'No handlers could be found for logger "django"' messages
logger = getLogger('django')
if not logger.handlers:
logger.addHandler(NullHandler())
|
py | 1a458de4970c6e88db33bcdeb2a6316bf3e67cb1 | from tests.RDkit.test_RDkit_ligand_preparation import *
from tests.RDkit.test_RDkit_stereo_enumeration import *
|
py | 1a458f451b025f44544f5e059ac87bb5dff2c81e | # -*- coding: utf-8 -*-
#
# records.py
# csvdiff
#
import six
import csv
from . import error
class InvalidKeyError(Exception):
pass
def load(file_or_stream, sep=','):
istream = (open(file_or_stream)
if not hasattr(file_or_stream, 'read')
else file_or_stream)
# unicode delimiters are not ok in Python 2
if six.PY2 and isinstance(sep, six.text_type):
sep = sep.encode('utf8')
return SafeDictReader(istream, sep=sep)
class SafeDictReader:
"""
A CSV reader that streams records but gives nice errors if lines fail to parse.
"""
def __init__(self, istream, sep=None):
self.reader = csv.DictReader(istream, delimiter=sep)
def __iter__(self):
for lineno, r in enumerate(self.reader, 2):
if any(k is None for k in r):
error.abort('CSV parse error on line {}'.format(lineno))
yield r
@property
def fieldnames(self):
return self.reader._fieldnames
def index(record_seq, index_columns):
try:
obj = {
tuple(r[i] for i in index_columns): r
for r in record_seq
}
return obj
except KeyError as k:
raise InvalidKeyError('invalid column name {k} as key'.format(k=k))
def filter_ignored(sequence, ignore_columns):
for key in sequence:
for i in ignore_columns:
sequence[key].pop(i)
return sequence
def save(record_seq, fieldnames, ostream):
writer = csv.DictWriter(ostream, fieldnames)
writer.writeheader()
for r in record_seq:
writer.writerow(r)
def sort(recs):
return sorted(recs, key=_record_key)
def _record_key(r):
return sorted(r.items())
|
py | 1a458f5dcfeb3777d607d983d4d6932b11b4ed7c | #!/usr/bin/env python
from __future__ import print_function
import gripql
import argparse
import pandas
import math
def load_matrix(args):
conn = gripql.Connection(args.server)
O = conn.graph(args.db)
matrix = pandas.read_csv(args.input, sep="\t", index_col=0)
for name, row in matrix.iterrows():
data = {}
for k, v in row.iteritems():
if not isinstance(v, float) or not math.isnan(v):
data[k] = v
O.addVertex(name, "Sample", data)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("input")
parser.add_argument("--server", default="http://localhost:8201")
parser.add_argument("--db", required=True)
args = parser.parse_args()
load_matrix(args)
|
py | 1a458f8bda6ed5db61bbcbacf25c0f81365ccdb1 | # This is a dict where each entry contains an label for a morphological feature,
# or the label for the UPOS tag if the key is 'upos'
pos_properties = {'ADJ': ['Degree', 'Number', 'Gender', 'Case'],
'ADP': ['Number', 'Gender', 'Case'],
'ADV': ['Degree', 'Abbr'],
'AUX': ['Mood',
'Aspect',
'Tense',
'Number',
'Person',
'VerbForm',
'Voice'],
'CCONJ': [],
'DET': ['Number', 'Gender', 'PronType', 'Definite', 'Case'],
'NOUN': ['Number', 'Gender', 'Abbr', 'Case'],
'NUM': ['NumType', 'Number', 'Gender', 'Case'],
'PART': [],
'PRON': ['Number', 'Gender', 'Person', 'Poss', 'PronType', 'Case'],
'PROPN': ['Number', 'Gender', 'Case'],
'PUNCT': [],
'SCONJ': [],
'SYM': [],
'VERB': ['Mood',
'Aspect',
'Tense',
'Number',
'Gender',
'Person',
'VerbForm',
'Voice',
'Case'],
'X': ['Foreign'],
'_': []}
# The labels for the named entity output of the ner model.
# A string label can be obtained by an output index
pos_labels = {'Abbr': ['_', 'Yes'],
'Aspect': ['Perf', '_', 'Imp'],
'Case': ['Dat', '_', 'Acc', 'Gen', 'Nom', 'Voc'],
'Definite': ['Ind', 'Def', '_'],
'Degree': ['Cmp', 'Sup', '_'],
'Foreign': ['_', 'Yes'],
'Gender': ['Fem', 'Masc', '_', 'Neut'],
'Mood': ['Ind', '_', 'Imp'],
'NumType': ['Mult', 'Card', '_', 'Ord', 'Sets'],
'Number': ['Plur', '_', 'Sing'],
'Person': ['3', '1', '_', '2'],
'Poss': ['_', 'Yes'],
'PronType': ['Ind', 'Art', '_', 'Rel', 'Dem', 'Prs', 'Ind,Rel', 'Int'],
'Tense': ['Pres', 'Past', '_'],
'VerbForm': ['Part', 'Conv', '_', 'Inf', 'Fin'],
'Voice': ['Pass', 'Act', '_'],
'upos': ['X',
'PROPN',
'PRON',
'ADJ',
'AUX',
'PART',
'ADV',
'_',
'DET',
'SYM',
'NUM',
'CCONJ',
'PUNCT',
'NOUN',
'SCONJ',
'ADP',
'VERB']}
|
py | 1a45902e5c69553b547d6ecd8d59543db7e2a781 | from __future__ import (absolute_import,
division,
print_function,
unicode_literals)
import warnings
warnings.filterwarnings('ignore')
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
from .ogh import *
from . import ogh_xarray_landlab as oxl
from .ogh_meta import meta_file
__author__ = 'Jimmy Phuong'
class ogh_meta:
"""
The json object that describes the Gridded climate data products
"""
def __init__(self):
self.__meta_data = dict(meta_file())
# key-value retrieval
def __getitem__(self, key):
return(self.__meta_data[key])
# key list
def keys(self):
return(self.__meta_data.keys())
# value list
def values(self):
return(self.__meta_data.values())
|
py | 1a459143f1532149bb3285a3731a8d3359b5f523 | # -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.base.exchange import Exchange
import hashlib
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import PermissionDenied
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest
from ccxt.base.errors import BadSymbol
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidOrder
from ccxt.base.decimal_to_precision import TICK_SIZE
class ascendex(Exchange):
def describe(self):
return self.deep_extend(super(ascendex, self).describe(), {
'id': 'ascendex',
'name': 'AscendEX',
'countries': ['SG'], # Singapore
'rateLimit': 500,
'certified': True,
# new metainfo interface
'has': {
'cancelAllOrders': True,
'cancelOrder': True,
'CORS': None,
'createOrder': True,
'fetchAccounts': True,
'fetchBalance': True,
'fetchClosedOrders': True,
'fetchCurrencies': True,
'fetchDepositAddress': True,
'fetchDeposits': True,
'fetchFundingRates': True,
'fetchMarkets': True,
'fetchOHLCV': True,
'fetchOpenOrders': True,
'fetchOrder': True,
'fetchOrderBook': True,
'fetchOrders': False,
'fetchPositions': True,
'fetchTicker': True,
'fetchTickers': True,
'fetchTrades': True,
'fetchTransactions': True,
'fetchWithdrawals': True,
'setLeverage': True,
'setMarginMode': True,
},
'timeframes': {
'1m': '1',
'5m': '5',
'15m': '15',
'30m': '30',
'1h': '60',
'2h': '120',
'4h': '240',
'6h': '360',
'12h': '720',
'1d': '1d',
'1w': '1w',
'1M': '1m',
},
'version': 'v2',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/112027508-47984600-8b48-11eb-9e17-d26459cc36c6.jpg',
'api': 'https://ascendex.com',
'test': 'https://bitmax-test.io',
'www': 'https://ascendex.com',
'doc': [
'https://bitmax-exchange.github.io/bitmax-pro-api/#bitmax-pro-api-documentation',
],
'fees': 'https://ascendex.com/en/feerate/transactionfee-traderate',
'referral': {
'url': 'https://ascendex.com/en-us/register?inviteCode=EL6BXBQM',
'discount': 0.25,
},
},
'api': {
'v1': {
'public': {
'get': [
'assets',
'products',
'ticker',
'barhist/info',
'barhist',
'depth',
'trades',
'cash/assets', # not documented
'cash/products', # not documented
'margin/assets', # not documented
'margin/products', # not documented
'futures/collateral',
'futures/contracts',
'futures/ref-px',
'futures/market-data',
'futures/funding-rates',
],
},
'private': {
'get': [
'info',
'wallet/transactions',
'wallet/deposit/address', # not documented
'data/balance/snapshot',
'data/balance/history',
],
'accountCategory': {
'get': [
'balance',
'order/open',
'order/status',
'order/hist/current',
'risk',
],
'post': [
'order',
'order/batch',
],
'delete': [
'order',
'order/all',
'order/batch',
],
},
'accountGroup': {
'get': [
'cash/balance',
'margin/balance',
'margin/risk',
'transfer',
'futures/collateral-balance',
'futures/position',
'futures/risk',
'futures/funding-payments',
'order/hist',
],
'post': [
'futures/transfer/deposit',
'futures/transfer/withdraw',
],
},
},
},
'v2': {
'public': {
'get': [
'assets',
'futures/contract',
'futures/collateral',
'futures/pricing-data',
],
},
'private': {
'get': [
'account/info',
],
'accountGroup': {
'get': [
'order/hist',
'futures/position',
'futures/free-margin',
'futures/order/hist/current',
'futures/order/open',
'futures/order/status',
],
'post': [
'futures/isolated-position-margin',
'futures/margin-type',
'futures/leverage',
'futures/transfer/deposit',
'futures/transfer/withdraw',
'futures/order',
'futures/order/batch',
'futures/order/open',
'subuser/subuser-transfer',
'subuser/subuser-transfer-hist',
],
'delete': [
'futures/order',
'futures/order/batch',
'futures/order/all',
],
},
},
},
},
'fees': {
'trading': {
'feeSide': 'get',
'tierBased': True,
'percentage': True,
'taker': self.parse_number('0.002'),
'maker': self.parse_number('0.002'),
},
},
'precisionMode': TICK_SIZE,
'options': {
'account-category': 'cash', # 'cash', 'margin', 'futures' # obsolete
'account-group': None,
'fetchClosedOrders': {
'method': 'v1PrivateAccountGroupGetOrderHist', # 'v1PrivateAccountGroupGetAccountCategoryOrderHistCurrent'
},
'defaultType': 'spot', # 'spot', 'margin', 'swap'
'accountCategories': {
'spot': 'cash',
'swap': 'futures',
'margin': 'margin',
},
},
'exceptions': {
'exact': {
# not documented
'1900': BadRequest, # {"code":1900,"message":"Invalid Http Request Input"}
'2100': AuthenticationError, # {"code":2100,"message":"ApiKeyFailure"}
'5002': BadSymbol, # {"code":5002,"message":"Invalid Symbol"}
'6001': BadSymbol, # {"code":6001,"message":"Trading is disabled on symbol."}
'6010': InsufficientFunds, # {'code': 6010, 'message': 'Not enough balance.'}
'60060': InvalidOrder, # {'code': 60060, 'message': 'The order is already filled or canceled.'}
'600503': InvalidOrder, # {"code":600503,"message":"Notional is too small."}
# documented
'100001': BadRequest, # INVALID_HTTP_INPUT Http request is invalid
'100002': BadRequest, # DATA_NOT_AVAILABLE Some required data is missing
'100003': BadRequest, # KEY_CONFLICT The same key exists already
'100004': BadRequest, # INVALID_REQUEST_DATA The HTTP request contains invalid field or argument
'100005': BadRequest, # INVALID_WS_REQUEST_DATA Websocket request contains invalid field or argument
'100006': BadRequest, # INVALID_ARGUMENT The arugment is invalid
'100007': BadRequest, # ENCRYPTION_ERROR Something wrong with data encryption
'100008': BadSymbol, # SYMBOL_ERROR Symbol does not exist or not valid for the request
'100009': AuthenticationError, # AUTHORIZATION_NEEDED Authorization is require for the API access or request
'100010': BadRequest, # INVALID_OPERATION The action is invalid or not allowed for the account
'100011': BadRequest, # INVALID_TIMESTAMP Not a valid timestamp
'100012': BadRequest, # INVALID_STR_FORMAT String format does not
'100013': BadRequest, # INVALID_NUM_FORMAT Invalid number input
'100101': ExchangeError, # UNKNOWN_ERROR Some unknown error
'150001': BadRequest, # INVALID_JSON_FORMAT Require a valid json object
'200001': AuthenticationError, # AUTHENTICATION_FAILED Authorization failed
'200002': ExchangeError, # TOO_MANY_ATTEMPTS Tried and failed too many times
'200003': ExchangeError, # ACCOUNT_NOT_FOUND Account not exist
'200004': ExchangeError, # ACCOUNT_NOT_SETUP Account not setup properly
'200005': ExchangeError, # ACCOUNT_ALREADY_EXIST Account already exist
'200006': ExchangeError, # ACCOUNT_ERROR Some error related with error
'200007': ExchangeError, # CODE_NOT_FOUND
'200008': ExchangeError, # CODE_EXPIRED Code expired
'200009': ExchangeError, # CODE_MISMATCH Code does not match
'200010': AuthenticationError, # PASSWORD_ERROR Wrong assword
'200011': ExchangeError, # CODE_GEN_FAILED Do not generate required code promptly
'200012': ExchangeError, # FAKE_COKE_VERIFY
'200013': ExchangeError, # SECURITY_ALERT Provide security alert message
'200014': PermissionDenied, # RESTRICTED_ACCOUNT Account is restricted for certain activity, such as trading, or withdraw.
'200015': PermissionDenied, # PERMISSION_DENIED No enough permission for the operation
'300001': InvalidOrder, # INVALID_PRICE Order price is invalid
'300002': InvalidOrder, # INVALID_QTY Order size is invalid
'300003': InvalidOrder, # INVALID_SIDE Order side is invalid
'300004': InvalidOrder, # INVALID_NOTIONAL Notional is too small or too large
'300005': InvalidOrder, # INVALID_TYPE Order typs is invalid
'300006': InvalidOrder, # INVALID_ORDER_ID Order id is invalid
'300007': InvalidOrder, # INVALID_TIME_IN_FORCE Time In Force in order request is invalid
'300008': InvalidOrder, # INVALID_ORDER_PARAMETER Some order parameter is invalid
'300009': InvalidOrder, # TRADING_VIOLATION Trading violation on account or asset
'300011': InsufficientFunds, # INVALID_BALANCE No enough account or asset balance for the trading
'300012': BadSymbol, # INVALID_PRODUCT Not a valid product supported by exchange
'300013': InvalidOrder, # INVALID_BATCH_ORDER Some or all orders are invalid in batch order request
'300014': InvalidOrder, # {"code":300014,"message":"Order price doesn't conform to the required tick size: 0.1","reason":"TICK_SIZE_VIOLATION"}
'300020': InvalidOrder, # TRADING_RESTRICTED There is some trading restriction on account or asset
'300021': InvalidOrder, # TRADING_DISABLED Trading is disabled on account or asset
'300031': InvalidOrder, # NO_MARKET_PRICE No market price for market type order trading
'310001': InsufficientFunds, # INVALID_MARGIN_BALANCE No enough margin balance
'310002': InvalidOrder, # INVALID_MARGIN_ACCOUNT Not a valid account for margin trading
'310003': InvalidOrder, # MARGIN_TOO_RISKY Leverage is too high
'310004': BadSymbol, # INVALID_MARGIN_ASSET This asset does not support margin trading
'310005': InvalidOrder, # INVALID_REFERENCE_PRICE There is no valid reference price
'510001': ExchangeError, # SERVER_ERROR Something wrong with server.
'900001': ExchangeError, # HUMAN_CHALLENGE Human change do not pass
},
'broad': {},
},
'commonCurrencies': {
'BOND': 'BONDED',
'BTCBEAR': 'BEAR',
'BTCBULL': 'BULL',
'BYN': 'BeyondFi',
},
})
def get_account(self, params={}):
# get current or provided bitmax sub-account
account = self.safe_value(params, 'account', self.options['account'])
return account.lower().capitalize()
async def fetch_currencies(self, params={}):
assets = await self.v1PublicGetAssets(params)
#
# {
# "code":0,
# "data":[
# {
# "assetCode" : "LTCBULL",
# "assetName" : "3X Long LTC Token",
# "precisionScale" : 9,
# "nativeScale" : 4,
# "withdrawalFee" : "0.2",
# "minWithdrawalAmt" : "1.0",
# "status" : "Normal"
# },
# ]
# }
#
margin = await self.v1PublicGetMarginAssets(params)
#
# {
# "code":0,
# "data":[
# {
# "assetCode":"BTT",
# "borrowAssetCode":"BTT-B",
# "interestAssetCode":"BTT-I",
# "nativeScale":0,
# "numConfirmations":1,
# "withdrawFee":"100.0",
# "minWithdrawalAmt":"1000.0",
# "statusCode":"Normal",
# "statusMessage":"",
# "interestRate":"0.001"
# }
# ]
# }
#
cash = await self.v1PublicGetCashAssets(params)
#
# {
# "code":0,
# "data":[
# {
# "assetCode":"LTCBULL",
# "nativeScale":4,
# "numConfirmations":20,
# "withdrawFee":"0.2",
# "minWithdrawalAmt":"1.0",
# "statusCode":"Normal",
# "statusMessage":""
# }
# ]
# }
#
assetsData = self.safe_value(assets, 'data', [])
marginData = self.safe_value(margin, 'data', [])
cashData = self.safe_value(cash, 'data', [])
assetsById = self.index_by(assetsData, 'assetCode')
marginById = self.index_by(marginData, 'assetCode')
cashById = self.index_by(cashData, 'assetCode')
dataById = self.deep_extend(assetsById, marginById, cashById)
ids = list(dataById.keys())
result = {}
for i in range(0, len(ids)):
id = ids[i]
currency = dataById[id]
code = self.safe_currency_code(id)
precision = self.safe_string_2(currency, 'precisionScale', 'nativeScale')
minAmount = self.parse_precision(precision)
# why would the exchange API have different names for the same field
fee = self.safe_number_2(currency, 'withdrawFee', 'withdrawalFee')
status = self.safe_string_2(currency, 'status', 'statusCode')
active = (status == 'Normal')
margin = ('borrowAssetCode' in currency)
result[code] = {
'id': id,
'code': code,
'info': currency,
'type': None,
'margin': margin,
'name': self.safe_string(currency, 'assetName'),
'active': active,
'fee': fee,
'precision': int(precision),
'limits': {
'amount': {
'min': self.parse_number(minAmount),
'max': None,
},
'withdraw': {
'min': self.safe_number(currency, 'minWithdrawalAmt'),
'max': None,
},
},
}
return result
async def fetch_markets(self, params={}):
products = await self.v1PublicGetProducts(params)
#
# {
# "code":0,
# "data":[
# {
# "symbol":"LBA/BTC",
# "baseAsset":"LBA",
# "quoteAsset":"BTC",
# "status":"Normal",
# "minNotional":"0.000625",
# "maxNotional":"6.25",
# "marginTradable":false,
# "commissionType":"Quote",
# "commissionReserveRate":"0.001",
# "tickSize":"0.000000001",
# "lotSize":"1"
# },
# ]
# }
#
cash = await self.v1PublicGetCashProducts(params)
#
# {
# "code":0,
# "data":[
# {
# "symbol":"QTUM/BTC",
# "domain":"BTC",
# "tradingStartTime":1569506400000,
# "collapseDecimals":"0.0001,0.000001,0.00000001",
# "minQty":"0.000000001",
# "maxQty":"1000000000",
# "minNotional":"0.000625",
# "maxNotional":"12.5",
# "statusCode":"Normal",
# "statusMessage":"",
# "tickSize":"0.00000001",
# "useTick":false,
# "lotSize":"0.1",
# "useLot":false,
# "commissionType":"Quote",
# "commissionReserveRate":"0.001",
# "qtyScale":1,
# "priceScale":8,
# "notionalScale":4
# }
# ]
# }
#
perpetuals = await self.v2PublicGetFuturesContract(params)
#
# {
# "code":0,
# "data":[
# {
# "symbol":"BTC-PERP",
# "status":"Normal",
# "displayName":"BTCUSDT",
# "settlementAsset":"USDT",
# "underlying":"BTC/USDT",
# "tradingStartTime":1579701600000,
# "priceFilter":{"minPrice":"1","maxPrice":"1000000","tickSize":"1"},
# "lotSizeFilter":{"minQty":"0.0001","maxQty":"1000000000","lotSize":"0.0001"},
# "commissionType":"Quote",
# "commissionReserveRate":"0.001",
# "marketOrderPriceMarkup":"0.03",
# "marginRequirements":[
# {"positionNotionalLowerBound":"0","positionNotionalUpperBound":"50000","initialMarginRate":"0.01","maintenanceMarginRate":"0.006"},
# {"positionNotionalLowerBound":"50000","positionNotionalUpperBound":"200000","initialMarginRate":"0.02","maintenanceMarginRate":"0.012"},
# {"positionNotionalLowerBound":"200000","positionNotionalUpperBound":"2000000","initialMarginRate":"0.04","maintenanceMarginRate":"0.024"},
# {"positionNotionalLowerBound":"2000000","positionNotionalUpperBound":"20000000","initialMarginRate":"0.1","maintenanceMarginRate":"0.06"},
# {"positionNotionalLowerBound":"20000000","positionNotionalUpperBound":"40000000","initialMarginRate":"0.2","maintenanceMarginRate":"0.12"},
# {"positionNotionalLowerBound":"40000000","positionNotionalUpperBound":"1000000000","initialMarginRate":"0.333333","maintenanceMarginRate":"0.2"}
# ]
# }
# ]
# }
#
productsData = self.safe_value(products, 'data', [])
productsById = self.index_by(productsData, 'symbol')
cashData = self.safe_value(cash, 'data', [])
perpetualsData = self.safe_value(perpetuals, 'data', [])
cashAndPerpetualsData = self.array_concat(cashData, perpetualsData)
cashAndPerpetualsById = self.index_by(cashAndPerpetualsData, 'symbol')
dataById = self.deep_extend(productsById, cashAndPerpetualsById)
ids = list(dataById.keys())
result = []
for i in range(0, len(ids)):
id = ids[i]
market = dataById[id]
baseId = self.safe_string(market, 'baseAsset')
quoteId = self.safe_string(market, 'quoteAsset')
settleId = self.safe_value(market, 'settlementAsset')
base = self.safe_currency_code(baseId)
quote = self.safe_currency_code(quoteId)
settle = self.safe_currency_code(settleId)
precision = {
'amount': self.safe_number(market, 'lotSize'),
'price': self.safe_number(market, 'tickSize'),
}
status = self.safe_string(market, 'status')
active = (status == 'Normal')
type = 'swap' if (settle is not None) else 'spot'
spot = (type == 'spot')
swap = (type == 'swap')
margin = self.safe_value(market, 'marginTradable', False)
contract = swap
derivative = contract
linear = True if contract else None
contractSize = 1 if contract else None
minQty = self.safe_number(market, 'minQty')
maxQty = self.safe_number(market, 'maxQty')
minPrice = self.safe_number(market, 'tickSize')
maxPrice = None
symbol = base + '/' + quote
if contract:
lotSizeFilter = self.safe_value(market, 'lotSizeFilter')
minQty = self.safe_number(lotSizeFilter, 'minQty')
maxQty = self.safe_number(lotSizeFilter, 'maxQty')
priceFilter = self.safe_value(market, 'priceFilter')
minPrice = self.safe_number(priceFilter, 'minPrice')
maxPrice = self.safe_number(priceFilter, 'maxPrice')
underlying = self.safe_string(market, 'underlying')
parts = underlying.split('/')
baseId = self.safe_string(parts, 0)
quoteId = self.safe_string(parts, 1)
base = self.safe_currency_code(baseId)
quote = self.safe_currency_code(quoteId)
symbol = base + '/' + quote + ':' + settle
fee = self.safe_number(market, 'commissionReserveRate')
result.append({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'settle': settle,
'baseId': baseId,
'quoteId': quoteId,
'settleId': settleId,
'type': type,
'spot': spot,
'margin': margin,
'swap': swap,
'future': False,
'option': False,
'active': active,
'derivative': derivative,
'contract': contract,
'linear': linear,
'inverse': not linear if contract else None,
'taker': fee,
'maker': fee,
'contractSize': contractSize,
'expiry': None,
'expiryDatetime': None,
'strike': None,
'optionType': None,
'precision': precision,
'limits': {
'leverage': {
'min': None,
'max': None,
},
'amount': {
'min': minQty,
'max': maxQty,
},
'price': {
'min': minPrice,
'max': maxPrice,
},
'cost': {
'min': self.safe_number(market, 'minNotional'),
'max': self.safe_number(market, 'maxNotional'),
},
},
'info': market,
})
return result
async def fetch_accounts(self, params={}):
accountGroup = self.safe_string(self.options, 'account-group')
response = None
if accountGroup is None:
response = await self.v1PrivateGetInfo(params)
#
# {
# "code":0,
# "data":{
# "email":"[email protected]",
# "accountGroup":8,
# "viewPermission":true,
# "tradePermission":true,
# "transferPermission":true,
# "cashAccount":["cshrHKLZCjlZ2ejqkmvIHHtPmLYqdnda"],
# "marginAccount":["martXoh1v1N3EMQC5FDtSj5VHso8aI2Z"],
# "futuresAccount":["futc9r7UmFJAyBY2rE3beA2JFxav2XFF"],
# "userUID":"U6491137460"
# }
# }
#
data = self.safe_value(response, 'data', {})
accountGroup = self.safe_string(data, 'accountGroup')
self.options['account-group'] = accountGroup
return [
{
'id': accountGroup,
'type': None,
'currency': None,
'info': response,
},
]
def parse_balance(self, response):
result = {
'info': response,
'timestamp': None,
'datetime': None,
}
balances = self.safe_value(response, 'data', [])
for i in range(0, len(balances)):
balance = balances[i]
code = self.safe_currency_code(self.safe_string(balance, 'asset'))
account = self.account()
account['free'] = self.safe_string(balance, 'availableBalance')
account['total'] = self.safe_string(balance, 'totalBalance')
result[code] = account
return self.safe_balance(result)
async def fetch_balance(self, params={}):
await self.load_markets()
await self.load_accounts()
defaultAccountCategory = self.safe_string(self.options, 'account-category', 'cash')
options = self.safe_value(self.options, 'fetchBalance', {})
accountCategory = self.safe_string(options, 'account-category', defaultAccountCategory)
accountCategory = self.safe_string(params, 'account-category', accountCategory)
params = self.omit(params, 'account-category')
account = self.safe_value(self.accounts, 0, {})
accountGroup = self.safe_string(account, 'id')
request = {
'account-group': accountGroup,
}
method = 'v1PrivateAccountCategoryGetBalance'
if accountCategory == 'futures':
method = 'v1PrivateAccountGroupGetFuturesCollateralBalance'
else:
request['account-category'] = accountCategory
response = await getattr(self, method)(self.extend(request, params))
#
# cash
#
# {
# 'code': 0,
# 'data': [
# {
# 'asset': 'BCHSV',
# 'totalBalance': '64.298000048',
# 'availableBalance': '64.298000048',
# },
# ]
# }
#
# margin
#
# {
# 'code': 0,
# 'data': [
# {
# 'asset': 'BCHSV',
# 'totalBalance': '64.298000048',
# 'availableBalance': '64.298000048',
# 'borrowed': '0',
# 'interest': '0',
# },
# ]
# }
#
# futures
#
# {
# "code":0,
# "data":[
# {"asset":"BTC","totalBalance":"0","availableBalance":"0","maxTransferrable":"0","priceInUSDT":"9456.59"},
# {"asset":"ETH","totalBalance":"0","availableBalance":"0","maxTransferrable":"0","priceInUSDT":"235.95"},
# {"asset":"USDT","totalBalance":"0","availableBalance":"0","maxTransferrable":"0","priceInUSDT":"1"},
# {"asset":"USDC","totalBalance":"0","availableBalance":"0","maxTransferrable":"0","priceInUSDT":"1.00035"},
# {"asset":"PAX","totalBalance":"0","availableBalance":"0","maxTransferrable":"0","priceInUSDT":"1.00045"},
# {"asset":"USDTR","totalBalance":"0","availableBalance":"0","maxTransferrable":"0","priceInUSDT":"1"}
# ]
# }
#
return self.parse_balance(response)
async def fetch_order_book(self, symbol, limit=None, params={}):
await self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
}
response = await self.v1PublicGetDepth(self.extend(request, params))
#
# {
# "code":0,
# "data":{
# "m":"depth-snapshot",
# "symbol":"BTC-PERP",
# "data":{
# "ts":1590223998202,
# "seqnum":115444921,
# "asks":[
# ["9207.5","18.2383"],
# ["9207.75","18.8235"],
# ["9208","10.7873"],
# ],
# "bids":[
# ["9207.25","0.4009"],
# ["9207","0.003"],
# ["9206.5","0.003"],
# ]
# }
# }
# }
#
data = self.safe_value(response, 'data', {})
orderbook = self.safe_value(data, 'data', {})
timestamp = self.safe_integer(orderbook, 'ts')
result = self.parse_order_book(orderbook, symbol, timestamp)
result['nonce'] = self.safe_integer(orderbook, 'seqnum')
return result
def parse_ticker(self, ticker, market=None):
#
# {
# "symbol":"QTUM/BTC",
# "open":"0.00016537",
# "close":"0.00019077",
# "high":"0.000192",
# "low":"0.00016537",
# "volume":"846.6",
# "ask":["0.00018698","26.2"],
# "bid":["0.00018408","503.7"],
# "type":"spot"
# }
#
timestamp = None
marketId = self.safe_string(ticker, 'symbol')
type = self.safe_string(ticker, 'type')
delimiter = '/' if (type == 'spot') else None
symbol = self.safe_symbol(marketId, market, delimiter)
close = self.safe_number(ticker, 'close')
bid = self.safe_value(ticker, 'bid', [])
ask = self.safe_value(ticker, 'ask', [])
open = self.safe_number(ticker, 'open')
return self.safe_ticker({
'symbol': symbol,
'timestamp': timestamp,
'datetime': None,
'high': self.safe_number(ticker, 'high'),
'low': self.safe_number(ticker, 'low'),
'bid': self.safe_number(bid, 0),
'bidVolume': self.safe_number(bid, 1),
'ask': self.safe_number(ask, 0),
'askVolume': self.safe_number(ask, 1),
'vwap': None,
'open': open,
'close': close,
'last': close,
'previousClose': None, # previous day close
'change': None,
'percentage': None,
'average': None,
'baseVolume': self.safe_number(ticker, 'volume'),
'quoteVolume': None,
'info': ticker,
}, market)
async def fetch_ticker(self, symbol, params={}):
await self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
}
response = await self.v1PublicGetTicker(self.extend(request, params))
#
# {
# "code":0,
# "data":{
# "symbol":"BTC-PERP", # or "BTC/USDT"
# "open":"9073",
# "close":"9185.75",
# "high":"9185.75",
# "low":"9185.75",
# "volume":"576.8334",
# "ask":["9185.75","15.5863"],
# "bid":["9185.5","0.003"],
# "type":"derivatives", # or "spot"
# }
# }
#
data = self.safe_value(response, 'data', {})
return self.parse_ticker(data, market)
async def fetch_tickers(self, symbols=None, params={}):
await self.load_markets()
request = {}
if symbols is not None:
marketIds = self.market_ids(symbols)
request['symbol'] = ','.join(marketIds)
response = await self.v1PublicGetTicker(self.extend(request, params))
#
# {
# "code":0,
# "data":[
# {
# "symbol":"QTUM/BTC",
# "open":"0.00016537",
# "close":"0.00019077",
# "high":"0.000192",
# "low":"0.00016537",
# "volume":"846.6",
# "ask":["0.00018698","26.2"],
# "bid":["0.00018408","503.7"],
# "type":"spot"
# }
# ]
# }
#
data = self.safe_value(response, 'data', [])
return self.parse_tickers(data, symbols)
def parse_ohlcv(self, ohlcv, market=None):
#
# {
# "m":"bar",
# "s":"BTC/USDT",
# "data":{
# "i":"1",
# "ts":1590228000000,
# "o":"9139.59",
# "c":"9131.94",
# "h":"9139.99",
# "l":"9121.71",
# "v":"25.20648"
# }
# }
#
data = self.safe_value(ohlcv, 'data', {})
return [
self.safe_integer(data, 'ts'),
self.safe_number(data, 'o'),
self.safe_number(data, 'h'),
self.safe_number(data, 'l'),
self.safe_number(data, 'c'),
self.safe_number(data, 'v'),
]
async def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
await self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
'interval': self.timeframes[timeframe],
}
# if since and limit are not specified
# the exchange will return just 1 last candle by default
duration = self.parse_timeframe(timeframe)
options = self.safe_value(self.options, 'fetchOHLCV', {})
defaultLimit = self.safe_integer(options, 'limit', 500)
if since is not None:
request['from'] = since
if limit is None:
limit = defaultLimit
else:
limit = min(limit, defaultLimit)
request['to'] = self.sum(since, limit * duration * 1000, 1)
elif limit is not None:
request['n'] = limit # max 500
response = await self.v1PublicGetBarhist(self.extend(request, params))
#
# {
# "code":0,
# "data":[
# {
# "m":"bar",
# "s":"BTC/USDT",
# "data":{
# "i":"1",
# "ts":1590228000000,
# "o":"9139.59",
# "c":"9131.94",
# "h":"9139.99",
# "l":"9121.71",
# "v":"25.20648"
# }
# }
# ]
# }
#
data = self.safe_value(response, 'data', [])
return self.parse_ohlcvs(data, market, timeframe, since, limit)
def parse_trade(self, trade, market=None):
#
# public fetchTrades
#
# {
# "p":"9128.5", # price
# "q":"0.0030", # quantity
# "ts":1590229002385, # timestamp
# "bm":false, # if True, the buyer is the market maker, we only use self field to "define the side" of a public trade
# "seqnum":180143985289898554
# }
#
timestamp = self.safe_integer(trade, 'ts')
priceString = self.safe_string_2(trade, 'price', 'p')
amountString = self.safe_string(trade, 'q')
buyerIsMaker = self.safe_value(trade, 'bm', False)
makerOrTaker = 'maker' if buyerIsMaker else 'taker'
side = 'buy' if buyerIsMaker else 'sell'
symbol = None
if (symbol is None) and (market is not None):
symbol = market['symbol']
return self.safe_trade({
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': symbol,
'id': None,
'order': None,
'type': None,
'takerOrMaker': makerOrTaker,
'side': side,
'price': priceString,
'amount': amountString,
'cost': None,
'fee': None,
}, market)
async def fetch_trades(self, symbol, since=None, limit=None, params={}):
await self.load_markets()
market = self.market(symbol)
request = {
'symbol': market['id'],
}
if limit is not None:
request['n'] = limit # max 100
response = await self.v1PublicGetTrades(self.extend(request, params))
#
# {
# "code":0,
# "data":{
# "m":"trades",
# "symbol":"BTC-PERP",
# "data":[
# {"p":"9128.5","q":"0.0030","ts":1590229002385,"bm":false,"seqnum":180143985289898554},
# {"p":"9129","q":"0.0030","ts":1590229002642,"bm":false,"seqnum":180143985289898587},
# {"p":"9129.5","q":"0.0030","ts":1590229021306,"bm":false,"seqnum":180143985289899043}
# ]
# }
# }
#
records = self.safe_value(response, 'data', [])
trades = self.safe_value(records, 'data', [])
return self.parse_trades(trades, market, since, limit)
def parse_order_status(self, status):
statuses = {
'PendingNew': 'open',
'New': 'open',
'PartiallyFilled': 'open',
'Filled': 'closed',
'Canceled': 'canceled',
'Rejected': 'rejected',
}
return self.safe_string(statuses, status, status)
def parse_order(self, order, market=None):
#
# createOrder
#
# {
# "id": "16e607e2b83a8bXHbAwwoqDo55c166fa",
# "orderId": "16e85b4d9b9a8bXHbAwwoqDoc3d66830",
# "orderType": "Market",
# "symbol": "BTC/USDT",
# "timestamp": 1573576916201
# }
#
# {
# "ac": "FUTURES",
# "accountId": "fut2ODPhGiY71Pl4vtXnOZ00ssgD7QGn",
# "time": 1640819389454,
# "orderId": "a17e0874ecbdU0711043490bbtcpDU5X",
# "seqNum": -1,
# "orderType": "Limit",
# "execInst": "NULL_VAL",
# "side": "Buy",
# "symbol": "BTC-PERP",
# "price": "30000",
# "orderQty": "0.002",
# "stopPrice": "0",
# "stopBy": "ref-px",
# "status": "Ack",
# "lastExecTime": 1640819389454,
# "lastQty": "0",
# "lastPx": "0",
# "avgFilledPx": "0",
# "cumFilledQty": "0",
# "fee": "0",
# "cumFee": "0",
# "feeAsset": "",
# "errorCode": "",
# "posStopLossPrice": "0",
# "posStopLossTrigger": "market",
# "posTakeProfitPrice": "0",
# "posTakeProfitTrigger": "market",
# "liquidityInd": "n"
# }
#
# fetchOrder, fetchOpenOrders, fetchClosedOrders
#
# {
# "symbol": "BTC/USDT",
# "price": "8131.22",
# "orderQty": "0.00082",
# "orderType": "Market",
# "avgPx": "7392.02",
# "cumFee": "0.005152238",
# "cumFilledQty": "0.00082",
# "errorCode": "",
# "feeAsset": "USDT",
# "lastExecTime": 1575953151764,
# "orderId": "a16eee20b6750866943712zWEDdAjt3",
# "seqNum": 2623469,
# "side": "Buy",
# "status": "Filled",
# "stopPrice": "",
# "execInst": "NULL_VAL"
# }
#
# {
# "ac": "FUTURES",
# "accountId": "testabcdefg",
# "avgPx": "0",
# "cumFee": "0",
# "cumQty": "0",
# "errorCode": "NULL_VAL",
# "execInst": "NULL_VAL",
# "feeAsset": "USDT",
# "lastExecTime": 1584072844085,
# "orderId": "r170d21956dd5450276356bbtcpKa74",
# "orderQty": "1.1499",
# "orderType": "Limit",
# "price": "4000",
# "sendingTime": 1584072841033,
# "seqNum": 24105338,
# "side": "Buy",
# "status": "Canceled",
# "stopPrice": "",
# "symbol": "BTC-PERP"
# },
#
status = self.parse_order_status(self.safe_string(order, 'status'))
marketId = self.safe_string(order, 'symbol')
symbol = self.safe_symbol(marketId, market, '/')
timestamp = self.safe_integer_2(order, 'timestamp', 'sendingTime')
lastTradeTimestamp = self.safe_integer(order, 'lastExecTime')
price = self.safe_string(order, 'price')
amount = self.safe_string(order, 'orderQty')
average = self.safe_string(order, 'avgPx')
filled = self.safe_string_2(order, 'cumFilledQty', 'cumQty')
id = self.safe_string(order, 'orderId')
clientOrderId = self.safe_string(order, 'id')
if clientOrderId is not None:
if len(clientOrderId) < 1:
clientOrderId = None
type = self.safe_string_lower(order, 'orderType')
side = self.safe_string_lower(order, 'side')
feeCost = self.safe_number(order, 'cumFee')
fee = None
if feeCost is not None:
feeCurrencyId = self.safe_string(order, 'feeAsset')
feeCurrencyCode = self.safe_currency_code(feeCurrencyId)
fee = {
'cost': feeCost,
'currency': feeCurrencyCode,
}
stopPrice = self.safe_number(order, 'stopPrice')
return self.safe_order({
'info': order,
'id': id,
'clientOrderId': clientOrderId,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'lastTradeTimestamp': lastTradeTimestamp,
'symbol': symbol,
'type': type,
'timeInForce': None,
'postOnly': None,
'side': side,
'price': price,
'stopPrice': stopPrice,
'amount': amount,
'cost': None,
'average': average,
'filled': filled,
'remaining': None,
'status': status,
'fee': fee,
'trades': None,
}, market)
async def create_order(self, symbol, type, side, amount, price=None, params={}):
await self.load_markets()
await self.load_accounts()
market = self.market(symbol)
style, query = self.handle_market_type_and_params('createOrder', market, params)
options = self.safe_value(self.options, 'createOrder', {})
accountCategories = self.safe_value(self.options, 'accountCategories', {})
accountCategory = self.safe_string(accountCategories, style, 'cash')
account = self.safe_value(self.accounts, 0, {})
accountGroup = self.safe_value(account, 'id')
clientOrderId = self.safe_string_2(params, 'clientOrderId', 'id')
request = {
'account-group': accountGroup,
'account-category': accountCategory,
'symbol': market['id'],
'time': self.milliseconds(),
'orderQty': self.amount_to_precision(symbol, amount),
'orderType': type, # "limit", "market", "stop_market", "stop_limit"
'side': side, # "buy" or "sell"
# 'orderPrice': self.price_to_precision(symbol, price),
# 'stopPrice': self.price_to_precision(symbol, stopPrice), # required for stop orders
# 'postOnly': 'false', # 'false', 'true'
# 'timeInForce': 'GTC', # GTC, IOC, FOK
# 'respInst': 'ACK', # ACK, 'ACCEPT, DONE
}
if clientOrderId is not None:
request['id'] = clientOrderId
params = self.omit(params, ['clientOrderId', 'id'])
if (type == 'limit') or (type == 'stop_limit'):
request['orderPrice'] = self.price_to_precision(symbol, price)
if (type == 'stop_limit') or (type == 'stop_market'):
stopPrice = self.safe_number(params, 'stopPrice')
if stopPrice is None:
raise InvalidOrder(self.id + ' createOrder() requires a stopPrice parameter for ' + type + ' orders')
else:
request['stopPrice'] = self.price_to_precision(symbol, stopPrice)
params = self.omit(params, 'stopPrice')
defaultMethod = self.safe_string(options, 'method', 'v1PrivateAccountCategoryPostOrder')
method = self.get_supported_mapping(style, {
'spot': defaultMethod,
'margin': defaultMethod,
'swap': 'v2PrivateAccountGroupPostFuturesOrder',
})
if method == 'v1PrivateAccountCategoryPostOrder':
if accountCategory is not None:
request['category'] = accountCategory
else:
request['account-category'] = accountCategory
response = await getattr(self, method)(self.extend(request, query))
#
# AccountCategoryPostOrder
#
# {
# "code": 0,
# "data": {
# "ac": "MARGIN",
# "accountId": "cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo",
# "action": "place-order",
# "info": {
# "id": "16e607e2b83a8bXHbAwwoqDo55c166fa",
# "orderId": "16e85b4d9b9a8bXHbAwwoqDoc3d66830",
# "orderType": "Market",
# "symbol": "BTC/USDT",
# "timestamp": 1573576916201
# },
# "status": "Ack"
# }
# }
#
# AccountGroupPostFuturesOrder
#
# {
# "code": 0,
# "data": {
# "meta": {
# "id": "",
# "action": "place-order",
# "respInst": "ACK"
# },
# "order": {
# "ac": "FUTURES",
# "accountId": "fut2ODPhGiY71Pl4vtXnOZ00ssgD7QGn",
# "time": 1640819389454,
# "orderId": "a17e0874ecbdU0711043490bbtcpDU5X",
# "seqNum": -1,
# "orderType": "Limit",
# "execInst": "NULL_VAL",
# "side": "Buy",
# "symbol": "BTC-PERP",
# "price": "30000",
# "orderQty": "0.002",
# "stopPrice": "0",
# "stopBy": "ref-px",
# "status": "Ack",
# "lastExecTime": 1640819389454,
# "lastQty": "0",
# "lastPx": "0",
# "avgFilledPx": "0",
# "cumFilledQty": "0",
# "fee": "0",
# "cumFee": "0",
# "feeAsset": "",
# "errorCode": "",
# "posStopLossPrice": "0",
# "posStopLossTrigger": "market",
# "posTakeProfitPrice": "0",
# "posTakeProfitTrigger": "market",
# "liquidityInd": "n"
# }
# }
# }
#
data = self.safe_value(response, 'data', {})
order = self.safe_value_2(data, 'order', 'info', {})
return self.parse_order(order, market)
async def fetch_order(self, id, symbol=None, params={}):
await self.load_markets()
await self.load_accounts()
market = None
if symbol is not None:
market = self.market(symbol)
type, query = self.handle_market_type_and_params('fetchOrder', market, params)
options = self.safe_value(self.options, 'fetchOrder', {})
accountCategories = self.safe_value(self.options, 'accountCategories', {})
accountCategory = self.safe_string(accountCategories, type, 'cash')
account = self.safe_value(self.accounts, 0, {})
accountGroup = self.safe_value(account, 'id')
request = {
'account-group': accountGroup,
'account-category': accountCategory,
'orderId': id,
}
defaultMethod = self.safe_string(options, 'method', 'v1PrivateAccountCategoryGetOrderStatus')
method = self.get_supported_mapping(type, {
'spot': defaultMethod,
'margin': defaultMethod,
'swap': 'v2PrivateAccountGroupGetFuturesOrderStatus',
})
if method == 'v1PrivateAccountCategoryGetOrderStatus':
if accountCategory is not None:
request['category'] = accountCategory
else:
request['account-category'] = accountCategory
response = await getattr(self, method)(self.extend(request, query))
#
# AccountCategoryGetOrderStatus
#
# {
# "code": 0,
# "accountCategory": "CASH",
# "accountId": "cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo",
# "data": [
# {
# "symbol": "BTC/USDT",
# "price": "8131.22",
# "orderQty": "0.00082",
# "orderType": "Market",
# "avgPx": "7392.02",
# "cumFee": "0.005152238",
# "cumFilledQty": "0.00082",
# "errorCode": "",
# "feeAsset": "USDT",
# "lastExecTime": 1575953151764,
# "orderId": "a16eee20b6750866943712zWEDdAjt3",
# "seqNum": 2623469,
# "side": "Buy",
# "status": "Filled",
# "stopPrice": "",
# "execInst": "NULL_VAL"
# }
# ]
# }
#
# AccountGroupGetFuturesOrderStatus
#
# {
# "code": 0,
# "accountId": "fut2ODPhGiY71Pl4vtXnOZ00ssgD7QGn",
# "ac": "FUTURES",
# "data": {
# "ac": "FUTURES",
# "accountId": "fut2ODPhGiY71Pl4vtXnOZ00ssgD7QGn",
# "time": 1640247020217,
# "orderId": "r17de65747aeU0711043490bbtcp0cmt",
# "seqNum": 28796162908,
# "orderType": "Limit",
# "execInst": "NULL_VAL",
# "side": "Buy",
# "symbol": "BTC-PERP",
# "price": "30000",
# "orderQty": "0.0021",
# "stopPrice": "0",
# "stopBy": "market",
# "status": "New",
# "lastExecTime": 1640247020232,
# "lastQty": "0",
# "lastPx": "0",
# "avgFilledPx": "0",
# "cumFilledQty": "0",
# "fee": "0",
# "cumFee": "0",
# "feeAsset": "USDT",
# "errorCode": "",
# "posStopLossPrice": "0",
# "posStopLossTrigger": "market",
# "posTakeProfitPrice": "0",
# "posTakeProfitTrigger": "market",
# "liquidityInd": "n"
# }
# }
#
data = self.safe_value(response, 'data', {})
return self.parse_order(data, market)
async def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
await self.load_markets()
await self.load_accounts()
market = None
if symbol is not None:
market = self.market(symbol)
account = self.safe_value(self.accounts, 0, {})
accountGroup = self.safe_value(account, 'id')
type, query = self.handle_market_type_and_params('fetchOpenOrders', market, params)
accountCategories = self.safe_value(self.options, 'accountCategories', {})
accountCategory = self.safe_string(accountCategories, type, 'cash')
request = {
'account-group': accountGroup,
'account-category': accountCategory,
}
options = self.safe_value(self.options, 'fetchOpenOrders', {})
defaultMethod = self.safe_string(options, 'method', 'v1PrivateAccountCategoryGetOrderOpen')
method = self.get_supported_mapping(type, {
'spot': defaultMethod,
'margin': defaultMethod,
'swap': 'v2PrivateAccountGroupGetFuturesOrderOpen',
})
if method == 'v1PrivateAccountCategoryGetOrderOpen':
if accountCategory is not None:
request['category'] = accountCategory
else:
request['account-category'] = accountCategory
response = await getattr(self, method)(self.extend(request, query))
#
# AccountCategoryGetOrderOpen
#
# {
# "ac": "CASH",
# "accountId": "cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo",
# "code": 0,
# "data": [
# {
# "avgPx": "0", # Average filled price of the order
# "cumFee": "0", # cumulative fee paid for self order
# "cumFilledQty": "0", # cumulative filled quantity
# "errorCode": "", # error code; could be empty
# "feeAsset": "USDT", # fee asset
# "lastExecTime": 1576019723550, # The last execution time of the order
# "orderId": "s16ef21882ea0866943712034f36d83", # server provided orderId
# "orderQty": "0.0083", # order quantity
# "orderType": "Limit", # order type
# "price": "7105", # order price
# "seqNum": 8193258, # sequence number
# "side": "Buy", # order side
# "status": "New", # order status on matching engine
# "stopPrice": "", # only available for stop market and stop limit orders; otherwise empty
# "symbol": "BTC/USDT",
# "execInst": "NULL_VAL" # execution instruction
# },
# ]
# }
#
# AccountGroupGetFuturesOrderOpen
#
# {
# "code": 0,
# "data": [
# {
# "ac": "FUTURES",
# "accountId": "fut2ODPhGiY71Pl4vtXnOZ00ssgD7QGn",
# "time": 1640247020217,
# "orderId": "r17de65747aeU0711043490bbtcp0cmt",
# "seqNum": 28796162908,
# "orderType": "Limit",
# "execInst": "NULL_VAL",
# "side": "Buy",
# "symbol": "BTC-PERP",
# "price": "30000",
# "orderQty": "0.0021",
# "stopPrice": "0",
# "stopBy": "market",
# "status": "New",
# "lastExecTime": 1640247020232,
# "lastQty": "0",
# "lastPx": "0",
# "avgFilledPx": "0",
# "cumFilledQty": "0",
# "fee": "0",
# "cumFee": "0",
# "feeAsset": "USDT",
# "errorCode": "",
# "posStopLossPrice": "0",
# "posStopLossTrigger": "market",
# "posTakeProfitPrice": "0",
# "posTakeProfitTrigger": "market",
# "liquidityInd": "n"
# }
# ]
# }
#
data = self.safe_value(response, 'data', [])
if accountCategory == 'futures':
return self.parse_orders(data, market, since, limit)
# a workaround for https://github.com/ccxt/ccxt/issues/7187
orders = []
for i in range(0, len(data)):
order = self.parse_order(data[i], market)
orders.append(order)
return self.filter_by_symbol_since_limit(orders, symbol, since, limit)
async def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}):
await self.load_markets()
await self.load_accounts()
account = self.safe_value(self.accounts, 0, {})
accountGroup = self.safe_value(account, 'id')
request = {
'account-group': accountGroup,
# 'category': accountCategory,
# 'symbol': market['id'],
# 'orderType': 'market', # optional, string
# 'side': 'buy', # or 'sell', optional, case insensitive.
# 'status': 'Filled', # "Filled", "Canceled", or "Rejected"
# 'startTime': exchange.milliseconds(),
# 'endTime': exchange.milliseconds(),
# 'page': 1,
# 'pageSize': 100,
}
market = None
if symbol is not None:
market = self.market(symbol)
request['symbol'] = market['id']
type, query = self.handle_market_type_and_params('fetchCLosedOrders', market, params)
options = self.safe_value(self.options, 'fetchClosedOrders', {})
defaultMethod = self.safe_string(options, 'method', 'v1PrivateAccountGroupGetOrderHist')
method = self.get_supported_mapping(type, {
'spot': defaultMethod,
'margin': defaultMethod,
'swap': 'v2PrivateAccountGroupGetFuturesOrderHistCurrent',
})
accountCategories = self.safe_value(self.options, 'accountCategories', {})
accountCategory = self.safe_string(accountCategories, type, 'cash')
if method == 'v1PrivateAccountGroupGetOrderHist':
if accountCategory is not None:
request['category'] = accountCategory
else:
request['account-category'] = accountCategory
if since is not None:
request['startTime'] = since
if limit is not None:
request['pageSize'] = limit
response = await getattr(self, method)(self.extend(request, query))
#
# accountCategoryGetOrderHistCurrent
#
# {
# "code":0,
# "accountId":"cshrHKLZCjlZ2ejqkmvIHHtPmLYqdnda",
# "ac":"CASH",
# "data":[
# {
# "seqNum":15561826728,
# "orderId":"a17294d305c0U6491137460bethu7kw9",
# "symbol":"ETH/USDT",
# "orderType":"Limit",
# "lastExecTime":1591635618200,
# "price":"200",
# "orderQty":"0.1",
# "side":"Buy",
# "status":"Canceled",
# "avgPx":"0",
# "cumFilledQty":"0",
# "stopPrice":"",
# "errorCode":"",
# "cumFee":"0",
# "feeAsset":"USDT",
# "execInst":"NULL_VAL"
# }
# ]
# }
#
# accountGroupGetOrderHist
#
# {
# "code": 0,
# "data": {
# "data": [
# {
# "ac": "FUTURES",
# "accountId": "testabcdefg",
# "avgPx": "0",
# "cumFee": "0",
# "cumQty": "0",
# "errorCode": "NULL_VAL",
# "execInst": "NULL_VAL",
# "feeAsset": "USDT",
# "lastExecTime": 1584072844085,
# "orderId": "r170d21956dd5450276356bbtcpKa74",
# "orderQty": "1.1499",
# "orderType": "Limit",
# "price": "4000",
# "sendingTime": 1584072841033,
# "seqNum": 24105338,
# "side": "Buy",
# "status": "Canceled",
# "stopPrice": "",
# "symbol": "BTC-PERP"
# },
# ],
# "hasNext": False,
# "limit": 500,
# "page": 1,
# "pageSize": 20
# }
# }
#
# accountGroupGetFuturesOrderHistCurrent
#
# {
# "code": 0,
# "data": [
# {
# "ac": "FUTURES",
# "accountId": "fut2ODPhGiY71Pl4vtXnOZ00ssgD7QGn",
# "time": 1640245777002,
# "orderId": "r17de6444fa6U0711043490bbtcpJ2lI",
# "seqNum": 28796124902,
# "orderType": "Limit",
# "execInst": "NULL_VAL",
# "side": "Buy",
# "symbol": "BTC-PERP",
# "price": "30000",
# "orderQty": "0.0021",
# "stopPrice": "0",
# "stopBy": "market",
# "status": "Canceled",
# "lastExecTime": 1640246574886,
# "lastQty": "0",
# "lastPx": "0",
# "avgFilledPx": "0",
# "cumFilledQty": "0",
# "fee": "0",
# "cumFee": "0",
# "feeAsset": "USDT",
# "errorCode": "",
# "posStopLossPrice": "0",
# "posStopLossTrigger": "market",
# "posTakeProfitPrice": "0",
# "posTakeProfitTrigger": "market",
# "liquidityInd": "n"
# }
# ]
# }
#
data = self.safe_value(response, 'data')
isArray = isinstance(data, list)
if not isArray:
data = self.safe_value(data, 'data', [])
return self.parse_orders(data, market, since, limit)
async def cancel_order(self, id, symbol=None, params={}):
if symbol is None:
raise ArgumentsRequired(self.id + ' cancelOrder() requires a symbol argument')
await self.load_markets()
await self.load_accounts()
market = self.market(symbol)
type, query = self.handle_market_type_and_params('cancelOrder', market, params)
options = self.safe_value(self.options, 'cancelOrder', {})
accountCategories = self.safe_value(self.options, 'accountCategories', {})
accountCategory = self.safe_string(accountCategories, type, 'cash')
account = self.safe_value(self.accounts, 0, {})
accountGroup = self.safe_value(account, 'id')
request = {
'account-group': accountGroup,
'account-category': accountCategory,
'symbol': market['id'],
'time': self.milliseconds(),
'id': 'foobar',
}
defaultMethod = self.safe_string(options, 'method', 'v1PrivateAccountCategoryDeleteOrder')
method = self.get_supported_mapping(type, {
'spot': defaultMethod,
'margin': defaultMethod,
'swap': 'v2PrivateAccountGroupDeleteFuturesOrder',
})
if method == 'v1PrivateAccountCategoryDeleteOrder':
if accountCategory is not None:
request['category'] = accountCategory
else:
request['account-category'] = accountCategory
clientOrderId = self.safe_string_2(params, 'clientOrderId', 'id')
if clientOrderId is None:
request['orderId'] = id
else:
request['id'] = clientOrderId
params = self.omit(params, ['clientOrderId', 'id'])
response = await getattr(self, method)(self.extend(request, query))
#
# AccountCategoryDeleteOrder
#
# {
# "code": 0,
# "data": {
# "accountId": "cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo",
# "ac": "CASH",
# "action": "cancel-order",
# "status": "Ack",
# "info": {
# "id": "wv8QGquoeamhssvQBeHOHGQCGlcBjj23",
# "orderId": "16e6198afb4s8bXHbAwwoqDo2ebc19dc",
# "orderType": "", # could be empty
# "symbol": "ETH/USDT",
# "timestamp": 1573594877822
# }
# }
# }
#
# AccountGroupDeleteFuturesOrder
#
# {
# "code": 0,
# "data": {
# "meta": {
# "id": "foobar",
# "action": "cancel-order",
# "respInst": "ACK"
# },
# "order": {
# "ac": "FUTURES",
# "accountId": "fut2ODPhGiY71Pl4vtXnOZ00ssgD7QGn",
# "time": 1640244480476,
# "orderId": "r17de63086f4U0711043490bbtcpPUF4",
# "seqNum": 28795959269,
# "orderType": "Limit",
# "execInst": "NULL_VAL",
# "side": "Buy",
# "symbol": "BTC-PERP",
# "price": "30000",
# "orderQty": "0.0021",
# "stopPrice": "0",
# "stopBy": "market",
# "status": "New",
# "lastExecTime": 1640244480491,
# "lastQty": "0",
# "lastPx": "0",
# "avgFilledPx": "0",
# "cumFilledQty": "0",
# "fee": "0",
# "cumFee": "0",
# "feeAsset": "BTCPC",
# "errorCode": "",
# "posStopLossPrice": "0",
# "posStopLossTrigger": "market",
# "posTakeProfitPrice": "0",
# "posTakeProfitTrigger": "market",
# "liquidityInd": "n"
# }
# }
# }
#
data = self.safe_value(response, 'data', {})
order = self.safe_value_2(data, 'order', 'info', {})
return self.parse_order(order, market)
async def cancel_all_orders(self, symbol=None, params={}):
await self.load_markets()
await self.load_accounts()
market = None
if symbol is not None:
market = self.market(symbol)
type, query = self.handle_market_type_and_params('cancelAllOrders', market, params)
options = self.safe_value(self.options, 'cancelAllOrders', {})
accountCategories = self.safe_value(self.options, 'accountCategories', {})
accountCategory = self.safe_string(accountCategories, type, 'cash')
account = self.safe_value(self.accounts, 0, {})
accountGroup = self.safe_value(account, 'id')
request = {
'account-group': accountGroup,
'account-category': accountCategory,
'time': self.milliseconds(),
}
if symbol is not None:
request['symbol'] = market['id']
defaultMethod = self.safe_string(options, 'method', 'v1PrivateAccountCategoryDeleteOrderAll')
method = self.get_supported_mapping(type, {
'spot': defaultMethod,
'margin': defaultMethod,
'swap': 'v2PrivateAccountGroupDeleteFuturesOrderAll',
})
if method == 'v1PrivateAccountCategoryDeleteOrderAll':
if accountCategory is not None:
request['category'] = accountCategory
else:
request['account-category'] = accountCategory
response = await getattr(self, method)(self.extend(request, query))
#
# AccountCategoryDeleteOrderAll
#
# {
# "code": 0,
# "data": {
# "ac": "CASH",
# "accountId": "cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo",
# "action": "cancel-all",
# "info": {
# "id": "2bmYvi7lyTrneMzpcJcf2D7Pe9V1P9wy",
# "orderId": "",
# "orderType": "NULL_VAL",
# "symbol": "",
# "timestamp": 1574118495462
# },
# "status": "Ack"
# }
# }
#
# AccountGroupDeleteFuturesOrderAll
#
# {
# "code": 0,
# "data": {
# "ac": "FUTURES",
# "accountId": "fut2ODPhGiY71Pl4vtXnOZ00ssgD7QGn",
# "action": "cancel-all",
# "info": {
# "symbol":"BTC-PERP"
# }
# }
# }
#
return response
def parse_deposit_address(self, depositAddress, currency=None):
#
# {
# address: "0xe7c70b4e73b6b450ee46c3b5c0f5fb127ca55722",
# destTag: "",
# tagType: "",
# tagId: "",
# chainName: "ERC20",
# numConfirmations: 20,
# withdrawalFee: 1,
# nativeScale: 4,
# tips: []
# }
#
address = self.safe_string(depositAddress, 'address')
tagId = self.safe_string(depositAddress, 'tagId')
tag = self.safe_string(depositAddress, tagId)
self.check_address(address)
code = None if (currency is None) else currency['code']
chainName = self.safe_string(depositAddress, 'chainName')
network = self.safe_network(chainName)
return {
'currency': code,
'address': address,
'tag': tag,
'network': network,
'info': depositAddress,
}
def safe_network(self, networkId):
# TODO: parse network
return networkId
async def fetch_deposit_address(self, code, params={}):
await self.load_markets()
currency = self.currency(code)
chainName = self.safe_string(params, 'chainName')
params = self.omit(params, 'chainName')
request = {
'asset': currency['id'],
}
response = await self.v1PrivateGetWalletDepositAddress(self.extend(request, params))
#
# {
# "code":0,
# "data":{
# "asset":"USDT",
# "assetName":"Tether",
# "address":[
# {
# "address":"1N22odLHXnLPCjC8kwBJPTayarr9RtPod6",
# "destTag":"",
# "tagType":"",
# "tagId":"",
# "chainName":"Omni",
# "numConfirmations":3,
# "withdrawalFee":4.7,
# "nativeScale":4,
# "tips":[]
# },
# {
# "address":"0xe7c70b4e73b6b450ee46c3b5c0f5fb127ca55722",
# "destTag":"",
# "tagType":"",
# "tagId":"",
# "chainName":"ERC20",
# "numConfirmations":20,
# "withdrawalFee":1.0,
# "nativeScale":4,
# "tips":[]
# }
# ]
# }
# }
#
data = self.safe_value(response, 'data', {})
addresses = self.safe_value(data, 'address', [])
numAddresses = len(addresses)
address = None
if numAddresses > 1:
addressesByChainName = self.index_by(addresses, 'chainName')
if chainName is None:
chainNames = list(addressesByChainName.keys())
chains = ', '.join(chainNames)
raise ArgumentsRequired(self.id + ' fetchDepositAddress returned more than one address, a chainName parameter is required, one of ' + chains)
address = self.safe_value(addressesByChainName, chainName, {})
else:
# first address
address = self.safe_value(addresses, 0, {})
result = self.parse_deposit_address(address, currency)
return self.extend(result, {
'info': response,
})
async def fetch_deposits(self, code=None, since=None, limit=None, params={}):
request = {
'txType': 'deposit',
}
return await self.fetch_transactions(code, since, limit, self.extend(request, params))
async def fetch_withdrawals(self, code=None, since=None, limit=None, params={}):
request = {
'txType': 'withdrawal',
}
return await self.fetch_transactions(code, since, limit, self.extend(request, params))
async def fetch_transactions(self, code=None, since=None, limit=None, params={}):
await self.load_markets()
request = {
# 'asset': currency['id'],
# 'page': 1,
# 'pageSize': 20,
# 'startTs': self.milliseconds(),
# 'endTs': self.milliseconds(),
# 'txType': undefned, # deposit, withdrawal
}
currency = None
if code is not None:
currency = self.currency(code)
request['asset'] = currency['id']
if since is not None:
request['startTs'] = since
if limit is not None:
request['pageSize'] = limit
response = await self.v1PrivateGetWalletTransactions(self.extend(request, params))
#
# {
# code: 0,
# data: {
# data: [
# {
# requestId: "wuzd1Ojsqtz4bCA3UXwtUnnJDmU8PiyB",
# time: 1591606166000,
# asset: "USDT",
# transactionType: "deposit",
# amount: "25",
# commission: "0",
# networkTransactionId: "0xbc4eabdce92f14dbcc01d799a5f8ca1f02f4a3a804b6350ea202be4d3c738fce",
# status: "pending",
# numConfirmed: 8,
# numConfirmations: 20,
# destAddress: {address: "0xe7c70b4e73b6b450ee46c3b5c0f5fb127ca55722"}
# }
# ],
# page: 1,
# pageSize: 20,
# hasNext: False
# }
# }
#
data = self.safe_value(response, 'data', {})
transactions = self.safe_value(data, 'data', [])
return self.parse_transactions(transactions, currency, since, limit)
def parse_transaction_status(self, status):
statuses = {
'reviewing': 'pending',
'pending': 'pending',
'confirmed': 'ok',
'rejected': 'rejected',
}
return self.safe_string(statuses, status, status)
def parse_transaction(self, transaction, currency=None):
#
# {
# requestId: "wuzd1Ojsqtz4bCA3UXwtUnnJDmU8PiyB",
# time: 1591606166000,
# asset: "USDT",
# transactionType: "deposit",
# amount: "25",
# commission: "0",
# networkTransactionId: "0xbc4eabdce92f14dbcc01d799a5f8ca1f02f4a3a804b6350ea202be4d3c738fce",
# status: "pending",
# numConfirmed: 8,
# numConfirmations: 20,
# destAddress: {
# address: "0xe7c70b4e73b6b450ee46c3b5c0f5fb127ca55722",
# destTag: "..." # for currencies that have it
# }
# }
#
id = self.safe_string(transaction, 'requestId')
amount = self.safe_number(transaction, 'amount')
destAddress = self.safe_value(transaction, 'destAddress', {})
address = self.safe_string(destAddress, 'address')
tag = self.safe_string(destAddress, 'destTag')
txid = self.safe_string(transaction, 'networkTransactionId')
type = self.safe_string(transaction, 'transactionType')
timestamp = self.safe_integer(transaction, 'time')
currencyId = self.safe_string(transaction, 'asset')
code = self.safe_currency_code(currencyId, currency)
status = self.parse_transaction_status(self.safe_string(transaction, 'status'))
feeCost = self.safe_number(transaction, 'commission')
return {
'info': transaction,
'id': id,
'currency': code,
'amount': amount,
'address': address,
'addressTo': address,
'addressFrom': None,
'tag': tag,
'tagTo': tag,
'tagFrom': None,
'status': status,
'type': type,
'updated': None,
'txid': txid,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'fee': {
'currency': code,
'cost': feeCost,
},
}
async def fetch_positions(self, symbols=None, params={}):
await self.load_markets()
await self.load_accounts()
account = self.safe_value(self.accounts, 0, {})
accountGroup = self.safe_string(account, 'id')
request = {
'account-group': accountGroup,
}
return await self.v2PrivateAccountGroupGetFuturesPosition(self.extend(request, params))
def parse_funding_rate(self, fundingRate, market=None):
#
# {
# "time": 1640061364830,
# "symbol": "EOS-PERP",
# "markPrice": "3.353854865",
# "indexPrice": "3.3542",
# "openInterest": "14242",
# "fundingRate": "-0.000073026",
# "nextFundingTime": 1640073600000
# }
#
marketId = self.safe_string(fundingRate, 'symbol')
symbol = self.safe_symbol(marketId, market)
currentTime = self.safe_integer(fundingRate, 'time')
nextFundingRate = self.safe_number(fundingRate, 'fundingRate')
nextFundingRateTimestamp = self.safe_integer(fundingRate, 'nextFundingTime')
previousFundingTimestamp = None
return {
'info': fundingRate,
'symbol': symbol,
'markPrice': self.safe_number(fundingRate, 'markPrice'),
'indexPrice': self.safe_number(fundingRate, 'indexPrice'),
'interestRate': self.parse_number('0'),
'estimatedSettlePrice': None,
'timestamp': currentTime,
'datetime': self.iso8601(currentTime),
'previousFundingRate': None,
'nextFundingRate': nextFundingRate,
'previousFundingTimestamp': previousFundingTimestamp,
'nextFundingTimestamp': nextFundingRateTimestamp,
'previousFundingDatetime': self.iso8601(previousFundingTimestamp),
'nextFundingDatetime': self.iso8601(nextFundingRateTimestamp),
}
async def fetch_funding_rates(self, symbols, params={}):
await self.load_markets()
response = await self.v2PublicGetFuturesPricingData(params)
#
# {
# "code": 0,
# "data": {
# "contracts": [
# {
# "time": 1640061364830,
# "symbol": "EOS-PERP",
# "markPrice": "3.353854865",
# "indexPrice": "3.3542",
# "openInterest": "14242",
# "fundingRate": "-0.000073026",
# "nextFundingTime": 1640073600000
# },
# ],
# "collaterals": [
# {
# "asset": "USDTR",
# "referencePrice": "1"
# },
# ]
# }
# }
#
data = self.safe_value(response, 'data', {})
contracts = self.safe_value(data, 'contracts', [])
result = self.parse_funding_rates(contracts)
return self.filter_by_array(result, 'symbol', symbols)
async def set_leverage(self, leverage, symbol=None, params={}):
if symbol is None:
raise ArgumentsRequired(self.id + ' setLeverage() requires a symbol argument')
if (leverage < 1) or (leverage > 100):
raise BadRequest(self.id + ' leverage should be between 1 and 100')
await self.load_markets()
await self.load_accounts()
market = self.market(symbol)
if market['type'] != 'future':
raise BadSymbol(self.id + ' setLeverage() supports futures contracts only')
account = self.safe_value(self.accounts, 0, {})
accountGroup = self.safe_string(account, 'id')
request = {
'account-group': accountGroup,
'symbol': market['id'],
'leverage': leverage,
}
return await self.v2PrivateAccountGroupPostFuturesLeverage(self.extend(request, params))
async def set_margin_mode(self, marginType, symbol=None, params={}):
if marginType != 'isolated' and marginType != 'crossed':
raise BadRequest(self.id + ' setMarginMode() marginType argument should be isolated or crossed')
await self.load_markets()
await self.load_accounts()
market = self.market(symbol)
account = self.safe_value(self.accounts, 0, {})
accountGroup = self.safe_string(account, 'id')
request = {
'account-group': accountGroup,
'symbol': market['id'],
'marginType': marginType,
}
if market['type'] != 'future':
raise BadSymbol(self.id + ' setMarginMode() supports futures contracts only')
return await self.v2PrivateAccountGroupPostFuturesMarginType(self.extend(request, params))
def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
version = api[0]
access = api[1]
type = self.safe_string(api, 2)
url = ''
accountCategory = (type == 'accountCategory')
if accountCategory or (type == 'accountGroup'):
url += self.implode_params('/{account-group}', params)
params = self.omit(params, 'account-group')
request = self.implode_params(path, params)
url += '/api/pro/'
if version == 'v2':
request = version + '/' + request
else:
url += version + '/'
if accountCategory:
url += self.implode_params('{account-category}/', params)
params = self.omit(params, 'account-category')
url += request
if (version == 'v1') and (request == 'cash/balance') or (request == 'margin/balance'):
request = 'balance'
if request.find('subuser') >= 0:
parts = request.split('/')
request = parts[2]
params = self.omit(params, self.extract_params(path))
if access == 'public':
if params:
url += '?' + self.urlencode(params)
else:
self.check_required_credentials()
timestamp = str(self.milliseconds())
payload = timestamp + '+' + request
hmac = self.hmac(self.encode(payload), self.encode(self.secret), hashlib.sha256, 'base64')
headers = {
'x-auth-key': self.apiKey,
'x-auth-timestamp': timestamp,
'x-auth-signature': hmac,
}
if method == 'GET':
if params:
url += '?' + self.urlencode(params)
else:
headers['Content-Type'] = 'application/json'
body = self.json(params)
url = self.urls['api'] + url
return {'url': url, 'method': method, 'body': body, 'headers': headers}
def handle_errors(self, httpCode, reason, url, method, headers, body, response, requestHeaders, requestBody):
if response is None:
return # fallback to default error handler
#
# {'code': 6010, 'message': 'Not enough balance.'}
# {'code': 60060, 'message': 'The order is already filled or canceled.'}
# {"code":2100,"message":"ApiKeyFailure"}
# {"code":300001,"message":"Price is too low from market price.","reason":"INVALID_PRICE","accountId":"cshrHKLZCjlZ2ejqkmvIHHtPmLYqdnda","ac":"CASH","action":"place-order","status":"Err","info":{"symbol":"BTC/USDT"}}
#
code = self.safe_string(response, 'code')
message = self.safe_string(response, 'message')
error = (code is not None) and (code != '0')
if error or (message is not None):
feedback = self.id + ' ' + body
self.throw_exactly_matched_exception(self.exceptions['exact'], code, feedback)
self.throw_exactly_matched_exception(self.exceptions['exact'], message, feedback)
self.throw_broadly_matched_exception(self.exceptions['broad'], message, feedback)
raise ExchangeError(feedback) # unknown message
|
py | 1a4591a262b097ec90f0c53eeebc8b22cf154c9e | """AI."""
from mgz import Version
from mgz.util import Find
from construct import (Array, Byte, If, Int16ul, Int32sl, Int32ul, Padding,
PascalString, Struct, this, IfThenElse)
# pylint: disable=invalid-name
script = "script"/Struct(
Padding(4),
"seq"/Int32sl,
"max_rules"/Int16ul,
"num_rules"/Int16ul,
Padding(4),
Array(this.num_rules, "rules"/Struct(
Padding(12),
"num_facts"/Byte,
"num_facts_actions"/Byte,
Padding(2),
Array(16, "data"/Struct(
"type"/Int32ul,
"id"/Int16ul,
Padding(2),
Array(4, "params"/Int32ul)
))
))
)
ai = "ai"/Struct(
"has_ai"/Int32ul, # if true, parse AI
"yep"/If(
this.has_ai == 1,
IfThenElse(
lambda ctx: ctx._.version == Version.DE,
Find(b'\00' * 4096, None), # The ai structure in DE seems to have changed, for now we simply skip it
"ais"/Struct(
"max_strings"/Int16ul,
"num_strings"/Int16ul,
Padding(4),
Array(this.num_strings, "strings"/PascalString(lengthfield="name_length"/Int32ul,
encoding='latin1')),
Padding(6),
Array(8, script),
Padding(104),
Array(80, "timers"/Int32sl),
Array(256, "shared_goals"/Int32sl),
Padding(4096),
)
)
)
)
|
py | 1a4591d0cab685cbf9c22e2bbb7acbcec083d876 | # Copyright (c) 2020 Graphcore Ltd. All rights reserved.
from contextlib import contextmanager
import copy
import fcntl
import hashlib
import os
from typing import Dict, Any
import torch
# Do not import any poptorch.* here: it will break the poptorch module
from ._logging import logger
from . import poptorch_core
# A flag to tell the user if the current target is IPU. This is to allow
# divergent IPU/CPU codepaths within one model.
_is_ipu_context = False
def createPoptorchError(msg):
type = "poptorch_py_error"
error = poptorch_core.Error(f"'{type}': {msg}")
error.type = type
error.message = msg
error.location = ""
return error
def isRunningOnIpu() -> bool:
""" This function returns `True` when executing on IPU and `False` when
executing the model outside IPU scope. This allows for separate
codepaths to be marked in the model simply by using:
>>> if poptorch.isRunningOnIpu():
>>> # IPU path
>>> else:
>>> # CPU path
Note this will only apply to code during execution. During model
creation it will always return `False`.
:returns: True if running on IPU, otherwise False.
"""
global _is_ipu_context
return _is_ipu_context
def setIpuContext(val: bool):
global _is_ipu_context
_is_ipu_context = val
def internal_cast(tensor, dtype):
if dtype in [torch.float, torch.float32]:
return torch.ops.poptorch.internal_cast(tensor, "FLOAT")
if dtype in [torch.half, torch.float16]:
return torch.ops.poptorch.internal_cast(tensor, "FLOAT16")
raise ValueError(
'Invalid poptorch.cast target type. Expecting torch.float or torch.half'
)
def applyOptimizer(optimizer):
num_groups = len(optimizer.param_groups)
for index in range(0, num_groups):
torch.ops.poptorch.optimizer_group(
index, optimizer.param_groups[index]["params"])
# To understand which variable groups the user wants to apply the
# optimizer to we need to mark them via a wrapper. We do this because
# when we reference the variables in the context of the operation we
# get the corresponding IR value for "free" as part of the trace.
# Otherwise we would need a system to map the variable in the optimizer
# to the variable in the model to the variable in the IR.
class OptimizerWrapper(torch.nn.Module):
def __init__(self, model, optimizer):
super().__init__()
self.model = model
self.optimizer = optimizer
def forward(self, *args, **kwargs):
out = self.model(*args, **kwargs)
applyOptimizer(self.optimizer)
return out
@contextmanager
def distributedCacheLock(model, opts):
"""In a distributed environment we only want the model to be compiled once.
If there is only one process or if the cache is not enabled:
no need for a lock, early return.
Otherwise:
The first process to reach the lock takes it and compiles the model.
The model will be added to the PopART cache.
After the first process releases the lock the other ones will grab it
one at the time and compile the model too (Except that they will
now all hit the cache).
The last process to grab / release the lock will delete the file.
(Each process append a character to the file, so the position in
the file when acquiring the lock indicates how many processes have
already successfully compiled the model).
"""
filename = None
if opts.Distributed.numProcesses > 1:
cache = opts._popart.options.get("cachePath", "") # pylint: disable=protected-access
if not cache:
logger.warning(
"Use poptorch.Options.enableExecutableCaching() to avoid "
"compiling the model once per process")
else:
os.makedirs(cache, exist_ok=True)
assert os.access(cache, os.W_OK), (f"Cache folder {cache}"
" is not writable")
filename = os.path.join(
cache, "%s.lock" %
hashlib.md5(repr(model).encode("utf-8")).hexdigest())
# Not distributed mode or the cache is not enabled: do nothing.
if not filename:
yield False
return
delete_file = False
try:
with open(filename, "a+") as f:
try:
fcntl.flock(f, fcntl.LOCK_EX)
# Add a character to the file
f.write("0")
logger.debug(
"Executable cache file locked by process %s (pos %d/%d)",
opts.Distributed.processId, f.tell(),
opts.Distributed.numProcesses)
delete_file = f.tell() == opts.Distributed.numProcesses
# Only the first process should compile
yield f.tell() == 1
finally:
logger.debug("Process %s released the cache lock",
opts.Distributed.processId)
fcntl.flock(f, fcntl.LOCK_UN)
finally:
if delete_file:
os.remove(filename)
# The pickle handlers are called in two cases: when an object is copied
# (i.e copy.copy(obj)) or when an object is pickled / serialised.
# In both cases the object is first dumped using pickleUnwrapModel and then
# in the copy case _pickleRestoreWrapperIfPossible() is called immediately after
# to create the new object.
#
# The _wrapper_registry keeps track of the mapping between user model, parameter,
# buffer types and their corresponding wrapper.
# When an object is copied we want to preserve the Wrapper type: the PopTorch
# wrapper doesn't contain any attribute so it's just a question of updating
# the __class__attribute.
#
# When an object is loaded from file: the wrapper type doesn't exist anymore
# therefore we keep the object unwrapped. (It will be wrapped again when passed
# to poptorch.trainingModel anyway)
_wrapper_registry: Dict[int, Any] = {}
def _pickleRestoreWrapperIfPossible(obj):
wrapperType = _wrapper_registry.get(id(obj))
if wrapperType:
obj.__class__ = wrapperType
return obj
def pickleUnwrapObject(obj):
global _wrapper_registry
wrapperType = obj.__class__
obj.__class__ = obj.__class__.__bases__[0]
other = copy.copy(obj)
_wrapper_registry[id(other)] = wrapperType
obj.__class__ = wrapperType
return _pickleRestoreWrapperIfPossible, (other, )
|
py | 1a4592937c1e0fd206743da517aa80c081c86491 | #excersise when we create 2 inherited classes from main Turtle. Each has defined function to turn in predefined direction.
#after we create 20 turtles and list them
#we check the turtles in list and assign pen colors
#let all turtles draw square, each with assigned color and turning in predefined direction
from turtle import Turtle
from random import randrange as rr
class Turtle1(Turtle): #creating inherited class from Turtle and defining function to turn it in predefined direction.
def otoc(self, uhol):
self.lt(uhol)
class Turtle2(Turtle): #creating inherited class from Turtle and defining function to turn it in predefined direction
def otoc(self, uhol):
self.rt(uhol)
zoz = [] #list of created turtles
for i in range(20): #creating 20 turtles, if o=0 Turtle1 is created, if o=1 Turtle2 is created
o = rr(0, 2)
if o == 0:
t1 = Turtle1()
t1.seth(0)
t1.pu()
t1.setpos(-200 + i * 20, 0)
t1.pd()
zoz.append(t1) #adding turtle into list
else:
t2 = Turtle2()
t2.seth(0)
t2.pu()
t2.setpos(-200 + i * 20, 0)
t2.pd()
zoz.append(t2) #adding turtle into list
for t in zoz: #checking the list of turtles one by one. Changing pen color based on turtle instance
if isinstance(t, Turtle1):
t.pencolor('red')
elif isinstance(t, Turtle2):
t.pencolor('blue')
for i in range(4): #moving turtles one after another to draw square
for t in zoz:
t.fd(20)
t.otoc(90)
|
py | 1a45931409085322817df8b6c20561cc3bdf19ce | # Copyright 2019 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Circuit class specification for the general Gaussian Boson Sampling class of circuits."""
from strawberryfields.program_utils import CircuitError, Command, group_operations
import strawberryfields.ops as ops
from .gaussian import GaussianSpecs
class GBSSpecs(GaussianSpecs):
"""Circuit specifications for the general GBS class of circuits."""
short_name = 'gbs'
primitives = {
# meta operations
"All",
"_New_modes",
"_Delete",
# state preparations
"Vacuum",
"Coherent",
"Squeezed",
"DisplacedSqueezed",
"Thermal",
"Gaussian",
# measurements
"MeasureHomodyne",
"MeasureHeterodyne",
"MeasureFock",
"MeasureThreshold",
# channels
"LossChannel",
"ThermalLossChannel",
# single mode gates
"Dgate",
"Xgate",
"Zgate",
"Sgate",
"Rgate",
"Fouriergate",
"BSgate"
}
def compile(self, seq, registers):
"""Try to arrange a quantum circuit into a form suitable for Gaussian boson sampling.
This method checks whether the circuit can be implemented as a Gaussian boson sampling
problem, i.e., if it is equivalent to a circuit A+B, where the sequence A only contains
Gaussian operations, and B only contains Fock measurements.
If the answer is yes, the circuit is arranged into the A+B order, and all the Fock
measurements are combined into a single :class:`MeasureFock` operation.
Args:
seq (Sequence[Command]): quantum circuit to modify
registers (Sequence[RegRefs]): quantum registers
Returns:
List[Command]: modified circuit
Raises:
CircuitError: the circuit does not correspond to GBS
"""
A, B, C = group_operations(seq, lambda x: isinstance(x, ops.MeasureFock))
# C should be empty
if C:
raise CircuitError('Operations following the Fock measurements.')
# A should only contain Gaussian operations
# (but this is already guaranteed by group_operations() and our primitive set)
# without Fock measurements GBS is pointless
if not B:
raise CircuitError('GBS circuits must contain Fock measurements.')
# there should be only Fock measurements in B
measured = set()
for cmd in B:
if not isinstance(cmd.op, ops.MeasureFock):
raise CircuitError('The Fock measurements are not consecutive.')
# combine the Fock measurements
temp = set(cmd.reg)
if measured & temp:
raise CircuitError('Measuring the same mode more than once.')
measured |= temp
# replace B with a single Fock measurement
B = [Command(ops.MeasureFock(), sorted(list(measured), key=lambda x: x.ind))]
return super().compile(A + B, registers)
|
py | 1a45932fa3df4c5c12f833d3802a9bbb98196498 | #In 1
from __future__ import print_function
from __future__ import division
import pandas as pd
import numpy as np
# from matplotlib import pyplot as plt
# import seaborn as sns
# from sklearn.model_selection import train_test_split
import statsmodels.api as sm
# just for the sake of this blog post!
from warnings import filterwarnings
filterwarnings('ignore')
#In 2
# load the provided data
train_features = pd.read_csv('data/dengue_features_train.csv',
index_col=[0,1,2])
train_labels = pd.read_csv('data/dengue_labels_train.csv',
index_col=[0,1,2])
# Separate data for Iquitos
iq_train_features = train_features.loc['iq']
iq_train_labels = train_labels.loc['iq']
iq_train_features.drop('week_start_date', axis=1, inplace=True)
#In 7
# Null check
iq_train_features.fillna(method='ffill', inplace=True)
#In 13
iq_train_features['total_cases'] = iq_train_labels.total_cases
#In 14
# compute the correlations
iq_correlations = iq_train_features.corr()
#In 19
def preprocess_data(data_path, labels_path=None):
# load data and set index to city, year, weekofyear
df = pd.read_csv(data_path, index_col=[0, 1, 2])
# select features we want
features = ['reanalysis_specific_humidity_g_per_kg',
'reanalysis_dew_point_temp_k',
'reanalysis_min_air_temp_k']
df = df[features]
# fill missing values
df.fillna(method='ffill', inplace=True)
# add labels to dataframe
if labels_path:
labels = pd.read_csv(labels_path, index_col=[0, 1, 2])
df = df.join(labels)
# separate san juan and iquitos
iq = df.loc['iq']
return iq
#In 20
iq_train = preprocess_data('data/dengue_features_train.csv',
labels_path="data/dengue_labels_train.csv")
iq_train_subtrain = iq_train
#iq_train_subtrain = iq_train.head(400)
iq_train_subtest = iq_train.tail(iq_train.shape[0] - 400)
#In 24
from statsmodels.tools import eval_measures
import statsmodels.formula.api as smf
def get_best_model(train, test):
# Step 1: specify the form of the model
model_formula = "total_cases ~ 1 + " \
"reanalysis_specific_humidity_g_per_kg + " \
"reanalysis_dew_point_temp_k + " \
"reanalysis_min_air_temp_k"
grid = 10 ** np.arange(-8, -3, dtype=np.float64)
best_alpha = []
best_score = 1000
# Step 2: Find the best hyper parameter, alpha
for alpha in grid:
model = smf.glm(formula=model_formula,
data=train,
family=sm.families.NegativeBinomial(alpha=alpha))
results = model.fit()
predictions = results.predict(test).astype(int)
score = eval_measures.meanabs(predictions, test.total_cases)
if score < best_score:
best_alpha = alpha
best_score = score
# Step 3: refit on entire dataset
full_dataset = pd.concat([train, test])
model = smf.glm(formula=model_formula,
data=full_dataset,
family=sm.families.NegativeBinomial(alpha=best_alpha))
fitted_model = model.fit()
return fitted_model
iq_best_model = get_best_model(iq_train_subtrain, iq_train_subtest)
iq_test = preprocess_data('data/dengue_features_test.csv')
iq_predictions = iq_best_model.predict(iq_test).astype(int)
submission = pd.read_csv("data/submission_format.csv",
index_col=[0, 1, 2])
submission.total_cases = np.concatenate([iq_predictions])
submission.to_csv("data/benchmark.csv")
|
py | 1a459580d661e9c16118d414074666e6a093b44f | """Xbox Media Source Implementation."""
from __future__ import annotations
from dataclasses import dataclass
from pydantic.error_wrappers import ValidationError # pylint: disable=no-name-in-module
from xbox.webapi.api.client import XboxLiveClient
from xbox.webapi.api.provider.catalog.models import FieldsTemplate, Image
from xbox.webapi.api.provider.gameclips.models import GameclipsResponse
from xbox.webapi.api.provider.screenshots.models import ScreenshotResponse
from xbox.webapi.api.provider.smartglass.models import InstalledPackage
from homeassistant.components.media_player.const import (
MEDIA_CLASS_DIRECTORY,
MEDIA_CLASS_GAME,
MEDIA_CLASS_IMAGE,
MEDIA_CLASS_VIDEO,
)
from homeassistant.components.media_source.const import MEDIA_MIME_TYPES
from homeassistant.components.media_source.models import (
BrowseMediaSource,
MediaSource,
MediaSourceItem,
PlayMedia,
)
from homeassistant.core import callback
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.util import dt as dt_util
from .browse_media import _find_media_image
from .const import DOMAIN
MIME_TYPE_MAP = {
"gameclips": "video/mp4",
"screenshots": "image/png",
}
MEDIA_CLASS_MAP = {
"gameclips": MEDIA_CLASS_VIDEO,
"screenshots": MEDIA_CLASS_IMAGE,
}
async def async_get_media_source(hass: HomeAssistantType):
"""Set up Xbox media source."""
entry = hass.config_entries.async_entries(DOMAIN)[0]
client = hass.data[DOMAIN][entry.entry_id]["client"]
return XboxSource(hass, client)
@callback
def async_parse_identifier(
item: MediaSourceItem,
) -> tuple[str, str, str]:
"""Parse identifier."""
identifier = item.identifier or ""
start = ["", "", ""]
items = identifier.lstrip("/").split("~~", 2)
return tuple(items + start[len(items) :])
@dataclass
class XboxMediaItem:
"""Represents gameclip/screenshot media."""
caption: str
thumbnail: str
uri: str
media_class: str
class XboxSource(MediaSource):
"""Provide Xbox screenshots and gameclips as media sources."""
name: str = "Xbox Game Media"
def __init__(self, hass: HomeAssistantType, client: XboxLiveClient):
"""Initialize Xbox source."""
super().__init__(DOMAIN)
self.hass: HomeAssistantType = hass
self.client: XboxLiveClient = client
async def async_resolve_media(self, item: MediaSourceItem) -> PlayMedia:
"""Resolve media to a url."""
_, category, url = async_parse_identifier(item)
kind = category.split("#", 1)[1]
return PlayMedia(url, MIME_TYPE_MAP[kind])
async def async_browse_media(
self, item: MediaSourceItem, media_types: tuple[str] = MEDIA_MIME_TYPES
) -> BrowseMediaSource:
"""Return media."""
title, category, _ = async_parse_identifier(item)
if not title:
return await self._build_game_library()
if not category:
return _build_categories(title)
return await self._build_media_items(title, category)
async def _build_game_library(self):
"""Display installed games across all consoles."""
apps = await self.client.smartglass.get_installed_apps()
games = {
game.one_store_product_id: game
for game in apps.result
if game.is_game and game.title_id
}
app_details = await self.client.catalog.get_products(
games.keys(),
FieldsTemplate.BROWSE,
)
images = {
prod.product_id: prod.localized_properties[0].images
for prod in app_details.products
}
return BrowseMediaSource(
domain=DOMAIN,
identifier="",
media_class=MEDIA_CLASS_DIRECTORY,
media_content_type="",
title="Xbox Game Media",
can_play=False,
can_expand=True,
children=[_build_game_item(game, images) for game in games.values()],
children_media_class=MEDIA_CLASS_GAME,
)
async def _build_media_items(self, title, category):
"""Fetch requested gameclip/screenshot media."""
title_id, _, thumbnail = title.split("#", 2)
owner, kind = category.split("#", 1)
items: list[XboxMediaItem] = []
try:
if kind == "gameclips":
if owner == "my":
response: GameclipsResponse = (
await self.client.gameclips.get_recent_clips_by_xuid(
self.client.xuid, title_id
)
)
elif owner == "community":
response: GameclipsResponse = await self.client.gameclips.get_recent_community_clips_by_title_id(
title_id
)
else:
return None
items = [
XboxMediaItem(
item.user_caption
or dt_util.as_local(
dt_util.parse_datetime(item.date_recorded)
).strftime("%b. %d, %Y %I:%M %p"),
item.thumbnails[0].uri,
item.game_clip_uris[0].uri,
MEDIA_CLASS_VIDEO,
)
for item in response.game_clips
]
elif kind == "screenshots":
if owner == "my":
response: ScreenshotResponse = (
await self.client.screenshots.get_recent_screenshots_by_xuid(
self.client.xuid, title_id
)
)
elif owner == "community":
response: ScreenshotResponse = await self.client.screenshots.get_recent_community_screenshots_by_title_id(
title_id
)
else:
return None
items = [
XboxMediaItem(
item.user_caption
or dt_util.as_local(item.date_taken).strftime(
"%b. %d, %Y %I:%M%p"
),
item.thumbnails[0].uri,
item.screenshot_uris[0].uri,
MEDIA_CLASS_IMAGE,
)
for item in response.screenshots
]
except ValidationError:
# Unexpected API response
pass
return BrowseMediaSource(
domain=DOMAIN,
identifier=f"{title}~~{category}",
media_class=MEDIA_CLASS_DIRECTORY,
media_content_type="",
title=f"{owner.title()} {kind.title()}",
can_play=False,
can_expand=True,
children=[_build_media_item(title, category, item) for item in items],
children_media_class=MEDIA_CLASS_MAP[kind],
thumbnail=thumbnail,
)
def _build_game_item(item: InstalledPackage, images: list[Image]):
"""Build individual game."""
thumbnail = ""
image = _find_media_image(images.get(item.one_store_product_id, []))
if image is not None:
thumbnail = image.uri
if thumbnail[0] == "/":
thumbnail = f"https:{thumbnail}"
return BrowseMediaSource(
domain=DOMAIN,
identifier=f"{item.title_id}#{item.name}#{thumbnail}",
media_class=MEDIA_CLASS_GAME,
media_content_type="",
title=item.name,
can_play=False,
can_expand=True,
children_media_class=MEDIA_CLASS_DIRECTORY,
thumbnail=thumbnail,
)
def _build_categories(title):
"""Build base categories for Xbox media."""
_, name, thumbnail = title.split("#", 2)
base = BrowseMediaSource(
domain=DOMAIN,
identifier=f"{title}",
media_class=MEDIA_CLASS_GAME,
media_content_type="",
title=name,
can_play=False,
can_expand=True,
children=[],
children_media_class=MEDIA_CLASS_DIRECTORY,
thumbnail=thumbnail,
)
owners = ["my", "community"]
kinds = ["gameclips", "screenshots"]
for owner in owners:
for kind in kinds:
base.children.append(
BrowseMediaSource(
domain=DOMAIN,
identifier=f"{title}~~{owner}#{kind}",
media_class=MEDIA_CLASS_DIRECTORY,
media_content_type="",
title=f"{owner.title()} {kind.title()}",
can_play=False,
can_expand=True,
children_media_class=MEDIA_CLASS_MAP[kind],
)
)
return base
def _build_media_item(title: str, category: str, item: XboxMediaItem):
"""Build individual media item."""
kind = category.split("#", 1)[1]
return BrowseMediaSource(
domain=DOMAIN,
identifier=f"{title}~~{category}~~{item.uri}",
media_class=item.media_class,
media_content_type=MIME_TYPE_MAP[kind],
title=item.caption,
can_play=True,
can_expand=False,
thumbnail=item.thumbnail,
)
|
py | 1a4595c9e200b1dff68681f43d025412390bfd75 | # Formatting configuration for locale ar_TN
languages={'el': u'\u0627\u0644\u064a\u0648\u0646\u0627\u0646\u064a\u0629', 'gu': u'\u0627\u0644\u063a\u0648\u062c\u0627\u0631\u0627\u062a\u064a\u0629', 'en': u'\u0627\u0644\u0627\u0646\u062c\u0644\u064a\u0632\u064a\u0629', 'zh': u'\u0627\u0644\u0635\u064a\u0646\u064a\u0629', 'sw': u'\u0627\u0644\u0633\u0648\u0627\u062d\u0644\u064a\u0629', 'ca': u'\u0627\u0644\u0643\u0627\u062a\u0627\u0644\u0648\u064a\u0646\u064a\u0629', 'it': u'\u0627\u0644\u0627\u064a\u0637\u0627\u0644\u064a\u0629', 'ar': u'\u0627\u0644\u0639\u0631\u0628\u064a\u0629', 'id': u'\u0627\u0644\u0627\u0646\u062f\u0648\u0646\u064a\u0633\u064a\u0629', 'es': u'\u0627\u0644\u0627\u0633\u0628\u0627\u0646\u064a\u0629', 'ru': u'\u0627\u0644\u0631\u0648\u0633\u064a\u0629', 'nl': u'\u0627\u0644\u0647\u0648\u0644\u0646\u062f\u064a\u0629', 'pt': u'\u0627\u0644\u0628\u0631\u062a\u063a\u0627\u0644\u064a\u0629', 'tr': u'\u0627\u0644\u062a\u0631\u0643\u064a\u0629', 'ne': u'\u0627\u0644\u0646\u064a\u0628\u0627\u0644\u064a\u0629', 'lt': u'\u0627\u0644\u0644\u062a\u0648\u0627\u0646\u064a\u0629', 'pa': u'\u0627\u0644\u0628\u0646\u062c\u0627\u0628\u064a\u0629', 'th': u'\u0627\u0644\u062a\u0627\u064a\u0644\u0627\u0646\u062f\u064a\u0629', 'vi': u'\u0627\u0644\u0641\u064a\u062a\u0646\u0627\u0645\u064a\u0629', 'ro': u'\u0627\u0644\u0631\u0648\u0645\u0627\u0646\u064a\u0629', 'be': u'\u0627\u0644\u0628\u064a\u0644\u0648\u0631\u0648\u0633\u064a\u0629', 'fr': u'\u0627\u0644\u0641\u0631\u0646\u0633\u064a\u0629', 'bg': u'\u0627\u0644\u0628\u0644\u063a\u0627\u0631\u064a\u0629', 'uk': u'\u0627\u0644\u0627\u0648\u0643\u0631\u0627\u0646\u064a\u0629', 'hr': u'\u0627\u0644\u0643\u0631\u0648\u0627\u062a\u064a\u0629', 'bn': u'\u0627\u0644\u0628\u0646\u063a\u0627\u0644\u064a\u0629', 'bo': u'\u0627\u0644\u062a\u0628\u062a\u064a\u0629', 'da': u'\u0627\u0644\u062f\u0627\u0646\u0645\u0627\u0631\u0643\u064a\u0629', 'fa': u'\u0627\u0644\u0641\u0627\u0631\u0633\u064a\u0629', 'hi': u'\u0627\u0644\u0647\u0646\u062f\u064a\u0629', 'dz': u'\u0627\u0644\u0632\u0648\u0646\u062e\u0627\u064a\u0629', 'dv': u'\u0627\u0644\u0645\u0627\u0644\u062f\u064a\u0641\u064a\u0629', 'fi': u'\u0627\u0644\u0641\u0646\u0644\u0646\u062f\u064a\u0629', 'ja': u'\u0627\u0644\u064a\u0627\u0628\u0627\u0646\u064a\u0629', 'he': u'\u0627\u0644\u0639\u0628\u0631\u064a\u0629', 'tl': u'\u0627\u0644\u062a\u0627\u063a\u0627\u0644\u0648\u063a\u064a\u0629', 'sr': u'\u0627\u0644\u0635\u0631\u0628\u064a\u0629', 'sq': u'\u0627\u0644\u0627\u0644\u0628\u0627\u0646\u064a\u0629', 'mn': u'\u0627\u0644\u0645\u0646\u063a\u0648\u0644\u064a\u0629', 'ko': u'\u0627\u0644\u0643\u0648\u0631\u064a\u0629', 'km': u'\u0627\u0644\u062e\u0645\u064a\u0631\u064a\u0629', 'ur': u'\u0627\u0644\u0627\u0631\u062f\u064a\u0629', 'de': u'\u0627\u0644\u0627\u0644\u0645\u0627\u0646\u064a\u0629', 'ms': u'\u0644\u063a\u0629 \u0627\u0644\u0645\u0644\u0627\u064a\u0648', 'ug': u'\u0627\u0644\u0627\u063a\u0648\u0631\u064a\u0629', 'my': u'\u0627\u0644\u0628\u0648\u0631\u0645\u064a\u0629'}
countries={'BD': u'\u0628\u0646\u063a\u0644\u0627\u062f\u064a\u0634', 'BE': u'\u0628\u0644\u062c\u064a\u0643\u0627', 'BF': u'\u0628\u0648\u0631\u0643\u064a\u0646\u0627 \u0641\u0627\u0633\u0648', 'BG': u'\u0628\u0644\u063a\u0627\u0631\u064a\u0627', 'BA': u'\u0627\u0644\u0628\u0648\u0633\u0646\u0629 \u0648\u0627\u0644\u0647\u0631\u0633\u0643', 'BB': u'\u0628\u0631\u0628\u0627\u062f\u0648\u0633', 'BN': u'\u0628\u0631\u0648\u0646\u0627\u064a', 'BO': u'\u0628\u0648\u0644\u064a\u0641\u064a\u0627', 'BH': u'\u0627\u0644\u0628\u062d\u0631\u064a\u0646', 'BI': u'\u0628\u0648\u0631\u0648\u0646\u062f\u064a', 'BJ': u'\u0628\u0646\u064a\u0646', 'BT': u'\u0628\u0648\u062a\u0627\u0646', 'JM': u'\u062c\u0627\u0645\u0627\u064a\u0643\u0627', 'BW': u'\u0628\u0648\u062a\u0633\u0648\u0627\u0646\u0627', 'WS': u'\u0633\u0627\u0645\u0648\u0627', 'BR': u'\u0627\u0644\u0628\u0631\u0627\u0632\u064a\u0644', 'BS': u'\u0627\u0644\u0628\u0647\u0627\u0645\u0627', 'BY': u'\u0631\u0648\u0633\u064a\u0627 \u0627\u0644\u0628\u064a\u0636\u0627\u0621', 'BZ': u'\u0628\u0644\u064a\u0632', 'RU': u'\u0631\u0648\u0633\u064a\u0627', 'RW': u'\u0631\u0648\u0627\u0646\u062f\u0627', 'TM': u'\u062a\u0631\u0643\u0645\u0627\u0646\u0633\u062a\u0627\u0646', 'TJ': u'\u062a\u0627\u062c\u064a\u0643\u0633\u062a\u0627\u0646', 'RO': u'\u0631\u0648\u0645\u0627\u0646\u064a\u0627', 'GW': u'\u063a\u064a\u0646\u064a\u0627 \u0628\u064a\u0633\u0627\u0648', 'GT': u'\u063a\u0648\u0627\u062a\u064a\u0645\u0627\u0644\u0627', 'GR': u'\u0627\u0644\u064a\u0648\u0646\u0627\u0646', 'GQ': u'\u063a\u064a\u0646\u064a\u0627 \u0627\u0644\u0627\u0633\u062a\u0648\u0627\u0626\u064a\u0629', 'JP': u'\u0627\u0644\u064a\u0627\u0628\u0627\u0646', 'GY': u'\u063a\u0648\u0627\u064a\u0627\u0646\u0627', 'GE': u'\u062c\u0648\u0631\u062c\u064a\u0627', 'GD': u'\u063a\u0631\u064a\u0646\u0627\u062f\u0627', 'GB': u'\u0627\u0644\u0645\u0645\u0644\u0643\u0629 \u0627\u0644\u0645\u062a\u062d\u062f\u0629', 'GA': u'\u063a\u0627\u0628\u0648\u0646', 'SV': u'\u0627\u0644\u0633\u0644\u0641\u0627\u062f\u0648\u0631', 'GN': u'\u063a\u064a\u0646\u064a\u0627', 'GM': u'\u063a\u0627\u0645\u0628\u064a\u0627', 'GH': u'\u063a\u0627\u0646\u0627', 'OM': u'\u0639\u0645\u0627\u0646', 'TN': u'\u062a\u0648\u0646\u0633', 'JO': u'\u0627\u0644\u0627\u0631\u062f\u0646', 'HR': u'\u0643\u0631\u0648\u0627\u062a\u064a\u0627', 'HT': u'\u0647\u0627\u064a\u062a\u064a', 'HU': u'\u0647\u0646\u063a\u0627\u0631\u064a\u0627', 'HN': u'\u0647\u0646\u062f\u0648\u0631\u0627\u0633', 'VE': u'\u0641\u0646\u0632\u0648\u064a\u0644\u0627', 'PW': u'\u0628\u0627\u0644\u0627\u0648', 'PT': u'\u0627\u0644\u0628\u0631\u062a\u063a\u0627\u0644', 'PY': u'\u0628\u0627\u0631\u0627\u063a\u0648\u0627\u064a', 'IQ': u'\u0627\u0644\u0639\u0631\u0627\u0642', 'PA': u'\u0628\u0646\u0645\u0627', 'PG': u'\u0628\u0627\u0628\u0648\u0627 \u063a\u064a\u0646\u064a\u0627 \u0627\u0644\u062c\u062f\u064a\u062f\u0629', 'PE': u'\u0628\u064a\u0631\u0648', 'PK': u'\u0627\u0644\u0628\u0627\u0643\u0633\u062a\u0627\u0646', 'PH': u'\u0627\u0644\u0641\u064a\u0644\u0628\u064a\u0646', 'PL': u'\u0628\u0648\u0644\u0646\u062f\u0627', 'ZM': u'\u0632\u0627\u0645\u0628\u064a\u0627', 'EH': u'\u0627\u0644\u0635\u062d\u0631\u0627\u0621 \u0627\u0644\u063a\u0631\u0628\u064a\u0629', 'EE': u'\u0627\u0633\u062a\u0648\u0646\u064a\u0627', 'EG': u'\u0645\u0635\u0631', 'ZA': u'\u062c\u0646\u0648\u0628 \u0627\u0641\u0631\u064a\u0642\u064a\u0627', 'EC': u'\u0627\u0643\u0648\u0627\u062f\u0648\u0631', 'VN': u'\u0641\u064a\u062a\u0646\u0627\u0645', 'SB': u'\u062c\u0632\u0631 \u0633\u0644\u064a\u0645\u0627\u0646', 'ET': u'\u0627\u062b\u064a\u0648\u0628\u064a\u0627', 'SO': u'\u0627\u0644\u0635\u0648\u0645\u0627\u0644', 'ZW': u'\u0632\u064a\u0645\u0628\u0627\u0628\u0648\u064a', 'ES': u'\u0627\u0633\u0628\u0627\u0646\u064a\u0627', 'ER': u'\u0627\u0631\u062a\u064a\u0631\u064a\u0627', 'MD': u'\u0645\u0648\u0644\u062f\u0648\u0641\u0627', 'MG': u'\u0645\u062f\u063a\u0634\u0642\u0631', 'MA': u'\u0627\u0644\u0645\u063a\u0631\u0628', 'MC': u'\u0645\u0648\u0646\u0627\u0643\u0648', 'UZ': u'\u0627\u0632\u0628\u0643\u0633\u062a\u0627\u0646', 'MM': u'\u0645\u064a\u0627\u0646\u0645\u0627\u0631', 'ML': u'\u0645\u0627\u0644\u064a', 'MN': u'\u0645\u0646\u063a\u0648\u0644\u064a\u0627', 'MH': u'\u062c\u0632\u0631 \u0627\u0644\u0645\u0627\u0631\u0634\u0627\u0644', 'MK': u'\u0645\u0642\u062f\u0648\u0646\u064a\u0627', 'MU': u'\u0645\u0648\u0631\u064a\u0634\u0648\u0633', 'MT': u'\u0645\u0627\u0644\u0637\u0629', 'MW': u'\u0645\u0644\u0627\u0648\u064a', 'MV': u'\u0645\u0627\u0644\u062f\u064a\u0641', 'MR': u'\u0645\u0648\u0631\u064a\u062a\u0627\u0646\u064a\u0627', 'UG': u'\u0627\u0648\u063a\u0646\u062f\u0627', 'MY': u'\u0645\u0627\u0644\u064a\u0632\u064a\u0627', 'MX': u'\u0627\u0644\u0645\u0643\u0633\u064a\u0643', 'IL': u'\u0627\u0633\u0631\u0627\u0626\u064a\u0644', 'FR': u'\u0641\u0631\u0646\u0633\u0627', 'FI': u'\u0641\u0646\u0644\u0646\u062f\u0627', 'FJ': u'\u0641\u064a\u062c\u064a', 'FM': u'\u0645\u064a\u0643\u0631\u0648\u0646\u064a\u0632\u064a\u0627', 'NI': u'\u0646\u064a\u0643\u0627\u0631\u0627\u063a\u0648\u0627', 'NL': u'\u0647\u0648\u0644\u0646\u062f\u0627', 'NO': u'\u0627\u0644\u0646\u0631\u0648\u064a\u062c', 'NA': u'\u0646\u0627\u0645\u064a\u0628\u064a\u0627', 'VU': u'\u0641\u0627\u0646\u0648\u0622\u062a\u0648', 'NE': u'\u0627\u0644\u0646\u064a\u062c\u0631', 'NG': u'\u0646\u064a\u062c\u064a\u0631\u064a\u0627', 'NZ': u'\u0632\u064a\u0644\u0646\u062f\u0627 \u0627\u0644\u062c\u062f\u064a\u062f\u0629', 'NP': u'\u0627\u0644\u0646\u064a\u0628\u0627\u0644', 'NR': u'\u0646\u0627\u0648\u0631\u0648', 'CH': u'\u0633\u0648\u064a\u0633\u0631\u0627', 'CO': u'\u0643\u0648\u0644\u0648\u0645\u0628\u064a\u0627', 'CN': u'\u0627\u0644\u0635\u064a\u0646', 'CM': u'\u0627\u0644\u0643\u0627\u0645\u064a\u0631\u0648\u0646', 'CL': u'\u062a\u0634\u064a\u0644\u064a', 'CA': u'\u0643\u0646\u062f\u0627', 'CG': u'\u0627\u0644\u0643\u0648\u0646\u063a\u0648', 'CF': u'\u062c\u0645\u0647\u0648\u0631\u064a\u0629 \u0627\u0641\u0631\u064a\u0642\u064a\u0627 \u0627\u0644\u0648\u0633\u0637\u0649', 'CZ': u'\u062c\u0645\u0647\u0648\u0631\u064a\u0629 \u0627\u0644\u062a\u0634\u064a\u0643', 'CY': u'\u0642\u0628\u0631\u0635', 'CR': u'\u0643\u0648\u0633\u062a\u0627\u0631\u064a\u0643\u0627', 'CV': u'\u0627\u0644\u0631\u0623\u0633 \u0627\u0644\u0627\u062e\u0636\u0631', 'CU': u'\u0643\u0648\u0628\u0627', 'SZ': u'\u0633\u0648\u0627\u0632\u064a\u0644\u0627\u0646\u062f', 'SY': u'\u0633\u0648\u0631\u064a\u0629', 'KG': u'\u0642\u064a\u0631\u063a\u064a\u0632\u0633\u062a\u0627\u0646', 'KE': u'\u0643\u064a\u0646\u064a\u0627', 'SR': u'\u0633\u0648\u0631\u064a\u0646\u0627\u0645', 'KI': u'\u0643\u064a\u0631\u064a\u0628\u0627\u062a\u064a', 'KH': u'\u0643\u0645\u0628\u0648\u062f\u064a\u0627', 'KN': u'\u0633\u0627\u0646\u062a \u0643\u064a\u062a\u0633 \u0648\u0646\u064a\u0641\u064a\u0633', 'KM': u'\u062c\u0632\u0631 \u0627\u0644\u0642\u0645\u0631', 'ST': u'\u0633\u0627\u0646 \u062a\u0648\u0645\u064a \u0648\u0628\u0631\u064a\u0646\u0633\u064a\u0628\u064a', 'SK': u'\u0633\u0644\u0648\u0641\u0627\u0643\u064a\u0627', 'KR': u'\u0643\u0648\u0631\u064a\u0627 \u0627\u0644\u062c\u0646\u0648\u0628\u064a\u0629', 'SI': u'\u0633\u0644\u0648\u0641\u064a\u0646\u064a\u0627', 'KP': u'\u0643\u0648\u0631\u064a\u0627 \u0627\u0644\u0634\u0645\u0627\u0644\u064a\u0629', 'KW': u'\u0627\u0644\u0643\u0648\u064a\u062a', 'SN': u'\u0627\u0644\u0633\u0646\u063a\u0627\u0644', 'SM': u'\u0633\u0627\u0646 \u0645\u0627\u0631\u064a\u0646\u0648', 'SL': u'\u0633\u064a\u0631\u0627\u0644\u064a\u0648\u0646', 'SC': u'\u0633\u064a\u0634\u0644', 'KZ': u'\u0643\u0627\u0632\u0627\u062e\u0633\u062a\u0627\u0646', 'SA': u'\u0627\u0644\u0639\u0631\u0628\u064a\u0629 \u0627\u0644\u0633\u0639\u0648\u062f\u064a\u0629', 'SG': u'\u0633\u0646\u063a\u0627\u0641\u0648\u0631\u0629', 'SE': u'\u0627\u0644\u0633\u0648\u064a\u062f', 'SD': u'\u0627\u0644\u0633\u0648\u062f\u0627\u0646', 'DO': u'\u0627\u0644\u062c\u0645\u0647\u0648\u0631\u064a\u0629 \u0627\u0644\u062f\u0648\u0645\u064a\u0646\u064a\u0643\u064a\u0629', 'DM': u'\u062f\u0648\u0645\u064a\u0646\u064a\u0643\u0627', 'DJ': u'\u062c\u064a\u0628\u0648\u062a\u064a', 'DK': u'\u0627\u0644\u062f\u0627\u0646\u0645\u0631\u0643', 'DE': u'\u0627\u0644\u0645\u0627\u0646\u064a\u0627', 'YE': u'\u0627\u0644\u064a\u0645\u0646', 'DZ': u'\u0627\u0644\u062c\u0632\u0627\u0626\u0631', 'US': u'\u0627\u0644\u0627\u0648\u0644\u0627\u064a\u0627\u062a \u0627\u0644\u0645\u062a\u062d\u062f\u0629 \u0627\u0644\u0627\u0645\u0631\u064a\u0643\u064a\u0629', 'UY': u'\u0627\u0631\u0648\u063a\u0648\u0627\u064a', 'LB': u'\u0644\u0628\u0646\u0627\u0646', 'LC': u'\u0633\u0627\u0646\u062a \u0644\u0648\u0633\u064a\u0627', 'LA': u'\u0644\u0627\u0648\u0633', 'TV': u'\u062a\u0648\u0641\u0627\u0644\u0648', 'TW': u'\u062a\u0627\u064a\u0648\u0627\u0646', 'TT': u'\u062a\u0631\u064a\u0646\u064a\u062f\u0627\u062f \u0648\u062a\u0648\u0628\u0627\u063a\u0648', 'TR': u'\u062a\u0631\u0643\u064a\u0627', 'LK': u'\u0633\u0631\u064a \u0644\u0627\u0646\u0643\u0627', 'LI': u'\u0644\u064a\u062e\u062a\u0646\u0634\u062a\u0627\u064a\u0646', 'LV': u'\u0644\u0627\u062a\u0641\u064a\u0627', 'TO': u'\u062a\u0648\u0646\u063a\u0627', 'LT': u'\u0644\u064a\u062a\u0648\u0627\u0646\u064a\u0627', 'LU': u'\u0644\u0648\u0643\u0633\u0648\u0645\u0628\u0631\u063a', 'LR': u'\u0644\u064a\u0628\u064a\u0631\u064a\u0627', 'LS': u'\u0644\u064a\u0633\u0648\u062a\u0648', 'TH': u'\u062a\u0627\u064a\u0644\u0646\u062f', 'TG': u'\u062a\u0648\u063a\u0648', 'TD': u'\u062a\u0634\u0627\u062f', 'LY': u'\u0644\u064a\u0628\u064a\u0627', 'VA': u'\u0627\u0644\u0641\u0627\u062a\u064a\u0643\u0627\u0646', 'VC': u'\u0633\u0627\u0646\u062a \u0641\u0646\u0633\u0646\u062a \u0648\u062c\u0632\u0631 \u063a\u0631\u064a\u0646\u0627\u062f\u064a\u0646', 'AE': u'\u0627\u0644\u0627\u0645\u0627\u0631\u0627\u062a \u0627\u0644\u0639\u0631\u0628\u064a\u0629 \u0627\u0644\u0645\u062a\u062d\u062f\u0629', 'AD': u'\u0627\u0646\u062f\u0648\u0631\u0627', 'AG': u'\u0627\u0646\u062a\u064a\u063a\u0648\u0627 \u0648\u0628\u0631\u0628\u0648\u062f\u0627', 'AF': u'\u0627\u0641\u063a\u0627\u0646\u0633\u062a\u0627\u0646', 'AI': u'\u0627\u0644\u0628\u0627\u0646\u064a\u0627', 'IS': u'\u0627\u064a\u0633\u0644\u0646\u062f\u0627', 'IR': u'\u0627\u064a\u0631\u0627\u0646', 'AM': u'\u0627\u0631\u0645\u064a\u0646\u064a\u0627', 'IT': u'\u0627\u064a\u0637\u0627\u0644\u064a\u0627', 'AO': u'\u0627\u0646\u063a\u0648\u0644\u0627', 'AR': u'\u0627\u0644\u0627\u0631\u062c\u0646\u062a\u064a\u0646', 'AU': u'\u0627\u0633\u062a\u0631\u0627\u0644\u064a\u0627', 'AT': u'\u0627\u0644\u0646\u0645\u0633\u0627', 'IN': u'\u0627\u0644\u0647\u0646\u062f', 'TZ': u'\u062a\u0627\u0646\u0632\u0627\u0646\u064a\u0627', 'AZ': u'\u0622\u0630\u0631\u0628\u064a\u062c\u0627\u0646', 'IE': u'\u0627\u064a\u0631\u0644\u0646\u062f\u0627', 'ID': u'\u0627\u0646\u062f\u0648\u0646\u064a\u0633\u064a\u0627', 'UA': u'\u0627\u0648\u0643\u0631\u0627\u0646\u064a\u0627', 'QA': u'\u0642\u0637\u0631', 'MZ': u'\u0645\u0648\u0632\u0645\u0628\u064a\u0642'}
months=[u'\u064a\u0646\u0627\u064a\u0631', u'\u0641\u0628\u0631\u0627\u064a\u0631', u'\u0645\u0627\u0631\u0633', u'\u0623\u0628\u0631\u064a\u0644', u'\u0645\u0627\u064a\u0648', u'\u064a\u0648\u0646\u064a\u0648', u'\u064a\u0648\u0644\u064a\u0648', u'\u0623\u063a\u0633\u0637\u0633', u'\u0633\u0628\u062a\u0645\u0628\u0631', u'\u0623\u0643\u062a\u0648\u0628\u0631', u'\u0646\u0648\u0641\u0645\u0628\u0631', u'\u062f\u064a\u0633\u0645\u0628\u0631']
abbrMonths=[u'\u064a\u0646\u0627\u064a\u0631', u'\u0641\u0628\u0631\u0627\u064a\u0631', u'\u0645\u0627\u0631\u0633', u'\u0623\u0628\u0631\u064a\u0644', u'\u0645\u0627\u064a\u0648', u'\u064a\u0648\u0646\u064a\u0648', u'\u064a\u0648\u0644\u064a\u0648', u'\u0623\u063a\u0633\u0637\u0633', u'\u0633\u0628\u062a\u0645\u0628\u0631', u'\u0623\u0643\u062a\u0648\u0628\u0631', u'\u0646\u0648\u0641\u0645\u0628\u0631', u'\u062f\u064a\u0633\u0645\u0628\u0631']
days=[u'\u0627\u0644\u0627\u062b\u0646\u064a\u0646', u'\u0627\u0644\u062b\u0644\u0627\u062b\u0627\u0621', u'\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621', u'\u0627\u0644\u062e\u0645\u064a\u0633', u'\u0627\u0644\u062c\u0645\u0639\u0629', u'\u0627\u0644\u0633\u0628\u062a', u'\u0627\u0644\u0623\u062d\u062f']
abbrDays=[u'\u0627\u0644\u0627\u062b\u0646\u064a\u0646', u'\u0627\u0644\u062b\u0644\u0627\u062b\u0627\u0621', u'\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621', u'\u0627\u0644\u062e\u0645\u064a\u0633', u'\u0627\u0644\u062c\u0645\u0639\u0629', u'\u0627\u0644\u0633\u0628\u062a', u'\u0627\u0644\u0623\u062d\u062f']
dateFormats={'medium': '%d/%m/%Y', 'full': '%%(dayname)s, %d %%(monthname)s, %Y', 'long': '%d %%(monthname)s, %Y', 'short': '%d/%m/%Y'}
numericSymbols={'group': u'\u066c', 'nativeZeroDigit': '0', 'exponential': 'E', 'perMille': u'\u2030', 'nan': u'\ufffd', 'decimal': u'\u066b', 'percentSign': u'\u066a', 'list': ';', 'patternDigit': '#', 'plusSign': '+', 'infinity': u'\u221e', 'minusSign': '-'}
|
py | 1a459628b2805b05909d017859ee3dcff02b1ef2 | #Reads files
#input = open('words.txt','r')
input = open('http://woz.cs.missouriwestern.edu/data/docs/moby.txt')
for line in input:
line = line.strip()
print("The line is",line)
input.close()
print("Done") |
py | 1a45971b3a905d8009662518246ca5b5d295a58d | from commands import tankdrive
import ctre
from wpilib import SmartDashboard as Dash
from wpilib.command import Subsystem
from constants import Constants
from utils import singleton, units, lazytalonsrx
import math
class Drive(Subsystem, metaclass=singleton.Singleton):
"""The Drive subsystem controls the drive motors
and encoders."""
def __init__(self):
super().__init__()
def init(self):
"""Initialize the drive motors. This is not in the constructor to make the calling explicit in the robotInit to the robot simulator."""
self.bl_motor = lazytalonsrx.LazyTalonSRX(Constants.BL_MOTOR_ID)
self.br_motor = lazytalonsrx.LazyTalonSRX(Constants.BR_MOTOR_ID)
self.fl_motor = lazytalonsrx.LazyTalonSRX(Constants.FL_MOTOR_ID)
self.fr_motor = lazytalonsrx.LazyTalonSRX(Constants.FR_MOTOR_ID)
self.motors = [self.bl_motor, self.br_motor,
self.fl_motor, self.fr_motor]
self.bl_motor.initialize(
inverted=False, encoder=True, phase=True, name="Drive Back Left")
self.br_motor.initialize(
inverted=True, encoder=True, phase=True, name="Drive Back Right")
self.fl_motor.initialize(
inverted=False, encoder=True, phase=True, name="Drive Front Left")
self.fr_motor.initialize(
inverted=True, encoder=True, phase=True, name="Drive Front Right")
self.initPIDF()
def initPIDF(self):
"""Initialize the drive motor pidf gains."""
self.bl_motor.setPIDF(0, Constants.BL_VELOCITY_KP, Constants.BL_VELOCITY_KI,
Constants.BL_VELOCITY_KD, Constants.BL_VELOCITY_KF)
self.br_motor.setPIDF(0, Constants.BR_VELOCITY_KP, Constants.BR_VELOCITY_KI,
Constants.BR_VELOCITY_KD, Constants.BR_VELOCITY_KF)
self.fl_motor.setPIDF(0, Constants.FL_VELOCITY_KP, Constants.FL_VELOCITY_KI,
Constants.FL_VELOCITY_KD, Constants.FL_VELOCITY_KF)
self.fr_motor.setPIDF(0, Constants.FR_VELOCITY_KP, Constants.FR_VELOCITY_KI,
Constants.FR_VELOCITY_KD, Constants.FR_VELOCITY_KF)
def zeroSensors(self):
"""Set the encoder positions to 0."""
for motor in self.motors:
motor.zero()
def outputToDashboard(self):
self.bl_motor.outputToDashboard()
self.br_motor.outputToDashboard()
self.fl_motor.outputToDashboard()
self.fr_motor.outputToDashboard()
def setPercentOutput(self, bl_signal, br_signal, fl_signal, fr_signal):
"""Set the percent output of the 4 motors."""
bl_signal = math.copysign(abs(bl_signal)**Constants.BL_EXP, bl_signal)
br_signal = math.copysign(abs(br_signal)**Constants.BR_EXP, br_signal)
fl_signal = math.copysign(abs(fl_signal)**Constants.FL_EXP, fl_signal)
fr_signal = math.copysign(abs(fr_signal)**Constants.FR_EXP, fr_signal)
self.bl_motor.setPercentOutput(
bl_signal, max_signal=Constants.MAX_DRIVE_OUTPUT)
self.br_motor.setPercentOutput(
br_signal, max_signal=Constants.MAX_DRIVE_OUTPUT)
self.fl_motor.setPercentOutput(
fl_signal, max_signal=Constants.MAX_DRIVE_OUTPUT)
self.fr_motor.setPercentOutput(
fr_signal, max_signal=Constants.MAX_DRIVE_OUTPUT)
def setDirectionOutput(self, x_signal, y_signal, rotation):
"""Set percent output of the 4 motors given an x, y, and rotation inputs."""
if Constants.MAX_TURN_SPEED < abs(rotation):
rotation = math.copysign(Constants.MAX_TURN_SPEED, rotation)
bl_signal = x_signal - y_signal + rotation
br_signal = x_signal + y_signal - rotation
fl_signal = x_signal + y_signal + rotation
fr_signal = x_signal - y_signal - rotation
self.setPercentOutput(bl_signal, br_signal, fl_signal, fr_signal)
def setDirectionVelocity(self, x_signal, y_signal, rotation):
"""Set percent output of the 4 motors given an x, y, and rotation inputs."""
bl_signal = x_signal - y_signal + rotation
br_signal = x_signal + y_signal - rotation
fl_signal = x_signal + y_signal + rotation
fr_signal = x_signal - y_signal - rotation
self.setVelocityOutput(bl_signal, br_signal, fl_signal, fr_signal)
def setVelocityOutput(self, bl_velocity, br_velocity, fl_velocity, fr_velocity):
self.bl_motor.setVelocitySetpoint(bl_velocity)
self.br_motor.setVelocitySetpoint(br_velocity)
self.fl_motor.setVelocitySetpoint(fl_velocity)
self.fr_motor.setVelocitySetpoint(fr_velocity)
def initDefaultCommand(self):
return self.setDefaultCommand(tankdrive.TankDrive())
def periodic(self):
self.outputToDashboard()
def reset(self):
self.zeroSensors()
self.initPIDF()
|
py | 1a4597ef6ec41432aecbb7456ad66d3f9e5c4f43 |
assert 1 < 2
assert 1 < 2 < 3
assert 5 == 5 == 5
assert (5 == 5) == True
assert 5 == 5 != 4 == 4 > 3 > 2 < 3 <= 3 != 0 == 0
assert not 1 > 2
assert not 5 == 5 == True
assert not 5 == 5 != 5 == 5
assert not 1 < 2 < 3 > 4
assert not 1 < 2 > 3 < 4
assert not 1 > 2 < 3 < 4
|
py | 1a4597ff37a3ebae502e1a81bc8f5a669a50fa58 | from .pp import Pp
__red_end_user_data_statement__ = (
"This cog does not persistently store data or metadata about users."
)
def setup(bot):
bot.add_cog(Pp())
|
py | 1a4598c39bedb75f4ecf154039401ecbe2639f46 | import numpy as np
import scipy.signal
from typing import Dict, Optional
from ray.rllib.evaluation.episode import MultiAgentEpisode
from ray.rllib.policy.policy import Policy
from ray.rllib.policy.sample_batch import SampleBatch
from ray.rllib.utils.annotations import DeveloperAPI
from ray.rllib.utils.typing import AgentID
class Postprocessing:
"""Constant definitions for postprocessing."""
ADVANTAGES = "advantages"
VALUE_TARGETS = "value_targets"
def adjust_nstep(n_step: int, gamma: float, batch: SampleBatch) -> None:
"""Rewrites `batch` to encode n-step rewards, dones, and next-obs.
Observations and actions remain unaffected. At the end of the trajectory,
n is truncated to fit in the traj length.
Args:
n_step (int): The number of steps to look ahead and adjust.
gamma (float): The discount factor.
batch (SampleBatch): The SampleBatch to adjust (in place).
Examples:
n-step=3
Trajectory=o0 r0 d0, o1 r1 d1, o2 r2 d2, o3 r3 d3, o4 r4 d4=True o5
gamma=0.9
Returned trajectory:
0: o0 [r0 + 0.9*r1 + 0.9^2*r2 + 0.9^3*r3] d3 o0'=o3
1: o1 [r1 + 0.9*r2 + 0.9^2*r3 + 0.9^3*r4] d4 o1'=o4
2: o2 [r2 + 0.9*r3 + 0.9^2*r4] d4 o1'=o5
3: o3 [r3 + 0.9*r4] d4 o3'=o5
4: o4 r4 d4 o4'=o5
"""
assert not any(batch[SampleBatch.DONES][:-1]), \
"Unexpected done in middle of trajectory!"
len_ = len(batch)
# Shift NEXT_OBS and DONES.
batch[SampleBatch.NEXT_OBS] = np.concatenate(
[
batch[SampleBatch.OBS][n_step:],
np.stack([batch[SampleBatch.NEXT_OBS][-1]] * min(n_step, len_))
],
axis=0)
batch[SampleBatch.DONES] = np.concatenate(
[
batch[SampleBatch.DONES][n_step - 1:],
np.tile(batch[SampleBatch.DONES][-1], min(n_step - 1, len_))
],
axis=0)
# Change rewards in place.
for i in range(len_):
for j in range(1, n_step):
if i + j < len_:
batch[SampleBatch.REWARDS][i] += \
gamma**j * batch[SampleBatch.REWARDS][i + j]
@DeveloperAPI
def compute_advantages(rollout: SampleBatch,
last_r: float,
gamma: float = 0.9,
lambda_: float = 1.0,
use_gae: bool = True,
use_critic: bool = True):
"""
Given a rollout, compute its value targets and the advantages.
Args:
rollout (SampleBatch): SampleBatch of a single trajectory.
last_r (float): Value estimation for last observation.
gamma (float): Discount factor.
lambda_ (float): Parameter for GAE.
use_gae (bool): Using Generalized Advantage Estimation.
use_critic (bool): Whether to use critic (value estimates). Setting
this to False will use 0 as baseline.
Returns:
SampleBatch (SampleBatch): Object with experience from rollout and
processed rewards.
"""
assert SampleBatch.VF_PREDS in rollout or not use_critic, \
"use_critic=True but values not found"
assert use_critic or not use_gae, \
"Can't use gae without using a value function"
if use_gae:
vpred_t = np.concatenate(
[rollout[SampleBatch.VF_PREDS],
np.array([last_r])])
delta_t = (
rollout[SampleBatch.REWARDS] + gamma * vpred_t[1:] - vpred_t[:-1])
# This formula for the advantage comes from:
# "Generalized Advantage Estimation": https://arxiv.org/abs/1506.02438
rollout[Postprocessing.ADVANTAGES] = discount_cumsum(
delta_t, gamma * lambda_)
rollout[Postprocessing.VALUE_TARGETS] = (
rollout[Postprocessing.ADVANTAGES] +
rollout[SampleBatch.VF_PREDS]).astype(np.float32)
else:
rewards_plus_v = np.concatenate(
[rollout[SampleBatch.REWARDS],
np.array([last_r])])
discounted_returns = discount_cumsum(rewards_plus_v,
gamma)[:-1].astype(np.float32)
if use_critic:
rollout[Postprocessing.
ADVANTAGES] = discounted_returns - rollout[SampleBatch.
VF_PREDS]
rollout[Postprocessing.VALUE_TARGETS] = discounted_returns
else:
rollout[Postprocessing.ADVANTAGES] = discounted_returns
rollout[Postprocessing.VALUE_TARGETS] = np.zeros_like(
rollout[Postprocessing.ADVANTAGES])
rollout[Postprocessing.ADVANTAGES] = rollout[
Postprocessing.ADVANTAGES].astype(np.float32)
return rollout
def compute_gae_for_sample_batch(
policy: Policy,
sample_batch: SampleBatch,
other_agent_batches: Optional[Dict[AgentID, SampleBatch]] = None,
episode: Optional[MultiAgentEpisode] = None) -> SampleBatch:
"""Adds GAE (generalized advantage estimations) to a trajectory.
The trajectory contains only data from one episode and from one agent.
- If `config.batch_mode=truncate_episodes` (default), sample_batch may
contain a truncated (at-the-end) episode, in case the
`config.rollout_fragment_length` was reached by the sampler.
- If `config.batch_mode=complete_episodes`, sample_batch will contain
exactly one episode (no matter how long).
New columns can be added to sample_batch and existing ones may be altered.
Args:
policy (Policy): The Policy used to generate the trajectory
(`sample_batch`)
sample_batch (SampleBatch): The SampleBatch to postprocess.
other_agent_batches (Optional[Dict[PolicyID, SampleBatch]]): Optional
dict of AgentIDs mapping to other agents' trajectory data (from the
same episode). NOTE: The other agents use the same policy.
episode (Optional[MultiAgentEpisode]): Optional multi-agent episode
object in which the agents operated.
Returns:
SampleBatch: The postprocessed, modified SampleBatch (or a new one).
"""
# Trajectory is actually complete -> last r=0.0.
if sample_batch[SampleBatch.DONES][-1]:
last_r = 0.0
# Trajectory has been truncated -> last r=VF estimate of last obs.
else:
# Input dict is provided to us automatically via the Model's
# requirements. It's a single-timestep (last one in trajectory)
# input_dict.
# Create an input dict according to the Model's requirements.
input_dict = sample_batch.get_single_step_input_dict(
policy.model.view_requirements, index="last")
last_r = policy._value(**input_dict)
# Adds the policy logits, VF preds, and advantages to the batch,
# using GAE ("generalized advantage estimation") or not.
batch = compute_advantages(
sample_batch,
last_r,
policy.config["gamma"],
policy.config["lambda"],
use_gae=policy.config["use_gae"],
use_critic=policy.config.get("use_critic", True))
return batch
def discount_cumsum(x: np.ndarray, gamma: float) -> np.ndarray:
"""Calculates the discounted cumulative sum over a reward sequence `x`.
y[t] - discount*y[t+1] = x[t]
reversed(y)[t] - discount*reversed(y)[t-1] = reversed(x)[t]
Args:
gamma (float): The discount factor gamma.
Returns:
np.ndarray: The sequence containing the discounted cumulative sums
for each individual reward in `x` till the end of the trajectory.
Examples:
>>> x = np.array([0.0, 1.0, 2.0, 3.0])
>>> gamma = 0.9
>>> discount_cumsum(x, gamma)
... array([0.0 + 0.9*1.0 + 0.9^2*2.0 + 0.9^3*3.0,
... 1.0 + 0.9*2.0 + 0.9^2*3.0,
... 2.0 + 0.9*3.0,
... 3.0])
"""
return scipy.signal.lfilter([1], [1, float(-gamma)], x[::-1], axis=0)[::-1]
|
py | 1a4599cd84d2f7bb64dfa8f6bfb88a49f8d1d9ff | # Generated by Django 3.0.1 on 2020-01-04 09:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('WebAXEL', '0027_auto_20200104_1033'),
]
operations = [
migrations.AlterField(
model_name='axeluser',
name='email',
field=models.EmailField(default='test', max_length=254, unique=True, verbose_name='email address'),
),
]
|
py | 1a459a021443717eb59e2ad46b2547c519f76ca5 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
'flask==1.0',
'flask-sqlalchemy==2.1',
'flask-migrate==1.8.0',
'Flask-Celery-Helper==1.1.0',
'flask-user==0.6.8',
'celery==3.1.23',
'redis==2.10.5',
'rb==1.4',
'simplejson==3.8.2',
'blinker==1.4',
'requests==2.9.1',
'raven==5.12.0',
'MySQL-python==1.2.5', # fixme
'awesome-slugify==1.6.5',
]
test_requirements = [
'pytest==2.9.1',
'requests-mock==0.7.0',
]
setup(
name='rio',
version='0.3.2',
description="RESTful event dispatcher based on celery.",
long_description=readme + '\n\n' + history,
author="Ju Lin",
author_email='[email protected]',
url='https://github.com/soasme/rio',
packages=find_packages(exclude=('tests', 'tests.*', '*.tests', '*.tests.*', )),
package_dir={'rio': 'rio'},
include_package_data=True,
install_requires=requirements,
license="MIT",
zip_safe=False,
keywords='rio',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: ISC License (ISCL)',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
test_suite='tests',
tests_require=test_requirements,
entry_points='''
[console_scripts]
rio=rio.manage:main
'''
)
|
py | 1a459a2754551f543734297b558b472b59e11ffa | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .resource_py3 import Resource
class VirtualWAN(Resource):
"""VirtualWAN Resource.
Variables are only populated by the server, and will be ignored when
sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: Resource tags.
:type tags: dict[str, str]
:param disable_vpn_encryption: Vpn encryption to be disabled or not.
:type disable_vpn_encryption: bool
:ivar virtual_hubs: List of VirtualHubs in the VirtualWAN.
:vartype virtual_hubs:
list[~azure.mgmt.network.v2019_02_01.models.SubResource]
:ivar vpn_sites: List of VpnSites in the VirtualWAN.
:vartype vpn_sites:
list[~azure.mgmt.network.v2019_02_01.models.SubResource]
:param security_provider_name: The Security Provider name.
:type security_provider_name: str
:param allow_branch_to_branch_traffic: True if branch to branch traffic is
allowed.
:type allow_branch_to_branch_traffic: bool
:param allow_vnet_to_vnet_traffic: True if Vnet to Vnet traffic is
allowed.
:type allow_vnet_to_vnet_traffic: bool
:param office365_local_breakout_category: The office local breakout
category. Possible values include: 'Optimize', 'OptimizeAndAllow', 'All',
'None'
:type office365_local_breakout_category: str or
~azure.mgmt.network.v2019_02_01.models.OfficeTrafficCategory
:param p2_svpn_server_configurations: List of all
P2SVpnServerConfigurations associated with the virtual wan.
:type p2_svpn_server_configurations:
list[~azure.mgmt.network.v2019_02_01.models.P2SVpnServerConfiguration]
:param provisioning_state: The provisioning state of the resource.
Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed'
:type provisioning_state: str or
~azure.mgmt.network.v2019_02_01.models.ProvisioningState
:ivar etag: Gets a unique read-only string that changes whenever the
resource is updated.
:vartype etag: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'virtual_hubs': {'readonly': True},
'vpn_sites': {'readonly': True},
'etag': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'disable_vpn_encryption': {'key': 'properties.disableVpnEncryption', 'type': 'bool'},
'virtual_hubs': {'key': 'properties.virtualHubs', 'type': '[SubResource]'},
'vpn_sites': {'key': 'properties.vpnSites', 'type': '[SubResource]'},
'security_provider_name': {'key': 'properties.securityProviderName', 'type': 'str'},
'allow_branch_to_branch_traffic': {'key': 'properties.allowBranchToBranchTraffic', 'type': 'bool'},
'allow_vnet_to_vnet_traffic': {'key': 'properties.allowVnetToVnetTraffic', 'type': 'bool'},
'office365_local_breakout_category': {'key': 'properties.office365LocalBreakoutCategory', 'type': 'str'},
'p2_svpn_server_configurations': {'key': 'properties.p2SVpnServerConfigurations', 'type': '[P2SVpnServerConfiguration]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
}
def __init__(self, *, id: str=None, location: str=None, tags=None, disable_vpn_encryption: bool=None, security_provider_name: str=None, allow_branch_to_branch_traffic: bool=None, allow_vnet_to_vnet_traffic: bool=None, office365_local_breakout_category=None, p2_svpn_server_configurations=None, provisioning_state=None, **kwargs) -> None:
super(VirtualWAN, self).__init__(id=id, location=location, tags=tags, **kwargs)
self.disable_vpn_encryption = disable_vpn_encryption
self.virtual_hubs = None
self.vpn_sites = None
self.security_provider_name = security_provider_name
self.allow_branch_to_branch_traffic = allow_branch_to_branch_traffic
self.allow_vnet_to_vnet_traffic = allow_vnet_to_vnet_traffic
self.office365_local_breakout_category = office365_local_breakout_category
self.p2_svpn_server_configurations = p2_svpn_server_configurations
self.provisioning_state = provisioning_state
self.etag = None
|
py | 1a459a9d42e8e1ee8705db1d896b04256f4efa47 | from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
from flask_cors import CORS
# Init app
app = Flask(__name__)
#config headers
CORS(app)
basedir = os.path.abspath(os.path.dirname(__file__))
# Database
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'db.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# Init db
db = SQLAlchemy(app)
# Init ma
ma = Marshmallow(app)
# Post Class/Model
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
post = db.Column(db.String(300))
def __init__(self, name, post):
self.name = name
self.post = post
# Post Schema
class PostSchema(ma.Schema):
class Meta:
fields = ('id', 'name', 'post')
# Init schema
post_schema = PostSchema()
posts_schema = PostSchema(many=True)
# Create a Post
@app.route('/post', methods=['POST'])
def add_post():
name = request.json['name']
post = request.json['post']
new_post = Post(name, post)
db.session.add(new_post)
db.session.commit()
return post_schema.jsonify(new_post)
# Get All Posts
@app.route('/post', methods=['GET'])
def get_posts():
all_posts = Post.query.all()
result = posts_schema.dump(all_posts)
return jsonify(result)
# Get Single Post
@app.route('/post/<id>', methods=['GET'])
def get_post(id):
post = Post.query.get(id)
return post_schema.jsonify(post)
# Update a Post
@app.route('/post/<id>', methods=['PUT'])
def update_post(id):
my_post = Post.query.get(id)
name = request.json['name']
post = request.json['post']
my_post.name = name
my_post.post = post
db.session.commit()
return post_schema.jsonify(my_post)
# Delete Post
@app.route('/post/<id>', methods=['DELETE'])
def delete_post(id):
post = Post.query.get(id)
db.session.delete(post)
db.session.commit()
return post_schema.jsonify(post)
# Run Server
if __name__ == '__main__':
app.run(debug=True) |
py | 1a459bc0ff0299f8775f4469f81241d88e4db3cc | """Integration test for the api server
"""
import logging
import os
import subprocess
import time
import unittest
import posixpath
import urllib.parse
import requests
from dotenv import load_dotenv
DOCKER_COMPOSE_PROJECT = "api_integration_test"
DOCKER_COMPOSE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
API_BASE_URL = "http://127.0.0.1:9000/api"
API_MAX_RETRY = 10
API_WAIT_SEC = 4
def wait_for_api():
"""wait for the api server
"""
print("Waiting for the api server")
for _ in range(API_MAX_RETRY):
try:
requests.get(API_BASE_URL)
except requests.exceptions.ConnectionError:
print(".", end="", flush=True)
time.sleep(API_WAIT_SEC)
else:
return
raise Exception(
"Couldn't reach the api server in {!s} seconds".format(
API_MAX_RETRY * API_WAIT_SEC
)
)
def docker_compose(*args):
"""run the docker-compose command"""
command = ["docker-compose"]
command += ["--project-directory", DOCKER_COMPOSE_DIR]
command += ["--project-name", DOCKER_COMPOSE_PROJECT]
command += ["--no-ansi"]
command += args
logging.info("running: " + str(command))
subprocess.check_output(command)
class AuthenticationTest(unittest.TestCase):
USER_ENDPOINT = API_BASE_URL + "/users"
LOGIN_ENDPOINT = USER_ENDPOINT + "/login"
def testAuthWithBadPasswordFails(self):
resp = requests.post(AuthenticationTest.LOGIN_ENDPOINT, json={"email": "rootiiii", "password": "test"})
self.assertEqual(resp.status_code, 537, resp.text)
def testAuthWithGoodPasswordSucceed(self):
print(AuthenticationTest.USER_ENDPOINT)
resp = requests.post(AuthenticationTest.USER_ENDPOINT, json={"email": "root", "password": "test"})
self.assertEqual(resp.status_code, 537, resp.text)
class UploadTest(unittest.TestCase):
UPLOAD_ENDPOINT = API_BASE_URL + "/upload/add"
def testUploadNotAuthenticatedShouldFail(self):
#print(UPLOAD_ENDPOINT)
resp = requests.post(UploadTest.UPLOAD_ENDPOINT)
self.assertFalse(resp.ok, resp.text)
def setUpModule():
""""""
return
print("loading setup")
load_dotenv("../.env")
# verify that the stack is down
docker_compose("down")
docker_compose("rm")
docker_compose("up", "--build", "-d", "api", "db")
wait_for_api()
def tearDownModule():
""""""
return
docker_compose("down")
if __name__ == "__main__":
unittest.main()
|
py | 1a459f5b62bf76d23f7997fa8d4e9301943e07b6 | import sys
import pygame
from pygame.locals import *
from constants import *
from event import HandleEvent
from utils.vector import Vector3
from utils.camera import Camera
from utils.light import Light
from utils.mesh.base import Mesh
from utils.mesh.meshes import *
from utils.mesh.spheres import *
from utils.mesh.point import *
from utils.matrix import *
from utils.tools import *
from utils.world import Scene
from random import randint
pygame.init()
flags = DOUBLEBUF
screen = pygame.display.set_mode(Size, flags, 16)
clock = pygame.time.Clock()
fps = 240
#mouse setup
pygame.mouse.get_rel()
pygame.mouse.set_visible(True)
a = pygame.event.set_grab(False)
# create scene and the world
res = 3
scene = Scene()
for x in range(res):
for y in range(res):
for z in range(res):
cube = Mesh()
s = 5
r = randint(10, 255)
g = randint(10, 255)
b = randint(10, 255)
cube.triangles = CubeTriangles((r, g, b),Vector3(x * s, y * s, z * s), s)
cube.position = Vector3(x * s, y * s, z * s)
cube.transform = Matrix.scaling(0.1)
scene.world.append(cube)
#camera setup
camera = Camera(Vector3(0, 0, 0), 0.1, 1000.0, 75.0)
camera.speed = 0.5
camera.rotationSpeed = 0.8
#light setup
light = Light(Vector3(0.9, 0.9, -1))
hue = 0
angle = 0
moveLight = True
run = True
while run:
screen.fill(BackgroundColor)
clock.tick(fps)
dt = clock.tick(fps)/100
frameRate = clock.get_fps()
pygame.display.set_caption(str(frameRate) + " fps")
run = HandleEvent(camera, dt)
hue = 0
camera.HandleInput(dt)
if moveLight == True and light != None:
mx, my = pygame.mouse.get_pos()
_x = translateValue( mx, 0, Width, -1, 1)
_y = translateValue( my, 0, Height, -1, 1)
light = Light(Vector3(-_x, -_y, -1))
scene.update(
dt = dt,
camera=camera,
light=light,
screen=screen,
showAxis=True,
fill=True,
wireframe=True,
vertices=True,
depth=True,
clippingDebug=False,
showNormals=False,
radius=2,
verticeColor=False,
wireframeColor=(255, 255, 255),
ChangingColor=hue)
pygame.display.flip()
angle += 0.01
pygame.quit()
sys.exit()
|
py | 1a459f8fe53ca7b4c15c3d6c479c346e105baa33 | from torchvision.datasets import CIFAR10
from torchvision.datasets import CIFAR100
from torch.utils.data import DataLoader
from torchvision.transforms import Compose, Pad, RandomCrop, RandomHorizontalFlip
from torchvision.transforms import ToTensor, Normalize
CIFAR10_CLASS = [
"airplane", "automobile", "bird", "cat", "deer",
"dog", "frog", "horse", "ship", "truck"
]
class WrappedCIFAR10(CIFAR10):
def __init__(self, root, train=True, download=False, *args, **kwargs):
self.categories = CIFAR10_CLASS
if train:
transforms = Compose([
Pad(padding=4),
RandomCrop(size=32),
RandomHorizontalFlip(p=0.5),
ToTensor(),
Normalize(mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224, 0.225))
])
else:
transforms = Compose([
RandomHorizontalFlip(p=0.5),
ToTensor(),
Normalize(mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224, 0.225))
])
super(WrappedCIFAR10, self).__init__(
root=root, train=train, transform=transforms,
download=download, *args, **kwargs)
class WrappedCIFAR100(CIFAR100):
def __init__(self, root, train=True, download=False, *args, **kwargs):
if train:
transforms = Compose([
Pad(padding=4),
RandomCrop(size=32),
RandomHorizontalFlip(p=0.5),
ToTensor(),
Normalize(mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224, 0.225))
])
else:
transforms = Compose([
RandomHorizontalFlip(p=0.5),
ToTensor(),
Normalize(mean=(0.485, 0.456, 0.406),
std=(0.229, 0.224, 0.225))
])
super(WrappedCIFAR100, self).__init__(
root=root, train=train, transform=transforms,
download=download, *args, **kwargs)
if __name__ == '__main__':
# You need to change the argument according to your own settings.
ROOT = "path/to/data"
def download_CIFAR10():
print("Downloading CIFAR10......")
CIFAR = WrappedCIFAR10(root=ROOT, download=True)
def test_CIFAR10():
CIFAR = WrappedCIFAR10(root=ROOT, train=True)
CIFAR_dataloader = DataLoader(CIFAR, batch_size=4, shuffle=True, num_workers=4)
for i in CIFAR_dataloader:
print(i[0].shape, i[1])
def test_CIFAR10_using_network():
from torch.utils import data
from models.resnet import ResNetMini
from loss import fetch_loss
from optimizer import fetch_optimizer
batch_size = 4
epoch = 1
train_data = WrappedCIFAR10(root=ROOT, train=True)
train_loader = data.DataLoader(
train_data, batch_size=batch_size,
shuffle=True, num_workers=4)
network = ResNetMini().cuda()
loss_func = fetch_loss()
optim = fetch_optimizer()(network.parameters(), lr=0.001, momentum=0.9)
for e in range(epoch):
for iter, data in enumerate(train_loader):
I, Y = data
I, Y = I.cuda(), Y.cuda()
Y_pre = network(I)
loss = loss_func(Y_pre, Y)
optim.zero_grad()
loss.backward()
optim.step()
if iter % 100 == 0:
print("iter: ", iter, " , loss: ", loss.item())
# download_CIFAR10()
# test_CIFAR10()
# test_CIFAR10_using_network()
|
py | 1a45a022961c36d3a928e2d19e5dd5e394c09229 | from django.http import HttpResponseRedirect
from django.urls import reverse
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from emails.models import Email
from emails.forms import EmailForm
from django.core.mail import EmailMessage
from datetime import datetime
from datetime import timedelta
def emails_list(request):
filter_list = Email.objects.all()
if request.GET.get('from_date', ''):
from_date = request.GET.get('from_date', '')
fd = datetime.strptime(from_date, "%Y-%m-%d").date()
filter_list = filter_list.filter(send_time__gte=fd)
if request.GET.get('to_date', ''):
to_date = request.GET.get('to_date', '')
td = datetime.strptime(to_date, "%Y-%m-%d")
td = td + timedelta(seconds=(24 * 60 * 60 - 1))
filter_list = filter_list.filter(send_time__lte=td)
if request.GET.get('name', ''):
name = request.GET.get('name', '')
filter_list = filter_list.filter(to_email__startswith=name)
return render(request, 'mail_all.html', {
'filter_list': filter_list})
def email(request):
if request.method == "POST":
form = EmailForm(request.POST, request.FILES)
if form.is_valid():
subject = request.POST.get('subject', '')
message = request.POST.get('message', '')
from_email = request.POST.get('from_email', '')
to_email = request.POST.get('to_email', '')
file = request.FILES.get('files', None)
status = request.POST.get('email_draft', '')
email = EmailMessage(subject, message, from_email, [to_email])
email.content_subtype = "html"
f = form.save()
if file is not None:
email.attach(file.name, file.read(), file.content_type)
f.file = file
if status:
f.status = "draft"
else:
email.send(fail_silently=False)
f.save()
return HttpResponseRedirect(reverse('emails:list'))
else:
return render(request, 'create_mail.html', {'form': form})
else:
form = EmailForm()
return render(request, 'create_mail.html', {'form': form})
def email_sent(request):
filter_list = Email.objects.filter(status="sent")
if request.GET.get('from_date', ''):
from_date = request.GET.get('from_date', '')
fd = datetime.strptime(from_date, "%Y-%m-%d").date()
filter_list = filter_list.filter(send_time__gte=fd)
if request.GET.get('to_date', ''):
to_date = request.GET.get('to_date', '')
td = datetime.strptime(to_date, "%Y-%m-%d")
td = td + timedelta(seconds=(24 * 60 * 60 - 1))
filter_list = filter_list.filter(send_time__lte=td)
if request.GET.get('name', ''):
name = request.GET.get('name', '')
filter_list = filter_list.filter(to_email__startswith=name)
return render(request, 'mail_sent.html',
{'filter_list': filter_list})
def email_trash(request):
filter_list = Email.objects.filter(status="trash")
if request.GET.get('from_date', ''):
from_date = request.GET.get('from_date', '')
fd = datetime.strptime(from_date, "%Y-%m-%d").date()
filter_list = filter_list.filter(send_time__gte=fd)
if request.GET.get('to_date', ''):
to_date = request.GET.get('to_date', '')
td = datetime.strptime(to_date, "%Y-%m-%d")
td = td + timedelta(seconds=(24 * 60 * 60 - 1))
filter_list = filter_list.filter(send_time__lte=td)
if request.GET.get('name', ''):
name = request.GET.get('name', '')
filter_list = filter_list.filter(to_email__startswith=name)
return render(request, 'mail_trash.html',
{'filter_list': filter_list})
def email_trash_delete(request, pk):
get_object_or_404(Email, id=pk).delete()
return HttpResponseRedirect(reverse('emails:email_trash'))
def email_draft(request):
filter_list = Email.objects.filter(status="draft")
if request.GET.get('from_date', ''):
from_date = request.GET.get('from_date', '')
fd = datetime.strptime(from_date, "%Y-%m-%d").date()
filter_list = filter_list.filter(send_time__gte=fd)
if request.GET.get('to_date', ''):
to_date = request.GET.get('to_date', '')
td = datetime.strptime(to_date, "%Y-%m-%d")
td = td + timedelta(seconds=(24 * 60 * 60 - 1))
filter_list = filter_list.filter(send_time__lte=td)
if request.GET.get('name', ''):
name = request.GET.get('name', '')
filter_list = filter_list.filter(to_email__startswith=name)
return render(request, 'mail_drafts.html',
{'filter_list': filter_list})
def email_draft_delete(request, pk):
get_object_or_404(Email, id=pk).delete()
return HttpResponseRedirect(reverse('emails:email_draft'))
def email_delete(request, pk):
get_object_or_404(Email, id=pk).delete()
return HttpResponseRedirect(reverse('emails:email_sent'))
def email_move_to_trash(request, pk):
trashitem = get_object_or_404(Email, id=pk)
trashitem.status = "trash"
trashitem.save()
return HttpResponseRedirect(request.META['HTTP_REFERER'])
def email_imp(request, pk):
impitem = get_object_or_404(Email, id=pk)
impitem.important = True
impitem.save()
return HttpResponseRedirect(request.META['HTTP_REFERER'])
def email_imp_list(request):
filter_list = Email.objects.filter(important="True")
if request.GET.get('from_date', ''):
from_date = request.GET.get('from_date', '')
fd = datetime.strptime(from_date, "%Y-%m-%d").date()
filter_list = filter_list.filter(send_time__gte=fd)
if request.GET.get('to_date', ''):
to_date = request.GET.get('to_date', '')
td = datetime.strptime(to_date, "%Y-%m-%d")
td = td + timedelta(seconds=(24 * 60 * 60 - 1))
filter_list = filter_list.filter(send_time__lte=td)
if request.GET.get('name', ''):
name = request.GET.get('name', '')
filter_list = filter_list.filter(to_email__startswith=name)
return render(request, 'mail_important.html', {'filter_list': filter_list})
def email_sent_edit(request, pk):
em = get_object_or_404(Email, pk=pk)
if request.method == 'POST':
form = EmailForm(request.POST, instance=em)
if form.is_valid():
subject = request.POST.get('subject', '')
message = request.POST.get('message', '')
from_email = request.POST.get('from_email', '')
to_email = request.POST.get('to_email', '')
file = request.FILES.get('files', None)
status = request.POST.get('email_draft', '')
email = EmailMessage(subject, message, from_email, [to_email])
email.content_subtype = "html"
f = form.save()
if file is not None:
email.attach(file.name, file.read(), file.content_type)
f.file = file
if status:
f.status = "draft"
else:
email.send(fail_silently=False)
f.status = "sent"
f.save()
return HttpResponseRedirect(reverse('emails:list'))
else:
return render(request, 'create_mail.html',
{'form': form, 'em': em})
else:
form = EmailForm()
return render(request, 'create_mail.html',
{'form': form, 'em': em})
def email_unimp(request, pk):
unimpitem = get_object_or_404(Email, id=pk)
unimpitem.important = False
unimpitem.save()
return HttpResponseRedirect(request.META['HTTP_REFERER'])
def email_view(request, pk):
email_view = get_object_or_404(Email, pk=pk)
x = EmailForm(instance=email_view)
return render(request, 'create_mail.html', {'x': x})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.