blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
133
path
stringlengths
2
333
src_encoding
stringclasses
30 values
length_bytes
int64
18
5.47M
score
float64
2.52
5.81
int_score
int64
3
5
detected_licenses
listlengths
0
67
license_type
stringclasses
2 values
text
stringlengths
12
5.47M
download_success
bool
1 class
219937ccca517f4b2cff9b90ae9ca28c9d82359c
Python
vikrantuk/Code-Signal
/Arcade/Intro/32_absoluteValuesSumMinimization.py
UTF-8
1,328
4.34375
4
[]
no_license
''' Given a sorted array of integers a, your task is to determine which element of a is closest to all other values of a. In other words, find the element x in a, which minimizes the following sum: abs(a[0] - x) + abs(a[1] - x) + ... + abs(a[a.length - 1] - x) (where abs denotes the absolute value) If there are several possible answers, output the smallest one. Example For a = [2, 4, 7], the output should be absoluteValuesSumMinimization(a) = 4. for x = 2, the value will be abs(2 - 2) + abs(4 - 2) + abs(7 - 2) = 7. for x = 4, the value will be abs(2 - 4) + abs(4 - 4) + abs(7 - 4) = 5. for x = 7, the value will be abs(2 - 7) + abs(4 - 7) + abs(7 - 7) = 8. The lowest possible value is when x = 4, so the answer is 4. For a = [2, 3], the output should be absoluteValuesSumMinimization(a) = 2. for x = 2, the value will be abs(2 - 2) + abs(3 - 2) = 1. for x = 3, the value will be abs(2 - 3) + abs(3 - 3) = 1. Because there is a tie, the smallest x between x = 2 and x = 3 is the answer. ''' def absoluteValuesSumMinimization(a): elment = -1 total= float('inf') for el in a: temp=0 for i in range(len(a)): temp+= abs(a[i]-el) if(temp<total): total=temp elment=el elif(temp==total): elment=min(elment,el) return(elment)
true
3f77ccab7ba01aedb98101951dfe4f0230e6fa54
Python
suchareq3/covid-vaccination-map
/main.py
UTF-8
11,670
3.078125
3
[]
no_license
""" Generates a world map with worldwide vaccination data in the form of a .svg file. Vaccination data is based on the user-given date and other preferences specified by the user. """ import csv import json import os.path import sys from datetime import datetime import pygal import requests from pygal.style import Style from requests import get from tqdm import tqdm def main(): print("Connecting to Github to check for data updates...") update_data() with open("vaccinations.json") as vacc_data_file, \ open("population_2020.csv") as pop_data_file, \ open("owid_to_pygal.json") as format_file: vacc_data = json.load(vacc_data_file) area_codes = json.load(format_file) print("\nWelcome! This program generates a world map full of vaccination data\n" "in the form of a .svg file in the same location as main.py\n" "based on your user-given date and vaccination type.\n") newest_date = datetime.fromtimestamp(os.path.getmtime("vaccinations.json")).strftime("%Y-%m-%d") user_date = take_date(newest_date) area_type = take_user_preference(["country", "continent"], "area type (COUNTRIES or CONTINENTS)") vacc_doses = take_user_preference(["one dose", "all doses"], "vaccination doses (ONE dose or ALL doses)") valid_areas, invalid_areas = collect_data(vacc_data, pop_data_file, area_codes, user_date, vacc_doses, area_type) generate_map(valid_areas, invalid_areas, user_date, area_type, vacc_doses) input("Done! To see the result, open the newly generated vaccmap.svg with a browser.\n" "Press any key to quit...") def update_data(): """ Connects to Github via the internet to determine data's freshness Presents the user with a choice to download updated data files """ file_paths = {"vaccinations.json": "public/data/vaccinations/vaccinations.json", "population_2020.csv": "scripts/input/un/population_2020.csv"} for file_name, remote_path in file_paths.items(): while True: try: local_file_date = datetime.fromtimestamp(os.path.getmtime(file_name)) api_url = f"https://api.github.com/repos/owid/covid-19-data/commits?path={remote_path}&per_page=1" last_updated = requests.get(api_url).json()[0]['commit']['committer']['date'] remote_file_date = datetime.strptime(last_updated, "%Y-%m-%dT%H:%M:%SZ") day_difference = (remote_file_date - local_file_date).days if day_difference >= 0: choice = input(f"{file_name} is OUTDATED. It's roughly {str(day_difference + 1)} days old. " "Would you like to update it? (Y/N): ") if "y" in choice.lower(): download_file(file_name, remote_path) break except requests.exceptions.ConnectionError: print("CAN'T CONNECT TO THE INTERNET! Your files might be out of date. " "Try checking your internet connection or Github's status.") return except PermissionError: input(f"PERMISSION ERROR! Cannot access {file_name}. " "It might be open in another program - try closing it, then launch main.py again.\n" "Press any key to quit...") sys.exit(0) except FileNotFoundError: choice = input(f"CANNOT FIND {file_name}! It is required to run the program.\n" "Would you like to download it from Github? (Y/N): ") if "y" in choice.lower(): try: download_file(file_name, remote_path) except requests.exceptions.ConnectionError: input("CAN'T CONNECT TO THE INTERNET EITHER! :(\n" "Try checking your internet connection or Github's status.\n" "Quitting program...") sys.exit(0) else: input("Understood. Quitting program.\n" "Press any key to quit...") sys.exit(0) def download_file(file_name, remote_path): """ An extension of download_data() Downloads specific file from OWID's 'covid-19-data' repo """ download_url = f"https://github.com/owid/covid-19-data/raw/master/{remote_path}" downloaded_data = get(download_url, stream=True) progress = tqdm(unit="B", unit_scale=True, unit_divisor=1024, desc=file_name) with open(file_name, "wb") as f: for chunk in downloaded_data.iter_content(chunk_size=1024): data_size = f.write(chunk) progress.update(data_size) progress.close() def take_date(newest_date): """ Receives a valid date from user input and returns it as a "datetime" object """ lower_end_date = datetime.strptime("2020-12-08", "%Y-%m-%d") higher_end_date = datetime.strptime(newest_date, "%Y-%m-%d") print("NOTE: The date has to be between 2020-12-08 and " + newest_date + ".") counter = 0 while True: if counter >= 3: print("3 consecutive incorrect responses recorded!\n" "Picking the default value (" + newest_date + ")...\n") return higher_end_date try: counter += 1 user_date = input("Type date here (YYYY-mm-dd): ") conv_user_date = datetime.strptime(user_date, "%Y-%m-%d") # datetime.strptime causes a ValueError if the format is incorrect except ValueError: print("Incorrect date format!") else: date_is_correct = lower_end_date <= conv_user_date <= higher_end_date if date_is_correct: return conv_user_date print("Incorrect date!") def take_user_preference(choices, pref_name): """ Records user preference from a list of choices If user keeps picking incorrect choices, picks the first choice as the default one Returns it as a string to be used in other functions """ counter = 0 while True: if counter >= 3: print("3 consecutive incorrect responses recorded!\n" "Picking the default value (" + choices[0].upper() + ")...\n") return choices[0] response = input("Type " + pref_name + " here: ").lower() if len(response) >= 3: for choice in choices: if response[0:3] in choice: return choice counter += 1 print("Response incorrect or too short!") def collect_data(vacc_data, pop_data_file, area_codes, user_date, vacc_doses, area_type): """ Collects data from the main data file based on provided user preferences Returns a table of processed data to be used in generate_map """ valid_areas = {} invalid_areas = {} pop_data = csv.DictReader(pop_data_file) for country in vacc_data: # TODO: reduce the IFS here OWID_area_code = country["iso_code"] if OWID_area_code not in area_codes: continue if area_type == "country": if OWID_area_code.startswith("OWID"): continue else: if not OWID_area_code.startswith("OWID"): continue total_pop = check_population(OWID_area_code, pop_data, pop_data_file) area_data = country["data"][::-1] area_code = area_codes[OWID_area_code] valid_areas[area_code] = calc_vacc_perc(total_pop, vacc_doses, area_data, user_date) if area_code not in valid_areas or valid_areas[area_code] == 0: invalid_areas[area_code] = valid_areas.pop(area_code, 0) invalid_areas = fill_map_holes(invalid_areas, valid_areas) return valid_areas, invalid_areas def check_population(OWID_area_code, pop_data, pop_data_file): """ Takes country's area code from vaccinations.json Returns country's population number from population_2020.csv """ for country in pop_data: if country['iso_code'] == OWID_area_code: # DictReader's iterator doesn't reset on its own, I have to do it manually with seek() pop_data_file.seek(0) return int(country['population']) return 0 def calc_vacc_perc(total_pop, vacc_doses, area_data, user_date): """ An extension of collect_data() 1) Determines whether data exists for the given country and given day. a) if it doesn't exist for the given day, attempt to find data within the last 21 days 2) Calculates vaccination percentage and returns that into the current country's value """ first_available_date = datetime.strptime(area_data[0]["date"], "%Y-%m-%d") delta = (user_date - first_available_date).days for i in range(0, (22 - delta)): day = area_data[i] # TODO: see if there's a better looking alternative for these ifs vacc_pop = 0 if "one" in vacc_doses: if "people_vaccinated" in day: vacc_pop = day["people_vaccinated"] else: if "people_fully_vaccinated" in day: vacc_pop = day["people_fully_vaccinated"] return round((vacc_pop / total_pop) * 100, 2) return 0 def fill_map_holes(invalid_areas, valid_areas): """ An extension of collect_data() Determines which countries on the Pygal map weren't "mentioned" during the assignment process Then assigns them to invalid_areas, filling out any potential non-assigned countries on the map """ with open("pygal-areas.csv", 'r', encoding='utf-8-sig', newline='') as file: for pygal_area in file: pygal_area = pygal_area.strip() if pygal_area not in invalid_areas and pygal_area not in valid_areas: invalid_areas[pygal_area] = 0 return invalid_areas def generate_map(valid_areas, invalid_areas, user_date, area_type, vacc_doses): """ Determines the style (colors) to be used in the world map Then, using data from collect_data(), generates a .svg file with the world map. """ if area_type == "country": custom_style = Style(colors=('rgb(22, 152, 40)', '#BBBBBB')) worldmap = pygal.maps.world.World(style=custom_style) worldmap.add('% vaccinated', valid_areas) # Continents and their colors are handled differently # (This makes me wish I chose something else instead of Pygal lol it's such a mess) else: values = [] for value in valid_areas.values(): values.append("rgba(22, 152, 40, " + str((value / 100) + 0.15) + ")") values.append("#BBBBBB") custom_style = Style(colors=values) worldmap = pygal.maps.world.SupranationalWorld(style=custom_style) for continent, value in valid_areas.items(): worldmap.add(continent.title().replace("_", " "), [(continent, value)]) worldmap.add('No data', invalid_areas) date = datetime.strftime(user_date, '%Y-%m-%d') worldmap.title = f"{area_type.title()} vaccination data ({vacc_doses.upper()}) for {date}" worldmap.render_to_file('vaccmap.svg') if __name__ == '__main__': main()
true
f9ab4ec040b7323863a2183b49fc4eb70b7a8d60
Python
zhengnengjin/python_Learning
/Day26/编码拾遗.py
UTF-8
620
3.578125
4
[]
no_license
#__author: ZhengNengjin #__date: 2018/10/16 # Py3:str bytes # str: unicode # bytes: 十六进制 a = 'hello郑能锦' print(type(a)) # <class 'str'> '''str>>>>>bytes : 编码''' b = bytes(a,'utf8') #utf8规则下的bytes类型 print(b) #b'hello\xe9\x83\x91\xe8\x83\xbd\xe9\x94\xa6' b2 = a.encode('utf8') print(b2)#b'hello\xe9\x83\x91\xe8\x83\xbd\xe9\x94\xa6' '''bytes>>>>>str : 解码''' #解码的第一种方式 a = str(b2, "utf8") print(a) #hello郑能锦 #解码的第二张方式 a2 = b2.decode("utf8") print(a2) #hello郑能锦 '''按照什么规则编码就得按照什么规则解码'''
true
d82518095beab44de9451a184c034c043126aeca
Python
fgpiaui/vacinaDados
/cidade.py
UTF-8
7,624
2.8125
3
[]
no_license
from colunas import * class Cidade: def __init__(self, df, municipios): self.df = df self.municipios = municipios self.municipios['doses'] = self.municipios['populacao']*2 self.dicionario_cidade = dict.fromkeys(list(self.df['estabelecimento_municipio_nome'] .unique()), dict()) def taxa_doses_por_cidade(self, df): df_doses_por_populacao = df.set_index('estabelecimento_municipio_nome') \ .join(self.municipios.set_index('nome')) df_doses_por_populacao.index.name = 'cidade' df_doses_por_populacao['quantidade_vacina'] = df_doses_por_populacao['quantidade_vacina'].astype('int64') df_doses_por_populacao['populacao'] = df_doses_por_populacao['populacao'].astype('int64') df_doses_por_populacao['taxa'] = df_doses_por_populacao['quantidade_vacina'] / df_doses_por_populacao['populacao'] df_doses_por_populacao['taxa'] = (df_doses_por_populacao['taxa'] * 100).round(2) df_doses_por_populacao = df_doses_por_populacao.reset_index()[['cidade', 'vacina_descricao_dose','taxa']] self.dicionario_cidade={ 'top_2_dose': list(df_doses_por_populacao[df_doses_por_populacao['vacina_descricao_dose']=='    2ª Dose'].sort_values( 'taxa', ascending=False).head().T.to_dict().values()), 'top_1_dose': list(df_doses_por_populacao[df_doses_por_populacao['vacina_descricao_dose'] == '    1ª Dose'].sort_values( 'taxa', ascending=False).head().T.to_dict().values()), } return df_doses_por_populacao def vacinas_aplicadas(self, coluna): colunas = ['estabelecimento_municipio_nome', coluna] df_vacinas_nome_quantidade = self.df.groupby(colunas)['estabelecimento_municipio_nome']\ .count()\ .reset_index(name='quantidade_vacina') df_vacinas_nome_quantidade['percentual'] = \ df_vacinas_nome_quantidade['quantidade_vacina']/ df_vacinas_nome_quantidade\ .groupby('estabelecimento_municipio_nome').transform('sum')['quantidade_vacina'] if coluna == 'paciente_idade': df_vacinas_nome_quantidade = df_vacinas_nome_quantidade.sort_values(by=['paciente_idade']) else: df_vacinas_nome_quantidade = df_vacinas_nome_quantidade.sort_values(by=['quantidade_vacina']) if coluna == 'paciente_enumsexobiologico': df_vacinas_nome_quantidade[coluna] = df_vacinas_nome_quantidade[coluna]\ .replace({'F':'Feminino', 'M':'Masculino'}) return df_vacinas_nome_quantidade def vacinacao_por_data(self): df_data_vacinacao = self.df.groupby(vacina_endereco)['estabelecimento_municipio_nome'].count()\ .reset_index(name='quantidade_vacina') df_data_vacinacao['vacinacao_total_diaria'] = \ df_data_vacinacao.groupby(['estabelecimento_municipio_nome'])['quantidade_vacina'].cumsum() df_data_vacinacao['media_movel'] = \ df_data_vacinacao.groupby(['estabelecimento_municipio_nome']) \ .rolling(7)['quantidade_vacina'].mean().fillna(0).round(2).reset_index()['quantidade_vacina'] return df_data_vacinacao def taxa_vacinacao_por_cidade(self): contagem = self.df.groupby(cidade_estado)['estabelecimento_municipio_nome'].count() \ .reset_index(name='quantidade_vacina') \ .sort_values(['estabelecimento_uf', 'quantidade_vacina'], ascending=[True, False]) df_taxa_vacinacao = contagem.set_index('estabelecimento_municipio_nome') \ .join(self.municipios.set_index('nome')) df_taxa_vacinacao.index.name = 'cidade' df_taxa_vacinacao = df_taxa_vacinacao[['quantidade_vacina', 'populacao', 'doses']] df_taxa_vacinacao = df_taxa_vacinacao.astype('int64') # print(df_taxa_vacinacao.dtypes) df_taxa_vacinacao['taxa_vacinacao'] = df_taxa_vacinacao['quantidade_vacina'] / df_taxa_vacinacao['doses'] df_taxa_vacinacao['taxa_vacinacao'] = (df_taxa_vacinacao['taxa_vacinacao']*100).round(2) return df_taxa_vacinacao def cria_dicionario(self, vacinas, df_taxa_vacinacao, vacinas_aplicadas, raca_aplicada, sexo_aplicada, idade_aplicada, descricao_dose): for c in df_taxa_vacinacao.index.values: populacao = df_taxa_vacinacao.at[c, 'populacao'] quantidade_vacina = df_taxa_vacinacao.at[c, 'quantidade_vacina'] taxa_vacinacao = df_taxa_vacinacao.at[c, 'taxa_vacinacao'] doses = df_taxa_vacinacao.at[c, 'doses'] vacina_cidade = self.trata_dataframe_cidade(vacinas, c) vacinas_aplicadas_cidade = self.trata_dataframe_cidade(vacinas_aplicadas, c) raca_aplicada_cidade = self.trata_dataframe_cidade(raca_aplicada, c) sexo_aplicada_cidade = self.trata_dataframe_cidade(sexo_aplicada, c) idade_aplicada_cidade = self.trata_dataframe_cidade(idade_aplicada, c) descricao_dose_cidade = self.trata_dataframe_cidade(descricao_dose, c, doses=True) descricao_dose_cidade['per_populacao'] = (100*(descricao_dose_cidade['quantidade_vacina']/populacao)).round(2) vacinas_aplicadas_cidade = self.type_string(self.trata_dataframe_campo(vacinas_aplicadas_cidade, ['vacina_nome'])) raca_aplicada_cidade = self.type_string(self.trata_dataframe_campo(raca_aplicada_cidade, ['paciente_racacor_valor'])) sexo_aplicada_cidade = self.type_string(self.trata_dataframe_campo(sexo_aplicada_cidade, ['paciente_enumsexobiologico'])) idade_aplicada_cidade = self.type_string(self.trata_dataframe_campo(idade_aplicada_cidade, ['paciente_idade'])) descricao_dose_cidade = self.type_string(self.trata_dataframe_campo(descricao_dose_cidade, ['vacina_descricao_dose','per_populacao'])) datas = list(vacina_cidade['vacina_dataaplicacao']) quantidade_vacinas = list(vacina_cidade['quantidade_vacina']) quantidade_vacinas_total = list(vacina_cidade['vacinacao_total_diaria']) media_movel = list(vacina_cidade['media_movel']) self.dicionario_cidade[c] = { 'taxa_vacinacao': taxa_vacinacao, 'quantidade_vacina': str(quantidade_vacina), 'populacao': str(populacao), 'doses':str(doses), 'datas': datas, 'quantidade_vacinas': quantidade_vacinas, 'quantidade_vacinas_total':quantidade_vacinas_total, 'media_movel':media_movel, 'vacinas_aplicadas':list(vacinas_aplicadas_cidade.T.to_dict().values()), 'raca_aplicada_cidade':list(raca_aplicada_cidade.T.to_dict().values()), 'sexo_aplicada_cidade':list(sexo_aplicada_cidade.T.to_dict().values()), 'idade_aplicada_cidade':list(idade_aplicada_cidade.T.to_dict().values()), 'descricao_dose_cidade':list(descricao_dose_cidade.T.to_dict().values()), } @staticmethod def type_string(df): df['quantidade_vacina'] = df['quantidade_vacina'].astype('str') return df @staticmethod def trata_dataframe_cidade(df, c, doses=False): df = df[df['estabelecimento_municipio_nome'] == c] return df @staticmethod def trata_dataframe_campo(df, campo): campo.extend(['quantidade_vacina', 'percentual']) df = df[campo] return df
true
c0017f11d6e18e811f6ed696e9982ffb534bacbc
Python
uberscientist/activetick_http
/activetick_http/__init__.py
UTF-8
14,662
2.859375
3
[ "MIT" ]
permissive
from . quote_fields import quote_definitions, quote_dtypes from io import StringIO import pandas as pd import numpy as np from datetime import datetime, timedelta from requests import Session # TODO look into read_csv use_cols option for speedups # TODO Fix doc comment formatting on methods class ActiveTick: def __init__(self, host='127.0.0.1', port=5000, cache=False): # Active tick HTTP proxy config self.host = host self.port = port self.r = Session() self.cache = cache self._date_fmt = '%Y%m%d%H%M%S' # Contains generator for stream once requested self.stream_ = None def _date_wrap(self, date): # wrapper to allow for np.datetime64 and convert to string ts = pd.to_datetime(str(date)) return ts.strftime(self._date_fmt) def _format_symbols(self, symbols): """ symbols - string (returns unchanged) or list of symbols to concat with + symbols (string, list) Formats list of symbols for ActiveTick URL :param symbols: :return: String """ if not isinstance(symbols, str): symbols = '+'.join(symbols) return symbols def _date_parser(self, date_format): """ Date parser function factory for pandas csv parsing of ActiveTick data :param date_format: Format used for parsing date (string) :return: (list of datetimes) """ def date_parser(dates): return [ datetime.strptime(date, date_format) for date in dates ] return date_parser def quoteData(self, symbols, quoteFields): """ symbols - Symbol (or iterable of multiple symbols) for contracts, ie SPY, AAPL--130308C00440000 (string, iter) quote_fields - List of all fields of interest (string, list) # Example: # look to quoteFields.py for the lookup table used and available fields atClient.quoteData('SPY', ['LastPrice' , 'BidSize', 'AskSize']) # returns pandas DataFrame with columns named :return: pandas.DataFrame() indexed on the symbol column with columns with requested quoteFields with extra status meta data regarding the request and symbols, to just get a DataFrame with the requested fields quoteData('SPY', fields)[fields] """ names = ['symbol', 'symbol_status'] def __name_fmt(names, field): names += ["{f}_field_id".format(f=field), "{f}_status".format(f=field), "{f}_datatype".format(f=field), "{f}".format(f=field)] return names if not isinstance(quoteFields, str): # Create column names from quoteFields for field in quoteFields: names = __name_fmt(names, field) # TODO: Declare specific dtypes for each column in names # Translate from human readable quoteFields to IDs quoteFields = map(lambda field: quote_definitions[field], quoteFields) quoteFields = '+'.join(quoteFields) else: # Only one quoteField as string names = __name_fmt(names, quoteFields) quoteFields = quote_definitions[quoteFields] url = "http://{host}:{port}/quoteData?symbol={symbols}&field={quoteFields}".format( host=self.host, port=self.port, symbols=self._format_symbols(symbols), quoteFields=quoteFields ) # GET request is made and the CSV is read into a Pandas DataFrame df = pd.read_csv(url, header=None, names=names, index_col='symbol') return df def quoteStream(self, symbols, timeout=None): """ symbols - string or iter of symbols # Example # res is an instance of requests iter_lines() res = at.quoteStream('SPY') for quote in res: print(quote) :param timeout: integer, how many seconds to keep connection open :return: returns lazy iterator see requests iter_lines() that can be looped over to access streaming data """ # TODO: Start, pause, stop quote stream def __tickParse(tick): tick = tick.decode('utf-8') if tick[0] is 'Q': names = ['type', 'symbol', 'cond', 'bid_ex', 'ask_ex', 'bid', 'ask', 'bidz', 'askz', 'datetime'] dtype = {'type': object, 'symbol': object, 'cond': np.uint8, 'bid_ex': object, 'ask_ex': object, 'bid': np.float32, 'ask': np.float32, 'bidz': np.uint32, 'askz': np.uint32, 'datetime': object} else: names = ['type', 'symbol', 'flags', 'cond1', 'cond2', 'cond3', 'cond4', 'last_ex', 'last', 'lastz', 'datetime'] dtype = { 'type': object, 'symbol': object, 'flags': object, 'cond1': np.int8, 'cond2': np.int8, 'cond3': np.int8, 'cond4': np.int8, 'last_ex': object, 'last': np.float32, 'lastz': np.uint32 } date_format = '%Y%m%d%H%M%S%f' parse_date = self._date_parser(date_format) return pd.read_csv(StringIO(tick), names=names, index_col='type', dtype=dtype, parse_dates=['datetime'], date_parser=parse_date) url = 'http://{host}:{port}/quoteStream?symbol={symbols}'.format( host=self.host, port=self.port, symbols=self._format_symbols(symbols) ) self.stream_ = self.r.get(url, stream=True, timeout=timeout) pandas_stream = map(__tickParse, self.stream_.iter_lines()) first_line = next(pandas_stream) return pandas_stream def barData(self, symbol, historyType='I', intradayMinutes=60, beginTime=datetime(datetime.now().year, datetime.now().month, 1), endTime=datetime.now()): """ :param symbol: Takes only one symbol, string :param historyType: Takes 'I', 'D' or 'W' as a string (Intraday 0, Daily 1 or Weekly 0) :param intradayMinutes: If historyType is 'I' select a bar size: 0 to 60 minutes (int) :param beginTime: Beginning date for query (datetime) :param endTime: Ending date for query (datetime) :return: Pandas DataFrame OHLCV indexed on the datetime """ history_lookup = { 'I': 0, 'D': 1, 'W': 2 } def __getIntradayMinutesAttr(): # Returns URL segment for intraday minutes if needed if historyType is not 'I': attr_str = '' else: attr_str = 'intradayMinutes={intradayMinutes}&'.format(intradayMinutes=str(intradayMinutes)) return attr_str beginTime_s = self._date_wrap(beginTime) endTime_s = self._date_wrap(endTime) cache_key = "AT:BARDATA:{symbol}:{historyType}:{intradayMinutes}:{beginTime}:{endTime}" cache_key = cache_key.format( symbol=symbol, historyType=history_lookup[historyType], intradayMinutes=intradayMinutes, beginTime=beginTime_s, endTime=endTime_s) # If the data is cached if self.cache and self.cache.exists(cache_key): return pd.read_msgpack(self.cache.get(cache_key)) url = 'http://{host}:{port}/barData?symbol={symbol}&historyType={historyType}' \ '&{intradayMintuesAttr}beginTime={beginTime}&endTime={endTime}' url = url.format( host=self.host, port=self.port, symbol=symbol, historyType=history_lookup[historyType], intradayMintuesAttr=__getIntradayMinutesAttr(), beginTime=beginTime_s, endTime=endTime_s) dtypes = {'datetime': object, 'open': np.float32, 'high': np.float32, 'low': np.float32, 'close': np.float32, 'volume': np.uint32} df = pd.read_csv(url, header=None, names=['datetime', 'open', 'high', 'low', 'close', 'volume'], index_col='datetime', parse_dates=['datetime'], dtype=dtypes) # Cache the data if self.cache: self.cache.set(cache_key, df.to_msgpack(compress='zlib')) return df def tickData(self, symbol, trades=False, quotes=True, beginTime=datetime.now() - timedelta(minutes=15), endTime=datetime.now()): """ Gets tick level data in between a time range, limited to returning 100,000 quotes/trades at a time :param symbol: String, ticker for symbol in ActiveTick format :param trades: Boolean, whether to return trade ticks :param quotes: Boolean whether to return quote ticks :param beginTime: datetime beginning of date range :param endTime: datetime end of date range :return: """ tick_date_fmt = '%Y%m%d%H%M%S%f' date_parser = self._date_parser(tick_date_fmt) q_names = ['type', 'datetime', 'bid', 'ask', 'bidz', 'askz', 'bidx', 'askx', 'cond'] t_names = ['type', 'datetime', 'last', 'lastz', 'lastx', 'cond1', 'cond2', 'cond3', 'cond4'] def __get_trades(df): trades_df = df[df[0] == 'T'].copy() trades_df.columns = t_names trades_df.loc[:, 'last'] = trades_df.loc[:, 'last'].astype(np.float32) trades_df.loc[:, 'lastz'] = trades_df.loc[:, 'lastz'].astype(np.uint32) trades_df.loc[:, ['cond1', 'cond2', 'cond3', 'cond4']] = trades_df.loc[:, ['cond1', 'cond2', 'cond3', 'cond4']].astype(np.uint8) return trades_df def __get_quotes(df): quotes_df = df[df[0] == 'Q'].copy() quotes_df.columns = q_names quotes_df.loc[:, ['bid', 'ask']] = quotes_df.loc[:, ['bid', 'ask']].astype(np.float32) quotes_df.loc[:, ['bidz', 'askz']] = quotes_df.loc[:, ['bidz', 'askz']].astype(np.uint32) quotes_df.loc[:, 'cond'] = quotes_df.loc[:, 'cond'].astype(np.uint8) return quotes_df def __at_request(url, names): if(names): date_col = 'datetime' else: date_col = 1 del q_names[1] del t_names[1] try: df = pd.read_csv(url, header=None, engine='c', index_col=date_col, parse_dates=[date_col], names=names, date_parser=date_parser) return df except Exception as e: print('caught exception:', e) print('No or malformed data: ', url) return pd.DataFrame() if not trades and not quotes: return pd.DataFrame() beginTime_s = self._date_wrap(beginTime) endTime_s = self._date_wrap(endTime) cache_key = 'AT:TICKDATA:{symbol}:{trades}:{quotes}:{beginTime}:{endTime}' cache_key = cache_key.format( symbol=symbol, trades=int(trades), quotes=int(quotes), beginTime=beginTime_s, endTime=endTime_s ) # Return cached data if self.cache and self.cache.exists(cache_key): return pd.read_msgpack(self.cache.get(cache_key)) # Retrieve data not found in cache else: url = 'http://{host}:{port}/tickData?symbol={symbol}&trades={trades}' \ '&quotes={quotes}&beginTime={beginTime}&endTime={endTime}' url = url.format( host=self.host, port=self.port, symbol=symbol, trades=int(trades), quotes=int(quotes), beginTime=beginTime_s, endTime=endTime_s ) # Quote column names if quotes and not trades: df = __at_request(url, q_names) # Trade columns names if trades and not quotes: df = __at_request(url, t_names) if trades and quotes: df = __at_request(url, None) if not df.empty: df = __get_trades(df).append(__get_quotes(df)).sort_index(axis=0) if self.cache: self.cache.set(cache_key, df.to_msgpack(compress='zlib')) return df def optionChain(self, symbol): """ Returns unnamed pandas dataframe of option symbols currently listed for underlying symbol :param symbol: String, ticker symbol for underlying :return: Raw unnamed dataframe from ActiveTick """ url = 'http://{host}:{port}/optionChain?symbol={symbol}'.format( host=self.host, port=self.port, symbol=symbol) df = pd.read_csv(url) return df __version__ = '0.12.1' __url__ = 'https://github.com/uberscientist/activetick_http' if __name__ == '__main__': print('ActiveTick Python Module' + __version__ + ', attaches to ActiveTick HTTP Proxy, returns Pandas DataFrames.\n' 'http://www.activetick.com/activetick/contents/PersonalServicesDataAPIDownload.aspx', 'Git repo:' + __url__, 'Uses pytest for tests.\n', 'Has optional (recommended) Redis (http://redis.io) caching built in..', sep='\n')
true
f022cd49fa1078d7a7b717dc610679c440fc282d
Python
eduardo-duran/automizer-crontab-parser
/tests/test_period_day.py
UTF-8
4,708
3.09375
3
[]
no_license
import unittest from application.services.period_day import PeriodDay from domain.schedule import Schedule class TestPeriodDay(unittest.TestCase): def test_getHours_with_startHour_8(self): startHour = '8' dummy = '' period = createPeriod( dummy, startHour, dummy ) hours = period.getHours() expected = "8" self.assertEqual( expected, hours ) def test_getMinutes_with_startMinute_10(self): startMinute = '10' dummy = '' period = createPeriod( dummy, dummy, startMinute ) minutes = period.getMinutes() expected = "10" self.assertEqual( expected, minutes ) def test_getDaysOfWeek_with_one_value(self): days_of_week = '2' dummy = '' period = createPeriod( days_of_week, dummy, dummy ) days = period.getDaysOfWeek() expected = "1" self.assertEqual( expected, days ) def test_getDaysOfWeek_with_two_values(self): days_of_week = '2,3' dummy = '' period = createPeriod( days_of_week, dummy, dummy ) days = period.getDaysOfWeek() expected = "1,2" self.assertEqual( expected, days ) def test_getDaysOfWeek_with_zero_runDays_throw_exception(self): days_of_week = '0' dummy = '' period = createPeriod( days_of_week, dummy, dummy ) self.assertRaises( SystemExit, period.getDaysOfWeek ) def test_getDaysOfWeek_with_empty_runDays_throw_exception(self): days_of_week = '' dummy = '' period = createPeriod( days_of_week, dummy, dummy ) self.assertRaises( SystemExit, period.getDaysOfWeek ) def test_getDaysOfWeek_with_one_value_7_runDays_returns_6(self): days_of_week = '7' dummy = '' period = createPeriod( days_of_week, dummy, dummy ) days = period.getDaysOfWeek() expected = "6" self.assertEqual( expected, days ) def test_getDaysOfWeek_with_two_values_with_7_runDays_returns_correctly(self): days_of_week = '4,7' dummy = '' period = createPeriod( days_of_week, dummy, dummy ) days = period.getDaysOfWeek() expected = "3,6" self.assertEqual( expected, days ) def test_getDaysOfWeek_with_five_values_with_a_7_in_runDays_returns_correctly(self): days_of_week = '2,3,4,5,7' dummy = '' period = createPeriod( days_of_week, dummy, dummy ) days = period.getDaysOfWeek() expected = "1,2,3,4,6" self.assertEqual( expected, days ) def test_getDaysOfMonth_is_ignored_and_returns_star(self): dummy = 'any value' period = createPeriod( dummy, dummy, dummy ) days = period.getDaysOfMonth() expected = "*" self.assertEqual( expected, days ) def test_getMonths_is_ignored_and_returns_star(self): dummy = 'any value' period = createPeriod( dummy, dummy, dummy ) days = period.getMonths() expected = "*" self.assertEqual( expected, days ) def test_getFormula_with_one_day(self): runDaysOfWeek = '1' startHour = '16' startMinute = '4' period = createPeriod( runDaysOfWeek, startHour, startMinute ) formula = period.getFormula() expected = '4 16 * * 0' self.assertEqual( expected, formula ) def test_getFormula_with_two_days(self): runDaysOfWeek = '4,5' startHour = '2' startMinute = '52' period = createPeriod( runDaysOfWeek, startHour, startMinute ) formula = period.getFormula() expected = '52 2 * * 3,4' self.assertEqual( expected, formula ) def test_getFormula_with_four_days_returns_correctly(self): runDaysOfWeek = '2,4,5,7' startHour = '5' startMinute = '44' period = createPeriod( runDaysOfWeek, startHour, startMinute ) formula = period.getFormula() expected = '44 5 * * 1,3,4,6' self.assertEqual( expected, formula ) def createPeriod( runDaysOfWeek, startHour, startMinute ): schedule = Schedule.createDaySchedule ( runDaysOfWeek, startHour, startMinute ) return PeriodDay( schedule ) if __name__ == '__main__': unittest.main()
true
d1d32d0ac8d882d65f52f030e725f5394414ad9c
Python
ksu-is/Commute-Traffic-Twitter-Bot
/Practice/twitter_practice2.py
UTF-8
1,927
2.734375
3
[]
no_license
import sys import tweepy import keys import datetime, time import tkinter as tk auth = tweepy.OAuthHandler(keys.TWITTER_APP_KEY, keys.TWITTER_APP_SECRET) auth.set_access_token(keys.TWITTER_KEY, keys.TWITTER_SECRET) api = tweepy.API(auth) def get_tweets(api,username): display_message = "" try: stuff = api.user_timeline(screen_name = username, count = 4, include_rts = False) for status in stuff: display_message += status.text + "\n\n" return display_message except tweepy.TweepError as e: display_message = "Something went wrong.." return display_message #set up tkinter framework (buttons, label, whatever) HEIGHT = 600 WIDTH = 600 root = tk.Tk() canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH) canvas.pack() background_image = tk.PhotoImage(file='blue_background.png') background_label = tk.Label(root, image=background_image) background_label.place(relwidth=1, relheight=1) frame = tk.Frame(root, bg='#80c1ff', bd=5) frame.place(relx=0.5, rely=.01, relwidth=0.80, relheight=0.8, anchor='n') label = tk.Label(frame, font=('courier', 8), text="", wraplength=450, anchor='w', justify='left') label.place(relwidth=1, relheight=1) lower_frame = tk.Frame(root, bg='#80c1ff', bd=5) lower_frame.place(relx=0.5, rely=0.82, relwidth=0.80, relheight=0.17, anchor='n') button_75 = tk.Button(lower_frame, text='I-75') button_75.place(relwidth=0.20, relheight=1) button_85 = tk.Button(lower_frame, text='I-85') button_85.place(relx=.20, relwidth=0.20, relheight=1) button_285 = tk.Button(lower_frame, text='I-285') button_285.place(relx=.40, relwidth=.20, relheight=1) button_20 = tk.Button(lower_frame, text='I-20') button_20.place(relx=0.60, relwidth=0.20, relheight=1) button_400 = tk.Button(lower_frame, text="SR 400") button_400.place(relx=0.80, relwidth=0.20, relheight=1) label.config(text = get_tweets(api, "GDOT_I75_ATL")) root.mainloop()
true
19f9ec38883bc4f3baddfe9e386cbb255f2fd59c
Python
dmtrbrlkv/CrackWatcherBot
/app/main.py
UTF-8
2,179
2.609375
3
[]
no_license
import crack_watch import bot import time import logging from threading import Thread class Watcher(Thread): def __init__(self, every, subscribe, cursor): super().__init__() self.every = every self.subscribe = subscribe self.cursor = cursor @staticmethod def send_info_to_subscribers(game_infos, subscribe): for game_info in game_infos: for id, is_AAA in subscribe.items(): if not is_AAA or (is_AAA and game_info.is_AAA): bot.send_game_info(id, game_info) logging.info(f"Send crack info {game_info.title} to {id}") def run(self): last_date = self.load_last_date() cw = crack_watch.CrackWatch(last_date=last_date) while True: logging.info(f"Watch new cracks") if cw.load_new_cracked(): logging.info(f"Watched {len(cw.last_game_infos)} new cracks") self.send_info_to_subscribers(cw.last_game_infos, self.subscribe) self.save_last_date(cw.last_check_date) else: logging.info(f"Cant load new cracks") time.sleep(self.every) def load_last_date(self): self.cursor.execute('SELECT * FROM last_watch') date = self.cursor.fetchone() return date[0] def save_last_date(self, date): self.cursor.execute(f"UPDATE last_watch SET date = '{str(date)}'") def main(): logging.basicConfig(level=logging.INFO, format='[%(asctime)s] %(levelname).1s %(message)s', datefmt='%Y.%m.%d %H:%M:%S') logging.info(f"Start") b = bot.bot subscribe = bot.subscribe cursor = bot.cursor every = bot.every watcher = Watcher(every, subscribe, cursor) watcher.start() # # game_infos = cw.new_cracked() # print(game_infos) # # cw.load_new_cracked() # game_infos = cw.new_cracked() # print(game_infos) # # cw.load_new_cracked() # game_infos = cw.new_cracked() # print(game_infos) # # # save_last_date(cw.last_check_date) b.polling(none_stop=True) logging.info(f"Stop") if __name__ == "__main__": main()
true
98d13c7c41687a9e137c84b67b577a3107c4d35e
Python
krprithvi/vacationplanner
/app/legs.py
UTF-8
860
3.234375
3
[]
no_license
import re class Leg: segments = None travelDuration = None travelDurationHours = None travelDurationMinutes = None maxAirline = None def __init__(self, segments, travelDuration, maxAirline): self.segments = segments self.travelDuration = travelDuration self.maxAirline = maxAirline try: hours_minutes_regex = re.compile('\d+') time = hours_minutes_regex.findall(self.travelDuration) if len(time) == 2: self.travelDurationHours, self.travelDurationMinutes = time elif 'H' in travelDuration: self.travelDurationHours = time[0] elif 'M' in travelDuration: self.travelDurationMinutes = time[1] except Exception as e: print(str(e)) self.travelDurationMinutes = "NA"
true
381cf2cec343761e65edcf4c88456420a7bb23f9
Python
chitn/Algorithms-illustrated-by-Python
/example/prim.py
UTF-8
1,522
3.25
3
[]
no_license
# MST # https://www.spoj.com/problems/MST/ # AC from heapq import heappush, heappop INF = 10**9 def prims(sta): visit = [] dist[sta] = 0 heappush(visit, (0, sta)) while (len(visit) > 0): vh_data = heappop(visit) vh = vh_data[1] visited[vh] = True for vn_data in graph[vh]: vn = vn_data[0] w = vn_data[1] if (visited[vn] == False) and (w < dist[vn]): dist[vn] = w path[vn] = vh heappush(visit, (w, vn)) def mst_out(): ans = 0 for i in range(n+1): if (path[i] == -1): continue ans += dist[i] # print("{0} - {1}: {2}".format(path[i], i, dist[i])) # print("Weight of the MSTL {0}".format(ans)) print(ans) if __name__ == '__main__': # import sys # sys.stdin = open('INP.txt', 'r') n, m = map(int, input().split()) graph = [[] for i in range(n+1)] dist = [INF for i in range(n+1)] path = [-1 for i in range(n+1)] visited = [False for i in range(n+1)] for i in range(m): u, v, w = map(int, input().split()) graph[u].append((v, w)) graph[v].append((u, w)) # graph = [[],[(2,10),(3,5),(4,7)],[(1,10),(3,15),(4,2)],[(1,5),(2,15),(4,40)],[(1,7),(2,2),(3,40)]] prims(1) mst_out() """ 4 6 1 2 10 1 3 5 1 4 7 2 4 2 2 3 15 3 4 40 """
true
252a87d8a7dbe9766c4a0267abc893cd6dbbd480
Python
moon729/PythonAlgorithm
/5. 재귀 알고리즘/gcd.py
UTF-8
268
4
4
[]
no_license
#euclidean algorithm def gcd(x:int, y:int) -> int: if x < y: x, y = y, x if y == 0: return x else: return gcd(y, x%y) if __name__ == '__main__': x = int(input('x : ')) y = int(input('y : ')) print(f'gcd(x,y) = {gcd(x,y)}')
true
63d949bb0778cc84f862cf0c74e7e8ac92b1f38a
Python
dylanpmorgan/cwdm_ML
/cwdmModel.py
UTF-8
5,683
2.640625
3
[]
no_license
import os, time, sys, pdb import numpy as np try: import cPickle as pickle except: import pickle import itertools import sklearn.base from sklearn.linear_model import LogisticRegression from sklearn.cross_validation import train_test_split from sklearn.grid_search import GridSearchCV from matplotlib.colors import Normalize from matplotlib import pyplot as plt class cwdmModel(sklearn.base.BaseEstimator, sklearn.base.ClassifierMixin): def __init__(self,model=None, bands=None, model_params = {}): assert hasattr(model, "fit") assert hasattr(model, "predict") assert hasattr(model, "score") if hasattr(model, "decision_function"): assert hasattr(model, "decision_function") else: assert hasattr(model, "predict_proba") self.model = model.set_params(**model_params) self.bands = bands self.colors = self.get_color_permutations(bands) self._trained_models = dict() self._trained_models_scores = dict() self._is_trained = False self._best_params = dict() self._optimized_models = dict() self._optimized_models_scores = dict() self._is_optimized = False def fit(self, X, y): X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.8) for each in self.colors: X_color_train = self.get_color_indices(X_train, each) X_color_test = self.get_color_indices(X_test, each) clf = sklearn.base.clone(self.model) clf.fit(X_color_train, y_train) # Score serves as classifier metric score = int(100*clf.score(X_color_test, y_test)) self._trained_models[each] = pickle.dumps(clf) self._trained_models_scores[each] = score self._is_trained = True weighted_predictions = self.get_weighted_predictions(X_test) y_predictor = LogisticRegression() y_predictor.fit(weighted_predictions, y_test) self._y_predictor = y_predictor return self def get_weighted_predictions(self, X): if self._is_trained: model_items = self._trained_models.items() model_weights = self._trained_models_scores elif self._is_optimized: model_items = self._optimized_models.items() model_weights = self._optimized_models_scores predictions = [] weights = [] for color, model_string in model_items: X_color = self.get_color_indices(X, color) clf = pickle.loads(model_string) pred = clf.predict(X_color) weight = model_weights[color] weights.append(weight) predictions.append(pred * weight) #predictions = np.array(predictions) / np.sum(weights) weighted_predictions = np.mean(predictions, axis=0) return weighted_predictions.reshape(-1,1) def predict(self, X, y=None): weighted_predictions = self.get_weighted_predictions(X) y_pred = self._y_predictor.predict(weighted_predictions) return y_pred def optimize_fit(self, X, y, param_grid, n_iter=100, check=False): X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=100) for each in self.colors: X_color_train = self.get_color_indices(X_train, each) X_color_test = self.get_color_indices(X_test, each) clf = sklearn.base.clone(self.model) opt = GridSearchCV(clf, param_grid=param_grid, verbose=True, cv=3) opt.fit(X_color_train, y_train) print("The best parameters are %s with a score of %0.2f" % (opt.best_params_, opt.best_score_)) if check: plot_validation(opt) clf.set_params(opt.best_params_) clf.fit(X_color_train, y_train) score = int(100*clf.score(X_color_test, y_test)) self._best_params[each] = opt.best_params_ self._optimized_models[each] = pickle.dumps(clf) self._optimized_scores[each] = score self._is_optimized = True weighted_predictions = self.get_weighted_predictions(X_test) y_predictor = LogisticRegression() y_predictor.fit(weighted_predictions, y_test) self._y_predictor = y_predictor return self def get_color_permutations(self, bands): # Color comboinations c_combo = list(itertools.combinations(bands,2)) # Color-cut combinations cc_combo = list(itertools.combinations(c_combo,2)) cc_labels = ["".join([cc[0][0],cc[0][1],cc[1][0],cc[1][1]]) for cc in cc_combo] return cc_labels def get_color_indices(self, X, color): # Make X from colors color_x = np.array(X[color[2]] - X[color[3]]) color_y = np.array(X[color[0]] - X[color[1]]) return np.vstack([color_x,color_y]).T def plot_validation(self, opt): # Plot the Validation accuarcy of model optimizer scores = [x[1] for x in opt.grid_scores_] scores = np.array(scores).reshape(len(param_grid["C"]), len(param_grid["gamma"])) plt.figure(figsize=(8, 6)) plt.subplots_adjust(left=.2, right=0.95, bottom=0.15, top=0.95) plt.imshow(scores, interpolation='nearest', cmap=plt.cm.hot) plt.xlabel('gamma') plt.ylabel('C') plt.colorbar() plt.xticks(np.arange(len(param_grid["gamma"])), param_grid["gamma"], rotation=45) plt.yticks(np.arange(len(param_grid["C"])), param_grid["C"]) plt.title('Validation accuracy') plt.show()
true
0d15222ae33375ca909f14cc43e47829955247fd
Python
rlawjdghek/2021-LG-AI-Competition
/src/augmentations.py
UTF-8
8,376
2.609375
3
[]
no_license
import cv2 import numpy as np import torch import albumentations as A from albumentations.core.transforms_interface import DualTransform import os # 출처: https://www.kaggle.com/shivyshiv/efficientnet-gridmask-training-pytorch class GridMask_(DualTransform): """GridMask augmentation for image classification and object detection. Args: num_grid (int): number of grid in a row or column. fill_value (int, float, lisf of int, list of float): value for dropped pixels. rotate ((int, int) or int): range from which a random angle is picked. If rotate is a single int an angle is picked from (-rotate, rotate). Default: (-90, 90) mode (int): 0 - cropout a quarter of the square of each grid (left top) 1 - reserve a quarter of the square of each grid (left top) 2 - cropout 2 quarter of the square of each grid (left top & right bottom) Targets: image, mask Image types: uint8, float32 Reference: | https://arxiv.org/abs/2001.04086 | https://github.com/akuxcw/GridMask """ def __init__(self, num_grid=3, fill_value=0, rotate=0, mode=0, always_apply=False, p=0.5): super(GridMask_, self).__init__(always_apply, p) if isinstance(num_grid, int): num_grid = (num_grid, num_grid) if isinstance(rotate, int): rotate = (-rotate, rotate) self.num_grid = num_grid self.fill_value = fill_value self.rotate = rotate self.mode = mode self.masks = None self.rand_h_max = [] self.rand_w_max = [] def init_masks(self, height, width): if self.masks is None: self.masks = [] n_masks = self.num_grid[1] - self.num_grid[0] + 1 for n, n_g in enumerate(range(self.num_grid[0], self.num_grid[1] + 1, 1)): grid_h = height / n_g grid_w = width / n_g this_mask = np.ones((int((n_g + 1) * grid_h), int((n_g + 1) * grid_w))).astype(np.uint8) for i in range(n_g + 1): for j in range(n_g + 1): this_mask[ int(i * grid_h): int(i * grid_h + grid_h / 2), int(j * grid_w): int(j * grid_w + grid_w / 2) ] = self.fill_value if self.mode == 2: this_mask[ int(i * grid_h + grid_h / 2): int(i * grid_h + grid_h), int(j * grid_w + grid_w / 2): int(j * grid_w + grid_w) ] = self.fill_value if self.mode == 1: this_mask = 1 - this_mask self.masks.append(this_mask) self.rand_h_max.append(grid_h) self.rand_w_max.append(grid_w) def apply(self, image, mask, rand_h, rand_w, angle, **params): h, w = image.shape[:2] hm, wm = mask.shape[:2] # angle = np.random.uniform(-angle, angle) # matrix = cv2.getRotationMatrix2D((wm/2, hm/2), angle, 1) # mask = cv2.warpAffine(mask, matrix, (int(wm*1.5), int(hm*1.5))) #mask = cv2.rotate(mask, angle) if self.rotate[1] > 0 else mask mask = mask[:, :, np.newaxis] if image.ndim == 3 else mask image *= mask[rand_h:rand_h + h, rand_w:rand_w + w].astype(image.dtype) return image def get_params_dependent_on_targets(self, params): img = params['image'] height, width = img.shape[:2] self.init_masks(height, width) mid = np.random.randint(len(self.masks)) mask = self.masks[mid] rand_h = np.random.randint(self.rand_h_max[mid]) rand_w = np.random.randint(self.rand_w_max[mid]) angle = np.random.randint(self.rotate[0], self.rotate[1]) if self.rotate[1] > 0 else 0 return {'mask': mask, 'rand_h': rand_h, 'rand_w': rand_w, 'angle': angle} @property def targets_as_params(self): return ['image'] def get_transform_init_args_names(self): return ('num_grid', 'fill_value', 'rotate', 'mode') def shear_transfrom(img1, img2=None, strength=0.5, is_vertical=True, p=0.3): if np.random.rand() < p: h, w, c = img1.shape src = np.float32([[w / 3, h / 3], [2 * w / 3, h / 3], [w / 3, 2 * h / 3]]) degree = np.random.uniform(-strength, strength) if is_vertical: dst = np.float32([[w / 3, h / 3 + (h / 3) * degree], [2 * w / 3, h / 3], [w / 3, 2 * h / 3 + (h / 3) * degree]]) else: dst = np.float32( [[(w / 3) + (w / 3) * degree, h / 3], [(2 * w / 3) + degree * (w / 3), h / 3], [(w / 3), 2 * h / 3]]) M = cv2.getAffineTransform(src, dst) img1 = cv2.warpAffine(img1, M, (w, h)) if img2 is not None: img2 = cv2.warpAffine(img2, M, (w, h)) return img1, img2 else: return img1 else: return img1, img2 if img2 is not None else img1 class ShearTransform: def __init__(self, strength = 0.5, p=0.5): self.p = p self.strength = strength def __call__(self, img1, img2=None): return shear_transfrom(img1, img2, self.strength, p=self.p) class HorizontalFlip: def __init__(self, p=0.5): self.hflip = A.Compose( [A.HorizontalFlip(p=p)], additional_targets={"target_image": "image"}) def __call__(self, img1, img2=None): if img2 is None: img1 = self.hflip(image=img1)['image'] return img1 else: transformed = self.hflip(image=img1, target_image=img2) img1 = transformed['image'] img2 = transformed['target_image'] return img1, img2 class VerticalFlip: def __init__(self, p=0.5): self.vflip = A.Compose( [A.VerticalFlip(p=p)], additional_targets={"target_image": "image"}) def __call__(self, img1, img2=None): if img2 is None: img1 = self.vflip(image=img1)['image'] return img1 else: transformed = self.vflip(image=img1, target_image=img2) img1 = transformed['image'] img2 = transformed['target_image'] return img1, img2 class CutOut: def __init__(self, p=0.5): self.cutout = A.Compose( [A.Cutout(num_holes=8, max_h_size=86, max_w_size=86, fill_value=0, always_apply=False, p=p)], additional_targets={"target_image": "image"}) def __call__(self, img1, img2=None): if img2 is None: img1 = self.cutout(image=img1)['image'] return img1 else: transformed = self.cutout(image=img1, target_image=img2) img1 = transformed['image'] img2 = transformed['target_image'] return img1, img2 class GridMask: def __init__(self, p=0.5): self.gm = A.Compose([ GridMask_(num_grid=4, mode=0, rotate=30, p=p, fill_value=0.) ], additional_targets={"target_image": "image"}) def __call__(self, img1, img2=None): if img2 is None: img1 = self.gm(image=img1)['image'] return img1 else: transformed = self.gm(image=img1, target_image=img2) img1 = transformed['image'] img2 = transformed['target_image'] return img1, img2 if __name__ == "__main__": sample_img = cv2.imread('./sample_img.png') co = CutOut(p=1.) hf = HorizontalFlip(p=1.) vf = VerticalFlip(p=1.) gm = GridMask(p=1.) sh = ShearTransform(p=1.) sample_img_hflip = hf(sample_img.copy()) sample_img_vflip = vf(sample_img.copy()) sample_img_shear = sh(sample_img.copy()) sample_img_gridmask = gm(sample_img.copy()) sample_img_cutout = co(sample_img.copy()) save_path = './augmentation_save' os.makedirs(save_path, exist_ok=True) cv2.imwrite(os.path.join(save_path, "sample_hflip.png"), sample_img_hflip) cv2.imwrite(os.path.join(save_path, "sample_vflip.png"), sample_img_vflip) cv2.imwrite(os.path.join(save_path, "sample_shear.png"), sample_img_shear) cv2.imwrite(os.path.join(save_path, "sample_gridmask.png"), sample_img_gridmask) cv2.imwrite(os.path.join(save_path, "sample_cutout.png"), sample_img_cutout)
true
faf2360b7c3759ef0f49ba2bef17675f71f6bb27
Python
PPodhorodecki/Prework
/03_Biblioteka_standardowa_w_języku_python/Zadanie_2-Łączenie_listy/task.py
UTF-8
83
3.046875
3
[]
no_license
lista=list(["a", "b", "c", "d", "e"]) separator = " " print(separator.join(lista))
true
be11da17cd3b82ab32c3818d558a45ba3e3d2e89
Python
sogoodnow/python-study
/week9/week9/spiders/dangdang.py
UTF-8
3,005
2.765625
3
[]
no_license
# -*- coding: utf-8 -*- import scrapy from ..items import DangItem from scrapy.loader import ItemLoader from scrapy.http import Request class DangdangSpider(scrapy.Spider): name = 'dangdang' allowed_domains = ['search.dangdang.com'] start_urls = ['http://search.dangdang.com/?key=python&act=input'] page = 1 def parse(self, response): """ #=======itemloader实现============ item = ItemLoader(item=DangItem(),response=response) # 标题 item.add_css('title','ul li[class*="line"] p[class="name"] a::attr(title)') # 详细 item.add_css('detail','ul li[class*="line"] p[class="detail"]::text') # 价格 item.add_css('price','ul li[class*="line"] p[class="price"] span[class="search_pre_price"]::text') # 评论数 item.add_css('comment_num', 'ul li[class*="line"] p[class="search_star_line"] a[class="search_comment_num"]::text') # 作者 item.add_xpath('author','//ul[@class="bigimg"]/li[contains(@class,"line")]/p[@class="search_book_author"]/span[1]/a[1]/text()') # 出版社 item.add_xpath('publish','//ul[@class="bigimg"]/li[contains(@class,"line")]/p[@class="search_book_author"]/span[3]/a/text()') # 出版时间 item.add_xpath('p_time','//ul[@class="bigimg"]/li[contains(@class,"line")]/p[@class="search_book_author"]/span[2]/text()') yield item.load_item() """ # =======单item实现============ for li in response.css('ul li[class*="line"]'): item = DangItem() # 图片判断 if li.css('.pic img::attr(data-original)').extract_first(): item['img_urls'] = li.css('.pic img::attr(data-original)').extract_first() else: item['img_urls'] = li.css('.pic img::attr(src)').extract_first() # 标题 item['title'] = li.css('p[class="name"] a::attr(title)').extract_first() # 详细 item['detail'] = li.css('p[class="detail"]::text').extract_first() # 价格 item['price'] = li.css('p[class="price"] span[class="search_pre_price"]::text').extract_first() # 评论数 item['comment_num'] = li.css('p[class="search_star_line"] a[class="search_comment_num"]::text').extract_first() # 作者 item['author'] = li.xpath('./p[@class="search_book_author"]/span[1]/a[1]/text()').extract_first() # 出版社 item['publish'] = li.xpath('./p[@class="search_book_author"]/span[3]/a/text()').extract_first() # 出版时间 item['p_time'] = li.xpath('./p[@class="search_book_author"]/span[2]/text()').extract_first() yield item # 循环收集10页数据 self.page += 1 if self.page <= 10: next_url = self.start_urls[0]+'&page_index='+str(self.page) yield Request(url=next_url,callback=self.parse)
true
e0eb57defc9fe468e5e18471d3d2af683a18f0a2
Python
deternan/Light-tools-Python-
/Value_check.py
UTF-8
272
2.875
3
[]
no_license
# coding=utf8 ''' NaN_check version: December 03, 2019 02:02 PM Last revision: December 03, 2019 02:12 PM Author : Chao-Hsuan Ke ''' import numpy as np aa = 18 divided = 3 if(divided!=0): print(aa/divided) else: print('divided: 0') #print(np.isnan(divided/aa))
true
11888fae7fc65fc486b8f4e8814d87bfa04ee383
Python
decretist/Sg
/post/freq.py
UTF-8
530
2.765625
3
[]
no_license
#!/usr/local/bin/python3 # # Paul Evans (pevans@sandiego.edu) # import re import helper def main(): """freq.py | sort -n -r | head -300 | awk '{print $2}' | sort > freq.out""" string = open('../hand/Gratian3.txt', 'r').read() words = re.split(r'\W', string) sg_freqs = helper.dictify(words) keys = sg_freqs.keys() for key in keys: # print("%2d\t%s" % (sg_freqs[key], key)) # print("{:2d}\t{}".format(sg_freqs[key], key)) print(f'{sg_freqs[key]:2d}\t{key:s}') if __name__ == '__main__': main()
true
666acecdc0d8441ae7191d700497fff0b6cb69f7
Python
xieziwei99/jqxxsx
/var/cityclass.py
UTF-8
1,697
2.65625
3
[]
no_license
#!/usr/bin/python # -*- coding: UTF-8 -*- #用来存储一二三线城市名单 class CityClass: TierOneCities = ('北京', '上海', '广州', '深圳') NewTierOneCites = ('成都', '重庆', '杭州', '武汉', '西安', '天津', '苏州', '南京', '郑州', '长沙', '东莞', '沈阳', '青岛', '合肥', '佛山') TierTwoCities = ('无锡', '宁波', '昆明', '大连', '福州', '厦门', '哈尔滨', '济南', '温州', '南宁', '长春', '泉州', '石家庄', '贵阳', '南昌', '金华', '常州', '南通', '嘉兴', '太原', '徐州', '惠州', '珠海', '中山', '台州', '烟台', '兰州', '绍兴', '海口', '扬州') TierThreeCities = ('汕头', '湖州', '盐城', '潍坊', '保定', '镇江', '洛阳', '泰州', '乌鲁木齐', '临沂', '唐山', '漳州', '赣州', '廊坊', '呼和浩特', '芜湖', '桂林', '银川', '揭阳', '三亚', '遵义', '江门', '济宁', '莆田', '湛江', '绵阳', '淮安', '连云港', '淄博', '宜昌', '邯郸', '上饶', '柳州', '舟山', '咸阳', '九江', '衡阳', '威海', '宁德', '阜阳', '株洲', '丽水', '南阳', '襄阳', '大庆', '沧州', '信阳', '岳阳', '商丘', '肇庆', '清远', '滁州', '龙岩', '荆州', '蚌埠', '新乡', '鞍山', '湘潭', '马鞍山', '三明', '潮州', '梅州', '秦皇岛', '南平', '吉林', '安庆', '泰安', '宿迁', '包头', '郴州', '南充') def __init__(self): pass def getCites(self): return self.TierOneCities,self.NewTierOneCites,self.TierTwoCities,self.TierThreeCities pass
true
7d5f447eb752a213029d9ccfd025b9030582aa70
Python
DiFve/Datastructure-Lab
/Lab04/63010789_Lab04_2.py
UTF-8
1,413
3.3125
3
[]
no_license
class Queue: queue=[] maxq=0 def __init__(self,max): self.queue=[] self.maxq=max def pop(self): if(len(self.queue)>0): self.queue.pop(0) def top(self): if(len(self.queue)>0): return self.queue[0] else: return "err" def append(self,num): self.queue.append(num) def __str__(self): return str(self.queue) def qlen(self): return int(len(self.queue)) def getQueue(self): return self.queue def setQueue(self,q): self.queue = q def isEmpty(self): if(len(self.queue)>0): return False else: return True def isFull(self): if(len(self.queue)<self.maxq): return False else: return True inp = input("Enter people : ") mainQ = list(inp) q1=Queue(5) q2=Queue(5) count=1 timer1,timer2=0,0 for i in inp: mainQ.pop(0) print(count,end=" ") print(mainQ,end=" ") if(timer1>=3): q1.pop() timer1=0 if(timer2>=2): q2.pop() timer2=0 if(not q1.isFull()): q1.append(i) elif(not q2.isFull()): q2.append(i) if(not q1.isEmpty()): timer1+=1 if(not q2.isEmpty()): timer2+=1 lst1=q1.getQueue() lst2=q2.getQueue() print(lst1,end=" ") print(lst2) count+=1
true
6425a3e1de47807306368060294b81d55899dd53
Python
ShirleyKirk/black_history_Python
/Python_Practice/Unit_1/shelve_practice/second_version/dump_db_classes.py
UTF-8
213
2.734375
3
[]
no_license
import shelve data_box=shelve.open('classes-shelve') for key in data_box: print(key,"=>\n",data_box[key].name,':',data_box[key].pay) #print(data_box['tom'].lastName()) #bob=data_box['bob'] #print(bob.lastName())
true
e85275bc4fd21a5b1587c548ceba0f8055497ed4
Python
JaanaKaaree/data-extraction
/get_facebook.py
UTF-8
697
2.84375
3
[]
no_license
import facebook import configparser config = configparser.RawConfigParser() config.read('config.ini') accesstoken = config.get('Facebook', 'access_token') print (accesstoken) graph = facebook.GraphAPI(access_token=accesstoken, version="2.12") # Search for places near 1 Hacker Way in Menlo Park, California. places = graph.search(type='place', center='46.814309,-71.207917', distance=1000, fields='name,checkins,location') # Each given id maps to an object the contains the requested fields. for place in places['data']: print('%s %s' % (place['name'].encode(),place['location'].get('zip'))) print (place['checkins'])
true
914feaabb89dda242e14d1fe5813cf6f3c158192
Python
gmoretti1/Scientific_Python_Assignments_POLIMI_EETBS
/Assignment 6-Pandas A-Deadline Oct 31 2017/Assignment6_Moretti/Assignment6_Moretti.py
UTF-8
1,973
3.453125
3
[]
no_license
# -*- coding: utf-8 -*- """ EETBS 2017/2018 - Assignment 6 - Redoing assignment 2 using pandas module Giorgio Moretti (10433550) """ import pandas as pd # The lists are made using this order: [type, length, k, h, area, R value] resistances_names = ["indoor","outdoor","foam","side plaster","center plaster","brick"] resistances_indices = ["type","L","k","h","A","R"] R1 = ["conv", None, None, 10, 0.25, 0] R2 = ["conv", None, None, 25, 0.25, 0] R3 = ["cond", 0.03, 0.026, None, 0.25, 0] R4 = ["cond", 0.02, 0.22, None, 0.25, 0] R5 = ["cond", 0.16, 0.22, None, 0.015, 0] R6 = ["cond", 0.16, 0.72, None, 0.22, 0] resistances = [R1,R2,R3,R4,R5,R6] R_dataframe = pd.DataFrame(resistances,resistances_names,resistances_indices) R_dataframe.loc[:,"R"][R_dataframe.loc[:,"type"] == "conv"] = 1.0/(R_dataframe.loc[:,"h"][R_dataframe.loc[:,"type"] == "conv"]*R_dataframe.loc[:,"A"][R_dataframe.loc[:,"type"] == "conv"]) R_dataframe.loc[:,"R"][R_dataframe.loc[:,"type"] == "cond"] = R_dataframe.loc[:,"L"][R_dataframe.loc[:,"type"] == "cond"]/(R_dataframe.loc[:,"k"][R_dataframe.loc[:,"type"] == "cond"]*R_dataframe.loc[:,"A"][R_dataframe.loc[:,"type"] == "cond"]) print R_dataframe R_series = R_dataframe.loc["indoor","R"] + R_dataframe.loc["outdoor","R"] + R_dataframe.loc["foam","R"] + 2*R_dataframe.loc["side plaster","R"] R_parallel = 1/(2/R_dataframe.loc["center plaster","R"] + 1/ R_dataframe.loc["brick","R"]) R_TOT = round(R_series + R_parallel,4) T_in = 20 # [°C] T_out = -10 # [°C] A_unit = 1*0.25 # [m^2] Qdot_unit = round((T_in - T_out)/R_TOT,4) # unit heat transfer rate [W] A_wall = 3*5 # [m^2] Qdot_wall = round(Qdot_unit * (A_wall/A_unit),4) # [W] print "\n ********** RESULTS **********" print "\n The total resistance of the wall is: R_WALL_TOT = " + str(R_TOT) + " °C/W" print "\n The unit heat transfer rate is: Qdot_UNIT = " + str(Qdot_unit) + " W" print "\n The heat transfer rate through the wall is: Qdot_WALL = " + str(Qdot_wall) + " W"
true
369bff85a7de932c6ff5aa368084e8fbe1c74b7b
Python
gobber/sklearn-export
/sklearn_export/estimator/regressor/MLPRegressor/__init__.py
UTF-8
2,936
2.84375
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- from sklearn_export.estimator.regressor.Regressor import Regressor class MLPRegressor(Regressor): """ See also -------- sklearn.neural_network.MLPRegressor http://scikit-learn.org/stable/modules/generated/ sklearn.neural_network.MLPRegressor.html """ # @formatter:on def __init__(self, estimator, **kwargs): """ Port a trained estimator to a dict. Parameters ---------- :param estimator : MLPRegressor An instance of a trained MLPRegressor estimator. """ super(MLPRegressor, self).__init__(estimator, **kwargs) # Activation function ('identity', 'logistic', 'tanh' or 'relu'): if estimator.activation not in self.hidden_activation_functions: raise ValueError(("The activation function '%s' of the estimator " "is not supported.") % estimator.activation) # Estimator: est = estimator self.output_activation = est.out_activation_ self.hidden_activation = est.activation self.n_layers = est.n_layers_ self.n_hidden_layers = est.n_layers_ - 2 self.n_inputs = len(est.coefs_[0]) self.n_outputs = est.n_outputs_ self.hidden_layer_sizes = est.hidden_layer_sizes if isinstance(self.hidden_layer_sizes, int): self.hidden_layer_sizes = [self.hidden_layer_sizes] self.hidden_layer_sizes = list(self.hidden_layer_sizes) self.layer_units = \ [self.n_inputs] + self.hidden_layer_sizes + [est.n_outputs_] # Weights: self.coefficients = est.coefs_ # Bias: self.intercepts = est.intercepts_ @property def hidden_activation_functions(self): """Get list of supported activation functions for the hidden layers.""" return ['relu', 'identity', 'tanh', 'logistic'] def load_model_data(self, model_data=None): if model_data is None: model_data = {} model_data['bias'] = self._get_intercepts() model_data['hidden_activation'] = self.hidden_activation model_data['output_activation'] = self.output_activation model_data['type'] = 'MLPRegressor' weights = [] numrows = [] numcolumns = [] for c in self.coefficients: #w = [] #for j in range(0, len(c[0])): #for i in range(0, len(c)): #w.append(c[i][j]) numrows.append(len(c)) numcolumns.append(len(c[0])) weights.append(c.flatten('F').tolist()) model_data['weights'] = weights model_data['numRows'] = numrows model_data['numColumns'] = numcolumns return model_data def _get_intercepts(self): """ Create a list of interceptors. """ return [i.tolist() for i in self.intercepts]
true
72729ef0bf75210f57ebb91d684d689eed4453e6
Python
poojithumeshrao/poojith
/programs/kdtree.py
UTF-8
1,611
2.921875
3
[]
no_license
k = 3 count = 0 root = None import numpy as np import pdb import graphviz as gv class node: def __init__(self,k,d): self.points = d self.order = k self.left = None self.right = None def search(nod,point): nn = nod #pdb.set_trace() while (True): if nn == None: print 'error' elif nn.points[nn.order] >= point[nn.order]: if nn.left == None: temp = nn lorr = 0 break else : nn = nn.left else: if nn.right == None: temp = nn lorr = 1 break else : nn = nn.right return temp,lorr def insert(temp,lorr,point): #pdb.set_trace() t = node((temp.order+1)%k,point) if lorr == 0: temp.left = t else: temp.right = t data = np.random.randint(low = -50,high=50,size=(10,k)) print data g = gv.Graph(format='svg') def plot(no): if no == None: return p = str(no.order)+str(no.points) if no.left != None: l = str(no.left.order)+str(no.left.points) g.node(l) g.edge(p,l,label='left') plot(no.left) if no.right != None: r = str(no.right.order)+str(no.right.points) g.node(r) g.edge(p,r,label='right') plot(no.right) filename = g.render(filename='img/g1') for cord in data: #pdb.set_trace() if count == 0: root = node(0,cord) else : a,b = search(root,cord) insert(a,b,cord) count+=1 plot(root)
true
7f98bcb0b68a6b3450afb5fdc7396f0dfd83fc4a
Python
justinharringa/aprendendo-python
/2020-09-12/gabi/ex78.py
UTF-8
507
3.65625
4
[ "MIT" ]
permissive
lista_de_num = [int(input('digite um numero: ')) int(input('digite outro: ')) int(input('digite outro: ')) int(input('digite mais um: ')) int(input('o ultimo: ')) print(f'o maior valor foi: {max(lista_de_num)}') for i, v in enumerate(lista_de_num) if v == max: print(f'{i}..') print('o menor valor e {min(lista_de_num)}'.format(lista_de_num)) for i, v in numerate(lista_de_num) if v == min: print(f'{i}..')
true
f51e0df00b9a0f1fa6227e8ee2623e6ab441e891
Python
LichenZeng/AlphaZero_Gomoku
/policy_value_net_pytorch.py
UTF-8
10,135
2.828125
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- """ An implementation of the policyValueNet in PyTorch Tested in PyTorch 0.2.0 and 0.3.0 @author: Junxiao Song """ import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.autograd import Variable import numpy as np def set_learning_rate(optimizer, lr): """Sets the learning rate to the given value""" for param_group in optimizer.param_groups: param_group['lr'] = lr class Net(nn.Module): """policy-value network module""" def __init__(self, board_width, board_height): super(Net, self).__init__() self.board_width = board_width self.board_height = board_height # common layers self.conv1 = nn.Conv2d(4, 32, kernel_size=3, padding=1) self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1) self.conv3 = nn.Conv2d(64, 128, kernel_size=3, padding=1) # action policy layers self.act_conv1 = nn.Conv2d(128, 4, kernel_size=1) self.act_fc1 = nn.Linear(4 * board_width * board_height, board_width * board_height) # state value layers self.val_conv1 = nn.Conv2d(128, 2, kernel_size=1) self.val_fc1 = nn.Linear(2 * board_width * board_height, 64) self.val_fc2 = nn.Linear(64, 1) def forward(self, state_input): # common layers x = F.relu(self.conv1(state_input)) x = F.relu(self.conv2(x)) x = F.relu(self.conv3(x)) # action policy layers x_act = F.relu(self.act_conv1(x)) x_act = x_act.view(-1, 4 * self.board_width * self.board_height) x_act = F.log_softmax(self.act_fc1(x_act)) # state value layers x_val = F.relu(self.val_conv1(x)) x_val = x_val.view(-1, 2 * self.board_width * self.board_height) x_val = F.relu(self.val_fc1(x_val)) x_val = F.tanh(self.val_fc2(x_val)) return x_act, x_val class PolicyValueNet(): """policy-value network """ def __init__(self, board_width, board_height, model_file=None, use_gpu=False): self.use_gpu = use_gpu self.board_width = board_width self.board_height = board_height self.l2_const = 1e-4 # coef of l2 penalty # the policy value net module if self.use_gpu: self.policy_value_net = Net(board_width, board_height).cuda() else: self.policy_value_net = Net(board_width, board_height) # print("debug:", self.policy_value_net) """ debug: Net( (conv1): Conv2d(4, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (conv2): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (conv3): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (act_conv1): Conv2d(128, 4, kernel_size=(1, 1), stride=(1, 1)) (act_fc1): Linear(in_features=144, out_features=36, bias=True) # 4 x width x height (val_conv1): Conv2d(128, 2, kernel_size=(1, 1), stride=(1, 1)) (val_fc1): Linear(in_features=72, out_features=64, bias=True) # 2 x width x height (val_fc2): Linear(in_features=64, out_features=1, bias=True) ) """ self.optimizer = optim.Adam(self.policy_value_net.parameters(), weight_decay=self.l2_const) if model_file: net_params = torch.load(model_file) # debug: <class 'collections.OrderedDict'> # print("debug:", type(net_params)) self.policy_value_net.load_state_dict(net_params) def policy_value(self, state_batch): """ input: a batch of states output: a batch of action probabilities and state values """ if self.use_gpu: state_batch = Variable(torch.FloatTensor(state_batch).cuda()) log_act_probs, value = self.policy_value_net(state_batch) act_probs = np.exp(log_act_probs.data.cpu().numpy()) return act_probs, value.data.cpu().numpy() else: state_batch = Variable(torch.FloatTensor(state_batch)) log_act_probs, value = self.policy_value_net(state_batch) act_probs = np.exp(log_act_probs.data.numpy()) # print("debug: pv", type(state_batch), state_batch.shape) # print("debug: pv", type(log_act_probs), log_act_probs.shape, log_act_probs[0]) # print("debug: pv", type(value), value.shape, value[0]) # print("debug: pv", type(act_probs), act_probs.shape, act_probs[0]) """ debug: pv <class 'torch.Tensor'> torch.Size([512, 4, 6, 6]) debug: pv <class 'torch.Tensor'> torch.Size([512, 36]) tensor([-3.5188, -3.6358, -3.5779, -3.6464, -3.6030, -3.6298, -3.5478, -3.5090, -3.5997, -3.5677, -3.5541, -3.6722, -3.5616, -3.5636, -3.5926, -3.4936, -3.5709, -3.6210, -3.5447, -3.6076, -3.5882, -3.5600, -3.4815, -3.5765, -3.6788, -3.6113, -3.5063, -3.6241, -3.5781, -3.5612, -3.5779, -3.6497, -3.6608, -3.6400, -3.5247, -3.6140]) debug: pv <class 'torch.Tensor'> torch.Size([512, 1]) tensor(1.00000e-02 * [ 2.5594]) debug: pv <class 'numpy.ndarray'> (512, 36) [0.02963571 0.02636158 0.02793355 0.02608529 0.02724108 0.02652155 0.02878688 0.0299259 0.02733225 0.02821934 0.02860781 0.02542085 0.02839345 0.02833655 0.02752793 0.03039031 0.02813084 0.02675619 0.0288761 0.02711727 0.02764767 0.02843794 0.03076018 0.02797232 0.02525269 0.02701536 0.03000749 0.02667333 0.02792769 0.02840393 0.0279335 0.02599909 0.02571266 0.02625342 0.02945924 0.02694306] """ return act_probs, value.data.numpy() def policy_value_fn(self, board): """ input: board output: a list of (action, probability) tuples for each available action and the score of the board state """ legal_positions = board.availables current_state = np.ascontiguousarray(board.current_state().reshape( -1, 4, self.board_width, self.board_height)) if self.use_gpu: log_act_probs, value = self.policy_value_net( Variable(torch.from_numpy(current_state)).cuda().float()) act_probs = np.exp(log_act_probs.data.cpu().numpy().flatten()) else: log_act_probs, value = self.policy_value_net( Variable(torch.from_numpy(current_state)).float()) act_probs = np.exp(log_act_probs.data.numpy().flatten()) # print("debug: pvf", legal_positions) # print("debug: pvf,", value, log_act_probs, act_probs) """ debug: pvf [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 33, 34, 35] debug: pvf, tensor([[-0.1340]]) tensor([[-3.5891, -3.6159, -3.6483, -3.6113, -3.5677, -3.6311, -3.5342, -3.6449, -3.6345, -3.5444, -3.5193, -3.5488, -3.5690, -3.6075, -3.6792, -3.6329, -3.5296, -3.6544, -3.5786, -3.5870, -3.5027, -3.5944, -3.5537, -3.6383, -3.6251, -3.5364, -3.5302, -3.6542, -3.6004, -3.6269, -3.5623, -3.5152, -3.5181, -3.5594, -3.5809, -3.5221]]) [0.02762223 0.02689152 0.02603547 0.02701722 0.02822023 0.02648623 0.02918113 0.02612401 0.02639725 0.02888605 0.02961869 0.02876004 0.02818486 0.02711975 0.02524304 0.0264391 0.02931764 0.02587646 0.02791596 0.02768259 0.030115 0.02747608 0.0286187 0.0262969 0.02664538 0.02911758 0.02930048 0.02588317 0.02731332 0.02659828 0.02837263 0.02974232 0.02965699 0.02845607 0.02785116 0.02953648] """ act_probs = zip(legal_positions, act_probs[legal_positions]) value = value.data[0][0] # # debug: pvf value tensor(-0.1340) # print("debug: pvf value", value) return act_probs, value def train_step(self, state_batch, mcts_probs, winner_batch, lr): """perform a training step""" # wrap in Variable if self.use_gpu: state_batch = Variable(torch.FloatTensor(state_batch).cuda()) mcts_probs = Variable(torch.FloatTensor(mcts_probs).cuda()) winner_batch = Variable(torch.FloatTensor(winner_batch).cuda()) else: state_batch = Variable(torch.FloatTensor(state_batch)) mcts_probs = Variable(torch.FloatTensor(mcts_probs)) winner_batch = Variable(torch.FloatTensor(winner_batch)) # zero the parameter gradients self.optimizer.zero_grad() # set learning rate set_learning_rate(self.optimizer, lr) # forward log_act_probs, value = self.policy_value_net(state_batch) # define the loss = (z - v)^2 - pi^T * log(p) + c||theta||^2 # Note: the L2 penalty is incorporated in optimizer value_loss = F.mse_loss(value.view(-1), winner_batch) policy_loss = -torch.mean(torch.sum(mcts_probs * log_act_probs, 1)) loss = value_loss + policy_loss # backward and optimize loss.backward() self.optimizer.step() # calc policy entropy, for monitoring only entropy = -torch.mean( torch.sum(torch.exp(log_act_probs) * log_act_probs, 1) ) # print("debug:", loss, loss.data[0], "{:.5f} |x {:.5f}".format(loss.data[0], loss)) # print("debug:", entropy, entropy.data[0]) """ debug: tensor(4.1732) tensor(4.1732) 4.17323 |x 4.17323 debug: tensor(3.5791) tensor(3.5791) """ return loss.data[0], entropy.data[0] def get_policy_param(self): net_params = self.policy_value_net.state_dict() return net_params def save_model(self, model_file): """ save model params to file """ net_params = self.get_policy_param() # get model params torch.save(net_params, model_file)
true
a9666f4c82ff918effdd627e5fe29c691d7c48e1
Python
rtjxodnd/stockToKakao
/stockToKakao/p11_get_filltered_big_stock_info/bizLogic/screen.py
UTF-8
5,613
3
3
[]
no_license
from stockToKakao.p11_get_filltered_big_stock_info.crawler.crawlStockDetailInfo import getStockDetailInfo from stockToKakao.p11_get_filltered_big_stock_info.crawler.crawlDailyStockInfo import main_process as maxVolumeCrawler from stockToKakao.p11_get_filltered_big_stock_info.crawler.crawlImpairedRatio import find_impaired_ratio # 평균값 산출 def calculator_avg(factors): # 초기값 설정 tot_sum = 0 # 피제수설정 j = 0 # 제수설정 # 숫자 변환 및 제수 절정 for i in factors: if factors[i] == "\xa0" or factors[i] == "-" or factors[i] == "": factors[i] = 0 else: factors[i] = float(factors[i].replace(",", "")) j += 1 # 합계값 for i in factors: # 과거 데이터 중 하나라도 음수 있으면 0 리턴하고 종료. tot_sum += factors[i] # 제수가 0이면 roe = 0 리턴 if j == 0: return {"avg": 0} # 평균값 계산 avg = tot_sum / j return {"avg": avg} # 음수검증 def calculator_recent(factors): # 숫자 변환 및 제수 절정 for i in factors: if factors[i] == "\xa0" or factors[i] == "-" or factors[i] == "": factors[i] = 0 else: factors[i] = float(factors[i]) # 하나라도 음수 있으면 -1 리턴하고 종료. if factors[i] < 0: return {"recent": -1} return {"recent": 1} ########################################################### # Main 처리: data 읽어서 필터링한다. ########################################################### def main_process(stc_id): try: # data추출 crawling_data = getStockDetailInfo(stc_id) now_price = crawling_data["now_price"] price_high_52week = crawling_data["price_high_52week"] price_low_52week = crawling_data["price_low_52week"] sales_accounts = crawling_data["sales_accounts"] operating_profits = crawling_data["operating_profits"] net_incomes = crawling_data["net_incomes"] op_margins = crawling_data["op_margins"] net_margins = crawling_data["net_margins"] roes = crawling_data["roes"] debt_ratios = crawling_data["debt_ratios"] quick_ratios = crawling_data["quick_ratios"] reservation_rate = crawling_data["reservation_rates"] sales_accounts_recent = crawling_data["sales_accounts_recent"] operating_profits_recent = crawling_data["operating_profits_recent"] net_incomes_recent = crawling_data["net_incomes_recent"] op_margins_recent = crawling_data["op_margins_recent"] net_margins_recent = crawling_data["net_margins_recent"] roes_recent = crawling_data["roes_recent"] debt_ratios_recent = crawling_data["debt_ratios_recent"] quick_ratios_recent = crawling_data["quick_ratios_recent"] reservation_rate_recent = crawling_data["reservation_rates_recent"] # 평균값 산출 avg_sales_account = calculator_avg(sales_accounts)["avg"] avg_operating_profit = calculator_avg(operating_profits)["avg"] avg_net_income = calculator_avg(net_incomes)["avg"] avg_op_margin = calculator_avg(op_margins)["avg"] avg_net_margin = calculator_avg(net_margins)["avg"] avg_roe = calculator_avg(roes)["avg"] avg_debt_ratios = calculator_avg(debt_ratios)["avg"] avg_quick_ratios = calculator_avg(quick_ratios)["avg"] avg_reservation_rate = calculator_avg(reservation_rate)["avg"] # 음수검증(년단위) sales_account_recent = calculator_recent(sales_accounts)["recent"] operating_profit_recent = calculator_recent(operating_profits)["recent"] net_income_recent = calculator_recent(net_incomes)["recent"] op_margin_recent = calculator_recent(op_margins)["recent"] net_margin_recent = calculator_recent(net_margins)["recent"] roe_recent = calculator_recent(roes)["recent"] # 52주 최저가의 2배가 현재가 보다 작으면 매수 안함 if float(price_low_52week) * 2 < float(now_price): return False # 최근 매출액 중 음수가 있으면 매수 안함 if sales_account_recent < 0: return False # 최근 영업이익 중 음수가 있으면 매수 안함 if operating_profit_recent < 0: return False # 영업이익이 2년간 1.5배 미만 상승 안했으면 매수 안 함 # if float(operating_profits["operating_profit0"])*1.5 > float(operating_profits["operating_profit2"]): # continue # 당기순이익 평균이 0보다 작으면 매수 안함 if avg_net_income < 0: return False # 부채율이 150보다 크면 매수 안함 if avg_debt_ratios > 150: return False # 유보율이 100보다 작으면 매수 안함 if avg_quick_ratios < 100: return False # 자본잠식률 45퍼센트 이상이면 매수 안 함 impaired_info = find_impaired_ratio(stc_id, 45) if impaired_info["impaired_yn"] == "Y": return False # 3년이내 일거래 100억 존재 안하면 매수 안함 max_deal_amt_info = maxVolumeCrawler(stc_id) if max_deal_amt_info["over10billioYn"] == "N": return False except Exception as e: print(stc_id) print(e) return False # 끝까지 모든 조건 충족시 True 리턴 return True if __name__ == '__main__': print(main_process('005930'))
true
283243e5fd940e3d0001c4e166a875b17053e206
Python
ImpalerWrG/opensmac
/widget.py
UTF-8
11,795
3
3
[]
no_license
import pygame, render import txt import math def add((x1, y1), (x2, y2)): return x1 + x2, y1 + y2 def sub((x1, y1), (x2, y2)): return x1 - x2, y1 - y2 #widget size is internal for drawing, should be set by parent class Widget(object): expand = 0, 0 shrink = 0, 0 #size = 0, 0 def __init__(self, **kwargs): self.init() for key, val in kwargs.iteritems(): setattr(self, key, val) if 'child' in dir(self): self.child.parent = self if 'children' in dir(self): for child in self.children: child.parent = self if 'renderer' in dir(self): self.set_all(renderer = self.renderer) def init(self): self.setsize = None self.size = 0, 0 self.shrink = 0, 0 self.pos = 0, 0 return self.expand = 0, 0 def set_all(self, **kwargs): for key, val in kwargs.iteritems(): setattr(self, key, val) if 'child' in dir(self): self.child.set_all(**kwargs) if 'children' in dir(self): for child in self.children: child.set_all(**kwargs) def on_mousebutton(self, event): pass def on_mousemove(self, event): pass def on_mouseout(self, event): pass def inside(self, (mx, my)): w, h = self.size x, y = self.pos return mx > x and mx < x + w - 1 and my > y and my < y + h - 1 def events(self, events): for event in events: if event.type == pygame.MOUSEMOTION: #mx, my = event.pos if self.inside(event.pos): self.on_mousemove(event) else: self.on_mouseout(event) if event.type == pygame.MOUSEBUTTONDOWN: if self.inside(event.pos): self.on_mousebutton(event) def get_size(self): if self.setsize: return self.setsize, self.expand, self.shrink else: return (0, 0), self.expand, self.shrink def set_size(self, pos, size): self.pos = pos self.size = size def do(self, events): pass def draw(self): pass class Label(Widget): def init(self): self.high = False self.pos = 0, 0 self.size = 0, 0 self.bold = False def on_mousebutton(self, event): pass#self.high = not self.high def on_mousemove(self, event): self.high = True def on_mouseout(self, event): self.high = False def do(self, events): self.events(events) def get_size(self): return self.renderer.font_size(self.text, self.bold), (0, 0), (0, 0) def draw(self): if self.high: self.renderer.font_render(self.text, (0, 0, 0), self.pos, self.size, self.color, bold = self.bold) else: self.renderer.font_render(self.text, self.color, self.pos, self.size, bold = self.bold) class Image(Widget): def init(self): self.expand = 0, 0 def get_size(self): return self.image.get_size(), (0, 0), (0, 0) def draw(self): self.renderer.surface.blit(self.image, self.pos) class Glue(Widget): def init(self): self.setsize = 0, 0 self.expand = 1, 1 class Bar(Glue): def draw(self): print self.pos, self.size (x, y), (w, h) = self.pos, self.size self.renderer.frect(x, y, x + w - 1, y + h - 1, self.color) class Parent(Widget): def do(self, events): return self.child.do(events) def draw(self): self.child.draw() class Expand(Parent): def init(self): self.set_expand = 0, 0 def get_size(self): sex, sey = self.set_expand size, (cex, cey), shrink = self.child.get_size() return size, (sex, sey), shrink def set_size(self, pos, size): self.child.set_size(pos, size) class Frame(Parent): def get_size(self): childsize, childexpand, childshrink = self.child.get_size() return add(childsize, (self.fwidth*2, self.fwidth*2)), childexpand, childshrink def set_size(self, pos, size): self.pos = pos self.size = size self.child.set_size(add(pos, (self.fwidth, self.fwidth)), sub(size, (self.fwidth*2, self.fwidth*2))) def drawframe(self): pass def draw(self): self.drawframe() self.child.draw() class OPFrame(Frame): def drawframe(self): w, h = self.size x, y = self.pos self.renderer.rect(x, y, x + w - 1, y + h - 1, self.color) class OPRFrame(Frame): def drawframe(self): w, h = self.size x, y = self.pos l, t, r, b = x, y, x + w - 1, y + h - 1 self.renderer.naline(l + 1, t, r - 1, t, self.color) self.renderer.naline(l + 1, b, r - 1, b, self.color) self.renderer.naline(l, t + 1, l, b - 1, self.color) self.renderer.naline(r, t + 1, r, b - 1, self.color) class MultiParent(Widget): children = [] def do(self, events): for child in self.children: child.do(events) return [] def draw(self): #print self, self.pos, self.size clip = self.renderer.get_clip() w, h = self.size x, y = self.pos self.renderer.set_clip(pygame.Rect(self.pos, self.size)) for child in self.children: child.draw() self.renderer.set_clip(clip) #self.renderer.rect(x, y, x+w-1, y+h-1, red) class VBox(MultiParent): def get_size(self): self.childgeo = [child.get_size() for child in self.children] childsizes = [size for size, expand, shrink in self.childgeo] childexps = [expand for size, expand, shrink in self.childgeo] childshrinks = [shrink for size, expand, shrink in self.childgeo] self.size = max([w for w, h in childsizes]+[0]), sum([h for w, h in childsizes]) self.childexp = max([w for w, h in childexps]+[0]), sum([h for w, h in childexps]) self.childshrink = max([w for w, h in childshrinks]+[0]), sum([h for w, h in childshrinks]) return self.size, self.childexp, self.childshrink #return (0, 0), (1, 1) def set_size(self, pos, size): self.pos = pos x, y = pos w, h = size ew, eh = sub(size, self.size) #extra width and height self.size = size cex, cey = self.childexp csx, csy = self.childshrink euy, suy = 0, 0 if cey: euy = float(eh)/cey # vert expand unit if csy: suy = float(eh)/csy # vert shrink unit ''' print 'obj', self #print 'ch', self.children #print 'chgeo', self.childgeo print self.childexp for c in zip(self.children, self.childgeo): print c #eux = ew #hor expand print 'size, self.size', size, self.size print 'euy', euy ''' if eh < 0 and csy == 0: #badness #print 'badness', self, eh, len(self.children) clip = float(eh) / (len(self.children)) #badness clip oy = 0 draw = [] assert(euy >= 0) #print ' childsets', self for child, ((cw, ch), (ex, ey), (sx, sy)) in zip(self.children, self.childgeo): if ex: cw = w # hor expand elif cw > w: cw = w # hor cut if ey : ch = ch + int(ey * euy) # vert expand #print ey if sy and eh < 0: ch = ch + int(sy * suy) # vert shrink if eh < 0 and csy == 0: ch = int(ch + clip) #vert badness clip #print ' child.set_size', x, y+oy ,'/', ch, cw child.set_size((x, y + oy), (cw, ch)) oy += ch #print ' endchildsets', self class HBox(MultiParent): def get_size(self): self.childgeo = [child.get_size() for child in self.children] childsizes = [size for size, expand, shrink in self.childgeo] childexps = [expand for size, expand, shrink in self.childgeo] childshrinks = [shrink for size, expand, shrink in self.childgeo] self.size = sum([w for w, h in childsizes]+[0]), max([h for w, h in childsizes]+[0]) self.childexp = sum([w for w, h in childexps]+[0]), max([h for w, h in childexps]+[0]) self.childshrink = sum([w for w, h in childshrinks]+[0]), max([h for w, h in childshrinks]+[0]) #print 'hbox', self.size, self.childexp, self.childshrink #print childexps return self.size, self.childexp, self.childshrink def set_size(self, pos, size): self.pos = pos x, y = pos w, h = size ew, eh = sub(size, self.size) self.size = size cex, cey = self.childexp csx, csy = self.childshrink eux, sux = 0, 0 if cex: eux = float(ew)/cex if csx: sux = float(ew)/csx #euy = eh if ew < 0 and csx == 0: clip = float(ew) / (len(self.children)) ox = 0 for child, ((cw, ch), (ex, ey), (sx, sy)) in zip(self.children, self.childgeo): if ey: ch = h elif ch > h: ch = h if ex: cw = cw + int(ex * eux) if sx and eh < 0: cw = cw + int(sx * sux) if ew < 0 and csx == 0: cw = int(cw + clip) #vert badness clip child.set_size((x + ox, y), (cw, ch)) ox += cw class Box(MultiParent): def init(self): self.expand = 1, 1 def get_size(self): self.childgeo = [child.get_size() for child in self.children] return self.size, self.expand, self.shrink def set_size(self, pos, size): pass class StrLstBox(VBox): lines = [] def set_lines(self, lines): self.lines = lines self.children = [Label(text = line, color = blue1) for line in self.lines] self.set_all(renderer = self.renderer) #def init(self): # self.set_lines(self.lines) class ObjView(VBox): def do(self, events): if self.ref: obj = getattr(self.ref, self.attr) if obj: self.children = [Label(text = repr(obj), color = self.color2)] + \ [Label(text = k+' : '+repr(v), color = self.color) for k, v in vars(obj).iteritems()] else: self.children = [Label(text = 'None', color = self.color)] self.set_all(renderer = self.renderer) return if self.obj: self.children = [Label(text = k+' : '+repr(v), color = blue1) for k, v in vars(self.obj).iteritems()] self.set_all(renderer = self.renderer) class ListView(VBox): def do(self, events): if self.ref: lst = getattr(self.ref, self.attr) if lst: self.children = [Label(text = repr(e), color = self.color) for e in lst] else: self.children = [Label(text = 'None', color = self.color)] self.set_all(renderer = self.renderer) return #if self.obj: # self.children = [Label(text = k+' : '+repr(v), color = blue1) for k, v in vars(self.obj).iteritems()] # self.set_all(renderer = self.renderer) class RootWidget(Widget): def do(self, events): self.child.do(events) self.child.get_size() self.child.set_size((0, 0), self.renderer.get_size()) self.renderer.clear() self.child.draw() render.flip() return True black = (0, 0, 0) red = (255, 0, 0) white = (255, 255, 255) blue1 = 92, 124, 188 bluegreen1 = (24, 184, 228) green1 = (112, 156, 56) green2 = (48, 76, 40) green3 = (32, 56, 32) backstripe1 = (8, 20, 32) landgrid = (16, 40, 24) baseheader = (48, 60, 112) def lab(txt): return Label(text = txt, color = blue1) def HB(lst): return HBox(children = lst) def VB(lst): return VBox(children = lst) def bframe(widget): return OPFrame(child = widget, fwidth = 2, color = blue1) akeys = [k for k, v in txt.data.alphax.rawdata] #sect = txt.data.alphax.citizens lstbox = StrLstBox() class ActLabel(Label): def on_mousebutton(self, event): lstbox.set_lines(getattr(txt.data.alphax, self.text.lower())) #Label(on_mousebutton = (lambda self, e: lstbox.set_lines(getattr(txt.data.alphax, self.text.lower())))) #def ALabel(text #VBox(children = [lab(line) for line in sect]) wid = HBox(children = [VBox(children = [ActLabel(text = line, color = blue1) for line in akeys]), Bar(color = blue1), bframe(lstbox)]) wid = HBox(children = [VBox(children = [ActLabel(text = line, color = blue1) for line in akeys]), bframe(lstbox)]) #for i in range(1): # wid = bframe(wid) widfr = bframe(wid) #wid = OPFrame(child = wid, fwidth = 2, color = blue1) #menu = HB([lab('fail'), Glue(setsize = (10, 0), expand = (0, 0)), lab('klunk'), Glue(expand = (1, 0)), lab('quit')]) #m = Expand(child = menu, set_expand = (1, 0)) #widgets = VB([widfr, lab('miso')]) #widgets = widfr #main(widgets)
true
b7e2f3cec92beead03406ff1c75d15c341b6b4be
Python
noeljn/projectPy
/MineSweeper - old/TileGrid.py
UTF-8
3,992
3.34375
3
[]
no_license
import Tile import random class TileGrid(): def __init__(self, size_x, size_y, mines): self.size = [size_x, size_y] self.allTiles = [] self.mines = mines def ClickTile(self, cord): tile = self.GetTile(cord) if tile.open == False and tile.flaged == False: self.Flood(tile) def LoadGrid(self): for x in range(self.size[0]): for y in range(self.size[1]): self.allTiles.append(Tile.Tile(x,y)) def GenerateMines(self, cord): ##Find the all the safe Tiles safeTile = self.GetTile(cord) lista = [] for tile in safeTile.adjacentTiles: lista.append(tile) lista.append(safeTile) #Loops until all mines have been randomized i = 0 while(i < self.mines): i+=1 cord = [random.randint(0, self.size[0] - 1), random.randint(0, self.size[1] - 1)] cord = "Tile_{}_{}".format(cord[0], cord[1]) self.check = True for tile in lista: #Checks if cord already is mined or is a safeTile if tile.name == cord: self.check = False i+=-1 if self.check: for t in self.allTiles: #Mines the Tile and adds the Tile to the list of safeTiles if t.name == cord: t.Mine() lista.append(t) #After all mines have been placed we want all Tiles to check how many tiles there are around them #Then Flood on the starting Tile self.CheckMinesNear() self.Flood(safeTile) def __str__(self): #Returns the board of mines string = " " for y in range(self.size[1]): string += "\n" string += " ".join(str(self.allTiles[x]) for x in range(y*self.size[0], y*self.size[0] + self.size[0])) return string def addAdjacentTiles(self): #Adds the tiles around a tile to the list -> adjacentTiles for t in self.allTiles: for cord in t.adjacentCords: for tile in self.allTiles: if tile.name == "Tile_{}_{}".format(cord[0] + t.gridPosition[0], cord[1] + t.gridPosition[1]): t.adjacentTiles.append(tile) def CheckMinesNear(self): for tile in self.allTiles: tile.MinesNear() def Flood(self, startTile): stack = [] #Budget stack if(startTile.minesNear == 0): stack.append(startTile) startTile.OpenTile() while len(stack) > 0 : currentTile = stack.pop() for t in currentTile.adjacentTiles: if t.minesNear == 0 and t.mined == False and t.open == False: stack.append(t) if t.mined == False: t.OpenTile() #Returns False if you lose and True if you win, and 0 if neither def CheckWin(self): #Checks if all Tiles that shoud be open are and that all mines are not open win = 0 for tile in self.allTiles: if tile.mined and tile.open: win = False return win elif tile.mined == False and tile.open == False: return win win = True return win def RevealTiles(self): for tile in self.allTiles: tile.OpenTile() def GetTile(self, cord): #Get a tile by its position in the xy - plane cord = str(cord).strip() for t in self.allTiles: if "Tile_{}_{}".format(cord[0], cord[1]) == t.name: return t def CheckInput(self, cord): #Checks if input from user is valid try: cord = str(cord).strip() for t in self.allTiles: if "Tile_{}_{}".format(cord[0], cord[1]) == t.name: return False return True except: return True
true
1b2383c9b657e3d57d20d75db3dcc81dc043c63f
Python
shihaamabr/dhiraaguddns
/ipupdate.py
UTF-8
1,611
2.609375
3
[]
no_license
import requests import re LOGIN_URL = "https://portal.dhivehinet.net.mv/adsls/login_api" HOME_URL = "https://portal.dhivehinet.net.mv/home" #The creds DHIRAAGU_USERNAME="" DHIRAAGU_PASSWORD="" NOIP_USERNAME="" NOIP_PASSWORD="" NOIP_DOMAIN="" def login(username= DHIRAAGU_USERNAME, password=DHIRAAGU_PASSWORD): headers = {'Content-Type': 'application/x-www-form-urlencoded'} form_data = {"data[adsl][username]": username, "data[adsl][password]": password} login_req = requests.post(LOGIN_URL,headers=headers, data=form_data) # 200 means the creds are correct if login_req.status_code == 200: cookie = login_req.cookies home_page = requests.get(HOME_URL,cookies=cookie) #get the home page with the returned cookie return home_page.text else: return False #tries to find ip address from the homepage with regex def getIp(string): #tries to filter so it will work if two ip matches are found results = re.findall('<td colspan="2">(.*)</td>', string) result = ' '.join(result for result in results) #finds the ip in the new string ip_candidates = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", result) if len(ip_candidates) == 1: return ip_candidates[0] else: return "NULL" page = login() DHIRAAGU_IPADDRESS = getIp(page) print("IP Adress: {}".format(DHIRAAGU_IPADDRESS)) #Send IP to no-ip.com for DNS update requests.get("http://"+(NOIP_USERNAME)+":"+(NOIP_PASSWORD)+"@dynupdate.no-ip.com/nic/update?hostname="+(NOIP_DOMAIN)+"&myip="+(DHIRAAGU_IPADDRESS))
true
94f467320af0a054779611335db320995ed9a3cb
Python
AntonCharnichenka/Python-GitHub-repositories
/python_repositories.py
UTF-8
1,718
3.5
4
[]
no_license
"""This module represents an application collecting information of the most starred GitHub python projects and saving it in the form of diagram""" # import import requests import pygal # create api request and save response url = 'https://api.github.com/search/repositories?q=language:python&sort=stars' r = requests.get(url) print('Status code:', r.status_code) # status_code stores indication of request successful execution (code - 200) # save api response response_dict = r.json() # api returns its response in the json format (dictionary) print('Total repositories:', response_dict['total_count']) # analysis of information about repositories repositories_dicts = response_dict['items'] names, plot_dicts = [], [] for repository_dict in repositories_dicts: names.append(repository_dict['name']) description = repository_dict['description'] if not description: description = 'No description provided.' plot_dict = {'value': repository_dict['stargazers_count'], 'label': description, 'xlink': repository_dict['html_url']} plot_dicts.append(plot_dict) # create configuration object for visualization my_config = pygal.Config() my_config.x_label_rotation = 45 my_config.show_legend = False my_config.title_font_size = 18 my_config.label_font_size = 12 my_config.major_label_font_size = 14 my_config.truncate_label = 15 my_config.show_y_guides = False my_config.width = 1000 # create visualization chart = pygal.Bar(my_config, show_legend=False) chart.title = 'Most-Starred Python Projects on GitHub' chart.x_labels = names chart.add('', plot_dicts) chart.render_to_file('python_most_starred_github_repositories.svg')
true
13e8ded59dc860805a03b2631f14dda3ba849a31
Python
saikumarkorada20/Fairness-Aware-Ranking
/utils.py
UTF-8
97
2.609375
3
[]
no_license
def swap(dict, pos1, pos2): dict[pos1], dict[pos2] = dict[pos2], dict[pos1] return dict
true
8f0a29f67229e4f4f2c5e397984b536c0b7d8854
Python
wldp/quantitative
/quantitative/performance.py
UTF-8
1,501
2.90625
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import pandas as pd from scipy import stats APPROX_BDAYS_PER_MONTH = 21 APPROX_BDAYS_PER_YEAR = 252 MONTHS_PER_YEAR = 12 WEEKS_PER_YEAR = 52 TOTAL_SECONDS_IN_A_DAY = 24 * 60 * 60. TOTAL_SECONDS_IN_A_YEAR = TOTAL_SECONDS_IN_A_DAY * 365.24 ANNUALIZATION_FACTORS = {'daily': APPROX_BDAYS_PER_YEAR, 'weekly': WEEKS_PER_YEAR, 'monthly': MONTHS_PER_YEAR} def annualized_return(start_equity, end_equity, hold_period, period=365): return ((1 + cumulative_return(start_equity, end_equity)) ** (period / hold_period) - 1) def cumulative_return(start_equity, end_equity): return (end_equity - start_equity) / start_equity def drawdown(array): pass def downside_risk(): pass def information_ratio(): pass def sharpe_ratio(returns, risk_free): if isinstance(returns, (pd.Series, pd.DataFrame)): returns = returns.values if isinstance(risk_free, (pd.Series, pd.DataFrame)): risk_free = risk_free.values return np.mean(returns - risk_free) / np.std(returns - risk_free) def sortino_ratio(annualized_returns, target_return, downside_risk): # return (annualized_returns - target_return) / downside_risk pass def skew(returns): return stats.skew(returns) def kurtosis(returns): return stats.kurtosis(returns) def value_at_risk(returns, percentile=.05): return np.percentile(np.sort(returns, percentile * 100))
true
6c06f9429da3de42ba6675cd6d57a0a76d57850f
Python
981377660LMT/algorithm-study
/11_动态规划/dp分类/概率dp/掷色子/1223. 掷骰子模拟.py
UTF-8
1,277
3.640625
4
[]
no_license
from functools import lru_cache from typing import List # 投掷骰子时,连续 掷出数字 i 的次数不能超过 rollMax[i] # 计算掷 n 次骰子可得到的不同点数序列的数量。 # 1 <= n <= 5000 # rollMax.length == 6 # 1 <= rollMax[i] <= 15 MOD = int(1e9 + 7) class Solution: def dieSimulator(self, n: int, rollMax: List[int]) -> int: @lru_cache(None) def dfs(index: int, pre: int, count: int) -> int: if index == n: return 1 res = 0 for cur in range(1, 7): nextCount = 1 if cur != pre else count + 1 if nextCount <= rollMax[cur - 1]: res += dfs(index + 1, cur, nextCount) res %= MOD return res res = 0 for start in range(1, 7): res += dfs(1, start, 1) res %= MOD return res print(Solution().dieSimulator(n=2, rollMax=[1, 1, 2, 2, 2, 3])) # 输出:34 # 解释:我们掷 2 次骰子,如果没有约束的话,共有 6 * 6 = 36 种可能的组合。但是根据 rollMax 数组,数字 1 和 2 最多连续出现一次,所以不会出现序列 (1,1) 和 (2,2)。因此,最终答案是 36-2 = 34。
true
5f9d96db203a140a435feb1547aa9426165d96bf
Python
ZeyadYasser/Stanford-CS231n-Projects
/pytorch-testing/momentum/momentum.py
UTF-8
2,451
2.8125
3
[]
no_license
import torch import numpy as np import matplotlib.pyplot as plt device = torch.device('cpu') N, D_in, H, D_out = 64, 1000, 100, 10 x = torch.randn(N, D_in, device=device) y = torch.randn(N, D_out, device=device) start_w1 = np.random.randn(D_in, H) start_w2 = np.random.randn(H, D_out) start_w1 = np.random.randn(D_in, H) start_w2 = np.random.randn(H, D_out) start_v1 = np.zeros_like(start_w1) start_v2 = np.zeros_like(start_w2) def SGD_Momentum(lr, moment): losses = [] w1 = torch.tensor(start_w1, dtype=torch.float32, device=device, requires_grad=True) v1 = torch.tensor(start_v1, dtype=torch.float32, device=device) w2 = torch.tensor(start_w2, dtype=torch.float32, device=device, requires_grad=True) v2 = torch.tensor(start_v2, dtype=torch.float32, device=device) for t in range(100): y_pred = x.mm(w1).clamp(min=0).mm(w2) loss = (y_pred - y).pow(2).sum() loss.backward() with torch.no_grad(): v1 = moment * v1 + lr * w1.grad v2 = moment * v2 + lr * w2.grad w1 -= v1 w2 -= v2 w1.grad.zero_() w2.grad.zero_() losses.append(loss.item()) return losses def SGD(lr): losses = [] w1 = torch.tensor(start_w1, dtype=torch.float32, device=device, requires_grad=True) w2 = torch.tensor(start_w2, dtype=torch.float32, device=device, requires_grad=True) for t in range(100): y_pred = x.mm(w1).clamp(min=0).mm(w2) loss = (y_pred - y).pow(2).sum() loss.backward() with torch.no_grad(): w1 -= lr * w1.grad w2 -= lr * w2.grad w1.grad.zero_() w2.grad.zero_() losses.append(loss.item()) return losses # After many trials I found those Hyperparameters to be better for SGD+Momentum momentum_losses = SGD_Momentum(1e-6, 0.8) # From hyperparameter_optim.py I found lr of 1e-6 to perform well sgd_losses = SGD(1e-6) size = len(momentum_losses) print(size) for i in range(size): print("Iteration: %i, SGD+Momentum Loss=%.6f, SGD Loss=%.6f" \ % (i+1, momentum_losses[i], sgd_losses[i])) f, (ax1, ax2) = plt.subplots(1, 2, sharey=True, sharex=True, figsize=(14,5)) # Plot log(loss) instead due to large loss at the beginning ax1.plot(np.log(momentum_losses), 'b') ax1.set_title('SGD+Momentum') ax2.plot(np.log(sgd_losses), 'r') ax2.set_title('SGD') plt.ylabel('log(loss)') plt.show()
true
e0c3f271b83a5ae70cfbd0850f8d041f125aa045
Python
Saalu/Google_Automation
/python_list/slice.py
UTF-8
270
3.53125
4
[]
no_license
words =['Hello', 'world', '!'] print(words, type(words)) print(words[1]) m = [[1,2,3], [4,5,6]] print(m[1][2]) squares = [0,1,4,9,16,25,36, 49, 64] print(squares[2:6]) print(squares[6:]) print(squares[:6]) print(squares[::2]) print(squares[2:6:3]) print(squares[::-1])
true
2fe7d57017c570ae2fc1d6f666ceb74df5069717
Python
fannifulmer/exam-trial-basics
/box/box.py
UTF-8
694
4.78125
5
[]
no_license
# Create a class that represents a cuboid: # It should take its three dimensions as constructor parameters (numbers) # It should have a method called `get_surface` that returns the cuboid's surface # It should have a method called `get_volume` that returns the cuboid's volume class Cuboid(object): def __init__(self, h = 10, w = 20, l = 30): self.h = h self.w = w self.l = l def get_surface(self): return(2 * (self.l*self.w + self.w*self.h + self.h*self.l)) def get_volume(self): return(self.l * self.w * self.h) box = Cuboid(10, 20, 30) print(box.get_surface()) # should print 2200 print(box.get_volume()) # should print 6000
true
f2ee0620b99869ac1a6891b00e99ce623a0a390b
Python
jian01/tp-elixir-tdl
/python_client/blocking_socket_transferer.py
UTF-8
2,959
2.90625
3
[]
no_license
import os import socket import select from typing import Optional DEFAULT_SOCKET_BUFFER_SIZE = 4096 OK_MESSAGE = "OK" OK_MESSAGE_LEN = len(OK_MESSAGE.encode('utf-8')) SIZE_NUMBER_SIZE = 20 class SocketClosed(Exception): pass class BlockingSocketTransferer: def __init__(self, socket: socket): self.socket = socket self.poller = select.poll() self.poller.register(self.socket, select.POLLIN) def controlled_recv(self, size: int) -> bytes: data = self.socket.recv(size) if data == b'': raise SocketClosed return data @staticmethod def size_to_bytes_number(size: int) -> bytes: text = str(size) return text.zfill(SIZE_NUMBER_SIZE).encode('ascii') def receive_fixed_size(self, size) -> str: data = "" recv_size = 0 while recv_size < size: new_data = self.controlled_recv(size - recv_size) recv_size += len(new_data) data += new_data.decode('ascii') return data def send_ok(self): self.send_plain_text(OK_MESSAGE) def receive_ok(self): text = self.receive_plain_text() assert text == OK_MESSAGE def receive_file_data(self, file): file_size = int(self.receive_fixed_size(SIZE_NUMBER_SIZE)) self.send_ok() while file_size > 0: buffer = self.controlled_recv(DEFAULT_SOCKET_BUFFER_SIZE) file.write(buffer) file_size -= len(buffer) self.send_ok() def send_file(self, filename): file_size = os.stat(filename).st_size self.socket.sendall(self.size_to_bytes_number(file_size)) self.receive_ok() with open(filename, "rb") as file: while file_size > 0: buffer = file.read(DEFAULT_SOCKET_BUFFER_SIZE) self.socket.sendall(buffer) file_size -= DEFAULT_SOCKET_BUFFER_SIZE self.receive_ok() def send_plain_text(self, text): encoded_text = text.encode('utf-8') self.socket.sendall(self.size_to_bytes_number(len(encoded_text))) self.socket.sendall(encoded_text) def receive_plain_text(self, timeout: Optional[int] = None) -> str: if timeout: events = self.poller.poll(timeout) if not events: raise TimeoutError size_to_recv = int(self.receive_fixed_size(SIZE_NUMBER_SIZE)) result = "" recv_size = 0 while recv_size < size_to_recv: new_data = self.controlled_recv(size_to_recv - recv_size) result += new_data.decode('utf-8') recv_size += len(new_data) return result def abort(self): self.send_plain_text("ABORT") self.close() def close(self): self.socket.shutdown(socket.SHUT_WR) self.socket.close()
true
23a9f7ba8fec1049a274d62190f2fa46d1e3c253
Python
0x0400/LeetCode
/p1448.py
UTF-8
867
3.234375
3
[]
no_license
# https://leetcode.com/problems/count-good-nodes-in-binary-tree/ from common.tree import TreeNode # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def goodNodes(self, root: TreeNode) -> int: cnt = 0 if not root: return cnt nodes = [(root, root.val)] while nodes: nextNodes = [] for (node, maxVal) in nodes: if node.val >= maxVal: cnt += 1 if node.left: nextNodes.append((node.left, max(node.val, maxVal))) if node.right: nextNodes.append((node.right, max(node.val, maxVal))) nodes = nextNodes return cnt
true
6d7d6020fe7fa988ccf7c7711c7e5a207680e266
Python
JosePabloOnVP/IntroTestingAutomatizado
/Python/page_object/06_page_base/home_page.py
UTF-8
369
2.671875
3
[]
no_license
from search_page import SearchPage from page_base import BasePage class HomePage(BasePage): def navigate_to(self): self._driver.get(self._url) def search_for(self, keyword): search_field = self._driver.find_element_by_id("search") search_field.send_keys(keyword) search_field.submit() return SearchPage(self._driver)
true
adc949d60eaff162819e973593ba0f9e9990b05f
Python
ascle/repo-python
/placa/temp.py
UTF-8
1,404
3.078125
3
[]
no_license
import cv2 import numpy as np def draw_lines(hough, image, nlines): n_x, n_y=image.shape #convert to color image so that you can see the lines draw_im = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) for (rho, theta) in hough[0][:nlines]: try: x0 = np.cos(theta)*rho y0 = np.sin(theta)*rho pt1 = ( int(x0 + (n_x+n_y)*(-np.sin(theta))), int(y0 + (n_x+n_y)*np.cos(theta)) ) pt2 = ( int(x0 - (n_x+n_y)*(-np.sin(theta))), int(y0 - (n_x+n_y)*np.cos(theta)) ) alph = np.arctan( (pt2[1]-pt1[1])/( pt2[0]-pt1[0]) ) alphdeg = alph*180/np.pi #OpenCv uses weird angle system, see: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_houghlines/py_houghlines.html if abs( np.cos( alph - 180 )) > 0.8: #0.995: cv2.line(draw_im, pt1, pt2, (255,0,0), 2) if rho>0 and abs( np.cos( alphdeg - 90)) > 0.7: cv2.line(draw_im, pt1, pt2, (0,0,255), 2) except: pass cv2.imwrite("3HoughLines.png", draw_im, [cv2.IMWRITE_PNG_COMPRESSION, 12]) img = cv2.imread('exCars/image_0040.jpg') gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) flag,b = cv2.threshold(gray,160,255,cv2.THRESH_BINARY) cv2.imwrite("1tresh.jpg", b) element = np.ones((3,3)) b = cv2.erode(b,element) cv2.imwrite("2erodedtresh.jpg", b) edges = cv2.Canny(b,10,100,apertureSize = 3) cv2.imwrite("3Canny.jpg", edges) hough = cv2.HoughLines(edges, 1, np.pi/180, 200) draw_lines(hough, b, 100)
true
9af7724e7432957553e05edb512b0de00743f6b6
Python
Nymphet/sensors-plotter
/esp8266_probe_request/analyzer/time_series_histogram.py
UTF-8
1,790
3.078125
3
[]
no_license
import pandas as pd import numpy as np import matplotlib.pyplot as plt import esp8266_aux def calc_nbins(df, time_window_length): # calculate how many bins do we need start_time = df['time'].min() end_time = df['time'].max() nbins = (end_time - start_time) / pd.to_timedelta(time_window_length) nbins = int(nbins) if nbins == 0: nbins = 1 return nbins def histograms_of_time(df, time_window_length='10min', first_n = 10): # count how many times the signal has appeared in each time_window (Histogram) # the default method df.hist() works great, but it is based on matplotlib and is not # available over internet, so we will calculate the data only, and plot it with bokeh # later. # calculate histogram for each MAC MAC_list = esp8266_aux.get_MAC_list(df) histograms = dict() for MAC in MAC_list[:first_n]: histogram = histogram_of_time(df, MAC, time_window_length='10min') histograms[MAC] = histogram return histograms def histogram_of_time(df, MAC, time_window_length='10min'): nbins = calc_nbins(df, time_window_length) macdf = df[df['PeerMAC'] == MAC] n, time_bins, patches = plt.hist(macdf.time, bins=nbins) plt.close('all') histogram = pd.DataFrame() histogram['n'] = n histogram['time_bins'] = time_bins[:-1] # the time_bins plt.hist gives us are in gregorian days format, so we need to convert # them to unix timestamps first, then convert timestamps to pd.Timestamp histogram['time_bins'] = esp8266_aux.gregorian_to_timestamp(histogram['time_bins']) histogram['time_bins'] = pd.to_datetime(histogram['time_bins'], unit='s') return histogram #filename = '../data/data-2018-11-25.csv' #df = esp8266_aux.preprocess_csv_file(filename)
true
486b2045cee1c4e8e54b3cd6dabb1ab3380c5293
Python
giggzy/go-api-exercise
/scripts/gen_sample_json.py
UTF-8
2,194
3.15625
3
[]
no_license
#!/usr/bin/env python import json from string import ascii_letters # generate sample json file for testing json_file = 'sample.json' def gen_services(): records_count = 15 services = { "services" : []} #service_list = services["services"] for i in range(records_count): """ " { "name": "NameA", "id": "2" "desc": "A blah, blah, blah", "version_count": 2 "url": "https://example.com/serviveA" "versions": { [ { "name": "version1", "id": 1, }, { "name": "version2", "id": 2, } ] } }, """ current = ascii_letters[i] name = current + "_Service" desc = current + " blah, blah, blah" version_count = i + 1 url = "https://example.com/" + name versions = [] for v in range(version_count): versions.append({ "name": "version_" + str(v), "id": str(v) }) services["services"].append({ "id": str(version_count), "name": name, "description": desc, "url": url, "versionCount": version_count, "versions": versions }) return services """ # print out json file with open(json_file, 'w') as f: for c in ascii_letters: service_name += c f.write(json.dumps(data, indent=4)) """ """ Think about how to generate the json file Argparse? type Services struct { Services []Service `json:"services"` } type Service struct { Name string `json:"name"` Description string `json:"description"` VersionCount int `json:"versionCount"` } """ def main(): services = gen_services() with open(json_file, 'w') as f: f.write(json.dumps(services, indent=4)) #f.write(json.dump(json, indent=4)) if __name__ == "__main__": main()
true
1be3c13565fff4836bfa5ac062d038c14d24cb1e
Python
Cooler-ykt/my_education
/try_labs/Turtle/tur13.py
UTF-8
1,814
3.4375
3
[]
no_license
import math import turtle def draw_circle(Radius,pos_angle,rotation): n=36 storona=2*Radius*math.sin(math.pi/n) angle=360/n if rotation=='Left': nach_povorot=pos_angle+180/n turtle.seth(nach_povorot) for i in range(n): turtle.forward(storona) turtle.left(angle) else: nach_povorot=pos_angle-180/n turtle.seth(nach_povorot) for i in range(n): turtle.forward(storona) turtle.right(angle) def draw_duga(Radius,pos_angle,rotation): n=180 storona=2*Radius*math.sin(math.pi/n) angle=360/n if rotation=='Left': nach_povorot=pos_angle+180/n turtle.seth(nach_povorot) for i in range(n//2): turtle.forward(storona) turtle.left(angle) else: nach_povorot=pos_angle-180/n turtle.seth(nach_povorot) for i in range(n//2): turtle.forward(storona) turtle.right(angle) turtle.shape('turtle') turtle.color("black", "yellow") turtle.begin_fill() draw_circle(100,90,"Left") turtle.end_fill() turtle.seth(180) turtle.penup() turtle.forward(100) turtle.seth(90) turtle.forward(45) turtle.seth(180) turtle.forward(30) turtle.seth(90) turtle.color("black", "blue") turtle.pendown() turtle.begin_fill() draw_circle(10,90,"Left") turtle.end_fill() turtle.penup() turtle.seth(0) turtle.forward(60) turtle.pendown() turtle.begin_fill() draw_circle(10,90,"Right") turtle.end_fill() turtle.penup() turtle.seth(180) turtle.forward(30) turtle.seth(270) turtle.forward(55) turtle.seth(90) turtle.width(10) turtle.pendown() turtle.forward(40) turtle.penup() turtle.backward(45) turtle.color("red", "black") turtle.seth(180) turtle.forward(50) turtle.pendown() draw_duga(50,270,"Left")
true
96a443d78d0d764fac88294f248fcdfca978e251
Python
vrai-group/sequenceLearning
/neural-network.py
UTF-8
6,214
2.609375
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import datetime import re from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers.embeddings import Embedding from keras.preprocessing import sequence from sklearn.utils import compute_class_weight from sklearn.metrics import confusion_matrix, classification_report filename = "./dataset/data" # 15 Milan dataset http://ailab.wsu.edu/casas/datasets/ def load_dataset(): # dateset fields timestamps = [] sensors = [] values = [] activities = [] activity = '' # empty print('Loading dataset ...') with open(filename, 'rb') as features: database = features.readlines() for line in database: # each line f_info = line.decode().split() # find fields if 'M' == f_info[2][0] or 'D' == f_info[2][0] or 'T' == f_info[2][0]: # choose only M D T sensors, avoiding unexpected errors if not ('.' in str(np.array(f_info[0])) + str(np.array(f_info[1]))): f_info[1] = f_info[1] + '.000000' timestamps.append(datetime.datetime.strptime(str(np.array(f_info[0])) + str(np.array(f_info[1])), "%Y-%m-%d%H:%M:%S.%f")) sensors.append(str(np.array(f_info[2]))) values.append(str(np.array(f_info[3]))) if len(f_info) == 4: # if activity does not exist activities.append(activity) else: # if activity exists des = str(' '.join(np.array(f_info[4:]))) if 'begin' in des: activity = re.sub('begin', '', des) if activity[-1] == ' ': # if white space at the end activity = activity[:-1] # delete white space activities.append(activity) if 'end' in des: activities.append(activity) activity = '' features.close() # dictionaries: assigning keys to values temperature = [] for element in values: try: temperature.append(float(element)) except ValueError: pass sensorsList = sorted(set(sensors)) dictSensors = {} for i, sensor in enumerate(sensorsList): dictSensors[sensor] = i # print(dictSensors) activityList = sorted(set(activities)) dictActivities = {} for i, activity in enumerate(activityList): dictActivities[activity] = i # print(dictActivities) valueList = sorted(set(values)) dictValues = {} for i, v in enumerate(valueList): dictValues[v] = i # print(dictValues) dictObs = {} count = 0 for key in dictSensors.keys(): if "M" in key: dictObs[key + "OFF"] = count count += 1 dictObs[key + "ON"] = count count += 1 if "D" in key: dictObs[key + "CLOSE"] = count count += 1 dictObs[key + "OPEN"] = count count += 1 if "T" in key: for temp in range(0, int((max(temperature) - min(temperature)) * 2) + 1): dictObs[key + str(float(temp / 2.0) + min(temperature))] = count + temp # print(dictObs) X = [] Y = [] for kk, s in enumerate(sensors): if "T" in s: X.append(dictObs[s + str(round(float(values[kk]), 1))]) else: X.append(dictObs[s + str(values[kk])]) Y.append(dictActivities[activities[kk]]) data = [X, Y, dictActivities] return data def dataset_split(X, Y, train_perc): X_train = [] Y_train = [] X_test = [] Y_test = [] max_lenght = 0 for i, n in enumerate(Y): if i == 0: seq = n count = 1 a = i else: if seq == n: count += 1 else: if seq != n: if np.random.rand() < train_perc: X_train.append(X[a:a+count]) Y_train.append(seq) else: X_test.append(X[a:a+count]) Y_test.append(seq) if count > max_lenght: max_lenght = count seq = n count = 1 a = i if i == (len(Y) - 1): if np.random.rand() < train_perc: X_train.append(X[a:a + count]) Y_train.append(seq) else: X_test.append(X[a:a + count]) Y_test.append(seq) if count > max_lenght: max_lenght = count # same lenght for all sequences X_train = sequence.pad_sequences(X_train, maxlen=max_lenght) X_test = sequence.pad_sequences(X_test, maxlen=max_lenght) split = [X_train, X_test, Y_train, Y_test, max_lenght] return split def create_model(X_train, X_test, max_lenght, dictActivities): model = Sequential() model.add(Embedding(len(X_train)+len(X_test), 32, input_length=max_lenght)) model.add(LSTM(100)) model.add(Dense(len(dictActivities), activation='sigmoid')) model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) print(model.summary()) return model data = load_dataset() split = dataset_split(data[0], data[1], 0.8) #train_perc from 0 to 1 model = create_model(split[0], split[1], split[4], data[2]) # train the model print("Begin training ...") class_weight = compute_class_weight('balanced', np.unique(data[1]), data[1]) #use as optional argument in the fit function model.fit(split[0], split[2], validation_split=0.2, epochs=10, batch_size=64) # evaluate the model print("Begin testing ...") scores = model.evaluate(split[1], split[3], verbose=0) print("Accuracy: %.2f%%" % (scores[1]*100)) Y_pred = model.predict_classes(split[1], verbose=0) print(confusion_matrix(split[3], Y_pred)) target_names = list(data[2].keys()) print(classification_report(split[3], Y_pred, target_names=target_names))
true
f74519b5c5656780baed141fc8da2aaab3e91651
Python
antiface/OpenCLNoise
/openclnoise/genericfilter.py
UTF-8
612
2.59375
3
[ "MIT" ]
permissive
class GenericFilter(object): def __init__(self,filename,invocation,defines={}): self.__defines = defines self.__FILENAME = filename self.invocation = invocation def __loadCode(self): code = '' for k,v in self.__defines.iteritems(): code += '#define {0} {1}\n'.format(k,v) with open(self.__FILENAME,'r') as inp: code += inp.read() code += '\n' return code def __repr__(self): return 'Generic Filter: file: {0}; inv: "{1}"'.format(self.__FILENAME,self.invocation) def build_source(self): return self.__loadCode() def build_invocation_string(self): return self.invocation
true
46ceb4dc55ba23bcca3f793a30955925f7bc8d76
Python
luiscabus/ufal-linux-package-manager
/src/Graph.py
UTF-8
1,934
3.875
4
[]
no_license
from collections import defaultdict class Graph: def __init__(self, connections, directed=False): self.graph = defaultdict(set) self.directed = directed self.addConnections(connections) # Generate the graph dictionary based on the array of touples that # represent every edge in the graph. # Example: [(1, 2), (1, 3), (3, 4), (2, 4)] def addConnections(self, connections): for a, b in connections: self.add(a, b) # Add an edge to the dictionary def add(self, a, b): self.graph[a].add(b) if (not self.directed): self.graph[b].add(a) # Remove an edge and all it's references from a dictionary def remove(self, a): for n, ref in self.graph.iteritems(): try: ref.remove(a) except KeyError: pass try: del self.graph[a] except KeyError: pass # Find the shortest path between two nodes def shortest_path(self, start, end, path =[]): path = path + [start] if start == end: return path shortest = None for node in self.graph[start]: if node not in path: newpath = find_shortest_path(self.graph, node, end, path) if newpath: if not shortest or len(newpath) < len(shortest): shortest = newpath return shortest # Utilitary recursive function that implements a DFS algorithm and # stacks the result in the 'output'(reference) parameter def topological_util(self, visited_list, vertex, output): if not visited_list[vertex]: visited_list[vertex] = True for neighbour in self.graph[vertex]: try: self.topological_util(visited_list, neighbour, output) except: pass output.append(vertex) # Function to create the 'visited_list' to avoid cycles and start # the topological_sort for the given vertex def topological_sort(self, vertex): output = [] visited_list = defaultdict() for item in self.graph: visited_list[item] = False self.topological_util(visited_list, vertex, output) return output
true
66abacbb5d1057a912c17a333823b1037f3e7750
Python
omou-org/mainframe
/account/management/commands/migrate_summit_accounts.py
UTF-8
6,055
2.640625
3
[]
no_license
from django.core.management.base import BaseCommand, CommandError from django.db import transaction import pandas as pd import uuid import math from account.models import Student from account.models import Parent from account.models import Note from django.contrib.auth.models import User from rest_framework.authtoken.models import Token class Command(BaseCommand): help = "Closes the specified poll for voting" bad_rows = [] rowNum = 1 def handle(self, *args, **options): self.stdout.write(self.style.SUCCESS("Successfully called")) dataframe = self.read_data_from_file("data/summit_student.csv") self.insert_accounts(dataframe) print(str(self.bad_rows)) def read_data_from_file(self, file_name): return pd.read_csv(file_name) def insert_accounts(self, dataframe): # add school to student # add primary parent & add relationship from student to parent # parent info: # phone # # secondary phone # # first name # last name # city, address, ZIP # email # Make note obj # add relationship from note to student # add try/catch and print error lines to console # TODO: check objects created in database for row in dataframe.itertuples(): print(str(self.rowNum)) parent = self.create_parent(row) student_user = self.create_student(row, parent) self.create_note(row, student_user) self.rowNum += 1 def translate_gender(self, gender): if str(gender) == "Female": return "F" elif str(gender) == "Male": return "M" else: return "U" def get_first_name_last_name_from_field(self, name_field): words = name_field.split() if len(words) == 0: raise Exception("improper name field") if len(words) == 1: return words[0], "" return " ".join(words[:-1]), words[-1] def create_parent(self, row): if isinstance(row[15], float): return None try: ( parent_first_name, parent_last_name, ) = self.get_first_name_last_name_from_field(row[15]) username = row[18] email = row[18] if isinstance(row[18], float): username = uuid.uuid4() email = "" else: queryset = Parent.objects.filter(user__email=email) if queryset.count() > 0: return queryset[0] with transaction.atomic(): parent_user = User.objects.create_user( username=username, password="password", first_name=parent_first_name, last_name=parent_last_name, email=email, ) parent = Parent.objects.create( user=parent_user, user_uuid=parent_user.username, address=row[22], city=row[23], phone_number=row[16], state=row[24], zipcode=row[25], secondary_phone_number=row[17], account_type="PARENT", ) parent.save() return parent except Exception as e: print("ERROR: creating parent obj", row) print(e) self.bad_rows.append(str(self.rowNum) + " parent") return None def create_student(self, row, parent): try: student_user = User.objects.create_user( username=uuid.uuid4(), password="password", first_name=row[3], last_name=row[4], ) Token.objects.get_or_create(user=student_user) grade = row[10] if math.isnan(float(grade)): student = Student.objects.create( user=student_user, gender=self.translate_gender(row[9]), user_uuid=row[2], address=row[22], city=row[23], state=row[24], zipcode=row[25], school=row[11], primary_parent=parent, account_type="STUDENT", ) else: student = Student.objects.create( user=student_user, gender=self.translate_gender(row[9]), user_uuid=row[2], address=row[22], city=row[23], state=row[24], zipcode=row[25], school=row[11], primary_parent=parent, grade=row[10], account_type="STUDENT", ) student.save() return student_user except Exception as e: print("ERROR: creating student obj", row) print(e) self.bad_rows.append(str(self.rowNum) + " student") return None def create_note(self, row, student_user): try: note = Note.objects.create(user=student_user, body=row[26]) note.save() except Exception as e: print("ERROR: creating note obj", row) print(e) self.bad_rows.append(str(self.rowNum) + " note") return None # Index to column name mapping: # 1 "Criteria" # 2 "Student ID" # 3 "First Name" # 4 "Last Name" # 5 "Other Name" # 6 "Student" # 7 "Enroll Date" # 8 "Status" # 9 "Gender" # 10 "Grade" # 11 "School" # 12 "Updated Date" # 13 Updated by" # 14 "Title" # 15 "Parent" # 16 "H Phone" # 17 "C Phone" # 18 "E-mail address" # 19 "Emergency" # 20 "E Phone" # 21 "Ref By" # 22 "Address" # 23 "City" # 24 "State" # 25 "Zip" # 26 "Note"
true
a28715538a30eb9c3377d5ae97edfb413d550e7a
Python
Itchy83/PythonStudie
/Lektion 5/Diverse notater Kap8.py
UTF-8
1,296
3.96875
4
[]
no_license
def HelloWorld(): # simpel defination """ Her er det en god ide at beskrive hvad funktionen gør""" print('Hello World') HelloWorld() #Køres ved bare at skrive navnet på den. print('----------------------------------------------------------------------------------') def hej(navn): """Det her en en def med input, i det her tilfælde et navn""" print('Hej, ' + navn + '! Hvordan har du det?') hej('Mille-My') hej('Bjarne') print('----------------------------------------------------------------------------------') def MinBil(brand, variation): """ Her er det brugt to input i defination """ print('\nMin bil er en ' + brand + '!') print('Min ' + brand + ' er en model ' + variation + '!') MinBil('Fiat', 'Panda') print('----------------------------------------------------------------------------------') def dyr(navn, slags='Hund'): # I definatinon defineres, hvis intet bliver nævnt når man kalder def, hund er "Default" """I den her defination eksempel, prøver kun at nævn en af tingene""" print('\nNaboens dyr er en ' + slags + '!') print('Deres ' + slags + ' hedder ' + navn + '!') dyr(navn='Bailey') print('----------------------------------------------------------------------------------')
true
a49f62f2d4b50078a54296a4630e5e8d5e87b821
Python
ClickHouse/ClickHouse
/tests/ci/git_test.py
UTF-8
2,797
2.515625
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env python from unittest.mock import patch import os.path as p import unittest from git_helper import Git, Runner, CWD class TestRunner(unittest.TestCase): def test_init(self): runner = Runner() self.assertEqual(runner.cwd, p.realpath(p.dirname(__file__))) runner = Runner("/") self.assertEqual(runner.cwd, "/") def test_run(self): runner = Runner() output = runner.run("echo 1") self.assertEqual(output, "1") def test_one_time_writeable_cwd(self): runner = Runner() self.assertEqual(runner.cwd, CWD) runner.cwd = "/bin" self.assertEqual(runner.cwd, "/bin") runner.cwd = "/" self.assertEqual(runner.cwd, "/bin") runner = Runner("/") self.assertEqual(runner.cwd, "/") runner.cwd = "/bin" self.assertEqual(runner.cwd, "/") class TestGit(unittest.TestCase): def setUp(self): """we use dummy git object""" run_patcher = patch("git_helper.Runner.run", return_value="") self.run_mock = run_patcher.start() self.addCleanup(run_patcher.stop) update_patcher = patch("git_helper.Git.update") update_mock = update_patcher.start() self.addCleanup(update_patcher.stop) self.git = Git() update_mock.assert_called_once() self.git.run("test") self.run_mock.assert_called_once() self.git.new_branch = "NEW_BRANCH_NAME" self.git.new_tag = "v21.12.333.22222-stable" self.git.branch = "old_branch" self.git.sha = "" self.git.sha_short = "" self.git.latest_tag = "" self.git.description = "" self.git.commits_since_tag = 0 def test_tags(self): self.git.new_tag = "v21.12.333.22222-stable" self.git.latest_tag = "v21.12.333.22222-stable" for tag_attr in ("new_tag", "latest_tag"): self.assertEqual(getattr(self.git, tag_attr), "v21.12.333.22222-stable") setattr(self.git, tag_attr, "") self.assertEqual(getattr(self.git, tag_attr), "") for tag in ( "v21.12.333-stable", "v21.12.333-prestable", "21.12.333.22222-stable", "v21.12.333.22222-production", ): with self.assertRaises(Exception): setattr(self.git, tag_attr, tag) def test_tweak(self): self.git.commits_since_tag = 0 self.assertEqual(self.git.tweak, 1) self.git.commits_since_tag = 2 self.assertEqual(self.git.tweak, 2) self.git.latest_tag = "v21.12.333.22222-testing" self.assertEqual(self.git.tweak, 22224) self.git.commits_since_tag = 0 self.assertEqual(self.git.tweak, 22222)
true
65022c75224ede628132264342756e49fd35e4de
Python
CINick72/project_euler
/pe152/pe152_2.py
UTF-8
3,731
2.90625
3
[]
no_license
import time from decimal import * start = time.clock( ) getcontext().prec = 16 def is_prime(n): if n == 2 or n == 3: return True if n < 2 or n%2 == 0: return False if n < 9: return True if n%3 == 0: return False r = int(n**0.5) f = 5 while f <= r: # print '\t',f if n%f == 0: return False if n%(f+2) == 0: return False f +=6 return True def lcm(a,b): m = a*b while a != 0 and b != 0: if a > b: a %= b else: b %= a return m // (a+b) def sum(b, set1, set2): s1 = 0 s2 = 0 k = 1 l1 = len(set1) l2 = len(set2) lb = len(b) for i in b[::-1]: if l1 >= lb and l1 >= k: s1 = s1 + ( p[set1[l1 - k]] if i == '1' else 0 ) if l2 >= lb and l2 >= k: s2 = s2 + ( p[set2[l2 - k]] if i == '1' else 0 ) k = k + 1 return (s1, s2) q = [0] * 81 p = [0] * 81 for i in range(2, 81): p[i] = Decimal(1/i**2) primes = [] for i in range(2, 81): if is_prime(i): primes.append(i) # print(primes) primes_in = [2, 3, 5, 7, 13] primes_out = [] for prime in primes: if not prime in primes_in: primes_out.append(prime) N = 80 set1 = [] for i in range(2, N+1): t = False for k in primes_in: if i % k == 0: t = True break if t: for k in primes_out: if i % k == 0: t = False break if t: set1.append(i) # set1 = [2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, # 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, # 25, 26, 27, 28, 29, 33, 34, 35, 36, 39, # 40, 41, 42, 44, 46, 47, 48, 49, 51, 56, # 58, 63, 68, 70, 72, 77] print(set1) set_length = len(set1) print(set_length) st_index = 3 com = (set_length - st_index + 1) // 2 print(com) b = [] for i in range(1, 2**com): b.append(bin(i)[2:]) board = st_index + com # print(board) s1 = [] s2 = [] for bb in b[::-1]: s = sum(bb, set1[st_index:board], set1[board:]) s1.append(s[0]) s2.append(s[1]) t = Decimal(1/4 + 1/9 + 1/16) res = [] def find(): s1.sort(reverse=True) s2.sort() z = Decimal('0.0000000000000001') cnt = 0 for s in [Decimal(0.5) - t]: k = 0 k1 = 0 if s1[0] + s2[len(s2)-1] >= s: while True: try: st = s1[k] + s2[k1] diff = st - s if abs(diff) <= z: res.append([s1[k], s2[k1], '', '', [2, 3, 4]]) cnt = cnt + 1 k = k + 1 # k1 = k1 + 1 elif diff > 0: k = k + 1 else: k1 = k1 + 1 except: break print(cnt) find() print('find=', time.clock() - start) def reveal(b, start, end): ret = [] k = 1 l1 = end - start for i in b[::-1]: if l1 >= k: if i == '1': ret.append(set1[start + (l1 - k)]) k = k + 1 return ret for bb in b[::-1]: s = sum(bb, set1[st_index:board], set1[board:]) for r in res: if s[0] == r[0]: r[2] = bb if s[1] == r[1]: r[3] = bb rr = [] for r in res: r[4].extend(reveal(r[2], st_index, board)) r[4].extend(reveal(r[3], board, set_length)) r[4].sort() l = 1 for kk in r[4]: l = lcm(l, kk) s = 0 for kk in r[4]: s += ( l / kk ) ** 2 check = s / l**2 if check == 0.5 and not r[4] in rr: print(r[4]) rr.append(r[4]) print(len(rr)) print('end=', time.clock() - start)
true
0837c9c2c80f4e1bf9bdbefc47ee806a8ae5b909
Python
ningshengit/small_spider
/PythonExample/PythonExample/菜鸟编程网站基础实例/Python 十进制转二进制、八进制、十六进制.py
UTF-8
360
3.265625
3
[]
no_license
实例(Python 3.0+) # -*- coding: UTF-8 -*- # Filename : test.py # author by : www.runoob.com # 获取用户输入十进制数 dec = int(input("输入数字:")) print("十进制数为:", dec) print("转换为二进制为:", bin(dec)) print("转换为八进制为:", oct(dec)) print("转换为十六进制为:", hex(dec))
true
07be75b9620010aec525ba04ac8248e834c370c3
Python
lisasil/insight_journal
/insight_journal/stats.py
UTF-8
4,834
3.34375
3
[]
no_license
#!/usr/bin/env python import sys import nltk import re import os from nltk.sentiment.vader import SentimentIntensityAnalyzer from collections import Counter class Stats: def __init__(self, entry): self.entry = entry #save text to file f = open('entry.txt', 'w') f.write(self.entry + '\n') f.close() def __del__(self): os.remove('entry.txt') def getTotalWords(self): total_words = 0 #open file with open('entry.txt') as entry: #iterate through each word in file for line in entry.readlines(): for word in line.split(): #increment count total_words += 1 return total_words def getTenseDist(self): #get input body of text e = open('entry.txt').read() #tokenize the file by word word_list = nltk.word_tokenize(e) #tag each part of speech and store in list word_tag_list = nltk.pos_tag(word_list) #iterate through words and count occurrences of words and tags #word_count = Counter(word for word,tag in word_tag_list) #tag_count = Counter(tag for word,tag in word_tag_list) #split into past/present/future past_tags = filter(lambda x: x[1] == 'VBD' or x[1] == 'VBN', word_tag_list) present_tags = filter(lambda x: x[1] == 'VBG' or x[1] == 'VBP' or x[1] == 'VBZ', word_tag_list) future_tags = filter(lambda x: x[1] == 'MD', word_tag_list) #convert filter objects to lists past_list = list(past_tags) present_list = list(present_tags) future_list = list(future_tags) #count occurences past_count = len(past_list) present_count = len(present_list) future_count = len(future_list) total_count = past_count + present_count + future_count if total_count == 0: total_count = 1 tense_tuple = (round((past_count/total_count) * 100), round((present_count/total_count) * 100), round((future_count/total_count) * 100)) return tense_tuple def getPolarizedScores(self): #get input body of text e = open('entry.txt').read() #tokenize the file by sentence sentence_list = nltk.sent_tokenize(e) #declare vars total_neg = 0 total_neu = 0 total_pos = 0 total_com = 0 total = 0 num_sent = 0; #load object sid = SentimentIntensityAnalyzer() #determine score for each sentence for sentence in sentence_list: scores = sid.polarity_scores(sentence) for score in scores: if score == "neg": total_neg += scores[score] elif score == "neu": total_neu += scores[score] elif score == "pos": total_pos += scores[score] else: total_com += scores[score] #print(score) #print(scores[score]) #print("========================================") #print("{:-<40}\n{}\n".format(sentence, str(ss))) #print(total_neg) #print(total_neu) #print(total_pos) #print(total_com) total = total_neg + total_neu + total_pos #also equals to number of sentences #make tuple of scores total_scores = (round((total_neg/total) * 100), round((total_neu/total) * 100), round((total_pos/total) * 100), round((total_com/total) * 100), round(total)) return total_scores def getPolarizedWords(self): #get input body of text e = open('entry.txt').read() #tokenize the file by sentence sentence_list = nltk.sent_tokenize(e) #declare lists pos_word_list=[] neu_word_list=[] neg_word_list=[] #iterate through list for sentence in sentence_list: #tokenize by word tokenized_sentence = nltk.word_tokenize(sentence) #load object sid = SentimentIntensityAnalyzer() #split words by polarity for word in tokenized_sentence: if (sid.polarity_scores(word)['compound']) >= 0.1: pos_word_list.append(word) elif (sid.polarity_scores(word)['compound']) <= -0.1: neg_word_list.append(word) else: neu_word_list.append(word) #score = sid.polarity_scores(sentence) #print('\nScores:', score) #print("========================================") #make tuple of lists word_polarity = (neg_word_list, neu_word_list, pos_word_list) return word_polarity
true
f972bd423ce4ce537899156b690f734ab57ea11b
Python
ejziel/Trabalho-Pratico-1
/client.py
UTF-8
2,135
2.875
3
[]
no_license
import socket import sys import pickle import time import os import tqdm # arguments host = sys.argv[1] port = int(sys.argv[2]) filename = sys.argv[3] SEPARATOR = "<SEPARATOR>" BUFFER_SIZE = 1024 def request_file(filename, host, port, direc): # create the client socket s = socket.socket() print(f"[+] Connecting to {host}:{port}") s.connect((host, port)) print("[+] Connected.") # send the filename s.send(f"{filename}".encode()) received = s.recv(BUFFER_SIZE).decode() aux, filesize = received.split(SEPARATOR) if (int(aux)): # convert to integer filesize = int(filesize) # start receiving the file from the socket # and writing to the file stream progress = tqdm.tqdm(range(filesize), f"Receiving {filename}", unit="B", unit_scale=True, unit_divisor=1024) with open(direc+"/"+filename, "wb") as f: for _ in progress: # read 1024 bytes from the socket (receive) bytes_read = s.recv(BUFFER_SIZE) if not bytes_read: # nothing is received # file transmitting is done break # write to the file the bytes we just received f.write(bytes_read) # update the progress bar progress.update(len(bytes_read)) print(f"[+] File {filename} saved") else: print(f"[+] File {filename} does not exist in the server") # close socket s.close() def request_list(host, port): # create the client socket s = socket.socket() print(f"[+] Connecting to {host}:{port}") s.connect((host, port)) print("[+] Connected.") aux = "cache_list" # request list s.send(f"{aux}".encode()) received = s.recv(BUFFER_SIZE) received = pickle.loads(received) if not received: print("[+] There are no cached files ") else: print(f"[+] Cached files: {received} ") if(filename == "list"): request_list(host, port) else: direc = sys.argv[4] request_file(filename, host, port, direc)
true
3fcedfd7954755a92d0e74690a27d6993170b567
Python
Sunshine-Queen/Test
/day03/morra.py
UTF-8
402
3.796875
4
[]
no_license
import random player=int(input("请输入:剪刀(0),石头(1),布(2):")) computer=random.randint(0,2) if((player == 0)and(computer == 2))or ((player == 1)and(computer == 0))or((player==2)and(computer==1)): print("获胜,哈哈哈,你太厉害了") elif computer==player: print("平局,要不要在玩一次") else: print("输了,不要灰心呐,再来一次")
true
d6771c041edfa61e1a70f17cd8292fb4380124be
Python
danbikle/tsds
/public/class08/class08a.py
UTF-8
359
2.59375
3
[]
no_license
""" class08a.py This script should help me do the lab of class08. Ref: http://www.tsds4.us/cclasses/class08#lab Demo: rm -f allpredictions.csv wget http://www.spy611.com/csv/allpredictions.csv python class08a.py """ import pandas as pd allpredictions_df = pd.read_csv('allpredictions.csv') print(allpredictions_df.head()) 'bye'
true
b16687b32d5640a2f8ccd8521c8cbd5c0a281116
Python
pattiestarfish/root
/machine learning/logistic regression/feature_importance.py
UTF-8
1,423
3.5
4
[]
no_license
#determines how much weight each feature carries import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression from exam import exam_features_scaled, passed_exam_2 # Train a sklearn logistic regression model on the normalized exam data model_2 = LogisticRegression() model_2.fit(exam_features_scaled,passed_exam_2) # Assign and update coefficients coefficients = model_2.coef_ # coefficients = coefficients.tolist()[0] # Plot bar graph plt.bar([1,2],coefficients) plt.xticks([1,2],['hours studied','math courses taken']) plt.xlabel('feature') plt.ylabel('coefficient') plt.show() #--------------------------------------------- #Classification Thresholding import numpy as np from exam import hours_studied, calculated_coefficients, intercept def log_odds(features, coefficients, intercept): return np.dot(features, coefficients) + intercept def sigmoid(z): denominator = 1 + np.exp(-z) return 1 / denominator # Create predict_class() function here def predict_class(features, coefficients, intercept, threshold): calculated_log_odds = log_odds(features, coefficients, intercept) probabilities = sigmoid(calculated_log_odds) return np.where(probabilities >= threshold, 1, 0) # Make final classifications on Codecademy University data here final_results = predict_class(hours_studied, calculated_coefficients, intercept, 0.5) print(final_results)
true
f246fa706e779f700d25e62bacc8995fa88aff15
Python
KashishGambhir/python-programs
/data structure.py
UTF-8
516
3.75
4
[]
no_license
#append(obj) list.append(obj) alis=[11,'abc','xyz','python','abc'] alis.append(2009) print alis #count list.count(obj) print alis.count(123) print alis.count('abc') #extend() alis=['abc','ab','xyz','qrst'] blis=[1,2,3,4,5] alis.extend(blis) print alis #index() list.index(obj) alis=['abc','ab','xyz','qrst'] alis.index('ab') #insert() list.insert(no,obj) alis.insert(3,2000) print alis #remove() alis.remove(2000) print alis #sort() alis.sort() print alis #nested list() list=["hello",.20,10,[30,40]] list[3]
true
abfa1ce25a32b7062d2cbc9f363437fe4066f0b3
Python
LIGHT1213/PythonStudy
/6/a&a+.py
UTF-8
200
3.546875
4
[]
no_license
f = open('1.txt', 'a+') #打开文件,返回一个文件对象 content = input("请输入写入的内容:") f.write (content) str=f.read() f.close() #关闭文件 print(str)
true
74d76dd31155fcd10ab2c1d648c2565d9a641f9a
Python
Jane-QinJ/Python
/workspace/diaryProject.py
UTF-8
3,043
3.296875
3
[]
no_license
#!/usr/bin/python # -*- coding: utf-8 -*- from Tkinter import * import os #写日记 def write(): textVar.set("") #清空entry text.delete("0.0","end") #清空text label.config(text="写日记模式") listBox.pack_forget() #隐藏listBox entry.pack() #显示entry text.pack() #显示pack #保存 def save(): title = textVar.get() + ".txt" #获取标题 content = text.get("0.0","end") if title != ".txt": fileObj = open(title,"wb") #打开一个文件 fileObj.write(content) #写入内容 fileObj.close() #关闭打开的文件 label.config(text = "已保存") else: label.config(text="请输入标题") def read(): listBox.delete(0,END) #清空listBox dir = os.getcwd() #获取当前目录 list = os.listdir(dir) #获取目录内所有文件 showText = "看日记模式" if len(list) == 0: #如果当前没有日记 showText += "(日记本是空的)" #设置提示 label.config(text=showText) for item in list: #遍历 listBox.insert(0,item) #向listBox插入数据 listBox.bind('<Double-Button-1>',showDiary) #绑定双击事件 entry.pack_forget() #隐藏entry text.pack_forget() #隐藏text listBox.pack() #显示listBox #显示日记内容 def showDiary(event): title = listBox.get(listBox.curselection()) #获取点击的日记名 showTitle = title[:-4] #截取至倒数第4个字符 textVar.set(showTitle) #设置日记标题 fileObj = open(title,"r+") #打开对应标题的文件 content = fileObj.read() #获取文件内容 text.delete("0.0","end") #清空 text text.insert("end",content) #把内容显示在text上 fileObj.close() #关闭打开的文件 listBox.pack_forget() #隐藏listBox entry.pack() #显示entry text.pack() #显示 text #创建日记文件夹 def initDiary(): dir = os.getcwd() #获取当前.py 文件目录 list = os.listdir(dir) #获取当前目录中所有文件 haveDiary = False #设置一个变量,是否存在diary文件夹,默认为False for item in list: #遍历 if item == "diary": #判断是否存在diary文件夹 haveDiary = True #如果有,设置diary为True if haveDiary == False: #如果haveDiary为False os.mkdir("diary") #创建diary文件夹 os.chdir("./diary") #改变.py工作目录到diary内 initDiary() # 需要的控件 root = Tk() root.geometry('500x400') root.title("程序媛日记本") saveBtn = Button(root,text="保存",command=save) saveBtn.pack(side=LEFT, anchor='sw') quitBtn = Button(root,text="退出",command=quit) quitBtn.pack(side=RIGHT,anchor='se') #command = write表示点击按钮时 会执行write方法 writeBtn = Button(root,text="写日记", command=write) writeBtn.pack(side=BOTTOM,anchor='s') readBtn = Button(root,text="看日记",command=read) readBtn.pack(side=BOTTOM,anchor='s') textVar = StringVar() entry = Entry(root,textvariable=textVar) text = Text(root) listBox = Listbox(root,height = 300) label = Label(root) label.pack() root.mainloop()
true
c8b80e5eacb9c5789c60afceeb87c815d6e0fb03
Python
jtmorgan/ds4ux
/notifications/bgt-traffic-solutions/challenge3.py
UTF-8
1,249
3.5625
4
[ "MIT" ]
permissive
""" How much southbound traffic does the Burke-Gilman get, on average, during Morning commute hours? How much does it get during evening commute hours? """ import bgt_traffic morning_commute_hours = ['07:00:00 AM', '08:00:00 AM', '09:00:00 AM'] evening_commute_hours = ['04:00:00 PM', '05:00:00 PM', '06:00:00 PM'] am_sb_totals = [] pm_sb_totals = [] for dkey, dval in bgt_traffic.traffic.items(): am_sb = 0 pm_sb = 0 for hkey, hval in dval.items(): if hkey in morning_commute_hours: am_sb += (hval['ped sb'] + hval['bike sb']) elif hkey in evening_commute_hours: pm_sb += (hval['ped sb'] + hval['bike sb']) else: pass am_sb_totals.append(am_sb) pm_sb_totals.append(pm_sb) print("On average, %d people travel south on the Burke-Gilman during morning commute hours." % ((sum(am_sb_totals)/len(am_sb_totals)))) print("On average, %d people travel south on the Burke-Gilman during evening commute hours." % ((sum(pm_sb_totals)/len(pm_sb_totals)))) #this isn't what I expected! #On average, 118 people travel south on the Burke-Gilman during morning commute hours. #On average, 203 people travel south on the Burke-Gilman during evening commute hours.
true
f697a67deb5c7c880a3419da250de0f3c1f96d3d
Python
ShamHolder/ML-Algorithms
/project/msh_machinelearning/bayes.py
UTF-8
2,368
3.3125
3
[]
no_license
import numpy as np from math import sqrt from math import pi from math import exp class NaiveBayes(): def __init__(self, train, test): summary = summarizeByClass(train) predictions = list() for row in test: predicitons.append(predict(summary, row)) return predictions def predict(self, summary, row): probabiities = calcClassProbability(summary, row) bestLabel, bestProb = None, -1 for classValue, probability in probabilities.items(): if bestLabel is None or probability > bestProb: bestProb = probability bestLabel = classValue return bestLabel def classSeparate(self, dataset): separated = dict() for i in range(len(dataset)): vector = dataset[i] classValue = vector[-1] if (classValue not in separated): separated[classValue] = list() separated[classValue].append(vector) return separated def summarizeDataset(self, dataset): summaries = [(mean(col), stdDev(col), len(col)) for col in zip(*dataset)] del(summaries[-1]) return summaries def summarizeByClass(self, dataset): separated = self.classSeparate(dataset) summaries = dict() for classValue, row in separated.items(): summaries[classValue] = self.summarizeDataset(row) return summaries def calcClassProbability(self, summaries, row): totalRows = sum([summaries[label][0][-1] for label in summaries]) probabilities = dict() for classValue, classSummaries in summaries.items(): probabilities[classValue] = summaries[classValue][0][-1] / float(totalRows) for i in range(len(classSummaries)): mean, stddev, count = classSummaries[i] probabilities[classValue] *= calcGaussianProbability(row[i], mean, stddev) return probabilities def mean(self, data): return sum(data)/float(len(data)) def stdDev(self, data): avg = mean(data) variance = sum([(x-avg)**2 for x in data]) / float(len(data)-1) return sqrt(variance) def calcGaussianProbability(self, x, mean, stddev): return (1 / (sqrt(2*pi) * stddev)) * exp(-((x-mean)**2 / (2 * stddev**2)))
true
228649fef4457654c075ceee16598076dc2d0b32
Python
oyatziry/KnightsTourGame
/knightsTour.py
UTF-8
2,053
4
4
[]
no_license
import Tkinter as Tk class KnightGame: def __init__(self): self.canvas_width = 500 self.canvas_height = 500 self.tiles = {} self.canvas = Tk.Canvas(root, width = self.canvas_width, height = self.canvas_height) self.canvas.pack() self.currentRow = 0 self.currentColumn = 0 def knight_tour(self, n): numRows = n numColumns = n cellWidth = int(self.canvas_width/numColumns) cellHeight = int(self.canvas_height/numRows) for column in range(numColumns): for row in range(numRows): x1 = column * cellWidth y1 = row * cellHeight x2 = x1 + cellWidth y2 = y1 + cellHeight tile = self.canvas.create_rectangle(x1,y1,x2,y2, fill='white') self.tiles[row, column] = tile self.canvas.tag_bind(tile, "<1>", lambda event, row=row, column=column: self.newTile(row, column)) currentTile = self.canvas.itemconfigure(self.tiles[0,0], fill="orange") def newTile(self, row, column): #make current tile orange tile = self.tiles[row, column] tile_color = self.canvas.itemcget(tile, "fill") new_color = "orange" old_color = "blue" dx = abs(row - self.currentRow) dy = abs(column - self.currentColumn) oldTile = self.tiles[self.currentRow, self.currentColumn] #if legal, change to orange & change old tile to blue & push positions to variables row and column if (dx==1 and dy==2) or (dx==2 and dy==1): self.canvas.itemconfigure(tile, fill=new_color) #change current tile to orange self.canvas.itemconfigure(oldTile, fill=old_color) #change old tile to blue self.currentRow = row self.currentColumn = column #if not legal, dont do anything else: print("Illegal move. Try again.") root = Tk.Tk() gui = KnightGame() gui.knight_tour(5) #takes in any value 'n' to make board root.mainloop()
true
fc54ea774641fbe8872a63257f36b0dee0b8ef12
Python
profcarlos/MSG
/6sv1/Py6S_tutorial_test.py
UTF-8
5,423
2.65625
3
[]
no_license
from Py6S import * import os #s = SixS('C:\\Users\\carlos.silveira\\Dropbox\\newPython\\brdf\\sixsV1_1_dell.exe') s = SixS('C:\\Users\\carlos.silveira\\Dropbox\\newPython\\6SV1\\sixsV1_1_lab.exe') s.produce_debug_report() #classmethod UserWaterAndOzone(water, ozone) #Set 6S to use an atmosphere defined by an amount of water vapour and ozone. #Arguments: #•water – The total amount of water in a vertical path through the atmosphere (in g/cm^2) #•ozone – The total amount of ozone in a vertical path through the atmosphere (in cm-atm) s.atmosprofile = AtmosProfile.UserWaterAndOzone(0.1, 0.02) s.aot550 = 0.01 #class Py6S.Wavelength #Select one or more wavelengths for the 6S simulation. s.wavelength = Wavelength(0.56, 0.71) print('wavelength:') print(s.wavelength) #class Py6S.AtmosCorr #Class representing options for selecting atmospheric correction settings for 6S. #classmethod AtmosCorrBRDFFromReflectance(reflectance) #Set 6S to perform atmospheric correction using a fully BRDF-represented surface, using a given reflectance value. s.atmos_corr = AtmosCorr.AtmosCorrBRDFFromReflectance(0.4) print('atmos_corr: ') print(s.atmos_corr) #classmethod HomogeneousMODISBRDF(par1, par2, par3) #Parameterisation for a surface BRDF based on the MODIS Operational BRDF model. s.ground_reflectance = GroundReflectance.HomogeneousMODISBRDF(0.4, 0.001, 0.05) s.ground_altitude = 1.2 # Not change results! s.ground_pressure = 1000 print('ground_reflectance:') print(s.ground_reflectance) #class Geometry.User Stores parameters for a user-defined geometry for 6S. #Attributes: # •solar_z – Solar zenith angle # •solar_a – Solar azimuth angle # •view_z – View zenith angle •view_a – View azimuth angle # •day – The day the image was acquired in (1-31) # •month – The month the image was acquired in (0-12) s.geometry = Geometry.User() s.geometry.solar_z = 30.2610 # Forth data in angles: sunzen >> File 201505111300_angles.tif s.geometry.solar_a = 83.9880 # Second data in angles: sunaz s.geometry.view_z = 58.1128 # Third data in angles: satzen s.geometry.view_a = 104.4975 # First data in angles: sataz #class Py6S.AeroProfile Class representing options for Aerosol Profile s.aeroprofile = AeroProfile.UserProfile(AeroProfile.Continental) s.aeroprofile.add_layer(5, 0.34) # Add a 5km-thick layer with an AOT of 0.34 s.aeroprofile.add_layer(10, 0.7) # Add a 10km-thick layer with an AOT of 0.7 s.aeroprofile.add_layer(100, 0.01) # Add a 100km-thick layer with an AOT of 0.01 #print(s.aeroprofile.values) s.run() print("----") print( "aot550" + "\t" + str(s.outputs.aot550)) print( "apparent_radiance" + "\t" + str(s.outputs.apparent_radiance)) print( "apparent_reflectance" + "\t" + str(s.outputs.apparent_reflectance)) print( "atmos_corrected_reflectance_brdf" + "\t" + str(s.outputs.atmos_corrected_reflectance_brdf)) print( "atmos_corrected_reflectance_lambertian" + "\t" + str(s.outputs.atmos_corrected_reflectance_lambertian)) print( "atmospheric_intrinsic_radiance" + "\t" + str(s.outputs.atmospheric_intrinsic_radiance)) print( "atmospheric_intrinsic_reflectance" + "\t" + str(s.outputs.atmospheric_intrinsic_reflectance)) print( "azimuthal_angle_difference" + "\t" + str(s.outputs.azimuthal_angle_difference)) print( "background_radiance" + "\t" + str(s.outputs.background_radiance)) print( "background_reflectance" + "\t" + str(s.outputs.background_reflectance)) print( "coef_xa" + "\t" + str(s.outputs.coef_xa)) print( "coef_xb" + "\t" + str(s.outputs.coef_xb)) print( "coef_xc" + "\t" + str(s.outputs.coef_xc)) print( "day" + "\t" + str(s.outputs.day)) print( "diffuse_solar_irradiance" + "\t" + str(s.outputs.diffuse_solar_irradiance)) print( "diffuse_solar_irradiance" + "\t" + str(s.outputs.diffuse_solar_irradiance)) print( "environmental_irradiance" + "\t" + str(s.outputs.environmental_irradiance)) print( "ground_altitude" + "\t" + str(s.outputs.ground_altitude)) print( "ground_pressure" + "\t" + str(s.outputs.ground_pressure)) print( "int_funct_filt" + "\t" + str(s.outputs.int_funct_filt)) print( "int_solar_spectrum" + "\t" + str(s.outputs.int_solar_spectrum)) print( "measured_radiance" + "\t" + str(s.outputs.measured_radiance)) print( "month" + "\t" + str(s.outputs.month)) print( "percent_diffuse_solar_irradiance" + "\t" + str(s.outputs.percent_diffuse_solar_irradiance)) print( "percent_direct_solar_irradiance" + "\t" + str(s.outputs.percent_direct_solar_irradiance)) print( "percent_environmental_irradiance" + "\t" + str(s.outputs.percent_environmental_irradiance)) print( "pixel_radiance" + "\t" + str(s.outputs.pixel_radiance)) print( "pixel_reflectance" + "\t" + str(s.outputs.pixel_reflectance)) print( "scattering_angle" + "\t" + str(s.outputs.scattering_angle)) print( "solar_a" + "\t" + str(s.outputs.solar_a)) print( "solar_z" + "\t" + str(s.outputs.solar_z)) print( "total_gaseous_transmittance" + "\t" + str(s.outputs.total_gaseous_transmittance)) print( "view_a" + "\t" + str(s.outputs.view_a)) print( "view_z" + "\t" + str(s.outputs.view_z)) print( "visibility" + "\t" + str(s.outputs.visibility)) print( "wv_above_aerosol" + "\t" + str(s.outputs.wv_above_aerosol)) print( "wv_mixed_with_aerosol" + "\t" + str(s.outputs.wv_mixed_with_aerosol)) print( "wv_under_aerosol" + "\t" + str(s.outputs.wv_under_aerosol))
true
761006cd69862812867b58f3db875be2b5998265
Python
blank77/store
/zd_day06/main.py
UTF-8
1,026
3.078125
3
[]
no_license
from HTMLTestRunner import HTMLTestRunner import unittest import os tests = unittest.defaultTestLoader.discover(os.getcwd(),pattern="test_ss.py") ''' ''' runner = HTMLTestRunner.HTMLTestRunner( title="这是一份抖音的测试报告", #标题 description="这是一份详细的抖音的测试报告", #备注 verbosity=1, stream= open(file="抖音测试报告.html",mode="w+",encoding="utf-8") ) ''' verbosity是一个选项,表示测试结果的信息复杂度,有0、1、2 三个值 0 (静默模式): 你只能获得总的测试用例数和总的结果 比如 总共10个 失败2 成功8 1 (默认模式): 非常类似静默模式 只是在每个成功的用例前面有个“.” 每个失败的用例前面有个 “F” 2 (详细模式):测试结果会显示每个测试用例的所有相关的信息 并且 你在命令行里加入不同的参数可以起到一样的效果 加入 --quiet 参数 等效于 verbosity=0 加入--verbose参数等效于 verbosity=2 ''' runner.run(tests)
true
b0358407b77cff1df30b1955877c3a81517490ca
Python
AdityaRavipati/algo-ds
/anagram.py
UTF-8
762
3.015625
3
[]
no_license
# code from collections import defaultdict import sys def anagram(str_test): string = str_test.split() import pdb; pdb.set_trace() i = 0 str1 = string[0] str2 = string[1] l1 = len(str1) l2 = len(str2) if l1 != l2: print("NO") sys.exit("NO") d = defaultdict(lambda: 0) while (i < l1 and i < l2 and (str1[i] and str2[i])): d[str1[i]] = d[str1[i]] + 1 d[str2[i]] = d[str2[i]] - 1 i += 1 for i in range(0, l1): if d[str1[i]]: print("NO") sys.exit("NO") print("YES") #anagram("wxrzvimgedlenxnqjideqhzrpubtunekwyqf rklteuwmkkrelkkteqggptpeqfsvbeyyawxqekiqunejslsgwxfkrbtqlbfejxdfuqhpbdkiebkqicscgiaedfgvqsfksrywf") anagram('aditya atyida')
true
c7f618c9c71bdd9db3a0a3f810f0266ac643fa1c
Python
victor3r/search-algorithms
/Stack.py
UTF-8
715
4.03125
4
[ "MIT" ]
permissive
class Stack: def __init__(self, size): self.size = size self.cities = [None] * self.size self.top = -1 def push(self, city): if not Stack.fullStack(self): self.top += 1 self.cities[self.top] = city else: print("A pilha já está cheia") def pop(self): if not Stack.emptyStack(self): temp = self.cities[self.top] self.top -= 1 return temp else: print("A pilha já está vazia") def getTop(self): return self.cities[self.top] def emptyStack(self): return self.top == -1 def fullStack(self): return self.top == self.size - 1
true
c2c0c360feed62177ba14473c17020cbb9ec37f9
Python
RethikNirmal/Optical-Character-Recognition
/data_extract.py
UTF-8
3,482
2.546875
3
[]
no_license
from scipy import misc import numpy as np import cv2 image_size = (54,128) import h5py def createImageData(datapoint, output_size, path): rawimg = cv2.imread(path+datapoint['filename']) img = np.array(cv2.resize(rawimg, output_size)) return img, rawimg.shape def generateData(data, n=1000): ''' generates flattened SVHN dataset ''' Ximg_flat = [] Xidx_flat = [] ycount_flat = [] ycoord_flat = [] ylabel_flat = [] for datapoint in np.random.choice(data, size=n, replace=False): print(datapoint) img,_ = createImageData(datapoint, image_size, 'train/') for i in range(0,datapoint['length']): Ximg_flat.append(img) Xidx_flat.append(i) ycount_flat.append(datapoint['length']) ylabel_flat.append(datapoint['labels'][i]) ylabel_flat = [0 if y==10 else int(y) for y in ylabel_flat] return np.array(Ximg_flat), np.array(Xidx_flat), np.array(ycount_flat), np.array(ylabel_flat) def read_process_h5(filename): """ Reads and processes the mat files provided in the SVHN dataset. Input: filename Ouptut: list of python dictionaries """ f = h5py.File(filename, 'r') groups = f['digitStruct'].keys() bbox_ds = np.array(f['digitStruct/bbox']).squeeze() names_ds =np.array(f['digitStruct/name']).squeeze() data_list = [] num_files = bbox_ds.shape[0] count = 0 for objref1, objref2 in zip(bbox_ds, names_ds): data_dict = {} # Extract image name names_ds = np.array(f[objref2]).squeeze() filename = ''.join(chr(x) for x in names_ds) data_dict['filename'] = filename #print filename # Extract other properties items1 = f[objref1].items() # print(f[objref1].keys()) # Extract image label labels_ds = np.array(f[objref1]['label']).squeeze() try: label_vals = [int(f[ref][:][0, 0]) for ref in labels_ds] except TypeError: label_vals = [labels_ds] data_dict['labels'] = label_vals data_dict['length'] = len(label_vals) # Extract image height height_ds = np.array(f[objref1]['height']).squeeze() try: height_vals = [f[ref][:][0, 0] for ref in height_ds] except TypeError: height_vals = [height_ds] data_dict['height'] = height_vals # Extract image left coords left_ds = np.array(f[objref1]['left']).squeeze() try: left_vals = [f[ref][:][0, 0] for ref in left_ds] except TypeError: left_vals = [left_ds] data_dict['left'] = left_vals # Extract image top coords top_ds = np.array(f[objref1]['top']).squeeze() try: top_vals = [f[ref][:][0, 0] for ref in top_ds] except TypeError: top_vals = [top_ds] data_dict['top'] = top_vals # Extract image width width_ds = np.array(f[objref1]['width']).squeeze() try: width_vals = [f[ref][:][0, 0] for ref in width_ds] except TypeError: width_vals = [width_ds] data_dict['width'] = width_vals data_list.append(data_dict) count += 1 #print ("Processed:" +count +" ," + num_files) return data_list
true
5f8981a5988e3cfc44f26ce28c2fe2bfd8259b78
Python
lucaskf1996/robotica2020
/aula02/atividade2.py
UTF-8
7,803
2.765625
3
[]
no_license
#!/usr/bin/python # -*- coding: utf-8 -*- import cv2 import numpy as np from matplotlib import pyplot as plt import time from math import pi import matplotlib.cm as cm # Parameters to use when opening the webcam. cap = cv2.VideoCapture(0) cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) lower = 0 upper = 1 magentaMin = np.array([139, 50, 100], dtype=np.uint8) magentaMax = np.array([189, 255, 200], dtype=np.uint8) cianoMin = np.array([85, 50, 100], dtype=np.uint8) cianoMax = np.array([135, 255, 255], dtype=np.uint8) #fonte para letra font = cv2.FONT_HERSHEY_SIMPLEX # Returns an image containing the borders of the image # sigma is how far from the median we are setting the thresholds def auto_canny(image, sigma=0.33): # compute the median of the single channel pixel intensities v = np.median(image) # apply automatic Canny edge detection using the computed median lower = int(max(0, (1.0 - sigma) * v)) upper = int(min(255, (1.0 + sigma) * v)) edged = cv2.Canny(image, lower, upper) # return the edged image return edged # Cria o detector BRISK brisk = cv2.BRISK_create() # Configura o algoritmo de casamento de features que vê *como* o objeto que deve ser encontrado aparece na imagem bf = cv2.BFMatcher(cv2.NORM_HAMMING) # Define o mínimo de pontos similares MINIMO_SEMELHANCAS = 10 # Essa função vai ser usada abaixo. Ela encontra a matriz (homografia) # que quando multiplicada pela imagem de entrada gera a imagem de def find_homography_draw_box(kp1, kp2, img_cena): out = img_cena.copy() src_pts = np.float32([ kp1[m.queryIdx].pt for m in good_matches ]).reshape(-1,1,2) dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good_matches ]).reshape(-1,1,2) # Tenta achar uma trasformacao composta de rotacao, translacao e escala que situe uma imagem na outra # Esta transformação é chamada de homografia # Para saber mais veja # https://docs.opencv.org/3.4/d9/dab/tutorial_homography.html M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC,5.0) matchesMask = mask.ravel().tolist() h,w = img_original.shape # Um retângulo com as dimensões da imagem original pts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2) # Transforma os pontos do retângulo para onde estao na imagem destino usando a homografia encontrada dst = cv2.perspectiveTransform(pts,M) # Desenha um contorno em vermelho ao redor de onde o objeto foi encontrado img2b = cv2.polylines(out,[np.int32(dst)],True,(255,255,0),5, cv2.LINE_AA) return img2b def find_good_matches(descriptor_image1, frame_gray): """ Recebe o descritor da imagem a procurar e um frame da cena, e devolve os keypoints e os good matches """ des1 = descriptor_image1 kp2, des2 = brisk.detectAndCompute(frame_gray,None) # Tenta fazer a melhor comparacao usando o algoritmo matches = bf.knnMatch(des1,des2,k=2) # store all the good matches as per Lowe's ratio test. good = [] for m,n in matches: if m.distance < 0.7*n.distance: good.append(m) return kp2, good original_bgr = cv2.imread("insper_logo.png") # Imagem a procurar img_original = cv2.cvtColor(original_bgr, cv2.COLOR_BGR2GRAY) original_rgb = cv2.cvtColor(original_bgr, cv2.COLOR_BGR2RGB) # Encontra os pontos únicos (keypoints) nas duas imagems kp1, des1 = brisk.detectAndCompute(img_original ,None) while(True): # Capture frame-by-frame print("New frame") ret, frame = cap.read() # Convert the frame to grayscale gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # A gaussian blur to get rid of the noise in the image blur = cv2.GaussianBlur(gray,(5,5),0) # Detect the edges present in the image bordas = auto_canny(blur) #Faz um map em HSV hsvFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) circles = [] # reseta o valor da distancia do papel papel = None # reseta o angulo e vetor para novo frame angulo = None vetor = () # reset das coordenadas dos centros magenta = () ciano = () # Obtains a version of the edges image where we can draw in color bordas_color = cv2.cvtColor(bordas, cv2.COLOR_GRAY2BGR) # HoughCircles - detects circles using the Hough Method. For an explanation of # param1 and param2 please see an explanation here http://www.pyimagesearch.com/2014/07/21/detecting-circles-images-using-opencv-hough-circles/ circles = None circles=cv2.HoughCircles(bordas,cv2.HOUGH_GRADIENT,2,40,param1=50,param2=100,minRadius=5,maxRadius=60) kp2, good_matches = find_good_matches(des1, gray) if len(good_matches) > MINIMO_SEMELHANCAS: print("Matches found") bordas_color = find_homography_draw_box(kp1, kp2, bordas_color) else: print("Not enough matches are found - %d/%d" % (len(good_matches),MINIMO_SEMELHANCAS)) if circles is not None: circles = np.uint16(np.around(circles)) for i in circles[0,:]: #print(i) mask = cv2.inRange(hsvFrame, magentaMin, magentaMax) if mask[i[1]][i[0]] > 200: cv2.circle(bordas_color,(i[0],i[1]),i[2],(int(frame[i[1],i[0]][0]), int(frame[i[1],i[0]][1]), int(frame[i[1],i[0]][2])),-1) # Salva as coordenadas do circulo magenta magenta = (i[0],i[1]) cv2.circle(bordas_color,(i[0],i[1]),2,(0,0,255),3) mask = cv2.inRange(hsvFrame, cianoMin, cianoMax) if mask[i[1]][i[0]] > 200: cv2.circle(bordas_color,(i[0],i[1]),i[2],(int(frame[i[1],i[0]][0]), int(frame[i[1],i[0]][1]), int(frame[i[1],i[0]][2])),-1) # Salva as coordenadas do círculo ciano ciano = (i[0],i[1]) cv2.circle(bordas_color,(i[0],i[1]),2,(0,0,255),3) #Desenha a reta entre os centros dos círculos try: cv2.line(bordas_color,magenta,ciano,(0,255,0),5) if magenta [0] > ciano[0] and magenta[1] > ciano[1]: dist = ((magenta[0]-ciano[0])**2+(magenta[1]-ciano[1])**2)**(1/2) papel = (777 * 14 / dist) angulo = (180-abs(np.arctan((magenta[1]-ciano[1])/(magenta[0]-ciano[0]))*180/np.pi)) elif magenta[0] > ciano[0] and ciano[1] > magenta[1]: dist = ((magenta[0]-ciano[0])**2+(ciano[1]-magenta[1])**2)**(1/2) papel = (777 * 14 / dist) angulo = (abs(np.arctan((ciano[1]-magenta[1])/(magenta[0]-ciano[0]))*180/np.pi)) elif ciano[0] > magenta[0] and ciano[1] > magenta[1]: dist = ((ciano[0]-magenta[0])**2+(ciano[1]-magenta[1])**2)**(1/2) papel = (777 * 14 / dist) angulo = (180-abs(np.arctan((ciano[1]-magenta[1])/(ciano[0]-magenta[0]))*180/np.pi)) elif ciano[0] > magenta[0] and magenta[1] > ciano[1]: dist = ((ciano[0]-magenta[0])**2+(magenta[1]-ciano[1])**2)**(1/2) papel = (777 * 14 / dist) angulo = (abs(np.arctan((magenta[1]-ciano[1])/(ciano[0]-magenta[0]))*180/np.pi)) elif ciano[1] == magenta[1]: angulo = "pi/2" else: angulo = "0" cv2.putText(bordas_color,"%.2f cm" % papel,(0,130), font, 2,(255,255,255),2,cv2.LINE_AA) cv2.putText(bordas_color,"%.2f graus" % angulo,(0,50), font, 2,(255,255,255),2,cv2.LINE_AA) except: print("cade circulo") # Display the resulting frame cv2.imshow('Detector de circulos',bordas_color) print("No circles were found") if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows()
true
fa66831213d32da5d67dcfbdbb07d492e91fdd73
Python
VikaOlegova/QuickSpec-to-XCTest-converter
/main.py
UTF-8
19,719
2.53125
3
[]
no_license
import re import os from subprocess import Popen, PIPE from pathlib import Path import shutil import string import sys def write_file(filename, text): dir = os.path.dirname(filename) if dir != '': os.makedirs(dir, exist_ok=True) with open(filename, 'w', encoding='utf-8') as f: f.write(text) class Node: def __init__(self, start: str, content: [str], subnodes): self.start = start self.content = content self.subnodes = subnodes class SwiftParser: def __init__(self, text: str): self.text = text lines = text.split('\n') index_of_class_end = lines.index('}') self.extensions = lines[index_of_class_end + 1:] lines = lines[:index_of_class_end + 1] self.root, _ = self.parse_node('root', lines) def parse_node(self, start, lines): content = [] subnodes = [] open_count = 0 close_count = 0 idx = 0 while idx < len(lines): line = lines[idx] quick_funcs = [ 'override func spec(', 'beforeEach', 'describe(', 'context(', 'sharedExamples(', 'it(', 'class ', 'final class ' ] quick_funcs = [ line.strip().startswith(x) for x in quick_funcs ] is_start_of_node = True in quick_funcs if is_start_of_node: if line.count('{') == line.count('}'): # it is oneliner subnodes.append(Node( start=line, content=[re.search(r'\{(.+)\}', line).group(1).strip()], subnodes=[] )) else: n, n_length = self.parse_node(line, lines[idx + 1:]) if 'sharedExample' in n.start: print() idx += n_length + 1 subnodes.append(n) else: open_count += line.count('{') close_count += line.count('}') if '}' == line.strip() and open_count == close_count - 1: return Node(start=start, content=content, subnodes=subnodes), idx else: content.append(line) idx += 1 return Node(start=start, content=content, subnodes=subnodes), idx def strip_array(arr: [str]): return [x.strip() for x in arr] class QuickParser: class TestCase: def __init__(self, naming: [str], content: [str], before_each: [str], vars: [str]): self.naming = naming self.content = content self.before_each = before_each self.vars = vars self.shared_example_name = None shared_examples_match = next((x for x in naming if 'sharedExamples(' in x), None) if shared_examples_match: self.shared_example_name = re.search(r'sharedExamples\("(.*?)"\)', shared_examples_match).group(1) def __init__(self, text: str, root_node: Node, extensions: [str]): self.text = text self.extensions = extensions self.common_setup = [] self.common_vars = [] self.test_cases: list[QuickParser.TestCase] = [] # self.imports = re.findall(r'import (\w+)', text, flags=re.MULTILINE) self.class_name = re.findall(r'class (\w+): QuickSpec \{', text, flags=re.MULTILINE)[0].replace('Spec', 'Tests') self.root_node = root_node self.process_node(root_node) self.strip_all() self.extract_commons() self.cleanup_test_cases() self.testable_name = None for var in self.common_vars: match = re.search(r'var (\w+): (\w+)', var) if match: var_name = match.group(1) var_type = match.group(2) if var_type in self.class_name: self.testable_name = var_name def strip_all(self): for result in self.test_cases: result.naming = strip_array(result.naming) result.content = strip_array(result.content) result.before_each = strip_array(result.before_each) result.vars = strip_array(result.vars) def process_node(self, node: Node, context_content=[], context_naming=[], context_before_each=[], context_vars=[], level=0): my_naming = context_naming + [node.start] my_content = list(context_content) my_before_each = list(context_before_each) my_vars = list(context_vars) for line in node.content: if line.strip().startswith('var '): my_vars.append(line) for n in node.subnodes: if n.start.strip().startswith('beforeEach {'): if level <= 3: my_before_each += n.content else: my_content += n.content my_content += node.content for n in node.subnodes: self.process_node(n, my_content, my_naming, my_before_each, my_vars, level + 1) convert_to_test_case = node.start.strip().startswith('it(') if next((x for x in node.content if x.strip().startswith('itBehavesLike(')), None): convert_to_test_case = True if convert_to_test_case: result = QuickParser.TestCase(naming=my_naming, content=my_content, before_each=my_before_each, vars=my_vars) self.test_cases.append(result) def extract_commons(self): def extract(array_key: str): res = {} for r in self.test_cases: for val in r.__dict__[array_key]: if val not in res: res[val] = 1 else: res[val] += 1 common = [x for x in res.keys() if res[x] == len(self.test_cases)] return common self.common_setup = extract("before_each") self.common_vars = extract("vars") def cleanup_test_cases(self): for test in self.test_cases: test.before_each = [x for x in test.before_each if x not in self.common_setup] test.content = [x for x in test.content if x not in self.root_node.content and not x.startswith("//swiftlint") and not x.startswith("// swiftlint") and x not in self.common_vars] class XCTestGenerator: def __init__(self, parser: QuickParser): self.parser = parser def generate_setup(self): common_before_each = self.parser.common_setup common_before_each_str = '\n'.join(common_before_each) return f'''override func setUp() {{ super.setUp() {common_before_each_str} }}\n\n''' def generate_teardown(self): tear_downs = [ x.split('=')[0] + '= nil' for x in self.parser.common_setup if '=' in x ] tear_downs.reverse() tear_downs_str = '\n'.join(tear_downs) return f'''override func tearDown() {{ {tear_downs_str} super.tearDown() }}\n\n''' def generate_test_case(self, test: QuickParser.TestCase, used_test_names: set): def convert_expectations(line: str): if not line.endswith('in') and line.count('{') == line.count('}'): line = re.sub(r'expect\((.+?)\) == (.+?)$', r'XCTAssertEqual(\g<1>, \g<2>)', line) line = re.sub(r'expect\((.+?)\) === (.+?)$', r'XCTAssertTrue(\g<1> === \g<2>)', line) line = re.sub(r'expect\((.+?)\).to\(beNil\(\)\)', r'XCTAssertNil(\g<1>)', line) line = re.sub(r'expect\((.+?)\).(?:notTo|toNot)\(beNil\(\)\)', r'XCTAssertNotNil(\g<1>)', line) line = re.sub(r'expect\((.+?)\).to\(beAKindOf\((.+?)\.self\)\)', r'XCTAssertTrue(\g<1> is \g<2>)', line) line = re.sub(r'expect\(expression:\s*(.+?)\s*\)\.to\(throwError\((.+)\)\)', r'customAssertThrowsError(expression: \g<1>, expectedError: \g<2>)', line) line = re.sub(r'expect\(expression:\s*(.+?)\s*\)\.to\(throwError\(\)\)', r'customAssertThrowsError(expression: \g<1>)', line) line = re.sub(r'expect\(expression:\s*(.+?)\s*\)\.(?:toNot|notTo)\(throwError\(\)\)', r'customAssertNoThrow(expression: \g<1>)', line) return line def convert_wait_until(lines): # text = '\n'.join(lines) content = [] start = None curly = 1 timeout = None result_lines = [] found = False for idx, line in enumerate(lines): if 'waitUntil' in line: match = re.search(r'waitUntil(?:\(timeout:(.+)\))? \{', line) timeout = match.group(1) found = True start = idx curly = 1 result_lines.append('let exp = expectation(description: "")') elif start is not None: curly += line.count('{') - line.count('}') if curly == 0: start = None timeout = timeout.strip() if timeout else '0.5' result_lines.append(f'wait(for: [exp], timeout: {timeout})') timeout = None else: content.append(line) result_lines.append(line.replace('done()', 'exp.fulfill()')) else: result_lines.append(line) return result_lines def join_declarations_and_assignments(lines): class VAR: def __init__(self, name, type, declaration_idx): self.name = name self.type = type.replace('!', '').replace('?', '') self.value = None self.declaration_idx = declaration_idx self.assignment_idx = None self.should_be_var = False @property def joined(self): var_type = 'var' if self.should_be_var else 'let' return f'{var_type} {self.name}: {self.type} = {self.value}' vars = {} # find declarations for idx, line in enumerate(lines): match = re.search(r'var (\w+): (\S+)', line) if match and ('=' not in line or '= []' in line or '= ""' in line): vars[match.group(1)] = VAR(name=match.group(1), type=match.group(2), declaration_idx=idx) # find assignments for idx, line in enumerate(lines): match = re.search(r'^(\w+) = (.+)$', line) if match and match.group(1) in vars: name = match.group(1) if vars[name].value is None: vars[name].value = match.group(2) vars[name].assignment_idx = idx else: vars[name].should_be_var = True # result for _, var in vars.items(): lines[var.declaration_idx] = '' if var.value: lines[var.assignment_idx] = var.joined lines = [x for x in lines if x != ''] return lines def fix_xctfail(lines): return [ x.replace('fail(', 'XCTFail(') for x in lines ] body_lines = test.before_each + test.content body_lines = join_declarations_and_assignments(body_lines) body_lines = fix_xctfail(body_lines) body_lines = [convert_expectations(x) for x in body_lines] body_lines = convert_wait_until(body_lines) def generate_test_name(): naming = [] for x in test.naming[4:]: match = re.search(r'describe\("(.*)"\)', x) if match: naming.append(match.group(1)) match = re.search(r'context\("(.*)"\)', x) if match: naming.append(match.group(1)) match = re.search(r'it\("(.*)"\)', x) if match: naming.append('it ' + match.group(1)) naming_raw = ' '.join(naming).title() func_name = 'test' if test.shared_example_name is None else test.shared_example_name + '_' allowed_characters = string.digits + string.ascii_letters test_name = ''.join([x for x in naming_raw if x in allowed_characters]) if len(test_name) >= 100: naming_raw = ' _ '.join(naming).title() allowed_characters += '_' test_name = ''.join([x for x in naming_raw if x in allowed_characters]) func_name += test_name duplicate_detected = False while func_name in used_test_names: duplicate_detected = True match = re.search(r'^\D+(\d+)$', func_name) if match: number = int(match.group(1)) + 1 func_name = func_name.split('#')[0] + '#' + str(number) else: func_name += '#1' used_test_names.add(func_name) func_name = func_name.replace('#', '_') if duplicate_detected: print("Duplicate func name fixed: " + func_name) return func_name, naming_raw def insert_arrange_act_assert(lines, testable_name): lines = [x for x in lines if x != ''] last_testable_call_idx = None act_inserted = False for idx, line in enumerate(lines): if re.search(rf'\W?{testable_name}\W', line) and 'Assert' not in line: last_testable_call_idx = idx if last_testable_call_idx is not None: lines.insert(last_testable_call_idx, '\n// act') act_inserted = True line_before_assert = lines[last_testable_call_idx + 1] assert_comment = '// assert' \ if line_before_assert.count('{') > line_before_assert.count('}') \ else '\n// assert' lines.insert(last_testable_call_idx + 2, assert_comment) else: first_assert_idx = next((i for i, v in enumerate(lines) if 'Assert' in v), None) if first_assert_idx is not None: lines.insert(first_assert_idx, '\n// assert') if not lines[0].strip().startswith('//'): lines.insert(0, '// arrange') if not act_inserted: lines = [ x.replace('// assert', '// act & assert') for x in lines ] return '\n'.join(lines) func_name, _ = generate_test_name() test_body = insert_arrange_act_assert(body_lines, self.parser.testable_name) result = f'''func {func_name}() {{ {test_body} }}''' return result def generate_test_cases(self): used_test_names = set() cases = [self.generate_test_case(x, used_test_names) for x in self.parser.test_cases] return '\n\n'.join(cases) def generate(self): xctest = self.parser.text.split('class')[0] \ .replace("import Quick\n", "") \ .replace("import Nimble", "import XCTest") xctest += f'class {self.parser.class_name}: XCTestCase {{\n\n' xctest += '\n'.join(self.parser.common_vars) + '\n\n' xctest += self.generate_setup() xctest += self.generate_teardown() xctest += self.generate_test_cases() xctest += '\n}' if self.parser.extensions: xctest += '\n\n' + '\n'.join(self.parser.extensions) return xctest def convert_quick(filename, out_file): with open(filename, 'r', encoding='utf-8') as file: text = file.read() if 'QuickSpec' not in text: print(f"Skipped file without QuickSpec: {filename}") return print(f'==== Processing {filename} ====') swift_parser = SwiftParser(text) parser = QuickParser(text, swift_parser.root, swift_parser.extensions) test = XCTestGenerator(parser).generate() write_file(out_file, test) run_swiftformat(out_file) def run_swiftformat(swift_file): process = Popen(['swiftformat', swift_file, '--config', '.swiftformat'], stdout=PIPE, stderr=PIPE) stdout, stderr = process.communicate() stdout = stdout.decode('utf-8') stderr = stderr.decode('utf-8') print(stdout + stderr) def remove_line_wraps(filename, out_file): with open(filename, 'r', encoding='utf-8') as file: text = file.read() if 'QuickSpec' not in text: print(f"Skipped file without QuickSpec: {filename}") return index = text.index(': QuickSpec {') first = text[:index] second = text[index:] second = re.sub(r'([\.,\[\(=:])\s*\n\s*', r'\g<1>', second, flags=re.MULTILINE) second = re.sub(r'\s*\n\s*([\.,\]\)=])', r'\g<1>', second, flags=re.MULTILINE) write_file(out_file, first + second) def rm_dir(dir): try: shutil.rmtree(dir) except FileNotFoundError: pass def replace_path_dir(path, old, new): _old = re.sub(r'/$', r'', old) _new = re.sub(r'/$', r'', new) return str(path).replace(_old, _new) def backup_originals(src_dir, out_dir): for path in list(Path(src_dir).rglob('*.swift')): filename = str(path) if '/backup/' in str(path): continue with open(filename, 'r', encoding='utf-8') as file: text = file.read() if 'QuickSpec' in text: write_file(filename=replace_path_dir(filename, src_dir, out_dir), text=text) def unwrap_all_files(src_dir, out_dir): for path in list(Path(src_dir).rglob('*.swift')): if '/backup/' not in str(path): remove_line_wraps(path, replace_path_dir(path, src_dir, out_dir)) def convert_all_files(src_dir, out_dir): for path in list(Path(src_dir).rglob('*.swift')): if '/backup/' not in str(path): out_file = replace_path_dir(path, src_dir, out_dir) convert_quick(str(path), out_file=out_file) def print_usage_and_exit(): print('Usage: python3 main.py <folder with quickspec tests>') exit(1) if len(sys.argv) != 2: print_usage_and_exit() work_dir = sys.argv[1] unwrapped_dir = work_dir if not os.path.isdir(work_dir): print(f'Error: "{work_dir}" is not directory.') print_usage_and_exit() backup_originals(src_dir=work_dir, out_dir=os.path.join(work_dir, 'backup')) unwrap_all_files(src_dir=work_dir, out_dir=unwrapped_dir) convert_all_files(src_dir=unwrapped_dir, out_dir=work_dir) # convert_quick(str('unwrapped/example.swift'), out_dir='out') print("!!! Check file `CustomThrowingAssertFunctions.swift` for definitions of" "\n\t`customAssertThrowsError`\n\t`customAssertNoThrow`")
true
0360dc0e5367d946d0712bbef90a9eb6bf30b910
Python
wangyum/Anaconda
/lib/python2.7/site-packages/gensim/models/wrappers/dtmmodel.py
UTF-8
13,934
2.609375
3
[ "Python-2.0", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-unknown" ]
permissive
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2014 Artyom Topchyan <artyom.topchyan@live.com> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html # Based on Copyright (C) 2014 Radim Rehurek <radimrehurek@seznam.cz> """ Python wrapper for Dynamic Topic Models (DTM) and the Document Influence Model (DIM) [1]. This module allows for DTM and DIM model estimation from a training corpus. Example: >>> model = gensim.models.wrappers.DtmModel('dtm-win64.exe', my_corpus, my_timeslices, num_topics=20, id2word=dictionary) .. [1] https://github.com/magsilva/dtm/tree/master/bin """ import logging import random import tempfile import os from subprocess import PIPE import numpy as np import six from gensim import utils, corpora, matutils from gensim.utils import check_output logger = logging.getLogger(__name__) class DtmModel(utils.SaveLoad): """ Class for DTM training using DTM binary. Communication between DTM and Python takes place by passing around data files on disk and executing the DTM binary as a subprocess. """ def __init__( self, dtm_path, corpus=None, time_slices=None, mode='fit', model='dtm', num_topics=100, id2word=None, prefix=None, lda_sequence_min_iter=6, lda_sequence_max_iter=20, lda_max_em_iter=10, alpha=0.01, top_chain_var=0.005, rng_seed=0, initialize_lda=True): """ `dtm_path` is path to the dtm executable, e.g. `C:/dtm/dtm-win64.exe`. `corpus` is a gensim corpus, aka a stream of sparse document vectors. `id2word` is a mapping between tokens ids and token. `mode` controls the mode of the mode: 'fit' is for training, 'time' for analyzing documents through time according to a DTM, basically a held out set. `model` controls the choice of model. 'fixed' is for DIM and 'dtm' for DTM. `lda_sequence_min_iter` min iteration of LDA. `lda_sequence_max_iter` max iteration of LDA. `lda_max_em_iter` max em optiimzatiion iterations in LDA. `alpha` is a hyperparameter that affects sparsity of the document-topics for the LDA models in each timeslice. `top_chain_var` is a hyperparameter that affects. `rng_seed` is the random seed. `initialize_lda` initialize DTM with LDA. """ if not os.path.isfile(dtm_path): raise ValueError("dtm_path must point to the binary file, not to a folder") self.dtm_path = dtm_path self.id2word = id2word if self.id2word is None: logger.warning("no word id mapping provided; initializing from corpus, assuming identity") self.id2word = utils.dict_from_corpus(corpus) self.num_terms = len(self.id2word) else: self.num_terms = 0 if not self.id2word else 1 + max(self.id2word.keys()) if self.num_terms == 0: raise ValueError("cannot compute DTM over an empty collection (no terms)") self.num_topics = num_topics try: lencorpus = len(corpus) except: logger.warning("input corpus stream has no len(); counting documents") lencorpus = sum(1 for _ in corpus) if lencorpus == 0: raise ValueError("cannot compute DTM over an empty corpus") if model == "fixed" and any([i == 0 for i in [len(text) for text in corpus.get_texts()]]): raise ValueError("""There is a text without words in the input corpus. This breaks method='fixed' (The DIM model).""") if lencorpus != sum(time_slices): raise ValueError("mismatched timeslices %{slices} for corpus of len {clen}".format( slices=sum(time_slices), clen=lencorpus)) self.lencorpus = lencorpus if prefix is None: rand_prefix = hex(random.randint(0, 0xffffff))[2:] + '_' prefix = os.path.join(tempfile.gettempdir(), rand_prefix) self.prefix = prefix self.time_slices = time_slices self.lda_sequence_min_iter = int(lda_sequence_min_iter) self.lda_sequence_max_iter = int(lda_sequence_max_iter) self.lda_max_em_iter = int(lda_max_em_iter) self.alpha = alpha self.top_chain_var = top_chain_var self.rng_seed = rng_seed self.initialize_lda = str(initialize_lda).lower() self.lambda_ = None self.obs_ = None self.lhood_ = None self.gamma_ = None self.init_alpha = None self.init_beta = None self.init_ss = None self.em_steps = [] self.influences_time = [] if corpus is not None: self.train(corpus, time_slices, mode, model) def fout_liklihoods(self): return self.prefix + 'train_out/lda-seq/' + 'lhoods.dat' def fout_gamma(self): return self.prefix + 'train_out/lda-seq/' + 'gam.dat' def fout_prob(self): return self.prefix + 'train_out/lda-seq/' + 'topic-{i}-var-e-log-prob.dat' def fout_observations(self): return self.prefix + 'train_out/lda-seq/' + 'topic-{i}-var-obs.dat' def fout_influence(self): return self.prefix + 'train_out/lda-seq/' + 'influence_time-{i}' def foutname(self): return self.prefix + 'train_out' def fem_steps(self): return self.prefix + 'train_out/' + 'em_log.dat' def finit_alpha(self): return self.prefix + 'train_out/' + 'initial-lda.alpha' def finit_beta(self): return self.prefix + 'train_out/' + 'initial-lda.beta' def flda_ss(self): return self.prefix + 'train_out/' + 'initial-lda-ss.dat' def fcorpustxt(self): return self.prefix + 'train-mult.dat' def fcorpus(self): return self.prefix + 'train' def ftimeslices(self): return self.prefix + 'train-seq.dat' def convert_input(self, corpus, time_slices): """ Serialize documents in LDA-C format to a temporary text file,. """ logger.info("serializing temporary corpus to %s" % self.fcorpustxt()) # write out the corpus in a file format that DTM understands: corpora.BleiCorpus.save_corpus(self.fcorpustxt(), corpus) with utils.smart_open(self.ftimeslices(), 'wb') as fout: fout.write(utils.to_utf8(str(len(self.time_slices)) + "\n")) for sl in time_slices: fout.write(utils.to_utf8(str(sl) + "\n")) def train(self, corpus, time_slices, mode, model): """ Train DTM model using specified corpus and time slices. """ self.convert_input(corpus, time_slices) arguments = "--ntopics={p0} --model={mofrl} --mode={p1} --initialize_lda={p2} --corpus_prefix={p3} --outname={p4} --alpha={p5}".format( p0=self.num_topics, mofrl=model, p1=mode, p2=self.initialize_lda, p3=self.fcorpus(), p4=self.foutname(), p5=self.alpha) params = "--lda_max_em_iter={p0} --lda_sequence_min_iter={p1} --lda_sequence_max_iter={p2} --top_chain_var={p3} --rng_seed={p4} ".format( p0=self.lda_max_em_iter, p1=self.lda_sequence_min_iter, p2=self.lda_sequence_max_iter, p3=self.top_chain_var, p4=self.rng_seed) arguments = arguments + " " + params logger.info("training DTM with args %s" % arguments) cmd = [self.dtm_path] + arguments.split() logger.info("Running command %s" % cmd) check_output(cmd, stderr=PIPE) self.em_steps = np.loadtxt(self.fem_steps()) self.init_ss = np.loadtxt(self.flda_ss()) if self.initialize_lda: self.init_alpha = np.loadtxt(self.finit_alpha()) self.init_beta = np.loadtxt(self.finit_beta()) self.lhood_ = np.loadtxt(self.fout_liklihoods()) # document-topic proportions self.gamma_ = np.loadtxt(self.fout_gamma()) # cast to correct shape, gamme[5,10] is the proprtion of the 10th topic # in doc 5 self.gamma_.shape = (self.lencorpus, self.num_topics) # normalize proportions self.gamma_ /= self.gamma_.sum(axis=1)[:, np.newaxis] self.lambda_ = np.zeros((self.num_topics, self.num_terms * len(self.time_slices))) self.obs_ = np.zeros((self.num_topics, self.num_terms * len(self.time_slices))) for t in range(self.num_topics): topic = "%03d" % t self.lambda_[t, :] = np.loadtxt(self.fout_prob().format(i=topic)) self.obs_[t, :] = np.loadtxt(self.fout_observations().format(i=topic)) # cast to correct shape, lambda[5,10,0] is the proportion of the 10th # topic in doc 5 at time 0 self.lambda_.shape = (self.num_topics, self.num_terms, len(self.time_slices)) self.obs_.shape = (self.num_topics, self.num_terms, len(self.time_slices)) # extract document influence on topics for each time slice # influences_time[0] , influences at time 0 if model == 'fixed': for k, t in enumerate(self.time_slices): stamp = "%03d" % k influence = np.loadtxt(self.fout_influence().format(i=stamp)) influence.shape = (t, self.num_topics) # influence[2,5] influence of document 2 on topic 5 self.influences_time.append(influence) def print_topics(self, num_topics=10, times=5, num_words=10): return self.show_topics(num_topics, times, num_words, log=True) def show_topics(self, num_topics=10, times=5, num_words=10, log=False, formatted=True): """ Print the `num_words` most probable words for `num_topics` number of topics at 'times' time slices. Set `topics=-1` to print all topics. Set `formatted=True` to return the topics as a list of strings, or `False` as lists of (weight, word) pairs. """ if num_topics < 0 or num_topics >= self.num_topics: num_topics = self.num_topics chosen_topics = range(num_topics) else: num_topics = min(num_topics, self.num_topics) chosen_topics = range(num_topics) # add a little random jitter, to randomize results around the same # alpha # sort_alpha = self.alpha + 0.0001 * \ # numpy.random.rand(len(self.alpha)) # sorted_topics = list(numpy.argsort(sort_alpha)) # chosen_topics = sorted_topics[: topics / 2] + \ # sorted_topics[-topics / 2:] if times < 0 or times >= len(self.time_slices): times = len(self.time_slices) chosen_times = range(times) else: times = min(times, len(self.time_slices)) chosen_times = range(times) shown = [] for time in chosen_times: for i in chosen_topics: if formatted: topic = self.print_topic(i, time, num_words=num_words) else: topic = self.show_topic(i, time, num_words=num_words) shown.append(topic) # if log: # logger.info("topic #%i (%.3f): %s" % (i, self.alpha[i], # topic)) return shown def show_topic(self, topicid, time, num_words=50): """ Return `num_words` most probable words for the given `topicid`, as a list of `(word_probability, word)` 2-tuples. """ topics = self.lambda_[:, :, time] topic = topics[topicid] # liklihood to probability topic = np.exp(topic) # normalize to probability dist topic = topic / topic.sum() # sort according to prob bestn = matutils.argsort(topic, num_words, reverse=True) beststr = [(topic[id], self.id2word[id]) for id in bestn] return beststr def print_topic(self, topicid, time, num_words=10): """Return the given topic, formatted as a string.""" return ' + '.join(['%.3f*%s' % v for v in self.show_topic(topicid, time, num_words)]) def dtm_vis(self, corpus, time): """ returns term_frequency, vocab, doc_lengths, topic-term distributions and doc_topic distributions, specified by pyLDAvis format. all of these are needed to visualise topics for DTM for a particular time-slice via pyLDAvis. input parameter is the year to do the visualisation. """ topic_term = np.exp(self.lambda_[:,:,time]) / np.exp(self.lambda_[:,:,time]).sum() topic_term = topic_term * self.num_topics doc_topic = self.gamma_ doc_lengths = [len(doc) for doc_no, doc in enumerate(corpus)] term_frequency = np.zeros(len(self.id2word)) for doc_no, doc in enumerate(corpus): for pair in doc: term_frequency[pair[0]] += pair[1] vocab = [self.id2word[i] for i in range(0, len(self.id2word))] # returns numpy arrays for doc_topic proportions, topic_term proportions, and document_lengths, term_frequency. # these should be passed to the `pyLDAvis.prepare` method to visualise one time-slice of DTM topics. return doc_topic, topic_term, doc_lengths, term_frequency, vocab def dtm_coherence(self, time, num_words=20): """ returns all topics of a particular time-slice without probabilitiy values for it to be used for either "u_mass" or "c_v" coherence. TODO: because of print format right now can only return for 1st time-slice. should we fix the coherence printing or make changes to the print statements to mirror DTM python? """ coherence_topics = [] for topic_no in range(0, self.num_topics): topic = self.show_topic(topicid=topic_no, time=time, num_words=num_words) coherence_topic = [] for prob, word in topic: coherence_topic.append(word) coherence_topics.append(coherence_topic) return coherence_topics
true
501d8db8dd050050164c3b70bcbf609381a52015
Python
waltont8/AutoCSVAPI
/AutoCSVAPI.py
UTF-8
1,666
2.71875
3
[ "BSD-3-Clause" ]
permissive
#!/usr/bin/env python3 import getopt import sys import csv import json from http.server import BaseHTTPRequestHandler, HTTPServer import socketserver import re from urllib.parse import parse_qs, urlparse IP = "127.0.0.1" PORT = 8888 argv = sys.argv[1:] opts, args = getopt.getopt(argv, 'x:y:') if len(args) != 1: print("Usage is `AutoCSVAPI file.csv`") exit(-1) fileName = args[0] headers = [] rows = [] with open(fileName, newline='') as csvfile: dialect = csv.Sniffer().sniff(csvfile.read(1024)) csvfile.seek(0) reader = csv.reader(csvfile, dialect) try: headers = next(reader, None) for row in reader: rows.append(row) except csv.Error as e: sys.exit('file {}, line {}: {}'.format(fileName, reader.line_num, e)) def MakeHandlerClassFromArgv(rows): class CustomHandler(BaseHTTPRequestHandler): def __init__(self, *args, **kwargs): super(CustomHandler, self).__init__(*args, **kwargs) self.rows = rows def do_GET(self): queries = parse_qs(urlparse(self.path).query, keep_blank_values=False) rowResult = rows for i, k in enumerate(queries.keys()): rowResult = [n for n in rowResult if n[i] in queries[k]] data = json.dumps(rowResult) self.send_response(200) self.send_header('Content-Type', 'application/json') self.end_headers() self.wfile.write(data.encode('utf8')) return CustomHandler HandlerClass = MakeHandlerClassFromArgv(rows) server = HTTPServer((IP, PORT), HandlerClass) server.serve_forever()
true
8488af40db5ae6030d66773aee3491fce0eaa5f6
Python
Thomas84/pyChilizer
/Architype.tab/PHPP.panel/Mass thermal bridge.pushbutton/script.py
UTF-8
8,030
2.515625
3
[]
no_license
__title__ = "Mass Thermal\n Bridge PHPP" __doc__ = "Populate the PHPP Thermal Bridge Value parameters for all Windows \nv1.1" from pyrevit import revit, DB from pyrevit.framework import List from pyrevit.forms import ProgressBar # http://www.revitapidocs.com/2018.1/5da8e3c5-9b49-f942-02fc-7e7783fe8f00.htm class FamilyLoaderOptionsHandler(DB.IFamilyLoadOptions): def OnFamilyFound(self, familyInUse, overwriteParameterValues): #pylint: disable=W0613 """A method called when the family was found in the target document.""" return True def OnSharedFamilyFound(self, sharedFamily, #pylint: disable=W0613 familyInUse, #pylint: disable=W0613 source, #pylint: disable=W0613 overwriteParameterValues): #pylint: disable=W0613 source = DB.FamilySource.Family overwriteParameterValues = True return True # Creates a model line; used for debugging def CreateLine(doc, line, dir): with revit.Transaction("draw line"): plane = DB.Plane.CreateByNormalAndOrigin(dir, line.GetEndPoint(0)) sketch_plane = DB.SketchPlane.Create(doc, plane) curve = doc.Create.NewModelCurve(line, sketch_plane) # Remove unnecessary IDs from the collection def CleanElementIds(_elements, _win, _host_win, _doc): element_ids = [] # Skip myself and my parent window host for element in _elements: if element.IntegerValue == _host_win.Id.IntegerValue and not _doc.IsFamilyDocument: continue if element.IntegerValue == _win.Id.IntegerValue: continue element_ids.append(element) return List[DB.ElementId](element_ids) # Find an intersection based on direction def FindSingleIntersection(_win, _host_win, _elements, _current_view, _location_pt, _direction, _doc): # line = DB.Line.CreateBound(_location_pt, _location_pt + 2 * _direction) # Keep for visual debugging # CreateLine(_doc, line, DB.XYZ(1, 0, 0)) # Keep for visual debugging (change plane dir) try: element_ids = CleanElementIds(_elements, _win, _host_win, _doc) # Get the clean list of Ids target = DB.FindReferenceTarget.All # Any intersection for the time being, can test more ref_int = DB.ReferenceIntersector(element_ids, target, _current_view) # The Intersector nearest_up = ref_int.FindNearest(_location_pt, _direction) # Find only the nearest shot = nearest_up.GetReference() # We got a shot! TO DO: Check if no intersection return shot except: pass # Populate the PHPP ThermalValue parameter # TO DO: Handle no parameter - possible UI improvement solution? def PopulateThermalValue(_win, _dir, _intersection, _doc): if not _intersection: value = 1 else: cat = _doc.GetElement(_intersection).Category # if cat.Name == "Walls": if cat.Id.IntegerValue == int(DB.BuiltInCategory.OST_Walls): value = 1 else: value = 0 with DB.Transaction(_doc, "populate parameter") as tr: tr.Start() if _dir == "up": # print(str(_win.Name) + " : " + str(value)) _win.LookupParameter("ART_ThermalBridgeValue_Top").Set(str(value)) elif _dir == "down": _win.LookupParameter("ART_ThermalBridgeValue_Bottom").Set(str(value)) elif _dir == "left": _win.LookupParameter("ART_ThermalBridgeValue_Left").Set(str(value)) else: _win.LookupParameter("ART_ThermalBridgeValue_Right").Set(str(value)) tr.Commit() # Find the intersections for each Window and populate the thermal value # TO DO: Handle no intersection - Update 26/11/20 handled by assuming value = 1 when no intersection def PopulateIntersection(_win, _elements, _current_view, _doc): bb = _win.get_BoundingBox(_current_view) x = _win.Location.Point.X y = _win.Location.Point.Y location_pt = DB.XYZ(x, y, (bb.Max.Z + bb.Min.Z) * 0.5) if _doc.IsFamilyDocument: wall = DB.FilteredElementCollector(_doc) \ .OfCategory(DB.BuiltInCategory.OST_Walls) \ .WhereElementIsNotElementType() \ .ToElements() host_win = wall[0] else: host_win = _win.SuperComponent # The root window # host_win = _win.SuperComponent # The root window direction_up = DB.XYZ(0, 0, 1) direction_down = DB.XYZ(0, 0, -1) direction_left = _win.HandOrientation.Normalize() # The left will be read from outside-in direction_right = direction_left.Negate() up = FindSingleIntersection(_win, host_win, _elements, _current_view, location_pt, direction_up, _doc) down = FindSingleIntersection(_win, host_win, _elements, _current_view, location_pt, direction_down, _doc) left = FindSingleIntersection(_win, host_win, _elements, _current_view, location_pt, direction_left, _doc) right = FindSingleIntersection(_win, host_win, _elements, _current_view, location_pt, direction_right, _doc) PopulateThermalValue(_win, "up", up, _doc) PopulateThermalValue(_win, "down", down, _doc) PopulateThermalValue(_win, "left", left, _doc) PopulateThermalValue(_win, "right", right, _doc) def Get3DView(_doc): view3d = DB.FilteredElementCollector(_doc) \ .OfClass(DB.View3D) \ .ToElements() view3d = next(v for v in view3d if v.Name == "View 1") return view3d def ExecuteWindow(_doc): # TO DO: create filter if not active 3D view current_view = Get3DView(_doc) if not isinstance(current_view, DB.View3D): print("Please run in 3D view where you can see all Windows") cat_filters = [DB.ElementCategoryFilter(DB.BuiltInCategory.OST_Windows), DB.ElementCategoryFilter(DB.BuiltInCategory.OST_Doors), DB.ElementCategoryFilter(DB.BuiltInCategory.OST_Walls)] cat_filter = DB.LogicalOrFilter(List[DB.ElementFilter](cat_filters)) elements = DB.FilteredElementCollector(_doc) \ .WherePasses(cat_filter) \ .WhereElementIsNotElementType() \ .ToElementIds() windows = DB.FilteredElementCollector(_doc) \ .OfCategory(DB.BuiltInCategory.OST_Windows) \ .WhereElementIsNotElementType() \ .ToElements() # filter nested by not hosted on wall - MAYBE BETTER FILTER # this bugs out for some reason on a live project - I added a Type Comment filter, still not good maybe :/ phpp_win = [w for w in windows if _doc.GetElement(w.GetTypeId()).get_Parameter( DB.BuiltInParameter.ALL_MODEL_TYPE_COMMENTS).AsString() == "Panel"] nested_win = [w for w in windows if not isinstance(w.Host, DB.Wall)] host_wall = [w.Host for w in windows if isinstance(w.Host, DB.Wall)] if len(phpp_win) == 0: print("No panels with Type Comment = 'Panel' found.") # with revit.TransactionGroup('Populate Thermal Bridge Values'): # win = revit.pick_element("pick a window") # Keep for visual debugging # PopulateIntersection(win, elements, current_view) counter = 0 max_value = len(phpp_win) elements = [e for e in elements if "Default" not in _doc.GetElement(e).Name] with ProgressBar(cancellable=True, step=1) as pb: with DB.TransactionGroup(_doc, 'Populate Thermal Bridge Values') as tg: tg.Start() for win in phpp_win: if pb.cancelled: break else: PopulateIntersection(win, elements, current_view, _doc) pb.update_progress(counter, max_value) counter += 1 tg.Assimilate() selection = revit.get_selection() for sel in selection: fam_ins = sel fam = fam_ins.Symbol.Family fam_doc = revit.doc.EditFamily(fam) ExecuteWindow(fam_doc) # print("Is document modifiable? " + str(revit.doc.IsModifiable)) fam = fam_doc.LoadFamily(revit.doc, FamilyLoaderOptionsHandler())
true
8db5531b7537b5b88e7b8f5bc7e8b2b64d39f5f8
Python
seoul-ssafy-class-2-studyclub/GaYoung_SSAFY
/programmers/1004_기능개발.py
UTF-8
907
3.40625
3
[]
no_license
progresses = [95, 90, 99, 99, 80, 99] speeds = [1, 1, 1, 1, 1, 1] def solution(progresses, speeds): # 끝나는 요일 계산하기 check = [] for i in range(len(progresses)): x, y = divmod((100 - progresses[i]), speeds[i]) if y == 0: check.append(x) elif y != 0: check.append(x + 1) # 몇일 째 몇개의 기능이 배포되는지 확인 now = check[0] cnt = 0 answer = [] while check: x = check.pop(0) if x <= now: cnt += 1 else: answer.append(cnt) cnt = 1 now = x answer.append(cnt) # 마지막으로 최대값이 나온 다음에 더해지는 cnt는 answer에 포함되지 않기때문에 # while문이 끝났을 때의 cnt를 넣어준다. # print(answer) return answer print(solution(progresses,speeds))
true
87688ef38d3d7e3f5a19d46dcd536b45402d6845
Python
zsquareplusc/lttp-backup
/link_to_the_past/hashes.py
UTF-8
1,705
2.9375
3
[ "BSD-3-Clause" ]
permissive
#!/usr/bin/env python3 # encoding: utf-8 # # (C) 2012-2016 Chris Liechti <cliechti@gmx.net> # # SPDX-License-Identifier: BSD-3-Clause """\ Link To The Past - a backup tool Hash functions and commands. """ import hashlib import zlib class CRC32(object): """\ CRC32 API compatible to the hashlib functions (subset used by this program). >>> h = CRC32() >>> h.update(b'Hello World') >>> h.hexdigest() '4a17b156' """ def __init__(self): self.value = 0 def update(self, data): self.value = zlib.crc32(data, self.value) & 0xffffffff def hexdigest(self): return '{:08x}'.format(self.value) class NoHash(object): """\ API compatible to the hashlib functions (subset used by this program). >>> h = NoHash() >>> h.update(b'Hello World') >>> h.hexdigest() '-' """ def __init__(self): pass def update(self, data): pass def hexdigest(self): return '-' # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - SUPPORTED_HASHES = { 'NONE': NoHash, 'CRC32': CRC32, 'MD5': hashlib.md5, 'SHA-256': hashlib.sha256, 'SHA-512': hashlib.sha512, } def get_factory(name): """\ Get an object for calculating a hash. >>> f = get_factory('SHA-256') >>> h = f() >>> h.update(b'Hello World') >>> h.hexdigest() 'a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e' """ if name is None: name = 'NONE' return SUPPORTED_HASHES[name.upper()] # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - if __name__ == '__main__': import doctest doctest.testmod()
true
0f81ae6c2204049471d13bddeaf9c5643c634493
Python
Mahendrarrao/Python-sample-programs
/week511.py
UTF-8
547
3.203125
3
[]
no_license
fname = input("Enter file name: ") fhandle = open(fname) list = [] counts = dict() for line in fhandle: sline = line.rstrip() temp = sline.split() i = 0 for word in temp: i = i + 1 if 'From' in word: if 'From:' not in word: list.append(temp[i]) for word in list: counts[word] = counts.get(word,0) + 1 bigcount = None bigword = None for word,count in counts.items(): if bigcount is None or count > bigcount: bigcount = count bigword = word print(bigword,bigcount)
true
9c0149c90030ffb0cc8f199a8ba25df25579a67d
Python
ritwickdey/Python-Week-Day-3
/demo/demo_7.py
UTF-8
109
3.4375
3
[]
no_license
# Demo of math module from math import * print(sqrt(81)) #output: 9.0 print(pi) #output: 3.141592653589793
true
e477cfc5fbd5c1ea1e8b08e7d27b5dbfc2c30b94
Python
jerryfeng007/pythonCodes
/练习题/00032头尾元素对调.py
UTF-8
164
3.546875
4
[]
no_license
# 定义一个列表,并将列表中的头尾两个元素对调。 def duidiao(l): l[0], l[-1] = l[-1], l[0] return l print(duidiao([1, 2, 3, 4, 5]))
true
06b10872199dfc031e3ed18c3e09cddff59c0d3f
Python
drpuig/Leetcode-1
/minimum-number-of-arrows-to-burst-balloons/minimum-number-of-arrows-to-burst-balloons.py
UTF-8
483
2.984375
3
[]
no_license
class Solution:    def findMinArrowShots(self, points: List[List[int]]) -> int:        if not points: return 0        points.sort()        print(points)        count = 1        _, cur_e = points[0]        for s, e in points[1:]:            if s > cur_e:                count += 1                cur_e = e            else:                cur_e = min(cur_e, e)        return count                
true
f6ebabc6fdfe911c3ed3955fcd5ebc7d8f8fc80b
Python
mais2086/Facoders
/python/exr1.py
UTF-8
125
3.078125
3
[]
no_license
def list(list_name): b=[list_name[0],list_name[-1]] return b a = [1, 5, 6, 2, 58, 5, 109, 1000, 22] print (list(a))
true
03fc2fa7e1240beef47907473166862ee874b3c6
Python
JordanStone/Project2
/p1/test.py
UTF-8
1,051
3.359375
3
[]
no_license
#!/usr/bin/env python #test.py # import pointerqueue def testPass(name,passed): if (passed): print "The method", name, "has passed." else: print "The method", name, "has failed." def main(): rqueue = pointerqueue.pointerQueue() equeue = [] print "Testing ENQUEUE method." for n in range(1,11): rqueue.ENQUEUE(n) equeue.append(n) if rqueue.rear.car != n: passed = False else: passed = True testPass("ENQUEUE",passed) passed = True print "Testing FRONT method." if rqueue.FRONT() != equeue[0]: print rqueue.FRONT() print equeue[0] passed = False testPass("FRONT",passed) passed = True print "Testing DEQUEUE method." rqueue.DEQUEUE() equeue.pop(0) if rqueue.FRONT() != equeue[0]: print rqueue.FRONT() print equeue[0] passed = False testPass("DEQUEUE",passed) passed = True print "Testing MAKENULL method." rqueue.MAKENULL() del equeue[0:len(equeue)] if rqueue.front != None: print rqueue.FRONT() passed = False testPass("MAKENULL",passed) if __name__ == "__main__": main()
true
a6690499a1c580c24227b80f6630f57b5b10d69c
Python
erik1066/covid-web-scraper
/src/sc_scraper.py
UTF-8
2,990
2.515625
3
[ "Apache-2.0" ]
permissive
import requests, json, io, datetime, pathlib, sys, time, os, csv from io import StringIO import county_report, state_report from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By STATE_ABBR = 'SC' STATE = 'South Carolina' URL = 'https://www.arcgis.com/home/webmap/viewer.html?url=https://services2.arcgis.com/XZg2efAbaieYAXmu/ArcGIS/rest/services/COVID19_SharingView/FeatureServer/0&source=sd' def get_row_data(table): for row in table: yield [td.text for td in row.find_elements_by_xpath(".//td")] def scraper(): counties = [] # You will need a WebDriver for Edge. See https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/ try: browser = webdriver.Edge("msedgedriver.exe") browser.get(URL) time.sleep(1) show_table_link = WebDriverWait(browser, 30).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/div[1]/div[3]/div[3]/div/div/div[3]/div[2]/div/div[1]/div[2]/div[1]/div[1]/div/div[2]/span'))) show_table_link.click() time.sleep(1) county_div = WebDriverWait(browser, 30).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/div[1]/div[3]/div[5]/div[4]/div[1]/div/div/div/div[1]/div/div/div[2]/div/div[2]/div'))) county_div_rows = county_div.find_elements_by_xpath('.//div[@role="row"]') # SC puts its county level data into lots of <div> elements, with one <div> per county. Each <div> has its own single-row <table> that contains the county data. Thus, we # have some extra stuff to do to make this work right. for div_row in county_div_rows: county_table = div_row.find_element_by_xpath('.//table') htmlRows = county_table.find_elements_by_xpath(".//tr") rows = get_row_data(htmlRows) for row in rows: county_name = row[0] if county_name == 'Unknown': continue confirmed = int(row[3].replace(',', '')) deaths = int(row[4].replace(',', '')) county = county_report.CountyReport(STATE, county_name, confirmed, deaths, -1, -1, datetime.datetime.now()) counties.append(county) except: print("Unexpected error:", sys.exc_info()[0]) browser.quit() # print the number of counties we processed print(' ', STATE_ABBR, ':', len(counties), ' counties processed OK') # build the state-level report object that will include all of the counties stateReport = state_report.StateReport(STATE, STATE_ABBR, counties, datetime.datetime.now()) # return the state-level report return stateReport
true
8c0dd593606048a14baa6a06dc683c15abed0e58
Python
epaillas/contrast_old
/python_tools/meanfrommocks.py
UTF-8
1,161
2.75
3
[]
no_license
import numpy as np import glob import click import sys @click.command() @click.option('--handle_in', type=str, required=True) @click.option('--handle_out', type=str, required=True) def mean_from_mocks(handle_in, handle_out): print('\nAveraging mean from mocks for the following arguments:') print('handle_in: {}'.format(handle_in)) print('handle_out: {}'.format(handle_out)) # loop over all mocks and calculate mean mock_files = sorted(glob.glob(handle_in)) data_list = [] for mock_file in mock_files: data = np.genfromtxt(mock_file) data_list.append(data) data_list = np.asarray(data_list) data_mean = np.nanmean(data_list, axis=0) data_std = np.nanstd(data_list, axis=0)[:, -1] print('np.shape(data_list): {}'.format(np.shape(data_list))) print('np.shape(data_mean): {}'.format(np.shape(data_mean))) print('np.shape(data_std): {}'.format(np.shape(data_std))) cout = np.c_[data_mean, data_std] cout = np.nan_to_num(cout) fmt = np.shape(cout)[1] * '%15.5f ' np.savetxt(handle_out, cout, fmt=fmt) if __name__ == '__main__': mean_from_mocks()
true
9fa75964065e7bb4e696c3e4da1121b30e7feb81
Python
KennSmithDS/machine-learning
/stock_projects/prnews_crawler/prnews/pipelines.py
UTF-8
1,279
2.53125
3
[]
no_license
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html import sqlite3 class PrnewsPipeline: def __init__(self): self.db_connection() # def __del__(self): # self.close_db _connection() def db_connection(self): self.conn = sqlite3.connect('prnews_articles.db') self.curr = self.conn.cursor() # def close_db _connection(self): # self.conn.close() def item_db_check(self, item): url_to_check = item['url'] self.curr.execute("""SELECT url FROM articles WHERE url = ?""", (url_to_check, )) rows = self.curr.fetchall() if len(rows) == 0: return False else: return True def insert_item_to_db(self, item): self.curr.execute("""INSERT INTO articles VALUES (?, ?, ?, ?, ?)""", ( item['url'], item['title'], item['body_text'], item['date_published'], item['tickers'] )) self.conn.commit() def process_item(self, item, spider): # if not self.item_db_check(item): self.insert_item_to_db(item) return item
true
49370e411b2e8c9b9ec5fce158d70bf3283733da
Python
BigBrou/Laboratory
/PythonK/FirstPython/Library/LibraryUse.py
UTF-8
932
2.875
3
[]
no_license
#Import Library ##Import datetime of datetime only from datetime import date, timedelta VsDate = date.today() print(VsDate.strftime('%y/%m/%d')) VtOneweek = timedelta(days= 7) VsDate = VsDate + VtOneweek print(VsDate.strftime('%y/%m/%d')) #################################### import zipfile VsCompressFileName = zipfile.ZipFile('C:\\PythonTest.zip', 'w') VsCompressFileName.write('C:\\cdx.ini', 'cdx') VsCompressFileName.close() VsFileConfirm = zipfile.ZipFile('C:\\PythonTest.Zip') print(VsFileConfirm.namelist()) VsFileConfirm.extractall() VsFileConfirm.close() #################################### #File Use VfFile = open('C:\\Test.txt', 'a') VfFile.write('C#') VfFile.flush() VfFile = open('C:\\Test.txt', 'r+') VfFile.write('r+\n') VfFile.seek(0) #Move Cursor to Start print(VfFile.read()) VfFile.close() with open('C:\\Test.txt', 'r+') as VfFileWith: VfFileWith.write('No Need to Close \\n')
true
9687f9e4757611a65bcbbb7f64095180ecfab1c0
Python
ArlenZhang1988/PythonLearning
/Lesson 71 pratice two content checker.py
UTF-8
528
3.28125
3
[]
no_license
from tkinter import* import hashlib # learning checker root = Tk() text = Text(root,width = 30,height = 5) text.pack() text.insert(INSERT,"I low her") contents = text.get("1.0",END) def GetSig(contents): m = hashlib.md5(contents.encode()) return m.digest() sig = GetSig(contents) def Check(): contents = text.get("1.0",END) if sig != GetSig(contents): print("Data is changed") else: print("Data is not changed") Button(root,text = "Check content", command = Check).pack() mainloop()
true
cdcac7fc207ec5cc4e3a9593c46f45976ab16f5e
Python
pinakm9/filters
/python/experiments/BPF Evolution/bpf5_evol.py
UTF-8
1,487
2.609375
3
[]
no_license
""" Plots evolution of ensembles """ # Takes size (or length of Markov chain or final time) of models as the command line argument # add modules folder to Python's search path import sys from pathlib import Path from os.path import dirname, realpath script_dir = Path(dirname(realpath(__file__))) module_dir = str(script_dir.parent.parent) sys.path.insert(0, module_dir + '/modules') sys.path.insert(0, module_dir + '/models') # import remaining modules import filter as fl import model5 import config as cf # set parameters ev_time = int(sys.argv[1]) model, a, b, x0 = model5.model(size = ev_time) particle_count = 100 resampling_threshold = 0.1 # set up configuration config = {'Henon a': a, 'Henon b': b, 'Particle count': particle_count, 'Resampling threshold': resampling_threshold,\ 'Evolution time': ev_time, 'Model': 'model5', 'Starting point': x0} cc = cf.ConfigCollector(expr_name = 'Evolution', folder = script_dir) cc.add_params(config) cc.write() # assimilation using a bootstrap particle filter hidden_path = model5.gen_path(length = ev_time) print(hidden_path) observed_path = model.observation.generate_path(hidden_path) bpf = fl.ParticleFilter(model, particle_count = particle_count, record_path = cc.res_path + '/bpf_assimilation.h5') bpf.update(observed_path, threshold_factor = resampling_threshold, method = 'mean') bpf.plot_ensembles(db_path=str(script_path) + '/Evolution#8/bpf_assimilation.h5', hidden_path=hidden_path, obs_inv = True, pt_size = 80)
true
0488deb041523a29a84cd746a8a9726972fa4fe7
Python
qmul21-CC-Group17/REST-API
/app/main/service/user.py
UTF-8
2,494
2.5625
3
[]
no_license
from app.main.model.user import User from app.main import db def save_new_user(data): user_exist = User.query.filter_by(username=data['username']).first( ) or User.query.filter_by(email=data['email']).first() if user_exist: return { 'status': 'fail', 'message': "User already exist, please login or register" }, 409 user = User( username=data['username'], email=data['email'], password = data['password'], full_time=data['full_time'], location=data['location'], keyword = data['keyword'] ) save_user(user) return { 'status': 'success', 'user ID': User.query.filter_by(username=user.username)[0].id, 'username': user.username, 'email': user.email, 'full_time': user.full_time, 'location': user.location, 'keyword': user.keyword, 'message': "please login with your email id and password" }, 201 def update_existing_user(data, id): if 'username' in data: user_exist=User.query.filter_by(username=data['username']).first() if user_exist: return { 'status': 'fail', 'message': "Username already exist, please try different username" }, 409 if 'email' in data: user_exist=User.query.filter_by(email=data['email']).first() if user_exist: return { 'status': 'fail', 'message': "email id already exist, please try different username" }, 409 return update_user(data, id) def save_user(user): db.session.add(user) db.session.commit() def update_user(data, id): user = User.query.get(id) for key, value in data.items(): setattr(user, key, value) db.session.add(user) db.session.commit() return { 'status': 'success', 'message': 'Details updated successfully' }, 200 def get_all_users(): return User.query.all() def get_user_by_id(id_): return User.query.get(id_) def delete_user_by_id(id): user = User.query.get(id) if user: db.session.delete(user) db.session.commit() return { 'status': 'success', 'message': 'Deleted successfully' }, 200 else: return { 'status': 'fail', 'message': 'User not found' }, 400
true
1955053c004056dffd9d10481caf945f1621097b
Python
tongue01/hybrid-cosim
/SemanticAdaptationForFMI/FMIAbstraction/src/case_study/scenarios/ControlledScenario_EventController.py
UTF-8
9,805
2.796875
3
[]
no_license
""" In this scenario, the controller is a statchart that receives events at his input. The main semantic adaptation is getting the continuous armature signal coming from the power system, and converting it into an event. """ import logging from bokeh.plotting import figure, output_file, show from case_study.units.adaptations.InacurateControllerArmatureAdaptation_Event import InacurateControllerArmatureAdaptation_Event from case_study.units.adaptations.PowerInputAdaptation_Event import PowerInputAdaptation_Event from case_study.units.ct_based.ObstacleFMU import ObstacleFMU from case_study.units.ct_based.PowerFMU import PowerFMU from case_study.units.ct_based.WindowFMU import WindowFMU from case_study.units.de_based.DriverControllerStatechartFMU_Event import DriverControllerStatechartFMU_Event from case_study.units.de_based.EnvironmentStatechartFMU_Event import EnvironmentStatechartFMU_Event NUM_RTOL = 1e-08 NUM_ATOL = 1e-08 l = logging.getLogger() l.setLevel(logging.DEBUG) START_STEP_SIZE = 0.001 FMU_START_RATE = 10 STOP_TIME = 10; environment = EnvironmentStatechartFMU_Event("env", NUM_RTOL, NUM_ATOL) controller = DriverControllerStatechartFMU_Event("controller", NUM_RTOL, NUM_ATOL) power = PowerFMU("power", NUM_RTOL, NUM_ATOL, START_STEP_SIZE/FMU_START_RATE, J=0.085, b=5, K=1.8, R=0.15, L=0.036, V_a=12) armature_threshold = 20.0 adapt_armature = InacurateControllerArmatureAdaptation_Event("arm_adapt", NUM_RTOL, NUM_ATOL, armature_threshold, True) adapt_power_input = PowerInputAdaptation_Event("power_adapt") window = WindowFMU("window", NUM_RTOL, NUM_ATOL, START_STEP_SIZE/FMU_START_RATE, J=0.085, r=0.017, b = 150, c = 1e3) # c = 1e5 makes this an unstable system. obstacle = ObstacleFMU("obstacle", NUM_RTOL, NUM_ATOL, START_STEP_SIZE/FMU_START_RATE, c=1e5, fixed_x=0.45) environment.enterInitMode() controller.enterInitMode() power.enterInitMode() adapt_armature.enterInitMode() adapt_power_input.enterInitMode() window.enterInitMode() obstacle.enterInitMode() # Solve initialisation. """ The initialisation may impose a completely different order for the execution of the FMUs. In this case we know that there is no direct feed-through between the power input and its outputs, so we can safely set its initial state, get its output, and then compute all the other FMUs, before setting the new inputs to the power. There is also a tight coupling between the window and the obstacle FMU but we know what the initial force is, so we can use that to set the inputs and outputs in the right order, without having to do a fixed point iteration. But in the general case, we would need a fixed point iteration. """ pOut = power.setValues(0, 0, { power.omega: 0.0, power.theta: 0.0, power.i: 0.0 }) pOut = power.getValues(0, 0, [power.omega, power.theta, power.i]) window.setValues(0, 0, {window.omega_input: pOut[power.omega], window.theta_input: pOut[power.theta], window.theta: 0.0, window.omega: 0.0 }) wOut = window.getValues(0, 0, [window.x]) obstacle.setValues(0,0, {obstacle.x: wOut[window.x]}) oOut = obstacle.getValues(0, 0, [obstacle.F]) window.setValues(0, 0, {window.F_obj: oOut[obstacle.F]}) wOut = window.getValues(0, 0, [window.tau]) adapt_armature.setValues(0, 0, {adapt_armature.armature_current: pOut[power.i], adapt_armature.out_event: "" }) adaptArmOut = adapt_armature.getValues(0, 0, [adapt_armature.out_event]) environment.setValues(0, 0, {environment.__current_state : "Neutral", environment.out_event : ""}) envOut = environment.getValues(0, 0, [environment.out_event]) # coupling equation for the input event of the controller controller_in = adaptArmOut[adapt_armature.out_event] + envOut[environment.out_event] if adaptArmOut[adapt_armature.out_event] != "" and envOut[environment.out_event] != "": controller_in = adaptArmOut[adapt_armature.out_event] controller.setValues(0, 0, {controller.in_event : controller_in, controller.__current_state: "Neutral", controller.out_event: ""}) cOut = controller.getValues(0, 0, [controller.out_event]) adapt_power_input.setValues(0, 0, {adapt_power_input.in_event : cOut[controller.out_event], adapt_power_input.out_down: 0.0, adapt_power_input.out_up: 0.0}) adaptPowerOut = adapt_power_input.getValues(0, 0, [adapt_power_input.out_up, adapt_power_input.out_down]) # Finally set the other power inputs power.setValues(0, 0, {power.tau: wOut[window.tau], power.up: adaptPowerOut[adapt_power_input.out_up], power.down: adaptPowerOut[adapt_power_input.out_down]}) environment.exitInitMode() controller.exitInitMode() power.exitInitMode() adapt_armature.exitInitMode() adapt_power_input.exitInitMode() window.exitInitMode() obstacle.exitInitMode() trace_i = [0.0] trace_omega = [0.0] trace_x = [0.0] trace_F = [0.0] times = [0.0] time = 0.0 for step in range(1, int(STOP_TIME / START_STEP_SIZE) + 1): # Note that despite the fact that there is no feedthrough between # the inputs and the outputs of the power system, # the internal solver would still benefit from an up-to-date # value given for the inputs. However, that creates an algebraic loop, # so for now, we just get old values for the inputs. wOut = window.getValues(step-1, 0, [window.tau, window.x]) adaptPowerOut = adapt_power_input.getValues(step-1, 0, [adapt_power_input.out_up, adapt_power_input.out_down]) power.setValues(step, 0, {power.tau: wOut[window.tau], power.up: adaptPowerOut[adapt_power_input.out_up], power.down: adaptPowerOut[adapt_power_input.out_down]}) power.doStep(time, step, 0, START_STEP_SIZE) pOut = power.getValues(step, 0, [power.omega, power.theta, power.i]) obstacle.setValues(step, 0, {obstacle.x: wOut[window.x]}) obstacle.doStep(time, step, 0, START_STEP_SIZE) oOut = obstacle.getValues(step, 0, [obstacle.F]) window.setValues(step, 0, {window.omega_input: pOut[power.omega], window.theta_input: pOut[power.theta], window.F_obj: oOut[obstacle.F] }) window.doStep(time, step, 0, START_STEP_SIZE) wOut = window.getValues(step, 0, [window.tau, window.x]) adapt_armature.setValues(step, 0, {adapt_armature.armature_current: pOut[power.i]}) adapt_armature.doStep(time, step, 0, START_STEP_SIZE) adaptArmOut = adapt_armature.getValues(step, 0, [adapt_armature.out_event]) environment.doStep(time, step, 0, START_STEP_SIZE) envOut = environment.getValues(step, 0, [environment.out_event]) # coupling equation for the input event of the controller controller_in = adaptArmOut[adapt_armature.out_event] + envOut[environment.out_event] if adaptArmOut[adapt_armature.out_event] != "" and envOut[environment.out_event] != "": controller_in = adaptArmOut[adapt_armature.out_event] controller.setValues(step, 0, {controller.in_event : controller_in}) controller.doStep(time, step, 0, START_STEP_SIZE) cOut = controller.getValues(step, 0, [controller.out_event]) adapt_power_input.setValues(step, 0, {adapt_power_input.in_event : cOut[controller.out_event]}) adapt_power_input.doStep(time, step, 0, START_STEP_SIZE) adaptPowerOut = adapt_power_input.getValues(step, 0, [adapt_power_input.out_up, adapt_power_input.out_down]) # Finally set the other power inputs """ The instruction below is not really needed, as power has already performed the step. However, we leave it here because in case an algebraic loop were being solved, this is where we would set the improved values for the power inputs, and check for convergence. """ power.setValues(step, 0, {power.tau: wOut[window.tau], power.up: adaptPowerOut[adapt_power_input.out_up], power.down: adaptPowerOut[adapt_power_input.out_down]}) trace_omega.append(pOut[power.omega]) trace_i.append(pOut[power.i]) trace_x.append(wOut[window.x]) trace_F.append(oOut[obstacle.F]) time += START_STEP_SIZE times.append(time) color_pallete = [ "#e41a1c", "#377eb8", "#4daf4a", "#984ea3", "#ff7f00", "#ffff33", "#a65628", "#f781bf" ] output_file("./results.html", title="Results") p = figure(title="Plot", x_axis_label='time', y_axis_label='') p.line(x=times, y=trace_omega, legend="trace_omega", color=color_pallete[0]) p.line(x=times, y=trace_i, legend="trace_i", color=color_pallete[1]) show(p) output_file("./results_x.html", title="Results") p = figure(title="Plot", x_axis_label='time', y_axis_label='') p.line(x=times, y=trace_x, legend="trace_x", color=color_pallete[2]) show(p) output_file("./results_F.html", title="Results") p = figure(title="Plot", x_axis_label='time', y_axis_label='') p.line(x=times, y=trace_F, legend="trace_F", color=color_pallete[3]) show(p)
true
1684915267f58c55264c56f4b7ea2b08ac43defd
Python
ivSaav/Programming-Fundamentals
/RE07/triplet.py
UTF-8
598
3.8125
4
[]
no_license
#Given a tuple of n integers, with n > 3, write a Python function triplet(atuple) that finds a #triplet (a, b, c) such that their sum is zero (i.e., a + b + c = 0) def triplet(atuple): result = () indx_1 = 0 for item1 in atuple: indx_1 += 1 indx_2 = indx_1 for item2 in atuple[indx_1:]: indx_2 += 1 for item3 in atuple[indx_2:]: if item1 + item2 + item3 == 0: result = (item1, item2, item3) return result if result == (): return ()
true
4fa13ad720f3e5ef2655d1c030f0ef34ad504ac1
Python
webclinic017/SeleAio
/main.py
UTF-8
1,674
2.546875
3
[]
no_license
from email import encoders import smtplib, ssl from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase smtp_server = "smtp.gmail.com" port = 587 # For starttls sender_email = "poingshop@gmail.com" body = "This is an email with attachment sent from Python" password = input("what is your password of your email? ") context = ssl.create_default_context() with open("emails.txt", 'r') as f: emlist = f.readlines() try: server = smtplib.SMTP(smtp_server,port) server.ehlo() # Can be omitted server.starttls(context=context) # Secure the connection server.ehlo() # Can be omitted server.login(sender_email, password) for email in emlist: receiver_email = email message = MIMEMultipart("alternative") message["Subject"] = "multipart test" message["From"] = sender_email message["To"] = receiver_email message["Bcc"] = receiver_email message.attach(MIMEText(body, "plain")) filename="resume.pdf" with open(filename, "rb") as attachment: part = MIMEBase("application", "octet-stream") part.set_payload(attachment.read()) encoders.encode_base64(part) part.add_header( "Content-Disposition", f"attachment; filename= {filename}", ) message.attach(part) text = message.as_string() part1 = MIMEText(text, "plain") message.attach(part1) server.sendmail(sender_email, receiver_email, text ) except Exception as e: print(e) finally: server.quit() # این پروژه نهاییست
true
f271bbb8cb7868a53db12170be134b5d92d85fed
Python
afcarl/chatbot--EricSchles
/server/app/models.py
UTF-8
530
2.75
3
[]
no_license
from app import db class Greeting(db.Model): __tablename__ = 'greeting' id = db.Column(db.Integer, primary_key=True) greeting = db.Column(db.String) def __init__(self, greeting): self.greeting = greeting def __str__(self): return repr(self.greeting) class Log(db.Model): __tablename__ = 'log' id = db.Column(db.Integer, primary_key=True) log = db.Column(db.String) def __init__(self, log): self.log = log def __str__(self): return repr(self.log)
true
731b1372c087218dd6f8efa69210988600945f26
Python
Aravinthr20/Beg-Set5
/range.py
UTF-8
93
3.28125
3
[]
no_license
x=int(input()) if(x>10) or (x==0) or (x<0): print("NO") elif(x<=10): print("yes")
true
95d2aef0b079198520f5f7572e931875b8894d48
Python
h0108j/MyPythone
/Ch05/sam05.py
UTF-8
481
3.859375
4
[]
no_license
scoreKor = int(input("국어 점수를 입력하세요.")) scoreMath = int(input("수학 점수를 입력하세요.")) scoreEng = int(input("영어 점수를 입력하세요.")) avg = (scoreKor + scoreMath + scoreEng)/3 print("평균:", avg) if avg >= 90: print("A학점 입니다.") elif avg >= 80: print("B학점 입니다.") elif avg >= 70: print("C학점 입니다.") elif avg >= 60: print("D학점 입니다.") else: print("F학점 입니다.")
true
1b299bc4054869e3514cf0b9e1400bfd6741e4d0
Python
IamWilliamWang/Leetcode-practice
/2020.4/Permute.py
UTF-8
447
3.171875
3
[]
no_license
class Solution: def permute(self, nums: list) -> list: if len(nums) == 0: return [[]] result = [] for firstNum in nums: nextNums = nums.copy() nextNums.remove(firstNum) matrix = self.permute(nextNums) for i in range(len(matrix)): matrix[i].insert(0, firstNum) result += matrix return result print(Solution().permute([]))
true
69c2d640e36c7b4b793c1f55dff32493385e0a54
Python
lijx10/opengm
/src/interfaces/python/examples/add_multiple_unaries.py
UTF-8
945
2.8125
3
[ "MIT" ]
permissive
import opengm import numpy #------------------------------------------------------------------------------------ # This example shows how multiple unaries functions and functions / factors add once #------------------------------------------------------------------------------------ # add unaries from a for a 2d grid / image width=10 height=20 numVar=width*height numLabels=2 # construct gm gm=opengm.gm(numpy.ones(numVar,dtype=opengm.index_type)*numLabels) # construct an array with all unaries (random in this example) unaries=numpy.random.rand(width,height,numLabels) # reshape unaries is such way, that the first axis is for the different functions unaries2d=unaries.reshape([numVar,numLabels]) # add all unary functions at once (#numVar unaries) fids=gm.addFunctions(unaries2d) # numpy array with the variable indices for all factors vis=numpy.arange(0,numVar,dtype=numpy.uint64) # add all unary factors at once gm.addFactors(fids,vis)
true
a92d19877f72cf0bfa435883d6aed26778871c11
Python
Thirumurugan-12/Python-programs-11th
/2n2n+1.py
UTF-8
183
3.671875
4
[]
no_license
#sum of N natural numbers n=int(input("Enter the number ")) os,es=0,0 for i in range(1,n+1,2): os+=i print(i,os) for i in range(2,n+1,2): es+=i print(i,es)
true
cbe938073c14ba7bd0bad9fa136dfcd30525cbc7
Python
giurgiumatei/Fundamentals-of-Programming
/Pandemic Simulation (Prophecy of Corona)/Services.py
UTF-8
1,624
2.71875
3
[]
no_license
class service: def __init__(self,p_repo): self.p_repo=p_repo def get_persons(self): return self.p_repo.get_persons() def infect(self):#look specifications persons=self.p_repo.get_persons() counter=0 #check if there are ill persons for p in persons: #search for them if p.get_status()=='ill': counter=1 if counter==0: return 0 for p in persons: # if healthy become ill if p.get_immune_status()!='vaccinated': if p.get_status()=='healthy': p.set_status('ill') print("Infected") self.p_repo.set_persons(persons) return 1 #exit after spreading plague def simulate(self):# simulate the day persons=self.p_repo.get_persons() # get persons list for p in persons:#look in the persons list p.set_cont(int(p.get_cont()-1))# decrease the day counter if p.get_cont()==0: p.set_status('healthy') # set status to healthy self.p_repo.set_persons(persons) return 1 def vaccinate(self,value): persons=self.p_repo.get_persons() for p in persons: if p.get_id()==value: if p.get_status()=='healthy': p.set_immune_status('vaccinated') self.p_repo.set_persons(persons) return 1 return 0
true
0c0a568b320982f1f54bb9b530d6453b75a54b99
Python
stevenlrj/Deep-Learning
/vgg.py
UTF-8
3,624
3.3125
3
[]
no_license
import tensorflow as tf import numpy as np import scipy.io def _conv_layer(input, weights, bias): """ used to calculate the output of con2d layer, Wx+b """ conv = tf.nn.conv2d(input, tf.constant(weights), strides=(1, 1, 1, 1), padding='SAME') return tf.nn.bias_add(conv, bias) def cnn_net(model_path, input_image): """ :input: :model_path: path to the pre-trained vgg19 mat file :input_image: initial image used for training :output: :net: the neural net weights given specified layer name, either in 'conv' or 'relu' or 'pool' :mean_pixel: teh calculated mean_pixel value of """ # in the original pre-trained VGG19 network, there're 43 layers with # types like conv2d, zero-padding, max-pooling, dropout, # fully-connected layers, etc. Here we're only interested in # conv layers, relu activation functions and pooling layers vgg19_layers = ( 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', 'pool2', 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', 'relu3_3', 'conv3_4', 'relu3_4', 'pool3', 'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3', 'relu4_3', 'conv4_4', 'relu4_4', 'pool4', 'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3', 'relu5_3', 'conv5_4', 'relu5_4' ) # First let's load in the pre-trained model vgg19_model = scipy.io.loadmat(model_path) # extract mean info mean = vgg19_model['normalization'][0][0][0] # mean is of size (224, 224, 3) # then calculate the mean for each channel (RGB) mean_pixel = np.mean(mean, axis=(0, 1)) # mean is of size (3,) # exract weights info from 'layer' weights = vgg19_model['layers'][0] # initilize net variable as an empty dictionary, later when # we extract each layer's info, we simply refer to the key value net = {} layer_output = input_image for i, layer in enumerate(vgg19_layers): layer_type = layer[:4] if layer_type == 'conv': # for conv layers, each kernels of size (3, 3, 3, 64), and bias of size (1, 64) kernels, bias = weights[i][0][0][0][0] # Note that the information stored in tf and mat are different, here # we need to switch the first and second dimention of the variable # matconvnet: weights are [width, height, in_channels, out_channels] # tensorflow: weights are [height, width, in_channels, out_channels] kernels = np.transpose(kernels, (1, 0, 2, 3)) # reshape bias from 2d (1, 64) to 1d (64, ) bias = bias.reshape(-1) layer_output = _conv_layer(layer_output, kernels, bias) elif layer_type == 'relu': layer_output = tf.nn.relu(layer_output) elif layer_type == 'pool': # proposed in the original paper, the trained results are better using # average pooling instead of max pool, so here we changed the # pooling to average pooling. layer_output = tf.nn.avg_pool(layer_output, ksize=(1, 2, 2, 1), strides=(1, 2, 2, 1), padding='SAME') # finally, store the output from each layer into corresponding net (a dictionary) net[layer] = layer_output assert len(net) == len(vgg19_layers) return net, mean_pixel def preprocess(image, mean_pixel): """ normalize image """ return image - mean_pixel def unprocess(image, mean_pixel): """ restore image as final output """ return image + mean_pixel
true
7d92d1191c205b193d003fdaea3776d8531cf6b4
Python
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_123/47.py
UTF-8
1,415
2.546875
3
[]
no_license
import fileinput,sys import math print_indicator = 0 def myprint(*arg): if print_indicator != 0: print print_indicator print arg lines = [] for line in fileinput.input(): lines.append(line) n= int(lines[0]) case = 0 line_no =1 myprint("n",n) for j in xrange(1,n+1): case +=1 print "Case #%d:" % (case), nbym = (lines[line_no]).partition(" ") line_no +=1 A = int(nbym[0]) N = int(nbym[2]) #slow(r,t) #fast(r,t) current_line = lines[line_no] line_no+=1 row = [] for k in xrange(0,N): cl_split = current_line.partition(" ") row.append(int(cl_split[0])) current_line = cl_split[2] #row.sort() myprint("row", row) added = 0 delete_rest_score = N k = 0 best_score = N cur_score = N row.sort() while (k < len(row)): myprint("A", A, "added", added, "best_score", best_score) if (A > row[k]): A += row[k] k +=1 cur_score -=1 if (cur_score < best_score): best_score = cur_score else: added += 1 A += A-1 cur_score += 1 if added > best_score: break myprint("A", A, "added", added, "best_score", best_score) print best_score
true