Translate the list of turbulance or icing into a readable sentence

    Ex: Occasional moderate turbulence in clouds from 3000ft to 14000ft
166926
def turb_ice(turbice: [str], unit: str = 'ft') -> str:  # type: ignore
    
    if not turbice:
        return ''
    # Determine turbulance or icing
    if turbice[0][0] == '5':
        conditions = TURBULANCE_CONDITIONS
    elif turbice[0][0] == '6':
        conditions = ICING_CONDITIONS
    else:
        return ''
    # Create list of split items (type, floor, height)
    split = []
    for item in turbice:
        if len(item) == 6:
            split.append([item[1:2], item[2:5], item[5]])
    # Combine items that cover a layer greater than 9000ft
    for i in reversed(range(len(split) - 1)):
        if split[i][2] == '9' and split[i][0] == split[i + 1][0] \
                and int(split[i + 1][1]) == (int(split[i][1]) + int(split[i][2]) * 10):
            split[i][2] = str(int(split[i][2]) + int(split[i + 1][2]))
            split.pop(i + 1)
    # Return joined, formatted string from split items
    return ', '.join(['{conditions} from {low_alt}{unit} to {high_alt}{unit}'.format(
        conditions=conditions[item[0]], low_alt=int(item[1]) * 100,
        high_alt=int(item[1]) * 100 + int(item[2]) * 1000, unit=unit) for item in split])
59193
def cmd(send, *_):
    
    words = [[verb, noun, abbrev, noun, adj, abbrev, noun], [verb, adj, abbrev, noun], [verb, abbrev, noun, verb, adj, noun],
             [verb, noun, ingverb, adj, abbrev, noun], [adj, abbrev, noun, verb, adj, noun], [abbrev, noun, verb, adj, noun, verb, abbrev, noun],
             [ingverb, noun, verb, adj, abbrev, noun], [verb, adj, abbrev, noun, verb, abbrev, noun]]
    msgtype = [
        "If we %s the %s, we can get to the %s %s through the %s %s %s!" % tuple(map(choice, words[0])),
        "We need to %s the %s %s %s!" % tuple(map(choice, words[1])),
        "Try to %s the %s %s, maybe it will %s the %s %s!" % tuple(map(choice, words[2])),
        "You can't %s the %s without %s the %s %s %s!" % tuple(map(choice, words[3])),
        "Use the %s %s %s, then you can %s the %s %s!" % tuple(map(choice, words[4])),
        "The %s %s is down, %s the %s %s so we can %s the %s %s!" % tuple(map(choice, words[5])),
        "%s the %s won't do anything, we need to %s the %s %s %s!" % tuple(map(choice, words[6])),
        "I'll %s the %s %s %s, that should %s the %s %s!" % tuple(map(choice, words[7]))
    ]

    send(choice(msgtype))
454117
def _forecast_transform(f_d):
    """"""
    begins = f_d.get('localTimestamp', None)
    issued = f_d.get('issueTimestamp', None)
    solid_stars = f_d.get('solidRating', None)
    faded_stars = f_d.get('fadedRating', None)
    air_pressure = f_d.get('condition_pressure', None)
    unit_pressure = f_d.get('condition_unitPressure', None)
    air_temp = f_d.get('condition_temperature', None)
    unit_temp = f_d.get('condition_unit', None)
    max = f_d.get('swell_maxBreakingHeight', None)
    abs_max = f_d.get('swell_absMaxBreakingHeight', None)
    min = f_d.get('swell_minBreakingHeight', None)
    abs_min = f_d.get('swell_absMinBreakingHeight', None)
    swell_dir = f_d.get('swell_components_combined_compassDirection', None)
    swell_unit = f_d.get('swell_unit', None)
    probability = f_d.get('swell_probability', None)
    period = f_d.get('swell_components_combined_period', None)
    wind_chill = f_d.get('wind_chill', None)
    wind_gusts = f_d.get('wind_gusts', None)
    wind_direction = f_d.get('wind_compassDirection', None)
    wind_degrees = f_d.get('wind_direction', None)
    wind_speed = f_d.get('wind_speed', None)
    wind_unit = f_d.get('wind_unit', None)

    return {
            'air_pressure': "{}{}".format(air_pressure, unit_pressure),
            'air_temp': "{}° {}".format(air_temp, unit_temp),
            'stars': "{} solid, {} faded".format(solid_stars, faded_stars),
            'begins': dt.utcfromtimestamp(begins).strftime("%a %-I %p"),
            'issued': dt.utcfromtimestamp(issued).strftime("%a %-I %p"),
            'max_breaking_height': "{} {}".format(max, swell_unit),
            'min_breaking_height': "{} {}".format(min, swell_unit),
            'probability': "{}%".format(probability),
            'swell_direction': "{}".format(swell_dir),
            'swell_period': "{} seconds".format(period),
            'wind_chill': "{}°".format(wind_chill),
            'wind_direction': "{}° {}".format(wind_degrees, wind_direction),
            'wind_gusts': "{} {}".format(wind_gusts, wind_unit),
            'wind_speed': "{} {}".format(wind_speed, wind_unit),
            }
346827
def from_sky(cls, distancelimit=15, magnitudelimit=18):
        '''
        

        '''

        # define a query for cone search surrounding this center
        criteria = []
        if distancelimit is not None:
            criteria.append('parallax >= {}'.format(1000.0/distancelimit))
        if magnitudelimit is not None:
            criteria.append('phot_g_mean_mag <= {}'.format(magnitudelimit))

        allskyquery = """{} WHERE {}""".format(cls.basequery, ' and '.join(criteria))
        print(allskyquery)

        # run the query
        print('querying Gaia DR2, for distance<{} and G<{}'.format(distancelimit, magnitudelimit))
        table = query(allskyquery)

        # store the search parameters in this object
        c = cls(cls.standardize_table(table))

        c.standardized.meta['query'] = allskyquery
        c.standardized.meta['magnitudelimit'] = magnitudelimit
        c.standardized.meta['distancelimit'] = distancelimit

        #c.distancelimit = distancelimit
        #c.magnitudelimit = magnitudelimit or c.magnitudelimit
        return c
120428
def condense(ss_unescaped):
    
    def estimated_len(longg, short):
        return (3
                + len(short)
                + sum(map(len, longg))
                - len(longg)
                * (len(short) - 1)
                - 1 )

    def stupid_len(longg):
        return sum(map(len, longg)) + len(longg)

    ss = [re.escape(s) for s in set(ss_unescaped)]
    ss.sort(key=len)

    short2long = defaultdict(lambda: {'p':[],'s':[]})

    for short, longg in combinations(ss, 2):
        if longg.startswith(short):
            short2long[short]['p'].append(longg)
        if longg.endswith(short):
            short2long[short]['s'].append(longg)

    short2long = sorted(list(short2long.items()),
                        key=lambda x: len(x[0]),
                        reverse=True)

    output = []
    objs = set(ss)

    for s, pre_sur in short2long:
        pp = set(pre_sur['p']) & objs
        ss = set(pre_sur['s']) & objs
        if ((stupid_len(pp) - estimated_len(pp, s))
            < (stupid_len(ss) - estimated_len(ss, s))):
            reg = (r'({heads})?{surfix}'
                    .format(surfix=s,
                           heads='|'.join(sorted([p[:-len(s)] for p in ss],
                           key=len,
                           reverse=True))))
            assert len(reg) == estimated_len(ss, s)
            output.append(reg)
            objs -= (ss | set([s]))
        elif ((stupid_len(pp) - estimated_len(pp, s))
            > (stupid_len(ss) - estimated_len(ss, s))):
            reg = (r'{prefix}({tails})?'
                .format(prefix=s,
                        tails='|'.join(sorted([p[len(s):] for p in pp],
                        key=len,
                        reverse=True))))
            assert len(reg) == estimated_len(pp, s)
            output.append(reg)
            objs -= (pp | set([s]))

    for residual in objs:
        output.append(residual)
    return re.sub(r'\(([^)])\)\?', r'\1?', r'|'.join(output))
42230
def _parse_supl(content):
        
        col_names = ['year', 'month', 'day', 'hour', 'minute',
                     'hourly_low_pressure', 'hourly_low_pressure_time',
                     'hourly_high_wind', 'hourly_high_wind_direction',
                     'hourly_high_wind_time']

        col_units = {'hourly_low_pressure': 'hPa',
                     'hourly_low_pressure_time': None,
                     'hourly_high_wind': 'meters/second',
                     'hourly_high_wind_direction': 'degrees',
                     'hourly_high_wind_time': None,
                     'time': None}

        df = pd.read_table(StringIO(content), comment='#', na_values='MM',
                           names=col_names, sep=r'\s+')

        df['time'] = pd.to_datetime(df[['year', 'month', 'day', 'hour', 'minute']], utc=True)

        df['hours'] = np.floor(df['hourly_low_pressure_time'] / 100)
        df['minutes'] = df['hourly_low_pressure_time'] - df['hours'] * 100
        df['hours'] = df['hours'].replace(99, np.nan)
        df['minutes'] = df['minutes'].replace(99, np.nan)
        df['hourly_low_pressure_time'] = pd.to_datetime(df[['year', 'month', 'day', 'hours',
                                                            'minutes']], utc=True)

        df['hours'] = np.floor(df['hourly_high_wind_time'] / 100)
        df['minutes'] = df['hourly_high_wind_time'] - df['hours'] * 100
        df['hours'] = df['hours'].replace(99, np.nan)
        df['minutes'] = df['minutes'].replace(99, np.nan)
        df['hourly_high_wind_time'] = pd.to_datetime(df[['year', 'month', 'day',
                                                         'hours', 'minutes']], utc=True)
        df = df.drop(columns=['year', 'month', 'day', 'hour', 'minute', 'hours', 'minutes'])
        df.units = col_units
        return df
902822
def foreach_sentence(layer, drop_factor=1.0):
    """"""

    def sentence_fwd(docs, drop=0.0):
        sents = []
        lengths = []
        for doc in docs:
            doc_sents = [sent for sent in doc.sents if len(sent)]
            subset = [
                s for s in doc_sents if numpy.random.random() >= drop * drop_factor
            ]
            if subset:
                sents.extend(subset)
                lengths.append(len(subset))
            else:
                numpy.random.shuffle(doc_sents)
                sents.append(doc_sents[0])
                lengths.append(1)
        flat, bp_flat = layer.begin_update(sents, drop=0.0)
        output = layer.ops.unflatten(flat, lengths)

        def sentence_bwd(d_output, sgd=None):
            d_flat = layer.ops.flatten(d_output)
            d_sents = bp_flat(d_flat, sgd=sgd)
            if d_sents is None:
                return d_sents
            else:
                return layer.ops.unflatten(d_sents, lengths)

        return output, sentence_bwd

    model = wrap(sentence_fwd, layer)
    return model
972089
def items(cls):
        
        return [
            cls.TEMPERATURE,
            cls.PRESSURE,
            cls.HUMIDITY,
            cls.WIND_SPEED,
            cls.WIND_DIRECTION,
            cls.CLOUDS
        ]
488660
def pretty(self,verbose=0):
        """"""
        # split prompt lines and add blanks in later lines to align them
        plines = self.prompt.split('\n')
        for i in range(len(plines)-1): plines[i+1] = 32*' ' + plines[i+1]
        plines = '\n'.join(plines)
        namelen = min(len(self.name), 12)
        pvalue = self.get(prompt=0,lpar=1)
        alwaysquoted = ['s', 'f', '*gcur', '*imcur', '*ukey', 'pset']
        if self.type in alwaysquoted and self.value is not None: pvalue = '"' + pvalue + '"'
        if self.mode == "h":
            s = "%13s = %-15s %s" % ("("+self.name[:namelen],
                                    pvalue+")", plines)
        else:
            s = "%13s = %-15s %s" % (self.name[:namelen],
                                    pvalue, plines)
        if not verbose: return s

        if self.choice is not None:
            s = s + "\n" + 32*" " + "|"
            nline = 33
            for i in range(len(self.choice)):
                sch = str(self.choice[i]) + "|"
                s = s + sch
                nline = nline + len(sch) + 1
                if nline > 80:
                    s = s + "\n" + 32*" " + "|"
                    nline = 33
        elif self.min not in [None, INDEF] or self.max not in [None, INDEF]:
            s = s + "\n" + 32*" "
            if self.min not in [None, INDEF]:
                s = s + str(self.min) + " <= "
            s = s + self.name
            if self.max not in [None, INDEF]:
                s = s + " <= " + str(self.max)
        return s
917001
def _clean_body_df(self, df):
        """"""
        if self.suffix == '-drvd.txt':
            df = df.dropna(subset=('temperature', 'reported_relative_humidity',
                           'u_wind', 'v_wind'), how='all').reset_index(drop=True)

            df.units = {'pressure': 'hPa',
                        'reported_height': 'meter',
                        'calculated_height': 'meter',
                        'temperature': 'Kelvin',
                        'temperature_gradient': 'Kelvin / kilometer',
                        'potential_temperature': 'Kelvin',
                        'potential_temperature_gradient': 'Kelvin / kilometer',
                        'virtual_temperature': 'Kelvin',
                        'virtual_potential_temperature': 'Kelvin',
                        'vapor_pressure': 'Pascal',
                        'saturation_vapor_pressure': 'Pascal',
                        'reported_relative_humidity': 'percent',
                        'calculated_relative_humidity': 'percent',
                        'u_wind': 'meter / second',
                        'u_wind_gradient': '(meter / second) / kilometer)',
                        'v_wind': 'meter / second',
                        'v_wind_gradient': '(meter / second) / kilometer)',
                        'refractive_index': 'unitless'}

        else:
            df['u_wind'], df['v_wind'] = get_wind_components(df['speed'],
                                                             np.deg2rad(df['direction']))
            df['u_wind'] = np.round(df['u_wind'], 1)
            df['v_wind'] = np.round(df['v_wind'], 1)

            df = df.dropna(subset=('temperature', 'direction', 'speed',
                           'dewpoint_depression', 'u_wind', 'v_wind'),
                           how='all').reset_index(drop=True)

            df['dewpoint'] = df['temperature'] - df['dewpoint_depression']

            df.drop('dewpoint_depression', axis=1, inplace=True)

            df.units = {'etime': 'second',
                        'pressure': 'hPa',
                        'height': 'meter',
                        'temperature': 'degC',
                        'dewpoint': 'degC',
                        'direction': 'degrees',
                        'speed': 'meter / second',
                        'u_wind': 'meter / second',
                        'v_wind': 'meter / second'}

        return df
1009132
def simple_atmo_opstring(haze, contrast, bias):
    """"""
    gamma_b = 1 - haze
    gamma_g = 1 - (haze / 3.0)
    ops = (
        "gamma g {gamma_g}, " "gamma b {gamma_b}, " "sigmoidal rgb {contrast} {bias}"
    ).format(gamma_g=gamma_g, gamma_b=gamma_b, contrast=contrast, bias=bias)
    return ops
189791
def cloud_base(temp, hum):
    
    if temp is None or hum is None:
        return None
    dew_pt = dew_point(temp, hum)
    spread = float(temp) - dew_pt
    return spread * 125.0
839203
def better_sentences(func):
    """"""

    @wraps(func)
    def wrapped(*args):

            sentences = func(*args)
            new_sentences = []
            for i, l in enumerate(sentences):
                if '\n\n' in l:
                    splits = l.split('\n\n')
                    if len(splits)>1:
                        for ind,spl in enumerate(splits):
                            if len(spl) <20:
                                #if DEBUG: print "Discarding: ", spl
                                del splits[ind]
                    new_sentences.extend(splits)
                else:
                    new_sentences.append(l)
            return new_sentences
    return wrapped
818065
def f2p(phrase, max_word_size=15, cutoff=3):
    

    results = f2p_list(phrase, max_word_size, cutoff)
    return ' '.join(i[0][0] for i in results)
1141558
def time_col_turbulent(EnergyDis, ConcAl, ConcClay, coag, material,
                       DiamTarget, DIM_FRACTAL):
    
    return((1/6) * (6/np.pi)**(1/9) * EnergyDis**(-1/3) * DiamTarget**(2/3)
           * frac_vol_floc_initial(ConcAl, ConcClay, coag, material)**(-8/9)
           * (DiamTarget / material.Diameter)**((8*(DIM_FRACTAL-3)) / 9)
           )
11409
def parse_in_line(txt: str, units: Units) -> typing.Dict[str, str]:
    
    retwx = {}
    wxdata = txt.split(' ')
    wxdata, _, retwx['wind_shear'] = core.sanitize_report_list(wxdata)
    wxdata, retwx['type'], retwx['start_time'], retwx['end_time'] = core.get_type_and_times(wxdata)
    wxdata, retwx['wind_direction'], retwx['wind_speed'], \
        retwx['wind_gust'], _ = core.get_wind(wxdata, units)
    if 'CAVOK' in wxdata:
        retwx['visibility'] = core.make_number('CAVOK')
        retwx['clouds'] = []
        wxdata.pop(wxdata.index('CAVOK'))
    else:
        wxdata, retwx['visibility'] = core.get_visibility(wxdata, units)
        wxdata, retwx['clouds'] = core.get_clouds(wxdata)
    retwx['other'], retwx['altimeter'], retwx['icing'], retwx['turbulance'] \
        = core.get_taf_alt_ice_turb(wxdata)
    return retwx
763861
def sanitize_cloud(cloud: str) -> str:
    
    if len(cloud) < 4:
        return cloud
    if not cloud[3].isdigit() and cloud[3] != '/':
        if cloud[3] == 'O':
            cloud = cloud[:3] + '0' + cloud[4:]  # Bad "O": FEWO03 -> FEW003
        else:  # Move modifiers to end: BKNC015 -> BKN015C
            cloud = cloud[:3] + cloud[4:] + cloud[3]
    return cloud