def init_sync(cls, name: str, reload: bool = False, limit: int = None):
        if name not in cls.cache and not reload:
            is_async = False
            exchange = getattr(ccxt, name)({
                "timeout": 30 * 1000
            })  # timeout 100s - occasionally causes timeout errors
            markets = exchange.fetch_markets()
            markets = _(markets[:limit]).filter({
                'active': 'true'
            }).key_by('symbol').value()
            symbols = sorted(markets.keys())

            # order_books = { symbol: exchange.fetch_order_book(symbol) for symbol in symbols }
            order_books = {}
            for symbol in symbols:
                while not order_books.get(symbol):
                    try:
                        order_books[symbol] = exchange.fetch_order_book(symbol)
                    except:
                        time.sleep(
                            1
                        )  # occasionally an order book will time out, so keep trying until it succeeds

            cls.cache[name] = Exchange(name, exchange, markets, order_books,
                                       is_async)

        return cls.cache[name]
Example #2
0
def getDeleteListOfPapers(remarkable_files, papers):
    delete_list = []
    paperNames = _(papers).map(lambda p: p.get('title')).value()
    for f in remarkable_files:
        if (f not in paperNames):
            delete_list.append(f)
    return delete_list
Example #3
0
    def combined(cls, orders: 'List[Order]') -> 'Union[Order, None]':
        if len(orders) == 0: return None

        assert _(orders).map('base_currency').uniq().size().value() == 1
        assert _(orders).map('quote_currency').uniq().size().value() == 1
        assert _(orders).map('ask_bid').uniq().size().value() == 1
        assert _(orders).map('market.symbol').uniq().size().value() == 1
        assert _(orders).map('market.exchange').uniq().size().value() == 1

        limit_order_price = Money(0, orders[0].quote_currency)
        quote_total_price = Money(0, orders[0].quote_currency)
        base_volume = Money(0, orders[0].base_currency)

        for order in orders:
            quote_total_price += order.quote_total_price
            base_volume += order.base_volume
        quote_price_unit = quote_total_price / base_volume.amount

        if orders[0].ask_bid == 'ask':
            limit_order_price = _(orders).map('quote_unit_price').max().value()
        if orders[0].ask_bid == 'bid':
            limit_order_price = _(orders).map('quote_unit_price').min().value()

        combined_order = Order(
            raw=[quote_price_unit.amount, base_volume.amount],
            market=orders[0].market,
            ask_bid=orders[0].ask_bid,
            limit_order_price=limit_order_price,
        )
        return combined_order
Example #4
0
def update_csrf():  # not used for now
    headless = wd.firefox.options.Options()
    headless.add_argument("--headless")
    profile = wd.firefox.firefox_profile.FirefoxProfile()
    browser = wd.Firefox(
        # options=headless,
        firefox_profile=profile)
    browser.get("https://my.worldclass.ru/schedule")
    for f in (_(cookies.items()).map(lambda a: {
            "name": a[0],
            "value": a[1]
    })).value():
        print(f)
        browser.add_cookie(f)
    browser.get("https://my.worldclass.ru/")
    return browser.find_element_by_name("_csrf").get_property("value")
    async def init_async(cls,
                         name: str,
                         reload: bool = False,
                         limit: int = None):
        if name not in cls.cache or reload:
            is_async = True
            exchange = getattr(ccxt_async, name)({"timeout": 30 * 1000})
            markets = await exchange.fetch_markets()
            markets = _(markets[:limit]).filter({
                'active': 'true'
            }).key_by('symbol').value()
            symbols = sorted(markets.keys())
            order_books = await asyncio.gather(
                *[exchange.fetch_order_book(symbol) for symbol in symbols])
            order_books = dict(_.zip(symbols, order_books))

            cls.cache[name] = Exchange(name, exchange, markets, order_books,
                                       is_async)

        return cls.cache[name]
Example #6
0
def variance(array):
    """Calculate the variance of the elements in `array`.

    Args:
        array (list): List to process.

    Returns:
        float: Calculated variance.

    Example:

        >>> variance([1, 18, 20, 4])
        69.6875

    .. versionadded:: 2.1.0
    """
    ave = average(array)

    def var(x): return power(x - ave, 2)  # pylint: disable=missing-docstring

    return pyd._(array).map_(var).average().value()
Example #7
0
def variance(array):
    """Calculate the variance of the elements in `array`.

    Args:
        array (list): List to process.

    Returns:
        float: Calculated variance.

    Example:

        >>> variance([1, 18, 20, 4])
        69.6875

    .. versionadded:: 2.1.0
    """
    avg = mean(array)

    def var(x):
        return power(x - avg, 2)

    return pyd._(array).map_(var).mean().value()
Example #8
0
def variance(array):
    """Calculate the variance of the elements in `array`.

    Args:
        array (list): List to process.

    Returns:
        float: Calculated variance.

    Example:

        >>> variance([1, 18, 20, 4])
        69.6875

    .. versionadded:: 2.1.0
    """
    ave = average(array)

    def var(x):
        return power(x - ave, 2)  # pylint: disable=missing-docstring

    return pyd._(array).map_(var).average().value()
    def __init__(self,
                 name: str,
                 exchange: ccxt.Exchange,
                 markets: dict,
                 order_books: dict,
                 is_async: bool = False):
        self.is_async = is_async
        self.name = name
        self.exchange = exchange

        # self.symbols = ['ADC/BTC', 'ADC/DOGE', 'ADC/ETH', 'BCH/BTC', 'BCH/DOGE', 'BCH/ETH', 'BITB/BTC', 'BITB/DOGE', 'BITB/ETH', 'BLK/BTC', 'BLK/DOGE', 'BLK/ETH', ... ]
        self.symbols = sorted(markets.keys())

        # self.currencies = ['ADC', 'BCH', 'BITB', 'BLK', 'BSTY', ]
        self.currencies = _(exchange.symbols).map(
            lambda s: re.split('/', s)).flatten().uniq().sort_by().value()

        for symbol in self.symbols:
            markets[symbol]['exchange'] = name
            _.assign(markets[symbol], order_books[symbol])
            markets[symbol] = Market(markets[symbol])

        self.markets = markets
        self.markets_df = pd.DataFrame(markets)
Example #10
0
        description=(event["service"]["shortDescription"]),
        location=(event["room"]["name"]),
        start=start,
        end=end,
    )


print("Updating csrf...")
csrf = update_csrf_hls()

print("Logging in to EteSync...")
etesync = etebase.Account.login(etebase.Client("gensec"), ete_username,
                                ete_password)
collection_manager = etesync.get_collection_manager()
calendar = (_(collection_manager.list("etebase.vevent").data).filter(
    lambda a: a.uid == calendar_uid).map(
        collection_manager.get_item_manager).value()[0])

print("Fetching WorldClass schedule...")
start = dt.datetime.now()
start.replace(hour=0, minute=0, second=0)
event_list = get_gym_events(start, start + dt.timedelta(days=2))

# ===== Write after this line

# Call if you need to dispose of your test events
# clear_generated()

# Call to schedule and add workout to calendar
# add_workout(event)
Example #11
0
def test_dash_instance_chaining():
    value = [1, 2, 3, 4]
    from__ = _._(value).without(2, 3).reject(lambda x: x > 1)
    from_chain = _.chain(value).without(2, 3).reject(lambda x: x > 1)

    assert from__.value() == from_chain.value()
Example #12
0
def test_dash_instance_chaining():
    value = [1, 2, 3, 4]
    from__ = _._(value).without(2, 3).reject(lambda x: x > 1)
    from_chain = _.chain(value).without(2, 3).reject(lambda x: x > 1)

    assert from__.value() == from_chain.value()
Example #13
0
from pydash import _
from string import Template

head = lambda list: list[0]
tail = lambda list: list[1:]

findNonZero = _().find_last_index(lambda elem: elem != 0)
checkForZero = lambda x: x if x > 0 else 0
checkCoeffList = _.flow(findNonZero, checkForZero)
sliceZeroCoeffs = lambda coeffs_list: _.slice(coeffs_list, 0,
                                              checkCoeffList(coeffs_list) + 1)
prepareCoeefs = _.flow(_.reverse, sliceZeroCoeffs)

size = lambda list: _.size(list)
reverse = lambda list: _.reverse(list)

append = lambda appends, list: list + appends
curryLeftAppend = _.curry(append)
curryRightAppend = _.curry_right(append)

isNumerical = lambda x: isinstance(x, (int, float))
isListEmpty = lambda list: size(list) == 0
isListNumerical = _().every(isNumerical)

addToFirstElem = _.curry(lambda value, list: [list[0] + value] + list[1:])
sumIdenticalSizeList = lambda a_list, b_list: _.map(
    a_list, lambda x, index: b_list[index] + x)
# size b gt size a
sumGtList = lambda a, b: _.flow(
    sumIdenticalSizeList, curryLeftAppend(_.slice(b, size(a), size(b))))(a, b)
sumList = lambda a, b: sumGtList(a, b) if size(b) > size(a) else sumGtList(
Example #14
0
 def generate_sentence():
     current_word_count = random.randint(5, 30) if word_count is None else word_count
     return _(vocab).sample_size(current_word_count).join(' ').capitalize().value()