#import libraries

import pandas as pd
import numpy as np
import random, math, datetime

def updateVars(T, cityFeeRates, marketShare, repairCosts, chargingCosts, usagePrice, basePrice, bRiderShare, bRiderGrowth, scootersInitial, keepScooterRideRatio, custSupportCosts, avgLifespanScooter, scooterCosts):

    #clearing previously calculated epoch values for the variables
    chargedRatio.clear()
    repairedRatio.clear()
    functioningScooterRatio.clear()
    avgTripDur.clear()
    avgFare.clear()
    availability.clear()
    insuranceCosts.clear()
    creditCardFees.clear()
    grossRevRide.clear()
    usage.clear()
    scootRideRatio.clear()
    avgRidesDayScoot.clear()
    opCosts.clear()
    depreciation.clear()
    movAvgDepreciation.clear()
    cityFees.clear()
    proFormaContribution.clear()
    monthlyEarnings.clear()
    scooters.clear()
    scootersInUse.clear()
    functioningScooters.clear()
    avgScootDistance.clear()
    movAvgUsage.clear()
    movAvgAvgTripDur.clear()

    usageMultiplicator = cosValues[month-1:month+T-1]
    contraRev = [0.44] * T
    if cityFeeRates == True:
        cityFeesA, cityFeesD = 0, 0
    else:
        cityFeesA, cityFeesD = 10, 1

    # formats the xAxis of the plots to contain listMonths
    fmtr = ticker.IndexFormatter(listMonths[month:month+T])

    #calculating the values for each epoch t in time horizont T and appending them to a list
    for t in range(T):
        popBerlin.append(int(popBerlinInitial + popBerlinGrowthFactor * t))

        if bRiderGrowth == "flat":
            bRider.append(int(bRiderShare * popBerlin[-1] * marketShare))
        elif bRiderGrowth == "linear":
            # linear user growth (growth per month: 10% of users in starting month)
            bRider.append(int(bRiderShare * marketShare *
                              (popBerlin[-1] + t * 0.1 * popBerlin[0])))
        else:
            # exponential user growth 10%-MoM
            bRider.append(
                int(bRiderShare*1.1**t * popBerlin[-1] * marketShare))

        #average trip duration in min; estimation; #makes sure that avgTripDurMin <= avgTripDur <= avgTripDurMax
        if t == 0:
            avgTripDur.append(avgTripDurDefault)
        else:
            avgTripDur.append(round(min(avgTripDurMax, max(avgTripDurMin, avgTripDurDefault * (1 +
                                                                                + avgTripDurBasePriceElasticity *
                                                                                ((basePrice - basePriceDefault)/basePriceDefault)
                                                                                + avgTripDurUsagePriceElasticity * ((usagePrice - usagePriceDefault)/usagePriceDefault))
                                                           )), 2))

        if avgTripDur[-1] <= avgTripDurMin:
            avgTripDur[-1] = avgTripDurMin

        selectionAvgTripDur = min(windowAvgTripDur, len(avgTripDur))
        y = np.ones(selectionAvgTripDur,)/selectionAvgTripDur
        movAvgAvgTripDur.append(
            sum([a*b for a, b in zip(avgTripDur[-selectionAvgTripDur:], y)]))

        #avg fare
        # gross revenue per ride
        avgFare.append(round(movAvgAvgTripDur[-1] * usagePrice + basePrice, 2))

        #other costs per ride
        insuranceCosts.append(0.05)  # in $
        creditCardFees.append(round(0.1 * avgFare[-1], 2))  # in $

        #scooter ratios
        chargedRatio.append(round(min(1, chargingWeightCharged * chargingCosts / chargingCostsMax -
                                      avgTripDurWeightCharged * (movAvgAvgTripDur[-1]-avgTripDurDefault)/avgTripDurDefault), 3))
        repairedRatio.append(round(repairCosts / repairCostsMax, 3))
        functioningScootRatioMin = int(
            max(0, (-1 + repairedRatio[-1] + chargedRatio[-1]) * 100))
        functioningScootRatioMax = int(
            min(repairedRatio[-1], chargedRatio[-1]) * 100)
        functioningScootRatioMean = (
            functioningScootRatioMin + functioningScootRatioMax) / 2
        #functioningScooterRatio.append(round(random.randint(functioningScootRatioMin, abs(functioningScootRatioMax))/100,3)) #repairCosts and chargingCosts are independent features
        # repairCosts and chargingCosts are independent features
        functioningScooterRatio.append(round(functioningScootRatioMean/100, 3))

        #number of scooters and scooter to (1000) rider ratio
        initialScootRideRatio = scootersInitial / bRider[0] * 1000

        if keepScooterRideRatio == True:
            scooters.append(int(initialScootRideRatio/1000 * bRider[-1]))
        else:
            scooters.append(scootersInitial)

        #Scooters per 1000 users
        scootRideRatio.append(round(scooters[-1] / bRider[-1] * 1000, 2))

        #scooter availability
        #functioning scooters
        functioningScooters.append(
            int(functioningScooterRatio[-1] * scooters[-1]))

        #avg scooters in use per minute:
        if t == 0:
            scootersInUse.append(int(min(
                functioningScooters[-1], bRider[-1] * movAvgAvgTripDur[-1] * usageDefault / usageHours)))
        else:
            scootersInUse.append(int(min(
                functioningScooters[-1], bRider[-1] * movAvgAvgTripDur[-1] * movAvgUsage[-1] / usageHours)))

        #avg free scooters at any time (between 06:00 - 23:59)
        remainingScooters = functioningScooters[-1] - scootersInUse[-1]
        if remainingScooters == 0:
            avgScootDistance.append(
                int(0.5 * math.sqrt((berlinCoveredArea/1)/pi) * 1000))  # in m

        else:
            avgScootDistance.append(
                int(0.5 * math.sqrt((berlinCoveredArea/remainingScooters)/pi) * 1000))  # in m

        #print("\navgScootDistance: " + str(avgScootDistance))
        #print("remainingScooters: " + str(remainingScooters))

        #usage
        if avgFare[-1] >= avgFareDefault:
            usageAvgFareElasticity = ((1.5 * usageDefault - usageDefault) / usageDefault) / (
                (basePriceMin - avgFareDefault) / avgFareDefault)
        else:
            usageAvgFareElasticity = ((5 * usageDefault - usageDefault) / usageDefault) / (
                (basePriceMin - avgFareDefault) / avgFareDefault)

        usage.append(round(min(usageMax,
                               max(usageMin,
                                   usageMultiplicator[t] * usageDefault *
                                   (1 +
                                    usageAvgFareElasticity *
                                    ((avgTripDurDefault * usagePrice +
                                      basePrice) - avgFareDefault)/avgFareDefault
                                       + usageCustSupportCostElasticity *
                                       (custSupportCosts - custSupportCostsDefault) /
                                    custSupportCostsDefault
                                       + usageAvgScootDistanceWeightElasticity *
                                       (avgScootDistance[-1] - avgScootDistanceDefault) /
                                    avgScootDistanceDefault
                                    )
                                   )), 2))

        selectionUsage = min(windowUsage, len(usage))
        y = np.ones(selectionUsage,)/selectionUsage
        movAvgUsage.append(
            sum([a*b for a, b in zip(usage[-selectionUsage:], y)]))

        #average number of rides per day per scooter
        if usageMultiplicator == 0:
            avgRidesDayScoot.append(0)
        else:
            avgRidesDayScoot.append(round(
                min(usageHours/avgTripDur[-1], bRider[-1] * movAvgUsage[-1] / scooters[-1]), 3))

        #city fees per ride
        if usageMultiplicator == 0:
            depreciation.append(0)
            cityFees.append(0)
        else:
            cityFees.append(
                round((cityFeesA/365 + cityFeesD)/avgRidesDayScoot[-1], 3))
            depreciation.append(
                scooterCosts / (avgLifespanScooter * avgRidesDayScoot[-1]))

        #depreciation costs per scooter per ride (straight line depreciation)
        """
        The (learned) moving average models more realistic for accounting purposes and is more robust against oscillations.
        Therefore, "depreciation" will be removed from the plots in subsequent states.
        However, currently it is still plotted to allow for better detection of unrealistic model behavior.
        """
        selection = min(windowDepreciation, len(depreciation))
        y = np.ones(selection,)/selection
        movAvgDepreciation.append(
            sum([a*b for a, b in zip(depreciation[-selection:], y)]))

        # operational costs per ride
        opCosts.append(round(contraRev[t] + repairCosts + chargingCosts +
                             custSupportCosts + insuranceCosts[-1] + creditCardFees[-1] + cityFees[-1], 2))

        #pro Forma Contribution per Ride
        proFormaContribution.append(
            round(avgFare[-1] - opCosts[-1] - movAvgDepreciation[-1], 2))

        #earnings per month
        monthlyEarnings.append(
            round(proFormaContribution[-1] * avgRidesDayScoot[-1] * scooters[-1] * 30.5, 2))

return
{"inputs": {"T": T,
            "marketShare": marketShare,
            "cityFeeRates": cityFeeRates,
            "repairCosts": repairCosts,
            "chargingCosts": chargingCosts,
            "usagePrice": usagePrice,
            "basePrice": basePrice,
            "bRiderShare": bRiderShare,
            "bRiderGrowth": bRiderGrowth,
            "scootersInitial": scootersInitial,
            "keepScooterRideRatio": keepScooterRideRatio,
            "custSupportCosts": custSupportCosts,
            "avgLifespanScooter": avgLifespanScooter,
            "scooterCosts": scooterCosts},
 "outputs": {"bRider": bRider,
             "avgTripDur": avgTripDur,
             "avgFare": avgFare,
             "movAvgAvgTripDur": movAvgAvgTripDur,
             "insuranceCosts": insuranceCosts,
             "creditCardFees": creditCardFees,
             "chargedRatio": chargedRatio,
             "repairedRatio": repairedRatio,
             "functioningScooterRatio": functioningScooterRatio,
             "initialScootRideRatio": initialScootRideRatio,
             "scooters": scooters,
             "scootRideRatio": scootRideRatio,
             "functioningScooters": functioningScooters,
             "scootersInUse": scootersInUse,
             "avgScootDistance": avgScootDistance,
             "usage": usage,
             "movAvgUsage": movAvgUsage,
             "avgRidesDayScoot": avgRidesDayScoot,
             "cityFees": cityFees,
             "opCosts": opCosts,
             "depreciation": depreciation,
             "movAvgDepreciation": movAvgDepreciation,
             "proFormaContribution": proFormaContribution,
             "monthlyEarnings": monthlyEarnings
             }}


import numpy as np
import pandas as pd
import datetime
import math

# TO DO: REPLACE ALL ASSERTIONS WITH THROW EXCEPTIONS
# TO DO: RENAME AS STATELESS_DATA_MUNGING_OR_WRANGLING

class FeatureEngineering():
    def __init__(self, npi_data_df, confirmed_cases_df):
        '''
        Inputs: 2 data frames containing preprocessed data
          npi_data_df: data frame containing rows of the form: geographic location, npi_name, start_date
          confirmed_cases_df : data frame containing rows of the form: geographic location, date, cumulative number of cases
        '''

        ## preprocessed data
        self.npi_data_df = npi_data_df
        self.confirmed_cases_df = confirmed_cases_df

        colnames = self.npi_data_df.columns
        assert len(colnames) == 3
        self.npi_location_col, self.npi_col, self.npi_start_date_col = colnames

        colnames = self.confirmed_cases_df.columns
        assert len(colnames) == 3
        self.confirmed_cases_location_col, self.confirmed_cases_date_col, self.confirmed_cases_num_col = colnames

        ## initialize transformed data
        self.confirmed_cases_ts = None   # time series of confirmed cases at each location
        #self.new_cases_ts = None    # time series of daily new confirmed cases at each location
        #self.infection_rate_ts = None   # time series of infection rate at each location

    def get_npi_location_col(self):
        return self.npi_data_df[self.npi_location_col]

    def get_npi_col(self):
        return self.npi_data_df[self.npi_col]

    def get_npi_start_date_col(self):
        return self.npi_data_df[self.npi_start_date_col]

    def get_confirmed_cases_time_series(self):
        if self.confirmed_cases_ts is None:
            self.calc_confirmed_cases_ts_()
        return self.confirmed_cases_ts

    def get_new_cases_time_series(self, smoothing_ws=3):
        '''smoothing_ws : window size for smoothing infection rate time series.'''
        return self.calc_new_cases_ts_(smoothing_ws=smoothing_ws)

    def align_time_series(self, ts, N):
        '''
        Input:
            ts : matrix of locations and time series; each row is a time series of a location.
            N : align each row by the date of Nth case.
        Output: two matrix: where rows represent geographic location, columns represent number of
                    days since the Nth confirmed case in a geographic location, and values
                    represent the number of confirmed cases, and the infection rate, respectively.
        '''

        reference_date = self.calc_date_Nth_case_(N)

        extract_ts = lambda x,date:  x.loc[x.index>=date].reset_index(drop=True)

        d = dict()
        for colname,coldata in ts.iteritems():
            d[colname] = extract_ts(coldata,reference_date[colname])
        aligned_ts = pd.DataFrame(d)
        aligned_ts.index.name = 'num_days'
        aligned_ts.columns.name = ts.columns.name

        return aligned_ts

    def get_num_npis_matrix(self):
        '''Returns a matrix, one row per location, one column per date.
        where (i,j)th value is the number of NPI's adopted so far at
        the ith location as of date j.
        '''

        num_npis_matrix = self.npi_data_df.pivot_table(index=self.npi_location_col,
                                                       columns=self.npi_start_date_col,
                                                       values=self.npi_col, aggfunc='count')\
                                         .fillna(value=0)\
                                         .cumsum(axis=1)
        num_npis_matrix.columns.name = 'adoption_date'
        return num_npis_matrix

    def get_normalized_num_npis_matrix(self, N):
        '''Returns a matrix, rows are locations,
        columns are number of days relative to date of Nth case,
        and the (i,j)th value is the number of NPI's adopted so far at
        the ith location j days after it reached its Nth confirmed case,
        where N is an input parameter.
        The date of the Nth confirmed case serves as a reference date
        for normalizing variations in start dates of the disease.
        '''

        # Calculate date of Nth case for each county
        reference_date = self.calc_date_Nth_case_(N=N)

        # start date of NPI adoption as number of days since Nth case
        npi_data_df = self.npi_data_df.copy()
        npi_data_df['start_day'] = self.npi_data_df.apply(lambda row: (row.start_date - reference_date[row.county_state]).days, axis=1)

        normalized_num_npis_matrix = npi_data_df.pivot_table(index=self.npi_location_col,
                                                             columns='start_day',
                                                             values=self.npi_col, aggfunc='count')\
                                                 .fillna(value=0)\
                                                 .cumsum(axis=1)

        normalized_num_npis_matrix.columns.name = 'adoption_day'
        return normalized_num_npis_matrix

    def get_target_vector2(self, N, D):
        ''' Number of confirmed cases D days after Nth confirmed case at every location. '''

        ## Number of confirmed cases time series
        confirmed_cases_ts = self.get_confirmed_cases_time_series()

        ## Number of confirmed cases D days after Nth case
        target_confirmed_cases_ts = self.align_time_series(confirmed_cases_ts, N).iloc[D,:].T

        return np.log10(target_confirmed_cases_ts)

    def get_NPI_agg_features2(self, N, D=0):
        '''
          Inputs:
            N: number of cases parameter.
            D: number of days parameter.
          Returns : a matrix, where rows represent geographic locations, columns represent
            NPIs, and the (i,j)th value is the number of days that the jth NPI was in effect
            up to D days after Nth confirmed case. Thus these features implicity encode for
            each (location,NPI) pair both whether and when the NPI was adopted at that location.
        '''

        reference_date0 = self.calc_date_Nth_case_(N)
        reference_date1 = reference_date0 + datetime.timedelta(days=D)   # date of Nth case + D days

        ## extract the start date of each npi in each geographic location
        npi_adoption_date_matrix = self.calc_npi_start_date_matrix_()

        assert set(reference_date1.index) - set(npi_adoption_date_matrix.index) == set()

        # calculate number of days that each measure was adopted prior to the reference date
        num_days_since_ref_date = npi_adoption_date_matrix.apply(lambda x: reference_date1-x, axis=0)
        npi_feature_matrix = num_days_since_ref_date.applymap(lambda x: x.days if (not math.isnan(x.days) and x.days>0) else 0)
        assert npi_feature_matrix.isnull().sum().sum() == 0
        npi_feature_matrix.loc[reference_date0.isnull(),:] = math.nan

        ## FOR DEBUGGING
        #print(reference_date0.isnull().sum(), reference_date1.isnull().sum())
        #print(npi_feature_matrix.isnull().sum(axis=1).sort_values(ascending=False).head(10))

        return npi_feature_matrix

    #===========================================================================#

    def calc_npi_start_date_matrix_(self):
        #npi_data_df.pivot(index='county_state', columns='npi', values='start_date')
        return self.npi_data_df.pivot(index=self.npi_location_col,
                                      columns=self.npi_col,
                                      values=self.npi_start_date_col)

    def calc_date_Nth_case_(self, N):
        ''' returns the date of Nth case for each geographic location'''
        ''' fixed bug on 6/9/2020 '''

        if self.confirmed_cases_ts is None:
            self.calc_confirmed_cases_ts_()

        def helper_func_(x, N):
            '''Input: x is a time series. N is a value.
               Returns the date such that x[date] ~= N
            '''

            ##OLD VERSION
            ##return x[x>=N].index.min()

            ## MORE CORRECT VERSION, as of 6/9/2020

            if N > x.max():
                return math.nan

            #elif N < x.min():
            #    return x[x>0].index.min()

            elif (x == N).sum():
                return x[x == N].index.min()

            else:
                idx1 = x<N
                idx2 = x>N
                assert idx1.sum() and idx2.sum()

                i1 = x[idx1].index.max()
                i2 = x[idx2].index.min()
                x1 = x[i1]
                x2 = x[i2]
                delta = int(round((N-x1)/(x2-x1)*(i2-i1).days))
                return i1 + pd.Timedelta(delta, unit='days')

        return self.confirmed_cases_ts.apply(lambda x: helper_func_(x,N), axis=0)

    def calc_confirmed_cases_ts_(self):
        '''
        re-calculates and sets the value of self.confirmed_cases_ts
        '''

        ## extract non-aligned confirmed cases matrix; the columns in this matrix correspond to real start dates.
        confirmed_cases_ts = self.confirmed_cases_df.pivot(index=self.confirmed_cases_date_col,
                                                           columns=self.confirmed_cases_location_col,
                                                           values=self.confirmed_cases_num_col)

        ## fill-in leading missing values with 0's in each time series
        # because they indicate 0 confirmed cases at that date.

        confirmed_cases_ts.fillna(value=0, inplace=True)
        assert confirmed_cases_ts.isnull().sum().sum() == 0

        self.confirmed_cases_ts = confirmed_cases_ts

    def calc_new_cases_ts_(self, smoothing_ws):
        if self.confirmed_cases_ts is None:
            self.calc_confirmed_cases_ts_()

        new_cases_ts = self.confirmed_cases_ts.diff(periods=1, axis=0).rolling(window=smoothing_ws).mean()

        # fill-in leading missing values; they are just an artifact of differencing.
        new_cases_ts.fillna(method='backfill', inplace=True)
        assert new_cases_ts.isnull().sum().sum() == 0

        return new_cases_ts

# ---------------------------- UNUSED METHODS --------------------------------------------- #

    def __get_target_vector1__(self):
        ''' Total number of confirmed cases at every location. '''
        confirmed_cases_ts = self.get_confirmed_cases_time_series()
        return np.log10(confirmed_cases_ts.max(axis=0))

    def __get_NPI_agg_features1__(self, N, D):
        '''
        Inputs:
          N: number of cases that characterize onset of disease at a location.
          D: number of days after date of Nth case.
        Returns : a vector, one value per location, where ith value is the number
          of NPI's adopted at location i up to D days after date of Nth confirmed case.
        '''

        normalized_num_npis_matrix = self.get_normalized_num_npis_matrix(N)
        return normalized_num_npis_matrix.loc[:,D]

    def __get_infection_rate_time_series__(self, num_periods, smoothing_ws=3, q=.95):
        '''
          num_periods : interval size in number of days for calculating infection rate :
               where InfectionRate(t) = (ConfirmedCases(t)-ConfirmedCases(t-num_periods)) / ConfirmedCases(t-num_periods)
          smoothing_ws : window size for smoothing infection rate time series.
        '''
        return self.__calc_infection_rate_ts__(num_periods=num_periods, smoothing_ws=smoothing_ws, q=q)

    def __calc_infection_rate_ts__(self, num_periods, smoothing_ws, q=0):

        if self.confirmed_cases_ts is None:
            self.calc_confirmed_cases_ts_()

        calc_change_rate = lambda x, n, w: x.fillna(method='ffill') \
                 .pct_change(periods=n, fill_method='ffill') \
                 .rolling(window=w).mean()  ##.median()

        infection_rate_ts = self.confirmed_cases_ts.apply(lambda x: calc_change_rate(x, n=num_periods, w=smoothing_ws), axis=0)

        ## trimming
        if q > 0:
            qv = np.nanquantile(infection_rate_ts.values, q=q)
            infection_rate_ts = infection_rate_ts.applymap(lambda x: x if x<qv or math.isnan(x) else qv)

        return infection_rate_ts


import click
from buildutils import BuildConfiguration
from buildutils.plugins import FlakePlugin, GenericCommandPlugin, EnsureVenvActivePlugin, group

@click.command()
@click.option('--profile', '-pr')
@click.option('--plugins', '-p')
@click.option('--list-plugins', '-l', is_flag=True)
def main(profile: str, plugins: str, list_plugins: bool):
    (
        BuildConfiguration()
        .config('build.ini')
        .plugins(
            EnsureVenvActivePlugin(),
            FlakePlugin(),
            group(
                'generate-docs',
                GenericCommandPlugin('PREPARE_DOCS', 'Prepare Sphinx for generating documentation from inline comments.'),
                GenericCommandPlugin('GENERATE_DOCS', 'Generate documentation from inline comments using Sphinx')
            )
        )
        .build(profile, plugins, list_plugins)
    )

if __name__ == '__main__':
    main()


import numpy as np
import scipy.stats as stats
import pylab as pl
import matplotlib.pyplot as pyplot
from flask import send_file, Flask, request, jsonify
app = Flask(__name__)

@app.route('/simple_statistics', methods=['POST'])
def simple_statistics():
    filename = 'myfig.png'
    content = request.get_json()
    sorted_input = sorted([y for [x, y, z] in content['data']])
    fit = stats.norm.pdf(sorted_input, np.mean(sorted_input), np.std(sorted_input))
    pl.plot(sorted_input, fit, '-o')
    pl.xlabel("Time in seconds")
    pl.hist(sorted_input, normed=True)
    pl.savefig(filename)
    return send_file(filename, mimetype='image/png')


n, m = map(int, input().split())
notHear = set()
notSee = set()

for _ in range(n):
    notHear.add(input())

for _ in range(m):
    notSee.add(input())

notHearSee = notHear.intersection(notSee)
sortList = sorted(notHearSee)
print(len(sortList))
for i in sortList:
    print(i)


from SecondLayer.Utilities import _getRandomHeader, _commitSQLCommand
import requests
import re
class yahooComment:
      def __init__(user,comment,like,dislike,replies):
          user.comment = comment
          user.like = like
          user.dislike = dislike
          user.replies = replies

def _getYahooFinanceComment(coinname,coin,numberofcomment): #Get Cryptocurrency people comment from Yahoo Finance

    numberoftimes = numberofcomment / 30
    count = 30;
    dataset = []
    check = 0
    counter = 0
    link = "https://sg.finance.yahoo.com/_finance_doubledown/api/resource/canvass.getMessageList;apiVersion=v1;context=finmb_"+coin+"_CCC;count=30;lang=en-SG;namespace=yahoo_finance;oauthConsumerKey=finance.oauth.client.canvass.prod.consumerKey;oauthConsumerSecret=finance.oauth.client.canvass.prod.consumerSecret;query=namespace%20%3D%20%22yahoo_finance%22%20and%20(contextId%3D%22finmb_"+coin+"_CCC%22%20or%20tag%3D%22"+coin+"-USD%22);"

    while counter < numberoftimes and check != 1: #Change the number to get the desired number of comments
        request = requests.get(link,headers=_getRandomHeader())

        #Find the specified sentence/number/word by using regex expressions
        comment = re.findall("userText?.*?tags",str(request.content.decode('utf8').encode('ascii', errors='ignore')))
        like    = re.findall("upVoteCount?.*?,",str(request.content.decode('utf8').encode('ascii', errors='ignore')))
        dislike = re.findall("downVoteCount?.*?,",str(request.content.decode('utf8').encode('ascii', errors='ignore')))
        reply = re.findall("replyCount?.*?,",str(request.content.decode('utf8').encode('ascii', errors='ignore')))
        nextpage = re.findall("startIndex?.*?,",str(request.content.decode('utf8').encode('ascii', errors='ignore')))

        if(len(comment) == 0): #Check if it does return any feedback else end the loop
           check = 1;

        for x in range(len(comment)):
            comment[x] = re.sub('https?.*|"imageMessageDetails?.*','',str(comment[x]).replace("\\n",'').replace("\\",'')) #Fliter the sentence/number or word
            if comment[x] != 'userText":"' and comment[x] != 'userText":"",':
                dataset.insert(len(dataset),yahooComment(str(comment[x])[11:-8],str(like[x]).replace('upVoteCount":','').replace(",",''),str(dislike[x]).replace('downVoteCount":','').replace(",",''),str(reply[x]).replace('replyCount":','').replace("},",'')))

        if len(nextpage) !=  0:
            link ="https://sg.finance.yahoo.com/_finance_doubledown/api/resource/canvass.getMessageList;apiVersion=v1;context=finmb_"+ coin+ "_CCC;count=30;" + "index=v%3D" + nextpage[0][15:-32] +  "%3As%3D" + nextpage[0][19:-22] + "%3Asl%3D" + nextpage[0][30:-8] +  "%3Aoff%3D" + str(count) + ";lang=en-SG;namespace=yahoo_finance;oauthConsumerKey=finance.oauth.client.canvass.prod.consumerKey;oauthConsumerSecret=finance.oauth.client.canvass.prod.consumerSecret;query=namespace%20%3D%20%22yahoo_finance%22%20and%20(contextId%3D%22finmb_"+coin+"_CCC%22%20or%20tag%3D%22"+coin+"-USD%22);"
        count += 30
        counter += 1
    pass

    _commitSQLCommand("CREATE Table IF NOT EXISTS yahoocomment" + str(coinname).replace(" ","") + "(id int NOT NULL AUTO_INCREMENT,comment varchar(10000) DEFAULT NULL,thumbup int DEFAULT NULL,thumbdown int DEFAULT NULL,reply int DEFAULT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=1021 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;",'')
    _commitSQLCommand("DELETE FROM yahoocomment" + str(coinname).replace(" ",""),'')

    for x in range(len(dataset)):
        _commitSQLCommand("INSERT INTO yahoocomment"+ str(coinname).replace(" ","") + " VALUES (%s,%s,%s,%s,%s)",(x+1,dataset[x].comment,dataset[x].like,dataset[x].dislike,dataset[x].replies))

    if len(dataset) == 0:
        _commitSQLCommand("INSERT INTO yahoocomment"+ str(coinname).replace(" ","") + " VALUES (%s,%s,%s,%s,%s)",(1,"No Data",0,0,0))


# -*- coding: utf-8 -*-
from socket import *
from Metod import Method
def send(data):
    s = socket(AF_INET, SOCK_DGRAM)
    s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
    if len(data):
        host = Method.get255BroadAddList()
        port = Method.port()
        print('send to',host,port)
        s.sendto(data,(host,port))

    else:
        print('数据为空')


import collections
import numpy as np
import torch.optim as optim
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Iterable, List
from ml_utils.model_training import torch_trainer
import torch.utils.data
import datasets
import numpy as np
from sklearn.preprocessing import MultiLabelBinarizer
from torch.utils.data import default_collate
import pandas as pd
from sklearn.metrics import classification_report, f1_score

class Dataset(torch.utils.data.Dataset):
    "Characterizes a dataset for PyTorch"

    def __init__(
        self,
        vectors: np.array,
        labels: np.array,
        sentences: Iterable[List[str]],
        device: str,
    ):
        "Initialization"
        self.labels = labels
        self.device = device
        self.vectors = vectors
        self.num_sentences = [len(x) for x in sentences]

    def __len__(self):
        "Denotes the total number of samples"
        return len(self.labels)

    def __getitem__(self, index):
        return {
            "inputs": np.vstack(self.vectors[index]),
            "labels": self.labels[index],
            "train_labels": torch.from_numpy(self.labels[index]).float(),
            "indices": index,
            "num_sentences": self.num_sentences[index],
        }

class BasicModel(torch_trainer.BaseModule):
    def __init__(self, dims):
        super(BasicModel, self).__init__()
        self.dims = dims
        self.flat = nn.Flatten()
        self.conv1 = nn.Conv1d(768, 768, kernel_size=(1))
        self.conv2 = nn.Conv1d(768, 768, kernel_size=(1))
        self.conv3 = nn.Conv1d(768, 768, kernel_size=(1))
        self.lin1 = nn.Linear(int(768 / 1), int(768 / 1))
        self.lin2 = nn.Linear(int(768 / 1), int(768 / 1))
        self.lin = nn.Linear(int(768 / 1), dims)
        self.metric = 0

    def forward(self, x):
        if x.device != self.device:
            x.to(self.device)
        x = x.float()
        x = torch.transpose(x, 1, 2)
        F.leaky_relu(self.conv1(x), inplace=True)
        F.leaky_relu(self.conv2(x), inplace=True)
        F.leaky_relu(self.conv3(x), inplace=True)
        x = torch.transpose(x, 1, 2)
        x = self.lin2(x)
        x = self.lin1(x)
        x = self.lin(x)
        return x

    def get_dims(self):
        return self.dims

    @property
    def name(self):
        return "BasicModel"

    def activation(self, inputs, mean=True):
        if mean:
            predictions = inputs.mean(1).float()
        else:
            predictions = inputs
        return torch.sigmoid(predictions)

    def predict(self, input, explain=False, **kwargs):
        logits = self(input)
        activated = self.activation(logits, not explain).cpu().detach()
        return activated.round()

def collate_fn(batch):
    first_elem = batch[0]
    elem_type = type(first_elem)
    if isinstance(first_elem, torch.Tensor) and any(
        first_elem.shape != elem_.shape for elem_ in batch
    ):
        return torch.nn.utils.rnn.pad_sequence(batch, batch_first=True)

    if isinstance(first_elem, np.ndarray) and any(
        first_elem.shape != elem_.shape for elem_ in batch
    ):
        batch = [torch.from_numpy(b) for b in batch]
        return torch.nn.utils.rnn.pad_sequence(batch, batch_first=True)

    elif isinstance(first_elem, collections.abc.Mapping):
        try:
            return elem_type(
                {key: collate_fn([d[key] for d in batch]) for key in first_elem}
            )
        except TypeError:
            # The mapping type may not support `__init__(iterable)`.
            return {key: collate_fn([d[key] for d in batch]) for key in first_elem}
    else:
        return default_collate(batch)

def get_class_weights(class_series):
    n_samples = len(class_series)

    if hasattr(class_series[0], "__len__"):
        n_classes = len(class_series[0])

        # Count each class frequency
        class_count = [0] * n_classes
        for classes in class_series:
            for index in range(n_classes):
                if classes[index] != 0:
                    class_count[index] += 1
                    # Compute class weights using balanced method
        class_weights = [
            n_samples / (n_classes * freq) if freq > 0 else 1 for freq in class_count
        ]
    else:
        n_classes = len(set(class_series))
        from sklearn.utils import class_weight

        class_weights = class_weight.compute_class_weight(
            "balanced", classes=np.unique(class_series), y=class_series
        )

    class_labels = range(len(class_weights))
    return dict(zip(class_labels, class_weights))

def make_binary(example):
    x = int(any(example["violated_articles"]))
    example["binary_labels"] = np.array([x])
    return example

def filter_occ(example):
    x = set(example["violated_articles"])
    filter_ = set(["11", "14", "10", "2", "8", "13", "3", "5", "P1-1", "6"])
    example["filtered_violated_articles"] = x - (x - filter_)
    return example

if __name__ == "__main__":

    encoders = [
        "bert_base_uncased",
        # "legal_bert_base_uncased",
        # "ecthr_base_ex",
        # "roberta_base",
        # "longformer_base",
        # "ecthr_robert_long",
    ]
    for encoder in encoders:
        data = datasets.load_from_disk(
            "data/ecthr_cases_violated_" + encoder
        )

        data = data.map(filter_occ)
        label = "filtered_violated_articles"

        label_binarizer = MultiLabelBinarizer()
        label_binarizer = label_binarizer.fit(data["train"][label])

        trainDataset = Dataset(
            data["train"]["vectors"],
            label_binarizer.transform(data["train"][label]).astype(float),
            data["train"]["gold_rationales"],
            "cuda",
        )

        testDataset = Dataset(
            data["test"]["vectors"],
            label_binarizer.transform(data["test"][label]).astype(float),
            data["test"]["gold_rationales"],
            "cuda",
        )

        valDataset = Dataset(
            data["dev"]["vectors"],
            label_binarizer.transform(data["dev"][label]).astype(float),
            data["dev"]["gold_rationales"],
            "cuda",
        )

        class_weights = get_class_weights(trainDataset.labels)
        model = BasicModel(len(class_weights)).cuda()
        criterion = nn.BCELoss(weight=torch.tensor(list(class_weights.values())).cuda())

        optimizer = optim.Adam(model.parameters())

        BATCH_SIZE = 64
        testdataLoader = torch.utils.data.DataLoader(
            testDataset, collate_fn=collate_fn, shuffle=False, batch_size=BATCH_SIZE
        )
        valdataLoader = torch.utils.data.DataLoader(
            valDataset, collate_fn=collate_fn, shuffle=False, batch_size=BATCH_SIZE
        )
        traindataLoader = torch.utils.data.DataLoader(
            trainDataset, shuffle=True, collate_fn=collate_fn, batch_size=BATCH_SIZE
        )

        torch_trainer.train_model(
            model,
            traindataLoader=traindataLoader,
            testdataLoader=valdataLoader,
            criterion=criterion,
            optimizer=optimizer,
            activation=model.activation,
            device="cuda",
            epochs=15,
        )

        print(encoder)
        test_res = torch_trainer.validate_model(
            model, testdataLoader, criterion, model.activation, "cuda"
        )

        clsf_report = pd.DataFrame(
            classification_report(
                y_true=test_res[1], y_pred=test_res[0], output_dict=True
            )
        ).transpose()
        clsf_report.index = list(label_binarizer.classes_) + list(
            clsf_report.index[-4:]
        )

        clsf_report["tes_res"] = pd.Series([test_res[0]], index=clsf_report.index[[0]])
        clsf_report["tes_label"] = pd.Series(
            [test_res[1]], index=clsf_report.index[[0]]
        )
        clsf_report.to_csv(encoder + ".csv", index=True)
        torch.save(model.state_dict(), encoder + "_classification_model.pt")
        print(clsf_report["f1-score"])


import io
import json
import platform
import re
import sys
import tokenize
import traceback
from contextlib import contextmanager
from dataclasses import replace
from datetime import datetime, timezone
from enum import Enum
from json.decoder import JSONDecodeError
from pathlib import Path
from typing import (
    Any,
    Dict,
    Generator,
    Iterator,
    List,
    MutableMapping,
    Optional,
    Pattern,
    Sequence,
    Set,
    Sized,
    Tuple,
    Union,
)

import click
from click.core import ParameterSource
from mypy_extensions import mypyc_attr
from pathspec import PathSpec
from pathspec.patterns.gitwildmatch import GitWildMatchPatternError

from _black_version import version as __version__
from black.cache import Cache
from black.comments import normalize_fmt_off
from black.const import (
    DEFAULT_EXCLUDES,
    DEFAULT_INCLUDES,
    DEFAULT_LINE_LENGTH,
    STDIN_PLACEHOLDER,
)
from black.files import (
    find_project_root,
    find_pyproject_toml,
    find_user_pyproject_toml,
    gen_python_files,
    get_gitignore,
    normalize_path_maybe_ignore,
    parse_pyproject_toml,
    wrap_stream_for_windows,
)
from black.handle_ipynb_magics import (
    PYTHON_CELL_MAGICS,
    TRANSFORMED_MAGICS,
    jupyter_dependencies_are_installed,
    mask_cell,
    put_trailing_semicolon_back,
    remove_trailing_semicolon,
    unmask_cell,
)
from black.linegen import LN, LineGenerator, transform_line
from black.lines import EmptyLineTracker, LinesBlock
from black.mode import FUTURE_FLAG_TO_FEATURE, VERSION_TO_FEATURES, Feature
from black.mode import Mode as Mode  # re-exported
from black.mode import TargetVersion, supports_feature
from black.nodes import (
    STARS,
    is_number_token,
    is_simple_decorator_expression,
    is_string_token,
    syms,
)
from black.output import color_diff, diff, dump_to_file, err, ipynb_diff, out
from black.parsing import InvalidInput  # noqa F401
from black.parsing import lib2to3_parse, parse_ast, stringify_ast
from black.report import Changed, NothingChanged, Report
from black.trans import iter_fexpr_spans
from blib2to3.pgen2 import token
from blib2to3.pytree import Leaf, Node

COMPILED = Path(__file__).suffix in (".pyd", ".so")

# types
FileContent = str
Encoding = str
NewLine = str

class WriteBack(Enum):
    NO = 0
    YES = 1
    DIFF = 2
    CHECK = 3
    COLOR_DIFF = 4

    @classmethod
    def from_configuration(
        cls, *, check: bool, diff: bool, color: bool = False
    ) -> "WriteBack":
        if check and not diff:
            return cls.CHECK

        if diff and color:
            return cls.COLOR_DIFF

        return cls.DIFF if diff else cls.YES

# Legacy name, left for integrations.
FileMode = Mode

def read_pyproject_toml(
    ctx: click.Context, param: click.Parameter, value: Optional[str]
) -> Optional[str]:
    """Inject Black configuration from "pyproject.toml" into defaults in `ctx`.

    Returns the path to a successfully found and read configuration file, None
    otherwise.
    """
    if not value:
        value = find_pyproject_toml(
            ctx.params.get("src", ()), ctx.params.get("stdin_filename", None)
        )
        if value is None:
            return None

    try:
        config = parse_pyproject_toml(value)
    except (OSError, ValueError) as e:
        raise click.FileError(
            filename=value, hint=f"Error reading configuration file: {e}"
        ) from None

    if not config:
        return None
    else:
        # Sanitize the values to be Click friendly. For more information please see:
        # https://github.com/psf/black/issues/1458
        # https://github.com/pallets/click/issues/1567
        config = {
            k: str(v) if not isinstance(v, (list, dict)) else v
            for k, v in config.items()
        }

    target_version = config.get("target_version")
    if target_version is not None and not isinstance(target_version, list):
        raise click.BadOptionUsage(
            "target-version", "Config key target-version must be a list"
        )

    exclude = config.get("exclude")
    if exclude is not None and not isinstance(exclude, str):
        raise click.BadOptionUsage("exclude", "Config key exclude must be a string")

    extend_exclude = config.get("extend_exclude")
    if extend_exclude is not None and not isinstance(extend_exclude, str):
        raise click.BadOptionUsage(
            "extend-exclude", "Config key extend-exclude must be a string"
        )

    default_map: Dict[str, Any] = {}
    if ctx.default_map:
        default_map.update(ctx.default_map)
    default_map.update(config)

    ctx.default_map = default_map
    return value

def target_version_option_callback(
    c: click.Context, p: Union[click.Option, click.Parameter], v: Tuple[str, ...]
) -> List[TargetVersion]:
    """Compute the target versions from a --target-version flag.

    This is its own function because mypy couldn't infer the type correctly
    when it was a lambda, causing mypyc trouble.
    """
    return [TargetVersion[val.upper()] for val in v]

def re_compile_maybe_verbose(regex: str) -> Pattern[str]:
    """Compile a regular expression string in `regex`.

    If it contains newlines, use verbose mode.
    """
    if "\n" in regex:
        regex = "(?x)" + regex
    compiled: Pattern[str] = re.compile(regex)
    return compiled

def validate_regex(
    ctx: click.Context,
    param: click.Parameter,
    value: Optional[str],
) -> Optional[Pattern[str]]:
    try:
        return re_compile_maybe_verbose(value) if value is not None else None
    except re.error as e:
        raise click.BadParameter(f"Not a valid regular expression: {e}") from None

@click.command(
    context_settings={"help_option_names": ["-h", "--help"]},
    # While Click does set this field automatically using the docstring, mypyc
    # (annoyingly) strips 'em so we need to set it here too.
    help="The uncompromising code formatter.",
)
@click.option("-c", "--code", type=str, help="Format the code passed in as a string.")
@click.option(
    "-l",
    "--line-length",
    type=int,
    default=DEFAULT_LINE_LENGTH,
    help="How many characters per line to allow.",
    show_default=True,
)
@click.option(
    "-t",
    "--target-version",
    type=click.Choice([v.name.lower() for v in TargetVersion]),
    callback=target_version_option_callback,
    multiple=True,
    help=(
        "Python versions that should be supported by Black's output. By default, Black"
        " will try to infer this from the project metadata in pyproject.toml. If this"
        " does not yield conclusive results, Black will use per-file auto-detection."
    ),
)
@click.option(
    "--pyi",
    is_flag=True,
    help=(
        "Format all input files like typing stubs regardless of file extension (useful"
        " when piping source on standard input)."
    ),
)
@click.option(
    "--ipynb",
    is_flag=True,
    help=(
        "Format all input files like Jupyter Notebooks regardless of file extension "
        "(useful when piping source on standard input)."
    ),
)
@click.option(
    "--python-cell-magics",
    multiple=True,
    help=(
        "When processing Jupyter Notebooks, add the given magic to the list"
        f" of known python-magics ({', '.join(sorted(PYTHON_CELL_MAGICS))})."
        " Useful for formatting cells with custom python magics."
    ),
    default=[],
)
@click.option(
    "-x",
    "--skip-source-first-line",
    is_flag=True,
    help="Skip the first line of the source code.",
)
@click.option(
    "-S",
    "--skip-string-normalization",
    is_flag=True,
    help="Don't normalize string quotes or prefixes.",
)
@click.option(
    "-C",
    "--skip-magic-trailing-comma",
    is_flag=True,
    help="Don't use trailing commas as a reason to split lines.",
)
@click.option(
    "--experimental-string-processing",
    is_flag=True,
    hidden=True,
    help="(DEPRECATED and now included in --preview) Normalize string literals.",
)
@click.option(
    "--preview",
    is_flag=True,
    help=(
        "Enable potentially disruptive style changes that may be added to Black's main"
        " functionality in the next major release."
    ),
)
@click.option(
    "--check",
    is_flag=True,
    help=(
        "Don't write the files back, just return the status. Return code 0 means"
        " nothing would change. Return code 1 means some files would be reformatted."
        " Return code 123 means there was an internal error."
    ),
)
@click.option(
    "--diff",
    is_flag=True,
    help="Don't write the files back, just output a diff for each file on stdout.",
)
@click.option(
    "--color/--no-color",
    is_flag=True,
    help="Show colored diff. Only applies when `--diff` is given.",
)
@click.option(
    "--fast/--safe",
    is_flag=True,
    help="If --fast given, skip temporary sanity checks. [default: --safe]",
)
@click.option(
    "--required-version",
    type=str,
    help=(
        "Require a specific version of Black to be running (useful for unifying results"
        " across many environments e.g. with a pyproject.toml file). It can be"
        " either a major version number or an exact version."
    ),
)
@click.option(
    "--include",
    type=str,
    default=DEFAULT_INCLUDES,
    callback=validate_regex,
    help=(
        "A regular expression that matches files and directories that should be"
        " included on recursive searches. An empty value means all files are included"
        " regardless of the name. Use forward slashes for directories on all platforms"
        " (Windows, too). Exclusions are calculated first, inclusions later."
    ),
    show_default=True,
)
@click.option(
    "--exclude",
    type=str,
    callback=validate_regex,
    help=(
        "A regular expression that matches files and directories that should be"
        " excluded on recursive searches. An empty value means no paths are excluded."
        " Use forward slashes for directories on all platforms (Windows, too)."
        " Exclusions are calculated first, inclusions later. [default:"
        f" {DEFAULT_EXCLUDES}]"
    ),
    show_default=False,
)
@click.option(
    "--extend-exclude",
    type=str,
    callback=validate_regex,
    help=(
        "Like --exclude, but adds additional files and directories on top of the"
        " excluded ones. (Useful if you simply want to add to the default)"
    ),
)
@click.option(
    "--force-exclude",
    type=str,
    callback=validate_regex,
    help=(
        "Like --exclude, but files and directories matching this regex will be "
        "excluded even when they are passed explicitly as arguments."
    ),
)
@click.option(
    "--stdin-filename",
    type=str,
    is_eager=True,
    help=(
        "The name of the file when passing it through stdin. Useful to make "
        "sure Black will respect --force-exclude option on some "
        "editors that rely on using stdin."
    ),
)
@click.option(
    "-W",
    "--workers",
    type=click.IntRange(min=1),
    default=None,
    help=(
        "Number of parallel workers [default: BLACK_NUM_WORKERS environment variable "
        "or number of CPUs in the system]"
    ),
)
@click.option(
    "-q",
    "--quiet",
    is_flag=True,
    help=(
        "Don't emit non-error messages to stderr. Errors are still emitted; silence"
        " those with 2>/dev/null."
    ),
)
@click.option(
    "-v",
    "--verbose",
    is_flag=True,
    help=(
        "Also emit messages to stderr about files that were not changed or were ignored"
        " due to exclusion patterns."
    ),
)
@click.version_option(
    version=__version__,
    message=(
        f"%(prog)s, %(version)s (compiled: {'yes' if COMPILED else 'no'})\n"
        f"Python ({platform.python_implementation()}) {platform.python_version()}"
    ),
)
@click.argument(
    "src",
    nargs=-1,
    type=click.Path(
        exists=True, file_okay=True, dir_okay=True, readable=True, allow_dash=True
    ),
    is_eager=True,
    metavar="SRC ...",
)
@click.option(
    "--config",
    type=click.Path(
        exists=True,
        file_okay=True,
        dir_okay=False,
        readable=True,
        allow_dash=False,
        path_type=str,
    ),
    is_eager=True,
    callback=read_pyproject_toml,
    help="Read configuration from FILE path.",
)
@click.pass_context
def main(  # noqa: C901
    ctx: click.Context,
    code: Optional[str],
    line_length: int,
    target_version: List[TargetVersion],
    check: bool,
    diff: bool,
    color: bool,
    fast: bool,
    pyi: bool,
    ipynb: bool,
    python_cell_magics: Sequence[str],
    skip_source_first_line: bool,
    skip_string_normalization: bool,
    skip_magic_trailing_comma: bool,
    experimental_string_processing: bool,
    preview: bool,
    quiet: bool,
    verbose: bool,
    required_version: Optional[str],
    include: Pattern[str],
    exclude: Optional[Pattern[str]],
    extend_exclude: Optional[Pattern[str]],
    force_exclude: Optional[Pattern[str]],
    stdin_filename: Optional[str],
    workers: Optional[int],
    src: Tuple[str, ...],
    config: Optional[str],
) -> None:
    """The uncompromising code formatter."""
    ctx.ensure_object(dict)

    if src and code is not None:
        out(
            main.get_usage(ctx)
            + "\n\n'SRC' and 'code' cannot be passed simultaneously."
        )
        ctx.exit(1)
    if not src and code is None:
        out(main.get_usage(ctx) + "\n\nOne of 'SRC' or 'code' is required.")
        ctx.exit(1)

    root, method = (
        find_project_root(src, stdin_filename) if code is None else (None, None)
    )
    ctx.obj["root"] = root

    if verbose:
        if root:
            out(
                f"Identified `{root}` as project root containing a {method}.",
                fg="blue",
            )

        if config:
            config_source = ctx.get_parameter_source("config")
            user_level_config = str(find_user_pyproject_toml())
            if config == user_level_config:
                out(
                    "Using configuration from user-level config at "
                    f"'{user_level_config}'.",
                    fg="blue",
                )
            elif config_source in (
                ParameterSource.DEFAULT,
                ParameterSource.DEFAULT_MAP,
            ):
                out("Using configuration from project root.", fg="blue")
            else:
                out(f"Using configuration in '{config}'.", fg="blue")
            if ctx.default_map:
                for param, value in ctx.default_map.items():
                    out(f"{param}: {value}")

    error_msg = "Oh no! 💥 💔 💥"
    if (
        required_version
        and required_version != __version__
        and required_version != __version__.split(".")[0]
    ):
        err(
            f"{error_msg} The required version `{required_version}` does not match"
            f" the running version `{__version__}`!"
        )
        ctx.exit(1)
    if ipynb and pyi:
        err("Cannot pass both `pyi` and `ipynb` flags!")
        ctx.exit(1)

    write_back = WriteBack.from_configuration(check=check, diff=diff, color=color)
    if target_version:
        versions = set(target_version)
    else:
        # We'll autodetect later.
        versions = set()
    mode = Mode(
        target_versions=versions,
        line_length=line_length,
        is_pyi=pyi,
        is_ipynb=ipynb,
        skip_source_first_line=skip_source_first_line,
        string_normalization=not skip_string_normalization,
        magic_trailing_comma=not skip_magic_trailing_comma,
        experimental_string_processing=experimental_string_processing,
        preview=preview,
        python_cell_magics=set(python_cell_magics),
    )

    if code is not None:
        # Run in quiet mode by default with -c; the extra output isn't useful.
        # You can still pass -v to get verbose output.
        quiet = True

    report = Report(check=check, diff=diff, quiet=quiet, verbose=verbose)

    if code is not None:
        reformat_code(
            content=code, fast=fast, write_back=write_back, mode=mode, report=report
        )
    else:
        assert root is not None  # root is only None if code is not None
        try:
            sources = get_sources(
                root=root,
                src=src,
                quiet=quiet,
                verbose=verbose,
                include=include,
                exclude=exclude,
                extend_exclude=extend_exclude,
                force_exclude=force_exclude,
                report=report,
                stdin_filename=stdin_filename,
            )
        except GitWildMatchPatternError:
            ctx.exit(1)

        path_empty(
            sources,
            "No Python files are present to be formatted. Nothing to do 😴",
            quiet,
            verbose,
            ctx,
        )

        if len(sources) == 1:
            reformat_one(
                src=sources.pop(),
                fast=fast,
                write_back=write_back,
                mode=mode,
                report=report,
            )
        else:
            from black.concurrency import reformat_many

            reformat_many(
                sources=sources,
                fast=fast,
                write_back=write_back,
                mode=mode,
                report=report,
                workers=workers,
            )

    if verbose or not quiet:
        if code is None and (verbose or report.change_count or report.failure_count):
            out()
        out(error_msg if report.return_code else "All done! ✨ 🍰 ✨")
        if code is None:
            click.echo(str(report), err=True)
    ctx.exit(report.return_code)

def get_sources(
    *,
    root: Path,
    src: Tuple[str, ...],
    quiet: bool,
    verbose: bool,
    include: Pattern[str],
    exclude: Optional[Pattern[str]],
    extend_exclude: Optional[Pattern[str]],
    force_exclude: Optional[Pattern[str]],
    report: "Report",
    stdin_filename: Optional[str],
) -> Set[Path]:
    """Compute the set of files to be formatted."""
    sources: Set[Path] = set()

    using_default_exclude = exclude is None
    exclude = re_compile_maybe_verbose(DEFAULT_EXCLUDES) if exclude is None else exclude
    gitignore: Optional[Dict[Path, PathSpec]] = None
    root_gitignore = get_gitignore(root)

    for s in src:
        if s == "-" and stdin_filename:
            p = Path(stdin_filename)
            is_stdin = True
        else:
            p = Path(s)
            is_stdin = False

        if is_stdin or p.is_file():
            normalized_path: Optional[str] = normalize_path_maybe_ignore(
                p, root, report
            )
            if normalized_path is None:
                if verbose:
                    out(f'Skipping invalid source: "{normalized_path}"', fg="red")
                continue
            if verbose:
                out(f'Found input source: "{normalized_path}"', fg="blue")

            normalized_path = "/" + normalized_path
            # Hard-exclude any files that matches the `--force-exclude` regex.
            if force_exclude:
                force_exclude_match = force_exclude.search(normalized_path)
            else:
                force_exclude_match = None
            if force_exclude_match and force_exclude_match.group(0):
                report.path_ignored(p, "matches the --force-exclude regular expression")
                continue

            if is_stdin:
                p = Path(f"{STDIN_PLACEHOLDER}{str(p)}")

            if p.suffix == ".ipynb" and not jupyter_dependencies_are_installed(
                warn=verbose or not quiet
            ):
                continue

            sources.add(p)
        elif p.is_dir():
            p_relative = normalize_path_maybe_ignore(p, root, report)
            assert p_relative is not None
            p = root / p_relative
            if verbose:
                out(f'Found input source directory: "{p}"', fg="blue")

            if using_default_exclude:
                gitignore = {
                    root: root_gitignore,
                    p: get_gitignore(p),
                }
            sources.update(
                gen_python_files(
                    p.iterdir(),
                    root,
                    include,
                    exclude,
                    extend_exclude,
                    force_exclude,
                    report,
                    gitignore,
                    verbose=verbose,
                    quiet=quiet,
                )
            )
        elif s == "-":
            if verbose:
                out("Found input source stdin", fg="blue")
            sources.add(p)
        else:
            err(f"invalid path: {s}")

    return sources

def path_empty(
    src: Sized, msg: str, quiet: bool, verbose: bool, ctx: click.Context
) -> None:
    """
    Exit if there is no `src` provided for formatting
    """
    if not src:
        if verbose or not quiet:
            out(msg)
        ctx.exit(0)

def reformat_code(
    content: str, fast: bool, write_back: WriteBack, mode: Mode, report: Report
) -> None:
    """
    Reformat and print out `content` without spawning child processes.
    Similar to `reformat_one`, but for string content.

    `fast`, `write_back`, and `mode` options are passed to
    :func:`format_file_in_place` or :func:`format_stdin_to_stdout`.
    """
    path = Path("<string>")
    try:
        changed = Changed.NO
        if format_stdin_to_stdout(
            content=content, fast=fast, write_back=write_back, mode=mode
        ):
            changed = Changed.YES
        report.done(path, changed)
    except Exception as exc:
        if report.verbose:
            traceback.print_exc()
        report.failed(path, str(exc))

# diff-shades depends on being to monkeypatch this function to operate. I know it's
# not ideal, but this shouldn't cause any issues ... hopefully. ~ichard26
@mypyc_attr(patchable=True)
def reformat_one(
    src: Path, fast: bool, write_back: WriteBack, mode: Mode, report: "Report"
) -> None:
    """Reformat a single file under `src` without spawning child processes.

    `fast`, `write_back`, and `mode` options are passed to
    :func:`format_file_in_place` or :func:`format_stdin_to_stdout`.
    """
    try:
        changed = Changed.NO

        if str(src) == "-":
            is_stdin = True
        elif str(src).startswith(STDIN_PLACEHOLDER):
            is_stdin = True
            # Use the original name again in case we want to print something
            # to the user
            src = Path(str(src)[len(STDIN_PLACEHOLDER) :])
        else:
            is_stdin = False

        if is_stdin:
            if src.suffix == ".pyi":
                mode = replace(mode, is_pyi=True)
            elif src.suffix == ".ipynb":
                mode = replace(mode, is_ipynb=True)
            if format_stdin_to_stdout(fast=fast, write_back=write_back, mode=mode):
                changed = Changed.YES
        else:
            cache = Cache.read(mode)
            if write_back not in (WriteBack.DIFF, WriteBack.COLOR_DIFF):
                if not cache.is_changed(src):
                    changed = Changed.CACHED
            if changed is not Changed.CACHED and format_file_in_place(
                src, fast=fast, write_back=write_back, mode=mode
            ):
                changed = Changed.YES
            if (write_back is WriteBack.YES and changed is not Changed.CACHED) or (
                write_back is WriteBack.CHECK and changed is Changed.NO
            ):
                cache.write([src])
        report.done(src, changed)
    except Exception as exc:
        if report.verbose:
            traceback.print_exc()
        report.failed(src, str(exc))

def format_file_in_place(
    src: Path,
    fast: bool,
    mode: Mode,
    write_back: WriteBack = WriteBack.NO,
    lock: Any = None,  # multiprocessing.Manager().Lock() is some crazy proxy
) -> bool:
    """Format file under `src` path. Return True if changed.

    If `write_back` is DIFF, write a diff to stdout. If it is YES, write reformatted
    code to the file.
    `mode` and `fast` options are passed to :func:`format_file_contents`.
    """
    if src.suffix == ".pyi":
        mode = replace(mode, is_pyi=True)
    elif src.suffix == ".ipynb":
        mode = replace(mode, is_ipynb=True)

    then = datetime.fromtimestamp(src.stat().st_mtime, timezone.utc)
    header = b""
    with open(src, "rb") as buf:
        if mode.skip_source_first_line:
            header = buf.readline()
        src_contents, encoding, newline = decode_bytes(buf.read())
    try:
        dst_contents = format_file_contents(src_contents, fast=fast, mode=mode)
    except NothingChanged:
        return False
    except JSONDecodeError:
        raise ValueError(
            f"File '{src}' cannot be parsed as valid Jupyter notebook."
        ) from None
    src_contents = header.decode(encoding) + src_contents
    dst_contents = header.decode(encoding) + dst_contents

    if write_back == WriteBack.YES:
        with open(src, "w", encoding=encoding, newline=newline) as f:
            f.write(dst_contents)
    elif write_back in (WriteBack.DIFF, WriteBack.COLOR_DIFF):
        now = datetime.now(timezone.utc)
        src_name = f"{src}\t{then}"
        dst_name = f"{src}\t{now}"
        if mode.is_ipynb:
            diff_contents = ipynb_diff(src_contents, dst_contents, src_name, dst_name)
        else:
            diff_contents = diff(src_contents, dst_contents, src_name, dst_name)

        if write_back == WriteBack.COLOR_DIFF:
            diff_contents = color_diff(diff_contents)

        with lock or nullcontext():
            f = io.TextIOWrapper(
                sys.stdout.buffer,
                encoding=encoding,
                newline=newline,
                write_through=True,
            )
            f = wrap_stream_for_windows(f)
            f.write(diff_contents)
            f.detach()

    return True

def format_stdin_to_stdout(
    fast: bool,
    *,
    content: Optional[str] = None,
    write_back: WriteBack = WriteBack.NO,
    mode: Mode,
) -> bool:
    """Format file on stdin. Return True if changed.

    If content is None, it's read from sys.stdin.

    If `write_back` is YES, write reformatted code back to stdout. If it is DIFF,
    write a diff to stdout. The `mode` argument is passed to
    :func:`format_file_contents`.
    """
    then = datetime.now(timezone.utc)

    if content is None:
        src, encoding, newline = decode_bytes(sys.stdin.buffer.read())
    else:
        src, encoding, newline = content, "utf-8", ""

    dst = src
    try:
        dst = format_file_contents(src, fast=fast, mode=mode)
        return True

    except NothingChanged:
        return False

    finally:
        f = io.TextIOWrapper(
            sys.stdout.buffer, encoding=encoding, newline=newline, write_through=True
        )
        if write_back == WriteBack.YES:
            # Make sure there's a newline after the content
            if dst and dst[-1] != "\n":
                dst += "\n"
            f.write(dst)
        elif write_back in (WriteBack.DIFF, WriteBack.COLOR_DIFF):
            now = datetime.now(timezone.utc)
            src_name = f"STDIN\t{then}"
            dst_name = f"STDOUT\t{now}"
            d = diff(src, dst, src_name, dst_name)
            if write_back == WriteBack.COLOR_DIFF:
                d = color_diff(d)
                f = wrap_stream_for_windows(f)
            f.write(d)
        f.detach()

def check_stability_and_equivalence(
    src_contents: str, dst_contents: str, *, mode: Mode
) -> None:
    """Perform stability and equivalence checks.

    Raise AssertionError if source and destination contents are not
    equivalent, or if a second pass of the formatter would format the
    content differently.
    """
    assert_equivalent(src_contents, dst_contents)
    assert_stable(src_contents, dst_contents, mode=mode)

def format_file_contents(src_contents: str, *, fast: bool, mode: Mode) -> FileContent:
    """Reformat contents of a file and return new contents.

    If `fast` is False, additionally confirm that the reformatted code is
    valid by calling :func:`assert_equivalent` and :func:`assert_stable` on it.
    `mode` is passed to :func:`format_str`.
    """
    if mode.is_ipynb:
        dst_contents = format_ipynb_string(src_contents, fast=fast, mode=mode)
    else:
        dst_contents = format_str(src_contents, mode=mode)
    if src_contents == dst_contents:
        raise NothingChanged

    if not fast and not mode.is_ipynb:
        # Jupyter notebooks will already have been checked above.
        check_stability_and_equivalence(src_contents, dst_contents, mode=mode)
    return dst_contents

def validate_cell(src: str, mode: Mode) -> None:
    """Check that cell does not already contain TransformerManager transformations,
    or non-Python cell magics, which might cause tokenizer_rt to break because of
    indentations.

    If a cell contains ``!ls``, then it'll be transformed to
    ``get_ipython().system('ls')``. However, if the cell originally contained
    ``get_ipython().system('ls')``, then it would get transformed in the same way:

        >>> TransformerManager().transform_cell("get_ipython().system('ls')")
        "get_ipython().system('ls')\n"
        >>> TransformerManager().transform_cell("!ls")
        "get_ipython().system('ls')\n"

    Due to the impossibility of safely roundtripping in such situations, cells
    containing transformed magics will be ignored.
    """
    if any(transformed_magic in src for transformed_magic in TRANSFORMED_MAGICS):
        raise NothingChanged
    if (
        src[:2] == "%%"
        and src.split()[0][2:] not in PYTHON_CELL_MAGICS | mode.python_cell_magics
    ):
        raise NothingChanged

def format_cell(src: str, *, fast: bool, mode: Mode) -> str:
    """Format code in given cell of Jupyter notebook.

    General idea is:

      - if cell has trailing semicolon, remove it;
      - if cell has IPython magics, mask them;
      - format cell;
      - reinstate IPython magics;
      - reinstate trailing semicolon (if originally present);
      - strip trailing newlines.

    Cells with syntax errors will not be processed, as they
    could potentially be automagics or multi-line magics, which
    are currently not supported.
    """
    validate_cell(src, mode)
    src_without_trailing_semicolon, has_trailing_semicolon = remove_trailing_semicolon(
        src
    )
    try:
        masked_src, replacements = mask_cell(src_without_trailing_semicolon)
    except SyntaxError:
        raise NothingChanged from None
    masked_dst = format_str(masked_src, mode=mode)
    if not fast:
        check_stability_and_equivalence(masked_src, masked_dst, mode=mode)
    dst_without_trailing_semicolon = unmask_cell(masked_dst, replacements)
    dst = put_trailing_semicolon_back(
        dst_without_trailing_semicolon, has_trailing_semicolon
    )
    dst = dst.rstrip("\n")
    if dst == src:
        raise NothingChanged from None
    return dst

def validate_metadata(nb: MutableMapping[str, Any]) -> None:
    """If notebook is marked as non-Python, don't format it.

    All notebook metadata fields are optional, see
    https://nbformat.readthedocs.io/en/latest/format_description.html. So
    if a notebook has empty metadata, we will try to parse it anyway.
    """
    language = nb.get("metadata", {}).get("language_info", {}).get("name", None)
    if language is not None and language != "python":
        raise NothingChanged from None

def format_ipynb_string(src_contents: str, *, fast: bool, mode: Mode) -> FileContent:
    """Format Jupyter notebook.

    Operate cell-by-cell, only on code cells, only for Python notebooks.
    If the ``.ipynb`` originally had a trailing newline, it'll be preserved.
    """
    if not src_contents:
        raise NothingChanged

    trailing_newline = src_contents[-1] == "\n"
    modified = False
    nb = json.loads(src_contents)
    validate_metadata(nb)
    for cell in nb["cells"]:
        if cell.get("cell_type", None) == "code":
            try:
                src = "".join(cell["source"])
                dst = format_cell(src, fast=fast, mode=mode)
            except NothingChanged:
                pass
            else:
                cell["source"] = dst.splitlines(keepends=True)
                modified = True
    if modified:
        dst_contents = json.dumps(nb, indent=1, ensure_ascii=False)
        if trailing_newline:
            dst_contents = dst_contents + "\n"
        return dst_contents
    else:
        raise NothingChanged

def format_str(src_contents: str, *, mode: Mode) -> str:
    """Reformat a string and return new contents.

    `mode` determines formatting options, such as how many characters per line are
    allowed.  Example:

    >>> import black
    >>> print(black.format_str("def f(arg:str='')->None:...", mode=black.Mode()))
    def f(arg: str = "") -> None:
        ...

    A more complex example:

    >>> print(
    ...   black.format_str(
    ...     "def f(arg:str='')->None: hey",
    ...     mode=black.Mode(
    ...       target_versions={black.TargetVersion.PY36},
    ...       line_length=10,
    ...       string_normalization=False,
    ...       is_pyi=False,
    ...     ),
    ...   ),
    ... )
    def f(
        arg: str = '',
    ) -> None:
        hey

    """
    dst_contents = _format_str_once(src_contents, mode=mode)
    # Forced second pass to work around optional trailing commas (becoming
    # forced trailing commas on pass 2) interacting differently with optional
    # parentheses.  Admittedly ugly.
    if src_contents != dst_contents:
        return _format_str_once(dst_contents, mode=mode)
    return dst_contents

def _format_str_once(src_contents: str, *, mode: Mode) -> str:
    src_node = lib2to3_parse(src_contents.lstrip(), mode.target_versions)
    dst_blocks: List[LinesBlock] = []
    if mode.target_versions:
        versions = mode.target_versions
    else:
        future_imports = get_future_imports(src_node)
        versions = detect_target_versions(src_node, future_imports=future_imports)

    context_manager_features = {
        feature
        for feature in {Feature.PARENTHESIZED_CONTEXT_MANAGERS}
        if supports_feature(versions, feature)
    }
    normalize_fmt_off(src_node, mode)
    lines = LineGenerator(mode=mode, features=context_manager_features)
    elt = EmptyLineTracker(mode=mode)
    split_line_features = {
        feature
        for feature in {Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF}
        if supports_feature(versions, feature)
    }
    block: Optional[LinesBlock] = None
    for current_line in lines.visit(src_node):
        block = elt.maybe_empty_lines(current_line)
        dst_blocks.append(block)
        for line in transform_line(
            current_line, mode=mode, features=split_line_features
        ):
            block.content_lines.append(str(line))
    if dst_blocks:
        dst_blocks[-1].after = 0
    dst_contents = []
    for block in dst_blocks:
        dst_contents.extend(block.all_lines())
    if not dst_contents:
        # Use decode_bytes to retrieve the correct source newline (CRLF or LF),
        # and check if normalized_content has more than one line
        normalized_content, _, newline = decode_bytes(src_contents.encode("utf-8"))
        if "\n" in normalized_content:
            return newline
        return ""
    return "".join(dst_contents)

def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]:
    """Return a tuple of (decoded_contents, encoding, newline).

    `newline` is either CRLF or LF but `decoded_contents` is decoded with
    universal newlines (i.e. only contains LF).
    """
    srcbuf = io.BytesIO(src)
    encoding, lines = tokenize.detect_encoding(srcbuf.readline)
    if not lines:
        return "", encoding, "\n"

    newline = "\r\n" if b"\r\n" == lines[0][-2:] else "\n"
    srcbuf.seek(0)
    with io.TextIOWrapper(srcbuf, encoding) as tiow:
        return tiow.read(), encoding, newline

def get_features_used(  # noqa: C901
    node: Node, *, future_imports: Optional[Set[str]] = None
) -> Set[Feature]:
    """Return a set of (relatively) new Python features used in this file.

    Currently looking for:
    - f-strings;
    - self-documenting expressions in f-strings (f"{x=}");
    - underscores in numeric literals;
    - trailing commas after * or ** in function signatures and calls;
    - positional only arguments in function signatures and lambdas;
    - assignment expression;
    - relaxed decorator syntax;
    - usage of __future__ flags (annotations);
    - print / exec statements;
    - parenthesized context managers;
    - match statements;
    - except* clause;
    - variadic generics;
    """
    features: Set[Feature] = set()
    if future_imports:
        features |= {
            FUTURE_FLAG_TO_FEATURE[future_import]
            for future_import in future_imports
            if future_import in FUTURE_FLAG_TO_FEATURE
        }

    for n in node.pre_order():
        if is_string_token(n):
            value_head = n.value[:2]
            if value_head in {'f"', 'F"', "f'", "F'", "rf", "fr", "RF", "FR"}:
                features.add(Feature.F_STRINGS)
                if Feature.DEBUG_F_STRINGS not in features:
                    for span_beg, span_end in iter_fexpr_spans(n.value):
                        if n.value[span_beg : span_end - 1].rstrip().endswith("="):
                            features.add(Feature.DEBUG_F_STRINGS)
                            break

        elif is_number_token(n):
            if "_" in n.value:
                features.add(Feature.NUMERIC_UNDERSCORES)

        elif n.type == token.SLASH:
            if n.parent and n.parent.type in {
                syms.typedargslist,
                syms.arglist,
                syms.varargslist,
            }:
                features.add(Feature.POS_ONLY_ARGUMENTS)

        elif n.type == token.COLONEQUAL:
            features.add(Feature.ASSIGNMENT_EXPRESSIONS)

        elif n.type == syms.decorator:
            if len(n.children) > 1 and not is_simple_decorator_expression(
                n.children[1]
            ):
                features.add(Feature.RELAXED_DECORATORS)

        elif (
            n.type in {syms.typedargslist, syms.arglist}
            and n.children
            and n.children[-1].type == token.COMMA
        ):
            if n.type == syms.typedargslist:
                feature = Feature.TRAILING_COMMA_IN_DEF
            else:
                feature = Feature.TRAILING_COMMA_IN_CALL

            for ch in n.children:
                if ch.type in STARS:
                    features.add(feature)

                if ch.type == syms.argument:
                    for argch in ch.children:
                        if argch.type in STARS:
                            features.add(feature)

        elif (
            n.type in {syms.return_stmt, syms.yield_expr}
            and len(n.children) >= 2
            and n.children[1].type == syms.testlist_star_expr
            and any(child.type == syms.star_expr for child in n.children[1].children)
        ):
            features.add(Feature.UNPACKING_ON_FLOW)

        elif (
            n.type == syms.annassign
            and len(n.children) >= 4
            and n.children[3].type == syms.testlist_star_expr
        ):
            features.add(Feature.ANN_ASSIGN_EXTENDED_RHS)

        elif (
            n.type == syms.with_stmt
            and len(n.children) > 2
            and n.children[1].type == syms.atom
        ):
            atom_children = n.children[1].children
            if (
                len(atom_children) == 3
                and atom_children[0].type == token.LPAR
                and atom_children[1].type == syms.testlist_gexp
                and atom_children[2].type == token.RPAR
            ):
                features.add(Feature.PARENTHESIZED_CONTEXT_MANAGERS)

        elif n.type == syms.match_stmt:
            features.add(Feature.PATTERN_MATCHING)

        elif (
            n.type == syms.except_clause
            and len(n.children) >= 2
            and n.children[1].type == token.STAR
        ):
            features.add(Feature.EXCEPT_STAR)

        elif n.type in {syms.subscriptlist, syms.trailer} and any(
            child.type == syms.star_expr for child in n.children
        ):
            features.add(Feature.VARIADIC_GENERICS)

        elif (
            n.type == syms.tname_star
            and len(n.children) == 3
            and n.children[2].type == syms.star_expr
        ):
            features.add(Feature.VARIADIC_GENERICS)

        elif n.type in (syms.type_stmt, syms.typeparams):
            features.add(Feature.TYPE_PARAMS)

    return features

def detect_target_versions(
    node: Node, *, future_imports: Optional[Set[str]] = None
) -> Set[TargetVersion]:
    """Detect the version to target based on the nodes used."""
    features = get_features_used(node, future_imports=future_imports)
    return {
        version for version in TargetVersion if features <= VERSION_TO_FEATURES[version]
    }

def get_future_imports(node: Node) -> Set[str]:
    """Return a set of __future__ imports in the file."""
    imports: Set[str] = set()

    def get_imports_from_children(children: List[LN]) -> Generator[str, None, None]:
        for child in children:
            if isinstance(child, Leaf):
                if child.type == token.NAME:
                    yield child.value

            elif child.type == syms.import_as_name:
                orig_name = child.children[0]
                assert isinstance(orig_name, Leaf), "Invalid syntax parsing imports"
                assert orig_name.type == token.NAME, "Invalid syntax parsing imports"
                yield orig_name.value

            elif child.type == syms.import_as_names:
                yield from get_imports_from_children(child.children)

            else:
                raise AssertionError("Invalid syntax parsing imports")

    for child in node.children:
        if child.type != syms.simple_stmt:
            break

        first_child = child.children[0]
        if isinstance(first_child, Leaf):
            # Continue looking if we see a docstring; otherwise stop.
            if (
                len(child.children) == 2
                and first_child.type == token.STRING
                and child.children[1].type == token.NEWLINE
            ):
                continue

            break

        elif first_child.type == syms.import_from:
            module_name = first_child.children[1]
            if not isinstance(module_name, Leaf) or module_name.value != "__future__":
                break

            imports |= set(get_imports_from_children(first_child.children[3:]))
        else:
            break

    return imports

def assert_equivalent(src: str, dst: str) -> None:
    """Raise AssertionError if `src` and `dst` aren't equivalent."""
    try:
        src_ast = parse_ast(src)
    except Exception as exc:
        raise AssertionError(
            "cannot use --safe with this file; failed to parse source file AST: "
            f"{exc}\n"
            "This could be caused by running Black with an older Python version "
            "that does not support new syntax used in your source file."
        ) from exc

    try:
        dst_ast = parse_ast(dst)
    except Exception as exc:
        log = dump_to_file("".join(traceback.format_tb(exc.__traceback__)), dst)
        raise AssertionError(
            f"INTERNAL ERROR: Black produced invalid code: {exc}. "
            "Please report a bug on https://github.com/psf/black/issues.  "
            f"This invalid output might be helpful: {log}"
        ) from None

    src_ast_str = "\n".join(stringify_ast(src_ast))
    dst_ast_str = "\n".join(stringify_ast(dst_ast))
    if src_ast_str != dst_ast_str:
        log = dump_to_file(diff(src_ast_str, dst_ast_str, "src", "dst"))
        raise AssertionError(
            "INTERNAL ERROR: Black produced code that is not equivalent to the"
            " source.  Please report a bug on "
            f"https://github.com/psf/black/issues.  This diff might be helpful: {log}"
        ) from None

def assert_stable(src: str, dst: str, mode: Mode) -> None:
    """Raise AssertionError if `dst` reformats differently the second time."""
    # We shouldn't call format_str() here, because that formats the string
    # twice and may hide a bug where we bounce back and forth between two
    # versions.
    newdst = _format_str_once(dst, mode=mode)
    if dst != newdst:
        log = dump_to_file(
            str(mode),
            diff(src, dst, "source", "first pass"),
            diff(dst, newdst, "first pass", "second pass"),
        )
        raise AssertionError(
            "INTERNAL ERROR: Black produced different code on the second pass of the"
            " formatter.  Please report a bug on https://github.com/psf/black/issues."
            f"  This diff might be helpful: {log}"
        ) from None

@contextmanager
def nullcontext() -> Iterator[None]:
    """Return an empty context manager.

    To be used like `nullcontext` in Python 3.7.
    """
    yield

def patched_main() -> None:
    # PyInstaller patches multiprocessing to need freeze_support() even in non-Windows
    # environments so just assume we always need to call it if frozen.
    if getattr(sys, "frozen", False):
        from multiprocessing import freeze_support

        freeze_support()

    main()

if __name__ == "__main__":
    patched_main()


"""
Power Curves

These curve functions are written in the style of Scipy.optimize:

fun : callable
The objective function to be minimized.
fun(x, *args) -> float
where x is an 1-D array with shape (n,) and args is a tuple of the fixed parameters needed to completely specify the
function.

ref: https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html#scipy.optimize.minimize

"""

from __future__ import annotations

import numpy as np
import pandas as pd

def _power_curve(x: np.ndarray | pd.Series, a: float, b: float, c: float, d: float, g: float):
    """The actual power curve implementation.

    Args:
        x(:obj:`numpy.ndarray` | `pandas.Series`): input data
        a(:obj:`float`): the minimum value asymptote
        b(:obj:`float`): steepness of the curve
        c(:obj:`float`): the point of inflection
        d(:obj:`float`): the maximum value asymptote
        g(:obj:`float`): asymmetry of the curve

    Returns:
        (:obj:`numpy.ndarray`): The converted power data.
    """
    if isinstance(x, pd.Series):
        x = x.values
    return d + (a - d) / (1 + (x / c) ** b) ** g

def logistic5param(x: np.ndarray | pd.Series, a: float, b: float, c: float, d: float, g: float):
    """Create and return a 5 parameter logistic function

    Args:
        x(:obj:`numpy.ndarray` | `pandas.Series`): Input data.
        a(:obj:`float`): The minimum value asymptote.
        b(:obj:`float`): Steepness of the curve.
        c(:obj:`float`): The point of inflection.
        d(:obj:`float`): The maximum value asymptote.
        g(:obj:`float`): Asymmetry of the curve.

    Returns:
        Function[numpy.ndarray[real]] -> numpy.ndarray[real]

    """

    res = np.ones_like(x, dtype=np.float64)
    # In the case where b<0, x==0, there is a divide by zero error. The answer should be "d" when x==0 and b<0.
    if b < 0:
        res *= d  # Initialize result, default value is d
        dom = x != 0.0  # Only nonzero elements in domain
    else:
        dom = slice(None)  # All elements in domain

    # Apply power curve definition to point within domain
    res[dom] = _power_curve(x[dom], a, b, c, d, g)

    return res

def logistic5param_capped(
    x: np.ndarray | pd.Series,
    a: float,
    b: float,
    c: float,
    d: float,
    g: float,
    lower: float,
    upper: float,
):
    """Create and return a capped 5 parameter logistic function whose output is capped by lower and upper bounds.

    Args:
        x(:obj:`numpy.ndarray` | `pandas.Series`): Input data.
        a(:obj:`float`): The minimum value asymptote.
        b(:obj:`float`): Steepness of the curve.
        c(:obj:`float`): The point of inflection.
        d(:obj:`float`): The maximum value asymptote.
        g(:obj:`float`): Asymmetry of the curve.
        lower(:obj:`float`): Input values below this number are set to this number.
        upper(:obj:`float`): Input values above this number are set to this number.

    Returns:
        Function[numpy.ndarray[real]] -> numpy.ndarray[real]

    """
    return _cap(logistic5param(x, a, b, c, d, g), lower, upper)

"""
Helpers for Power Curve
"""

def _cap(y, lower, upper):
    if type(y) is np.ndarray:
        y = np.where(y < lower, lower, y)
        y = np.where(y > upper, upper, y)
    else:
        y = y.where(y > lower, lower)
        y = y.where(y < upper, upper)
    return y


import sys
import math
import random
print("System platform: " + sys.platform)
print("System version: " + sys.version)
print("This py file for testing dictionary structure only :3")
person = {"name": "Thieu Quang Tuan",
          "gender": "male",
          "occupation": "student",
          "class": "D14CQCN02-N"}

print(person)
print("Name: " + person["name"])
print("Gender: " + person["gender"])
print("Occupation: " + person["occupation"])

person["age"] = 21;
print(person)
for key in person:
    print(person[key])

vowels = ["u", "e", "o", "a"]
foundVowels = {}
word = input("Give me a word: ")
for char in word:
    if char in vowels and char in foundVowels:
        foundVowels[char] += 1
    elif char in vowels and char not in foundVowels:
        foundVowels[char] = 1
print("We test for loop: for key in sorted(foundVowels)")
for key in sorted(foundVowels):
    if foundVowels[key] > 0:
        print(key, "was found ", foundVowels[key], " times")
print("Now test for loop: for key, value in sorted(foundVowels.items())")
for key, value in sorted(foundVowels.items()):
    if value > 0:
        print(key, "was found ", value, " times")
print("found = ", foundVowels)

primeNumbers = {}
isPrimeNumber = True
for i in range(100):
    number = random.randint(1, 100)
    if number < 2:
        isPrimeNumber = False
    for testValue in range(2, int(number/2) + 1, 1):
        if number % testValue == 0:
            isPrimeNumber = False
            break
    if isPrimeNumber:
        primeNumbers.setdefault(number, 0)
        primeNumbers[number] += 1
    isPrimeNumber = True
print(sorted(primeNumbers.items()))
print(primeNumbers)


import jieba

def pingjia():
    with open('comment.txt', 'r', encoding='utf-8') as file:
        text = file.read()

    # 将文本分词
    lists = jieba.lcut(text)

    # 统计词频
    word_freq = {}
    for word in lists:
        if (
                word == '一个' or word == '没有' or word == '他们' or word == '我们' or word == '这个' or word == '自己' or word == '已经' or word == 'pla' or word == 'way'):
            continue
        if (len(word) == 1):
            continue
        if word in word_freq:
            word_freq[word] += 1
        else:
            word_freq[word] = 1

    items = list(word_freq.items())
    items.sort(key=lambda x: x[1], reverse=True)

    for i in range(15):
        word, count = items[i]
        print("{0:<10}{1:>5}".format(word, count))

if __name__ == '__main__':
    pingjia()

test1/期末考试/在线商城的评价分析.py

在线商城的评价分析.py


from pathlib import Path
from typing import Dict

from ...utils import FileBuffer
from ...utils.singleton import SingletonMeta
from .archive import Archive
from .file import File

# Based on yretenai code from https://github.com/yretenai/HFSExtract

class HFSv2(metaclass=SingletonMeta):

    def __init__(self, hfs_root: Path):
        self.files: Dict[str, Archive] = {}
        self._archives: Dict[str, Archive] = {}
        for hfs_file in hfs_root.iterdir():
            if hfs_file.stem in self._archives:
                continue
            buffer = FileBuffer(hfs_file)
            archive = Archive(hfs_file.name)
            archive.read(buffer)
            self._archives[hfs_file.stem] = archive
            self.files.update({k: archive for k in archive.files.keys()})

    def get_file(self, path):
        path = Path(path).as_posix().lower()
        if path in self.files:
            return self.files[path].get_file(path)
        return None

    def has_file(self, path):
        path = Path(path).as_posix()
        return path in self.files