Example #1
0
 def _queryapi(self, method_url, get, post):
     c = pycurl.Curl()
     if bool(get):
         query_url = method_url + '?' + urlencode(get)
     else:
         query_url = method_url
     c.setopt(c.URL, query_url)
     if bool(post):
         # first clear all fields that are None
         post_cleared = {}
         for i in post:
             if post[i] is not None:
                 post_cleared[i] = post[i]
         postfields = urlencode(post_cleared)
         c.setopt(c.POSTFIELDS, postfields)
     buffer = StringIO()
     c.setopt(c.WRITEFUNCTION, buffer.write)
     c.setopt(c.HTTPHEADER, ['PddToken: ' + self.token])
     c.perform()
     http_response_code = c.getinfo(c.RESPONSE_CODE)
     http_response_data = json.loads(buffer.getvalue())
     c.close()
     if 200 != http_response_code:
         self.module.fail_json(msg='Error querying yandex pdd api, HTTP status=' + c.getinfo(c.RESPONSE_CODE) + ' error=' + http_response_data.error)
     return (http_response_code, http_response_data)
        def relpath(path, start=os.path.curdir):
            """Return a relative version of a path"""
            from os.path import sep, curdir, join, abspath, commonprefix, \
                 pardir, splitunc

            if not path:
                raise ValueError("no path specified")
            start_list = abspath(start).split(sep)
            path_list = abspath(path).split(sep)
            if start_list[0].lower() != path_list[0].lower():
                unc_path, rest = splitunc(path)
                unc_start, rest = splitunc(start)
                if bool(unc_path) ^ bool(unc_start):
                    raise ValueError("Cannot mix UNC and non-UNC paths (%s and %s)"
                                                                        % (path, start))
                else:
                    raise ValueError("path is on drive %s, start on drive %s"
                                                        % (path_list[0], start_list[0]))
            # Work out how much of the filepath is shared by start and path.
            for i in range(min(len(start_list), len(path_list))):
                if start_list[i].lower() != path_list[i].lower():
                    break
            else:
                i += 1

            rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
            if not rel_list:
                return curdir
            return join(*rel_list)
Example #3
0
 def check(rv, ans):
     assert bool(rv[1]) == bool(ans[1])
     if ans[1]:
         return s_check(rv, ans)
     e = rv[0].expand()
     a = ans[0].expand()
     return e in [a, -a] and rv[1] == ans[1]
    def onOK(self, event): # wxGlade: PreferencesPanel.<event_handler>
        """Record all of the preferences and return to fitting mode."""

        # Record structure viewer stuff
        executable = str(self.textCtrlViewer.GetValue()).strip()
        argstr = str(self.textCtrlArgument.GetValue()).strip()
        fileformat = str(self.choiceFormat.GetStringSelection())
        config = {
                "executable" : executable,
                "argstr"     : argstr,
                "fileformat" : fileformat,
                }

        viewer = structureviewer.getStructureViewer()
        viewer.setConfig(config)

        # Structures path
        remember = bool(self.structureDirCheckBox.GetValue())
        if not self.cP.has_section("PHASE"):
            self.cP.add_section("PHASE")
        self.cP.set("PHASE", "remember", str(remember))

        # Data set path
        remember = bool(self.dataDirCheckBox.GetValue())
        if not self.cP.has_section("DATASET"):
            self.cP.add_section("DATASET")
        self.cP.set("DATASET", "remember", str(remember))

        # Get out of here
        self.onCancel(event)
        return
Example #5
0
    def get_visibility_errors(self, customer):
        if self.product.deleted:
            yield ValidationError(_('This product has been deleted.'), code="product_deleted")

        if customer and customer.is_all_seeing:  # None of the further conditions matter for omniscient customers.
            return

        if not self.visible:
            yield ValidationError(_('This product is not visible.'), code="product_not_visible")

        is_logged_in = (bool(customer) and not customer.is_anonymous)

        if not is_logged_in and self.visibility_limit != ProductVisibility.VISIBLE_TO_ALL:
            yield ValidationError(
                _('The Product is invisible to users not logged in.'),
                code="product_not_visible_to_anonymous")

        if is_logged_in and self.visibility_limit == ProductVisibility.VISIBLE_TO_GROUPS:
            # TODO: Optimization
            user_groups = set(customer.groups.all().values_list("pk", flat=True))
            my_groups = set(self.visibility_groups.values_list("pk", flat=True))
            if not bool(user_groups & my_groups):
                yield ValidationError(
                    _('This product is not visible to your group.'),
                    code="product_not_visible_to_group"
                )

        for receiver, response in get_visibility_errors.send(ShopProduct, shop_product=self, customer=customer):
            for error in response:
                yield error
Example #6
0
    def _update(self, message, clean_ctrl_chars=True, commit=True, waitFlush=None, waitSearcher=None):
        """
        Posts the given xml message to http://<self.url>/update and
        returns the result.

        Passing `sanitize` as False will prevent the message from being cleaned
        of control characters (default True). This is done by default because
        these characters would cause Solr to fail to parse the XML. Only pass
        False if you're positive your data is clean.
        """
        path = 'update/'

        # Per http://wiki.apache.org/solr/UpdateXmlMessages, we can append a
        # ``commit=true`` to the URL and have the commit happen without a
        # second request.
        query_vars = []

        if commit is not None:
            query_vars.append('commit=%s' % str(bool(commit)).lower())

        if waitFlush is not None:
            query_vars.append('waitFlush=%s' % str(bool(waitFlush)).lower())

        if waitSearcher is not None:
            query_vars.append('waitSearcher=%s' % str(bool(waitSearcher)).lower())

        if query_vars:
            path = '%s?%s' % (path, '&'.join(query_vars))

        # Clean the message of ctrl characters.
        if clean_ctrl_chars:
            message = sanitize(message)

        return self._send_request('post', path, message, {'Content-type': 'text/xml; charset=utf-8'})
Example #7
0
def IncBench(inc):

    NR_CYCLES = 201
      
    m = 8
    n = 2 ** m

    count = Signal(intbv(0)[m:])
    count_v = Signal(intbv(0)[m:])
    enable = Signal(bool(0))
    clock, reset = [Signal(bool(0)) for i in range(2)]


    inc_inst = inc(count, enable, clock, reset, n=n)

    @instance
    def clockgen():
        clock.next = 1
        for i in range(NR_CYCLES):
            yield delay(10)
            clock.next = not clock

    @instance
    def monitor():
        reset.next = 0
        enable.next = 1
        yield clock.negedge
        reset.next = 1
        yield clock.negedge
        while True:
            yield clock.negedge
            print count

    return inc_inst, clockgen, monitor
Example #8
0
 def _process(self):
     self.user.settings.set('suggest_categories', True)
     tz = session.tzinfo
     hours, minutes = timedelta_split(tz.utcoffset(datetime.now()))[:2]
     categories = get_related_categories(self.user)
     categories_events = []
     if categories:
         category_ids = {c['categ'].id for c in categories.itervalues()}
         today = now_utc(False).astimezone(tz).date()
         query = (Event.query
                  .filter(~Event.is_deleted,
                          Event.category_chain_overlaps(category_ids),
                          Event.start_dt.astimezone(session.tzinfo) >= today)
                  .options(joinedload('category').load_only('id', 'title'),
                           joinedload('series'),
                           subqueryload('acl_entries'),
                           load_only('id', 'category_id', 'start_dt', 'end_dt', 'title', 'access_key',
                                     'protection_mode', 'series_id', 'series_pos', 'series_count'))
                  .order_by(Event.start_dt, Event.id))
         categories_events = get_n_matching(query, 10, lambda x: x.can_access(self.user))
     from_dt = now_utc(False) - relativedelta(weeks=1, hour=0, minute=0, second=0)
     linked_events = [(event, {'management': bool(roles & self.management_roles),
                               'reviewing': bool(roles & self.reviewer_roles),
                               'attendance': bool(roles & self.attendance_roles)})
                      for event, roles in get_linked_events(self.user, from_dt, 10).iteritems()]
     return WPUser.render_template('dashboard.html', 'dashboard',
                                   offset='{:+03d}:{:02d}'.format(hours, minutes), user=self.user,
                                   categories=categories,
                                   categories_events=categories_events,
                                   suggested_categories=get_suggested_categories(self.user),
                                   linked_events=linked_events)
Example #9
0
def database_filename(subreddit=None, username=None):
    '''
    Given a subreddit name or username, return the appropriate database filename.
    '''
    if bool(subreddit) == bool(username):
        raise ValueError('Enter subreddit or username but not both')

    text = subreddit or username
    text = text.replace('/', os.sep)

    if os.sep in text:
        # If they've given us a full path, don't mess
        # with it
        return text

    text = text.replace('\\', os.sep)
    if not text.endswith('.db'):
        text += '.db'

    if subreddit:
        full_path = DATABASE_SUBREDDIT % text
    else:
        full_path = DATABASE_USER % text

    basename = os.path.basename(full_path)
    if os.path.exists(basename):
        # Prioritize existing local files of the same name before creating
        # the deeper, proper one.
        return basename

    return full_path
Example #10
0
def GetDisplayModes():
    res = []
    displayDevice = DISPLAY_DEVICE()
    displayDevice.cb = sizeof(DISPLAY_DEVICE)
    devMode = DEVMODE()
    devMode.dmSize = sizeof(DEVMODE)
    iDevNum = 0
    while True:
        if EnumDisplayDevices(None, iDevNum, pointer(displayDevice), 0) == 0:
            break
        iDevNum += 1
        if displayDevice.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER:
            continue
        EnumDisplaySettingsEx(
            displayDevice.DeviceName,
            ENUM_CURRENT_SETTINGS,
            pointer(devMode),
            0
        )
        displayMode = (
            displayDevice.DeviceName,
            devMode.dmPosition.x,
            devMode.dmPosition.y,
            devMode.dmPelsWidth,
            devMode.dmPelsHeight,
            devMode.dmDisplayFrequency,
            devMode.dmBitsPerPel,
            bool(
                displayDevice.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP
            ),
            bool(displayDevice.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE),
            devMode.dmDisplayFlags,
        )
        res.append(displayMode)
    return tuple(res)
Example #11
0
    def synonyms(self, tax_id=None, tax_name=None):
        if not bool(tax_id) ^ bool(tax_name):
            raise ValueError(
                'Exactly one of tax_id and tax_name may be provided.')

        names = self.names

        if tax_name:
            s1 = select([names.c.tax_id], names.c.tax_name == tax_name)
            res = s1.execute().fetchone()

            if res:
                tax_id = res[0]
            else:
                msg = '"{}" not found in names.tax_names'.format(tax_name)
                raise ValueError(msg)

        s = select([names.c.tax_name, names.c.is_primary],
                   names.c.tax_id == tax_id)
        output = s.execute().fetchall()

        if not output:
            raise ValueError('"{}" not found in names.tax_id'.format(tax_id))

        return output
Example #12
0
    def _get_no_init( self ):
        if None is self._no_init and False == bool( self.indexing_suite ):
            #select all public constructors and exclude copy constructor
            cs = self.constructors( lambda c: not c.is_copy_constructor and c.access_type == 'public'
                                    , recursive=False, allow_empty=True )

            has_suitable_constructor = bool( cs )
            if cs and len(cs) == 1 and cs[0].is_trivial_constructor and self.find_noncopyable_vars():
                has_suitable_constructor = False

            has_nonpublic_destructor = declarations.has_destructor( self ) \
                                       and not declarations.has_public_destructor( self )

            trivial_constructor = self.find_trivial_constructor()

            if has_nonpublic_destructor \
               or ( self.is_abstract and not self.is_wrapper_needed() ) \
               or not has_suitable_constructor:
                self._no_init = True
            elif not trivial_constructor or trivial_constructor.access_type != 'public':
                exportable_cs = [c for c in cs if c.exportable and c.ignore == False]
                if not exportable_cs:
                    self._no_init = True
            else:
                pass
        if None is self._no_init:
            self._no_init = False
        return self._no_init
Example #13
0
    def get_columns(self, connection, table_name, schema=None, **kw):
        table_id = self.get_table_id(connection, table_name, schema,
                                     info_cache=kw.get("info_cache"))

        COLUMN_SQL = text("""
          SELECT col.name AS name,
                 t.name AS type,
                 (col.status & 8) AS nullable,
                 (col.status & 128) AS autoincrement,
                 com.text AS 'default',
                 col.prec AS precision,
                 col.scale AS scale,
                 col.length AS length
          FROM systypes t, syscolumns col LEFT OUTER JOIN syscomments com ON
              col.cdefault = com.id
          WHERE col.usertype = t.usertype
              AND col.id = :table_id
          ORDER BY col.colid
        """)

        results = connection.execute(COLUMN_SQL, table_id=table_id)

        columns = []
        for (name, type_, nullable, autoincrement, default, precision, scale,
             length) in results:
            col_info = self._get_column_info(name, type_, bool(nullable),
                             bool(autoincrement), default, precision, scale,
                             length)
            columns.append(col_info)

        return columns
Example #14
0
    def __init__(
            self,
            host=None,
            port=6379,
            unix_sock=None,
            database=0,
            password=None,
            encoding=None,
            conn_timeout=2,
            read_timeout=2,
            sentinel=False):

        if not bool(host) != bool(unix_sock):
            raise PyRedisError('Ether host or unix_sock has to be provided')
        self._closed = False
        self._conn_timeout = conn_timeout
        self._read_timeout = read_timeout
        self._encoding = encoding
        self._reader = None
        self._sentinel = sentinel
        self._writer = writer
        self._sock = None
        self.host = host
        self.port = port
        self.unix_sock = unix_sock
        self.password = password
        self.database = database
Example #15
0
def test_page(request):
    title = 'Pyramid Debugtoolbar'
    log.info(title)
    return {
        'title': title,
        'show_jinja2_link': bool(pyramid_jinja2),
        'show_sqla_link': bool(sqlalchemy)}
Example #16
0
 def __init__(self, announce, piece_length=262144, **kw):
     self.piece_length = piece_length
     if not bool(urlparse.urlparse(announce).scheme):
         raise ValueError('No schema present for url')
     self.tdict = {
         'announce': announce,
         'creation date': int(time()),
         'info': {
             'piece length': self.piece_length
         }
     }
     if kw.get('comment'):
         self.tdict.update({'comment': kw.get('comment')})
     if kw.get('httpseeds'):
         if not isinstance(kw.get('httpseeds'), list):
             raise TypeError('httpseeds must be a list')
         else:
             self.tdict.update({'httpseeds': kw.get('httpseeds')})
     if kw.get('announcelist'):
         if not isinstance(kw.get('announcelist'), list):
             raise TypeError('announcelist must be a list of lists')
         if False in [isinstance(l, list) for l in kw.get('announcelist')]:
             raise TypeError('announcelist must be a list of lists')
         if False in [bool(urlparse.urlparse(f[0]).scheme) for f in kw.get('announcelist')]:
             raise ValueError('No schema present for url')
         else:
             self.tdict.update({'announce-list': kw.get('announcelist')})
Example #17
0
 def _plugin_current_changed(self, current, previous):
     if current.isValid():
         actual_idx = self.proxy_model.mapToSource(current)
         display_plugin = self.model.display_plugins[actual_idx.row()]
         self.description.setText(display_plugin.description)
         self.forum_link = display_plugin.forum_link
         self.zip_url = display_plugin.zip_url
         self.forum_action.setEnabled(bool(self.forum_link))
         self.install_button.setEnabled(display_plugin.is_valid_to_install())
         self.install_action.setEnabled(self.install_button.isEnabled())
         self.uninstall_action.setEnabled(display_plugin.is_installed())
         self.history_action.setEnabled(display_plugin.has_changelog)
         self.configure_button.setEnabled(display_plugin.is_installed())
         self.configure_action.setEnabled(self.configure_button.isEnabled())
         self.toggle_enabled_action.setEnabled(display_plugin.is_installed())
         self.donate_enabled_action.setEnabled(bool(display_plugin.donation_link))
     else:
         self.description.setText('')
         self.forum_link = None
         self.zip_url = None
         self.forum_action.setEnabled(False)
         self.install_button.setEnabled(False)
         self.install_action.setEnabled(False)
         self.uninstall_action.setEnabled(False)
         self.history_action.setEnabled(False)
         self.configure_button.setEnabled(False)
         self.configure_action.setEnabled(False)
         self.toggle_enabled_action.setEnabled(False)
         self.donate_enabled_action.setEnabled(False)
     self.update_forum_label()
Example #18
0
    def setSaveOptionsPNG(self, optimize=None, palette=None, palette256=None):
        """ Optional arguments are added to self.png_options for pickup when saving.
        
            Palette argument is a URL relative to the configuration file,
            and it implies bits and optional transparency options.
        
            More information about options:
                http://effbot.org/imagingbook/format-png.htm
        """
        if optimize is not None:
            self.png_options['optimize'] = bool(optimize)
        
        if palette is not None:
            palette = urljoin(self.config.dirpath, palette)
            palette, bits, t_index = load_palette(palette)
            
            self.bitmap_palette, self.png_options['bits'] = palette, bits
            
            if t_index is not None:
                self.png_options['transparency'] = t_index

        if palette256 is not None:
            self.palette256 = bool(palette256)
        else:
            self.palette256 = None
Example #19
0
 def __init__(self,
         tx=False,  # safe assumption
         agc=True,  # show useless controls > hide functionality
         dc_cancel=True,  # ditto
         dc_offset=True,  # safe assumption
         tune_delay=DEFAULT_DELAY,
         e4000=False):
     """
     All values are booleans.
     
     tx: The device supports transmitting (osmosdr.sink).
     agc: The device has a hardware AGC (set_gain_mode works).
     dc_cancel: The device supports DC offset auto cancellation
         (set_dc_offset_mode auto works).
     dc_offset: The output has a DC offset and tuning should
         avoid the area around DC.
     e4000: The device is an RTL2832U + E4000 tuner and can be
         confused into tuning to 0 Hz.
     """
     
     # TODO: If the user specifies an OsmoSDRProfile without a full set of explicit args, derive the rest from the device string instead of using defaults.
     self.tx = bool(tx)
     self.agc = bool(agc)
     self.dc_cancel = bool(dc_cancel)
     self.dc_offset = bool(dc_offset)
     self.tune_delay = float(tune_delay)
     self.e4000 = bool(e4000)
Example #20
0
def _create_bootstrap(script_name, packages_to_install, paver_command_line,
                      install_paver=True, more_text="", dest_dir='.',
                      no_site_packages=None, system_site_packages=None,
                      unzip_setuptools=False, distribute=None, index_url=None,
                      find_links=None):
    # configure easy install template
    easy_install_options = []
    if index_url:
        easy_install_options.extend(["--index-url", index_url])
    if find_links:
        easy_install_options.extend(
            ["--find-links", " ".join(find_links)])
    easy_install_options = (
        easy_install_options
        and "'%s', " % "', '".join(easy_install_options) or '')
    confd_easy_install_tmpl = (_easy_install_tmpl %
                               ('bin_dir',  easy_install_options))
    if install_paver:
        paver_install = (confd_easy_install_tmpl %
                         ('paver==%s' % setup_meta['version']))
    else:
        paver_install = ""

    options = ""
    # if deprecated 'no_site_packages' was specified and 'system_site_packages'
    # wasn't, set it from that value
    if system_site_packages is None and no_site_packages is not None:
        system_site_packages = not no_site_packages
    if system_site_packages is not None:
        options += ("    options.system_site_packages = %s\n" %
                    bool(system_site_packages))
    if unzip_setuptools:
        options += "    options.unzip_setuptools = True\n"
    if distribute is not None:
        options += "    options.use_distribute = %s\n" % bool(distribute)
    options += "\n"

    extra_text = """def adjust_options(options, args):
    args[:] = ['%s']
%s
def after_install(options, home_dir):
    if sys.platform == 'win32':
        bin_dir = join(home_dir, 'Scripts')
    else:
        bin_dir = join(home_dir, 'bin')
%s""" % (dest_dir, options, paver_install)
    for package in packages_to_install:
        extra_text += confd_easy_install_tmpl % package
    if paver_command_line:
        command_list = list(paver_command_line.split())
        extra_text += "    subprocess.call([join(bin_dir, 'paver'),%s)" % repr(command_list)[1:]

    extra_text += more_text
    bootstrap_contents = venv.create_bootstrap_script(extra_text)
    fn = script_name

    debug("Bootstrap script extra text: " + extra_text)
    def write_script():
        open(fn, "w").write(bootstrap_contents)
    dry("Write bootstrap script %s" % fn, write_script)
    def __init__(self, isoform_filename, sam_filename, output_prefix,
                 min_aln_coverage, min_aln_identity, min_flnc_coverage,
                 max_fuzzy_junction, allow_extra_5exon, skip_5_exon_alt):
        """
        Parameters:
          isoform_filename -- input file containing isoforms, as fastq|fasta|contigset
          sam_filename -- input sam file produced by mapping fastq_filename to reference and sorted.
          #collapsed_isoform_filename -- file to output collapsed isoforms as fasta|fastq|contigset
          min_aln_coverage -- min coverage over reference to collapse a group of isoforms
          min_aln_identity -- min identity aligning to reference to collapse a group of isoforms
          min_flnc_coverage -- min supportive flnc reads to not ignore an isoform
                               Must be 1 when collapsing consensus isoforms, which is the case in production isoseq.
                               Can be >= 1 only when directly collapsing FLNC reads.
          max_fuzzy_junction -- max edit distance between fuzzy-matching exons
          allow_extra_5exon -- whether or not to allow shorter 5' exons
          skip_5_exon_alt -- whether or not to skip alternative 5' exons
        """
        self.suffix = parse_ds_filename(isoform_filename)[1]
        super(CollapseIsoformsRunner, self).__init__(prefix=output_prefix,
                                                     allow_extra_5exon=allow_extra_5exon)

        self.isoform_filename = isoform_filename # input, uncollapsed fa|fq|ds
        self.sam_filename = sam_filename # input, sorted, gmap sam
        #self.collapsed_isoform_filename = collapsed_isoform_filename # output, collapsed, fa|fq|ds

        self.min_aln_coverage = float(min_aln_coverage)
        self.min_aln_identity = float(min_aln_identity)
        self.min_flnc_coverage = int(min_flnc_coverage)
        self.max_fuzzy_junction = int(max_fuzzy_junction)
        self.allow_extra_5exon = bool(allow_extra_5exon)
        self.skip_5_exon_alt = bool(skip_5_exon_alt)
Example #22
0
def create_cookie(name, value, **kwargs):
    """Make a cookie from underspecified parameters.
    By default, the pair of `name` and `value` will be set for the domain ''
    and sent on every request (this is sometimes called a "supercookie").
    """
    result = dict(
        version=0,
        name=name,
        value=value,
        port=None,
        domain='',
        path='/',
        secure=False,
        expires=None,
        discard=True,
        comment=None,
        comment_url=None,
        rest={"HttpOnly": None},
        rfc2109=False,
    )
    if kwargs.get("path") in ("", "/,"):
        del kwargs["path"]
    badargs = set(kwargs) - set(result)
    if badargs:
        err = "create_cookie() got unexpected keyword arguments: %s"
        raise TypeError(err % list(badargs))
    result.update(kwargs)
    result["port_specified"] = bool(result["port"])
    result["domain_specified"] = bool(result["domain"])
    result["domain_initial_dot"] = result["domain"].startswith(".")
    result["path_specified"] = bool(result["path"])
    return Cookie(**result)
Example #23
0
    def add_package(self, login, package_name,
                    summary=None,
                    license=None,
                    public=True,
                    publish=True,
                    license_url=None,
                    attrs=None):
        '''
        Add a new package to a users account

        :param login: the login of the package owner
        :param package_name: the name of the package to be created
        :param package_type: A type identifyer for the package (eg. 'pypi' or 'conda', etc.)
        :param summary: A short summary about the package
        :param license: the name of the package license
        :param license_url: the url of the package license
        :param public: if true then the package will be hosted publicly
        :param attrs: A dictionary of extra attributes for this package
        :param host_publicly: TODO: describe
        '''
        url = '%s/package/%s/%s' % (self.domain, login, package_name)

        attrs = attrs or {}
        attrs['summary'] = summary
        attrs['license'] = {'name':license, 'url':license_url}

        payload = dict(public=bool(public),
                       publish=bool(publish),
                       public_attrs=dict(attrs or {})
                       )

        data = jencode(payload)
        res = self.session.post(url, verify=True, data=data)
        self._check_response(res)
        return res.json()
Example #24
0
    def __init__(self, PERMISSIVE=True, get_header=False,
                 structure_builder=None, QUIET=False):
        """Create a PDBParser object.

        The PDB parser call a number of standard methods in an aggregated
        StructureBuilder object. Normally this object is instanciated by the
        PDBParser object itself, but if the user provides his/her own
        StructureBuilder object, the latter is used instead.

        Arguments:
         - PERMISSIVE - Evaluated as a Boolean. If false, exceptions in
           constructing the SMCRA data structure are fatal. If true (DEFAULT),
           the exceptions are caught, but some residues or atoms will be missing.
           THESE EXCEPTIONS ARE DUE TO PROBLEMS IN THE PDB FILE!.
         - structure_builder - an optional user implemented StructureBuilder class.
         - QUIET - Evaluated as a Boolean. If true, warnings issued in constructing
           the SMCRA data will be suppressed. If false (DEFAULT), they will be shown.
           These warnings might be indicative of problems in the PDB file!
        """
        if structure_builder is not None:
            self.structure_builder = structure_builder
        else:
            self.structure_builder = StructureBuilder()
        self.header = None
        self.trailer = None
        self.line_counter = 0
        self.PERMISSIVE = bool(PERMISSIVE)
        self.QUIET = bool(QUIET)
Example #25
0
def _check_function(function, flag, run_args, data):
    object_name, function_name = _split_function_name(function)
    if not function_name:
        return None

    # Make sure function is present in either libvirt module or
    # object_name class
    flag_tuple = ()

    if not _has_command(function_name, objname=object_name):
        return False

    if flag:
        found_flag = _get_flag(flag)
        if not bool(found_flag):
            return False
        flag_tuple = (found_flag,)

    if run_args is None:
        return None

    # If function requires an object, make sure the passed obj
    # is of the correct type
    if object_name:
        classobj = _get_command(object_name)
        if not isinstance(data, classobj):
            raise ValueError(
                "Passed obj %s with args must be of type %s, was %s" %
                (data, str(classobj), type(data)))

    cmd = _get_command(function_name, obj=data)

    # Function with args specified is all the proof we need
    return _try_command(cmd, run_args + flag_tuple,
                        check_all_error=bool(flag_tuple))
Example #26
0
    def _check_for_list(self, location):
        # Standard LatLng list or tuple with 2 number values
        if len(location) == 2:
            lat = self._convert_float(location[0])
            lng = self._convert_float(location[1])
            condition_1 = isinstance(lat, float)
            condition_2 = isinstance(lng, float)

            # Check if input are Floats
            if bool(condition_1 and condition_2):
                condition_3 = lat <= 90 and lat >= -90
                condition_4 = lng <= 180 and lng >= -180

                # Check if inputs are within the World Geographical
                # boundary (90,180,-90,-180)
                if bool(condition_3 and condition_4):
                    self.lat = lat
                    self.lng = lng
                    return self.lat, self.lng
                else:
                    print("[ERROR] Coords are not within the world's geographical boundary\n"
                          'Latitudes must be within -90 to 90 degrees\n'
                          'Longitude must be within -180 to 180 degrees')
                    sys.exit()
            else:
                print("[ERROR] Coordinates must be numbers.\n"
                      '>>> g = geocoder.location("Ottawa ON")\n'
                      '>>> g = geocoder.location([45.23, -75.12])\n'
                      '>>> g = geocoder.location("45.23, -75.12")\n'
                      '>>> g = geocoder.location({"lat": 45.23, "lng": -75.12})')
                sys.exit()
Example #27
0
def make_client(conf):
    """Creates a kazoo client given a configuration dictionary."""
    # See: http://kazoo.readthedocs.org/en/latest/api/client.html
    client_kwargs = {
        'read_only': bool(conf.get('read_only')),
        'randomize_hosts': bool(conf.get('randomize_hosts')),
    }
    # See: http://kazoo.readthedocs.org/en/latest/api/retry.html
    if 'command_retry' in conf:
        client_kwargs['command_retry'] = conf['command_retry']
    if 'connection_retry' in conf:
        client_kwargs['connection_retry'] = conf['connection_retry']
    hosts = _parse_hosts(conf.get("hosts", "localhost:2181"))
    if not hosts or not isinstance(hosts, six.string_types):
        raise TypeError("Invalid hosts format, expected "
                        "non-empty string/list, not %s" % type(hosts))
    client_kwargs['hosts'] = hosts
    if 'timeout' in conf:
        client_kwargs['timeout'] = float(conf['timeout'])
    # Kazoo supports various handlers, gevent, threading, eventlet...
    # allow the user of this client object to optionally specify one to be
    # used.
    if 'handler' in conf:
        client_kwargs['handler'] = conf['handler']
    return client.KazooClient(**client_kwargs)
Example #28
0
def mark_provider_template(api, provider, template, tested=None, usable=None,
        diagnosis='', build_number=None, stream=None):
    """Mark a provider template as tested and/or usable

    Args:
        api: The trackerbot API to act on
        provider: The provider's key in cfme_data or a :py:class:`Provider` instance
        template: The name of the template to mark on this provider or a :py:class:`Template`
        tested: Whether or not this template has been tested on this provider
        usable: Whether or not this template is usable on this provider
        diagnosis: Optional reason for marking a template

    Returns the response of the API request

    """
    provider_template = _as_providertemplate(provider, template, group=stream)

    if tested is not None:
        provider_template['tested'] = bool(tested)

    if usable is not None:
        provider_template['usable'] = bool(usable)

    if diagnosis:
        provider_template['diagnosis'] = diagnosis

    if build_number:
        provider_template['build_number'] = int(build_number)

    return api.providertemplate.post(provider_template)
Example #29
0
    def get_category(resource_type, name):
        # this will return one of the following:
        # 'Version', 'Shared', 'Routing' or 'None'

        versioned = [
            'OS::Nova::Server',
            'OS::Neutron::Port'
        ]
        shared = [
            'OS::Heat::RandomString',
            'OS::Neutron::Net',
            'OS::Neutron::Subnet',
            'OS::Neutron::SecurityGroup',
            'OS::Neutron::Router',
            'OS::Neutron::RouterInterface',
            'OS::Neutron::Port',
            'OS::Nova::Server'
        ]
        routing = [
            'OS::Neutron::FloatingIP'
        ]

        if resource_type in versioned:
            if bool(versionRe.search(name)):
                return 'Version'
        if resource_type in shared:
            if bool(sharedRe.search(name)):
                return 'Shared'
        if resource_type in routing:
            if not bool(versionRe.search(name)) and not bool(sharedRe.search(name)):
                return 'Routing'
        return 'None'
Example #30
0
 def generateExits(self, position):
     newRooms=[-1,-1,-1,-1]
     for i in range(4):
         if bool(random.randint(0,1)):
             if i==0:#north
                 newRooms[i]=(position[0],position[1]-1)
             elif i==1:#east
                 newRooms[i]=(position[0]+1,position[1])
             elif i==2:#south
                 newRooms[i]=(position[0],position[1]+1)
             elif i==3:#west
                 newRooms[i]=(position[0]-1,position[1])
     #time to check the new rooms to make sure that they are in range etc
     for i in range(3,-1,-1):
         if newRooms[i]!=-1:
             x=newRooms[i][0]
             y=newRooms[i][1]
             if x>=self.SIZE or x<0:
                 newRooms[i]=-1
                 continue
             if y>=self.SIZE or y<0:
                 newRooms[i]=-1
                 continue
             #now check to see if this room butts up against anything existing room
             if self.levelGrid[x][y]!=-1:
                 #lets see if we want to connect them
                 if not bool(random.randint(0,1)):
                     newRooms[i]=-1
                     continue
     #print(newRooms)
     return newRooms