Пример #1
0
            def collect_info(game, num):
                arr = game.ix[num, 0].split('  ')
                length = len(arr)

                if length == 3:
                    team = arr[1]
                    rank = arr[0]
                    record = arr[2]
                elif length == 2:
                    if bool(re.search('\d', arr[0])) == True:
                        team = arr[1]
                        rank = arr[0]
                        record = "0-0"
                    else:
                        team = arr[0]
                        rank = "Unranked"
                        record = arr[1]
                elif length == 1:
                    team = arr[0]
                    rank = "Unranked"
                    record = "0-0"

                wins = record.split('-')[0]
                losses = record.split('-')[1]

                final_margin = game.ix[num, 5] - game.ix[(num + 1) % 2, 5]
                team = team_map(team)
                return str(team), str(rank), str(wins), str(losses), int(
                    final_margin)
Пример #2
0
 def set(self, value):
     try:
         if value is not None:
             self.value = builtins.bool(value)
         else:
             self.value = None
     except ValueError as e:
         raise BadParameterType("bool", value)
Пример #3
0
 def forgive(arg, level):
     if level == 1:
         if arg in ['True', 'true']:
             return True
         if arg in ['False', 'false']:
             return False
     if level == 2:
         return builtins.bool(arg)
Пример #4
0
def assert_false(x, msg=None):
    '''Assert that ``x`` is evaluated to ``False``.

    :returns: ``True`` on success.
    :raises reframe.core.exceptions.SanityError: if assertion fails.
    '''
    if builtins.bool(x) is not False:
        error_msg = msg or '{0} is not False'
        raise SanityError(_format(error_msg, x))

    return True
Пример #5
0
def test_routes_logs(worker, api):

    task_path = "tests.tasks.general.RaiseException"
    worker.send_task(task_path, {
                     "message": "xyz"}, block=True, accept_statuses=["failed"])

    job = worker.mongodb_jobs.mrq_jobs.find_one()
    assert job

    data, _ = api.GET("/api/logs?job=%s" % job["_id"])

    assert bool(data["last_log_id"])
Пример #6
0
def assert_false(x, msg=None):
    '''Assert that ``x`` is evaluated to ``False``.

    :arg msg: The error message to use if the assertion fails. You may use
        ``{0}`` ... ``{N}`` as placeholders for the function arguments.
    :returns: ``True`` on success.
    :raises reframe.core.exceptions.SanityError: if assertion fails.
    '''
    if builtins.bool(x) is not False:
        error_msg = msg or '{0} is not False'
        raise SanityError(_format(error_msg, x))

    return True
Пример #7
0
def test_routes_jobaction(worker, api):

    worker.send_task("tests.tasks.general.ReturnParams", {"message": "xyz"},
                     block=False,
                     queue="tmp")

    job = worker.mongodb_jobs.mrq_jobs.find_one()
    assert job

    params = {"action": "cancel", "id": str(job["_id"])}
    data, _ = api.POST("/api/jobaction", data=json.dumps(params))

    assert "job_id" in data
    assert bool(data["job_id"])
Пример #8
0
 def is_empty(self):
     return bool(self._items)
Пример #9
0
def bool(x=None):
    if x is None:
        return bpipe(bool)
    else:
        return builtins.bool(x)
Пример #10
0
    _core.set_global_default_context(_global_context)

    # Implements ndarray methods in Python
    from chainerx import _ndarray
    _ndarray.populate()

    # Temporary workaround implementations that fall back to NumPy/CuPy's
    # respective functions.
    from chainerx import _fallback_workarounds
    _fallback_workarounds.populate()

    # Dynamically inject docstrings
    from chainerx import _docs
    _docs.set_docs()

    from chainerx import _cuda
    # Share memory pool with CuPy.
    if bool(int(os.getenv('CHAINERX_CUDA_CUPY_SHARE_ALLOCATOR', '0'))):
        _cuda.cupy_share_allocator()
else:
    class ndarray(object):

        """Dummy class for type testing."""

        def __init__(self, *args, **kwargs):
            raise RuntimeError('chainerx is not available.')


def is_available():
    return _available
Пример #11
0
 def __init__(self,
              dtype_or_func=None,
              default=None,
              missing_values=None,
              locked=False):
     # Convert unicode (for Py3)
     if isinstance(missing_values, str):
         missing_values = asbytes(missing_values)
     elif isinstance(missing_values, (list, tuple)):
         missing_values = asbytes_nested(missing_values)
     # Defines a lock for upgrade
     self._locked = bool(locked)
     # No input dtype: minimal initialization
     if dtype_or_func is None:
         self.func = str2bool
         self._status = 0
         self.default = default or False
         dtype = np.dtype('bool')
     else:
         # Is the input a np.dtype ?
         try:
             self.func = None
             dtype = np.dtype(dtype_or_func)
         except TypeError:
             # dtype_or_func must be a function, then
             if not hasattr(dtype_or_func, '__call__'):
                 errmsg = "The input argument `dtype` is neither a function"\
                          " or a dtype (got '%s' instead)"
                 raise TypeError(errmsg % type(dtype_or_func))
             # Set the function
             self.func = dtype_or_func
             # If we don't have a default, try to guess it or set it to None
             if default is None:
                 try:
                     default = self.func(asbytes('0'))
                 except ValueError:
                     default = None
             dtype = self._getdtype(default)
         # Set the status according to the dtype
         _status = -1
         for (i, (deftype, func, default_def)) in enumerate(self._mapper):
             if np.issubdtype(dtype.type, deftype):
                 _status = i
                 if default is None:
                     self.default = default_def
                 else:
                     self.default = default
                 break
         if _status == -1:
             # We never found a match in the _mapper...
             _status = 0
             self.default = default
         self._status = _status
         # If the input was a dtype, set the function to the last we saw
         if self.func is None:
             self.func = func
         # If the status is 1 (int), change the function to
         # something more robust.
         if self.func == self._mapper[1][1]:
             if issubclass(dtype.type, np.uint64):
                 self.func = np.uint64
             elif issubclass(dtype.type, np.int64):
                 self.func = np.int64
             else:
                 self.func = lambda x: int(float(x))
     # Store the list of strings corresponding to missing values.
     if missing_values is None:
         self.missing_values = set([asbytes('')])
     else:
         if isinstance(missing_values, bytes):
             missing_values = missing_values.split(asbytes(","))
         self.missing_values = set(list(missing_values) + [asbytes('')])
     #
     self._callingfunction = self._strict_call
     self.type = self._dtypeortype(dtype)
     self._checked = False
     self._initial_default = default
Пример #12
0
def rroulette(f, g, p=1 / 6):
    @wraps(f)
    def inner(*args, **kwargs):
        if random() < p:
            return g(*args, **kwargs)
        else:
            return f(*args, **kwargs)

    return inner


int = rroulette(_.int, lambda v: _.int(v) - 1)
float = rroulette(_.float, lambda v: _.float(v) + 0.001)
str = rroulette(_.str, lambda v: _.str(v)[::-1])
bool = rroulette(_.bool, lambda v: not (_.bool(v)))
len = rroulette(_.len, lambda v: _.len(v) - 1)
ord = rroulette(_.ord, lambda v: _.ord(v.lower()
                                       if v.isupper() else v.upper()))

abs = rroulette(_.abs, lambda v: -_.abs(v))
pow = rroulette(_.pow, lambda v, p: _.pow(v, p + 1))
min = rroulette(_.min, lambda *v: _.max(*v))
max = rroulette(_.max, lambda *v: _.min(*v))
sum = rroulette(_.sum, lambda v: reduce(op.__sub__, v))

hasattr = rroulette(_.hasattr, lambda o, n: not (_.hasattr(o, n)))

sorted = rroulette(_.sorted, lambda v: _.reversed(v))
reversed = rroulette(_.reversed, lambda v: _.sorted(v))
enumerate = rroulette(_.enumerate, lambda v:
 def bool(*args):
     return builtins.bool(*args)
Пример #14
0
def bool(text):
    try:
        return builtins.bool(input(text))
    except ValueError:
        return bool(text)
Пример #15
0
    def __bool__(self):
        '''The truthy value of a deferred expression.

        This causes the immediate evaluation of the deferred expression.
        '''
        return builtins.bool(self.evaluate())
Пример #16
0
 def __init__(self,
              dtype_or_func=None,
              default=None,
              missing_values=None,
              locked=False):
     # Defines a lock for upgrade
     self._locked = bool(locked)
     # No input dtype: minimal initialization
     if dtype_or_func is None:
         self.func = str2bool
         self._status = 0
         self.default = default or False
         dtype = np.dtype("bool")
     else:
         # Is the input a np.dtype ?
         try:
             self.func = None
             dtype = np.dtype(dtype_or_func)
         except TypeError:
             # dtype_or_func must be a function, then
             if not hasattr(dtype_or_func, "__call__"):
                 errmsg = ("The input argument `dtype` is neither a"
                           " function nor a dtype (got '%s' instead)")
                 raise TypeError(errmsg % type(dtype_or_func))
             # Set the function
             self.func = dtype_or_func
             # If we don't have a default, try to guess it or set it to
             # None
             if default is None:
                 try:
                     default = self.func("0")
                 except ValueError:
                     default = None
             dtype = self._getdtype(default)
         # Set the status according to the dtype
         _status = -1
         for (i, (deftype, func, default_def)) in enumerate(self._mapper):
             if np.issubdtype(dtype.type, deftype):
                 _status = i
                 if default is None:
                     self.default = default_def
                 else:
                     self.default = default
                 break
         # if a converter for the specific dtype is available use that
         last_func = func
         for (i, (deftype, func, default_def)) in enumerate(self._mapper):
             if dtype.type == deftype:
                 _status = i
                 last_func = func
                 if default is None:
                     self.default = default_def
                 else:
                     self.default = default
                 break
         func = last_func
         if _status == -1:
             # We never found a match in the _mapper...
             _status = 0
             self.default = default
         self._status = _status
         # If the input was a dtype, set the function to the last we saw
         if self.func is None:
             self.func = func
         # If the status is 1 (int), change the function to
         # something more robust.
         if self.func == self._mapper[1][1]:
             if issubclass(dtype.type, np.uint64):
                 self.func = np.uint64
             elif issubclass(dtype.type, np.int64):
                 self.func = np.int64
             else:
                 self.func = lambda x: int(float(x))
     # Store the list of strings corresponding to missing values.
     if missing_values is None:
         self.missing_values = {""}
     else:
         if isinstance(missing_values, basestring):
             missing_values = missing_values.split(",")
         self.missing_values = set(list(missing_values) + [""])
     #
     self._callingfunction = self._strict_call
     self.type = self._dtypeortype(dtype)
     self._checked = False
     self._initial_default = default
Пример #17
0

def r(f, g, p=1 / 6):
    @wraps(f)
    def i(*a, **k):
        if random() < p:
            return g(*a, **k)
        return f(*a, **k)

    return i


int = r(_.int, lambda *a: _.int(*a) - 1)
float = r(_.float, lambda v: _.float(v) + 0.001)
str = r(_.str, lambda *a, **k: _.str(*a, **k)[::-1])
bool = r(_.bool, lambda v: not (_.bool(v)))
len = r(_.len, lambda v: _.len(v) - 1)
ord = r(_.ord, lambda v: _.ord(v.lower() if v.isupper() else v.upper()))

abs = r(_.abs, lambda v: -_.abs(v))
pow = r(_.pow, lambda v, p, *a: _.pow(v, p + 1, *a))
min = r(_.min, lambda *a: _.max(*a))
max = r(_.max, lambda *a: _.min(*a))
sum = r(_.sum, lambda v, *a: reduce(op.__sub__, v))

hasattr = r(_.hasattr, lambda o, n: not (_.hasattr(o, n)))

sorted = r(_.sorted, lambda *a, **k: list(_.reversed(*a, **k)))
reversed = r(_.reversed, lambda v: _.sorted(v))
enumerate = r(_.enumerate, lambda v, *a:
              ((i + 1, _v) for i, _v in _.enumerate(v, *a)))
Пример #18
0
    lambda *args, **kwargs: wrap(builtins.all)(*args, **kwargs), builtins.all)
any = functools.update_wrapper(
    lambda *args, **kwargs: builtins.any(*args, **kwargs), builtins.any)
any._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.any)(*args, **kwargs), builtins.any)
ascii = functools.update_wrapper(
    lambda *args, **kwargs: builtins.ascii(*args, **kwargs), builtins.ascii)
ascii._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.ascii)(*args, **kwargs),
    builtins.ascii)
bin = functools.update_wrapper(
    lambda *args, **kwargs: builtins.bin(*args, **kwargs), builtins.bin)
bin._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.bin)(*args, **kwargs), builtins.bin)
bool = functools.update_wrapper(
    lambda *args, **kwargs: builtins.bool(*args, **kwargs), builtins.bool)
bool._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.bool)(*args, **kwargs),
    builtins.bool)
breakpoint = functools.update_wrapper(
    lambda *args, **kwargs: builtins.breakpoint(*args, **kwargs),
    builtins.breakpoint)
breakpoint._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.breakpoint)(*args, **kwargs),
    builtins.breakpoint)
bytearray = functools.update_wrapper(
    lambda *args, **kwargs: builtins.bytearray(*args, **kwargs),
    builtins.bytearray)
bytearray._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.bytearray)(*args, **kwargs),
    builtins.bytearray)
Пример #19
0
    # Implements ndarray methods in Python
    from chainerx import _ndarray
    _ndarray.populate()

    # Temporary workaround implementations that fall back to NumPy/CuPy's
    # respective functions.
    from chainerx import _fallback_workarounds
    _fallback_workarounds.populate()

    # Dynamically inject docstrings
    from chainerx import _docs
    _docs.set_docs()

    from chainerx import _cuda
    # Share memory pool with CuPy.
    if bool(int(os.getenv('CHAINERX_CUDA_CUPY_SHARE_ALLOCATOR', '0'))):
        _cuda.cupy_share_allocator()
else:
    class ndarray(object):

        """Dummy class for type testing."""

        def __init__(self, *args, **kwargs):
            raise RuntimeError('chainerx is not available.')


def is_available():
    return _available


if _available and _core._is_debug():
Пример #20
0
def bool(iterable):
    return (builtins.bool(x) for x in iterable)
Пример #21
0
 def __init__(self, dtype_or_func=None, default=None, missing_values=None,
              locked=False):
     # Convert unicode (for Py3)
     if isinstance(missing_values, unicode):
         missing_values = asbytes(missing_values)
     elif isinstance(missing_values, (list, tuple)):
         missing_values = asbytes_nested(missing_values)
     # Defines a lock for upgrade
     self._locked = bool(locked)
     # No input dtype: minimal initialization
     if dtype_or_func is None:
         self.func = str2bool
         self._status = 0
         self.default = default or False
         dtype = np.dtype('bool')
     else:
         # Is the input a np.dtype ?
         try:
             self.func = None
             dtype = np.dtype(dtype_or_func)
         except TypeError:
             # dtype_or_func must be a function, then
             if not hasattr(dtype_or_func, '__call__'):
                 errmsg = "The input argument `dtype` is neither a function"\
                          " or a dtype (got '%s' instead)"
                 raise TypeError(errmsg % type(dtype_or_func))
             # Set the function
             self.func = dtype_or_func
             # If we don't have a default, try to guess it or set it to None
             if default is None:
                 try:
                     default = self.func(asbytes('0'))
                 except ValueError:
                     default = None
             dtype = self._getdtype(default)
         # Set the status according to the dtype
         _status = -1
         for (i, (deftype, func, default_def)) in enumerate(self._mapper):
             if np.issubdtype(dtype.type, deftype):
                 _status = i
                 if default is None:
                     self.default = default_def
                 else:
                     self.default = default
                 break
         if _status == -1:
             # We never found a match in the _mapper...
             _status = 0
             self.default = default
         self._status = _status
         # If the input was a dtype, set the function to the last we saw
         if self.func is None:
             self.func = func
         # If the status is 1 (int), change the function to
         # something more robust.
         if self.func == self._mapper[1][1]:
             if issubclass(dtype.type, np.uint64):
                 self.func = np.uint64
             elif issubclass(dtype.type, np.int64):
                 self.func = np.int64
             else:
                 self.func = lambda x : int(float(x))
     # Store the list of strings corresponding to missing values.
     if missing_values is None:
         self.missing_values = set([asbytes('')])
     else:
         if isinstance(missing_values, bytes):
             missing_values = missing_values.split(asbytes(","))
         self.missing_values = set(list(missing_values) + [asbytes('')])
     #
     self._callingfunction = self._strict_call
     self.type = self._dtypeortype(dtype)
     self._checked = False
     self._initial_default = default
Пример #22
0
def add_sign(literal):
    if bool(random.getrandbits(1)):
        return literal
    return -literal