예제 #1
0
def handle_form():
    """Handles input from user."""

    # Get values from form.
    departure_day = request.form.get("departure-day")
    departure_time = request.form.get("departure-time")
    directions_result = dictify(request.form.get("data"))

    result = make_result(directions_result, departure_time, departure_day)

    return jsonify(result)
예제 #2
0
def load_scans_2(folder):
    slices = list()
    dicom_files = glob.glob(folder + '/**/*', recursive=True)
    for dicom_file in dicom_files:
        meta_data_dicom = pydicom.dcmread(dicom_file)
        ds = dictify(meta_data_dicom)
        modality = ds['Modality']
        if modality == 'CT':
            slices.append(meta_data_dicom)
    slices.sort(key=lambda x: float(x.ImagePositionPatient[2]))
    return slices
예제 #3
0
def process_2(study_instance_id, ct_instances):
    rets_list = list()
    for ct_instance in ct_instances:
        meta_data_dicom = pydicom.dcmread(ct_instance)
        ds = dictify(meta_data_dicom)
        modality = ds['Modality']
        if modality == 'CT':
            ret = worker((study_instance_id, ct_instance, len(ct_instances)))
            if ret[0] is None:
                continue
            else:
                rets_list.append(ret)
    return rets_list
예제 #4
0
파일: user.py 프로젝트: Inna-r/dbs-back
def clean_user(user_obj):

    # some old users might not have a hash, saving will generate one
    if not user_obj.hash:
        user_obj.save()

    user_dict = dictify(user_obj)
    ret = {}
    for key in SAFE_KEYS:
        ret[key] = user_dict.get(key, None)
    ret.update(get_mjs(user_obj))

    return ret
예제 #5
0
def omdb_api_request(*args, **kwargs):
    """ Request from OMDb API and store in cache for 14 days"""
    request = OMDB_API
    request = '{0}{1}{2}&r=xml'.format(request, _omdb_apikey, OMDB_ARG)
    for key, value in kwargs.items():
        if value:  # Don't add empty kwargs
            request = '{0}&{1}={2}'.format(request, key, value)
    request = make_request(request, False)
    if request:
        request = ET.fromstring(request.content)
        request = utils.dictify(request)
    if request and request.get(
            'root') and not request.get('root').get('response') == 'False':
        request = request.get('root').get('movie')[0]
    else:
        request = {}
    return request
예제 #6
0
def get_organised_data(spreadsheet=private.spreadsheet):
    """
    Test spreadsheet publically available at foo maybe
    >>> gspread_test = 'gspread test'
    >>> data = get_organised_data(gspread_test)
    >>> testdata = {}
    >>> testdata = {'Blargh!': 6.6, 'Foo': 1, 'Bar': 5.6, 'Email': '*****@*****.**'}
    >>> data["*****@*****.**"] == testdata
    True

    """
    try:
        from Fit1038_Marking_2012 import data
    except ImportError:
        gc = gspread.login(private.username, private.password)
        wks = gc.open(spreadsheet).sheet1
        data = wks.get_all_values()

    return dictify(data)
예제 #7
0
def load_scans(sid):
    src_path = os.path.dirname(os.path.abspath(__file__))
    ct_dir = src_path + '/../studies/' + str(sid) + '/'
    files = glob.glob(ct_dir + '/**/*', recursive=True)
    instance_files = [file for file in files if isfile(file)]
    ct_instance_files = get_instance_files(instance_files)

    if len(ct_instance_files) == 0:
        print('error: No valid CT instances found !!')
        exit(-1)

    slices = list()
    for ct_instance_file in ct_instance_files:
        meta_data_dicom = pydicom.dcmread(ct_instance_file)
        ds = dictify(meta_data_dicom)
        modality = ds['Modality']
        if modality == 'CT':
            slices.append(meta_data_dicom)
    slices.sort(key=lambda x: float(x.ImagePositionPatient[2]))
    return slices
예제 #8
0
def handle_recs():
    """Handles request for recommendation."""

    # Get values from form.
    minutes_before = int(request.form.get("before"))
    minutes_after = int(request.form.get("after"))
    data = dictify(request.form.get("data"))

    # Check that user is logged in.
    user_id = session.get("user_id")

    if user_id:
        # If they're logged in, pass in their sensitivity rating.
        sensitivity = User.get_sensitivity_by_id(user_id)
        result = make_recommendation(data, minutes_before, minutes_after, sensitivity)

    else:
        result = make_recommendation(data, minutes_before, minutes_after)

    return jsonify(result)
예제 #9
0
def process(study_instance_id, ct_instances):
    inps = list()
    for ct_instance in ct_instances:
        meta_data_dicom = pydicom.dcmread(ct_instance)
        ds = dictify(meta_data_dicom)
        modality = ds['Modality']
        if modality == 'CT':
            inps.append((study_instance_id, ct_instance, len(ct_instances)))
    if len(inps) == 0:
        print("DICOM is most probably not a CT zip.")
        return []
    max_processes = 10
    print("Processes count = " + str(max_processes))
    with concurrent.futures.ProcessPoolExecutor(
            max_workers=max_processes) as executor:
        rets = executor.map(worker, inps)
        rets_list = list()
        for ret in rets:
            if ret[0] is None:
                continue
            else:
                rets_list.append(ret)
        return rets_list
예제 #10
0
def stats():
    req = http.request(
        'GET', 'https://www.goodreads.com/user/show/{}.xml?key={}'.format(
            app.config['GOODREADS_USERID'], app.config['GOODREADS_KEY']))
    r = dictify(ET.fromstring(req.data))
    user = r['GoodreadsResponse']['user'][0]
    friends_count = int(user['friends_count'][0]['_text'])
    reviews_count = int(user['reviews_count'][0]['_text'])
    fav_genres = user['favorite_books'][0]['_text'].split(', ')
    shelves = user['user_shelves'][0]['user_shelf']
    shelf_info = {
        shelf['name'][0]['_text']: int(shelf['book_count'][0]['_text'])
        for shelf in shelves}
    stats = {
        'friendsCount': friends_count,
        'reviewsCount': reviews_count,
        'books': {
            'numberShelves': len(shelves),
            'shelves': shelf_info,
        },
        'favoriteGenres': fav_genres,
    }
    return json.dumps(stats)
예제 #11
0
def stats():
    req = http.request(
        'GET', 'https://www.goodreads.com/user/show/{}.xml?key={}'.format(
            app.config['GOODREADS_USERID'], app.config['GOODREADS_KEY']))
    r = dictify(ET.fromstring(req.data))
    user = r['GoodreadsResponse']['user'][0]
    friends_count = int(user['friends_count'][0]['_text'])
    reviews_count = int(user['reviews_count'][0]['_text'])
    fav_genres = user['favorite_books'][0]['_text'].split(', ')
    shelves = user['user_shelves'][0]['user_shelf']
    shelf_info = {
        shelf['name'][0]['_text']: int(shelf['book_count'][0]['_text'])
        for shelf in shelves
    }
    stats = {
        'friendsCount': friends_count,
        'reviewsCount': reviews_count,
        'books': {
            'numberShelves': len(shelves),
            'shelves': shelf_info,
        },
        'favoriteGenres': fav_genres,
    }
    return json.dumps(stats)
예제 #12
0
def index(month=None, year=None):
    ''' Displays calendars and lists of open/recently closed tickets '''
    stylesheet = session.get('css', 'light')
    other_ssheet = other_colour(stylesheet)
    # prepare search string, with today as default
    today = datetime.date.today()
    basedate = datetime.date.today()
    replace_dict = {'day': 1}
    if month is not None:
        replace_dict['month'] = month
    if year is not None:
        replace_dict['year'] = year
    try:
        basedate = basedate.replace(**replace_dict)
    except ValueError:
        #TODO: prettify 404, add info
        abort(404)
    if today.month == basedate.month and today.year == basedate.year:
        today_day = today.day
    else:
        today_day = None
    del replace_dict
    monthstr = basedate.strftime(DATEFORMAT.replace("%d", "%%"))

    # determine next month/year if they are somewhat special
    next_month = basedate.month + 1
    prev_month = basedate.month - 1
    next_year, prev_year = (basedate.year, ) * 2

    if basedate.month == 12:
        next_month = 1
        next_year = basedate.year + 1
    elif basedate.month == 1:
        prev_month = 12
        prev_year = basedate.year - 1

    # calculate timestamp boundaries of the month
    clsd_after = calendar.timegm((basedate.year, basedate.month, 1) +
                                 (0, ) * 3) * (10**6)
    clsd_before = calendar.timegm((next_year or basedate.year, next_month, 1) +
                                  (0, ) * 3) * (10**6)

    month_data, month_data_raw, opened, closed = ({}, ) * 4
    for trac in TRACS:
        ## query Trac databases
        # for month data
        cur = trac['conn'].cursor(cursor_factory=DictCursor)
        cur.execute(QUERY_MONTH, (monthstr, ))
        month_data_raw = dictify(cur.fetchall(),
                                 'owner',
                                 dict2up=month_data_raw,
                                 add_data={
                                     'trac': trac['name'],
                                     'base_url': trac['base_url']
                                 })
        # query for due_date'less tickets closed on this month
        cur.execute(QUERY_UNSET_DATE, (clsd_after, clsd_before))
        for tckt in cur.fetchall():
            # add ticket to corresponding list of owner's tickets
            owner = tckt['owner']
            # convert timestamp-like ticket.time to `due_date`
            due_date = datetime.date.fromtimestamp(tckt['closed_at'] //
                                                   (10**6))
            due_date = due_date.strftime(DATEFORMAT)
            user_tckt_list = month_data_raw.get(owner, [])
            user_tckt_list.append({
                'id': tckt['id'],
                'due_date': due_date,
                'summary': tckt['summary'],
                'time': tckt['time'],
                'reporter': tckt['reporter'],
                'status': 'closed',
                'trac': trac['name'],
                'base_url': trac['base_url']
            })
            month_data_raw['owner'] = user_tckt_list

        # don't query for opened/closed tickets for non-current month
        if today_day is None:
            continue

        # for open tickets
        cur.execute(QUERY_OPEN)
        opened = dictify(cur.fetchall(),
                         'owner',
                         dict2up=opened,
                         add_data={
                             'trac': trac['name'],
                             'base_url': trac['base_url']
                         })
        # for recently closed tickets
        # (7 * 24 * 60 * 60) = 604800
        week_ago = (time.time() - 604800) * (10**6)
        cur.execute(QUERY_CLSD_WEEK, (week_ago, ))
        closed = dictify(cur.fetchall(),
                         'owner',
                         dict2up=closed,
                         add_data={
                             'trac': trac['name'],
                             'base_url': trac['base_url']
                         })

    # total dictification of month data
    for user, tickets in month_data_raw.items():
        for ticket in tickets:
            ##TODO: do it within utils.dictify (pass function in add_data)
            ticket['title'] = get_tckt_title(ticket)
        month_data[user] = dictify(tickets, 'due_date')
        for due_date in month_data[user].keys():
            tickets = month_data[user].pop(due_date)
            month_data[user][due_date] = dictify(tickets, 'trac')

    # don't query for opened/closed tickets for non-current month
    # TODO: too much indentation
    if today_day is not None:
        # a wee bit of simple dictification for opened tickets
        for user, tickets in opened.items():
            for ticket in tickets:
                ##TODO: do it within utils.dictify (pass function in add_data)
                if not ticket['first_due_date']:
                    continue
                first_due_date = time.strptime(ticket['first_due_date'],
                                               DATEFORMAT)
                first_due_date = datetime.date(first_due_date.tm_year,
                                               first_due_date.tm_mon,
                                               first_due_date.tm_mday)
                delay = today - first_due_date
                if delay.days > 0:
                    ticket['delayed_by'] = str(delay.days)
                else:
                    ticket['delayed_by'] = ''
            opened[user] = dictify(tickets, 'trac')

        # ...and for closed ones
        for user, tickets in closed.items():
            closed[user] = dictify(tickets, 'trac')

    # create calendars
    calendar.setfirstweekday(calendar.MONDAY)
    month, year = (basedate.month, basedate.year)
    week_cal = calendar.monthcalendar(year, month)
    # keep HTML classes for calendar cells
    day_classes = {}
    # 5th and 6th elements are holidays, zeroes should be dropped
    for holiday in filter(None,
                          itertools.chain(*[week[5:] for week in week_cal])):
        day_classes[holiday] = ['holiday']
    # today has its special HTML class
    if today_day:
        day_classes.setdefault(today_day, []).append('today')

    context = {
        'devs': DEVLIST,
        'devlist': DEVS,
        'month_data': month_data,
        'next_month': next_month,
        'next_year': next_year if next_year != today.year else "",
        'prev_month': prev_month,
        'prev_year': prev_year if prev_year != today.year else "",
        'calendar': week_cal,
        'weekhdr': calendar.weekheader(3).split(' '),
        'stylesheet': stylesheet,
        'other_ssheet': other_ssheet,
        'daytmpl': monthstr.replace('%', '%02d'),
        'month_name': calendar.month_name[month],
        'month': month,
        'year': year if year != today.year else "",
        'day_classes': concatenate_dict(day_classes),
        'opened': opened,
        'closed': closed,
    }
    return render_template('index.html', **context)