Example #1
1
    def setUp(self):
        """Initializes the base_url and sets the driver"""
        self.http_username = get_from_tconfig(["linotp", "username"], required=True)
        self.http_password = get_from_tconfig(["linotp", "password"], required=True)
        self.http_host = get_from_tconfig(["linotp", "host"], required=True)
        self.http_protocol = get_from_tconfig(["linotp", "protocol"], default="https")
        self.base_url = (
            self.http_protocol + "://" + self.http_username + ":" + self.http_password + "@" + self.http_host
        )
        self.driver = None
        selenium_driver = get_from_tconfig(["selenium", "driver"], default="firefox").lower()
        selenium_driver_language = get_from_tconfig(["selenium", "language"], default="en_us").lower()
        fp = webdriver.FirefoxProfile()
        fp.set_preference("intl.accept_languages", selenium_driver_language)
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument("--lang=" + selenium_driver_language)

        if selenium_driver == "chrome":
            try:
                self.driver = webdriver.Chrome(chrome_options=chrome_options)
            except WebDriverException:
                warnings.warn(
                    "Error creating Chrome driver. Maybe you forgot installing"
                    " 'chromedriver'. If you wanted to use another Browser please"
                    " adapt your config file."
                )
        elif selenium_driver == "firefox":
            self.driver = webdriver.Firefox(firefox_profile=fp)
        if self.driver is None:
            warnings.warn("Falling back to Firefox driver.")
            self.driver = webdriver.Firefox(firefox_profile=fp)
        self.driver.implicitly_wait(30)
        self.verification_errors = []
        self.accept_next_alert = True
Example #2
1
File: sql.py Project: Will-So/blaze
def compute_up(expr, data, **kwargs):
    index = expr.index[0]  # [0] replace_slices returns tuple ((start, stop), )
    if isinstance(index, slice):
        start = index.start or 0
        if start < 0:
            raise ValueError("start value of slice cannot be negative" " with a SQL backend")

        stop = index.stop
        if stop is not None and stop < 0:
            raise ValueError("stop value of slice cannot be negative with a " "SQL backend.")

        if index.step is not None and index.step != 1:
            raise ValueError("step parameter in slice objects not supported " "with SQL backend")

    elif isinstance(index, (np.integer, numbers.Integral)):
        if index < 0:
            raise ValueError("integer slice cannot be negative for the" " SQL backend")
        start = index
        stop = start + 1
    else:
        raise TypeError("type %r not supported for slicing wih SQL backend" % type(index).__name__)

    warnings.warn(
        "The order of the result set from a Slice expression " "computed against the SQL backend is not deterministic."
    )

    if stop is None:  # Represents open-ended slice. e.g. [3:]
        return select(data).offset(start)
    else:
        return select(data).offset(start).limit(stop - start)
Example #3
1
def run_fetcher_tests(server):
    exc_fetchers = []
    for klass, library_name in [
        (fetchers.Urllib2Fetcher, "urllib2"),
        (fetchers.CurlHTTPFetcher, "pycurl"),
        (fetchers.HTTPLib2Fetcher, "httplib2"),
    ]:
        try:
            exc_fetchers.append(klass())
        except RuntimeError as why:
            if why[0].startswith("Cannot find %s library" % (library_name,)):
                try:
                    __import__(library_name)
                except ImportError:
                    warnings.warn(
                        "Skipping tests for %r fetcher because " "the library did not import." % (library_name,)
                    )
                    pass
                else:
                    assert False, "%s present but not detected" % (library_name,)
            else:
                raise

    non_exc_fetchers = []
    for f in exc_fetchers:
        non_exc_fetchers.append(fetchers.ExceptionWrappingFetcher(f))

    for f in exc_fetchers:
        test_fetcher(f, True, server)

    for f in non_exc_fetchers:
        test_fetcher(f, False, server)
Example #4
1
    def connect_info(self, arg_s):
        """Print information for connecting other clients to this kernel

        It will print the contents of this session's connection file, as well as
        shortcuts for local clients.

        In the simplest case, when called from the most recently launched kernel,
        secondary clients can be connected, simply with:

        $> jupyter <app> --existing

        """

        try:
            connection_file = get_connection_file()
            info = get_connection_info(unpack=False)
        except Exception as e:
            warnings.warn("Could not get connection info: %r" % e)
            return

        # if it's in the default dir, truncate to basename
        if jupyter_runtime_dir() == os.path.dirname(connection_file):
            connection_file = os.path.basename(connection_file)

        print(info + "\n")
        print(
            "Paste the above JSON into a file, and connect with:\n"
            "    $> jupyter <app> --existing <file>\n"
            "or, if you are local, you can connect with just:\n"
            "    $> jupyter <app> --existing {0}\n"
            "or even just:\n"
            "    $> jupyter <app> --existing\n"
            "if this is the most recent Jupyter kernel you have started.".format(connection_file)
        )
Example #5
1
    def slave_okay(self, slave_okay=True):
        """(DEPRECATED) Specify whether this query should be allowed to execute on a slave.

        This method is deprecated and will be removed. Use the slave_okay
        parameter to `pymongo.collection.Collection.find` instead.

        By default, certain queries are not allowed to execute on mongod
        instances running in slave mode. If `slave_okay` is True then this
        query will be allowed to execute on slave instances. If False, the
        default behavior applies.

        Settings made through calls to this method take precedence over any
        settings made elsewhere (like the slave_okay option when creating a
        Connection). The last `slave_okay` applied to this cursor
        takes precedence.

        Raises InvalidOperation if this cursor has already been used.

        :Parameters:
          - `slave_okay` (optional): should this query be allowed to execute on
            slave instances
        """
        warnings.warn(
            "the slave_okay method is deprecated and will"
            " be removed - use the slave_okay paramater to find()"
            " instead",
            DeprecationWarning,
        )
        self.__check_okay_to_chain()

        self.__slave_okay = slave_okay
        return self
Example #6
1
    def runTests(self):
        if self.refleak:
            self.testRunner = RefleakTestRunner

            if not hasattr(sys, "gettotalrefcount"):
                warnings.warn(
                    "detecting reference leaks requires a debug build " "of Python, only memory leaks will be detected"
                )

        elif self.list:
            self.testRunner = TestLister()

        elif self.testRunner is None:
            self.testRunner = unittest.TextTestRunner

        if self.multiprocess and not self.nomultiproc:
            self.testRunner = ParallelTestRunner(
                self.testRunner, verbosity=self.verbosity, failfast=self.failfast, buffer=self.buffer
            )

        def run_tests_real():
            super(NumbaTestProgram, self).runTests()

        if self.profile:
            filename = os.path.splitext(os.path.basename(sys.modules["__main__"].__file__))[0] + ".prof"
            p = cProfile.Profile(timer=time.perf_counter)  # 3.3+
            p.enable()
            try:
                p.runcall(run_tests_real)
            finally:
                p.disable()
                print("Writing test profile data into %r" % (filename,))
                p.dump_stats(filename)
        else:
            run_tests_real()
Example #7
0
    def __init__(self, param, cursor, strings_only=False):
        # With raw SQL queries, datetimes can reach this function
        # without being converted by DateTimeField.get_db_prep_value.
        if settings.USE_TZ and isinstance(param, datetime.datetime):
            if timezone.is_naive(param):
                warnings.warn(
                    "Oracle received a naive datetime (%s)" " while time zone support is active." % param,
                    RuntimeWarning,
                )
                default_timezone = timezone.get_default_timezone()
                param = timezone.make_aware(param, default_timezone)
            param = param.astimezone(timezone.utc).replace(tzinfo=None)

        # Oracle doesn't recognize True and False correctly in Python 3.
        # The conversion done below works both in 2 and 3.
        if param is True:
            param = "1"
        elif param is False:
            param = "0"
        if hasattr(param, "bind_parameter"):
            self.force_bytes = param.bind_parameter(cursor)
        else:
            self.force_bytes = convert_unicode(param, cursor.charset, strings_only)
        if hasattr(param, "input_size"):
            # If parameter has `input_size` attribute, use that.
            self.input_size = param.input_size
        elif isinstance(param, six.string_types) and len(param) > 4000:
            # Mark any string param greater than 4000 characters as a CLOB.
            self.input_size = Database.CLOB
        else:
            self.input_size = None
Example #8
0
 def flush(self, all_dbs=False):
     warnings.warn(
         DeprecationWarning("'flush' has been deprecated. " "Use Redis.flushdb() or Redis.flushall() instead")
     )
     if all_dbs:
         return self.flushall()
     return self.flushdb()
Example #9
0
File: path.py Project: cjmeyer/coal
    def walkdirs(self, pattern=None, errors="strict"):
        """ D.walkdirs() -> iterator over subdirs, recursively.

        With the optional 'pattern' argument, this yields only
        directories whose names match the given pattern.  For
        example, mydir.walkdirs('*test') yields only directories
        with names ending in 'test'.

        The errors= keyword argument controls behavior when an
        error occurs.  The default is 'strict', which causes an
        exception.  The other allowed values are 'warn', which
        reports the error via warnings.warn(), and 'ignore'.
        """
        if errors not in ("strict", "warn", "ignore"):
            raise ValueError("invalid errors parameter")

        try:
            dirs = self.dirs()
        except Exception:
            if errors == "ignore":
                return
            elif errors == "warn":
                warnings.warn("Unable to list directory '%s': %s" % (self, sys.exc_info()[1]), TreeWalkWarning)
                return
            else:
                raise

        for child in dirs:
            if pattern is None or child.fnmatch(pattern):
                yield child
            for subsubdir in child.walkdirs(pattern, errors):
                yield subsubdir
Example #10
0
File: crs.py Project: bblay/cartopy
    def __init__(self, central_longitude=0):
        # Warn when using Robinson with proj4 4.8 due to discontinuity at
        # 40 deg N introduced by incomplete fix to issue #113 (see
        # https://trac.osgeo.org/proj/ticket/113).
        import re

        match = re.search(r"\d\.\d", PROJ4_RELEASE)
        if match is not None:
            proj4_version = float(match.group())
            if proj4_version >= 4.8:
                warnings.warn(
                    "The Robinson projection from Proj.4 versions "
                    "4.8.0 and later contains a discontinuity at "
                    "40 deg latitude. Use this projection with "
                    "caution."
                )
        else:
            warnings.warn(
                "Cannot determine Proj.4 version. The Robinson "
                "projection may be unreliable and should be used "
                "with caution."
            )

        proj4_params = {"proj": "robin", "lon_0": central_longitude}
        super(Robinson, self).__init__(proj4_params, central_longitude)
Example #11
0
def _dl_mult_symbols(symbols, start, end, interval, chunksize, retry_count, pause, method):
    stocks = {}
    failed = []
    passed = []
    for sym_group in _in_chunks(symbols, chunksize):
        for sym in sym_group:
            try:
                stocks[sym] = method(sym, start, end, interval, retry_count, pause)
                passed.append(sym)
            except IOError:
                warnings.warn("Failed to read symbol: {0!r}, replacing with " "NaN.".format(sym), SymbolWarning)
                failed.append(sym)

    if len(passed) == 0:
        raise RemoteDataError("No data fetched using " "{0!r}".format(method.__name__))
    try:
        if len(stocks) > 0 and len(failed) > 0 and len(passed) > 0:
            df_na = stocks[passed[0]].copy()
            df_na[:] = np.nan
            for sym in failed:
                stocks[sym] = df_na
        return Panel(stocks).swapaxes("items", "minor")
    except AttributeError:
        # cannot construct a panel with just 1D nans indicating no data
        raise RemoteDataError("No data fetched using " "{0!r}".format(method.__name__))
Example #12
0
 def decompile(self, data, ttFont):
     loca = ttFont["loca"]
     last = int(loca[0])
     noname = 0
     self.glyphs = {}
     self.glyphOrder = glyphOrder = ttFont.getGlyphOrder()
     for i in range(0, len(loca) - 1):
         try:
             glyphName = glyphOrder[i]
         except IndexError:
             noname = noname + 1
             glyphName = "ttxautoglyph%s" % i
         next = int(loca[i + 1])
         glyphdata = data[last:next]
         if len(glyphdata) != (next - last):
             raise ttLib.TTLibError("not enough 'glyf' table data")
         glyph = Glyph(glyphdata)
         self.glyphs[glyphName] = glyph
         last = next
     if len(data) - next >= 4:
         warnings.warn("too much 'glyf' table data: expected %d, received %d bytes" % (next, len(data)))
     if noname:
         warnings.warn("%s glyphs have no name" % noname)
     if ttFont.lazy is False:  # Be lazy for None and True
         for glyph in self.glyphs.values():
             glyph.expand(self)
 def __init__(
     self,
     alpha=1.0,
     l1_ratio=0.5,
     fit_intercept=True,
     normalize=False,
     precompute="auto",
     max_iter=1000,
     copy_X=True,
     tol=1e-4,
     warm_start=False,
     positive=True,
     rho=None,
 ):
     self.alpha = alpha
     self.l1_ratio = l1_ratio
     if rho is not None:
         self.l1_ratio = rho
         warnings.warn("rho was renamed to l1_ratio and will be removed " "in 0.15", DeprecationWarning)
     self.coef_ = None
     self.fit_intercept = fit_intercept
     self.normalize = normalize
     self.precompute = precompute
     self.max_iter = max_iter
     self.copy_X = copy_X
     self.tol = tol
     self.warm_start = warm_start
     self.positive = positive
     self.intercept_ = 0.0
Example #14
0
    def handle_noargs(self, **options):
        project_root = options.get("path", getattr(settings, "BASE_DIR", None))
        if not project_root:
            project_root = getattr(settings, "BASE_DIR", None)

        verbosity = int(options.get("verbosity"))
        if not project_root:
            warnings.warn("settings.BASE_DIR or specifying --path will become mandatory in 1.4.0", DeprecationWarning)
            project_root = get_project_root()
            if verbosity > 0:
                self.stdout.write(
                    """No path specified and settings.py does not contain BASE_DIR.
Assuming '%s' is the project root.

Please add BASE_DIR to your settings.py future versions 1.4.0 and higher of Django-Extensions
will require either BASE_DIR or specifying the --path option.

Waiting for 30 seconds. Press ctrl-c to abort.
"""
                    % project_root
                )
                if getattr(settings, "CLEAN_PYC_DEPRECATION_WAIT", True):
                    try:
                        time.sleep(30)
                    except KeyboardInterrupt:
                        self.stdout.write("Aborted\n")
                        return
        exts = options.get("optimize", False) and "*.py[co]" or "*.pyc"

        for root, dirs, filenames in os.walk(project_root):
            for filename in fnmatch.filter(filenames, exts):
                full_path = _j(root, filename)
                if verbosity > 1:
                    self.stdout.write("%s\n" % full_path)
                os.remove(full_path)
def pre_upgrade():
    """Check for potentially invalid revisions"""
    res = run_sql(
        """SELECT DISTINCT(changeset_id) FROM bibHOLDINGPEN
                     WHERE LENGTH(changeset_xml) =  %s""",
        [2 ** 16 - 1],
    )
    if res:
        warnings.warn(
            """You have %s holding pen entries with potentially corrupt data!
                         You can find the rows affected with the sql command:
                         SELECT DISTINCT(changeset_id) FROM bibHOLDINGPEN
                         WHERE LENGTH(changeset_xml) =  65535"""
            % len(res)
        )

        from invenio.textutils import wait_for_user

        try:
            wait_for_user(
                "\nThis upgrade will delete all the corrupted entries. A backup table bibHOLDINGPEN_backup will be created.\n"
            )
        except SystemExit:
            raise RuntimeError("Upgrade aborted by user.")

        for r in res:
            run_sql("""DELETE FROM bibHOLDINGPEN WHERE changeset_id=%s""" % r[0])
Example #16
0
 def __init__(self, fname):
     deprecation_msg = (
         "This object is being deprecated in favor of the " + "Topography class in clawpack.geoclaw.topotools."
     )
     warnings.filterwarnings("default", category=DeprecationWarning)
     warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
     warnings.resetwarnings()
     self.fname = fname
     self.topotype = 3
     self.neg_cmap = None
     self.pos_cmap = None
     self.cmap = None
     self.cmax = 100.0
     self.cmin = -4000.0
     self.climits = None
     self.figno = 200
     self.addcolorbar = False
     self.addcontour = False
     self.contour_levels = [0, 0]
     self.xlimits = None
     self.ylimits = None
     self.coarsen = 1
     self.imshow = True
     self.gridedges_show = True
     self.print_fname = True
Example #17
0
    def __call__(self, objfunc, initval, fargs, **kwargs):
        """
        Run the solver.

        Parameters
        ----------
        objfunc : callable
            objection function
        initval : iterable
            initial guess for the parameter values
        fargs : tuple
            other arguments to be passed to the statistic function
        kwargs : dict
            other keyword arguments to be passed to the solver

        """
        if "maxiter" not in kwargs:
            kwargs["maxiter"] = self._maxiter
        if "acc" not in kwargs:
            kwargs["acc"] = self._acc
        fitparams, final_func_val, numiter, funcalls, exit_mode = self.opt_method(
            objfunc, initval, args=fargs, xtol=self._acc, full_output=True
        )
        self.fit_info["final_func_val"] = final_func_val
        self.fit_info["numiter"] = numiter
        self.fit_info["exit_mode"] = exit_mode
        self.fit_info["num_function_calls"] = funcalls
        if self.fit_info["exit_mode"] == 1:
            warnings.warn(
                "The fit may be unsuccessful; " "Maximum number of function evaluations reached.", AstropyUserWarning
            )
        if self.fit_info["exit_mode"] == 2:
            warnings.warn("The fit may be unsuccessful; " "Maximum number of iterations reached.", AstropyUserWarning)
        return fitparams, self.fit_info
Example #18
0
    def _gpu_matrix_dot(matrix_a, matrix_b, matrix_c=None):
        """
        Performs matrix multiplication.

        Attempts to use the GPU if it's available. If the matrix multiplication
        is too big to fit on the GPU, this falls back to the CPU after throwing
        a warning.
        """
        if not hasattr(ZCA._gpu_matrix_dot, "theano_func"):
            ma, mb = theano.tensor.matrices("A", "B")
            mc = theano.tensor.dot(ma, mb)
            ZCA._gpu_matrix_dot.theano_func = theano.function([ma, mb], mc)

        theano_func = ZCA._gpu_matrix_dot.theano_func

        try:
            if matrix_c is None:
                return theano_func(matrix_a, matrix_b)
            else:
                matrix_c[...] = theano_func(matrix_a, matrix_b)
                return matrix_c
        except MemoryError, me:
            warnings.warn(
                "Matrix multiplication too big to fit on GPU. "
                "Re-doing with CPU. Consider using "
                'THEANO_FLAGS="device=cpu" for your next '
                "preprocessor run"
            )
            return numpy.dot(matrix_a, matrix_b, matrix_c)
Example #19
0
    def __init__(self, endpoint, **kwargs):
        self.endpoint = endpoint
        self.identity_headers = kwargs.get("identity_headers")
        self.auth_token = kwargs.get("token")
        if self.identity_headers:
            if self.identity_headers.get("X-Auth-Token"):
                self.auth_token = self.identity_headers.get("X-Auth-Token")
                del self.identity_headers["X-Auth-Token"]

        self.session = requests.Session()
        self.session.headers["User-Agent"] = USER_AGENT

        if self.auth_token:
            self.session.headers["X-Auth-Token"] = self.auth_token

        self.timeout = float(kwargs.get("timeout", 600))

        if self.endpoint.startswith("https"):
            compression = kwargs.get("ssl_compression", True)

            if compression is False:
                # Note: This is not seen by default. (python must be
                # run with -Wd)
                warnings.warn('The "ssl_compression" argument has been ' "deprecated.", DeprecationWarning)

            if kwargs.get("insecure", False) is True:
                self.session.verify = False
            else:
                if kwargs.get("cacert", None) is not "":
                    self.session.verify = kwargs.get("cacert", True)

            self.session.cert = (kwargs.get("cert_file"), kwargs.get("key_file"))
Example #20
0
    def __init__(
        self,
        db_field=None,
        name=None,
        required=False,
        default=None,
        unique=False,
        unique_with=None,
        primary_key=False,
        validation=None,
        choices=None,
        dup_check=True,
    ):
        self.db_field = (db_field or name) if not primary_key else "_id"
        if name:
            import warnings

            msg = "Fields' 'name' attribute deprecated in favour of 'db_field'"
            warnings.warn(msg, DeprecationWarning)
        self.name = None
        self.required = required or primary_key
        self.default = default
        self.unique = bool(unique or unique_with)
        self.unique_with = unique_with
        self.primary_key = primary_key
        self.validation = validation
        self.choices = choices
        self.dup_check = dup_check
        self._in_list = False
Example #21
0
def _fix_compat_issue36(func, errors, processor, args):
    #
    # TODO: remove before 1.0 release (will break backwards compatibility)
    #

    if errors and not hasattr(errors, "__iter__"):
        # what was expected to be a list is actually its first item
        errors = [errors]

        # what was expected to be a function is actually the second item
        if processor:
            errors.append(processor)
            processor = None

        # *args, if any, are the remaining items
        if args:
            errors.extend(args)

        import warnings

        warnings.warn(
            "{func.__name__}: wrappable exceptions must be declared "
            "as list, i.e. @wrap_errors([{errors}]) instead of "
            "@wrap_errors({errors})".format(func=func, errors=", ".join(x.__name__ for x in errors)),
            DeprecationWarning,
        )

    return errors, processor
Example #22
0
 def _copy_tempfiles(self):
     """
     Copies created images from tempfiles to a subfolder of baseline images.
     """
     try:
         filenames = self._get_final_filenames()
         directory = self.output_path
         if os.path.exists(directory):
             if not os.path.isdir(directory):
                 msg = (
                     "Could not keep output image, target directory " "exists but is no directory: %s"
                 ) % directory
                 warnings.warn(msg)
                 return
         else:
             os.mkdir(directory)
         if os.path.isfile(self.diff_filename):
             shutil.copy(self.diff_filename, filenames["diff"])
         shutil.copy(self.name, filenames["actual"])
     except Exception as e:
         msg = ("Failed to copy images from temporary directory " "(caught %s: %s).") % (
             e.__class__.__name__,
             str(e),
         )
         warnings.warn(msg)
Example #23
0
    def __init__(
        self,
        item=None,
        payment_form_cls=PaymentForm,
        payment_template="pro/payment.html",
        confirm_form_cls=ConfirmForm,
        confirm_template="pro/confirm.html",
        success_url="?success",
        fail_url=None,
        context=None,
        form_context_name="form",
        nvp_handler=None,
    ):
        self.item = item
        self.payment_form_cls = payment_form_cls
        self.payment_template = payment_template
        self.confirm_form_cls = confirm_form_cls
        self.confirm_template = confirm_template
        self.success_url = success_url
        self.fail_url = fail_url
        self.context = context or {}
        self.form_context_name = form_context_name
        self.nvp_handler = nvp_handler

        if nvp_handler is None:
            warnings.warn(
                "You didn't pass `nvp_handler` to PayPalPro. You should pass a callback "
                "here instead of using the `payment_was_successful` "
                "signal",
                DeprecationWarning,
            )
Example #24
0
def mpl_style_cb(key):
    warnings.warn(pc_mpl_style_deprecation_warning, FutureWarning, stacklevel=5)

    import sys
    from pandas.tools.plotting import mpl_stylesheet

    global style_backup

    val = cf.get_option(key)

    if "matplotlib" not in sys.modules.keys():
        if not val:  # starting up, we get reset to None
            return val
        raise Exception("matplotlib has not been imported. aborting")

    import matplotlib.pyplot as plt

    if val == "default":
        style_backup = dict([(k, plt.rcParams[k]) for k in mpl_stylesheet])
        plt.rcParams.update(mpl_stylesheet)
    elif not val:
        if style_backup:
            plt.rcParams.update(style_backup)

    return val
Example #25
0
    def hint(self, index):
        """Adds a 'hint', telling Mongo the proper index to use for the query.

        Judicious use of hints can greatly improve query performance. When
        doing a query on multiple fields (at least one of which is indexed)
        pass the indexed field as a hint to the query. Hinting will not do
        anything if the corresponding index does not exist. Raises
        InvalidOperation if this cursor has already been used.

        `index` should be an index as passed to create_index
        (e.g. [('field', ASCENDING)]). If `index` is None any existing
        hints for this query are cleared. The last hint applied to this cursor
        takes precedence over all others.

        :Parameters:
          - `index`: index to hint on (as an index specifier)
        """
        self.__check_okay_to_chain()
        if index is None:
            self.__hint = None
            return self

        if not isinstance(index, (types.StringTypes, types.ListType)):
            raise TypeError("hint takes an index name or " "a list specifying an index")
        if isinstance(index, types.StringTypes):
            warnings.warn(
                "hinting using an index name is deprecated and will" " be removed - use a regular index spec instead",
                DeprecationWarning,
            )
            index = self.__index_name_to_list(index)
        self.__hint = pymongo._index_document(index)
        return self
Example #26
0
File: web.py Project: z2v/aiohttp
    def finish(self):
        """Finalize an application.

        Deprecated alias for .cleanup()
        """
        warnings.warn("Use .cleanup() instead", DeprecationWarning)
        yield from self.cleanup()
Example #27
0
File: base.py Project: spoqa/celery
 def mail_admins(
     self,
     subject,
     body,
     fail_silently=False,
     sender=None,
     to=None,
     host=None,
     port=None,
     user=None,
     password=None,
     timeout=None,
     use_ssl=False,
     use_tls=False,
 ):
     try:
         message = self.mail.Message(sender=sender, to=to, subject=safe_str(subject), body=safe_str(body))
         mailer = self.mail.Mailer(
             host=host, port=port, user=user, password=password, timeout=timeout, use_ssl=use_ssl, use_tls=use_tls
         )
         mailer.send(message)
     except Exception, exc:
         if not fail_silently:
             raise
         warnings.warn(
             self.mail.SendmailWarning("Mail could not be sent: %r %r" % (exc, {"To": to, "Subject": subject}))
         )
Example #28
0
    def __iter__(self):
        """
        Wait for incoming events and receive them upon arrival.

        This methods implicitly calls :meth:`start()`, and starts polling the
        :meth:`fileno` of this monitor.  If a event comes in, it receives the
        corresponding device and yields it to the caller.

        The returned iterator is endless, and continues receiving devices
        without ever stopping.

        Yields ``(action, device)`` (see :meth:`receive_device` for a
        description).

        .. deprecated:: 0.16
           Will be removed in 1.0. Use an explicit loop over :meth:`poll()`
           instead, or monitor asynchronously with :class:`MonitorObserver`.
        """
        import warnings

        warnings.warn(
            "Will be removed in 1.0. Use an explicit loop over "
            '"poll()" instead, or monitor asynchronously with '
            '"MonitorObserver".',
            DeprecationWarning,
        )
        self.start()
        while True:
            device = self.poll()
            if device:
                yield device.action, device
Example #29
0
def get_default_device(default=0):
    from warnings import warn

    warn("get_default_device() is deprecated; " "use make_default_context() instead", DeprecationWarning)

    from pycuda.driver import Device
    import os

    dev = os.environ.get("CUDA_DEVICE")

    if dev is None:
        try:
            dev = open(os.path.join(os.path.expanduser("~"), ".cuda_device")).read().strip()
        except:
            pass

    if dev is None:
        dev = default

    try:
        dev = int(dev)
    except TypeError:
        raise TypeError("CUDA device number (CUDA_DEVICE or ~/.cuda-device) must be an integer")

    return Device(dev)
Example #30
0
    def assemble_interactions_only(self, model, agent_set):
        kf_bind = get_create_parameter(model, "kf_bind", 1.0)
        kr_bind = get_create_parameter(model, "kr_bind", 1.0)

        enz = model.monomers[self.enz.name]
        sub = model.monomers[self.sub.name]

        # See NOTE in monomers_one_step
        site = site_name(self)[0]

        rule_name = "%s_phospho_%s_%s" % (self.enz.name, self.sub.name, site)
        active_site = active_site_names["Kinase"]
        # Create a rule specifying that the substrate binds to the kinase at
        # its active site
        try:
            r = Rule(
                rule_name,
                enz(**{active_site: None}) + sub(**{site: None}) <> enz(**{active_site: 1}) + sub(**{site: 1}),
                kf_bind,
                kr_bind,
            )
            model.add_component(r)
        # If this rule is already in the model, issue a warning and continue
        except ComponentDuplicateNameError:
            msg = "Rule %s already in model! Skipping." % rule_name
            warnings.warn(msg)