<commit_before>import numpy

import cupy
from cupy.random import distributions
from cupy.random import generator

def rand(*size, **kwarg):
    """Returns an array of uniform random values over the interval ``[0, 1)``.

    Each element of the array is uniformly distributed on the half-open
    interval ``[0, 1)``. All elements are identically and independently
    distributed (i.i.d.).

    Args:
        size (tuple of ints): The shape of the array.
        dtype: Data type specifier. Only :class:`numpy.float32` and
            :class:`numpy.float64` types are allowed. The default is
            :class:`numpy.float64`.

    Returns:
        cupy.ndarray: A random array.

    .. seealso:: :func:`numpy.random.rand`

    """
    dtype = kwarg.pop('dtype', float)
    if kwarg:
        raise TypeError('rand() got unexpected keyword arguments %s'
                        % ', '.join(kwarg.keys()))
    return random_sample(size=size, dtype=dtype)

def randn(*size, **kwarg):
    """Returns an array of standard normal random values.

    Each element of the array is normally distributed with zero mean and unit
    variance. All elements are identically and independently distributed
    (i.i.d.).

    Args:
        size (tuple of ints): The shape of the array.
        dtype: Data type specifier. Only :class:`numpy.float32` and
            :class:`numpy.float64` types are allowed.
            The default is :class:`numpy.float64`.

    Returns:
        cupy.ndarray: An array of standard normal random values.

    .. seealso:: :func:`numpy.random.randn`

    """
    dtype = kwarg.pop('dtype', float)
    if kwarg:
        raise TypeError('randn() got unexpected keyword arguments %s'
                        % ', '.join(kwarg.keys()))
    return distributions.normal(size=size, dtype=dtype)

def randint(low, high=None, size=None):
    """Returns a scalar or an array of integer values over ``[low, high)``.

    Each element of returned values are independently sampled from
    uniform distribution over left-close and right-open interval
    ``[low, high)``.

    Args:
        low (int): If ``high`` is not ``None``,
            it is the lower bound of the interval.
            Otherwise, it is the **upper** bound of the interval
            and lower bound of the interval is set to ``0``.
        high (int): Upper bound of the interval.
        size (None or int or tuple of ints): The shape of returned value.

    Returns:
        int or cupy.ndarray of ints: If size is ``None``,
        it is single integer sampled.
        If size is integer, it is the 1D-array of length ``size`` element.
        Otherwise, it is the array whose shape specified by ``size``.
    """
    if high is None:
        lo = 0
        hi = low
    else:
        lo = low
        hi = high

    if lo >= hi:
        raise ValueError('low >= high')

    diff = hi - lo - 1
    rs = generator.get_random_state()
    return lo + rs.interval(diff, size)

def random_integers(low, high=None, size=None):
    """Return a scalar or an array of integer values over ``[low, high]``

    Each element of returned values are independently sampled from
    uniform distribution over closed interval ``[low, high]``.

    Args:
        low (int): If ``high`` is not ``None``,
            it is the lower bound of the interval.
            Otherwise, it is the **upper** bound of the interval
            and the lower bound is set to ``1``.
        high (int): Upper bound of the interval.
        size (None or int or tuple of ints): The shape of returned value.

    Returns:
        int or cupy.ndarray of ints: If size is ``None``,
        it is single integer sampled.
        If size is integer, it is the 1D-array of length ``size`` element.
        Otherwise, it is the array whose shape specified by ``size``.
    """
    if high is None:
        high = low
        low = 1
    return randint(low, high + 1, size)

def random_sample(size=None, dtype=float):
    """Returns an array of random values over the interval ``[0, 1)``.

    This is a variant of :func:`cupy.random.rand`.

    Args:
        size (int or tuple of ints): The shape of the array.
        dtype: Data type specifier. Only :class:`numpy.float32` and
            :class:`numpy.float64` types are allowed.

    Returns:
        cupy.ndarray: An array of uniformly distributed random values.

    .. seealso:: :func:`numpy.random.random_sample`

    """
    rs = generator.get_random_state()
    return rs.random_sample(size=size, dtype=dtype)

def choice(a, size=None, replace=True, p=None):
    """Returns an array of random values from a given 1-D array.

    Each element of the returned array is independently sampled
    from a according to p or uniformly.

    Args:
        a (1-D array-like or int):
            If a ``cupy.ndarray`` ,
            a random sample is generated from its elements.
            If an int, the random sample is generated as if a was
            ``cupy.arange(n)``
        size (int or tuple of ints): The shape of the array.
        replace (boolean): Whether the sample is with or without replacement
        p (1-D array-like):
            The probabilities associated with each entry in a.
            If not given the sample assumes a uniform distribution over all
            entries in a.

    Returns:
        cupy.ndarray: An array of a values distributed according to p or
                      uniformly.

    .. seealso:: :func:`numpy.random.choice`

    """
    a = cupy.array(a, copy=False)  # fix
    if a.ndim == 0:
        try:
            a_size = a.item()
        except TypeError:
            raise ValueError('a must be 1-dimensional or an integer')
        if a_size <= 0:
            raise ValueError('a must be greater than 0')
    elif a.ndim != 1:
        raise ValueError('a must be 1-dimensional')
    else:
        if len(a) == 0:
            raise ValueError('a must be non-empty')

    if p is not None:
        p = cupy.array(p)
        if p.ndim != 1:
            raise ValueError('p must be 1-dimensional')
        if len(p) != a_size:
            raise ValueError('a and p must have same size')
        if not (p >= 0).all():
            raise ValueError('probabilities are not non-negative')
        p_sum = cupy.sum(p).get()
        if not numpy.allclose(p_sum, 1):
            raise ValueError('probabilities do not sum to 1')
    rs = generator.get_random_state()  # fix
    return rs.random_choice(a=a, size=size, replace=replace, p=p)  # fix
<commit_msg>implement gumbel trick<commit_after>import numpy

import cupy
from cupy.random import distributions
from cupy.random import generator

def rand(*size, **kwarg):
    """Returns an array of uniform random values over the interval ``[0, 1)``.

    Each element of the array is uniformly distributed on the half-open
    interval ``[0, 1)``. All elements are identically and independently
    distributed (i.i.d.).

    Args:
        size (tuple of ints): The shape of the array.
        dtype: Data type specifier. Only :class:`numpy.float32` and
            :class:`numpy.float64` types are allowed. The default is
            :class:`numpy.float64`.

    Returns:
        cupy.ndarray: A random array.

    .. seealso:: :func:`numpy.random.rand`

    """
    dtype = kwarg.pop('dtype', float)
    if kwarg:
        raise TypeError('rand() got unexpected keyword arguments %s'
                        % ', '.join(kwarg.keys()))
    return random_sample(size=size, dtype=dtype)

def randn(*size, **kwarg):
    """Returns an array of standard normal random values.

    Each element of the array is normally distributed with zero mean and unit
    variance. All elements are identically and independently distributed
    (i.i.d.).

    Args:
        size (tuple of ints): The shape of the array.
        dtype: Data type specifier. Only :class:`numpy.float32` and
            :class:`numpy.float64` types are allowed.
            The default is :class:`numpy.float64`.

    Returns:
        cupy.ndarray: An array of standard normal random values.

    .. seealso:: :func:`numpy.random.randn`

    """
    dtype = kwarg.pop('dtype', float)
    if kwarg:
        raise TypeError('randn() got unexpected keyword arguments %s'
                        % ', '.join(kwarg.keys()))
    return distributions.normal(size=size, dtype=dtype)

def randint(low, high=None, size=None):
    """Returns a scalar or an array of integer values over ``[low, high)``.

    Each element of returned values are independently sampled from
    uniform distribution over left-close and right-open interval
    ``[low, high)``.

    Args:
        low (int): If ``high`` is not ``None``,
            it is the lower bound of the interval.
            Otherwise, it is the **upper** bound of the interval
            and lower bound of the interval is set to ``0``.
        high (int): Upper bound of the interval.
        size (None or int or tuple of ints): The shape of returned value.

    Returns:
        int or cupy.ndarray of ints: If size is ``None``,
        it is single integer sampled.
        If size is integer, it is the 1D-array of length ``size`` element.
        Otherwise, it is the array whose shape specified by ``size``.
    """
    if high is None:
        lo = 0
        hi = low
    else:
        lo = low
        hi = high

    if lo >= hi:
        raise ValueError('low >= high')

    diff = hi - lo - 1
    rs = generator.get_random_state()
    return lo + rs.interval(diff, size)

def random_integers(low, high=None, size=None):
    """Return a scalar or an array of integer values over ``[low, high]``

    Each element of returned values are independently sampled from
    uniform distribution over closed interval ``[low, high]``.

    Args:
        low (int): If ``high`` is not ``None``,
            it is the lower bound of the interval.
            Otherwise, it is the **upper** bound of the interval
            and the lower bound is set to ``1``.
        high (int): Upper bound of the interval.
        size (None or int or tuple of ints): The shape of returned value.

    Returns:
        int or cupy.ndarray of ints: If size is ``None``,
        it is single integer sampled.
        If size is integer, it is the 1D-array of length ``size`` element.
        Otherwise, it is the array whose shape specified by ``size``.
    """
    if high is None:
        high = low
        low = 1
    return randint(low, high + 1, size)

def random_sample(size=None, dtype=float):
    """Returns an array of random values over the interval ``[0, 1)``.

    This is a variant of :func:`cupy.random.rand`.

    Args:
        size (int or tuple of ints): The shape of the array.
        dtype: Data type specifier. Only :class:`numpy.float32` and
            :class:`numpy.float64` types are allowed.

    Returns:
        cupy.ndarray: An array of uniformly distributed random values.

    .. seealso:: :func:`numpy.random.random_sample`

    """
    rs = generator.get_random_state()
    return rs.random_sample(size=size, dtype=dtype)

def choice(a, size=None, replace=True, p=None):
    """Returns an array of random values from a given 1-D array.

    Each element of the returned array is independently sampled
    from a according to p or uniformly.

    Args:
        a (1-D array-like or int):
            If a ``cupy.ndarray`` ,
            a random sample is generated from its elements.
            If an int, the random sample is generated as if a was
            ``cupy.arange(n)``
        size (int or tuple of ints): The shape of the array.
        replace (boolean): Whether the sample is with or without replacement
        p (1-D array-like):
            The probabilities associated with each entry in a.
            If not given the sample assumes a uniform distribution over all
            entries in a.

    Returns:
        cupy.ndarray: An array of a values distributed according to p or
                      uniformly.

    .. seealso:: :func:`numpy.random.choice`

    """
    a = cupy.array(a, copy=False)  # fix
    if a.ndim == 0:
        try:
            a_size = a.item()
        except TypeError:
            raise ValueError('a must be 1-dimensional or an integer')
        if a_size <= 0:
            raise ValueError('a must be greater than 0')
    elif a.ndim != 1:
        raise ValueError('a must be 1-dimensional')
    else:
        a_size = len(a)
        if a_size == 0:
            raise ValueError('a must be non-empty')

    if p is not None:
        p = cupy.array(p)
        if p.ndim != 1:
            raise ValueError('p must be 1-dimensional')
        if len(p) != a_size:
            raise ValueError('a and p must have same size')
        if not (p >= 0).all():
            raise ValueError('probabilities are not non-negative')
        p_sum = cupy.sum(p).get()
        if not numpy.allclose(p_sum, 1):
            raise ValueError('probabilities do not sum to 1')

    shape = size
    if shape is not None:
        size = cupy.prod(shape)
    else:
        size = 1

    # Actual sampling
    if replace:
        if p is not None:
            p = cupy.broadcast_to(p, (size, a_size))
            index = cupy.argmax(cupy.log(p) -
                                cupy.random.gumbel(size=(size, a_size)),
                                axis=1)
            index.shape = shape
        else:
            index = cupy.random.randint(0, a_size, size=shape)
    else:
        if size > a_size:
            raise ValueError('Cannot take a larger sample than population \
                              when \'replace=False\'')
        if p is not None:
            pass  # Not yet
        else:
            pass  # Not yet

    rs = generator.get_random_state()  # fix
    return rs.random_choice(a=a, size=size, replace=replace, p=p)  # fix
<|endoftext|>


<commit_before>from spack import *

class Kripke(Package):
    """Kripke is a simple, scalable, 3D Sn deterministic particle transport code."""

    homepage = "https://codesign.llnl.gov/kripke.php"
    url      = ""
    #version('master', git='https://lc.llnl.gov/stash/scm/kripke/kripke.git')
    version('master', git='https://lc.llnl.gov/stash/scm/~islam3/kripke.git')

    def install(self, spec, prefix):
      with working_dir('build', create=True):
        cmake('-DCMAKE_INSTALL_PREFIX:PATH=.', '-DCMAKE_TOOLCHAIN_FILE=../cmake/Toolchain/chaos_5_x86_64_ib-ic15.cmake', '-DENABLE_OPENMP=1', '..', *std_cmake_args)
        make()
        make("install")

<commit_msg>Adding a new package: Kripke from the public tar ball<commit_after># FIXME:
# This is a template package file for Spack.  We've conveniently
# put "FIXME" labels next to all the things you'll want to change.
#
# Once you've edited all the FIXME's, delete this whole message,
# save this file, and test out your package like this:
#
#     spack install kripke
#
# You can always get back here to change things with:
#
#     spack edit kripke
#
# See the spack documentation for more information on building
# packages.
#
from spack import *

class Kripke(Package):
    """Kripke is a simple, scalable, 3D Sn deterministic particle transport proxy/mini app."""
    homepage = "https://codesign.llnl.gov/kripke.php"
    url      = "https://codesign.llnl.gov/downloads/kripke-openmp-1.1.tar.gz"

    version('1.1', '7fe6f2b26ed983a6ce5495ab701f85bf')

    #depends_on("mvapich2@1.9:")

    def install(self, spec, prefix):
        with working_dir('build', create=True):
         cmake('-DCMAKE_INSTALL_PREFIX:PATH=.', '-DENABLE_OPENMP=1', '-DENABLE_MPI=1', '..', *std_cmake_args)
         make()
	 #Kripke does not provide an install, so creating one here.
	 mkdirp(prefix.bin)
         install('kripke', prefix.bin)
<|endoftext|>


<commit_before># Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.

from UM.Job import Job
from UM.Application import Application
from UM.Math.Polygon import Polygon

import numpy
import copy
from . import ConvexHullNode

class ConvexHullJob(Job):
    def __init__(self, node):
        super().__init__()

        self._node = node

    def run(self):
        if not self._node:
            return
        ## If the scene node is a group, use the hull of the children to calculate its hull.
        if self._node.callDecoration("isGroup"):
            hull = Polygon(numpy.zeros((0, 2), dtype=numpy.int32))
            for child in self._node.getChildren():
                child_hull = child.callDecoration("getConvexHull")
                if child_hull:
                    hull.setPoints(numpy.append(hull.getPoints(), child_hull.getPoints(), axis = 0))

                if hull.getPoints().size < 3:
                    self._node.callDecoration("setConvexHull", None)
                    self._node.callDecoration("setConvexHullJob", None)
                    return

                Job.yieldThread()

        else:
            if not self._node.getMeshData():
                return
            mesh = self._node.getMeshData()
            vertex_data = mesh.getTransformed(self._node.getWorldTransformation()).getVertices()
            # Don't use data below 0. TODO; We need a better check for this as this gives poor results for meshes with long edges.
            vertex_data = vertex_data[vertex_data[:,1] >= 0]

            # Round the vertex data to 1/10th of a mm, then remove all duplicate vertices
            # This is done to greatly speed up further convex hull calculations as the convex hull
            # becomes much less complex when dealing with highly detailed models.
            vertex_data = numpy.round(vertex_data, 1)

            vertex_data = vertex_data[:, [0, 2]]    # Drop the Y components to project to 2D.

            # Grab the set of unique points.
            #
            # This basically finds the unique rows in the array by treating them as opaque groups of bytes
            # which are as long as the 2 float64s in each row, and giving this view to numpy.unique() to munch.
            # See http://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array
            tmp = numpy.ascontiguousarray(vertex_data).view(numpy.dtype((numpy.void, vertex_data.dtype.itemsize * vertex_data.shape[1])))
            _, idx = numpy.unique(tmp, return_index=True)
            vertex_data = vertex_data[idx]  # Select the unique rows by index.

            hull = Polygon(vertex_data)

        # First, calculate the normal convex hull around the points
        hull = hull.getConvexHull()

        # Then, do a Minkowski hull with a simple 1x1 quad to outset and round the normal convex hull.
        # This is done because of rounding errors.
        hull = hull.getMinkowskiHull(Polygon(numpy.array([[-0.5, -0.5], [-0.5, 0.5], [0.5, 0.5], [0.5, -0.5]], numpy.float32)))

        profile = Application.getInstance().getMachineManager().getWorkingProfile()
        if profile:
            if profile.getSettingValue("print_sequence") == "one_at_a_time" and not self._node.getParent().callDecoration("isGroup"):
                # Printing one at a time and it's not an object in a group
                self._node.callDecoration("setConvexHullBoundary", copy.deepcopy(hull))
                head_and_fans = Polygon(numpy.array(profile.getSettingValue("machine_head_with_fans_polygon"), numpy.float32))
                # Full head hull is used to actually check the order.
                full_head_hull = hull.getMinkowskiHull(head_and_fans)
                self._node.callDecoration("setConvexHullHeadFull", full_head_hull)
                mirrored = copy.deepcopy(head_and_fans)
                mirrored.mirror([0, 0], [0, 1]) #Mirror horizontally.
                mirrored.mirror([0, 0], [1, 0]) #Mirror vertically.
                head_and_fans = head_and_fans.intersectionConvexHulls(mirrored)
                # Min head hull is used for the push free
                min_head_hull = hull.getMinkowskiHull(head_and_fans)
                self._node.callDecoration("setConvexHullHead", min_head_hull)
                hull = hull.getMinkowskiHull(Polygon(numpy.array(profile.getSettingValue("machine_head_polygon"),numpy.float32)))
            else:
                self._node.callDecoration("setConvexHullHead", None)
        if self._node.getParent() is None: #Node was already deleted before job is done.
            self._node.callDecoration("setConvexHullNode",None)
            self._node.callDecoration("setConvexHull", None)
            self._node.callDecoration("setConvexHullJob", None)
            return
        hull_node = ConvexHullNode.ConvexHullNode(self._node, hull, Application.getInstance().getController().getScene().getRoot())
        self._node.callDecoration("setConvexHullNode", hull_node)
        self._node.callDecoration("setConvexHull", hull)
        self._node.callDecoration("setConvexHullJob", None)

        if self._node.getParent() and self._node.getParent().callDecoration("isGroup"):
            job = self._node.getParent().callDecoration("getConvexHullJob")
            if job:
                job.cancel()
            self._node.getParent().callDecoration("setConvexHull", None)
            hull_node = self._node.getParent().callDecoration("getConvexHullNode")
            if hull_node:
                hull_node.setParent(None)
<commit_msg>Rename 'tmp' to something a bit more meaningful. Contributes to CURA-1512<commit_after># Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.

from UM.Job import Job
from UM.Application import Application
from UM.Math.Polygon import Polygon

import numpy
import copy
from . import ConvexHullNode

class ConvexHullJob(Job):
    def __init__(self, node):
        super().__init__()

        self._node = node

    def run(self):
        if not self._node:
            return
        ## If the scene node is a group, use the hull of the children to calculate its hull.
        if self._node.callDecoration("isGroup"):
            hull = Polygon(numpy.zeros((0, 2), dtype=numpy.int32))
            for child in self._node.getChildren():
                child_hull = child.callDecoration("getConvexHull")
                if child_hull:
                    hull.setPoints(numpy.append(hull.getPoints(), child_hull.getPoints(), axis = 0))

                if hull.getPoints().size < 3:
                    self._node.callDecoration("setConvexHull", None)
                    self._node.callDecoration("setConvexHullJob", None)
                    return

                Job.yieldThread()

        else:
            if not self._node.getMeshData():
                return
            mesh = self._node.getMeshData()
            vertex_data = mesh.getTransformed(self._node.getWorldTransformation()).getVertices()
            # Don't use data below 0. TODO; We need a better check for this as this gives poor results for meshes with long edges.
            vertex_data = vertex_data[vertex_data[:,1] >= 0]

            # Round the vertex data to 1/10th of a mm, then remove all duplicate vertices
            # This is done to greatly speed up further convex hull calculations as the convex hull
            # becomes much less complex when dealing with highly detailed models.
            vertex_data = numpy.round(vertex_data, 1)

            vertex_data = vertex_data[:, [0, 2]]    # Drop the Y components to project to 2D.

            # Grab the set of unique points.
            #
            # This basically finds the unique rows in the array by treating them as opaque groups of bytes
            # which are as long as the 2 float64s in each row, and giving this view to numpy.unique() to munch.
            # See http://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array
            vertex_byte_view = numpy.ascontiguousarray(vertex_data).view(numpy.dtype((numpy.void, vertex_data.dtype.itemsize * vertex_data.shape[1])))
            _, idx = numpy.unique(vertex_byte_view, return_index=True)
            vertex_data = vertex_data[idx]  # Select the unique rows by index.

            hull = Polygon(vertex_data)

        # First, calculate the normal convex hull around the points
        hull = hull.getConvexHull()

        # Then, do a Minkowski hull with a simple 1x1 quad to outset and round the normal convex hull.
        # This is done because of rounding errors.
        hull = hull.getMinkowskiHull(Polygon(numpy.array([[-0.5, -0.5], [-0.5, 0.5], [0.5, 0.5], [0.5, -0.5]], numpy.float32)))

        profile = Application.getInstance().getMachineManager().getWorkingProfile()
        if profile:
            if profile.getSettingValue("print_sequence") == "one_at_a_time" and not self._node.getParent().callDecoration("isGroup"):
                # Printing one at a time and it's not an object in a group
                self._node.callDecoration("setConvexHullBoundary", copy.deepcopy(hull))
                head_and_fans = Polygon(numpy.array(profile.getSettingValue("machine_head_with_fans_polygon"), numpy.float32))
                # Full head hull is used to actually check the order.
                full_head_hull = hull.getMinkowskiHull(head_and_fans)
                self._node.callDecoration("setConvexHullHeadFull", full_head_hull)
                mirrored = copy.deepcopy(head_and_fans)
                mirrored.mirror([0, 0], [0, 1]) #Mirror horizontally.
                mirrored.mirror([0, 0], [1, 0]) #Mirror vertically.
                head_and_fans = head_and_fans.intersectionConvexHulls(mirrored)
                # Min head hull is used for the push free
                min_head_hull = hull.getMinkowskiHull(head_and_fans)
                self._node.callDecoration("setConvexHullHead", min_head_hull)
                hull = hull.getMinkowskiHull(Polygon(numpy.array(profile.getSettingValue("machine_head_polygon"),numpy.float32)))
            else:
                self._node.callDecoration("setConvexHullHead", None)
        if self._node.getParent() is None: #Node was already deleted before job is done.
            self._node.callDecoration("setConvexHullNode",None)
            self._node.callDecoration("setConvexHull", None)
            self._node.callDecoration("setConvexHullJob", None)
            return
        hull_node = ConvexHullNode.ConvexHullNode(self._node, hull, Application.getInstance().getController().getScene().getRoot())
        self._node.callDecoration("setConvexHullNode", hull_node)
        self._node.callDecoration("setConvexHull", hull)
        self._node.callDecoration("setConvexHullJob", None)

        if self._node.getParent() and self._node.getParent().callDecoration("isGroup"):
            job = self._node.getParent().callDecoration("getConvexHullJob")
            if job:
                job.cancel()
            self._node.getParent().callDecoration("setConvexHull", None)
            hull_node = self._node.getParent().callDecoration("getConvexHullNode")
            if hull_node:
                hull_node.setParent(None)
<|endoftext|>


<commit_before>#!/usr/bin/env python

#from topbook import TopBook
import facebook
from string import lower
from datetime import datetime
import urllib2

class NoPostsError(Exception):
	def __init__(self, value=""):
		self.value = value
	def __str__(self):
		return repr(self.value)

class TopBook(object):
	def __init__(self, cfg):
		self.token = cfg['fbtoken']
		self.pages = cfg['pages']
		self.lower_pages = map(lambda w: w.lower(), self.pages)
		self.graph = facebook.GraphAPI(self.token)

	def page_list(self):
		return "Configured pages are: " + ", ".join(self.pages.keys())

	def lookup(self, metric, query, days):
		attachments = []
		page = query
		if lower(query) in self.lower_pages:
			for config_page in self.pages:
				if lower(query) == lower(config_page):
					page = self.pages[config_page]

		# print 'Looking up `%s`.' % query
		top = {}
		if isinstance(page, basestring):
			try:
				top['id'], top['message'], top['likes'], top['comments'], top['picture'], top['shares'] = self.top_for_page(metric, page, days)
			except facebook.GraphAPIError:
				return "Error requesting post list for %s, page may not exist." % page
			except NoPostsError:
				return "No posts on %s in last day." % page
			top['page'] = ''
		elif isinstance(page, (list, tuple)):
			for subpage in page:
				print "Reqesting %s" % subpage
				try:
					post = {}
					post['id'], post['message'], post['likes'], post['comments'], post['picture'], post['shares'] = self.top_for_page(metric, subpage, days)
				except NoPostsError:
					# No posts in time range.
					print "No posts in time range."
					pass
				except Exception, e:
					return "Error requesting post list for %s: %s" % (subpage, e)
				if metric not in top or top[metric] < post[metric]:
					top['page'] = "%s" % subpage
					top['id'] = post['id']
					top['comments'] = post['comments']
					top['likes'] = post['likes']
					top['message'] = post['message']
					top['picture'] = post['picture']
					top['shares'] = post['shares']
		else:
			return "Page not found. Try the pages command for a list."

		message = {
			"fallback": "Fallback",
			"text": "%s http://www.facebook.com/%s" % (top['message'], top['id']),
			"fields": [
                {
                    "title": "Social",
                    "value": "%s Likes, %s Comments, %s Shares" % (top['likes'], top['comments'], top['shares']),
                    "short": True
                }
            ],
			"thumb_url": "%s" % top['picture']
		}
		if top['page']:
			message["fields"].append({"title":"Page","value":top['page'], "short": True})
		attachments.append(message)
		return {"attachments":attachments}
		# return "%s%s with %s likes and %s comments (http://www.facebook.com/%s) (%s)" % (top['page'], top['message'], top['likes'], top['comments'], top['id'], top['picture'])

	def top_for_page(self, metric, page, days):
		profile = self.graph.get_object(page)
		posts = self.graph.get_connections(profile['id'], 'posts?fields=id,message,created_time,picture,comments.limit(1).summary(true),likes.limit(1).summary(true),shares')
		top = {}
		data = []
		completed = False
		while True:
			for post in posts['data']:
				# "2016-04-13T18:04:04+0000"
				created_time = datetime.strptime(post['created_time'],"%Y-%m-%dT%H:%M:%S+0000")
				age = datetime.utcnow() - created_time
				if age.days >= days:
					completed = True
					break
				data.append(post)
			if completed:
				break
			req = urllib2.Request(posts['paging']['next'])
			response = urllib2.urlopen(req)
			posts = json.loads(response.read())
			# posts = requests.get(posts['paging']['next']).json()

		for post in data:
			if metric == "shares":
				if post.get(metric):
					total = post[metric].get('count')
				else:
					total = 0
			else:
				if post.get(metric):
					total = post[metric]['summary']['total_count']
				else:
					total = 0
			if metric not in top or top[metric] < total:
				top['id'] = post['id']
				top['comments'] = post['comments']['summary']['total_count']
				top['likes'] = post['likes']['summary']['total_count']
				top['message'] = post['message']
				top['picture'] = post['picture']
				top['shares'] = post.get('shares',{}).get("count",0)
			# print "%s: %s %s %s" % (page, post['comments']['summary']['total_count'], post['likes']['summary']['total_count'], post['message'])
		if not top:
			raise NoPostsError()
		return (top['id'], top['message'], top['likes'], top['comments'], top['picture'], top['shares'])

# --- Move all this junk to topbook.py when done ---

from bottle import route, run, request
import json
from string import lower
import re

accounts = {}
with open("config.json", 'r') as jsonfile:
    cfg = json.loads(jsonfile.read())
for app in cfg.keys():
	accounts[cfg[app]['slacktoken']] = TopBook(cfg[app])

@route("/")
def hello():
	return "Hello World.\n"

@route("/slack", method='POST')
def slack_parse():
	help = """
pages - Get a list of pages
likes <account> (last X days) - Show the most liked article for an account
comments <account> (last X days) - Show the most commented article for an account
	"""

	response = {}

	token = request.forms.get('token')
	if accounts[token]:
		topbook = accounts[token]
	else:
		return (json.dumps({"text":"Slack token not found in config."}))

	days = 1

	user_name = request.forms.get('user_name')
	trigger_word = request.forms.get('trigger_word')
	text = request.forms.get('text')
	if text.startswith(trigger_word):
		text = text[len(trigger_word):].lstrip()

	m = re.search('^(.*) in last (\d+) days?', text)
	m2 = re.search('^(.*) last (\d+) days?', text)
	if m and m.group(2):
		text = m.group(1)
		days = int(m.group(2))
	elif m2 and m2.group(2):
		text = m2.group(1)
		days = int(m2.group(2))

	if lower(text).startswith('help'):
		response['text'] = help
	elif lower(text).startswith('pages'):
		response['text'] = topbook.page_list()
	elif lower(text).startswith('likes'):
		response = topbook.lookup('likes', text[5:].lstrip(), days)
	elif lower(text).startswith('comments'):
		response = topbook.lookup('comments', text[8:].lstrip(), days)
	elif lower(text).startswith('shares'):
		response = topbook.lookup('shares', text[6:].lstrip(), days)
	else:
		response['text'] = "Ack! I don't know how to answer that. Try `%s help`?" % trigger_word

	return response

run(host='127.0.0.1', port=8000, debug=True, reloader=True)

<commit_msg>Add relative calculations.<commit_after>#!/usr/bin/env python

#from topbook import TopBook
import facebook
from string import lower
from datetime import datetime
import urllib2
import locale

class NoPostsError(Exception):
	def __init__(self, value=""):
		self.value = value
	def __str__(self):
		return repr(self.value)

class TopBook(object):
	def __init__(self, cfg):
		self.token = cfg['fbtoken']
		self.pages = cfg['pages']
		self.lower_pages = map(lambda w: w.lower(), self.pages)
		self.graph = facebook.GraphAPI(self.token)

	def page_list(self):
		return "Configured pages are: " + ", ".join(self.pages.keys())

	def lookup(self, metric, query, days, relative):
		attachments = []
		page = query
		sortmetric = metric
		if relative:
			sortmetric = "perfper"
		if lower(query) in self.lower_pages:
			for config_page in self.pages:
				if lower(query) == lower(config_page):
					page = self.pages[config_page]

		# print 'Looking up `%s`.' % query
		top = {}
		if isinstance(page, basestring):
			try:
				top['id'], top['message'], top['likes'], top['comments'], top['picture'], top['shares'], top['average'], top['perfper'] = self.top_for_page(metric, page, days)
			except facebook.GraphAPIError:
				return "Error requesting post list for %s, page may not exist." % page
			except NoPostsError:
				return "No posts on %s in last day." % page
			top['page'] = ''
		elif isinstance(page, (list, tuple)):
			for subpage in page:
				print "Reqesting %s" % subpage
				try:
					post = {}
					post['id'], post['message'], post['likes'], post['comments'], post['picture'], post['shares'], post['average'], post['perfper'] = self.top_for_page(metric, subpage, days)
				except NoPostsError:
					# No posts in time range.
					print "No posts in time range."
					pass
				except Exception, e:
					return "Error requesting post list for %s: %s" % (subpage, e)
				if metric not in top or top[sortmetric] < post[sortmetric]:
					top['page'] = "%s" % subpage
					top['id'] = post['id']
					top['comments'] = post['comments']
					top['likes'] = post['likes']
					top['message'] = post['message']
					top['picture'] = post['picture']
					top['shares'] = post['shares']
					top['average'] = post['average']
					top['perfper'] = post['perfper']
		else:
			return "Page not found. Try the pages command for a list."

                    # "value": "%s :thumbsup:, %s :speech_balloon:, %s :arrow_heading_up:" % (
		message = {
			"fallback": "Fallback",
			"text": "%s http://www.facebook.com/%s" % (top['message'], top['id']),
			"fields": [
                {
                    "title": "Social",
                    "value": "%s Likes, %s Comments, %s Shares" % (
                    		locale.format("%d", top['likes'], grouping=True),
                    		locale.format("%d", top['comments'], grouping=True),
                    		locale.format("%d", top['shares'], grouping=True)),
                    "short": True
                },
                {
                    "title": "Performance",
                    "value": "%%%s of average (%s)" % (
                    		locale.format("%d", top['perfper'], grouping=True),
                    		locale.format("%d", top['average'], grouping=True)),
                    "short": True
                }

            ],
			"thumb_url": "%s" % top['picture']
		}
		if top['page']:
			message["fields"].append({"title":"Page","value":"<http://www.facebook.com/%s|%s>" % (top['page'], top['page']), "short": True})
		attachments.append(message)
		return {"attachments":attachments}
		# return "%s%s with %s likes and %s comments (http://www.facebook.com/%s) (%s)" % (top['page'], top['message'], top['likes'], top['comments'], top['id'], top['picture'])

	def top_for_page(self, metric, page, days):
		profile = self.graph.get_object(page)
		posts = self.graph.get_connections(profile['id'], 'posts?fields=id,message,created_time,picture,comments.limit(1).summary(true),likes.limit(1).summary(true),shares')
		top = {}
		data = []
		completed = False
		while True:
			for post in posts['data']:
				# "2016-04-13T18:04:04+0000"
				created_time = datetime.strptime(post['created_time'],"%Y-%m-%dT%H:%M:%S+0000")
				age = datetime.utcnow() - created_time
				if age.days >= days:
					completed = True
					break
				data.append(post)
			if completed:
				break
			req = urllib2.Request(posts['paging']['next'])
			response = urllib2.urlopen(req)
			posts = json.loads(response.read())
			# posts = requests.get(posts['paging']['next']).json()
		totals = []
		for post in data:
			if metric == "shares":
				if post.get(metric):
					total = post[metric].get('count')
				else:
					total = 0
			else:
				if post.get(metric):
					total = post[metric]['summary']['total_count']
				else:
					total = 0
			totals.append(total)
			if metric not in top or top[metric] < total:
				top['id'] = post['id']
				top['comments'] = post['comments']['summary']['total_count']
				top['likes'] = post['likes']['summary']['total_count']
				top['message'] = post['message']
				top['picture'] = post['picture']
				top['shares'] = post.get('shares',{}).get("count",0)
			# print "%s: %s %s %s" % (page, post['comments']['summary']['total_count'], post['likes']['summary']['total_count'], post['message'])
		if not top:
			raise NoPostsError()
		average = 0
		perfper = 100.0
		if totals:
			average = sum(totals)/len(totals)
			if average > 0:
				perfper = (float(top[metric])/float(average))*100.0
		return (top['id'], top['message'], top['likes'], top['comments'], top['picture'], top['shares'], average, perfper)

# --- Move all this junk to topbook.py when done ---

from bottle import route, run, request
import json
from string import lower
import re

accounts = {}
with open("config.json", 'r') as jsonfile:
    cfg = json.loads(jsonfile.read())
for app in cfg.keys():
	accounts[cfg[app]['slacktoken']] = TopBook(cfg[app])

@route("/")
def hello():
	return "Hello World.\n"

@route("/slack", method='POST')
def slack_parse():
	help = """
pages - Get a list of pages
likes/comments/shares <account> (last X days) - Find the highest performing post in a page or page group
relative likes/comments/shares <account> (last X days) - Find the highest performing post in a page group, relative to the page's average
	"""

	response = {}
	locale.setlocale(locale.LC_ALL, 'en_US')

	token = request.forms.get('token')
	if accounts[token]:
		topbook = accounts[token]
	else:
		return (json.dumps({"text":"Slack token not found in config."}))

	days = 1

	user_name = request.forms.get('user_name')
	trigger_word = request.forms.get('trigger_word')
	text = request.forms.get('text')
	if text.startswith(trigger_word):
		text = text[len(trigger_word):].lstrip()

	m = re.search('^(.*) in last (\d+) days?', text)
	m2 = re.search('^(.*) last (\d+) days?', text)
	if m and m.group(2):
		text = m.group(1)
		days = int(m.group(2))
	elif m2 and m2.group(2):
		text = m2.group(1)
		days = int(m2.group(2))
	relative = False
	if lower(text).startswith('relative'):
		text = text[len("relative"):].lstrip()
		relative = True

	if lower(text).startswith('help'):
		response['text'] = help
	elif lower(text).startswith('pages'):
		response['text'] = topbook.page_list()
	elif lower(text).startswith('likes'):
		response = topbook.lookup('likes', text[5:].lstrip(), days, relative)
	elif lower(text).startswith('comments'):
		response = topbook.lookup('comments', text[8:].lstrip(), days, relative)
	elif lower(text).startswith('shares'):
		response = topbook.lookup('shares', text[6:].lstrip(), days, relative)
	else:
		response['text'] = "Ack! I don't know how to answer that. Try `%s help`?" % trigger_word

	return response

run(host='127.0.0.1', port=8000, debug=True, reloader=True)

<|endoftext|>


<commit_before>from __future__ import absolute_import, unicode_literals
from django.http import HttpResponse, JsonResponse
from django.template.loader import render_to_string
from django.utils.decorators import method_decorator
from django.views import View

from corehq import toggles
from corehq.apps.api.odata.utils import get_case_type_to_properties
from corehq.apps.domain.decorators import api_auth, basic_auth_or_try_api_key_auth
from corehq.apps.reports.analytics.esaccessors import get_case_types_for_domain_es
from corehq.util.view_utils import absolute_reverse

class ODataServiceView(View):

    @method_decorator(basic_auth_or_try_api_key_auth)
    @method_decorator(toggles.ODATA.required_decorator())
    def get(self, request, domain):
        data = {
            '@odata.context': absolute_reverse('odata_meta', args=[domain]),
            'value': [
                {
                    'name': case_type,
                    'kind': 'EntitySet',
                    'url': case_type,
                }
                for case_type in get_case_types_for_domain_es(domain)
            ]
        }
        return add_odata_headers(JsonResponse(data))

class ODataMetadataView(View):

    @method_decorator(basic_auth_or_try_api_key_auth)
    @method_decorator(toggles.ODATA.required_decorator())
    def get(self, request, domain):
        # template .items is evaluated as a dict lookup instead of a function, which messes with defaultdict
        case_type_to_properties = get_case_type_to_properties(domain)
        for case_type in case_type_to_properties:
            case_type_to_properties[case_type] = sorted(
                {'casename', 'casetype', 'dateopened', 'ownerid', 'backendid'}
                | set(case_type_to_properties[case_type])
            )
        metadata = render_to_string('api/odata_metadata.xml', {
            'case_type_to_properties': case_type_to_properties,
        })
        return add_odata_headers(HttpResponse(metadata, content_type='application/xml'))

def add_odata_headers(response):
    response['OData-Version'] = '4.0'
    return response
<commit_msg>stickler<commit_after>from __future__ import absolute_import, unicode_literals
from django.http import HttpResponse, JsonResponse
from django.template.loader import render_to_string
from django.utils.decorators import method_decorator
from django.views import View

from corehq import toggles
from corehq.apps.api.odata.utils import get_case_type_to_properties
from corehq.apps.domain.decorators import basic_auth_or_try_api_key_auth
from corehq.apps.reports.analytics.esaccessors import get_case_types_for_domain_es
from corehq.util.view_utils import absolute_reverse

class ODataServiceView(View):

    @method_decorator(basic_auth_or_try_api_key_auth)
    @method_decorator(toggles.ODATA.required_decorator())
    def get(self, request, domain):
        data = {
            '@odata.context': absolute_reverse('odata_meta', args=[domain]),
            'value': [
                {
                    'name': case_type,
                    'kind': 'EntitySet',
                    'url': case_type,
                }
                for case_type in get_case_types_for_domain_es(domain)
            ]
        }
        return add_odata_headers(JsonResponse(data))

class ODataMetadataView(View):

    @method_decorator(basic_auth_or_try_api_key_auth)
    @method_decorator(toggles.ODATA.required_decorator())
    def get(self, request, domain):
        # template .items is evaluated as a dict lookup instead of a function, which messes with defaultdict
        case_type_to_properties = get_case_type_to_properties(domain)
        for case_type in case_type_to_properties:
            case_type_to_properties[case_type] = sorted(
                {'casename', 'casetype', 'dateopened', 'ownerid', 'backendid'}
                | set(case_type_to_properties[case_type])
            )
        metadata = render_to_string('api/odata_metadata.xml', {
            'case_type_to_properties': case_type_to_properties,
        })
        return add_odata_headers(HttpResponse(metadata, content_type='application/xml'))

def add_odata_headers(response):
    response['OData-Version'] = '4.0'
    return response
<|endoftext|>


<commit_before>##############################################################################
# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the LICENSE file for our notice and the LGPL.
#
# This program 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) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *

class Libpng(AutotoolsPackage):
    """libpng is the official PNG reference library."""

    homepage = "http://www.libpng.org/pub/png/libpng.html"
    url      = "http://download.sourceforge.net/libpng/libpng-1.6.27.tar.gz"

    version('1.6.27', '58698519e9f6126c1caeefc28dbcbd5f')
    # From http://www.libpng.org/pub/png/libpng.html (2017-01-04)
    #     Virtually all libpng versions through 1.6.26, 1.5.27,
    #     1.4.19, 1.2.56, and 1.0.66, respectively, have a
    #     null-pointer-dereference bug in png_set_text_2() when an
    #     image-editing application adds, removes, and re-adds text
    #     chunks to a PNG image. (This bug does not affect pure
    #     viewers, nor are there any known editors that could trigger
    #     it without interactive user input. It has been assigned ID
    #     CVE-2016-10087.)  The vulnerability is fixed in versions
    #     1.6.27, 1.5.28, 1.4.20, 1.2.57, and 1.0.67, released on 29
    #     December 2016.

    # Required for qt@3
    version('1.2.57', 'dfcda3603e29dcc11870c48f838ef75b')

    depends_on('zlib@1.0.4:')  # 1.2.5 or later recommended
<commit_msg>Add latest version of libpng (#3987)<commit_after>##############################################################################
# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the LICENSE file for our notice and the LGPL.
#
# This program 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) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *

class Libpng(AutotoolsPackage):
    """libpng is the official PNG reference library."""

    homepage = "http://www.libpng.org/pub/png/libpng.html"
    url      = "http://download.sourceforge.net/libpng/libpng-1.6.29.tar.gz"

    version('1.6.29', '68553080685f812d1dd7a6b8215c37d8')
    version('1.6.27', '58698519e9f6126c1caeefc28dbcbd5f')
    # From http://www.libpng.org/pub/png/libpng.html (2017-01-04)
    #     Virtually all libpng versions through 1.6.26, 1.5.27,
    #     1.4.19, 1.2.56, and 1.0.66, respectively, have a
    #     null-pointer-dereference bug in png_set_text_2() when an
    #     image-editing application adds, removes, and re-adds text
    #     chunks to a PNG image. (This bug does not affect pure
    #     viewers, nor are there any known editors that could trigger
    #     it without interactive user input. It has been assigned ID
    #     CVE-2016-10087.)  The vulnerability is fixed in versions
    #     1.6.27, 1.5.28, 1.4.20, 1.2.57, and 1.0.67, released on 29
    #     December 2016.

    # Required for qt@3
    version('1.2.57', 'dfcda3603e29dcc11870c48f838ef75b')

    depends_on('zlib@1.0.4:')  # 1.2.5 or later recommended
<|endoftext|>


<commit_before>#!/usr/bin/python

import getopt
import sys
from mpd_muspy import _version
from mpd_muspy.sync import run as run_sync

def usage():
    print("MPD MuSpy beta", _version)
    print("Synchronize artists on your MuSpy account from the ones in your "
          "MPD database.\n")
    print("sync.py [options]")
    print("Options:")
    print("\t-c, --clean: Drop everything in the database to start syncing "
          "from a clean one")
    print("\t-h, --help: Print this help message")

def handle_arguments(opts):
    """
    Handle arguments
    """
    kwargs = dict()
    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit(0)
        elif o in ("-c", "--clean"):
            kwargs["clean"] = True
        else:
            print("Option " + o + " doesn't exists\n")
            usage()
    return kwargs

if __name__ == "__main__":
    # Arguments
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hc",
                                   ["help", "clean"])
        kwargs = handle_arguments(opts)
    except getopt.GetoptError as e:
        print(e)
        usage()
        exit(1)
    run_sync(**kwargs)
<commit_msg>Removing beta in help<commit_after>#!/usr/bin/python

import getopt
import sys
from mpd_muspy import _version
from mpd_muspy.sync import run as run_sync

def usage():
    print("MPD MuSpy", _version)
    print("Synchronize artists on your MuSpy account from the ones in your "
          "MPD database.\n")
    print("sync.py [options]")
    print("Options:")
    print("\t-c, --clean: Drop everything in the database to start syncing "
          "from a clean one")
    print("\t-h, --help: Print this help message")

def handle_arguments(opts):
    """
    Handle arguments
    """
    kwargs = dict()
    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit(0)
        elif o in ("-c", "--clean"):
            kwargs["clean"] = True
        else:
            print("Option " + o + " doesn't exists\n")
            usage()
    return kwargs

if __name__ == "__main__":
    # Arguments
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hc",
                                   ["help", "clean"])
        kwargs = handle_arguments(opts)
    except getopt.GetoptError as e:
        print(e)
        usage()
        exit(1)
    run_sync(**kwargs)
<|endoftext|>


<commit_before># Copyright 2013-2021 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)

from spack import *

class Rclone(Package):
    """Rclone is a command line program to sync files and directories
       to and from various cloud storage providers"""

    homepage = "https://rclone.org"
    url      = "https://github.com/ncw/rclone/releases/download/v1.56.2/rclone-v1.56.2.tar.gz"

    maintainers = ['alecbcs']

    version('1.56.2', sha256='a8813d25c4640e52495fee83e525e76283c63f01d1cce8fbb58d8486b0c20c8a')
    version('1.56.1', sha256='090b4b082caa554812f341ae26ea6758b40338836122595d6283c60c39eb5a97')
    version('1.56.0', sha256='81d2eda23ebaad0a355aab6ff030712470a42505b94c01c9bb5a9ead9168cedb')
    version('1.55.1', sha256='25da7fc5c9269b3897f27b0d946919df595c6dda1b127085fda0fe32aa59d29d')
    version('1.55.0', sha256='75accdaedad3b82edc185dc8824a19a59c30dc6392de7074b6cd98d1dc2c9040')
    version('1.51.0', sha256='3eb5b7ffce17e56fadb29bf854666723a14c93fedc02046c7f34c792dbd227ee')
    version('1.50.2', sha256='6dd8998a72514d3820d241ae46dc609c0305b742aee3db6aaf6017b46c996091')
    version('1.50.1', sha256='48d6c80883427469682b4d97099d7631cf3b67aa85e652c254423bd1422ce216')
    version('1.50.0', sha256='f901fd1752aae6116d94fd08d010a70d94535257c2d23caa505e631cce1e802a')
    version('1.49.5', sha256='abd2c83d71c63a4b0a30b1980b942868e707d05e14ae76ad39abf5cc5a5fde63')
    version('1.49.4', sha256='070afc85e4e9921151d7cb67247db8f0ff2f06fcf2652c43a42fa6e1e35847af')
    version('1.43', sha256='d30527b00cecb4e5e7188dddb78e5cec62d67cf2422dab82190db58512b5a4e3')

    depends_on("go", type='build')

    def setup_build_environment(self, env):
        # Point GOPATH at the top of the staging dir for the build step.
        env.prepend_path('GOPATH', self.stage.path)

    def install(self, spec, prefix):
        go('build')
        mkdirp(prefix.bin)
        install('rclone', prefix.bin)
<commit_msg>Add v1.57.0 to Rclone (#27205)<commit_after># Copyright 2013-2021 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)

from spack import *

class Rclone(Package):
    """Rclone is a command line program to sync files and directories
       to and from various cloud storage providers"""

    homepage = "https://rclone.org"
    url      = "https://github.com/ncw/rclone/releases/download/v1.57.0/rclone-v1.57.0.tar.gz"

    maintainers = ['alecbcs']

    version('1.57.0', sha256='3a762c02c202a9142c2d5c1a3927563a556d1683abadd25d2f695e237e4ea693')
    version('1.56.2', sha256='a8813d25c4640e52495fee83e525e76283c63f01d1cce8fbb58d8486b0c20c8a')
    version('1.56.1', sha256='090b4b082caa554812f341ae26ea6758b40338836122595d6283c60c39eb5a97')
    version('1.56.0', sha256='81d2eda23ebaad0a355aab6ff030712470a42505b94c01c9bb5a9ead9168cedb')
    version('1.55.1', sha256='25da7fc5c9269b3897f27b0d946919df595c6dda1b127085fda0fe32aa59d29d')
    version('1.55.0', sha256='75accdaedad3b82edc185dc8824a19a59c30dc6392de7074b6cd98d1dc2c9040')
    version('1.51.0', sha256='3eb5b7ffce17e56fadb29bf854666723a14c93fedc02046c7f34c792dbd227ee')
    version('1.50.2', sha256='6dd8998a72514d3820d241ae46dc609c0305b742aee3db6aaf6017b46c996091')
    version('1.50.1', sha256='48d6c80883427469682b4d97099d7631cf3b67aa85e652c254423bd1422ce216')
    version('1.50.0', sha256='f901fd1752aae6116d94fd08d010a70d94535257c2d23caa505e631cce1e802a')
    version('1.49.5', sha256='abd2c83d71c63a4b0a30b1980b942868e707d05e14ae76ad39abf5cc5a5fde63')
    version('1.49.4', sha256='070afc85e4e9921151d7cb67247db8f0ff2f06fcf2652c43a42fa6e1e35847af')
    version('1.43', sha256='d30527b00cecb4e5e7188dddb78e5cec62d67cf2422dab82190db58512b5a4e3')

    depends_on("go", type='build')

    def setup_build_environment(self, env):
        # Point GOPATH at the top of the staging dir for the build step.
        env.prepend_path('GOPATH', self.stage.path)

    def install(self, spec, prefix):
        go('build')
        mkdirp(prefix.bin)
        install('rclone', prefix.bin)
<|endoftext|>


<commit_before>from coloredlogs import install

from config import SERVICE, USERNAME, PASSWORD
from asyncio import get_event_loop

async def run():
    async with SERVICE as beam:
        await beam.run(USERNAME, PASSWORD)

install(level="DEBUG")

get_event_loop().run_until_complete(run())
<commit_msg>Add try/finally to run.py<commit_after>from coloredlogs import install

from config import SERVICE, USERNAME, PASSWORD
from asyncio import get_event_loop

async def run():
    async with SERVICE as beam:
        await beam.run(USERNAME, PASSWORD)

install(level="DEBUG")

loop = get_event_loop()
try:
    loop.run_until_complete(run())
finally:
    loop.close()
<|endoftext|>


<commit_before>import pcl
import numpy as np
import curvox.cloud_transformations

def write_pcd_with_normals(points, normals, output_pcd_filepath):

    with open(output_pcd_filepath, 'w') as new_pcd_file:
        new_pcd_file.write(
            "# .PCD v0.7 - Point Cloud Data file format\n"
            "VERSION 0.7\n"
            "FIELDS x y z normal_x normal_y normal_z\n"
            "SIZE 4 4 4 4 4 4\n"
            "TYPE F F F F F F\n"
            "COUNT 1 1 1 1 1 1\n"
            "WIDTH {0}\n"
            "HEIGHT 1\n"
            "POINTS {0}\n"
            "DATA ascii\n"
                .format(points.shape[0])
        )

        for point, normal in zip(points, normals):
            new_pcd_file.write("{} {} {} {} {} {}\n".format(point[0], point[1], point[2], normal[0], normal[1], normal[2]))

def compute_tactile_normals(cloud):
    points = cloud.to_array()
    num_points = points.shape[0]
    # n x 1 magnitude of each point
    magnitudes = np.linalg.norm(points, axis=1).reshape((num_points, 1))
    # divide points by per point magnitude, and flip sign to point back at origin
    normals = points / magnitudes

    return normals

def compute_depth_normals(pcd, ksearch, search_radius):
    points = pcd.to_array()
    # Convert PCD to PCD with normals
    normals = pcd.calc_normals(ksearch=ksearch, search_radius=search_radius)

    return normals

def calculate_normals_from_depth_and_tactile(depth_cloud, tactile_cloud, depth_downsample_factor):
    v_points = depth_cloud.to_array()
    v_normals = compute_depth_normals(depth_cloud, ksearch=10, search_radius=0)

    v_points = v_points[::depth_downsample_factor]
    v_normals = v_normals[::depth_downsample_factor]

    t_points = tactile_cloud.to_array()
    t_normals = compute_tactile_normals(tactile_cloud)

    vt_points = np.concatenate([v_points, t_points])
    vt_normals = np.concatenate([v_normals, t_normals])

    return vt_points, vt_normals

def pcd_to_np(pcd_filename):
    """
    Read in PCD then return nx3 numpy array

    :type pcd_filename: str
    :rtype numpy.ndarray
    """

    pcd = pcl.load(pcd_filename)
    return pcl_to_np(pcd)

def pcl_to_np(pointcloud):
    """
    Convert PCL pointcloud to numpy nx3 numpy array

    :type pointcloud: pcl.PointCloud
    :rtype numpy.ndarray
    """

    pc_nx3 = pointcloud.to_array()
    return pc_nx3

def np_to_pcl(pc_np):
    """
    Convert nx3 numpy array to PCL pointcloud

    :type pc_np: numpy.ndarray
    :rtype pcl.PointCloud
    """

    new_pcd = pcl.PointCloud(np.array(pc_np, np.float32))
    return new_pcd

<commit_msg>Added correct downsample rate<commit_after>import pcl
import numpy as np
import curvox.cloud_transformations

def write_pcd_with_normals(points, normals, output_pcd_filepath):

    with open(output_pcd_filepath, 'w') as new_pcd_file:
        new_pcd_file.write(
            "# .PCD v0.7 - Point Cloud Data file format\n"
            "VERSION 0.7\n"
            "FIELDS x y z normal_x normal_y normal_z\n"
            "SIZE 4 4 4 4 4 4\n"
            "TYPE F F F F F F\n"
            "COUNT 1 1 1 1 1 1\n"
            "WIDTH {0}\n"
            "HEIGHT 1\n"
            "POINTS {0}\n"
            "DATA ascii\n"
                .format(points.shape[0])
        )

        for point, normal in zip(points, normals):
            new_pcd_file.write("{} {} {} {} {} {}\n".format(point[0], point[1], point[2], normal[0], normal[1], normal[2]))

def compute_tactile_normals(cloud):
    points = cloud.to_array()
    num_points = points.shape[0]
    # n x 1 magnitude of each point
    magnitudes = np.linalg.norm(points, axis=1).reshape((num_points, 1))
    # divide points by per point magnitude, and flip sign to point back at origin
    normals = points / magnitudes

    return normals

def compute_depth_normals(pcd, ksearch, search_radius):
    points = pcd.to_array()
    # Convert PCD to PCD with normals
    normals = pcd.calc_normals(ksearch=ksearch, search_radius=search_radius)

    return normals

def calculate_normals_from_depth_and_tactile(depth_cloud, tactile_cloud, downsampled_pointcloud_size):
    v_points = depth_cloud.to_array()
    v_normals = compute_depth_normals(depth_cloud, ksearch=10, search_radius=0)

    depth_downsample_factor = v_points.shape[0] / downsampled_pointcloud_size

    v_points = v_points[::depth_downsample_factor]
    v_normals = v_normals[::depth_downsample_factor]

    t_points = tactile_cloud.to_array()
    t_normals = compute_tactile_normals(tactile_cloud)

    vt_points = np.concatenate([v_points, t_points])
    vt_normals = np.concatenate([v_normals, t_normals])

    return vt_points, vt_normals

def pcd_to_np(pcd_filename):
    """
    Read in PCD then return nx3 numpy array

    :type pcd_filename: str
    :rtype numpy.ndarray
    """

    pcd = pcl.load(pcd_filename)
    return pcl_to_np(pcd)

def pcl_to_np(pointcloud):
    """
    Convert PCL pointcloud to numpy nx3 numpy array

    :type pointcloud: pcl.PointCloud
    :rtype numpy.ndarray
    """

    pc_nx3 = pointcloud.to_array()
    return pc_nx3

def np_to_pcl(pc_np):
    """
    Convert nx3 numpy array to PCL pointcloud

    :type pc_np: numpy.ndarray
    :rtype pcl.PointCloud
    """

    new_pcd = pcl.PointCloud(np.array(pc_np, np.float32))
    return new_pcd

<|endoftext|>


<commit_before># 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)

from spack import *

class Spdlog(CMakePackage):
    """Very fast, header only, C++ logging library"""

    homepage = "https://github.com/gabime/spdlog"
    url = "https://github.com/gabime/spdlog/archive/v0.9.0.tar.gz"

    version('1.2.1', sha256='867a4b7cedf9805e6f76d3ca41889679054f7e5a3b67722fe6d0eae41852a767')
    version('1.2.0', sha256='0ba31b9e7f8e43a7be328ab0236d57810e5d4fc8a1a7842df665ae22d5cbd128')
    version('1.1.0',  sha256='3dbcbfd8c07e25f5e0d662b194d3a7772ef214358c49ada23c044c4747ce8b19')
    version('1.0.0',  sha256='90d5365121bcd2c41ce94dfe6a460e89507a2dfef6133fe5fad5bb35ac4ef0a1')
    version('0.17.0', sha256='94f74fd1b3344733d1db3de2ec22e6cbeb769f93a8baa0d4a22b1f62dc7369f8')
    version('0.16.3', sha256='b88d7be261d9089c817fc8cee6c000d69f349b357828e4c7f66985bc5d5360b8')
    version('0.16.2', sha256='2081e5df5e87402398847431e16b87c71dd5c4d632314bb976ace8161f4d32de')
    version('0.16.1', sha256='733260e1fbdcf1b3dc307fc585e4476240026de8be28eb905731d2ab0942deae')
    version('0.16.0', sha256='9e64e3b10c2a3c54dfff63aa056057cf1db8a5fd506b3d9cf77207511820baac')
    version('0.14.0', sha256='eb5beb4e53f4bfff5b32eb4db8588484bdc15a17b90eeefef3a9fc74fec1d83d')
    version('0.13.0', sha256='d798a6ca19165f0a18a43938859359269f5a07fd8e0eb83ab8674739c9e8f361')
    version('0.12.0', sha256='5cfd6a0b3182a88e1eb35bcb65a7ef9035140d7c73b16ba6095939dbf07325b9')
    version('0.11.0', '08232203f18a6f9ff47e083cc7a141a050805d3b')
    version('0.10.0', '57b471ef97a23cc29c38b62e00e89a411a87ea7f')
    version('0.9.0', 'dda741ef8e12d57d91f778d85e95a27d84a82ac4')

    depends_on('cmake@3.1:', type='build')
<commit_msg>spdlog: added version 1.4.1 (#12917)<commit_after># 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)

from spack import *

class Spdlog(CMakePackage):
    """Very fast, header only, C++ logging library"""

    homepage = "https://github.com/gabime/spdlog"
    url = "https://github.com/gabime/spdlog/archive/v0.9.0.tar.gz"

    version('1.4.1', sha256='3291958eb54ed942d1bd3aef1b4f8ccf70566cbc04d34296ec61eb96ceb73cff')
    version('1.2.1', sha256='867a4b7cedf9805e6f76d3ca41889679054f7e5a3b67722fe6d0eae41852a767')
    version('1.2.0', sha256='0ba31b9e7f8e43a7be328ab0236d57810e5d4fc8a1a7842df665ae22d5cbd128')
    version('1.1.0',  sha256='3dbcbfd8c07e25f5e0d662b194d3a7772ef214358c49ada23c044c4747ce8b19')
    version('1.0.0',  sha256='90d5365121bcd2c41ce94dfe6a460e89507a2dfef6133fe5fad5bb35ac4ef0a1')
    version('0.17.0', sha256='94f74fd1b3344733d1db3de2ec22e6cbeb769f93a8baa0d4a22b1f62dc7369f8')
    version('0.16.3', sha256='b88d7be261d9089c817fc8cee6c000d69f349b357828e4c7f66985bc5d5360b8')
    version('0.16.2', sha256='2081e5df5e87402398847431e16b87c71dd5c4d632314bb976ace8161f4d32de')
    version('0.16.1', sha256='733260e1fbdcf1b3dc307fc585e4476240026de8be28eb905731d2ab0942deae')
    version('0.16.0', sha256='9e64e3b10c2a3c54dfff63aa056057cf1db8a5fd506b3d9cf77207511820baac')
    version('0.14.0', sha256='eb5beb4e53f4bfff5b32eb4db8588484bdc15a17b90eeefef3a9fc74fec1d83d')
    version('0.13.0', sha256='d798a6ca19165f0a18a43938859359269f5a07fd8e0eb83ab8674739c9e8f361')
    version('0.12.0', sha256='5cfd6a0b3182a88e1eb35bcb65a7ef9035140d7c73b16ba6095939dbf07325b9')
    version('0.11.0', '08232203f18a6f9ff47e083cc7a141a050805d3b')
    version('0.10.0', '57b471ef97a23cc29c38b62e00e89a411a87ea7f')
    version('0.9.0', 'dda741ef8e12d57d91f778d85e95a27d84a82ac4')

    variant('shared', default=True,
            description='Build shared libraries (v1.4.0+)')

    depends_on('cmake@3.2:', type='build')

    def cmake_args(self):
        spec = self.spec

        args = []

        if self.spec.version >= Version('1.4.0'):
            args.extend([
                '-DSPDLOG_BUILD_SHARED:BOOL={0}'.format(
                    'ON' if '+shared' in spec else 'OFF'),
                # tests and examples
                '-DSPDLOG_BUILD_TESTS:BOOL={0}'.format(
                    'ON' if self.run_tests else 'OFF'),
                '-DSPDLOG_BUILD_EXAMPLE:BOOL={0}'.format(
                    'ON' if self.run_tests else 'OFF')
            ])

        return args
<|endoftext|>


<commit_before>#! /usr/bin/env python
# -*- coding: utf-8 -*-

import sys

def main(argv):
    pass

if __name__ == '__main__':
    main(sys.argv)
<commit_msg>currency_converter can parse arguments<commit_after>#! /usr/bin/env python
# -*- coding: utf-8 -*-

import argparse
import json
from currency_converter.money import Money

def main(args):
    m = Money()
    result = m.convert(args.amount, args.input_currency, args.output_currency)
    print(json.dumps(result, indent=4, sort_keys=True))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('--amount', type=float, help="amount", required=True)
    parser.add_argument('--input_currency', type=str,  help="amount", required=True)
    parser.add_argument('--output_currency', type=str, help="amount", required=False)
    args = parser.parse_args()
    main(args)
<|endoftext|>