hexsha
string
size
int64
ext
string
lang
string
max_stars_repo_path
string
max_stars_repo_name
string
max_stars_repo_head_hexsha
string
max_stars_repo_licenses
list
max_stars_count
int64
max_stars_repo_stars_event_min_datetime
string
max_stars_repo_stars_event_max_datetime
string
max_issues_repo_path
string
max_issues_repo_name
string
max_issues_repo_head_hexsha
string
max_issues_repo_licenses
list
max_issues_count
int64
max_issues_repo_issues_event_min_datetime
string
max_issues_repo_issues_event_max_datetime
string
max_forks_repo_path
string
max_forks_repo_name
string
max_forks_repo_head_hexsha
string
max_forks_repo_licenses
list
max_forks_count
int64
max_forks_repo_forks_event_min_datetime
string
max_forks_repo_forks_event_max_datetime
string
content
string
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
qsc_code_num_words_quality_signal
int64
qsc_code_num_chars_quality_signal
float64
qsc_code_mean_word_length_quality_signal
float64
qsc_code_frac_words_unique_quality_signal
float64
qsc_code_frac_chars_top_2grams_quality_signal
float64
qsc_code_frac_chars_top_3grams_quality_signal
float64
qsc_code_frac_chars_top_4grams_quality_signal
float64
qsc_code_frac_chars_dupe_5grams_quality_signal
float64
qsc_code_frac_chars_dupe_6grams_quality_signal
float64
qsc_code_frac_chars_dupe_7grams_quality_signal
float64
qsc_code_frac_chars_dupe_8grams_quality_signal
float64
qsc_code_frac_chars_dupe_9grams_quality_signal
float64
qsc_code_frac_chars_dupe_10grams_quality_signal
float64
qsc_code_frac_chars_replacement_symbols_quality_signal
float64
qsc_code_frac_chars_digital_quality_signal
float64
qsc_code_frac_chars_whitespace_quality_signal
float64
qsc_code_size_file_byte_quality_signal
float64
qsc_code_num_lines_quality_signal
float64
qsc_code_num_chars_line_max_quality_signal
float64
qsc_code_num_chars_line_mean_quality_signal
float64
qsc_code_frac_chars_alphabet_quality_signal
float64
qsc_code_frac_chars_comments_quality_signal
float64
qsc_code_cate_xml_start_quality_signal
float64
qsc_code_frac_lines_dupe_lines_quality_signal
float64
qsc_code_cate_autogen_quality_signal
float64
qsc_code_frac_lines_long_string_quality_signal
float64
qsc_code_frac_chars_string_length_quality_signal
float64
qsc_code_frac_chars_long_word_length_quality_signal
float64
qsc_code_frac_lines_string_concat_quality_signal
float64
qsc_code_cate_encoded_data_quality_signal
float64
qsc_code_frac_chars_hex_words_quality_signal
float64
qsc_code_frac_lines_prompt_comments_quality_signal
float64
qsc_code_frac_lines_assert_quality_signal
float64
qsc_codepython_cate_ast_quality_signal
float64
qsc_codepython_frac_lines_func_ratio_quality_signal
float64
qsc_codepython_cate_var_zero_quality_signal
bool
qsc_codepython_frac_lines_pass_quality_signal
float64
qsc_codepython_frac_lines_import_quality_signal
float64
qsc_codepython_frac_lines_simplefunc_quality_signal
float64
qsc_codepython_score_lines_no_logic_quality_signal
float64
qsc_codepython_frac_lines_print_quality_signal
float64
qsc_code_num_words
int64
qsc_code_num_chars
int64
qsc_code_mean_word_length
int64
qsc_code_frac_words_unique
null
qsc_code_frac_chars_top_2grams
int64
qsc_code_frac_chars_top_3grams
int64
qsc_code_frac_chars_top_4grams
int64
qsc_code_frac_chars_dupe_5grams
int64
qsc_code_frac_chars_dupe_6grams
int64
qsc_code_frac_chars_dupe_7grams
int64
qsc_code_frac_chars_dupe_8grams
int64
qsc_code_frac_chars_dupe_9grams
int64
qsc_code_frac_chars_dupe_10grams
int64
qsc_code_frac_chars_replacement_symbols
int64
qsc_code_frac_chars_digital
int64
qsc_code_frac_chars_whitespace
int64
qsc_code_size_file_byte
int64
qsc_code_num_lines
int64
qsc_code_num_chars_line_max
int64
qsc_code_num_chars_line_mean
int64
qsc_code_frac_chars_alphabet
int64
qsc_code_frac_chars_comments
int64
qsc_code_cate_xml_start
int64
qsc_code_frac_lines_dupe_lines
int64
qsc_code_cate_autogen
int64
qsc_code_frac_lines_long_string
int64
qsc_code_frac_chars_string_length
int64
qsc_code_frac_chars_long_word_length
int64
qsc_code_frac_lines_string_concat
null
qsc_code_cate_encoded_data
int64
qsc_code_frac_chars_hex_words
int64
qsc_code_frac_lines_prompt_comments
int64
qsc_code_frac_lines_assert
int64
qsc_codepython_cate_ast
int64
qsc_codepython_frac_lines_func_ratio
int64
qsc_codepython_cate_var_zero
int64
qsc_codepython_frac_lines_pass
int64
qsc_codepython_frac_lines_import
int64
qsc_codepython_frac_lines_simplefunc
int64
qsc_codepython_score_lines_no_logic
int64
qsc_codepython_frac_lines_print
int64
effective
string
hits
int64
d9265bc8d9e395e0e1f4b2ccd82a397094568300
324
py
Python
flask-portal/app/referral_api.py
TUMTICS-Dev/Talent-Pool
c51376453184e7a83d684ab5f9467535d49cc784
[ "MIT" ]
null
null
null
flask-portal/app/referral_api.py
TUMTICS-Dev/Talent-Pool
c51376453184e7a83d684ab5f9467535d49cc784
[ "MIT" ]
null
null
null
flask-portal/app/referral_api.py
TUMTICS-Dev/Talent-Pool
c51376453184e7a83d684ab5f9467535d49cc784
[ "MIT" ]
null
null
null
from abc import ABC class Refferal_API(ABC): def __init__(self): # TODO pass def NewVacancy(): # TODO pass def NewApplication(): # TODO pass def NotifyReferrer(): # TODO pass def NotifyApplicant(): # TODO pass
13.5
26
0.481481
29
324
5.206897
0.517241
0.264901
0.291391
0
0
0
0
0
0
0
0
0
0.447531
324
24
27
13.5
0.843575
0.074074
0
0.416667
0
0
0
0
0
0
0
0.041667
0
1
0.416667
false
0.416667
0.083333
0
0.583333
0
1
0
0
null
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
1
0
1
0
0
1
0
0
7
d92747989c01c959e00977a548eb19a60491a46f
502
py
Python
sms_voting/migrations/0012_auto_20211110_0517.py
Fedor-Lyanguzov/Voting
98f8fd958624fa9ba3835836c525fbb4abb6b5e5
[ "MIT" ]
null
null
null
sms_voting/migrations/0012_auto_20211110_0517.py
Fedor-Lyanguzov/Voting
98f8fd958624fa9ba3835836c525fbb4abb6b5e5
[ "MIT" ]
1
2021-12-04T11:43:25.000Z
2021-12-04T11:43:25.000Z
sms_voting/migrations/0012_auto_20211110_0517.py
Fedor-Lyanguzov/Voting
98f8fd958624fa9ba3835836c525fbb4abb6b5e5
[ "MIT" ]
null
null
null
# Generated by Django 3.2.8 on 2021-11-10 05:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sms_voting', '0011_auto_20211110_0502'), ] operations = [ migrations.RemoveField( model_name='bulletin', name='result', ), migrations.AlterField( model_name='poll', name='remote_participants', field=models.TextField(default=''), ), ]
21.826087
50
0.575697
49
502
5.755102
0.795918
0.06383
0
0
0
0
0
0
0
0
0
0.089337
0.308765
502
22
51
22.818182
0.723343
0.089641
0
0.125
1
0
0.153846
0.050549
0
0
0
0
0
1
0
false
0
0.0625
0
0.25
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
d9299b500db19594cc491478d54c215f25629150
670
py
Python
app/platform.py
edwarts/igenweb_supplier
90e03b7acdedf65ae6b338d39b067bd4d1c0eaad
[ "MIT" ]
null
null
null
app/platform.py
edwarts/igenweb_supplier
90e03b7acdedf65ae6b338d39b067bd4d1c0eaad
[ "MIT" ]
null
null
null
app/platform.py
edwarts/igenweb_supplier
90e03b7acdedf65ae6b338d39b067bd4d1c0eaad
[ "MIT" ]
null
null
null
import os from config import config def getpath(path): base_path = os.path.join(config.upload_path, 'app', 'static', 'upload') UPLOAD_LICENCE_FOLDER = os.path.join(base_path, 'licence') UPLOAD_COVER_FOLDER = os.path.join(base_path, 'cover') UPLOAD_PIECE_FOLDER = os.path.join(base_path, 'pieceimg') UPLOAD_LIGHT_FOLDER = os.path.join(base_path, 'light') if path == "licence": return UPLOAD_LICENCE_FOLDER elif path == "cover": return UPLOAD_COVER_FOLDER elif path == "pieceimg": return UPLOAD_PIECE_FOLDER elif path == "light": return UPLOAD_LIGHT_FOLDER return path
31.904762
65
0.658209
86
670
4.872093
0.244186
0.095465
0.119332
0.152745
0.229117
0.229117
0
0
0
0
0
0
0.237313
670
20
66
33.5
0.819961
0
0
0
0
0
0.097015
0
0
0
0
0
0
1
0.055556
false
0
0.111111
0
0.444444
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d92ba4c735d6a176f4e2696a38a3cab4031d7e30
5,551
py
Python
csvfit/fitpt.py
hanKo91/csvfit
0b07929235f0531ea3b21df2d550390f680edfcf
[ "MIT" ]
null
null
null
csvfit/fitpt.py
hanKo91/csvfit
0b07929235f0531ea3b21df2d550390f680edfcf
[ "MIT" ]
null
null
null
csvfit/fitpt.py
hanKo91/csvfit
0b07929235f0531ea3b21df2d550390f680edfcf
[ "MIT" ]
null
null
null
from click.exceptions import FileError from scipy.optimize import curve_fit import matplotlib.pyplot as plt from . import util import numpy as np import click import sys import csv import os def pt1(t, K, T): """ time-domain solution/formula for a first-order/pt1 system Args: t (float): time K (float): gain T (float): time-constant Returns: float: f(t) """ return K * (1 - np.exp(-t/T)) def pt2(t, K, T): """ time-domain solution/formula for a second-order/pt2 system with critical damping, d = 1, T = T1 = T2 Args: t (float): time K (float): gain T (float): time-constant Returns: float: f(t) """ return K * (1 - np.exp(-t/T) - ((t/T) * np.exp(-t/T))) def pt1gen(t_arr, K, T, y0 = 0): """ generate y(t) of PT1 for t in t_arr Args: t_arr (list(float)): time array K (float): gain T (float): time-constant Returns: list(float): y(t) for t in t_arr """ return [pt1(t, K, T) + y0 for t in t_arr] def pt2gen(t_arr, K, T, y0 = 0): """ generate y(t) of PT2 for t in t_arr Args: t_arr (list(float)): time array K (float): gain T (float): time-constant Returns: list(float): y(t) for t in t_arr """ return [pt2(t, K, T) + y0 for t in t_arr] def pt1fit(t, y, Kg=1, Tg=1): """ curve_fit of pt1(-like) data Args: t (list(float)): time y (list(float)): output Kg (float, optional): initial guess for gain. Defaults to 1. Tg (float, optional): initial guess for time-constant. Defaults to 1. Returns: tuple(float,float): best fit -> K_opt, T_opt """ if not len(t) == len(y): return None # delete offset and normalize t = [n - t[0] for n in t] y = [n - y[0] for n in y] t_norm = [n / max(t) for n in t] y_norm = [n / max(y) for n in y] (popt,_) = curve_fit(pt1, t_norm, y_norm, p0=[Kg, Tg], absolute_sigma=True) K_opt = max(y) * popt[0] T_opt = max(t) * popt[1] return (K_opt, T_opt) def pt2fit(t, y, Kg=1, Tg=1): """ curve_fit of pt2(-like) data Args: t (list(float)): time y (list(float)): output Kg (float, optional): initial guess for gain. Defaults to 1. Tg (float, optional): initial guess for time-constant. Defaults to 1. Returns: tuple(float,float): best fit -> K_opt, T_opt """ if not len(t) == len(y): return None # delete offset and normalize t = [n - t[0] for n in t] y = [n - t[0] for n in y] t_norm = [n / max(t) for n in t] y_norm = [n / max(y) for n in y] (popt,_) = curve_fit(pt2, t_norm, y_norm, p0=[Kg, Tg], absolute_sigma=True) K_opt = max(y) * popt[0] T_opt = max(t) * popt[1] return (K_opt, T_opt) @click.option("--datapath", "-d", help="Path to csv file with target data", type=click.Path(exists=True)) @click.option("--eventspath", "-e", help="Path to csv file with event data", type=click.Path()) @click.option("--outdir", "-o", help="Directory to store output artifacts", type=click.Path(exists=True)) @click.option("--columns", "-c", help="Name of the columns", type=str, multiple=True) @click.option("--type", "-t", help="PTn type: PT1, PT2", type=str, multiple=True) @click.option("--show", "-s", help="Show plots", is_flag=True) @click.command() def do_fit(datapath, eventspath, outdir, columns, show): data = [] delimiter = util.get_delimiter(datapath) with open(datapath, 'r') as data_file: reader = csv.DictReader(data_file, delimiter=delimiter) for entry in reader: data.append(entry) events = [] delimiter = util.get_delimiter(eventspath) with open(eventspath, 'r') as events_file: reader = csv.DictReader(events_file, delimiter=delimiter) for entry in reader: events.append(entry) data_per_event = {} time_slots = [] for key in list(events[0].keys()): if key == "<event-name>": continue from_index = int(events[0][key]) to_index = int(events[1][key]) time_slots.append(range(from_index, to_index)) data_per_event[key] = data[from_index:to_index] for col in columns: ptn_param = [] plt.figure() plt.plot(util.column(data, col), label="all") for index, key in enumerate(list(data_per_event.keys())): if type == "PT1": ptn_param.append(pt1fit(time_slots[index], util.column(data_per_event[key], col))) elif type == "PT2": ptn_param.append(pt2fit(time_slots[index], util.column(data_per_event[key], col))) print(key, end=": (K_opt, T_opt)=") print(ptn_param[index]) plt.plot(time_slots[index], util.column(data_per_event[key], col), label=f"{key} : {time_slots[index]}") plt.legend() plt.grid('both') plt.savefig(f"{outdir}/timeslots_{col}.png") for index, key in enumerate(list(data_per_event.keys())): plt.figure() col_data = np.array(util.column(data_per_event[key], col)) col_data -= col_data[0] plt.plot(col_data, label=f"{key}") t_arr = range(len(time_slots[index])) K_opt = ptn_param[index][0] T_opt = ptn_param[index][1] if type == "PT1": plt.plot(pt1gen(t_arr, K_opt, T_opt), "--", label=f"{key} --fit") elif type == "PT2": plt.plot(pt2gen(t_arr, K_opt, T_opt), "--", label=f"{key} --fit") plt.title(f"K_opt: {K_opt}\nT_opt: {T_opt}") plt.legend() plt.grid('both') plt.savefig(f"{outdir}/{col}_{key}_fit.png") if show: plt.show() def main(): if len(sys.argv) == 1: do_fit.main(["--help"]) else: do_fit.main() if __name__ == "__main__": main()
27.755
110
0.611421
914
5,551
3.588621
0.175055
0.015854
0.017073
0.017073
0.568293
0.564329
0.532927
0.480488
0.480488
0.427439
0
0.014362
0.222302
5,551
199
111
27.894472
0.745425
0.233291
0
0.277778
0
0
0.102902
0.013655
0
0
0
0
0
1
0.074074
false
0
0.083333
0
0.231481
0.018519
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d92be7a0a2a9418b2f005b72010bbabb90745df1
2,632
py
Python
commands/Premium/premium.py
adl212/Lacan-NTSport-Source-Code
b5b01cbb5cc97b5cbd3a6ebcf90c2e6d82322968
[ "MIT" ]
1
2021-04-25T18:31:48.000Z
2021-04-25T18:31:48.000Z
commands/Premium/premium.py
adl212/Lacan-NTSport-Source-Code
b5b01cbb5cc97b5cbd3a6ebcf90c2e6d82322968
[ "MIT" ]
6
2021-03-26T21:18:57.000Z
2021-05-03T18:04:37.000Z
commands/Premium/premium.py
adl212/Lacan-NTSport-Source-Code
b5b01cbb5cc97b5cbd3a6ebcf90c2e6d82322968
[ "MIT" ]
4
2021-03-06T16:48:36.000Z
2021-05-23T00:54:09.000Z
'''What is premium?''' from discord.ext import commands from packages.utils import Embed, ImproperType class Command(commands.Cog): def __init__(self, client): self.client= client @commands.command() async def premium(self, ctx): #return await ctx.send('This command is currently under maintenance. The developers will try to get it up again as soon as possible. In the meantime feel free to use `n.help` to get the other commands. Thank you for your understanding!') if await ImproperType.check(ctx): return embed=Embed('Premium', 'Premium is a one time purchase for your Discord server. \n It will make your server appearance a lot better. \n There are lots of benefits you will get for being a premium server. \n \n Your benefits are: \n :small_blue_diamond: **LIFETIME** server access to **all** features of this bot. \n :small_blue_diamond: You don\'t have to do anything, the bot will create speed, gold member, accuracy and race roles for your server. \n :small_blue_diamond: Role registering / updating system through the command `n.update`. \n :small_blue_diamond: Nickname updating system through the command `n.update`. \n :small_blue_diamond: The feeling that you helped the developers a lot through your purchasement. \n :small_blue_diamond: More things coming soon:tm:, so stay tuned. \n \n :small_orange_diamond: In order to receive these Premium features, check your class down below. Then send `10M` to [this](https://nitrotype.com/racer/hypertyper55) account and DM <@505338178287173642> on discord.', 'diamond_shape_with_a_dot_inside') #\n\n **__List of Premium 💠 Server Prizes__** (since December 20th 2020)\n\n:small_orange_diamond: ***Class I:*** Human Members: __<50__, Age: __>3 months__: `5M`.\n\n:small_orange_diamond: ***Class II:*** Human members: __50-99__, Age: __>3 months__: `10M`.\n\n:small_orange_diamond: ***Class III:*** Human members: 100-150, Age: __>3 months__: `15M`. \n\n:small_orange_diamond: ***Class IV:*** Human members: __150-199__, Age __>3 months__: `20M`. \n\n:small_orange_diamond: ***Class V: ***Human members: __200+__, Age: __>3 months__: `25M`. \n\n:small_orange_diamond: ***Class VI: ***Human members: __ANY__, Age: __<3 months__: `20M`.') embed.footer(f'{ctx.author} • Become a premium 💠 member today! 💗') embed.thumbnail('https://media.discordapp.net/attachments/719414661686099993/754971786231283712/season-callout-badge.png') await embed.send(ctx) try: await ctx.message.delete() except: pass def setup(client): client.add_cog(Command(client))
101.230769
1,054
0.720365
396
2,632
4.585859
0.462121
0.042952
0.026982
0.05011
0.154185
0.143172
0.060573
0.060573
0.060573
0.060573
0
0.046259
0.162234
2,632
26
1,055
101.230769
0.77551
0.338526
0
0
0
0.055556
0.27781
0
0
0
0
0
0
1
0.111111
false
0.055556
0.111111
0
0.277778
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
3
d92e5de5ecf3982b6bb7d90e259217262a07f9b5
4,435
py
Python
wireless_emulator/cli.py
Melacon/OpenYuma_WE
f43a25cf99444c29d9fbadfe336182d60e1bc3f4
[ "Apache-2.0" ]
1
2017-02-24T09:30:21.000Z
2017-02-24T09:30:21.000Z
wireless_emulator/cli.py
Melacon/OpenYuma_WE
f43a25cf99444c29d9fbadfe336182d60e1bc3f4
[ "Apache-2.0" ]
null
null
null
wireless_emulator/cli.py
Melacon/OpenYuma_WE
f43a25cf99444c29d9fbadfe336182d60e1bc3f4
[ "Apache-2.0" ]
2
2018-06-21T13:23:08.000Z
2021-04-01T06:35:16.000Z
from cmd import Cmd import sys from select import poll, POLLIN import string from subprocess import call from wireless_emulator import * from wireless_emulator.clean import cleanup class CLI(Cmd): prompt = 'WirelessTransportEmulator>' identchars = string.ascii_letters + string.digits + '_' + '-' def __init__(self, emulator, stdin=sys.stdin): self.emulator = emulator self.inPoller = poll() self.inPoller.register(stdin) Cmd.__init__(self) print( '*** Starting CLI:\n' ) self.run() def run(self): while True: try: # Make sure no nodes are still waiting self.cmdloop() break except KeyboardInterrupt: # Output a message - unless it's also interrupted # pylint: disable=broad-except try: print( '\nKeyboard interrupt. Use quit or exit to shotdown the emulator.\n' ) except Exception: pass def default(self, line): """Called on an input line when the command prefix is not recognized. Overridden to run shell commands when a node is the first CLI argument. Past the first CLI argument, node names are automatically replaced with corresponding IP addrs.""" first, args, line = self.parseline(line) node = self.emulator.getNeByName(first) if node is not None: rest = args.split(' ') node.executeCommand(args) else: print('Node %s not found' % first) def emptyline( self ): "Don't repeat last command when you hit return." pass def do_exit(self, _line): "Exit" cleanup(self.emulator.configFileName) return 'exited by user command' def do_quit(self, line): "Exit" return self.do_exit(line) def do_print_nodes(self, _line): "Prints the names of all the Network Elements emulated" print('Available NEs are:') for neObj in self.emulator.networkElementList: print('%s' % neObj.uuid) def do_print_node_info(self, line): "Prints the information of the specified Network Element" args = line.split() if len(args) != 1: print('ERROR: usage: print_node_info <NE_UUID>') return node = self.emulator.getNeByName(args[0]) if node is not None: print('#########################################') print('#### Network Element UUID: \'%s\'' % node.uuid) print('#### Network Element management IP: %s' % node.managementIPAddressString) print('########### Interfaces: ###########') for intf in node.interfaceList: print('Interface: UUID=\'%s\' having IP=%s and Linux Interface Name=\'%s\'' % (intf.uuid, intf.IP, intf.interfaceName)) print('#########################################') else: print('Node %s not found' % args[0]) def do_dump_nodes(self, _line): "Dumps the information about all of the available Network Elements" for node in self.emulator.networkElementList: print('#########################################') print('#### Network Element UUID: \'%s\'' % node.uuid) print('#### Network Element management IP: %s' % node.managementIPAddressString) print('########### Interfaces: ###########') for intf in node.interfaceList: print('Interface: UUID=\'%s\' having IP=%s and Linux Interface Name=\'%s\'' % (intf.uuid, intf.IP, intf.interfaceName)) print('#########################################') def do_dump_links(self, _line): "Dumps the links available in the network" for topo in self.emulator.topologies: print('#################### %s #####################' % topo.topologyLayer) for link in topo.linkList: print('## Link=%d ## \'%s\': \'%s\' <-------> \'%s\':\'%s\'' % (link.linkId, link.interfacesObj[0].getNeName(), link.interfacesObj[0].getInterfaceUuid(), link.interfacesObj[0].getInterfaceUuid(), link.interfacesObj[1].getNeName())) print('#########################################')
39.247788
112
0.530778
460
4,435
5.05
0.358696
0.041326
0.032716
0.016358
0.291864
0.249247
0.193715
0.193715
0.193715
0.193715
0
0.002259
0.30124
4,435
112
113
39.598214
0.747338
0.140699
0
0.306818
0
0
0.272139
0.062687
0
0
0
0
0
1
0.113636
false
0.022727
0.079545
0
0.261364
0.272727
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d92fdd9690a161af17e354836da77242710c2f29
1,036
py
Python
booking_app/models.py
alikhalilica/cilinic-temp
5822879cda27bc121adbd2a8da947c881d88fbd3
[ "MIT" ]
null
null
null
booking_app/models.py
alikhalilica/cilinic-temp
5822879cda27bc121adbd2a8da947c881d88fbd3
[ "MIT" ]
null
null
null
booking_app/models.py
alikhalilica/cilinic-temp
5822879cda27bc121adbd2a8da947c881d88fbd3
[ "MIT" ]
null
null
null
from django.db import models # Create your models here. class HelthDepartment(models.Model): name = models.CharField(max_length=100) availability = models.DateTimeField() def __str__(self): return self.name #helth_department = ((0,"daily task"),(1,"work jobs"),(2,"house needs")) class Patient(models.Model): name = models.CharField(max_length=100) contact = models.CharField(max_length=100) email = models.EmailField() booking_date = models.DateTimeField(auto_now_add=True,blank=True,null=True) appointment_date = models.DateTimeField(null=True , blank=True) #appointment_time = models.TimeField(null=True , blank=True) helth_department = models.ForeignKey(HelthDepartment,on_delete=models.CASCADE,null=True) history = models.TextField() #patient_contact = models.PhoneField() #helth_department = models.PositiveSmallIntegerField(choices=helth_department,default=0) def __str__(self): return self.name class Meta: ordering = ["-booking_date"]
33.419355
93
0.725869
124
1,036
5.879032
0.483871
0.082305
0.074074
0.098765
0.218107
0.18107
0.115226
0.115226
0
0
0
0.014908
0.158301
1,036
30
94
34.533333
0.821101
0.26834
0
0.333333
0
0
0.017287
0
0
0
0
0
0
1
0.111111
false
0
0.055556
0.111111
0.944444
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
1
1
0
0
2
d9300939b02465cc95f8d69b6ff94ca1db4e605a
1,647
py
Python
vid/migrations/0003_auto_20211222_0019.py
timmyoder/covid_tracker
88598043b595f3f63a28e43a732d2f854d4aca9d
[ "MIT" ]
null
null
null
vid/migrations/0003_auto_20211222_0019.py
timmyoder/covid_tracker
88598043b595f3f63a28e43a732d2f854d4aca9d
[ "MIT" ]
null
null
null
vid/migrations/0003_auto_20211222_0019.py
timmyoder/covid_tracker
88598043b595f3f63a28e43a732d2f854d4aca9d
[ "MIT" ]
null
null
null
# Generated by Django 3.0.3 on 2021-12-22 00:19 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('vid', '0002_allnty'), ] operations = [ migrations.CreateModel( name='CountyMetrics', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateTimeField()), ('county', models.CharField(max_length=128)), ('state', models.CharField(max_length=128)), ('fips', models.CharField(max_length=128, null=True)), ('cases', models.IntegerField(null=True)), ('deaths', models.IntegerField(null=True)), ('population', models.IntegerField()), ('testPositivityRatio', models.FloatField(null=True)), ('infectionRate', models.FloatField(null=True)), ], options={ 'unique_together': {('date', 'fips')}, }, ), migrations.RenameModel( old_name='AllNTY', new_name='EntireUS', ), migrations.DeleteModel( name='CasesDeathsNTY', ), migrations.DeleteModel( name='MetricsActNow', ), migrations.DeleteModel( name='PennCases', ), migrations.DeleteModel( name='PennDeaths', ), migrations.DeleteModel( name='PennHospitals', ), migrations.DeleteModel( name='Places', ), ]
30.5
114
0.518519
129
1,647
6.542636
0.527132
0.149289
0.177725
0.085308
0.095972
0
0
0
0
0
0
0.025998
0.346084
1,647
53
115
31.075472
0.75766
0.027322
0
0.297872
1
0
0.128125
0
0
0
0
0
0
1
0
false
0
0.021277
0
0.085106
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
d9305b2cad920233b9a78c2c2fa32100230f3dc5
101
py
Python
BOJ/16000~16999/16500~16599/16515.py
shinkeonkim/today-ps
f3e5e38c5215f19579bb0422f303a9c18c626afa
[ "Apache-2.0" ]
2
2020-01-29T06:54:41.000Z
2021-11-07T13:23:27.000Z
BOJ/16000~16999/16500~16599/16515.py
shinkeonkim/Today_PS
bb0cda0ee1b9c57e1cfa38355e29d0f1c6167a44
[ "Apache-2.0" ]
null
null
null
BOJ/16000~16999/16500~16599/16515.py
shinkeonkim/Today_PS
bb0cda0ee1b9c57e1cfa38355e29d0f1c6167a44
[ "Apache-2.0" ]
null
null
null
import math s = 0.0 k = 1 n = int(input()) for i in range(n+1): k*=max(1,i) s += 1/k print(s)
12.625
20
0.514851
25
101
2.08
0.6
0.076923
0
0
0
0
0
0
0
0
0
0.081081
0.267327
101
8
21
12.625
0.621622
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.125
0
0.125
0.125
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d930bd7e55bef5a0a588be2aeede17fbaa44f754
745
py
Python
exastolog/test/test_toy3.py
sysbio-curie/pyExaStoLog
a8474823c1b5ef1642339b022675e0d60e340073
[ "BSD-3-Clause" ]
2
2020-11-17T15:00:01.000Z
2021-07-02T07:14:15.000Z
exastolog/test/test_toy3.py
sysbio-curie/pyExaStoLog
a8474823c1b5ef1642339b022675e0d60e340073
[ "BSD-3-Clause" ]
null
null
null
exastolog/test/test_toy3.py
sysbio-curie/pyExaStoLog
a8474823c1b5ef1642339b022675e0d60e340073
[ "BSD-3-Clause" ]
1
2020-07-07T13:36:44.000Z
2020-07-07T13:36:44.000Z
from unittest import TestCase from ..Model import Model from ..Simulation import Simulation from os.path import dirname, join import numpy as np import math class TestToy3(TestCase): def test_toy3(self): model = Model(join(dirname(__file__), "../../notebooks/model_files/toy3.bnet")) simulation = Simulation(model, ['A','B'], [0, 0]) result = simulation.get_last_states_probtraj() self.assertAlmostEqual(result.iloc[0, :].sum(), 1.0) self.assertAlmostEqual(result.loc[0, '<nil>'], 0.25) self.assertAlmostEqual(result.loc[0, 'A'], 0.25) self.assertAlmostEqual(result.loc[0, 'A'], 0.25) self.assertAlmostEqual(result.loc[0, 'A -- B'], 0.25)
33.863636
87
0.632215
95
745
4.863158
0.410526
0.227273
0.292208
0.25974
0.294372
0.227273
0.227273
0.227273
0.227273
0.227273
0
0.041237
0.218792
745
22
88
33.863636
0.752577
0
0
0.125
0
0
0.069705
0.049598
0
0
0
0
0.3125
1
0.0625
false
0
0.375
0
0.5
0
0
0
0
null
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
4
d931c71fea8c07e381405bd85803e56da95fcf53
755
py
Python
azulejo/test/key_binder.py
johnteslade/azulejo
3b1a35981360513b21f90d96afff10352b6363e6
[ "MIT" ]
3
2015-07-17T09:35:22.000Z
2015-11-15T00:13:32.000Z
azulejo/test/key_binder.py
johnteslade/azulejo
3b1a35981360513b21f90d96afff10352b6363e6
[ "MIT" ]
1
2015-07-17T09:36:45.000Z
2015-07-22T20:20:53.000Z
azulejo/test/key_binder.py
johnteslade/azulejo
3b1a35981360513b21f90d96afff10352b6363e6
[ "MIT" ]
null
null
null
class KeyBinderDummy(object): """Class used to allow keybindings to be caught and to be actioned.""" def __init__(self): self.bindings = [] self.saved_obj = None def bind(self, action, dispatcher, dispatcher_params): """ Bind a key press """ self.bindings.append({ 'action': action, 'dispatcher': dispatcher, 'dispatcher_params': dispatcher_params, }) def action_key(self, action): """ Actions a key press by calling the relavent dispatcher """ key_found = [x for x in self.bindings if x['action'] == action] assert len(key_found) == 1 func = key_found[0]['dispatcher'] func(key_found[0]['dispatcher_params'])
23.59375
74
0.593377
88
755
4.931818
0.465909
0.147465
0.119816
0.059908
0.105991
0
0
0
0
0
0
0.005597
0.290066
755
31
75
24.354839
0.804104
0.181457
0
0
0
0
0.111111
0
0
0
0
0
0.066667
1
0.2
false
0
0
0
0.266667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d93384ace79fad1a67f4aac86155075e4bc1666a
1,179
py
Python
code/at_offer/dynamic_programming/coding_interview47.py
zhangrong1722/interview
187a485de0774561eb843d8ee640236adda97b90
[ "Apache-2.0" ]
2
2020-01-05T07:46:20.000Z
2020-04-17T02:58:13.000Z
code/at_offer/dynamic_programming/coding_interview47.py
zhangrong1722/interview
187a485de0774561eb843d8ee640236adda97b90
[ "Apache-2.0" ]
1
2020-01-05T07:50:26.000Z
2020-04-28T03:50:08.000Z
code/at_offer/dynamic_programming/coding_interview47.py
zhangrong1722/interview
187a485de0774561eb843d8ee640236adda97b90
[ "Apache-2.0" ]
1
2020-04-18T03:58:26.000Z
2020-04-18T03:58:26.000Z
""" 题目:礼物的最大价值 在一个mxn的期盼的每一格都放有一个礼物 每个礼物有一定的价值(价值大于0) 你可以从棋盘的左上角开始拿格子里的礼物 并每次向右或者向下移动一格 直到达到棋盘的右下角 给定一个棋盘及其上面的礼物 请计算你最多能拿到多少价值的礼物 思路:动态规划 动态规划方程 dp[i][j]=max(dp[i-1][j],dp[i][j-1])+arr[i][j] """ class Solution: def GetGiftMaxValue(self, arr): if arr is None or len(arr) == 0: return 0 rows, cols = len(arr), len(arr[0]) results = [[0 for _ in range(cols)] for _ in range(rows)] for i in range(rows): for j in range(cols): try: results[i][j] = max(results[i - 1][j], results[i][j - 1]) + arr[i][j] except: try: results[i][j] = results[i - 1][j] + arr[i][j] except: try: results[i][j] = results[i][j - 1] + arr[i][j] except: pass return results[rows - 1][cols - 1] s = Solution() print(s.GetGiftMaxValue([[1, 10, 3, 8], [12, 2, 9, 6], [5, 7, 4, 11], [3, 7, 16, 5]])) print(s.GetGiftMaxValue(None)) print(s.GetGiftMaxValue([[1, 4, 2]])) print(s.GetGiftMaxValue([[1], [4], [2]]))
33.685714
89
0.47922
156
1,179
3.608974
0.346154
0.039076
0.079929
0.031972
0.25222
0.25222
0.152753
0.152753
0.152753
0.110124
0
0.051248
0.354538
1,179
34
90
34.676471
0.688568
0.167091
0
0.25
0
0
0
0
0
0
0
0
0
1
0.041667
false
0.041667
0
0
0.166667
0.166667
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d933e1e2f9d405d172ef31e50f4cff727e9bd7de
218
py
Python
doubanRequest.py
speedsnail99/PythonDouban
c4a556311632c547162589220433ec59a962a2d6
[ "MIT" ]
null
null
null
doubanRequest.py
speedsnail99/PythonDouban
c4a556311632c547162589220433ec59a962a2d6
[ "MIT" ]
null
null
null
doubanRequest.py
speedsnail99/PythonDouban
c4a556311632c547162589220433ec59a962a2d6
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : doubanRequest.py # @Author: G # @Date : 2018/8/5 import requests url = 'https://movie.douban.com' doubanText = requests.get(url).text print(doubanText)
12.111111
35
0.642202
30
218
4.666667
0.866667
0
0
0
0
0
0
0
0
0
0
0.038674
0.169725
218
17
36
12.823529
0.734807
0.444954
0
0
0
0
0.206897
0
0
0
0
0
0
1
0
false
0
0.25
0
0.25
0.25
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d934ab92936dea1622b31e73b9513677a43d6b45
31,876
py
Python
tests/shop/test_shop_views.py
Torniojaws/vortech-backend
f775a97eeae089fa720088d86fe92d40bc5d65bc
[ "MIT" ]
null
null
null
tests/shop/test_shop_views.py
Torniojaws/vortech-backend
f775a97eeae089fa720088d86fe92d40bc5d65bc
[ "MIT" ]
93
2017-09-01T22:24:10.000Z
2021-12-22T14:07:06.000Z
tests/shop/test_shop_views.py
Torniojaws/vortech-backend
f775a97eeae089fa720088d86fe92d40bc5d65bc
[ "MIT" ]
null
null
null
import json import unittest from flask_caching import Cache from app import app, db from apps.shop.models import ( ShopItems, ShopCategories, ShopItemsCategoriesMapping, ShopItemLogos, ShopItemsURLMapping ) from apps.users.models import Users, UsersAccessTokens, UsersAccessLevels, UsersAccessMapping from apps.utils.time import get_datetime, get_datetime_one_hour_ahead class TestShopViews(unittest.TestCase): def setUp(self): # Clear redis cache completely cache = Cache() cache.init_app(app, config={"CACHE_TYPE": "RedisCache"}) with app.app_context(): cache.clear() self.app = app.test_client() # Add some categories cat1 = ShopCategories( Category="Units", SubCategory="Tests" ) cat2 = ShopCategories( Category="UnitTests", SubCategory="TestsUnits" ) db.session.add(cat1) db.session.add(cat2) db.session.commit() self.valid_cats = [cat1.ShopCategoryID, cat2.ShopCategoryID] # And some 3rd party logos logo1 = ShopItemLogos( Image="unittest-spotify.jpg", Created=get_datetime() ) logo2 = ShopItemLogos( Image="unittest-bandcamp.jpg", Created=get_datetime() ) logo3 = ShopItemLogos( Image="unittest-amazon.jpg", Created=get_datetime() ) logo4 = ShopItemLogos( Image="unittest-deezer.jpg", Created=get_datetime() ) db.session.add(logo1) db.session.add(logo2) db.session.add(logo3) db.session.add(logo4) db.session.commit() self.valid_logo_ids = [ logo1.ShopItemLogoID, logo2.ShopItemLogoID, logo3.ShopItemLogoID, logo4.ShopItemLogoID, ] # Add three shop items and related data item1 = ShopItems( Title="UnitTest ShopItem 1", Description="UnitTest This is item 1", Price=15.99, Currency="EUR", Image="unittest-shopitem1.jpg", Created=get_datetime() ) db.session.add(item1) db.session.commit() self.valid_items = [item1.ShopItemID] item1_cat1 = ShopItemsCategoriesMapping( ShopItemID=self.valid_items[0], ShopCategoryID=self.valid_cats[0] ) item1_cat2 = ShopItemsCategoriesMapping( ShopItemID=self.valid_items[0], ShopCategoryID=self.valid_cats[1] ) db.session.add(item1_cat1) db.session.add(item1_cat2) db.session.commit() item1_url1 = ShopItemsURLMapping( ShopItemID=self.valid_items[0], URLTitle="Spotify", URL="http://www.example.com/spotify", ShopItemLogoID=self.valid_logo_ids[0] ) item1_url2 = ShopItemsURLMapping( ShopItemID=self.valid_items[0], URLTitle="BandCamp", URL="http://www.example.com/bandcamp", ShopItemLogoID=self.valid_logo_ids[1] ) db.session.add(item1_url1) db.session.add(item1_url2) db.session.commit() # Item 2 item2 = ShopItems( Title="UnitTest ShopItem 2", Description="UnitTest This is item 2", Price=8.49, Currency="EUR", Image="unittest-shopitem2.jpg", Created=get_datetime() ) db.session.add(item2) db.session.commit() self.valid_items.append(item2.ShopItemID) item2_cat1 = ShopItemsCategoriesMapping( ShopItemID=self.valid_items[1], ShopCategoryID=self.valid_cats[0] ) db.session.add(item2_cat1) db.session.commit() item2_url1 = ShopItemsURLMapping( ShopItemID=self.valid_items[1], URLTitle="Spotify", URL="http://www.example.com/spotify", ShopItemLogoID=self.valid_logo_ids[0] ) item2_url2 = ShopItemsURLMapping( ShopItemID=self.valid_items[1], URLTitle="BandCamp", URL="http://www.example.com/bandcamp", ShopItemLogoID=self.valid_logo_ids[1] ) db.session.add(item2_url1) db.session.add(item2_url2) db.session.commit() # Item 3 item3 = ShopItems( Title="UnitTest ShopItem 3", Description="UnitTest This is item 3", Price=12, Currency="EUR", Image="unittest-shopitem3.jpg", Created=get_datetime() ) db.session.add(item3) db.session.commit() self.valid_items.append(item3.ShopItemID) item3_cat1 = ShopItemsCategoriesMapping( ShopItemID=self.valid_items[2], ShopCategoryID=self.valid_cats[0] ) item3_cat2 = ShopItemsCategoriesMapping( ShopItemID=self.valid_items[2], ShopCategoryID=self.valid_cats[1] ) db.session.add(item3_cat1) db.session.add(item3_cat2) db.session.commit() item3_url1 = ShopItemsURLMapping( ShopItemID=self.valid_items[2], URLTitle="Spotify", URL="http://www.example.com/spotify", ShopItemLogoID=self.valid_logo_ids[0] ) item3_url2 = ShopItemsURLMapping( ShopItemID=self.valid_items[2], URLTitle="BandCamp", URL="http://www.example.com/bandcamp", ShopItemLogoID=self.valid_logo_ids[1] ) db.session.add(item3_url1) db.session.add(item3_url2) db.session.commit() # We also need a valid admin user for the add release endpoint test. user = Users( Name="UnitTest Admin", Username="unittest", Password="password" ) db.session.add(user) db.session.commit() # This is non-standard, but is fine for testing. self.access_token = "unittest-access-token" user_token = UsersAccessTokens( UserID=user.UserID, AccessToken=self.access_token, ExpirationDate=get_datetime_one_hour_ahead() ) db.session.add(user_token) db.session.commit() # Define level for admin if not UsersAccessLevels.query.filter_by(LevelName="Admin").first(): access_level = UsersAccessLevels( UsersAccessLevelID=4, LevelName="Admin" ) db.session.add(access_level) db.session.commit() grant_admin = UsersAccessMapping( UserID=user.UserID, UsersAccessLevelID=4 ) db.session.add(grant_admin) db.session.commit() self.user_id = user.UserID def tearDown(self): for cat in ShopCategories.query.filter(ShopCategories.Category.like("Unit%")).all(): db.session.delete(cat) for logo in ShopItemLogos.query.filter(ShopItemLogos.Image.like("unittest%")).all(): db.session.delete(logo) for item in ShopItems.query.filter(ShopItems.Title.like("UnitTest%")).all(): db.session.delete(item) db.session.commit() user = Users.query.filter_by(UserID=self.user_id).first() db.session.delete(user) db.session.commit() def test_getting_all_shopitems(self): """This should return all the shopitems along with their associated data, in ascending order, ID=1 first.""" response = self.app.get("/api/1.0/shopitems/") data = json.loads(response.data.decode()) self.assertEqual(200, response.status_code) self.assertEqual(3, len(data["shopItems"])) self.assertEqual("UnitTest ShopItem 1", data["shopItems"][0]["title"]) self.assertEqual("UnitTest This is item 1", data["shopItems"][0]["description"]) self.assertEqual(15.99, data["shopItems"][0]["price"]) self.assertEqual("EUR", data["shopItems"][0]["currency"]) self.assertEqual("unittest-shopitem1.jpg", data["shopItems"][0]["image"]) self.assertNotEqual("", data["shopItems"][0]["createdAt"]) self.assertTrue("updatedAt" in data["shopItems"][0]) self.assertEqual( [self.valid_cats[0], self.valid_cats[1]], data["shopItems"][0]["categories"] ) self.assertEqual(2, len(data["shopItems"][0]["urls"])) self.assertEqual("Spotify", data["shopItems"][0]["urls"][0]["urlTitle"]) self.assertEqual( "http://www.example.com/spotify", data["shopItems"][0]["urls"][0]["url"] ) self.assertEqual(self.valid_logo_ids[0], data["shopItems"][0]["urls"][0]["logoID"]) def test_getting_specific_shopitem(self): """Should return the data of the specified shopitem.""" response = self.app.get("/api/1.0/shopitems/{}".format(self.valid_items[2])) data = json.loads(response.data.decode()) self.assertEqual(200, response.status_code) self.assertEqual(1, len(data["shopItems"])) self.assertEqual("UnitTest ShopItem 3", data["shopItems"][0]["title"]) self.assertEqual("UnitTest This is item 3", data["shopItems"][0]["description"]) self.assertEqual(12, data["shopItems"][0]["price"]) self.assertEqual("EUR", data["shopItems"][0]["currency"]) self.assertEqual("unittest-shopitem3.jpg", data["shopItems"][0]["image"]) self.assertNotEqual("", data["shopItems"][0]["createdAt"]) self.assertTrue("updatedAt" in data["shopItems"][0]) self.assertEqual( [self.valid_cats[0], self.valid_cats[1]], data["shopItems"][0]["categories"] ) self.assertEqual(2, len(data["shopItems"][0]["urls"])) self.assertEqual("Spotify", data["shopItems"][0]["urls"][0]["urlTitle"]) self.assertEqual( "http://www.example.com/spotify", data["shopItems"][0]["urls"][0]["url"] ) self.assertEqual(self.valid_logo_ids[0], data["shopItems"][0]["urls"][0]["logoID"]) self.assertEqual("BandCamp", data["shopItems"][0]["urls"][1]["urlTitle"]) self.assertEqual( "http://www.example.com/bandcamp", data["shopItems"][0]["urls"][1]["url"] ) self.assertEqual(self.valid_logo_ids[1], data["shopItems"][0]["urls"][1]["logoID"]) def test_getting_shopitems_by_category(self): """Should return all items that match the subcategory.""" response = self.app.get("/api/1.0/shopitems/category/{}/".format(self.valid_cats[1])) data = json.loads(response.data.decode()) self.assertEqual(200, response.status_code) self.assertNotEqual(None, data) self.assertEqual(2, len(data["shopItems"])) self.assertEqual("UnitTest ShopItem 1", data["shopItems"][0]["title"]) self.assertEqual("UnitTest ShopItem 3", data["shopItems"][1]["title"]) def test_adding_shopitem(self): """Should add the new item and its related data (categories and urls). For URLs, there is no valid case to reference any existing URLs in the database, so they will be added every time. However, we can reuse a logo (eg. Spotify), so basically you can pick a logo in the UI and then the POST data will have an ID.""" response = self.app.post( "/api/1.0/shopitems/", data=json.dumps( dict( title="UnitTest Post", description="UnitTest Description", price=14.95, currency="EUR", image="unittest-post.jpg", categories=[ self.valid_cats[0], {"category": "UnitTests", "subcategory": "UnitTest New Subcategory"} ], urls=[ { "title": "Spotify", "url": "http://www.example.com/spotify/1", "logoID": self.valid_logo_ids[0] }, { "title": "Amazon", "url": "http://www.example.com/amazon/123", "logoID": self.valid_logo_ids[2] }, ] ) ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) data = response.data.decode() item = ShopItems.query.filter_by(Title="UnitTest Post").first_or_404() cats = ShopItemsCategoriesMapping.query.filter_by(ShopItemID=item.ShopItemID).all() urls = ShopItemsURLMapping.query.filter_by(ShopItemID=item.ShopItemID).all() new_cat = ShopCategories.query.filter_by( SubCategory="UnitTest New Subcategory").first() self.assertEqual(201, response.status_code) self.assertTrue("Location" in data) self.assertNotEqual(None, item) self.assertNotEqual(None, cats) self.assertNotEqual(None, urls) self.assertEqual("UnitTest Post", item.Title) self.assertEqual("UnitTest Description", item.Description) self.assertEqual(14.95, float(item.Price)) self.assertEqual("EUR", item.Currency) self.assertEqual("unittest-post.jpg", item.Image) self.assertEqual(2, len(cats)) self.assertEqual("UnitTests", new_cat.Category) self.assertEqual("UnitTest New Subcategory", new_cat.SubCategory) self.assertEqual(2, len(urls)) # These appear in insert order. Sorting by title would be a lot of work for little benefit self.assertEqual("Spotify", urls[0].URLTitle) self.assertEqual("http://www.example.com/spotify/1", urls[0].URL) self.assertEqual("Amazon", urls[1].URLTitle) self.assertEqual("http://www.example.com/amazon/123", urls[1].URL) def test_updating_shop_item(self): """Should replace all existing values with the new updated values.""" response = self.app.put( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( dict( title="UnitTest Updated Title", description="UnitTest Updated Description", price=11.95, currency="EUR", image="unittest-update.jpg", categories=[ self.valid_cats[0], self.valid_cats[1], {"category": "UnitTests", "subcategory": "UnitTest New Subcategory"} ], urls=[ { "title": "Spotify", "url": "http://www.example.com/spotify/2", "logoID": self.valid_logo_ids[0] }, { "title": "Amazon MP3", "url": "http://www.example.com/amazon/124", "logoID": self.valid_logo_ids[2] }, { "title": "BandCamp", "url": "http://www.example.com/bandcamp/987", "logoID": self.valid_logo_ids[2] }, ] ) ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) self.assertEqual(200, response.status_code) self.assertEqual("", response.data.decode()) item = ShopItems.query.filter_by(ShopItemID=self.valid_items[1]).first_or_404() cats = ShopItemsCategoriesMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() urls = ShopItemsURLMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() new_cat = ShopCategories.query.filter_by( SubCategory="UnitTest New Subcategory").first() self.assertNotEqual(None, item) self.assertNotEqual(None, cats) self.assertNotEqual(None, urls) self.assertEqual("UnitTest Updated Title", item.Title) self.assertEqual("UnitTest Updated Description", item.Description) self.assertEqual(11.95, float(item.Price)) self.assertEqual("EUR", item.Currency) self.assertEqual("unittest-update.jpg", item.Image) self.assertNotEqual("", item.Updated) self.assertEqual(3, len(cats)) self.assertEqual("UnitTests", new_cat.Category) self.assertEqual("UnitTest New Subcategory", new_cat.SubCategory) self.assertEqual(3, len(urls)) # These appear in insert order. Sorting by title would be a lot of work for little benefit self.assertEqual("Spotify", urls[0].URLTitle) self.assertEqual("http://www.example.com/spotify/2", urls[0].URL) self.assertEqual("Amazon MP3", urls[1].URLTitle) self.assertEqual("http://www.example.com/amazon/124", urls[1].URL) self.assertEqual("BandCamp", urls[2].URLTitle) self.assertEqual("http://www.example.com/bandcamp/987", urls[2].URL) def test_patching_shopitem_add(self): """Patch a ShopItems entry with "add" operation.""" response = self.app.patch( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( [ dict({ "op": "add", "path": "/title", "value": "UnitTest Patched Title" }), dict({ "op": "add", "path": "/categories", "value": [self.valid_cats[1]] }), dict({ "op": "add", "path": "/urls", "value": [ { "title": "Deezer", "url": "deezer.com", "logoID": self.valid_logo_ids[3] } ] }), ] ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) item = ShopItems.query.filter_by(ShopItemID=self.valid_items[1]).first_or_404() cats = ShopItemsCategoriesMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() urls = ShopItemsURLMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() self.assertEqual(204, response.status_code) self.assertEqual("", response.data.decode()) self.assertEqual("UnitTest Patched Title", item.Title) self.assertEqual(2, len(cats)) self.assertEqual(3, len(urls)) self.assertEqual("Deezer", urls[2].URLTitle) self.assertEqual("deezer.com", urls[2].URL) def test_patching_shopitem_copy(self): """Patch a ShopItems entry with "copy" operation. There is no possible copy operation for categories and urls. Trying to do it would throw JsonPatchConflict since you can only copy to the same resource, ie. on top of itself.""" response = self.app.patch( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( [ dict({ "op": "copy", "from": "/title", "path": "/description" }) ] ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) item = ShopItems.query.filter_by(ShopItemID=self.valid_items[1]).first_or_404() self.assertEqual(204, response.status_code) self.assertEqual("", response.data.decode()) self.assertEqual("UnitTest ShopItem 2", item.Description) def test_patching_shopitem_move(self): """Patch a ShopItems entry with "move" operation. Move will by definition empty the source resource and populate the target resource with the value from source. However, this does not currently work yet due to SQLAlchemy and JSONPatch incompatibility. Just the value is replaced. The correct behaviour will be implemented later on.""" response = self.app.patch( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( [ dict({ "op": "move", "from": "/description", "path": "/image" }) ] ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) item = ShopItems.query.filter_by(ShopItemID=self.valid_items[1]).first_or_404() self.assertEqual(204, response.status_code) self.assertEqual("", response.data.decode()) self.assertEqual("UnitTest This is item 2", item.Image) def test_patching_shopitem_remove(self): """Patch a ShopItems entry with "remove" operation. This does not work for the base object due to SQLAlchemy JSONPatch incompatibility. But it does work for the joined tables URLs and categories.""" response = self.app.patch( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( [ dict({ "op": "remove", "path": "/title" }), dict({ "op": "remove", "path": "/categories" }), dict({ "op": "remove", "path": "/urls" }) ] ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) cats = ShopItemsCategoriesMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() urls = ShopItemsURLMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() self.assertEqual(204, response.status_code) self.assertEqual("", response.data.decode()) self.assertEqual([], cats) self.assertEqual([], urls) def test_patching_shopitem_replace(self): """Patch a ShopItems entry with "replace" operation.""" response = self.app.patch( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( [ dict({ "op": "replace", "path": "/title", "value": "UnitTest Patched Title" }), dict({ "op": "replace", "path": "/categories", "value": [self.valid_cats[1]] }), dict({ "op": "replace", "path": "/urls", "value": [ { "title": "Deezer", "url": "deezer.com", "logoID": self.valid_logo_ids[3] } ] }), ] ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) item = ShopItems.query.filter_by(ShopItemID=self.valid_items[1]).first_or_404() cats = ShopItemsCategoriesMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() urls = ShopItemsURLMapping.query.filter_by(ShopItemID=self.valid_items[1]).all() self.assertEqual(204, response.status_code) self.assertEqual("", response.data.decode()) self.assertEqual("UnitTest Patched Title", item.Title) self.assertEqual(1, len(cats)) self.assertEqual(1, len(urls)) self.assertEqual("Deezer", urls[0].URLTitle) self.assertEqual("deezer.com", urls[0].URL) def test_deleting_shop_item(self): """Should delete the specified shop item and it's mappings.""" response = self.app.delete( "/api/1.0/shopitems/{}".format(self.valid_items[2]), headers={ 'User': self.user_id, 'Authorization': self.access_token } ) cats = ShopItemsCategoriesMapping.query.filter_by(ShopItemID=self.valid_items[2]).all() urls = ShopItemsURLMapping.query.filter_by(ShopItemID=self.valid_items[2]).all() self.assertEqual(204, response.status_code) self.assertEqual("", response.data.decode()) self.assertEqual([], cats) self.assertEqual([], urls) def test_invalid_category_id(self): """When an invalid category ID is given, it should be skipped.""" response = self.app.post( "/api/1.0/shopitems/", data=json.dumps( dict( title="UnitTest Post", description="UnitTest Description", price=14.95, currency="EUR", image="unittest-post.jpg", categories=[0], urls=[ { "title": "Spotify", "url": "http://www.example.com/spotify/1", "logoID": self.valid_logo_ids[0] } ] ) ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) data = response.data.decode() item = ShopItems.query.filter_by(Title="UnitTest Post").first_or_404() cats = ShopItemsCategoriesMapping.query.filter_by(ShopItemID=item.ShopItemID).all() self.assertEqual(201, response.status_code) self.assertTrue("Location" in data) self.assertEqual([], cats) def test_existing_string_category(self): """Should use the existing category and not create a new entry to ShopCategories.""" response = self.app.post( "/api/1.0/shopitems/", data=json.dumps( dict( title="UnitTest Post", description="UnitTest Description", price=14.95, currency="EUR", image="unittest-post.jpg", categories=[ { "category": "UnitTests", "subcategory": "TestsUnits" } ], urls=[ { "title": "Spotify", "url": "http://www.example.com/spotify/1", "logoID": self.valid_logo_ids[0] } ] ) ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) data = response.data.decode() item = ShopItems.query.filter_by(Title="UnitTest Post").first_or_404() cats = ShopItemsCategoriesMapping.query.filter_by(ShopItemID=item.ShopItemID).all() category_entries = ShopCategories.query.filter_by(Category="UnitTests").all() self.assertEqual(201, response.status_code) self.assertTrue("Location" in data) self.assertEqual(1, len(cats)) # Should only have one entry for the given values. self.assertEqual(1, len(category_entries)) def test_patching_categories(self): """Patch ShopItems categories with "copy" and "move" operations. There is no possible operation for categories and urls. Trying to do it would throw JsonPatchConflict since you can only copy to the same resource, ie. on top of itself.""" response = self.app.patch( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( [ dict({ "op": "copy", "from": "/categories", "path": "/categories" }), dict({ "op": "move", "from": "/categories", "path": "/categories" }) ] ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) self.assertEqual(204, response.status_code) self.assertEqual("", response.data.decode()) def test_patching_urls(self): """Patch ShopItems urls with "copy" and "move" operations. There is no possible operation for categories and urls. Trying to do it would throw JsonPatchConflict since you can only copy to the same resource, ie. on top of itself.""" response = self.app.patch( "/api/1.0/shopitems/{}".format(self.valid_items[1]), data=json.dumps( [ dict({ "op": "copy", "from": "/urls", "path": "/urls" }), dict({ "op": "move", "from": "/urls", "path": "/urls" }) ] ), content_type="application/json", headers={ 'User': self.user_id, 'Authorization': self.access_token } ) self.assertEqual(204, response.status_code) self.assertEqual("", response.data.decode())
39.159705
99
0.513019
3,020
31,876
5.318874
0.103311
0.092448
0.033991
0.038847
0.704787
0.670983
0.621428
0.573679
0.550582
0.538442
0
0.019738
0.369024
31,876
813
100
39.207872
0.778899
0.080405
0
0.558952
0
0
0.141731
0.01389
0
0
0
0
0.165939
1
0.024745
false
0.001456
0.010189
0
0.03639
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d935132553f2baab50f6ba2b6d58b4003ca7df5b
3,728
py
Python
pyinsar/data_import/uavsar.py
MITeaps/pyinsar
4d22e3ef90ef842d6b390074a8b5deedc7658a2b
[ "MIT" ]
8
2019-03-15T19:51:27.000Z
2022-02-16T07:27:36.000Z
pyinsar/data_import/uavsar.py
MITeaps/pyinsar
4d22e3ef90ef842d6b390074a8b5deedc7658a2b
[ "MIT" ]
1
2022-02-08T03:48:56.000Z
2022-02-09T01:33:27.000Z
pyinsar/data_import/uavsar.py
MITeaps/pyinsar
4d22e3ef90ef842d6b390074a8b5deedc7658a2b
[ "MIT" ]
2
2021-01-12T05:32:21.000Z
2021-01-13T08:35:26.000Z
# The MIT License (MIT) # Copyright (c) 2017 Massachusetts Institute of Technology # # Author: Cody Rude # This software has been created in projects supported by the US National # Science Foundation and NASA (PI: Pankratius) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import re from collections import OrderedDict def read_uavsar_metadata(in_file): ''' Parse UAVSAR metadata @param in_file: String of Metadata filename or file object (file should end in .ann) @return OrderedDict of metadata ''' if isinstance(in_file, str): with open(in_file, 'r') as info_file: data_info = info_file.readlines() else: data_info = [line.decode() for line in in_file.readlines()] data_info = [line.strip() for line in data_info] # Function to convert string to a number def str_to_number(in_string): try: return int(in_string) except: return float(in_string) data_name = data_info[0][31:] meta_data_dict = OrderedDict() for line in data_info: # Only work on lines that aren't commented out if re.match('^[^;]',line) != None: # Get the data type ('&' is text) data_type = re.search('\s+\((.*)\)\s+=', line).group(1) # Remove data type from line tmp = re.sub('\s+\(.*\)\s+=', ' =', line) # Split line into key,value split_list = tmp.split('=',maxsplit=1) # remove any trailing comments and strip whitespace split_list[1] = re.search('[^;]*',split_list[1]).group().strip() split_list[0] = split_list[0].strip() #If data type is not a string, parse it as a float or int if data_type != '&': # Check if value is N/A if split_list[1] == 'N/A': split_list[1] = float('nan') # Check for Raskew Doppler Near Mid Far as this # entry should be three seperate entries elif split_list[0] == 'Reskew Doppler Near Mid Far': split_list[0] = 'Reskew Doppler Near' second_split = split_list[1].split() split_list[1] = str_to_number(second_split[0]) meta_data_dict['Reskew Doppler Mid'] = str_to_number(second_split[1]) meta_data_dict['Reskew Doppler Far'] = str_to_number(second_split[2]) # Parse value to an int or float else: split_list[1] = str_to_number(split_list[1]) # Add key, value pair to dictionary meta_data_dict[split_list[0]] = split_list[1] return meta_data_dict
36.54902
89
0.635193
519
3,728
4.447013
0.39499
0.058492
0.038995
0.022097
0.118284
0.041594
0
0
0
0
0
0.009648
0.277092
3,728
101
90
36.910891
0.846753
0.489002
0
0.055556
0
0
0.070926
0
0
0
0
0
0
1
0.055556
false
0
0.055556
0
0.194444
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d936d9d6566232424e349431594f08f1e023591e
1,964
py
Python
api/utils/responses.py
cakedan/files.gg
6d8fc06376a69809c0ae0a56ea2a842d6caddb98
[ "MIT" ]
8
2018-05-03T16:28:30.000Z
2020-02-02T12:22:36.000Z
api/utils/responses.py
cakedan/files.gg
6d8fc06376a69809c0ae0a56ea2a842d6caddb98
[ "MIT" ]
null
null
null
api/utils/responses.py
cakedan/files.gg
6d8fc06376a69809c0ae0a56ea2a842d6caddb98
[ "MIT" ]
1
2019-03-20T23:39:25.000Z
2019-03-20T23:39:25.000Z
import json from urllib.parse import urlencode from flask import Response from werkzeug.http import HTTP_STATUS_CODES class ApiResponse(Response): default_status = 200 default_mimetype = 'application/json' def __init__(self, data=None, status=None, **kwargs): if data is None: if kwargs.get('response') is None: status = 204 else: if hasattr(data, 'to_dict'): data = data.to_dict() kwargs['response'] = json.dumps(data) if status is not None: kwargs['status'] = status super(Response, self).__init__(**kwargs) class ApiRedirect(ApiResponse): default_status = 302 def __init__(self, url, query=None, *args, **kwargs): super(ApiResponse, self).__init__(None, *args, **kwargs) if not (300 < self.status_code and self.status_code < 400): raise ValueError('Invalid Status Code, Redirects should be equal to or between 300 and 399') if query: if '?' in url: url += '&' + urlencode(query) else: url += '?' + urlencode(query) self.headers.add('location', url) class ApiError(Exception): code = 0 message = None status = 400 def __init__(self, message=None, status=None, *args, **kwargs): super(Exception, self).__init__() if status is not None: self.status = status if message is not None: self.message = message elif self.message is None: self.message = HTTP_STATUS_CODES.get(self.status, 'Unknown Error') if kwargs.get('code') is not None: self.code = kwargs.get('code') kwargs['data'] = kwargs.pop('metadata', None) or {} kwargs['data'].update({'code': self.code, 'message': self.message, 'status': self.status}) kwargs['status'] = self.status self.response = ApiResponse(**kwargs)
28.882353
104
0.59165
232
1,964
4.857759
0.293103
0.053239
0.031943
0.034605
0.030169
0
0
0
0
0
0
0.01796
0.291242
1,964
67
105
29.313433
0.791667
0
0
0.083333
0
0
0.095723
0
0
0
0
0
0
1
0.0625
false
0
0.083333
0
0.333333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d937931645a0b4ee10a45ea07357635f954a0273
16,675
py
Python
example/samgraph/multi_gpu/train_gcn.py
SJTU-IPADS/fgnn-artifacts
c96e7ec8204d767152958dc63a764466e90424fd
[ "Apache-2.0" ]
23
2022-01-25T13:28:51.000Z
2022-03-23T07:05:47.000Z
example/samgraph/multi_gpu/train_gcn.py
SJTU-IPADS/gnnlab
5c73564e4a9bd5deeff7eed0b923c115ccba34d7
[ "Apache-2.0" ]
null
null
null
example/samgraph/multi_gpu/train_gcn.py
SJTU-IPADS/gnnlab
5c73564e4a9bd5deeff7eed0b923c115ccba34d7
[ "Apache-2.0" ]
1
2022-02-28T18:48:56.000Z
2022-02-28T18:48:56.000Z
import argparse import time import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np from dgl.nn.pytorch import GraphConv import dgl.multiprocessing as mp from torch.nn.parallel import DistributedDataParallel import os import sys import samgraph.torch as sam import datetime from common_config import * class GCN(nn.Module): def __init__(self, in_feats, n_hidden, n_classes, n_layers, activation, dropout): super(GCN, self).__init__() self.layers = nn.ModuleList() # input layer self.layers.append( GraphConv(in_feats, n_hidden, activation=activation, allow_zero_in_degree=True)) # hidden layers for _ in range(n_layers - 2): self.layers.append( GraphConv(n_hidden, n_hidden, activation=activation, allow_zero_in_degree=True)) # output layer self.layers.append( GraphConv(n_hidden, n_classes, allow_zero_in_degree=True)) self.dropout = nn.Dropout(p=dropout) def forward(self, blocks, features): h = features for i, layer in enumerate(self.layers): if i != 0: h = self.dropout(h) h = layer(blocks[i], h) return h def parse_args(default_run_config): argparser = argparse.ArgumentParser("GCN Training") add_common_arguments(argparser, default_run_config) argparser.add_argument('--fanout', nargs='+', type=int, default=default_run_config['fanout']) argparser.add_argument('--lr', type=float, default=default_run_config['lr']) argparser.add_argument('--dropout', type=float, default=default_run_config['dropout']) argparser.add_argument('--weight-decay', type=float, default=default_run_config['weight_decay']) return vars(argparser.parse_args()) def get_run_config(): run_config = {} run_config.update(get_default_common_config(run_mode=RunMode.FGNN)) run_config['sample_type'] = 'khop2' run_config['fanout'] = [5, 10, 15] run_config['lr'] = 0.003 run_config['dropout'] = 0.5 run_config['weight_decay'] = 0.0005 run_config.update(parse_args(run_config)) process_common_config(run_config) assert(run_config['arch'] == 'arch5') assert(run_config['sample_type'] != 'random_walk') run_config['num_fanout'] = run_config['num_layer'] = len( run_config['fanout']) print_run_config(run_config) return run_config def run_init(run_config): sam.config(run_config) sam.data_init() if run_config['validate_configs']: sys.exit() def run_sample(worker_id, run_config): num_worker = run_config['num_sample_worker'] global_barrier = run_config['global_barrier'] ctx = run_config['sample_workers'][worker_id] print('[Sample Worker {:d}/{:d}] Started with PID {:d}({:s})'.format( worker_id, num_worker, os.getpid(), torch.cuda.get_device_name(ctx))) sam.sample_init(worker_id, ctx) sam.notify_sampler_ready(global_barrier) num_epoch = sam.num_epoch() num_step = sam.steps_per_epoch() if (worker_id == (num_worker - 1)): num_step = int(num_step - int(num_step / num_worker) * worker_id) else: num_step = int(num_step / num_worker) epoch_sample_total_times_python = [] epoch_pipeline_sample_total_times_python = [] epoch_sample_total_times_profiler = [] epoch_sample_times = [] epoch_get_cache_miss_index_times = [] epoch_enqueue_samples_times = [] print('[Sample Worker {:d}] run sample for {:d} epochs with {:d} steps'.format( worker_id, num_epoch, num_step)) # run start barrier global_barrier.wait() for epoch in range(num_epoch): if run_config['pipeline']: # epoch start barrier 1 global_barrier.wait() tic = time.time() for step in range(num_step): sam.sample_once() # sam.report_step(epoch, step) toc0 = time.time() if not run_config['pipeline']: # epoch start barrier 2 global_barrier.wait() # epoch end barrier global_barrier.wait() toc1 = time.time() epoch_sample_total_times_python.append(toc0 - tic) epoch_pipeline_sample_total_times_python.append(toc1 - tic) epoch_sample_times.append( sam.get_log_epoch_value(epoch, sam.kLogEpochSampleTime)) epoch_get_cache_miss_index_times.append( sam.get_log_epoch_value( epoch, sam.KLogEpochSampleGetCacheMissIndexTime) ) epoch_enqueue_samples_times.append( sam.get_log_epoch_value(epoch, sam.kLogEpochSampleSendTime) ) epoch_sample_total_times_profiler.append( sam.get_log_epoch_value(epoch, sam.kLogEpochSampleTotalTime) ) if worker_id == 0: sam.report_step_average(epoch - 1, step - 1) print('[Sample Worker {:d}] Avg Sample Total Time {:.4f} | Sampler Total Time(Profiler) {:.4f}'.format( worker_id, np.mean(epoch_sample_total_times_python[1:]), np.mean(epoch_sample_total_times_profiler[1:]))) # run end barrier global_barrier.wait() if worker_id == 0: sam.report_init() if worker_id == 0: test_result = [] test_result.append(('sample_time', np.mean(epoch_sample_times[1:]))) test_result.append(('get_cache_miss_index_time', np.mean( epoch_get_cache_miss_index_times[1:]))) test_result.append( ('enqueue_samples_time', np.mean(epoch_enqueue_samples_times[1:]))) test_result.append(('epoch_time:sample_total', np.mean( epoch_sample_total_times_python[1:]))) if run_config['pipeline']: test_result.append( ('pipeline_sample_epoch_time', np.mean(epoch_pipeline_sample_total_times_python[1:]))) test_result.append(('init:presample', sam.get_log_init_value(sam.kLogInitL2Presample))) test_result.append(('init:load_dataset:mmap', sam.get_log_init_value(sam.kLogInitL3LoadDatasetMMap))) test_result.append(('init:load_dataset:copy:sampler', sam.get_log_init_value(sam.kLogInitL3LoadDatasetCopy))) test_result.append(('init:dist_queue:alloc+push', sam.get_log_init_value(sam.kLogInitL3DistQueueAlloc)+sam.get_log_init_value(sam.kLogInitL3DistQueuePush))) test_result.append(('init:dist_queue:pin:sampler', sam.get_log_init_value(sam.kLogInitL3DistQueuePin))) test_result.append(('init:internal:sampler', sam.get_log_init_value(sam.kLogInitL2InternalState))) test_result.append(('init:cache:sampler', sam.get_log_init_value(sam.kLogInitL2BuildCache))) for k, v in test_result: print('test_result:{:}={:.2f}'.format(k, v)) global_barrier.wait() # barrier for pretty print # trainer print result sam.shutdown() def run_train(worker_id, run_config): ctx = run_config['train_workers'][worker_id] num_worker = run_config['num_train_worker'] global_barrier = run_config['global_barrier'] train_device = torch.device(ctx) print('[Train Worker {:d}/{:d}] Started with PID {:d}({:s})'.format( worker_id, num_worker, os.getpid(), torch.cuda.get_device_name(ctx))) # let the trainer initialization after sampler # sampler should presample before trainer initialization sam.wait_for_sampler_ready(global_barrier) sam.train_init(worker_id, ctx) if num_worker > 1: dist_init_method = 'tcp://{master_ip}:{master_port}'.format( master_ip='127.0.0.1', master_port='12345') world_size = num_worker torch.distributed.init_process_group(backend="nccl", init_method=dist_init_method, world_size=world_size, rank=worker_id, timeout=datetime.timedelta(seconds=get_default_timeout())) in_feat = sam.feat_dim() num_class = sam.num_class() num_layer = run_config['num_layer'] model = GCN(in_feat, run_config['num_hidden'], num_class, num_layer, F.relu, run_config['dropout']) model = model.to(train_device) if num_worker > 1: model = DistributedDataParallel( model, device_ids=[train_device], output_device=train_device) loss_fcn = nn.CrossEntropyLoss() loss_fcn = loss_fcn.to(train_device) optimizer = optim.Adam( model.parameters(), lr=run_config['lr'], weight_decay=run_config['weight_decay']) num_epoch = sam.num_epoch() num_step = sam.steps_per_epoch() model.train() epoch_copy_times = [] epoch_convert_times = [] epoch_train_times = [] epoch_total_times_python = [] epoch_train_total_times_profiler = [] epoch_pipeline_train_total_times_python = [] epoch_cache_hit_rates = [] epoch_miss_nbytes = [] epoch_feat_nbytes = [] copy_times = [] convert_times = [] train_times = [] total_times = [] align_up_step = int( int((num_step + num_worker - 1) / num_worker) * num_worker) # run start barrier global_barrier.wait() print('[Train Worker {:d}] run train for {:d} epochs with {:d} steps'.format( worker_id, num_epoch, num_step)) run_start = time.time() for epoch in range(num_epoch): # epoch start barrier global_barrier.wait() tic = time.time() if run_config['pipeline'] or run_config['single_gpu']: need_steps = int(num_step / num_worker) if worker_id < num_step % num_worker: need_steps += 1 sam.extract_start(need_steps) for step in range(worker_id, align_up_step, num_worker): if step < num_step: t0 = time.time() if (not run_config['pipeline']) and (not run_config['single_gpu']): sam.sample_once() batch_key = sam.get_next_batch() t1 = time.time() blocks, batch_input, batch_label = sam.get_dgl_blocks( batch_key, num_layer) t2 = time.time() else: t0 = t1 = t2 = time.time() # Compute loss and prediction batch_pred = model(blocks, batch_input) loss = loss_fcn(batch_pred, batch_label) optimizer.zero_grad() loss.backward() optimizer.step() # wait for the train finish then we can free the data safely event_sync() if (step + num_worker < num_step): batch_input = None batch_label = None blocks = None t3 = time.time() copy_time = sam.get_log_step_value(epoch, step, sam.kLogL1CopyTime) convert_time = t2 - t1 train_time = t3 - t2 total_time = t3 - t1 sam.log_step(epoch, step, sam.kLogL1TrainTime, train_time) sam.log_step(epoch, step, sam.kLogL1ConvertTime, convert_time) sam.log_epoch_add(epoch, sam.kLogEpochConvertTime, convert_time) sam.log_epoch_add(epoch, sam.kLogEpochTrainTime, train_time) sam.log_epoch_add(epoch, sam.kLogEpochTotalTime, total_time) copy_times.append(copy_time) convert_times.append(convert_time) train_times.append(train_time) total_times.append(total_time) # sam.report_step_average(epoch, step) # sync the train workers if num_worker > 1: torch.distributed.barrier() toc = time.time() epoch_total_times_python.append(toc - tic) # epoch end barrier global_barrier.wait() feat_nbytes = sam.get_log_epoch_value( epoch, sam.kLogEpochFeatureBytes) miss_nbytes = sam.get_log_epoch_value( epoch, sam.kLogEpochMissBytes) epoch_miss_nbytes.append(miss_nbytes) epoch_feat_nbytes.append(feat_nbytes) epoch_cache_hit_rates.append( (feat_nbytes - miss_nbytes) / feat_nbytes) epoch_copy_times.append( sam.get_log_epoch_value(epoch, sam.kLogEpochCopyTime)) epoch_convert_times.append( sam.get_log_epoch_value(epoch, sam.kLogEpochConvertTime)) epoch_train_times.append( sam.get_log_epoch_value(epoch, sam.kLogEpochTrainTime)) epoch_train_total_times_profiler.append( sam.get_log_epoch_value(epoch, sam.kLogEpochTotalTime)) if worker_id == 0: print('Epoch {:05d} | Epoch Time {:.4f} | Total Train Time(Profiler) {:.4f} | Copy Time {:.4f}'.format( epoch, epoch_total_times_python[-1], epoch_train_total_times_profiler[-1], epoch_copy_times[-1])) # sync the train workers if num_worker > 1: torch.distributed.barrier() print('[Train Worker {:d}] Avg Epoch Time {:.4f} | Train Total Time(Profiler) {:.4f} | Copy Time {:.4f}'.format( worker_id, np.mean(epoch_total_times_python[1:]), np.mean(epoch_train_total_times_profiler[1:]), np.mean(epoch_copy_times[1:]))) # run end barrier global_barrier.wait() run_end = time.time() # sampler print init and result global_barrier.wait() # barrier for pretty print if worker_id == 0: sam.report_step_average(epoch - 1, step - 1) sam.report_init() test_result = [] test_result.append(('epoch_time:copy_time', np.mean(epoch_copy_times[1:]))) test_result.append(('convert_time', np.mean(epoch_convert_times[1:]))) test_result.append(('train_time', np.mean(epoch_train_times[1:]))) test_result.append(('epoch_time:train_total', np.mean( epoch_train_total_times_profiler[1:]))) test_result.append( ('cache_percentage', run_config['cache_percentage'])) test_result.append(('cache_hit_rate', np.mean( epoch_cache_hit_rates[1:]))) test_result.append(('epoch_feat_nbytes', np.mean(epoch_feat_nbytes[1:]))) test_result.append(('batch_feat_nbytes', np.mean(epoch_feat_nbytes[1:])/(align_up_step/num_worker))) test_result.append(('epoch_miss_nbytes', np.mean(epoch_miss_nbytes[1:]))) test_result.append(('batch_miss_nbytes', np.mean(epoch_miss_nbytes[1:])/(align_up_step/num_worker))) test_result.append(('batch_copy_time', np.mean(epoch_copy_times[1:])/(align_up_step/num_worker))) test_result.append(('batch_train_time', np.mean(epoch_train_total_times_profiler[1:])/(align_up_step/num_worker))) if run_config['pipeline']: test_result.append( ('pipeline_train_epoch_time', np.mean(epoch_total_times_python[1:]))) test_result.append(('run_time', run_end - run_start)) test_result.append(('init:load_dataset:copy:trainer', sam.get_log_init_value(sam.kLogInitL3LoadDatasetCopy))) test_result.append(('init:dist_queue:pin:trainer', sam.get_log_init_value(sam.kLogInitL3DistQueuePin))) test_result.append(('init:internal:trainer', sam.get_log_init_value(sam.kLogInitL2InternalState))) test_result.append(('init:cache:trainer', sam.get_log_init_value(sam.kLogInitL2BuildCache))) for k, v in test_result: print('test_result:{:}={:.4f}'.format(k, v)) # sam.dump_trace() sam.shutdown() if __name__ == '__main__': run_config = get_run_config() run_init(run_config) num_sample_worker = run_config['num_sample_worker'] num_train_worker = run_config['num_train_worker'] # global barrier is used to sync all the sample workers and train workers run_config['global_barrier'] = mp.Barrier( num_sample_worker + num_train_worker, timeout=get_default_timeout()) workers = [] # sample processes for worker_id in range(num_sample_worker): p = mp.Process(target=run_sample, args=(worker_id, run_config)) p.start() workers.append(p) # train processes for worker_id in range(num_train_worker): p = mp.Process(target=run_train, args=(worker_id, run_config)) p.start() workers.append(p) ret = sam.wait_one_child() if ret != 0: for p in workers: p.kill() for p in workers: p.join() if ret != 0: sys.exit(1)
36.891593
138
0.64054
2,115
16,675
4.715839
0.134752
0.052336
0.048125
0.020453
0.495087
0.434831
0.33086
0.241929
0.177161
0.144676
0
0.009665
0.249175
16,675
451
139
36.973392
0.786981
0.043658
0
0.202381
0
0.008929
0.10284
0.025129
0
0
0
0
0.005952
1
0.020833
false
0
0.044643
0
0.077381
0.029762
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d93b4251771b7cf7a6b382690dc7c24a823f2b1d
1,445
py
Python
Python-Arduino/Python-setter.py
TSG405/IOT
dc6f965baf3d0cc0a79e88bc9c3fd8d4ece3fa51
[ "BSD-3-Clause" ]
2
2020-10-29T07:28:26.000Z
2021-04-25T05:33:54.000Z
Python-Arduino/Python-setter.py
TSG405/IOT
dc6f965baf3d0cc0a79e88bc9c3fd8d4ece3fa51
[ "BSD-3-Clause" ]
null
null
null
Python-Arduino/Python-setter.py
TSG405/IOT
dc6f965baf3d0cc0a79e88bc9c3fd8d4ece3fa51
[ "BSD-3-Clause" ]
null
null
null
import serial # Using SERIAL module to connect to comm ports via ARDUINO Arduino_Serial = serial.Serial('/dev/ttyACM0',9600) # Connecting via ttyACM0 port (LINUX) print (Arduino_Serial.readline()) # Status print ("Please enter --------> 1 <------- to TURN ON THE LED and ---------> 0 <-------- to TURN OFF THE LED") while (True): # InFinite LOOP input_data = input() print ( "USER Entered... ", input_data ) if (input_data == '405'): # Exit Condition Arduino_Serial.write( '405'.encode() ) print ("--- Thank You ---") print ("--- ! BYE ! ---") break; elif (input_data == '1'): # Condition ONE Arduino_Serial.write( '1'.encode() ) # For Python 3 and above --> use "encode" to convert raw input into bytes! print ("--- LED IS ON NOW ---") print ("PRESS 405 to exit!!") elif (input_data == '0'): # Condition TWO Arduino_Serial.write( '0'.encode() ) # For Python 3 and above --> use "encode" to convert raw input into bytes! print ("--- LED IS OFF NOW ---") print ("PRESS 405 to exit!!") else: print(" Invalid Input! Sorry! ") ''' CODED BY TSG405 '''
40.138889
131
0.467128
150
1,445
4.433333
0.453333
0.097744
0.081203
0.04812
0.273684
0.273684
0.207519
0.207519
0.207519
0.207519
0
0.032992
0.391696
1,445
35
132
41.285714
0.723549
0.238062
0
0.090909
0
0
0.258004
0
0
0
0
0
0
1
0
false
0
0.045455
0
0.045455
0.454545
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
1
d93c3126662cf31eb885a0986f780983d532d782
3,453
py
Python
src/AIC2018_iamai/ReID/ReID_CNN/logger.py
gordonjun2/CenterTrack
358f94c36ef03b8ae7d15d8a48fbf70fff937e79
[ "MIT" ]
2
2020-04-13T14:06:23.000Z
2020-06-10T08:41:28.000Z
src/AIC2018_iamai/ReID/ReID_CNN/logger.py
gordonjun2/CenterTrack
358f94c36ef03b8ae7d15d8a48fbf70fff937e79
[ "MIT" ]
null
null
null
src/AIC2018_iamai/ReID/ReID_CNN/logger.py
gordonjun2/CenterTrack
358f94c36ef03b8ae7d15d8a48fbf70fff937e79
[ "MIT" ]
null
null
null
import os import pathlib import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.cm as cm import pandas as pd from collections import OrderedDict class Logger: def __init__(self, save_dir, prefix=''): #names = ['epoch', # 'loss', 'loss_max', 'loss_median', 'loss_min', 'active_loss', # 'feat_2-norm_max', 'feat_2-norm_median', 'feat_2-norm_min'] self.log = OrderedDict([('epoch', [])]) self.save_dir = os.path.join(save_dir) pathlib.Path(save_dir).mkdir(parents=True, exist_ok=True) self.prefix = prefix def logg(self, d): for k in d: if k not in self.log: self.log[k] = [] self.log[k].append(d[k]) def append_epoch(self, e): self.log['epoch'].append(e) def append_loss(self, b_loss): names = ['loss', 'loss_max', 'loss_median', 'loss_min', 'active_loss'] for n in names: if n not in self.log: self.log[n] = [] self.log['loss'].append(b_loss.mean()) self.log['loss_max'].append(b_loss.max()) self.log['loss_median'].append(np.median(b_loss)) self.log['loss_min'].append(b_loss.min()) self.log['active_loss'].append((b_loss > 1e-3).mean()) def append_feat(self, b_feat): names = ['feat_2-norm_max', 'feat_2-norm_median', 'feat_2-norm_min'] for n in names: if n not in self.log: self.log[n] = [] norm = np.linalg.norm(b_feat, axis=1) self.log['feat_2-norm_max'].append(norm.max()) self.log['feat_2-norm_median'].append(np.median(norm)) self.log['feat_2-norm_min'].append(norm.min()) def write_log(self): dataframe = pd.DataFrame(self.log) dataframe.to_csv(os.path.join(self.save_dir, '%slog.csv' % self.prefix), index=False) def plot(self): epoch = np.array(self.log['epoch']) plt.figure() labels = ['loss_max', 'loss_median', 'loss_min'] for i, l in enumerate(labels): data = np.array(self.log[l]) plt.semilogy(epoch, data, label=l, color=cm.Blues(0.25+float(i)*0.25)) data = np.array(self.log['loss']) plt.semilogy(epoch, data, label='loss', color='r') plt.legend() plt.xlabel('epoch') plt.ylabel('loss') plt.title('loss vs. epoch') plt.savefig(os.path.join(self.save_dir, '%sloss.png' % self.prefix)) plt.close() plt.figure() data = np.array(self.log['active_loss']) plt.plot(epoch, data, label='active_loss') plt.legend() plt.xlabel('epoch') plt.ylabel('% of active loss') plt.title('% of active loss vs. epoch') plt.savefig(os.path.join(self.save_dir, '%sactive_loss.png' % self.prefix)) plt.close() plt.figure() labels = ['feat_2-norm_max', 'feat_2-norm_median', 'feat_2-norm_min'] for i, l in enumerate(labels): data = np.array(self.log[l]) plt.plot(epoch, data, label=l, color=cm.Blues(0.25+float(i)*0.25)) plt.legend() plt.xlabel('epoch') plt.ylabel('2-norm of feature') plt.title('2-norm of feature vs. epoch') plt.savefig(os.path.join(self.save_dir, '%sfeature_norm.png' % self.prefix)) plt.close()
35.96875
94
0.56936
493
3,453
3.84787
0.194726
0.084871
0.056932
0.0369
0.491302
0.405377
0.373221
0.290986
0.290986
0.250923
0
0.011513
0.270489
3,453
95
95
36.347368
0.741564
0.044889
0
0.25974
0
0
0.144985
0
0
0
0
0
0
1
0.090909
false
0
0.103896
0
0.207792
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d93cdda3893693209b80cab60a21164807e0bd8b
1,493
py
Python
venv/lib/python2.7/site-packages/pychart/afm/ZapfDingbats.py
Christian-Castro/castro_odoo8
8247fdb20aa39e043b6fa0c4d0af509462ab3e00
[ "Unlicense" ]
1
2019-12-19T01:53:13.000Z
2019-12-19T01:53:13.000Z
venv/lib/python2.7/site-packages/pychart/afm/ZapfDingbats.py
Christian-Castro/castro_odoo8
8247fdb20aa39e043b6fa0c4d0af509462ab3e00
[ "Unlicense" ]
null
null
null
venv/lib/python2.7/site-packages/pychart/afm/ZapfDingbats.py
Christian-Castro/castro_odoo8
8247fdb20aa39e043b6fa0c4d0af509462ab3e00
[ "Unlicense" ]
null
null
null
# AFM font ZapfDingbats (path: /usr/share/fonts/afms/adobe/pzdr.afm). # Derived from Ghostscript distribution. # Go to www.cs.wisc.edu/~ghost to get the Ghostcript source code. import dir dir.afm["ZapfDingbats"] = (500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 278, 974, 961, 974, 980, 719, 789, 790, 791, 690, 960, 939, 549, 855, 911, 933, 911, 945, 974, 755, 846, 762, 761, 571, 677, 763, 760, 759, 754, 494, 552, 537, 577, 692, 786, 788, 788, 790, 793, 794, 816, 823, 789, 841, 823, 833, 816, 831, 923, 744, 723, 749, 790, 792, 695, 776, 768, 792, 759, 707, 708, 682, 701, 826, 815, 789, 789, 707, 687, 696, 689, 786, 787, 713, 791, 785, 791, 873, 761, 762, 762, 759, 759, 892, 892, 788, 784, 438, 138, 277, 415, 392, 392, 668, 668, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 732, 544, 544, 910, 667, 760, 760, 776, 595, 694, 626, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 894, 838, 1016, 458, 748, 924, 748, 918, 927, 928, 928, 834, 873, 828, 924, 924, 917, 930, 931, 463, 883, 836, 836, 867, 867, 696, 696, 874, 500, 874, 760, 946, 771, 865, 771, 888, 967, 888, 831, 873, 927, 970, 918, )
248.833333
1,304
0.621567
288
1,493
3.222222
0.451389
0.413793
0.601293
0.775862
0.342672
0.342672
0.342672
0.342672
0.342672
0.342672
0
0.632013
0.188212
1,493
5
1,305
298.6
0.133663
0.113865
0
0
0
0
0.009098
0
0
0
0
0
0
1
0
true
0
0.5
0
0.5
0
0
0
0
null
1
1
1
0
0
0
0
0
0
0
1
0
0
1
1
1
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
10
d93ce3e047e67035b0fc470f80c3e9659efed6a2
43,185
py
Python
data/scripts/bsRunaround.py
starpirate2203/BROODY-S-LAST-SCRIPT
7b5a9eab02c782ebf39b0f3edf69536fae8289c6
[ "MIT" ]
2
2021-09-07T16:04:30.000Z
2021-09-16T03:30:16.000Z
data/scripts/bsRunaround.py
starpirate2203/BROODY-S-LAST-SCRIPT
7b5a9eab02c782ebf39b0f3edf69536fae8289c6
[ "MIT" ]
null
null
null
data/scripts/bsRunaround.py
starpirate2203/BROODY-S-LAST-SCRIPT
7b5a9eab02c782ebf39b0f3edf69536fae8289c6
[ "MIT" ]
1
2021-09-21T12:42:28.000Z
2021-09-21T12:42:28.000Z
import bs import random import math class RunaroundGame(bs.CoopGameActivity): tips = [ 'Jump just as you\'re throwing to get bombs up to the highest levels.', 'No, you can\'t get up on the ledge. You have to throw bombs.', 'Whip back and forth to get more distance on your throws..'] @classmethod def getName(cls): return 'Runaround' @classmethod def getDescription(cls, sessionType): return "Prevent enemies from reaching the exit." def __init__(self, settings={}): settings['map'] = 'Tower D' bs.CoopGameActivity.__init__(self, settings) try: self._preset = self.settings['preset'] except Exception: self._preset = 'pro' self._playerDeathSound = bs.getSound('playerDeath') self._newWaveSound = bs.getSound('scoreHit01') self._winSound = bs.getSound("score") self._cashRegisterSound = bs.getSound('cashRegister') self._badGuyScoreSound = bs.getSound("shieldDown") self._heartTex = bs.getTexture('heart') self._heartModelOpaque = bs.getModel('heartOpaque') self._heartModelTransparent = bs.getModel('heartTransparent') self._aPlayerHasBeenKilled = False self._spawnCenter = self._mapType.defs.points['spawn1'][0:3] self._tntSpawnPosition = self._mapType.defs.points['tntLoc'][0:3] self._powerupCenter = self._mapType.defs.boxes['powerupRegion'][0:3] self._powerupSpread = ( self._mapType.defs.boxes['powerupRegion'][6]*0.5, self._mapType.defs.boxes['powerupRegion'][8]*0.5) self._scoreRegionMaterial = bs.Material() self._scoreRegionMaterial.addActions( conditions=("theyHaveMaterial", bs.getSharedObject('playerMaterial')), actions=(("modifyPartCollision", "collide", True), ("modifyPartCollision", "physical", False), ("call", "atConnect", self._handleReachedEnd))) self._lastWaveEndTime = bs.getGameTime() self._playerHasPickedUpPowerup = False def onTransitionIn(self): bs.CoopGameActivity.onTransitionIn(self, music='Marching') self._scoreBoard = bs.ScoreBoard( label=bs.Lstr(resource='scoreText'), scoreSplit=0.5) self._gameOver = False self._wave = 0 self._canEndWave = True # we use this in place of a regular int to make it harder to hack scores self._score = bs.SecureInt(0) self._timeBonus = 0 self._scoreRegion = bs.NodeActor( bs.newNode( 'region', attrs={'position': self.getMap().defs.boxes['scoreRegion'] [0: 3], 'scale': self.getMap().defs.boxes['scoreRegion'] [6: 9], 'type': 'box', 'materials': [self._scoreRegionMaterial]})) def onBegin(self): bs.CoopGameActivity.onBegin(self) self._dingSound = bs.getSound('dingSmall') self._dingSoundHigh = bs.getSound('dingSmallHigh') playerCount = len(self.players) hard = False if self._preset in ['proEasy', 'uberEasy'] else True if self._preset in ['pro', 'proEasy', 'tournament']: self._excludePowerups = ['curse'] self._haveTnt = True self._waves = [ {'entries': [ {'type': bs.BomberBot, 'path': 3 if hard else 2}, {'type': bs.BomberBot, 'path': 2}, {'type': bs.BomberBot, 'path': 2} if hard else None, {'type': bs.BomberBot, 'path': 2} if playerCount > 1 \ else None, {'type': bs.BomberBot, 'path': 1} if hard else None, {'type': bs.BomberBot, 'path': 1} if playerCount > 2 \ else None, {'type': bs.BomberBot, 'path': 1} if playerCount > 3 \ else None, ]}, {'entries': [ {'type': bs.BomberBot, 'path': 1} if hard else None, {'type': bs.BomberBot, 'path': 2} if hard else None, {'type': bs.BomberBot, 'path': 2}, {'type': bs.BomberBot, 'path': 2}, {'type': bs.BomberBot, 'path': 2} if playerCount > 3 \ else None, {'type': bs.ToughGuyBot, 'path': 3}, {'type': bs.ToughGuyBot, 'path': 3}, {'type': bs.ToughGuyBot, 'path': 3} if hard else None, {'type': bs.ToughGuyBot, 'path': 3} if playerCount > 1 \ else None, {'type': bs.ToughGuyBot, 'path': 3} if playerCount > 2 \ else None, ]}, {'entries': [ {'type': bs.NinjaBot, 'path': 2} if hard else None, {'type': bs.NinjaBot, 'path': 2} if playerCount > 2 \ else None, {'type': bs.ChickBot, 'path': 2}, {'type': bs.ChickBot, 'path': 2} if playerCount > 1 \ else None, {'type': 'spacing', 'duration': 3000}, {'type': bs.BomberBot, 'path': 2} if hard else None, {'type': bs.BomberBot, 'path': 2} if hard else None, {'type': bs.BomberBot, 'path': 2}, {'type': bs.BomberBot, 'path': 3} if hard else None, {'type': bs.BomberBot, 'path': 3}, {'type': bs.BomberBot, 'path': 3}, {'type': bs.BomberBot, 'path': 3} if playerCount > 3 \ else None, ]}, {'entries': [ {'type': bs.ChickBot, 'path': 1} if hard else None, {'type': 'spacing', 'duration': 1000} if hard else None, {'type': bs.ChickBot, 'path': 2}, {'type': 'spacing', 'duration': 1000}, {'type': bs.ChickBot, 'path': 3}, {'type': 'spacing', 'duration': 1000}, {'type': bs.ChickBot, 'path': 1} if hard else None, {'type': 'spacing', 'duration': 1000} if hard else None, {'type': bs.ChickBot, 'path': 2}, {'type': 'spacing', 'duration': 1000}, {'type': bs.ChickBot, 'path': 3}, {'type': 'spacing', 'duration': 1000}, {'type': bs.ChickBot, 'path': 1} if (playerCount > 1 \ and hard) else None, {'type': 'spacing', 'duration': 1000}, {'type': bs.ChickBot, 'path': 2} if playerCount > 2 \ else None, {'type': 'spacing', 'duration': 1000}, {'type': bs.ChickBot, 'path': 3} if playerCount > 3 \ else None, {'type': 'spacing', 'duration': 1000}, ]}, {'entries': [ {'type': bs.NinjaBotProShielded if hard else bs.NinjaBot, 'path': 1}, {'type': bs.ToughGuyBot, 'path': 2} if hard else None, {'type': bs.ToughGuyBot, 'path': 2}, {'type': bs.ToughGuyBot, 'path': 2}, {'type': bs.ToughGuyBot, 'path': 3} if hard else None, {'type': bs.ToughGuyBot, 'path': 3}, {'type': bs.ToughGuyBot, 'path': 3}, {'type': bs.ToughGuyBot, 'path': 3} if playerCount > 1 \ else None, {'type': bs.ToughGuyBot, 'path': 3} if playerCount > 2 \ else None, {'type': bs.ToughGuyBot, 'path': 3} if playerCount > 3 \ else None, ]}, {'entries': [ {'type': bs.BomberBotProShielded, 'path': 3}, {'type': 'spacing', 'duration': 1500}, {'type': bs.BomberBotProShielded, 'path': 2}, {'type': 'spacing', 'duration': 1500}, {'type': bs.BomberBotProShielded, 'path': 1} if hard \ else None, {'type': 'spacing', 'duration': 1000} if hard else None, {'type': bs.BomberBotProShielded, 'path': 3}, {'type': 'spacing', 'duration': 1500}, {'type': bs.BomberBotProShielded, 'path': 2}, {'type': 'spacing', 'duration': 1500}, {'type': bs.BomberBotProShielded, 'path': 1} if hard \ else None, {'type': 'spacing', 'duration': 1500} if hard else None, {'type': bs.BomberBotProShielded, 'path': 3} \ if playerCount > 1 else None, {'type': 'spacing', 'duration': 1500}, {'type': bs.BomberBotProShielded, 'path': 2} \ if playerCount > 2 else None, {'type': 'spacing', 'duration': 1500}, {'type': bs.BomberBotProShielded, 'path': 1} \ if playerCount > 3 else None, ]}, ] elif self._preset in ['uberEasy', 'uber', 'tournamentUber']: self._excludePowerups = [] self._haveTnt = True self._waves = [ {'entries': [ {'type': bs.ChickBot, 'path': 1} if hard else None, {'type': bs.ChickBot, 'path': 2}, {'type': bs.ChickBot, 'path': 2}, {'type': bs.ChickBot, 'path': 3}, {'type': bs.ToughGuyBotPro if hard else bs.ToughGuyBot, 'point': 'BottomLeft'}, {'type': bs.ToughGuyBotPro, 'point': 'BottomRight'} \ if playerCount > 2 else None, ]}, {'entries': [ {'type': bs.NinjaBot, 'path': 2}, {'type': bs.NinjaBot, 'path': 3}, {'type': bs.NinjaBot, 'path': 1} if hard else None, {'type': bs.NinjaBot, 'path': 2}, {'type': bs.NinjaBot, 'path': 3}, {'type': bs.NinjaBot, 'path': 1} if playerCount > 2 \ else None, ]}, {'entries': [ {'type': bs.BomberBotProShielded, 'path': 1} if hard \ else None, {'type': bs.BomberBotProShielded, 'path': 2}, {'type': bs.BomberBotProShielded, 'path': 2}, {'type': bs.BomberBotProShielded, 'path': 3}, {'type': bs.BomberBotProShielded, 'path': 3}, {'type': bs.NinjaBot, 'point': 'BottomRight'}, {'type': bs.NinjaBot, 'point': 'BottomLeft'} \ if playerCount > 2 else None, ]}, {'entries': [ {'type': bs.ChickBotPro, 'path': 1} if hard else None, {'type': bs.ChickBotPro, 'path': 1 if hard else 2}, {'type': bs.ChickBotPro, 'path': 1 if hard else 2}, {'type': bs.ChickBotPro, 'path': 1 if hard else 2}, {'type': bs.ChickBotPro, 'path': 1 if hard else 2}, {'type': bs.ChickBotPro, 'path': 1 if hard else 2}, {'type': bs.ChickBotPro, 'path': 1 if hard else 2} \ if playerCount > 1 else None, {'type': bs.ChickBotPro, 'path': 1 if hard else 2} \ if playerCount > 3 else None, ]}, {'entries': [ {'type': bs.ChickBotProShielded if hard else bs.ChickBotPro, 'point': 'BottomLeft'}, {'type': bs.ChickBotProShielded, 'point': 'BottomRight'} \ if hard else None, {'type': bs.ChickBotProShielded, 'point': 'BottomRight'} \ if playerCount > 2 else None, {'type': bs.BomberBot, 'path': 3}, {'type': bs.BomberBot, 'path': 3}, {'type': 'spacing', 'duration': 5000}, {'type': bs.ToughGuyBot, 'path': 2}, {'type': bs.ToughGuyBot, 'path': 2}, {'type': 'spacing', 'duration': 5000}, {'type': bs.ChickBot, 'path': 1} if hard else None, {'type': bs.ChickBot, 'path': 1} if hard else None, ]}, {'entries': [ {'type': bs.BomberBotProShielded, 'path': 2}, {'type': bs.BomberBotProShielded, 'path': 2} if hard \ else None, {'type': bs.MelBot, 'point': 'BottomRight'}, {'type': bs.BomberBotProShielded, 'path': 2}, {'type': bs.BomberBotProShielded, 'path': 2}, {'type': bs.MelBot, 'point': 'BottomRight'} \ if playerCount > 2 else None, {'type': bs.BomberBotProShielded, 'path': 2}, {'type': bs.PirateBot, 'point': 'BottomLeft'}, {'type': bs.BomberBotProShielded, 'path': 2}, {'type': bs.BomberBotProShielded, 'path': 2} \ if playerCount > 1 else None, {'type': 'spacing', 'duration': 5000}, {'type': bs.MelBot, 'point': 'BottomLeft'}, {'type': 'spacing', 'duration': 2000}, {'type': bs.PirateBot, 'point': 'BottomRight'}, ]}, ] elif self._preset in ['endless', 'endlessTournament']: self._excludePowerups = [] self._haveTnt = True # spit out a few powerups and start dropping more shortly self._dropPowerups(standardPoints=True) bs.gameTimer(4000, self._startPowerupDrops) self.setupLowLifeWarningSound() self._updateScores() self._bots = bs.BotSet() # our TNT spawner (if applicable) if self._haveTnt: self._tntSpawner = bs.TNTSpawner(position=self._tntSpawnPosition) # make sure to stay out of the way of menu/party buttons in the corner interfaceType = bs.getEnvironment()['interfaceType'] lOffs = (-80 if interfaceType == 'small' else -40 if interfaceType == 'medium' else 0) self._livesBG = bs.NodeActor( bs.newNode( 'image', attrs={'texture': self._heartTex, 'modelOpaque': self._heartModelOpaque, 'modelTransparent': self._heartModelTransparent, 'attach': 'topRight', 'scale': (90, 90), 'position': (-110 + lOffs, -50), 'color': (1, 0.2, 0.2)})) vr = bs.getEnvironment()['vrMode'] self._startLives = 10 self._lives = self._startLives self._livesText = bs.NodeActor( bs.newNode( 'text', attrs={'vAttach': 'top', 'hAttach': 'right', 'hAlign': 'center', 'color': (1, 1, 1, 1) if vr else(0.8, 0.8, 0.8, 1.0), 'flatness': 1.0 if vr else 0.5, 'shadow': 1.0 if vr else 0.5, 'vrDepth': 10, 'position': (-113 + lOffs, -69), 'scale': 1.3, 'text': str(self._lives)})) bs.gameTimer(2000, self._startUpdatingWaves) def _handleReachedEnd(self): n = bs.getCollisionInfo("opposingNode") spaz = n.getDelegate() if not spaz.isAlive(): return # ignore bodies flying in.. self._flawless = False p = spaz.node.position bs.playSound(self._badGuyScoreSound, position=p) light = bs.newNode('light', attrs={'position': p, 'radius': 0.5, 'color': (1, 0, 0)}) bs.animate(light, 'intensity', {0: 0, 100: 1, 500: 0}, loop=False) bs.gameTimer(1000, light.delete) spaz.handleMessage(bs.DieMessage(immediate=True, how='goal')) if self._lives > 0: self._lives -= 1 if self._lives == 0: self._bots.stopMoving() self.continueOrEndGame() self._livesText.node.text = str(self._lives) t = 0 def _safeSetAttr(node, attr, value): if node.exists(): setattr(node, attr, value) for i in range(4): bs.gameTimer(t, bs.Call(_safeSetAttr, self._livesText.node, 'color', (1, 0, 0, 1.0))) bs.gameTimer(t, bs.Call(_safeSetAttr, self._livesBG.node, 'opacity', 0.5)) t += 125 bs.gameTimer(t, bs.Call(_safeSetAttr, self._livesText.node, 'color', (1.0, 1.0, 0.0, 1.0))) bs.gameTimer(t, bs.Call(_safeSetAttr, self._livesBG.node, 'opacity', 1.0)) t += 125 bs.gameTimer( t, bs.Call( _safeSetAttr, self._livesText.node, 'color', (0.8, 0.8, 0.8, 1.0))) def onContinue(self): self._lives = 3 self._livesText.node.text = str(self._lives) self._bots.startMoving() def spawnPlayer(self, player): pos = ( self._spawnCenter[0] + random.uniform(-1.5, 1.5), self._spawnCenter[1], self._spawnCenter[2] + random.uniform(-1.5, 1.5)) s = self.spawnPlayerSpaz(player, position=pos) if self._preset in ['proEasy', 'uberEasy']: s._impactScale = 0.25 # add the material that causes us to hit the player-wall s.pickUpPowerupCallback = self._onPlayerPickedUpPowerup def _onPlayerPickedUpPowerup(self, player): self._playerHasPickedUpPowerup = True def _dropPowerup(self, index, powerupType=None): if powerupType is None: powerupType = bs.Powerup.getFactory().getRandomPowerupType( excludeTypes=self._excludePowerups) bs.Powerup( position=self.getMap().powerupSpawnPoints[index], powerupType=powerupType).autoRetain() def _startPowerupDrops(self): bs.gameTimer(3000, self._dropPowerups, repeat=True) def _dropPowerups(self, standardPoints=False, forceFirst=None): """ Generic powerup drop """ # if its been a minute since our last wave finished emerging, stop # giving out land-mine powerups. (prevents players from waiting # around for them on purpose and filling the map up) if bs.getGameTime() - self._lastWaveEndTime > 60000: extraExcludes = ['landMines'] else: extraExcludes = [] if standardPoints: pts = self.getMap().powerupSpawnPoints for i, pt in enumerate(pts): bs.gameTimer(1000+i*500, bs.Call( self._dropPowerup, i, forceFirst if i == 0 else None)) else: pt = (self._powerupCenter[0] +random.uniform(-1.0*self._powerupSpread[0], 1.0*self._powerupSpread[0]), self._powerupCenter[1], self._powerupCenter[2]+random.uniform(-self._powerupSpread[1], self._powerupSpread[1])) # drop one random one somewhere.. bs.Powerup(position=pt, powerupType=bs.Powerup.getFactory().getRandomPowerupType( excludeTypes=self._excludePowerups+extraExcludes) ).autoRetain() def endGame(self): # FIXME FIXME FIXME - if we don't start our bots moving again we get # stuck this is because the bot-set never prunes itself while movement # is off and onFinalize never gets called for some bots because # _pruneDeadObjects() saw them as dead and pulled them off the # weak-ref lists. this is an architectural issue; can hopefully fix # this by having _actorWeakRefs not look at exists() self._bots.startMoving() bs.gameTimer(1, bs.Call(self.doEnd, 'defeat')) bs.playMusic(None) bs.playSound(self._playerDeathSound) def doEnd(self, outcome): if outcome == 'defeat': delay = 2000 self.fadeToRed() else: delay = 0 if self._wave >= 2: score = self._score.get() failMessage = None else: score = None failMessage = 'Reach wave 2 to rank.' self.end( delay=delay, results={'outcome': outcome, 'score': score, 'failMessage': failMessage, 'playerInfo': self.initialPlayerInfo}) def _onGotScoresToBeat(self, scores): self._showStandardScoresToBeatUI(scores) def _updateWaves(self): # if we have no living bots, go to the next wave if (self._canEndWave and not self._bots.haveLivingBots() and not self._gameOver and self._lives > 0): self._canEndWave = False self._timeBonusTimer = None self._timeBonusText = None if self._preset in ['endless', 'endlessTournament']: won = False else: won = (self._wave == len(self._waves)) # reward time bonus baseDelay = 4000 if won else 0 if self._timeBonus > 0: bs.gameTimer(0, bs.Call(bs.playSound, self._cashRegisterSound)) bs.gameTimer(baseDelay, bs.Call( self._awardTimeBonus, self._timeBonus)) baseDelay += 1000 # reward flawless bonus if self._wave > 0 and self._flawless: bs.gameTimer(baseDelay, self._awardFlawlessBonus) baseDelay += 1000 self._flawless = True # reset if won: # completion achievements if self._preset in ['pro', 'proEasy']: self._awardAchievement('Pro Runaround Victory', sound=False) if self._lives == self._startLives: self._awardAchievement('The Wall', sound=False) if not self._playerHasPickedUpPowerup: self._awardAchievement('Precision Bombing', sound=False) elif self._preset in ['uber', 'uberEasy']: self._awardAchievement( 'Uber Runaround Victory', sound=False) if self._lives == self._startLives: self._awardAchievement('The Great Wall', sound=False) if not self._aPlayerHasBeenKilled: self._awardAchievement('Stayin\' Alive', sound=False) # give remaining players some points and have them celebrate self.showZoomMessage( bs.Lstr(resource='victoryText'), scale=1.0, duration=4000) self.celebrate(10000) bs.gameTimer(baseDelay, self._awardLivesBonus) baseDelay += 1000 bs.gameTimer(baseDelay, self._awardCompletionBonus) baseDelay += 850 bs.playSound(self._winSound) self.cameraFlash() bs.playMusic('Victory') self._gameOver = True bs.gameTimer(baseDelay, bs.Call(self.doEnd, 'victory')) return self._wave += 1 # short celebration after waves if self._wave > 1: self.celebrate(500) bs.gameTimer(baseDelay, self._startNextWave) def _awardCompletionBonus(self): bonus = 200 bs.playSound(self._cashRegisterSound) bs.PopupText( bs.Lstr( value='+${A} ${B}', subs=[('${A}', str(bonus)), ('${B}', bs.Lstr(resource='completionBonusText'))]), color=(0.7, 0.7, 1.0, 1), scale=1.6, position=(0, 1.5, -1)).autoRetain() self._score.add(bonus) self._updateScores() def _awardLivesBonus(self,): bonus = self._lives * 30 bs.playSound(self._cashRegisterSound) bs.PopupText( bs.Lstr( value='+${A} ${B}', subs=[('${A}', str(bonus)), ('${B}', bs.Lstr(resource='livesBonusText'))]), color=(0.7, 1.0, 0.3, 1), scale=1.3, position=(0, 1, -1)).autoRetain() self._score.add(bonus) self._updateScores() def _awardTimeBonus(self, bonus): bs.playSound(self._cashRegisterSound) bs.PopupText( bs.Lstr( value='+${A} ${B}', subs=[('${A}', str(bonus)), ('${B}', bs.Lstr(resource='timeBonusText'))]), color=(1, 1, 0.5, 1), scale=1.0, position=(0, 3, -1)).autoRetain() self._score.add(self._timeBonus) self._updateScores() def _awardFlawlessBonus(self): bs.playSound(self._cashRegisterSound) bs.PopupText( bs.Lstr( value='+${A} ${B}', subs=[('${A}', str(self._flawlessBonus)), ('${B}', bs.Lstr(resource='perfectWaveText'))]), color=(1, 1, 0.2, 1), scale=1.2, position=(0, 2, -1)).autoRetain() self._score.add(self._flawlessBonus) self._updateScores() def _startTimeBonusTimer(self): self._timeBonusTimer = bs.Timer( 1000, self._updateTimeBonus, repeat=True) def _startNextWave(self): self.showZoomMessage( bs.Lstr( value='${A} ${B}', subs=[('${A}', bs.Lstr(resource='waveText')), ('${B}', str(self._wave))]), scale=1.0, duration=1000, trail=True) bs.gameTimer(400, bs.Call(bs.playSound, self._newWaveSound)) t = 0 baseDelay = 500 botAngle = random.random()*360.0 spawnTime = 100 botTypes = [] if self._preset in ['endless', 'endlessTournament']: level = self._wave targetPoints = (level+1) * 8.0 groupCount = random.randint(1, 3) entries = [] spazTypes = [] if level < 6: spazTypes += [[bs.BomberBot, 5.0]] if level < 10: spazTypes += [[bs.ToughGuyBot, 5.0]] if level < 15: spazTypes += [[bs.ChickBot, 6.0]] if level > 5: spazTypes += [[bs.ChickBotPro, 7.5]]*(1+(level-5)/7) if level > 2: spazTypes += [[bs.BomberBotProShielded, 8.0]]*(1+(level-2)/6) if level > 6: spazTypes += [[bs.ChickBotProShielded, 12.0]]*(1+(level-6)/5) if level > 1: spazTypes += [[bs.NinjaBot, 10.0]]*(1+(level-1)/4) if level > 7: spazTypes += [[bs.NinjaBotProShielded, 15.0]]*(1+(level-7)/3) # bot type, their effect on target points defenderTypes = [[bs.BomberBot, 0.9], [bs.ToughGuyBot, 0.9], [bs.ChickBot, 0.85]] if level > 2: defenderTypes += [[bs.NinjaBot, 0.75]] if level > 4: defenderTypes += [[bs.MelBot, 0.7]]*(1+(level-5)/6) if level > 6: defenderTypes += [[bs.PirateBot, 0.7]]*(1+(level-5)/5) if level > 8: defenderTypes += [[bs.ToughGuyBotProShielded, 0.65]]*(1+(level-5)/4) if level > 10: defenderTypes += [[bs.ChickBotProShielded, 0.6]]*(1+(level-6)/3) for group in range(groupCount): thisTargetPoints = targetPoints/groupCount # adding spacing makes things slightly harder r = random.random() if r < 0.07: spacing = 1500 thisTargetPoints *= 0.85 elif r < 0.15: spacing = 1000 thisTargetPoints *= 0.9 else: spacing = 0 path = random.randint(1, 3) # dont allow hard paths on early levels if level < 3: if path == 1: path = 3 # easy path if path == 3: pass # harder path elif path == 2: thisTargetPoints *= 0.8 # even harder path elif path == 1: thisTargetPoints *= 0.7 # looping forward elif path == 4: thisTargetPoints *= 0.7 # looping backward elif path == 5: thisTargetPoints *= 0.7 # random elif path == 6: thisTargetPoints *= 0.7 def _addDefender(defenderType, point): # entries.append() return thisTargetPoints * defenderType[1], { 'type': defenderType[0], 'point': point} # add defenders defenderType1 = defenderTypes[random.randrange( len(defenderTypes))] defenderType2 = defenderTypes[random.randrange( len(defenderTypes))] defender1 = defender2 = None if ((group == 0) or (group == 1 and level > 3) or (group == 2 and level > 5)): if random.random() < min(0.75, (level-1)*0.11): thisTargetPoints, defender1 = _addDefender( defenderType1, 'BottomLeft') if random.random() < min(0.75, (level-1)*0.04): thisTargetPoints, defender2 = _addDefender( defenderType2, 'BottomRight') spazType = spazTypes[random.randrange(len(spazTypes))] memberCount = max(1, int(round(thisTargetPoints/spazType[1]))) for i, member in enumerate(range(memberCount)): if path == 4: thisPath = i % 3 # looping forward elif path == 5: thisPath = 3-(i % 3) # looping backward elif path == 6: thisPath = random.randint(1, 3) # random else: thisPath = path entries.append({'type': spazType[0], 'path': thisPath}) if spacing != 0: entries.append({'type': 'spacing', 'duration': spacing}) if defender1 is not None: entries.append(defender1) if defender2 is not None: entries.append(defender2) # some spacing between groups r = random.random() if r < 0.1: spacing = 5000 elif r < 0.5: spacing = 1000 else: spacing = 1 entries.append({'type': 'spacing', 'duration': spacing}) wave = {'entries': entries} else: wave = self._waves[self._wave-1] try: botAngle = wave['baseAngle'] except Exception: botAngle = 0 botTypes += wave['entries'] self._timeBonusMult = 1.0 thisFlawlessBonus = 0 nonRunnerSpawnTime = 1000 for info in botTypes: if info is None: continue botType = info['type'] if botType is not None: if botType == 'nonRunnerDelay': nonRunnerSpawnTime += info['duration'] continue if botType == 'spacing': t += info['duration'] continue else: try: path = info['path'] except Exception: path = random.randint(1, 3) self._timeBonusMult += botType.pointsMult * 0.02 thisFlawlessBonus += botType.pointsMult * 5 # if its got a position, use that try: point = info['point'] except Exception: point = 'Start' # space our our slower bots delay = baseDelay delay /= self._getBotSpeed(botType) t += int(delay*0.5) bs.gameTimer( t, bs.Call( self.addBotAtPoint, point, {'type': botType, 'path': path}, 100 if point == 'Start' else nonRunnerSpawnTime)) t += int(delay*0.5) # we can end the wave after all the spawning happens bs.gameTimer(t-int(delay*0.5)+nonRunnerSpawnTime+10, self._setCanEndWave) # reset our time bonus # in this game we use a constant time bonus so it erodes away in # roughly the same time (since the time limit a wave can take is # relatively constant) ..we then post-multiply a modifier to adjust # points self._timeBonus = 150 self._flawlessBonus = thisFlawlessBonus self._timeBonusText = bs.NodeActor( bs.newNode( 'text', attrs={'vAttach': 'top', 'hAttach': 'center', 'hAlign': 'center', 'color': (1, 1, 0.0, 1), 'shadow': 1.0, 'vrDepth': -30, 'flatness': 1.0, 'position': (0, -60), 'scale': 0.8, 'text': bs.Lstr( value='${A}: ${B}', subs=[('${A}', bs.Lstr( resource='timeBonusText')), ('${B}', str( int( self._timeBonus * self._timeBonusMult)))])})) bs.gameTimer(t, self._startTimeBonusTimer) # keep track of when this wave finishes emerging - we wanna # stop dropping land-mines powerups at some point # (otherwise a crafty player could fill the whole map with them) self._lastWaveEndTime = bs.getGameTime()+t self._waveText = bs.NodeActor( bs.newNode( 'text', attrs={'vAttach': 'top', 'hAttach': 'center', 'hAlign': 'center', 'vrDepth': -10, 'color': (1, 1, 1, 1), 'shadow': 1.0, 'flatness': 1.0, 'position': (0, -40), 'scale': 1.3, 'text': bs.Lstr( value='${A} ${B}', subs=[('${A}', bs.Lstr(resource='waveText')), ('${B}', str(self._wave) + ('' if self._preset in ['endless', 'endlessTournament'] else('/' + str(len(self._waves)))))])})) def _onBotSpawn(self, path, spaz): # add our custom update callback and set some info for this bot.. spazType = type(spaz) spaz.updateCallback = self._updateBot spaz.rWalkRow = path spaz.rWalkSpeed = self._getBotSpeed(spazType) def addBotAtPoint(self, point, spazInfo, spawnTime=100): # dont add if the game has ended if self._gameOver: return pt = self.getMap().defs.points['botSpawn'+point][:3] self._bots.spawnBot( spazInfo['type'], pos=pt, spawnTime=spawnTime, onSpawnCall=bs.Call( self._onBotSpawn, spazInfo['path'])) def _updateTimeBonus(self): self._timeBonus = int(self._timeBonus * 0.91) if self._timeBonus > 0 and self._timeBonusText is not None: self._timeBonusText.node.text = bs.Lstr( value='${A}: ${B}', subs=[('${A}', bs.Lstr(resource='timeBonusText')), ('${B}', str( int(self._timeBonus * self._timeBonusMult)))]) else: self._timeBonusText = None def _startUpdatingWaves(self): self._waveUpdateTimer = bs.Timer(2000, self._updateWaves, repeat=True) def _updateScores(self): score = self._score.get() if self._preset == 'endless': if score >= 500: self._awardAchievement('Runaround Master') if score >= 1000: self._awardAchievement('Runaround Wizard') if score >= 2000: self._awardAchievement('Runaround God') self._scoreBoard.setTeamValue(self.teams[0], score, maxScore=None) def _updateBot(self, bot): speed = bot.rWalkSpeed t = bot.node.position boxes = self.getMap().defs.boxes # bots in row 1 attempt the high road.. if bot.rWalkRow == 1: if bs.isPointInBox(t, boxes['b4']): bot.node.moveUpDown = speed bot.node.moveLeftRight = 0 bot.node.run = 0.0 return True # row 1 and 2 bots attempt the middle road.. if bot.rWalkRow in [1, 2]: if bs.isPointInBox(t, boxes['b1']): bot.node.moveUpDown = speed bot.node.moveLeftRight = 0 bot.node.run = 0.0 return True # *all* bots settle for the third row if bs.isPointInBox(t, boxes['b7']): bot.node.moveUpDown = speed bot.node.moveLeftRight = 0 bot.node.run = 0.0 return True elif bs.isPointInBox(t, boxes['b2']): bot.node.moveUpDown = -speed bot.node.moveLeftRight = 0 bot.node.run = 0.0 return True elif bs.isPointInBox(t, boxes['b3']): bot.node.moveUpDown = -speed bot.node.moveLeftRight = 0 bot.node.run = 0.0 return True elif bs.isPointInBox(t, boxes['b5']): bot.node.moveUpDown = -speed bot.node.moveLeftRight = 0 bot.node.run = 0.0 return True elif bs.isPointInBox(t, boxes['b6']): bot.node.moveUpDown = speed bot.node.moveLeftRight = 0 bot.node.run = 0.0 return True elif (bs.isPointInBox(t, boxes['b8']) and not bs.isPointInBox(t, boxes['b9'])) or t == (0.0, 0.0, 0.0): # default to walking right if we're still in the walking area bot.node.moveLeftRight = speed bot.node.moveUpDown = 0 bot.node.run = 0.0 return True # revert to normal bot behavior otherwise.. return False def handleMessage(self, m): if isinstance(m, bs.PlayerScoredMessage): self._score.add(m.score) self._updateScores() # respawn dead players elif isinstance(m, bs.PlayerSpazDeathMessage): self._aPlayerHasBeenKilled = True player = m.spaz.getPlayer() if player is None: bs.printError('FIXME: getPlayer() should no' ' longer ever be returning None') return if not player.exists(): return self.scoreSet.playerLostSpaz(player) # respawn them shortly respawnTime = 2000+len(self.initialPlayerInfo)*1000 player.gameData['respawnTimer'] = bs.Timer( respawnTime, bs.Call(self.spawnPlayerIfExists, player)) player.gameData['respawnIcon'] = bs.RespawnIcon(player, respawnTime) elif isinstance(m, bs.SpazBotDeathMessage): if m.how == 'goal': return pts, importance = m.badGuy.getDeathPoints(m.how) if m.killerPlayer is not None: try: target = m.badGuy.node.position except Exception: target = None try: if m.killerPlayer is not None and m.killerPlayer.exists(): self.scoreSet.playerScored( m.killerPlayer, pts, target=target, kill=True, screenMessage=False, importance=importance) bs.playSound( self._dingSound if importance == 1 else self._dingSoundHigh, volume=0.6) except Exception as e: print 'EXC in Runaround handling SpazBotDeathMessage:', e # normally we pull scores from the score-set, but if there's no # player lets be explicit.. else: self._score.add(pts) self._updateScores() else: self.__superHandleMessage(m) def __superHandleMessage(self, m): super(RunaroundGame, self).handleMessage(m) def _getBotSpeed(self, botType): if botType == bs.BomberBot: return 0.48 elif botType == bs.BomberBotPro: return 0.48 elif botType == bs.BomberBotProShielded: return 0.48 elif botType == bs.ToughGuyBot: return 0.57 elif botType == bs.ToughGuyBotPro: return 0.57 elif botType == bs.ToughGuyBotProShielded: return 0.57 elif botType == bs.ChickBot: return 0.73 elif botType == bs.ChickBotPro: return 0.78 elif botType == bs.ChickBotProShielded: return 0.78 elif botType == bs.NinjaBot: return 1.0 elif botType == bs.NinjaBotProShielded: return 1.0 elif botType == bs.PirateBot: return 1.0 elif botType == bs.MelBot: return 0.5 else: raise Exception('Invalid bot type to _getBotSpeed(): '+str(botType)) def _setCanEndWave(self): self._canEndWave = True
40.894886
80
0.481788
4,104
43,185
5.00731
0.164717
0.030365
0.025109
0.0218
0.37747
0.334015
0.286618
0.276496
0.252117
0.226813
0
0.033733
0.398657
43,185
1,055
81
40.933649
0.757596
0.054232
0
0.383372
0
0.002309
0.08409
0
0
0
0
0.000948
0
0
null
null
0.001155
0.006928
null
null
0.002309
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
1
d93e009b16961979c7713b17f8dc66060f79dd3b
710
py
Python
python/run.py
hguerrero/skupper-example-patient-portal
326afb5c85fedf5e215e0e4f53ba558edba12c8e
[ "Apache-2.0" ]
10
2020-01-22T07:17:46.000Z
2021-11-15T11:12:53.000Z
python/run.py
hguerrero/skupper-example-patient-portal
326afb5c85fedf5e215e0e4f53ba558edba12c8e
[ "Apache-2.0" ]
3
2019-09-26T14:03:29.000Z
2020-04-24T15:44:02.000Z
python/run.py
hguerrero/skupper-example-patient-portal
326afb5c85fedf5e215e0e4f53ba558edba12c8e
[ "Apache-2.0" ]
9
2019-10-08T19:46:34.000Z
2022-03-17T12:13:01.000Z
#!/usr/bin/python3 from plano import * ENV["BACKEND_SERVICE_HOST"] = "localhost" ENV["BACKEND_SERVICE_PORT"] = backend_port = str(get_random_port()) ENV["FRONTEND_SERVICE_PORT"] = frontend_port = str(get_random_port()) backend_url = f"http://localhost:{backend_port}/api/hello" frontend_url = f"http://localhost:{frontend_port}/" with start("python3 backend/app.py") as backend: with start("python3 frontend/app.py") as frontend: sleep(0.5) print(http_get(backend_url)) print(http_get(backend_url)) print(http_get(backend_url)) print(http_get(frontend_url)) print(http_get(frontend_url)) print(http_get(frontend_url)) print("SUCCESS")
28.4
69
0.695775
98
710
4.755102
0.316327
0.11588
0.154506
0.160944
0.386266
0.300429
0.300429
0.300429
0.300429
0.300429
0
0.008432
0.164789
710
24
70
29.583333
0.777403
0.023944
0
0.375
0
0
0.283237
0.030347
0
0
0
0
0
1
0
false
0
0.0625
0
0.0625
0.4375
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
2
d93e597ab6d0aecf326345fbe988189bcd506af5
14,492
py
Python
cfractions/__init__.py
lycantropos/cfractions
22ede26a22786f5480174e2306414ff38f7c7b77
[ "MIT" ]
3
2022-01-18T21:17:17.000Z
2022-01-23T21:49:52.000Z
cfractions/__init__.py
lycantropos/cfractions
22ede26a22786f5480174e2306414ff38f7c7b77
[ "MIT" ]
3
2021-06-28T13:30:58.000Z
2022-01-16T19:05:00.000Z
cfractions/__init__.py
lycantropos/cfractions
22ede26a22786f5480174e2306414ff38f7c7b77
[ "MIT" ]
1
2021-10-22T02:12:06.000Z
2021-10-22T02:12:06.000Z
"""Python C API alternative to `fractions` module.""" __version__ = '1.4.0' try: from _cfractions import Fraction except ImportError: import numbers as _numbers from fractions import Fraction as _Fraction from typing import (Any as _Any, Dict as _Dict, Optional as _Optional, Tuple as _Tuple, TypeVar as _TypeVar, Union as _Union, overload as _overload) _Number = _TypeVar('_Number', bound=_numbers.Number) class Fraction(_Fraction): def limit_denominator(self, max_denominator: int = 10 ** 6 ) -> 'Fraction': result = super().limit_denominator(max_denominator) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) def as_integer_ratio(self) -> _Tuple[int, int]: return self.numerator, self.denominator def __new__(cls, numerator: _Union[int, float] = 0, denominator: _Optional[int] = None, **kwargs) -> 'Fraction': if denominator is not None: if not isinstance(denominator, int): raise TypeError('Denominator should be an integer.') if not isinstance(numerator, int): raise TypeError('Numerator should be an integer ' 'when denominator is specified.') return super().__new__(cls, numerator, denominator, **kwargs) def __abs__(self) -> 'Fraction': result = super().__abs__() return Fraction(result.numerator, result.denominator) @_overload def __add__(self, other: _numbers.Rational) -> 'Fraction': """Returns sum of the fraction with given rational number.""" @_overload def __add__(self, other: _Number) -> _Number: """Returns sum of the fraction with given number.""" def __add__(self, other): result = super().__add__(_Fraction(other) if isinstance(other, _numbers.Rational) else other) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) def __copy__(self) -> 'Fraction': cls = type(self) return (self if cls is Fraction else cls(self._numerator, self._denominator)) def __deepcopy__(self, memo: _Optional[_Dict[int, _Any]] = None ) -> 'Fraction': return self.__copy__() def __divmod__(self, other: _Number ) -> _Tuple[_Number, _Union['Fraction', _Number]]: result = (divmod(float(self), other) if isinstance(other, float) else super().__divmod__(_Fraction(other) if isinstance(other, _numbers.Rational) else other)) return ((result[0], Fraction(result[1].numerator, result[1].denominator) if isinstance(result[1], _numbers.Rational) else result[1]) if isinstance(result, tuple) else result) @_overload def __floordiv__(self, other: _numbers.Rational) -> 'Fraction': """ Returns quotient of division of the fraction by given rational number. """ @_overload def __floordiv__(self, other: _Number) -> _Number: """Returns quotient of division of the fraction by given number.""" def __floordiv__(self, other): result = (float(self) // other if isinstance(other, float) else super().__floordiv__(_Fraction(other) if isinstance(other, _numbers.Rational) else other)) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) @_overload def __mod__(self, other: _numbers.Rational) -> 'Fraction': """ Returns remainder of division of the fraction by given rational number. """ @_overload def __mod__(self, other: _Number) -> _Number: """ Returns remainder of division of the fraction by given number. """ def __mod__(self, other): result = (float(self) % other if isinstance(other, float) else super().__mod__(_Fraction(other) if isinstance(other, _numbers.Rational) else other)) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) @_overload def __mul__(self, other: _numbers.Rational) -> 'Fraction': """Returns product of the fraction with given rational number.""" @_overload def __mul__(self, other: _Number) -> _Number: """Returns product of the fraction with given number.""" def __mul__(self, other): result = super().__mul__(_Fraction(other) if isinstance(other, _numbers.Rational) else other) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) def __neg__(self) -> 'Fraction': result = super().__neg__() return Fraction(result.numerator, result.denominator) def __pos__(self) -> 'Fraction': result = super().__pos__() return Fraction(result.numerator, result.denominator) def __pow__(self, exponent: _numbers.Complex, modulo: _Optional[_numbers.Complex] = None ) -> _numbers.Complex: result = super().__pow__(_Fraction(exponent.numerator, exponent.denominator) if isinstance(exponent, _numbers.Rational) else exponent) if isinstance(result, _numbers.Complex) and modulo is not None: result %= (_Fraction(modulo) if isinstance(modulo, _numbers.Rational) else modulo) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) @_overload def __radd__(self, other: _numbers.Rational) -> 'Fraction': """Returns sum of given rational number with the fraction.""" @_overload def __radd__(self, other: _Number) -> _Number: """Returns sum of given number with the fraction.""" def __radd__(self, other): result = super().__radd__(_Fraction(other) if isinstance(other, _numbers.Rational) else other) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) def __rdivmod__(self, other: _Number ) -> _Tuple[_Number, _Union['Fraction', _Number]]: result = (divmod(other, float(self)) if isinstance(other, float) else super().__rdivmod__(_Fraction(other) if isinstance(other, _numbers.Rational) else other)) return ((result[0], Fraction(result[1].numerator, result[1].denominator) if isinstance(result[1], _numbers.Rational) else result[1]) if isinstance(result, tuple) else result) @_overload def __rfloordiv__(self, other: _numbers.Rational) -> 'Fraction': """ Returns quotient of division of given rational number by the fraction. """ @_overload def __rfloordiv__(self, other: _Number) -> _Number: """Returns quotient of division of given number by the fraction.""" def __rfloordiv__(self, other): result = (other // float(self) if isinstance(other, float) else super().__rfloordiv__(Fraction(other) if isinstance(other, _numbers.Rational) else other)) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) @_overload def __rmod__(self, other: _numbers.Rational) -> 'Fraction': """ Returns remainder of division of given rational number by the fraction. """ @_overload def __rmod__(self, other: _Number) -> _Number: """ Returns remainder of division of given number by the fraction. """ def __rmod__(self, other): result = (other % float(self) if isinstance(other, float) else super().__rmod__(other)) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) @_overload def __rmul__(self, other: _numbers.Rational) -> 'Fraction': """Returns product of given rational number with the fraction.""" @_overload def __rmul__(self, other: _Number) -> _Number: """Returns product of given number with the fraction.""" def __rmul__(self, other): result = super().__rmul__(other) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) def __round__(self, precision: _Optional[int] = None ) -> _Union[int, 'Fraction']: result = super().__round__(precision) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) def __rpow__(self, base: _numbers.Complex, modulo: _Optional[_numbers.Complex] = None ) -> _numbers.Complex: result = (_Fraction(base.numerator, base.denominator).__pow__(self) if isinstance(base, _numbers.Rational) else super().__rpow__(base)) if isinstance(result, _numbers.Complex) and modulo is not None: result %= modulo return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) @_overload def __rsub__(self, other: _numbers.Rational) -> 'Fraction': """ Returns difference of given rational number with the fraction. """ @_overload def __rsub__(self, other: _Number) -> _Number: """Returns difference of given number with the fraction.""" def __rsub__(self, other): result = super().__rsub__(other) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) @_overload def __rtruediv__(self, other: _numbers.Rational) -> 'Fraction': """Returns division of given rational number by the fraction.""" @_overload def __rtruediv__(self, other: _Number) -> _Number: """Returns division of given number by the fraction.""" def __rtruediv__(self, other): result = super().__rtruediv__(other) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) @_overload def __sub__(self, other: _numbers.Rational) -> 'Fraction': """ Returns difference of the fraction with given rational number. """ @_overload def __sub__(self, other: _Number) -> _Number: """Returns difference of the fraction with given number.""" def __sub__(self, other): result = super().__sub__(_Fraction(other) if isinstance(other, _numbers.Rational) else other) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result) @_overload def __truediv__(self, other: _numbers.Rational) -> 'Fraction': """Returns division of the fraction by given rational number.""" @_overload def __truediv__(self, other: _Number) -> _Number: """Returns division of the fraction by given number.""" def __truediv__(self, other): result = super().__truediv__(_Fraction(other) if isinstance(other, _numbers.Rational) else other) return (Fraction(result.numerator, result.denominator) if isinstance(result, _Fraction) else result)
41.405714
79
0.50621
1,215
14,492
5.677366
0.087243
0.071325
0.057408
0.079878
0.766889
0.73891
0.732241
0.652798
0.591041
0.493331
0
0.001992
0.411054
14,492
349
80
41.524355
0.80621
0.100952
0
0.521912
0
0
0.022298
0
0
0
0
0
0
1
0.195219
false
0
0.01992
0.007968
0.318725
0
0
0
0
null
0
0
0
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d93f8a137f8c8b7524ee61b15619bc1ddd81fbf9
1,401
py
Python
src/logistic/logistic_sklearn.py
wenfengand/machine_learning_tools
7233e14ccb2cc32198ee5d73ee2c5952b5947443
[ "MIT" ]
null
null
null
src/logistic/logistic_sklearn.py
wenfengand/machine_learning_tools
7233e14ccb2cc32198ee5d73ee2c5952b5947443
[ "MIT" ]
null
null
null
src/logistic/logistic_sklearn.py
wenfengand/machine_learning_tools
7233e14ccb2cc32198ee5d73ee2c5952b5947443
[ "MIT" ]
null
null
null
import numpy as np import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.preprocessing import LabelBinarizer from sklearn.linear_model.logistic import LogisticRegression from sklearn.model_selection import train_test_split, cross_val_score from sklearn.metrics import classification_report from os.path import dirname, abspath, join PROJECT_ROOT = dirname(dirname(dirname(abspath(__file__)))) INPUT_ROOT = join(PROJECT_ROOT, 'input') SMS_FILE = join(INPUT_ROOT, 'sms', 'SMSSpamCollection') df = pd.read_csv(SMS_FILE, delimiter='\t', header=None) x = df[1].values y = df[0].values x_train_raw, x_test_raw, y_train, y_test = train_test_split(x,y) vectorizer = TfidfVectorizer() x_train = vectorizer.fit_transform(x_train_raw) x_test = vectorizer.transform(x_test_raw) lb = LabelBinarizer() y_train_binarized = lb.fit_transform(y_train) y_test_binarized = lb.transform(y_test) classifier = LogisticRegression() classifier.fit(x_train, y_train_binarized) predictions = classifier.predict(x_test) precisions = cross_val_score(classifier, x_train, y_train_binarized, cv=5, scoring='precision') print('Precisions from cross_val_score', precisions) report = classification_report(y_test_binarized, predictions,\ target_names=['ham', 'spam'], labels=lb.transform(['ham','spam']).reshape(-1)) print('Report from classification_report\n', report)
35.923077
95
0.797288
198
1,401
5.353535
0.368687
0.051887
0.036792
0.018868
0.066038
0
0
0
0
0
0
0.003167
0.098501
1,401
38
96
36.868421
0.836105
0
0
0
0
0
0.082857
0.016429
0
0
0
0
0
1
0
false
0
0.275862
0
0.275862
0.068966
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d941561113d1d4744ab96a504558e7c214535b01
1,289
py
Python
code/curvature_and_offset.py
amoi9/advanced-lane-finding
334ebcee8a232e62aa54ed88190dd2333026112c
[ "MIT" ]
null
null
null
code/curvature_and_offset.py
amoi9/advanced-lane-finding
334ebcee8a232e62aa54ed88190dd2333026112c
[ "MIT" ]
null
null
null
code/curvature_and_offset.py
amoi9/advanced-lane-finding
334ebcee8a232e62aa54ed88190dd2333026112c
[ "MIT" ]
null
null
null
import numpy as np from lane_pixel_finder import find_lane_pixels ''' Calculates the curvature of polynomial functions in meters. ''' # Define conversions in x and y from pixels space to meters ym_per_pix = 30/720 # meters per pixel in y dimension xm_per_pix = 3.7/700 # meters per pixel in x dimension def measure_curvature_real_with_pixels(img_shape, x, y): # Generate x and y values for plotting ploty = np.linspace(0, img_shape[0]-1, img_shape[0]) # Fit a second order polynomial to each using `np.polyfit` fit_cr = np.polyfit(y*ym_per_pix, x*xm_per_pix, 2) # Define y-value where we want radius of curvature # We'll choose the maximum y-value, corresponding to the bottom of the image y_eval = np.max(ploty) ##### calculation of R_curve (radius of curvature) ##### curverad = ((1 + (2*fit_cr[0]*y_eval*ym_per_pix + fit_cr[1])**2)**1.5) / np.absolute(2*fit_cr[0]) return curverad, fit_cr def measure_offset_real(img_shape, left_fit, right_fit): y = ym_per_pix * img_shape[0] l_fitValue = left_fit[0]* y**2 + left_fit[1]*y + left_fit[2] r_fit_Value = right_fit[0]*y**2 + right_fit[1]*y + right_fit[2] lane_center_pos = (l_fitValue + r_fit_Value) /2 return lane_center_pos - img_shape[1] / 2 * xm_per_pix
40.28125
101
0.699767
233
1,289
3.630901
0.364807
0.049645
0.037825
0.037825
0
0
0
0
0
0
0
0.034549
0.191621
1,289
32
102
40.28125
0.777351
0.297905
0
0
0
0
0
0
0
0
0
0
0
1
0.125
false
0
0.125
0
0.375
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d941a0519c73ad134015de68bcfb2d050dd83e9d
816
py
Python
notes/23 - exceptions/basic-input-example.py
hSpiels/ICS3-Python-Notes
5cb06623d6714a62ff20550d635c1fd3f7d27ea2
[ "MIT" ]
3
2022-02-10T19:06:28.000Z
2022-03-25T17:55:56.000Z
notes/23 - exceptions/basic-input-example.py
hSpiels/ICS3-Python-Notes
5cb06623d6714a62ff20550d635c1fd3f7d27ea2
[ "MIT" ]
null
null
null
notes/23 - exceptions/basic-input-example.py
hSpiels/ICS3-Python-Notes
5cb06623d6714a62ff20550d635c1fd3f7d27ea2
[ "MIT" ]
17
2020-09-15T16:40:23.000Z
2022-03-22T17:52:32.000Z
#----------------------------------------------------------------------------- # Name: Catching Exceptions (try-except.py) # Purpose: To provide example of a simple input loop using try-catch # # Author: Mr. Brooks # Created: 01-Oct-2020 # Updated: 01-March-2021 #----------------------------------------------------------------------------- while True: #Start an infinite loop value = input('Enter a number between -100 and 100: ') #Get a value from the user try: value = int(value) #Convert the value to an int except Exception as err: print(f'Something went wrong: {err}') #You should probably add a nicer error message else: #No exception was thrown, so break out of the infinite loop break print (value)
32.64
92
0.502451
93
816
4.408602
0.709677
0.058537
0
0
0
0
0
0
0
0
0
0.029221
0.245098
816
25
93
32.64
0.636364
0.645833
0
0
0
0
0.231047
0
0
0
0
0
0
1
0
false
0
0
0
0
0.222222
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d942a04ced23f92091eda9000046982c5f7f347a
306
py
Python
routers/repo/tests/in/py/sample_projects/car/rear_suspension_assembly.py
fermiumlabs/gitea
34b1f2546b306f15c65f21d8f9629507d3fdd798
[ "MIT" ]
1
2020-10-08T14:14:52.000Z
2020-10-08T14:14:52.000Z
routers/repo/tests/in/py/sample_projects/car/rear_suspension_assembly.py
fermiumlabs/gitea
34b1f2546b306f15c65f21d8f9629507d3fdd798
[ "MIT" ]
null
null
null
routers/repo/tests/in/py/sample_projects/car/rear_suspension_assembly.py
fermiumlabs/gitea
34b1f2546b306f15c65f21d8f9629507d3fdd798
[ "MIT" ]
null
null
null
# coding: utf-8 r"""Tabby rear suspension assembly""" from car_assemblies import make_rear_suspension_assembly from osvcad.view import view_assembly, view_assembly_graph assembly = make_rear_suspension_assembly() if __name__ == "__main__": view_assembly(assembly) view_assembly_graph(assembly)
23.538462
58
0.803922
40
306
5.625
0.475
0.213333
0.293333
0.231111
0.293333
0
0
0
0
0
0
0.003717
0.120915
306
12
59
25.5
0.832714
0.147059
0
0
0
0
0.031373
0
0
0
0
0
0
1
0
false
0
0.285714
0
0.285714
0
0
0
0
null
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
d944f0a9c7214dc418886b1718145909d59eb408
2,791
py
Python
python_examples/example_truncated_normal.py
KristerSJakobsson/pygosolnp
5a890d67782ff04f521644daeaef2f7708959e79
[ "BSL-1.0" ]
null
null
null
python_examples/example_truncated_normal.py
KristerSJakobsson/pygosolnp
5a890d67782ff04f521644daeaef2f7708959e79
[ "BSL-1.0" ]
null
null
null
python_examples/example_truncated_normal.py
KristerSJakobsson/pygosolnp
5a890d67782ff04f521644daeaef2f7708959e79
[ "BSL-1.0" ]
null
null
null
############################ # This example shows how to run pygosolnp with Truncated Normal distribution using Numpy and Scipy ############################ from typing import List, Optional # Numpy random has the PCG64 generator which according to some research is better than Mersenne Twister from numpy.random import Generator, PCG64 # Note that this script depends on scipy, which is not a requirement for pygosolnp from scipy.stats import truncnorm import pygosolnp # The Sampling class is an abstract class that can be inherited and customized as you please class TruncatedNormalSampling(pygosolnp.sampling.Sampling): def __init__(self, parameter_lower_bounds: List[float], parameter_upper_bounds: List[float], seed: Optional[int]): self.__generator = Generator(PCG64(seed)) self.__parameter_lower_bounds = parameter_lower_bounds self.__parameter_upper_bounds = parameter_upper_bounds def generate_sample(self, sample_size: int) -> List[float]: # This function returns random starting values for one sample return truncnorm.rvs(a=self.__parameter_lower_bounds, b=self.__parameter_upper_bounds, size=sample_size, random_state=self.__generator) # The Permutation Function has unique solution f(x) = 0 when x_i = i def permutation_function(data): n = 4 b = 0.5 result1 = 0 for index1 in range(1, n + 1): result2 = 0 for index2 in range(1, n + 1): result2 += ((pow(index2, index1) + b) * (pow(data[index2 - 1] / index2, index1) - 1)) result1 += pow(result2, 2) return result1 parameter_lower_bounds = [-4.0] * 4 parameter_upper_bounds = [4.0] * 4 if __name__ == '__main__': # Instantiate sampling object sampling = TruncatedNormalSampling( parameter_lower_bounds=parameter_lower_bounds, parameter_upper_bounds=parameter_upper_bounds, seed=99) # Note that the seed variable to pygosolnp.solve is ignored due to the custom sampling results = pygosolnp.solve( obj_func=permutation_function, par_lower_limit=parameter_lower_bounds, par_upper_limit=parameter_upper_bounds, number_of_restarts=6, number_of_simulations=20000, pysolnp_max_major_iter=25, pysolnp_tolerance=1E-9, start_guess_sampling=sampling) print(results.best_solution) # Best solution: [2.651591117309446, 1.7843343303461394, 3.8557508243271172, 2.601788248290573] # Objective function value: 101.48726054338877 # Not very good, the truncated normal function has generated samples that are mostly close to 0 # This is not very good for the permutation function
36.723684
103
0.685776
348
2,791
5.272989
0.431034
0.061035
0.087193
0.039237
0.105722
0.105722
0
0
0
0
0
0.062384
0.230383
2,791
75
104
37.213333
0.791899
0.320315
0
0
0
0
0.004376
0
0
0
0
0
0
1
0.068182
false
0
0.090909
0.022727
0.227273
0.022727
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d945a72b8bcb11f20ef8799e856a5654994ffaeb
3,197
py
Python
opengenomebrowser_tools/rename_custom_annotations.py
opengenomebrowser/opengenomebrowser-tools
b6ef2340b2fd67a61373d1d8a0f3ef71cc892d1e
[ "MIT" ]
null
null
null
opengenomebrowser_tools/rename_custom_annotations.py
opengenomebrowser/opengenomebrowser-tools
b6ef2340b2fd67a61373d1d8a0f3ef71cc892d1e
[ "MIT" ]
null
null
null
opengenomebrowser_tools/rename_custom_annotations.py
opengenomebrowser/opengenomebrowser-tools
b6ef2340b2fd67a61373d1d8a0f3ef71cc892d1e
[ "MIT" ]
null
null
null
from .utils import GenomeFile, split_locus_tag class CustomAnnotationFile(GenomeFile): def __init__(self, file: str, original_path: str = None, custom_annotation_type: str = None): if custom_annotation_type: self.custom_annotation_type = custom_annotation_type else: self.custom_annotation_type = file.rsplit('.', 1)[-1] super().__init__(file=file, original_path=original_path) def rename(self, out: str, new_locus_tag_prefix: str, old_locus_tag_prefix: str = None, validate: bool = False) -> None: old_locus_tag_prefix = self._pre_rename_check(out, new_locus_tag_prefix, old_locus_tag_prefix) with open(self.path) as in_f: content = in_f.readlines() def rename_line(line: str): assert line.startswith(old_locus_tag_prefix), f'custom_annotations_file line does not contain old_locus_tag_prefix!' \ f'{old_locus_tag_prefix=}, {line=}, {self.path=}' return line.replace(old_locus_tag_prefix, new_locus_tag_prefix, 1) content = [rename_line(line) for line in content] with open(out, 'w') as out_f: out_f.writelines(content) self.path = out if validate: self.validate_locus_tags(locus_tag_prefix=new_locus_tag_prefix) def detect_locus_tag_prefix(self) -> str: with open(self.path) as f: line = f.readline() locus_tag = line.split('\t', 1)[0] locus_tag_prefix, gene_id = split_locus_tag(locus_tag) assert gene_id.isdigit(), f'locus_tag in {self.path=} is malformed. expected: {locus_tag_prefix}_[0-9]+ reality: {locus_tag}' return locus_tag_prefix def validate_locus_tags(self, locus_tag_prefix: str = None): if locus_tag_prefix is None: locus_tag_prefix = self.detect_locus_tag_prefix() with open(self.path) as f: for line in f: locus_tag = line.split('\t')[0] real_locus_tag_prefix, gene_id = split_locus_tag(locus_tag) assert real_locus_tag_prefix == locus_tag_prefix, \ f'locus_tag_prefix in {self.path=} does not match. expected: {locus_tag_prefix} reality: {real_locus_tag_prefix}' assert gene_id.isdigit(), f'locus_tag in {self.path=} is malformed. expected: {locus_tag_prefix}_[0-9]+ reality: {locus_tag}' def rename_custom_annotations(file: str, out: str, new_locus_tag_prefix: str, old_locus_tag_prefix: str = None, validate: bool = False): """ Change the locus tags in a custom annotations file :param file: input file :param out: output file :param new_locus_tag_prefix: desired locus tag :param old_locus_tag_prefix: locus tag to replace :param validate: if true, perform sanity check """ CustomAnnotationFile( file=file ).rename( out=out, new_locus_tag_prefix=new_locus_tag_prefix, old_locus_tag_prefix=old_locus_tag_prefix, validate=validate ) def main(): import fire fire.Fire(rename_custom_annotations) if __name__ == '__main__': main()
38.059524
141
0.657804
436
3,197
4.451835
0.190367
0.197836
0.252447
0.096342
0.399279
0.32406
0.313756
0.265842
0.205049
0.205049
0
0.004174
0.250547
3,197
83
142
38.518072
0.805927
0.076009
0
0.075472
0
0.056604
0.147019
0.048321
0
0
0
0
0.075472
1
0.132075
false
0
0.037736
0
0.226415
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
d945b415451fdc9d37b82bd626b439e042bbaee1
11,757
py
Python
SAM/Classifiers/classifier_svm.py
lucaspuvis/SAM
159427d0b2a7fdd353b96c13085f926df096f309
[ "CC-BY-4.0" ]
3
2019-05-14T17:22:54.000Z
2020-07-05T15:39:11.000Z
SAM/Classifiers/classifier_svm.py
lucaspuvis/SAM
159427d0b2a7fdd353b96c13085f926df096f309
[ "CC-BY-4.0" ]
null
null
null
SAM/Classifiers/classifier_svm.py
lucaspuvis/SAM
159427d0b2a7fdd353b96c13085f926df096f309
[ "CC-BY-4.0" ]
null
null
null
import argparse, joblib, csv, sys, os import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches import pandas as pd from mpl_toolkits.mplot3d import Axes3D from yellowbrick.text import TSNEVisualizer from sklearn.cluster import KMeans from sklearn.svm import SVC, LinearSVC from sklearn.pipeline import Pipeline from sklearn.decomposition import PCA from sklearn.metrics import confusion_matrix, f1_score from sklearn.model_selection import train_test_split, StratifiedKFold, GridSearchCV, learning_curve from sklearn.feature_extraction.text import TfidfVectorizer ''' SVM classifier ''' # GLOBALS # Paths dir_path = os.path.dirname(os.path.realpath(__file__)) data_path = dir_path + '/TrainingData/training_data_all.csv' test_data_path = dir_path + '/TrainingData/HypothesisData.csv' model_path = dir_path + '/Model/svm_pipeline.joblib' stop_words_path = dir_path + '/TrainingData/stop_words_da.txt' # Rest # Train our SVM model def train_model(X, y, auto_split=False): # Create data processing and classifier pipeline svm_pipeline = Pipeline([ ('tfidf', TfidfVectorizer(ngram_range=(1,10), analyzer='char_wb', stop_words=load_stop_words(), use_idf=False, smooth_idf=True, sublinear_tf=False )), ('svm', LinearSVC(C=3)) ]) # Parameters for Grid Search. This is used for finding the best values for processing and classifying parameters = {#'tfidf__stop_words':(load_stop_words(), None), # 'tfidf__smooth_idf':(True, False), # 'tfidf__sublinear_tf':(True, False), } out = open('svm_f1score.txt', 'w+') X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1) skf = StratifiedKFold(4, True) if auto_split is True: X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1) clf = GridSearchCV(svm_pipeline, parameters, cv=skf.split(X_train, y_train), verbose=2, return_train_score=True, n_jobs=-1) clf.fit(X_train, y_train) clf = clf.best_estimator_ cm = confusion_matrix(y_test, clf.predict(X_test)) plt.figure() plot_confusion_matrix(cm) y_pred = clf.predict(X_test) f_score = f1_score(y_true=y_test, y_pred=y_pred, average='weighted') score = clf.score(X_test, y_test) out.write('{}, {}\n'.format(score, f_score)) else: clf = GridSearchCV(svm_pipeline, parameters, cv=skf.split(X, y), verbose=2, return_train_score=True, n_jobs=-1) X_test, y_test = load_test_dataset(squish_classes=True) clf.fit(X, y) clf = clf.best_estimator_ cm = confusion_matrix(y_test, clf.predict(X_test)) plot_confusion_matrix(cm) svm_score = clf.score(X_test, y_test) y_pred = clf.predict(X_test) f_score = f1_score(y_true=y_test, y_pred=y_pred, average='weighted') out.write('{}, {}\n'.format(svm_score, f_score)) print(cm) print('SVM Accuracy: {}'.format(round(svm_score*100, 4))) print('SVM F1 Score: {}'.format(round(f_score*100, 4))) joblib.dump(clf, model_path) return clf def load_dataset(encoding='utf8', squish_classes=True): ''' Loads training data and splits it into test and train sets Parameters ----------- encoding: The encoding of the file loaded. Default is UTF-8 Returns ------- X: The sentences, y: The labels ''' csv_reader = csv.reader(open(data_path, encoding=encoding)) X, y = [], [] # Saving comments and likes in seperate lists for row in csv_reader: X.append(row[1]) if squish_classes: if int(row[0]) < 0: y.append(-1) elif int(row[0]) > 0: y.append(1) else: y.append(0) else: y.append(row[0]) y = np.asarray(y) X = np.asarray(X) return X, y def load_test_dataset(encoding='utf-8-sig', squish_classes=True): ''' Loads training data and splits it into test and train sets Parameters ----------- encoding: The encoding of the file loaded. Default is UTF-8 Returns ------- X: The sentences, y: The labels ''' csv_reader = csv.reader(open(test_data_path, encoding=encoding)) X, y = [], [] # Saving comments and likes in seperate lists for row in csv_reader: X.append(row[1]) if squish_classes: if int(row[0]) < 0: y.append(-1) elif int(row[0]) > 0: y.append(1) else: y.append(0) else: y.append(row[0]) y = np.asarray(y) X = np.asarray(X) return X, y # Get list of stop words def load_stop_words(): stop_words = [] stop_words_list = open(stop_words_path, 'r') for word in stop_words_list.readlines(): stop_words.append(word.replace('\n', '')) return stop_words # <----------------------> # <- PLOTTING FUNCTIONS -> # <----------------------> def plot_data_2d(X_transformed, y): # PCA data2D = PCA(n_components=3).fit_transform(X_transformed.todense()) # Plot the datapoints with different colors depending on label for i in range(0, len(data2D)): if int(y[i]) < 0: plt.plot(data2D[i, 0], data2D[i, 1], "yo") elif int(y[i]) == 0: plt.plot(data2D[i, 0], data2D[i, 1], "bo") else: plt.plot(data2D[i, 0], data2D[i, 1], "co") # Labels for the plot negative_plt = mpatches.Patch(color='yellow', label='Negative') neutral_plt = mpatches.Patch(color='blue', label='Neutral') positive_plt = mpatches.Patch(color='cyan', label='Positive') plt.legend(handles=[positive_plt, neutral_plt, negative_plt]) plt.show() def plot_data_3d(X_transformed, y): ''' Loads training data and splits it into test and train sets Parameters ----------- X_transformed: The corpus transformed to a feature space, y: The labels ''' fig = plt.figure() ax = fig.add_subplot(111, projection='3d') data3d = PCA(n_components=3).fit_transform(X_transformed.todense()) # data3d = TSNE(n_components=3).fit_transform(X_transformed.todense()) # neg_xs, neg_ys, neg_zs = [], [], [] neu_xs, neu_ys, neu_zs = [], [], [] pos_xs, pos_ys, pos_zs = [], [], [] for i in range(0, len(y)): if y[i] < 0: neg_xs.append(data3d[i, 0]) neg_ys.append(data3d[i, 1]) neg_zs.append(data3d[i, 2]) if y[i] == 0: neu_xs.append(data3d[i, 0]) neu_ys.append(data3d[i, 1]) neu_zs.append(data3d[i, 2]) else: pos_xs.append(data3d[i, 0]) pos_ys.append(data3d[i, 1]) pos_zs.append(data3d[i, 2]) ax.scatter(neg_xs, neg_ys, neg_zs, c='b') ax.scatter(neu_xs, neu_ys, neu_zs, c='r') ax.scatter(pos_xs, pos_ys, pos_zs, c='g') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') def plot_confusion_matrix(cm, title='SVM Confusion matrix', cmap=plt.get_cmap('Blues')): plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(3) plt.xticks(tick_marks, [-1, 0, 1], rotation=45) plt.yticks(tick_marks, [-1, 0, 1]) plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') plt.show() # From https://scikit-learn.org/stable/auto_examples/model_selection/plot_learning_curve.html#sphx-glr-auto-examples-model-selection-plot-learning-curve-py def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, n_jobs=None, train_sizes=np.linspace(.1, 1.0, 10)): """ Generate a simple plot of the test and training learning curve. Parameters ---------- estimator : object type that implements the "fit" and "predict" methods An object of that type which is cloned for each validation. title : string Title for the chart. X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape (n_samples) or (n_samples, n_features), optional Target relative to X for classification or regression; None for unsupervised learning. ylim : tuple, shape (ymin, ymax), optional Defines minimum and maximum yvalues plotted. cv : int, cross-validation generator or an iterable, optional Determines the cross-validation splitting strategy. Possible inputs for cv are: - None, to use the default 3-fold cross-validation, - integer, to specify the number of folds. - :term:`CV splitter`, - An iterable yielding (train, test) splits as arrays of indices. For integer/None inputs, if ``y`` is binary or multiclass, :class:`StratifiedKFold` used. If the estimator is not a classifier or if ``y`` is neither binary nor multiclass, :class:`KFold` is used. Refer :ref:`User Guide <cross_validation>` for the various cross-validators that can be used here. n_jobs : int or None, optional (default=None) Number of jobs to run in parallel. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. train_sizes : array-like, shape (n_ticks,), dtype float or int Relative or absolute numbers of training examples that will be used to generate the learning curve. If the dtype is float, it is regarded as a fraction of the maximum size of the training set (that is determined by the selected validation method), i.e. it has to be within (0, 1]. Otherwise it is interpreted as absolute sizes of the training sets. Note that for classification the number of samples usually have to be big enough to contain at least one sample from each class. (default: np.linspace(0.1, 1.0, 5)) """ plt.figure() plt.title(title) if ylim is not None: plt.ylim(*ylim) plt.xlabel("Training examples") plt.ylabel("Score") train_sizes, train_scores, test_scores = learning_curve( estimator, X, y, cv=8, n_jobs=n_jobs, train_sizes=train_sizes) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) test_scores_mean = np.mean(test_scores, axis=1) test_scores_std = np.std(test_scores, axis=1) plt.grid() plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.1, color="r") plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.1, color="g") plt.plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training score") plt.plot(train_sizes, test_scores_mean, 'o-', color="g", label="Cross-validation score") plt.legend(loc="best") return plt # <----------------------> # <- SCRIPT STARTS HERE -> # <----------------------> # Train model first time X, y = load_dataset(squish_classes=True) pipeline = train_model(X, y, auto_split=False) X_transformed = pipeline.named_steps['tfidf'].transform(X) # tsne = TSNEVisualizer() # tsne.fit(X_transformed, y) # tsne.poof()
34.377193
155
0.623969
1,653
11,757
4.266788
0.238355
0.017865
0.016589
0.008507
0.346519
0.279314
0.243017
0.216929
0.207571
0.171558
0
0.015014
0.25219
11,757
341
156
34.478006
0.787193
0.316662
0
0.278689
0
0
0.054536
0.01614
0
0
0
0
0
1
0.043716
false
0
0.076503
0
0.147541
0.016393
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d94612c9ae12b600bebba592477a727af83fa451
951
py
Python
unityparser/composer.py
socialpoint-labs/unity-yaml-parser
91c175140ed32aed301bc34d4311f370da69a8ba
[ "MIT" ]
76
2019-06-17T13:17:59.000Z
2022-03-11T19:39:24.000Z
unityparser/composer.py
socialpoint-labs/unity-yaml-parser
91c175140ed32aed301bc34d4311f370da69a8ba
[ "MIT" ]
17
2019-06-07T09:04:27.000Z
2022-02-16T19:01:38.000Z
unityparser/composer.py
socialpoint-labs/unity-yaml-parser
91c175140ed32aed301bc34d4311f370da69a8ba
[ "MIT" ]
9
2019-10-08T16:07:35.000Z
2021-12-08T15:27:00.000Z
from yaml.composer import Composer as YamlComposer, ComposerError class Composer(YamlComposer): def compose_document(self): # Drop the DOCUMENT-START event. self.get_event() # UNITY: used to store data after the anchor self.extra_anchor_data = {} # Compose the root node. node = self.compose_node(None, None) # Drop the DOCUMENT-END event. self.get_event() # UNITY: prevent reset anchors after document end so we can access them on constructors # self.anchors = {} return node def get_anchor_from_node(self, node): for k, v in self.anchors.items(): if node == v: return k raise ComposerError("Expected anchor to be present for node") def get_extra_anchor_data_from_node(self, anchor): if anchor in self.extra_anchor_data: return self.extra_anchor_data[anchor] return ''
28.818182
95
0.635121
122
951
4.803279
0.409836
0.075085
0.102389
0.09727
0.075085
0
0
0
0
0
0
0
0.293375
951
32
96
29.71875
0.872024
0.240799
0
0.117647
0
0
0.053147
0
0
0
0
0
0
1
0.176471
false
0
0.058824
0
0.529412
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
d948e42d9fe9ba9b6716af9941792faae40da7f8
1,164
py
Python
build.py
2-propanol/BTF_extractor
0ec5358504ab51aff6256b98f51d29e540012ce8
[ "Zlib" ]
1
2022-02-16T14:53:26.000Z
2022-02-16T14:53:26.000Z
build.py
2-propanol/BTF_extractor
0ec5358504ab51aff6256b98f51d29e540012ce8
[ "Zlib" ]
1
2021-02-05T10:04:20.000Z
2021-04-11T13:45:01.000Z
build.py
2-propanol/BTF_extractor
0ec5358504ab51aff6256b98f51d29e540012ce8
[ "Zlib" ]
1
2021-02-04T04:22:19.000Z
2021-02-04T04:22:19.000Z
import platform from setuptools import Extension import numpy from Cython.Build import cythonize compile_args = [] link_args = [] pf = platform.system() if pf == "Windows": # for MSVC compile_args = ["/std:c++14", "/DNOMINMAX", "/O2", "/openmp"] elif pf == "Darwin": # for clang compile_args = ["-std=c++14", "-O2", "-march=native", "-Xpreprocessor", "-fopenmp"] link_args = ["-lomp"] elif pf == "Linux": # for gcc compile_args = ["-std=c++14", "-Ofast", "-march=native", "-fopenmp"] link_args = ["-fopenmp"] ext_modules = [ Extension( name="ubo2014_cy", sources=["btf_extractor/ubo2014.pyx"], include_dirs=[numpy.get_include(), "btf_extractor/c_ext"], define_macros=[("BTF_IMPLEMENTATION", "1"), ("NPY_NO_DEPRECATED_API", "1")], extra_compile_args=compile_args, extra_link_args=link_args, language="c++", ) ] def build(setup_kwargs): """ This function is mandatory in order to build the extensions. """ setup_kwargs.update( {"ext_modules": cythonize(ext_modules)} ) return setup_kwargs if __name__ == "__main__": build({})
24.25
87
0.617698
139
1,164
4.899281
0.517986
0.096916
0.061674
0.066079
0.07489
0
0
0
0
0
0
0.019672
0.213918
1,164
47
88
24.765957
0.72459
0.075601
0
0
0
0
0.248582
0.043478
0
0
0
0
0
1
0.030303
false
0
0.121212
0
0.181818
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d948fa8ba6380df2f7107ace914fc0822327e5fa
3,802
py
Python
apps/users/views.py
fangMint/django_web
cf50df6c1a2358996620ac83ffa99b31472d3c07
[ "AFL-3.0" ]
null
null
null
apps/users/views.py
fangMint/django_web
cf50df6c1a2358996620ac83ffa99b31472d3c07
[ "AFL-3.0" ]
null
null
null
apps/users/views.py
fangMint/django_web
cf50df6c1a2358996620ac83ffa99b31472d3c07
[ "AFL-3.0" ]
1
2021-11-22T10:15:50.000Z
2021-11-22T10:15:50.000Z
import logging from django.views import View from .models import Users, Tokens from libs.response_extra import response_failure, response_success, user_does_not_exists, view_exception from libs.tool_decorator import cvb_params from .decorator import cvb_token_check log = logging.getLogger(__name__) class LoginView(View): @cvb_params(POST_BODY=["account", "password"]) def post(self, request, body_params): try: request_body = request.headers recv_token = request_body["Token"] login_type = request_body["platform"] if "platform" in request_body else 1 # 1是网页端 account = body_params['account'] password = body_params['password'] if recv_token == "none": # 不存在token才登录,“none”是前端兼容IE浏览器 user_m = Users.objects.filter(account=account).first() if user_m: if user_m.permission: # 验证是否允许登录 if user_m.authentication(password): # 验证密码 token = Tokens.objects.token_create(user_m.id, login_type) data = { "account": account, "userType": user_m.user_type, "name": user_m.name, "portrait": user_m.portrait, "token": token } return response_success(msg="登录成功", code=0, data=data) return response_failure(msg='密码错误,请重新输入', code=6) return response_failure(msg='用户被禁止登录', code=7) return response_failure(msg="账号不存在", code=5) return response_failure(msg="携带token登录", code=4) except BaseException as err: log.error(f"登录接口异常 {err}") class LogoutView(View): @cvb_token_check def get(self, request, user_id): request_body = request.headers recv_token = request_body["Token"] token_m = Tokens.objects.filter(user_id=user_id, token=recv_token).first() if token_m: token_m.delete() return response_success(msg="退出成功") class RegisterView(View): @cvb_params(POST_BODY=['userType', 'name', 'account', 'password', 'email', 'gender', 'portrait']) def post(self, request, body_params): Users.objects.user_create( name=body_params["name"], account=body_params["account"], password=body_params["password"], gender=body_params["gender"], email=body_params["email"], portrait=body_params["portrait"], user_type=body_params["userType"], ) return response_success(msg="添加用户成功") class ModifyPasswordView(View): @cvb_token_check @cvb_params(POST_BODY=["oldPassword", "newPassword"]) def post(self, request, user_id, params): """ { "oldPassword":"123456", "newPassword":"1q2w3e4r" } """ try: user = Users.objects.filter(id=user_id).first() if user: if user.authentication(params["oldPassword"]): user.password = user.encryption(params["newPassword"]) user.save() return response_success(msg="密码修改成功", code=0) return response_failure(msg='旧密码错误,请重新输入', code=6) return user_does_not_exists() except BaseException as err: log.error(err) return view_exception() """ 注册: { "userType": 2, "name": "rocky_admin", "account": "13002111111", "password": "1q2w3e4r", "email":"rocky_admin@163com", "gender": 1, "portrait": "www.baidu.com" } 登录: { "account": "13002111111", "password": "1q2w3e4r" } """
33.946429
104
0.572593
399
3,802
5.24812
0.280702
0.052531
0.050143
0.057307
0.172875
0.152818
0.095511
0.095511
0.047755
0
0
0.020626
0.311415
3,802
112
105
33.946429
0.779221
0.026828
0
0.162162
0
0
0.088382
0
0
0
0
0
0
1
0.054054
false
0.121622
0.081081
0
0.337838
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
d94b812ea86c3f0c6f03bfe005b3691242fb682f
1,871
py
Python
src/compas_plotters/artists/circleartist.py
XingxinHE/compas
d2901dbbacdaf4694e5adae78ba8f093f10532bf
[ "MIT" ]
null
null
null
src/compas_plotters/artists/circleartist.py
XingxinHE/compas
d2901dbbacdaf4694e5adae78ba8f093f10532bf
[ "MIT" ]
null
null
null
src/compas_plotters/artists/circleartist.py
XingxinHE/compas
d2901dbbacdaf4694e5adae78ba8f093f10532bf
[ "MIT" ]
null
null
null
from compas_plotters.artists import Artist from matplotlib.patches import Circle as CirclePatch # from matplotlib.transforms import ScaledTranslation __all__ = ['CircleArtist'] class CircleArtist(Artist): """""" zorder = 1000 def __init__(self, circle, linewidth=1.0, linestyle='solid', facecolor=(1.0, 1.0, 1.0), edgecolor=(0, 0, 0), fill=True, alpha=1.0): super(CircleArtist, self).__init__(circle) self._mpl_circle = None self.circle = circle self.linewidth = linewidth self.linestyle = linestyle self.facecolor = facecolor self.edgecolor = edgecolor self.fill = fill self.alpha = alpha @property def data(self): points = [ self.circle.center[:2], self.circle.center[:2], self.circle.center[:2], self.circle.center[:2] ] points[0][0] -= self.circle.radius points[1][0] += self.circle.radius points[2][1] -= self.circle.radius points[3][1] += self.circle.radius return points def update_data(self): self.plotter.axes.update_datalim(self.data) def draw(self): circle = CirclePatch( self.circle.center[:2], linewidth=self.linewidth, linestyle=self.linestyle, radius=self.circle.radius, facecolor=self.facecolor, edgecolor=self.edgecolor, fill=self.fill, zorder=self.zorder ) self._mpl_circle = self.plotter.axes.add_artist(circle) self.update_data() def redraw(self): self._mpl_circle.center = self.circle.center[:2] self._mpl_circle.set_radius(self.circle.radius) self._mpl_circle.set_edgecolor(self.edgecolor) self._mpl_circle.set_facecolor(self.facecolor) self.update_data()
30.672131
135
0.611438
217
1,871
5.119816
0.230415
0.135014
0.070207
0.091809
0.121512
0.061206
0.061206
0.061206
0.061206
0.061206
0
0.022794
0.273116
1,871
60
136
31.183333
0.794118
0.027258
0
0.122449
0
0
0.009382
0
0
0
0
0
0
1
0.102041
false
0
0.040816
0
0.204082
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d94bae590f7b253620b6f2a82a919c8745ff9eb2
1,044
py
Python
SortedPriorityQueue.py
sidhu177/pythonprog
a75285e9e4d3cd6f1257b9a79dc39e49c68a695d
[ "MIT" ]
2
2019-05-01T04:32:07.000Z
2019-05-04T02:22:16.000Z
SortedPriorityQueue.py
sidhu177/pythonprog
a75285e9e4d3cd6f1257b9a79dc39e49c68a695d
[ "MIT" ]
null
null
null
SortedPriorityQueue.py
sidhu177/pythonprog
a75285e9e4d3cd6f1257b9a79dc39e49c68a695d
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Tue Sep 18 21:06:14 2018 Taken from Data Structures and Algorithms using Python """ class SortedPriorityQueue(PriorityQueueBase): def __init__(self): self._data = PositionalList() def __len__(self): return len(self._data) def add(self,key,value): newest = self._Item(key,value) walk = self._data.last() while walk is not None and newest < walk.element(): walk = self._data.before(walk) if walk is None: self._data.add_first(newest) else: self._data.add_after(walk,newest) def min(self): if self.is_empty(): raise Empty('Priority Queue is empty') p = self._data.first() item = p.element() return (item._key,item._value) def remove_min(self): if self.is_empty(): raise Empty('Priority queue is empty') item =self._data.delete(self._data.first()) return (item._key, item._value)
29
59
0.579502
131
1,044
4.412214
0.412214
0.124567
0.041522
0.044983
0.249135
0.17301
0.17301
0.17301
0.17301
0.17301
0
0.017956
0.306513
1,044
36
60
29
0.780387
0.109195
0
0.16
0
0
0.049837
0
0
0
0
0
0
1
0.2
false
0
0
0.04
0.36
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d94bb0c3552420db1ae043fe4832aefa03e3c1f7
14,576
py
Python
f5/utils/test/test_iapp_parser.py
jputrino/f5-common-python
64cd019eb22b0e9a49e0c49ebb05f2a23ffa0e49
[ "Apache-2.0" ]
null
null
null
f5/utils/test/test_iapp_parser.py
jputrino/f5-common-python
64cd019eb22b0e9a49e0c49ebb05f2a23ffa0e49
[ "Apache-2.0" ]
null
null
null
f5/utils/test/test_iapp_parser.py
jputrino/f5-common-python
64cd019eb22b0e9a49e0c49ebb05f2a23ffa0e49
[ "Apache-2.0" ]
null
null
null
# Copyright 2016 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from f5.utils import iapp_parser as ip import pytest good_templ = '''sys application template good_templ { actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } presentation { # APL presentation language } role-acl { hello test } run-as <user context> } } description <template description> partition <partition name> requires-modules { ltm } }''' brace_in_quote_templ = '''sys application template good_templ { actions { definition { html-help { # HTML Help for "" the template } implementation { # TMSH"{}{{}}}}}""{{{{}}"implementation code } presentation { # APL"{}{}{{{{{{" presentation language } role-acl { hello test } run-as <user context> } } description <template description> partition <partition name> requires-modules { ltm } }''' no_desc_templ = '''sys application template good_templ { actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } presentation { # APL presentation language } role-acl { hello test } run-as <user context> } } partition <partition name> requires-modules { ltm } }''' empty_rm_templ = '''sys application template good_templ { actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } presentation { # APL presentation language } role-acl { hello test } run-as <user context> } } partition <partition name> requires-modules { } }''' whitespace_rm_templ = '''sys application template good_templ { actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } presentation { # APL presentation language } role-acl { hello test } run-as <user context> } } partition <partition name> requires-modules {} }''' none_rm_templ = '''sys application template good_templ { actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } presentation { # APL presentation language } role-acl { hello test } run-as <user context> } } partition <partition name> requires-modules none }''' no_open_brace_templ = '''sys application template no_open_brace_templ { actions { definition { html-help # HTML Help for the template } implementation { # TMSH implementation code } presentation { # APL presentation language } role-acl {security role} run-as <user context> } } description <template description> partition <partition name> }''' no_close_brace_templ = '''sys application template no_close_brace_template { actions { definition { html-help { # HTML Help for the template # Missing closing braces implementation { # TMSH implementation code ''' no_pres_templ = '''sys application template no_pres_templ { actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } role-acl {<security role>} run-as <user context> } } description <template description> partition <partition name> }''' no_name_templ = '''sys application template { actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } run-as <user context> } } description <template description> partition <partition name> }''' bad_name_templ = '''sys application template bad#updown { actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } role-acl {<security role>} run-as <user context> } } description <template description> partition <partition name> }''' name_brace_templ = '''sys application template name_next_to_brace{ actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } role-acl {security role} run-as <user context> } } description <template description> partition <partition name> }''' good_attr_templ = '''sys application template good_templ { actions { definition { html-help {} implementation {} presentation {} } } description <template description> partition just_a_partition name }''' no_help_templ = '''sys application template good_templ { actions { definition { implementation { # TMSH implementation code } presentation { # APL presentation language } role-acl { hello test } run-as <user context> } } description <template description> partition <partition name> requires-modules { ltm asm } }''' dot_name_templ = '''sys application template good.dot.templ { actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } presentation { # APL presentation language } role-acl { hello test } run-as <user context> } } description <template description> partition <partition name> requires-modules { ltm } }''' dot_hyphen_name_templ = '''sys application template good.-dot-hyphen.-templ { actions { definition { html-help { # HTML Help for the template } implementation { # TMSH implementation code } presentation { # APL presentation language } role-acl { hello test } run-as <user context> } } description <template description> partition <partition name> requires-modules { ltm } }''' good_templ_dict = { u'name': u'good_templ', u'description': u'<template description>', u'partition': u'<partition name>', u'requiresModules': [u'ltm'], 'actions': { 'definition': { u'htmlHelp': u'# HTML Help for the template', u'roleAcl': [u'hello', u'test'], u'implementation': u'# TMSH implementation code', u'presentation': u'# APL presentation language' } } } brace_in_quote_templ_dict = { u'name': u'good_templ', u'description': u'<template description>', u'partition': u'<partition name>', u'requiresModules': [u'ltm'], 'actions': { 'definition': { u'htmlHelp': u'# HTML Help for "" the template', u'roleAcl': [u'hello', u'test'], u'implementation': u'# TMSH"{}{{}}}}}""{{{{}}"implementation code', u'presentation': u'# APL"{}{}{{{{{{" presentation language' } } } no_help_templ_dict = { u'name': u'good_templ', u'description': u'<template description>', u'partition': u'<partition name>', u'requiresModules': [u'ltm', u'asm'], 'actions': { 'definition': { u'roleAcl': [u'hello', u'test'], u'implementation': u'# TMSH implementation code', u'presentation': u'# APL presentation language' } } } none_rm_templ_dict = { u'name': u'good_templ', u'partition': u'<partition name>', u'requiresModules': u'none', 'actions': { 'definition': { u'htmlHelp': u'# HTML Help for the template', u'roleAcl': [u'hello', u'test'], u'implementation': u'# TMSH implementation code', u'presentation': u'# APL presentation language' } } } dot_name_templ_dict = { u'name': u'good.dot.templ', u'description': u'<template description>', u'partition': u'<partition name>', u'requiresModules': [u'ltm'], 'actions': { 'definition': { u'htmlHelp': u'# HTML Help for the template', u'roleAcl': [u'hello', u'test'], u'implementation': u'# TMSH implementation code', u'presentation': u'# APL presentation language' } } } dot_hyphen_name_templ_dict = { u'name': u'good.-dot-hyphen.-templ', u'description': u'<template description>', u'partition': u'<partition name>', u'requiresModules': [u'ltm'], 'actions': { 'definition': { u'htmlHelp': u'# HTML Help for the template', u'roleAcl': [u'hello', u'test'], u'implementation': u'# TMSH implementation code', u'presentation': u'# APL presentation language' } } } @pytest.fixture def TemplateSectionSetup(request): def tearDown(): prsr.template_sections.remove('notfound') request.addfinalizer(tearDown) prsr = ip.IappParser(good_templ) prsr.template_sections.append('notfound') return prsr def test__init__(): prsr = ip.IappParser(good_templ) assert prsr.template_str == good_templ def test__init__error(): prsr = None with pytest.raises(ip.EmptyTemplateException) as EmptyTemplateExceptInfo: prsr = ip.IappParser('') assert EmptyTemplateExceptInfo.value.message == \ 'Template empty or None value.' assert prsr is None def test_get_section_end_index(): prsr = ip.IappParser(good_templ) impl_start = prsr._get_section_start_index(u'implementation') impl_end = prsr._get_section_end_index(u'implementation', impl_start) templ_impl = unicode('''{ # TMSH implementation code }''') assert good_templ[impl_start:impl_end+1] == templ_impl def test_get_section_start_index_no_open_brace_error(): prsr = ip.IappParser(no_open_brace_templ) with pytest.raises(ip.NonextantSectionException) as \ NonextantSectionExceptInfo: prsr._get_section_start_index(u'html-help') assert NonextantSectionExceptInfo.value.message == \ 'Section html-help not found in template' def test_get_section_end_no_close_brace_error(): prsr = ip.IappParser(no_close_brace_templ) with pytest.raises(ip.CurlyBraceMismatchException) as \ CurlyBraceMismatchExceptInfo: help_start = prsr._get_section_start_index(u'html-help') prsr._get_section_end_index(u'html_help', help_start) assert CurlyBraceMismatchExceptInfo.value.message == \ 'Curly braces mismatch in section html_help.' def test_get_template_name(): prsr = ip.IappParser(good_templ) assert prsr._get_template_name() == u'good_templ' def test_get_template_name_next_to_brace(): prsr = ip.IappParser(name_brace_templ) assert prsr._get_template_name() == u'name_next_to_brace' def test_get_template_name_error(): prsr = ip.IappParser(no_name_templ) with pytest.raises(ip.NonextantTemplateNameException) as \ NonextantTemplateNameExceptInfo: prsr._get_template_name() assert NonextantTemplateNameExceptInfo.value.message == \ 'Template name not found.' def test_get_template_name_bad_name_error(): prsr = ip.IappParser(bad_name_templ) with pytest.raises(ip.NonextantTemplateNameException) as \ NonextantTemplateNameExceptInfo: prsr._get_template_name() assert NonextantTemplateNameExceptInfo.value.message == \ 'Template name not found.' def test_get_template_name_with_dot(): prsr = ip.IappParser(dot_name_templ) assert prsr.parse_template() == dot_name_templ_dict def test_get_template_name_with_dot_hyphen(): prsr = ip.IappParser(dot_hyphen_name_templ) assert prsr.parse_template() == dot_hyphen_name_templ_dict def test_parse_template(): prsr = ip.IappParser(good_templ) assert prsr.parse_template() == good_templ_dict def test_parse_template_brace_in_quote(): prsr = ip.IappParser(brace_in_quote_templ) assert prsr.parse_template() == brace_in_quote_templ_dict def test_parse_template_no_section_found(TemplateSectionSetup): with pytest.raises(ip.NonextantSectionException) as \ NonextantSectionExceptInfo: TemplateSectionSetup.parse_template() assert 'notfound' in TemplateSectionSetup.template_sections assert 'Section notfound not found in template' in \ NonextantSectionExceptInfo.value.message def test_parse_template_no_section_found_not_required(): prsr = ip.IappParser(no_help_templ) templ_dict = prsr.parse_template() assert templ_dict == no_help_templ_dict def test_get_template_attr(): prsr = ip.IappParser(good_attr_templ) attr = prsr._get_template_attr(u'partition') assert attr == u'just_a_partition name' def test_get_template_attr_attr_not_exists(): prsr = ip.IappParser(good_attr_templ) attr = prsr._get_template_attr(u'bad_attr') assert attr is None def test_attr_no_description(): prsr = ip.IappParser(no_desc_templ) templ_dict = prsr.parse_template() assert 'description' not in templ_dict def test_attr_empty_rm_error(): prsr = ip.IappParser(empty_rm_templ) with pytest.raises(ip.MalformedTCLListException) as ex: prsr.parse_template() assert 'requires-modules' in ex.value.message def test_attr_whitespace_rm_error(): prsr = ip.IappParser(whitespace_rm_templ) with pytest.raises(ip.MalformedTCLListException) as ex: prsr.parse_template() assert 'TCL list for "requires-modules" is malformed. If no elements are '\ 'needed "none" should be used without curly braces.' in \ ex.value.message def test_attr_none_rm(): prsr = ip.IappParser(none_rm_templ) templ_dict = prsr.parse_template() assert templ_dict == none_rm_templ_dict
26.215827
79
0.64565
1,627
14,576
5.590658
0.110018
0.034301
0.05321
0.029244
0.748461
0.691953
0.657432
0.583773
0.557828
0.547713
0
0.001011
0.253224
14,576
555
80
26.263063
0.834635
0.03787
0
0.552017
0
0
0.551788
0.010208
0
0
0
0
0.048832
1
0.048832
false
0
0.004246
0
0.055202
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d94e7f4e72a48e860eb440b1515c225287560f3f
2,284
py
Python
z2npprocess.py
evandromr/python_scitools
afe8ad113245069af0ef2a05c69046938459ab2d
[ "MIT" ]
2
2015-11-05T14:43:04.000Z
2016-01-06T18:49:31.000Z
z2npprocess.py
evandromr/python_scitools
afe8ad113245069af0ef2a05c69046938459ab2d
[ "MIT" ]
null
null
null
z2npprocess.py
evandromr/python_scitools
afe8ad113245069af0ef2a05c69046938459ab2d
[ "MIT" ]
null
null
null
#!/usr/env python import pprocess # parallel computing module import os # os utilitites import time # keep track of time import astropy.io.fits as fits # FITS manipulating library import matplotlib.pyplot as plt import numpy as np # numeric python for array manipulation import myscitools # my personal tools #input file informations and variables atributions---------------------- inptname = str(raw_input('Input file (with extension): ')) outptname = os.path.splitext(inptname)[0]+'_z2n_output.fits' inpt = fits.open(inptname) times = inpt[1].data.field('TIME') inpt.close() interval = float(times.max()-times.min()) startf = 1.0/interval print "The start frequency is: ", startf query = str(raw_input("Change the start frequency? (y/n): ")) if (query == 'y') or (query == 'Y'): startf = float(raw_input('Enter the start frequency: ')) else: pass endf = float(raw_input('Enter the last frequency: ')) over = float(raw_input('Enter oversample factor: ')) fact = 1.0/over deltaf = fact/interval print "The frequency step will be: ", deltaf query2 = str(raw_input('Change frequency step? (y/n): ')) if (query2 == 'y') or (query2 == 'Y'): deltaf = float(raw_input('Enter the frequency interval: ')) else: pass freqs = np.arange(startf, endf, deltaf) #harm = int(raw_input('The Harmonic to be considered:')) harm = 1 #----------------- The parallelism starts here ------------------------ nproc = int(raw_input('Enter the number of processor to use: ')) if nproc < 1: nproc = 1 # default number of cpus = 1 freqlist = np.array_split(freqs, nproc) results = pprocess.Map(limit=nproc, reuse=1) parallel_z2n = results.manage(pprocess.MakeReusable(myscitools.z2n)) print "\n Calculating with ", nproc, " processor(s)\n" tic = time.time() [parallel_z2n(somefreqs, times, harm) for somefreqs in freqlist] z2n = [] for result in results: for value in result: z2n.append(value) print 'time = {0}'.format(time.time() - tic) plt.plot(freqs, z2n) plt.xlabel('Frequency (Hz)') plt.ylabel('Z2n Power') plt.title(inptname) plt.show() plt.plot(freqs, z2n) plt.savefig('z2n.png') #create and write the output.fits file col1 = [freqs, 'frequency', 'E', 'Hz'] col2 = [z2n, 'z2nPower', 'E', 'arbitrary'] myscitools.makefits(outptname, col1, col2)
27.853659
72
0.684764
326
2,284
4.754601
0.420245
0.046452
0.041935
0.046452
0.063871
0
0
0
0
0
0
0.015971
0.150175
2,284
81
73
28.197531
0.782586
0.182574
0
0.107143
0
0
0.226954
0
0
0
0
0
0
0
null
null
0.035714
0.125
null
null
0.071429
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
1
d950b3d1717860b9f9b62454c2ec7519e0a1185c
625
py
Python
net/http_client.py
zengmeng1094/my_python_practice
529e3ce592508b30d49dc6d4a005081789d0db44
[ "Apache-2.0" ]
null
null
null
net/http_client.py
zengmeng1094/my_python_practice
529e3ce592508b30d49dc6d4a005081789d0db44
[ "Apache-2.0" ]
null
null
null
net/http_client.py
zengmeng1094/my_python_practice
529e3ce592508b30d49dc6d4a005081789d0db44
[ "Apache-2.0" ]
null
null
null
import requests import urllib3 from urllib3 import HTTPConnectionPool class HttpsClient: def __init__(self): pass @staticmethod def get(_url, _query_string={}, _header=None): urllib3.disable_warnings() _resp = requests.get(_url, _query_string, headers=_header, verify=False) return _resp.text @staticmethod def post(_url, _body={}, _header=None): urllib3.disable_warnings() _resp = requests.post(_url, _body, headers=_header, verify=False) return _resp.text if __name__ == '__main__': print(HttpsClient.get('http://127.0.0.1:5000/test'))
24.038462
80
0.6752
73
625
5.342466
0.520548
0.076923
0.05641
0.087179
0.420513
0.420513
0.420513
0
0
0
0
0.028455
0.2128
625
25
81
25
0.764228
0
0
0.333333
0
0
0.0544
0
0
0
0
0
0
1
0.166667
false
0.055556
0.166667
0
0.5
0.055556
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
d9514413b1dc12beee51ba849953b233bcf53932
6,217
py
Python
tests/test_redis.py
fedej/aio-rom
e84d55b84ca459b930d0cd86fd33f161cb26c7df
[ "MIT" ]
6
2021-03-22T22:12:34.000Z
2022-02-14T01:30:37.000Z
tests/test_redis.py
fedej/aio-rom
e84d55b84ca459b930d0cd86fd33f161cb26c7df
[ "MIT" ]
52
2021-02-22T16:38:27.000Z
2022-03-07T18:06:18.000Z
tests/test_redis.py
fedej/aio-rom
e84d55b84ca459b930d0cd86fd33f161cb26c7df
[ "MIT" ]
null
null
null
import os import sys from dataclasses import field from typing import List, Optional, Set, cast from unittest import skipUnless from aio_rom import Model from aio_rom.attributes import RedisModelSet if sys.version_info >= (3, 8): from unittest.async_case import IsolatedAsyncioTestCase as TestCase ASYNCTEST = False else: from asynctest import TestCase ASYNCTEST = True from aio_rom.fields import Metadata from aio_rom.session import redis_pool class Bar(Model, unsafe_hash=True): field1: int field2: str field3: List[int] = field(metadata=Metadata(eager=True), hash=False) field4: int = 3 class Foo(Model, unsafe_hash=True): eager_bars: List[Bar] = field(metadata=Metadata(eager=True), hash=False) lazy_bars: Set[Bar] = field(compare=False, metadata=Metadata(cascade=True)) f1: Optional[str] = None class FooBar(Model): foos: Set[Foo] = field(metadata=Metadata(cascade=True, eager=True)) @skipUnless(os.environ.get("CI"), "Redis CI test only") class RedisIntegrationTestCase(TestCase): async def asyncSetUp(self) -> None: self.bar = Bar(1, 123, "value", [1, 2, 3]) async def asyncTearDown(self) -> None: await Foo.delete_all() await Bar.delete_all() await FooBar.delete_all() if ASYNCTEST: tearDown = asyncTearDown # type: ignore[assignment] setUp = asyncSetUp # type: ignore[assignment] async def test_save(self) -> None: await self.bar.save() async with redis_pool() as redis: field1 = await redis.hget("bar:1", "field1") field2 = await redis.hget("bar:1", "field2") field3 = await redis.hget("bar:1", "field3") field3_value = await redis.lrange("bar:1:field3", 0, -1) assert "123" == field1 assert "value" == field2 assert "bar:1:field3" == field3 assert ["1", "2", "3"] == field3_value async def test_get(self) -> None: await self.bar.save() bar = await Bar.get(1) assert self.bar == bar async def test_get_with_references(self) -> None: await self.bar.save() foo = Foo(123, [self.bar], {self.bar}) await foo.save() gotten_foo = await Foo.get(123) assert foo == gotten_foo await cast(RedisModelSet[Bar], gotten_foo.lazy_bars).load() for bar in gotten_foo.lazy_bars: assert bar in foo.lazy_bars assert len(foo.lazy_bars) == len(gotten_foo.lazy_bars) async def _test_collection_references(self, test_cascade: bool = False) -> None: await self.bar.save() foo = Foo(123, [self.bar], {self.bar}) if not test_cascade: await foo.save() foobar = FooBar(321, {foo}) await foobar.save() gotten_foobar = await FooBar.get(321) assert foobar == gotten_foobar assert {foo} == gotten_foobar.foos for gotten_foo in gotten_foobar.foos: assert 1 == len(gotten_foo.eager_bars) await cast(RedisModelSet[Bar], gotten_foo.lazy_bars).load() for bar in gotten_foo.lazy_bars: assert bar in foo.lazy_bars async def test_collections(self) -> None: await self._test_collection_references() async def test_collection_cascades_references(self) -> None: await self._test_collection_references(test_cascade=True) async def test_update_collection_references(self) -> None: await self.bar.save() foo = Foo(123, [self.bar], {self.bar}) foobar = FooBar(321, {foo}) await foobar.save() refreshed = await foobar.refresh() foo2 = Foo(222, [], set()) refreshed.foos.add(foo2) await refreshed.save() gotten_foobar = await FooBar.get(321) assert refreshed == gotten_foobar assert {foo, foo2} == gotten_foobar.foos async def test_update(self) -> None: await self.bar.save() await self.bar.update(field2="updated") async with redis_pool() as redis: field2 = await redis.hget("bar:1", "field2") assert "updated" == field2 bar = await Bar.get(1) assert "updated" == bar.field2 async def test_update_reference(self) -> None: await self.bar.save() foo = Foo(123, [self.bar], {self.bar}) await foo.save() bar2 = Bar(2, 123, "otherbar", [1, 2, 3, 4]) await bar2.save() foo = await foo.update(lazy_bars={bar2}) async with redis_pool() as redis: lazy_bars = await redis.smembers("foo:123:lazy_bars") assert ["2"] == lazy_bars foo = await foo.update(eager_bars=[bar2]) async with redis_pool() as redis: eager_bars = await redis.lrange("foo:123:eager_bars", 0, -1) assert ["2"] == eager_bars gotten_foo = await Foo.get(123) assert foo == gotten_foo async def test_save_again_overrides_previous(self) -> None: await self.bar.save() bar = await Bar.get(1) bar.field2 = "updated" await bar.save() async with redis_pool() as redis: field2 = await redis.hget("bar:1", "field2") assert "updated" == field2 async def test_delete(self) -> None: await self.bar.save() async with redis_pool() as redis: assert await redis.exists("bar:1") await self.bar.delete() assert not await redis.exists("bar:1") async def test_delete_all(self) -> None: await self.bar.save() async with redis_pool() as redis: await Bar.delete_all() assert not await redis.keys("bar*") async def test_lazy_collection_cascade(self) -> None: foo = Foo(123, [self.bar], {self.bar}) await foo.save() foo = await Foo.get(123) other_bar = Bar(2, 124, "value2", []) foo.lazy_bars.add(other_bar) await foo.save() gotten_foo = await Foo.get(123) assert foo == gotten_foo await cast(RedisModelSet[Bar], gotten_foo.lazy_bars).load() await cast(RedisModelSet[Bar], foo.lazy_bars).load() assert 2 == len(foo.lazy_bars) == len(gotten_foo.lazy_bars)
33.605405
84
0.618144
821
6,217
4.550548
0.142509
0.044968
0.041756
0.050054
0.442987
0.415418
0.395343
0.327891
0.287473
0.269272
0
0.028646
0.264436
6,217
184
85
33.788043
0.788323
0.007882
0
0.378378
0
0
0.034874
0
0
0
0
0
0.168919
1
0
false
0
0.074324
0
0.155405
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d95365e9560d7743acef72009c98362dad09f3a4
1,514
py
Python
data/transcoder_evaluation_gfg/python/DYNAMIC_PROGRAMMING_SET_17_PALINDROME_PARTITIONING.py
mxl1n/CodeGen
e5101dd5c5e9c3720c70c80f78b18f13e118335a
[ "MIT" ]
241
2021-07-20T08:35:20.000Z
2022-03-31T02:39:08.000Z
data/transcoder_evaluation_gfg/python/DYNAMIC_PROGRAMMING_SET_17_PALINDROME_PARTITIONING.py
mxl1n/CodeGen
e5101dd5c5e9c3720c70c80f78b18f13e118335a
[ "MIT" ]
49
2021-07-22T23:18:42.000Z
2022-03-24T09:15:26.000Z
data/transcoder_evaluation_gfg/python/DYNAMIC_PROGRAMMING_SET_17_PALINDROME_PARTITIONING.py
mxl1n/CodeGen
e5101dd5c5e9c3720c70c80f78b18f13e118335a
[ "MIT" ]
71
2021-07-21T05:17:52.000Z
2022-03-29T23:49:28.000Z
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( str ) : n = len ( str ) C = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] P = [ [ False for i in range ( n ) ] for i in range ( n ) ] j = 0 k = 0 L = 0 for i in range ( n ) : P [ i ] [ i ] = True ; C [ i ] [ i ] = 0 ; for L in range ( 2 , n + 1 ) : for i in range ( n - L + 1 ) : j = i + L - 1 if L == 2 : P [ i ] [ j ] = ( str [ i ] == str [ j ] ) else : P [ i ] [ j ] = ( ( str [ i ] == str [ j ] ) and P [ i + 1 ] [ j - 1 ] ) if P [ i ] [ j ] == True : C [ i ] [ j ] = 0 else : C [ i ] [ j ] = 100000000 for k in range ( i , j ) : C [ i ] [ j ] = min ( C [ i ] [ j ] , C [ i ] [ k ] + C [ k + 1 ] [ j ] + 1 ) return C [ 0 ] [ n - 1 ] #TOFILL if __name__ == '__main__': param = [ ('ydYdV',), ('4446057',), ('0111',), ('keEj',), ('642861576557',), ('11111000101',), ('ram',), ('09773261',), ('1',), ('AVBEKClFdj',) ] n_success = 0 for i, parameters_set in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success+=1 print("#Results: %i, %i" % (n_success, len(param)))
29.115385
97
0.402246
207
1,514
2.859903
0.328502
0.094595
0.060811
0.111486
0.165541
0.14527
0.118243
0.081081
0.081081
0.081081
0
0.086705
0.428666
1,514
52
98
29.115385
0.597688
0.122193
0
0.047619
0
0
0.067322
0
0
0
0
0
0
1
0.02381
false
0
0
0
0.047619
0.02381
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d955563969d83170f71c06df9ab6aacad0658d81
787
py
Python
timetappy/staff.py
ak9999/timetappy
7429077b2a8f3e2f0b2b5ac26d9db713fd330a50
[ "MIT" ]
null
null
null
timetappy/staff.py
ak9999/timetappy
7429077b2a8f3e2f0b2b5ac26d9db713fd330a50
[ "MIT" ]
null
null
null
timetappy/staff.py
ak9999/timetappy
7429077b2a8f3e2f0b2b5ac26d9db713fd330a50
[ "MIT" ]
null
null
null
from .utils import return_response, api_get_request class StaffMixin(): TIMETAP_API_STAFF = '/staff' api_get_request = api_get_request @return_response def get_staff(self): return self.api_get_request(f'{self.TIMETAP_API_STAFF}') @return_response def get_staff_by_professionalId(self, professionalId: int): if not professionalId: raise ValueError('professionalId has not been set') return self.api_get_request(f'{self.TIMETAP_API_STAFF}/{professionalId}') @return_response def get_service_staff(self, professionalId: int): if not professionalId: raise ValueError('professionalId has not been set') return self.api_get_request(f'{self.TIMETAP_API_STAFF}/{professionalId}/serviceStaff')
32.791667
94
0.721728
98
787
5.489796
0.27551
0.066915
0.144981
0.111524
0.689591
0.596654
0.596654
0.596654
0.596654
0.596654
0
0
0.193139
787
23
95
34.217391
0.847244
0
0
0.411765
0
0
0.237611
0.151207
0
0
0
0
0
1
0.176471
false
0
0.058824
0.058824
0.588235
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
d955bd3b6a1f98f5c7cc4debf622f8e2f6c5f9cd
104
py
Python
goutdotcom/treatment/apps.py
Spiewart/goutdotcom
0916155732a72fcb8c8a2fb0f4dd81efef618af8
[ "MIT" ]
null
null
null
goutdotcom/treatment/apps.py
Spiewart/goutdotcom
0916155732a72fcb8c8a2fb0f4dd81efef618af8
[ "MIT" ]
null
null
null
goutdotcom/treatment/apps.py
Spiewart/goutdotcom
0916155732a72fcb8c8a2fb0f4dd81efef618af8
[ "MIT" ]
null
null
null
from django.apps import AppConfig class TreatmentConfig(AppConfig): name = 'goutdotcom.treatment'
17.333333
33
0.778846
11
104
7.363636
0.909091
0
0
0
0
0
0
0
0
0
0
0
0.144231
104
5
34
20.8
0.910112
0
0
0
0
0
0.192308
0
0
0
0
0
0
1
0
false
0
0.333333
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
d955de847bc6455510ab5fae7ec28c13dd87bbec
1,201
py
Python
Algorithms/0033_Search_in_Rotated_Sorted_Array/Python/Search_in_Rotated_Sorted_Array_Solution_1.py
lht19900714/Leetcode_Solutions
dac7a038329a5c1f8a78e86cc6f49116b963f1fb
[ "MIT" ]
null
null
null
Algorithms/0033_Search_in_Rotated_Sorted_Array/Python/Search_in_Rotated_Sorted_Array_Solution_1.py
lht19900714/Leetcode_Solutions
dac7a038329a5c1f8a78e86cc6f49116b963f1fb
[ "MIT" ]
null
null
null
Algorithms/0033_Search_in_Rotated_Sorted_Array/Python/Search_in_Rotated_Sorted_Array_Solution_1.py
lht19900714/Leetcode_Solutions
dac7a038329a5c1f8a78e86cc6f49116b963f1fb
[ "MIT" ]
null
null
null
# Space: O(1) # Time: O(logn) class Solution: def search(self, nums, target): length = len(nums) if length == 0: return -1 if length == 1: return 0 if nums[0] == target else -1 # First, find out the actual end point of sorted array left, right = 0, length - 1 while left + 1 < right: mid = (left + right) // 2 if nums[mid] > nums[right]: left = mid else: right = mid actual_end_point = right if nums[right] > nums[left] else left # Second, execute regular binary search for target number res = self.binary_search(nums, target, 0, actual_end_point) if res != -1: return res else: return self.binary_search(nums, target, actual_end_point + 1, length - 1) def binary_search(self, alist, target, start, end): left, right = start, end while left <= right: mid = (left + right) // 2 if alist[mid] == target: return mid if alist[mid] < target: left = mid + 1 else: right = mid - 1 return -1
27.930233
85
0.507077
150
1,201
4
0.28
0.075
0.093333
0.056667
0.153333
0.066667
0
0
0
0
0
0.026243
0.397169
1,201
42
86
28.595238
0.802486
0.111574
0
0.172414
0
0
0
0
0
0
0
0
0
1
0.068966
false
0
0
0
0.241379
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d959215b82b03d107b269df9d66aba263c6dfe42
7,807
py
Python
nxs_libs/interface/workload_manager/simple_policy.py
microsoft/nxs
b271c0637576084b36bd0bd397a673fb348913b3
[ "MIT" ]
5
2022-03-23T21:27:42.000Z
2022-03-24T19:57:27.000Z
nxs_libs/interface/workload_manager/simple_policy.py
microsoft/nxs
b271c0637576084b36bd0bd397a673fb348913b3
[ "MIT" ]
null
null
null
nxs_libs/interface/workload_manager/simple_policy.py
microsoft/nxs
b271c0637576084b36bd0bd397a673fb348913b3
[ "MIT" ]
1
2022-03-23T21:27:44.000Z
2022-03-23T21:27:44.000Z
import time import numpy as np from typing import Dict, List, Tuple from nxs_libs.interface.workload_manager import ( NxsBaseWorkloadManagerPolicy, ) from nxs_types.frontend import FrontendModelPipelineWorkloadReport from nxs_types.message import ( NxsMsgPinWorkload, NxsMsgType, NxsMsgReportInputWorkloads, NxsMsgUnpinWorkload, ) from nxs_types.nxs_args import NxsWorkloadManagerArgs class FrontendWorkloads: def __init__(self, frontend: str, model_timeout_secs: float) -> None: self.frontend = frontend self.model_timeout_secs = model_timeout_secs self.uuid2throughput: Dict[str, List[float]] = {} self.uuid2timestamps: Dict[str, List[float]] = {} # self.uuid2pipelineuuid: Dict[str, str] = {} # self.uuid2sessionuuid: Dict[str, str] = {} def add_workload(self, workload: FrontendModelPipelineWorkloadReport): uuid = f"{workload.pipeline_uuid}_{workload.session_uuid}" if uuid not in self.uuid2throughput: self.uuid2throughput[uuid] = [] self.uuid2timestamps[uuid] = [] # self.uuid2pipelineuuid[uuid] = workload.pipeline_uuid # self.uuid2sessionuuid[uuid] = workload.session_uuid self.uuid2throughput[uuid].append(workload.fps) self.uuid2timestamps[uuid].append(time.time()) def _remove_expired(self, uuid: str): timestamps = self.uuid2timestamps.get(uuid, []) for idx in range(len(timestamps)): elapsed = time.time() - timestamps[0] # print(idx, elapsed, self.model_timeout_secs) if elapsed < self.model_timeout_secs: break self.uuid2throughput[uuid].pop(0) self.uuid2timestamps[uuid].pop(0) if not self.uuid2throughput[uuid]: self.uuid2throughput.pop(uuid) self.uuid2timestamps.pop(uuid) # self.uuid2pipelineuuid.pop(uuid) # self.uuid2sessionuuid.pop(uuid) # print(f"Removed workload {uuid} from frontend {self.frontend}") def remove_expired(self): for uuid in list(self.uuid2throughput.keys()): self._remove_expired(uuid) def get_workloads(self) -> Dict[str, float]: data = {} self.remove_expired() for uuid in self.uuid2throughput: fps = np.sum(self.uuid2throughput[uuid]) if fps > 0: duration = max(1, time.time() - self.uuid2timestamps[uuid][0]) data[uuid] = float(fps) / duration return data class NxsSimpleWorkloadManagerPolicy(NxsBaseWorkloadManagerPolicy): def __init__(self, args: NxsWorkloadManagerArgs) -> None: super().__init__(args) # self.frontend2workloads:Dict[str, FrontendWorkloads] = {} self.uuid2throughput: Dict[str, List[float]] = {} self.uuid2timestamps: Dict[str, List[float]] = {} self.pinned_workloads: Dict[str, float] = {} self.t0 = time.time() def add_workload(self, workload: FrontendModelPipelineWorkloadReport) -> bool: is_new_workload = False uuid = f"{workload.pipeline_uuid}_{workload.session_uuid}" if uuid not in self.uuid2throughput: self.uuid2throughput[uuid] = [] self.uuid2timestamps[uuid] = [] # self.uuid2pipelineuuid[uuid] = workload.pipeline_uuid # self.uuid2sessionuuid[uuid] = workload.session_uuid is_new_workload = True self._log(f"Added new workload {uuid}") self.uuid2throughput[uuid].append(workload.fps) self.uuid2timestamps[uuid].append(time.time()) return is_new_workload def _remove_expired(self, uuid: str): timestamps = self.uuid2timestamps.get(uuid, []) for idx in range(len(timestamps)): elapsed = time.time() - timestamps[0] # print(idx, elapsed, self.model_timeout_secs) if elapsed < self.args.model_timeout_secs: break self.uuid2throughput[uuid].pop(0) self.uuid2timestamps[uuid].pop(0) if not self.uuid2throughput[uuid]: self.uuid2throughput.pop(uuid) self.uuid2timestamps.pop(uuid) # self.uuid2pipelineuuid.pop(uuid) # self.uuid2sessionuuid.pop(uuid) # print(f"Removed workload {uuid}") self._log(f"Removed workload {uuid}") def remove_expired(self): for uuid in list(self.uuid2throughput.keys()): self._remove_expired(uuid) def get_workloads(self) -> Dict[str, float]: data = {} self.remove_expired() for uuid in self.uuid2throughput: fps = np.sum(self.uuid2throughput[uuid]) if fps > 0: duration = max(1, time.time() - self.uuid2timestamps[uuid][0]) data[uuid] = float(fps) / duration return data def generate_scheduling_msgs( self, ) -> List[FrontendModelPipelineWorkloadReport]: workloads_dict = {} msgs = [] frontend_workloads_dict = self.get_workloads() for uuid in frontend_workloads_dict: if uuid not in workloads_dict: workloads_dict[uuid] = 0 workloads_dict[uuid] += frontend_workloads_dict[uuid] # process pinned_workloads for uuid in self.pinned_workloads: if uuid not in workloads_dict: workloads_dict[uuid] = 0 workloads_dict[uuid] += self.pinned_workloads[uuid] for uuid in workloads_dict: # print(uuid) pipeline_uuid, session_uuid = uuid.split("_") msg = FrontendModelPipelineWorkloadReport( pipeline_uuid=pipeline_uuid, session_uuid=session_uuid, fps=workloads_dict[uuid], ) msgs.append(msg) return msgs def process_msgs( self, msgs: List[NxsMsgReportInputWorkloads] ) -> Tuple[bool, List[FrontendModelPipelineWorkloadReport]]: to_schedule = False scheduling_msgs = [] for msg in msgs: # print(msg) if msg.type == NxsMsgType.REGISTER_WORKLOADS: # frontend_name = msg.data.frontend_name for workload in msg.data.workload_reports: if ( self.add_workload(workload) and self.args.enable_instant_scheduling ): to_schedule = True elif msg.type == NxsMsgType.PIN_WORKLOADS: pin_msg: NxsMsgPinWorkload = msg uuid = f"{pin_msg.pipeline_uuid}_{pin_msg.session_uuid}" self.pinned_workloads[uuid] = pin_msg.fps to_schedule = True self._log( f"Pinning workload - pipeline_uuid: {pin_msg.pipeline_uuid} - session_uuid: {pin_msg.session_uuid} - fps: {pin_msg.fps}" ) elif msg.type == NxsMsgType.UNPIN_WORKLOADS: unpin_msg: NxsMsgUnpinWorkload = msg uuid = f"{unpin_msg.pipeline_uuid}_{unpin_msg.session_uuid}" if uuid in self.pinned_workloads: self.pinned_workloads.pop(uuid) self._log( f"Unpinning workload - pipeline_uuid: {unpin_msg.pipeline_uuid} - session_uuid: {unpin_msg.session_uuid}" ) if time.time() - self.t0 > self.args.report_workloads_interval: to_schedule = True if to_schedule: # generate scheduling data scheduling_msgs = self.generate_scheduling_msgs() # print(scheduling_msgs) self.t0 = time.time() return to_schedule, scheduling_msgs
35.811927
140
0.608685
800
7,807
5.7525
0.13375
0.082573
0.049978
0.017384
0.562364
0.511082
0.473707
0.473707
0.473707
0.473707
0
0.011293
0.296785
7,807
217
141
35.976959
0.826958
0.103625
0
0.473333
0
0.006667
0.06594
0.040998
0
0
0
0
0
1
0.08
false
0
0.046667
0
0.173333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d95e1a45cff563a0bc7667c6cb86319a45a18004
23,258
py
Python
examples/grid_convergence.py
H0R5E/SNL-Delft3D-CEC-Verify
234c0acead13c74bad2979b300671733c7b184f7
[ "MIT" ]
null
null
null
examples/grid_convergence.py
H0R5E/SNL-Delft3D-CEC-Verify
234c0acead13c74bad2979b300671733c7b184f7
[ "MIT" ]
2
2021-12-10T17:17:21.000Z
2022-02-22T00:25:15.000Z
examples/grid_convergence.py
H0R5E/SNL-Delft3D-CEC-Verify
234c0acead13c74bad2979b300671733c7b184f7
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import os import uuid import platform import warnings from pathlib import Path from collections import defaultdict from dataclasses import replace import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt from convergence import Convergence from snl_d3d_cec_verify import (MycekStudy, Report, Result, LiveRunner, Template, Validate) from snl_d3d_cec_verify.result import (get_reset_origin, get_normalised_dims, get_normalised_data, get_normalised_data_deficit) from snl_d3d_cec_verify.text import Spinner matplotlib.rcParams.update({'font.size': 8}) def main(template_type, max_experiments, omp_num_threads): # Steps: # # 1. Define a series of grid studies, doubling resolution # 2. Iterate # 3. Determine U_\infty by running without turbines # 4. Run with turbines # 5. Record results # 6. After 3 runs record asymptotic ratio # 7. If in asymptotic range stop iterating # 8. Calculate resolution at desired GCI # 9. Compute at desired resolution if lower than last iteration # 10. Make report # Set grid resolutions and reporting times grid_resolution = [1 / 2 ** i for i in range(max_experiments)] sigma = [int(2 / delta) for delta in grid_resolution] kwargs = {"dx": grid_resolution, "dy": grid_resolution, "sigma": sigma, "restart_interval": 600} # Choose options based on the template type if template_type == "fm": kwargs["stats_interval"] = [240 / (k ** 2) for k in sigma] elif template_type == "structured": # Set time step based on flexible mesh runs dt_init_all = [0.5, 0.25, 0.1, 0.0375, 0.0125] kwargs["dt_init"] = dt_init_all[:max_experiments] else: raise ValueError(f"Template type '{template_type}' unrecognised") cases = MycekStudy(**kwargs) template = Template(template_type) # Use the LiveRunner class to get real time feedback from the Delft3D # calculation runner = LiveRunner(get_d3d_bin_path(), omp_num_threads=omp_num_threads) u_infty_data = defaultdict(list) u_wake_data = defaultdict(list) transect_data = defaultdict(list) u_infty_convergence = Convergence() u_wake_convergence = Convergence() case_counter = 0 run_directory = Path(template_type) / "runs" run_directory.mkdir(exist_ok=True, parents=True) report = Report(79, "%d %B %Y") report_dir = Path(template_type) / "grid_convergence_report" report_dir.mkdir(exist_ok=True, parents=True) global_validate = Validate() ustar_figs = [] ustar_axs = [] gamma_figs = [] gamma_axs = [] for _ in global_validate: ustar_fig, ustar_ax = plt.subplots(figsize=(5, 3.5), dpi=300) gamma_fig, gamma_ax = plt.subplots(figsize=(5, 3.5), dpi=300) ustar_figs.append(ustar_fig) ustar_axs.append(ustar_ax) gamma_figs.append(gamma_fig) gamma_axs.append(gamma_ax) while True: if case_counter + 1 > len(cases): break case = cases[case_counter] no_turb_case = replace(case, simulate_turbines=False) validate = Validate(case) ncells = get_cells(case) section = f"{case.dx}m Resolution" print(section) no_turb_dir = find_project_dir(run_directory, no_turb_case) if no_turb_dir is not None: try: Result(no_turb_dir) print("Loading pre-existing simulation at path " f"'{no_turb_dir}'") except FileNotFoundError: no_turb_dir = None # Determine $U_\infty$ for case, by running without the turbine if no_turb_dir is None: print("Simulating without turbine") no_turb_dir = get_unique_dir(run_directory) no_turb_dir.mkdir() template(no_turb_case, no_turb_dir) case_path = no_turb_dir / "case.yaml" no_turb_case.to_yaml(case_path) with Spinner() as spin: for line in runner(no_turb_dir): spin(line) result = Result(no_turb_dir) u_infty_ds = result.faces.extract_turbine_centre(-1, no_turb_case) u_infty = u_infty_ds["$u$"].values.take(0) u_infty_data["resolution (m)"].append(case.dx) u_infty_data["# cells"].append(ncells) u_infty_data["$U_\\infty$"].append(u_infty) with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="Insufficient grids for analysis") u_infty_convergence.add_grids([(case.dx, u_infty)]) turb_dir = find_project_dir(run_directory, case) if turb_dir is not None: try: Result(turb_dir) print(f"Loading pre-existing simulation at path '{turb_dir}'") except FileNotFoundError: turb_dir = None # Run with turbines if turb_dir is None: print("Simulating with turbine") turb_dir = get_unique_dir(run_directory) turb_dir.mkdir() template(case, turb_dir) case_path = turb_dir / "case.yaml" case.to_yaml(case_path) with Spinner() as spin: for line in runner(turb_dir): spin(line) result = Result(turb_dir) # Collect wake velocity at 1.2D downstream u_wake_ds = result.faces.extract_turbine_centre(-1, case, offset_x=0.84) u_wake = u_wake_ds["$u$"].values.take(0) u_wake_data["resolution (m)"].append(case.dx) u_wake_data["# cells"].append(ncells) u_wake_data["$U_{1.2D}$"].append(u_wake) # Record with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="Insufficient grids for analysis") u_wake_convergence.add_grids([(case.dx, u_wake)]) plot_transects(case, validate, result, u_infty, ustar_axs, gamma_axs) get_transect_error(case, validate, result, u_infty, transect_data) case_counter += 1 if case_counter < 3: continue if abs(1 - u_wake_convergence[0].asymptotic_ratio) < 0.01: break if case_counter == max_experiments: break gci_required = 0.01 u_infty_exact = u_infty_convergence[0].fine.f_exact u_infty_gci = u_infty_convergence.get_resolution(gci_required) err = [abs((f0 / u_infty_exact) - 1) for f0 in u_infty_data["$U_\\infty$"]] u_infty_data["error"] = err u_infty_df = pd.DataFrame(u_infty_data) u_wake_exact = u_wake_convergence[0].fine.f_exact u_wake_gci = u_wake_convergence.get_resolution(gci_required) err = [abs((f0 / u_wake_exact) - 1) for f0 in u_wake_data["$U_{1.2D}$"]] u_wake_data["error"] = err u_wake_df = pd.DataFrame(u_wake_data) gamma0_sim = 100 * (1 - u_wake_exact / u_infty_exact) centreline = global_validate[0] gamma0_true = 100 * (1 - centreline.data[0] / centreline.attrs["$U_\infty$"]) gamma0_err = abs((gamma0_sim - gamma0_true) / gamma0_true) transect_df = pd.DataFrame(transect_data) transect_grouped = transect_df.groupby(["Transect"]) transect_summary = "" n_transects = len(global_validate) lower_first = lambda s: s[:1].lower() + s[1:] if s else '' for i, transect in enumerate(global_validate): description = transect.attrs['description'] transect_df = transect_grouped.get_group(description).drop("Transect", axis=1) transect_rmse = transect_df.iloc[-1, 1] transect_summary += ( f"For the {lower_first(description)} transect, the root mean " "square error at the lowest grid resolution was " f"{transect_rmse:.4g}.") if (i + 1) < n_transects: transect_summary += " " report.content.add_heading("Summary", level=2) summary_text = ( f"This is a grid convergence study of {len(cases)} cases. The " f"case with the finest grid resolution, of {case.dx}m, achieved an " f"asymptotic ratio of {u_wake_convergence[0].asymptotic_ratio:.4g} " "(asymptotic range is indicated by a value $\\approx 1$). At zero " "grid resolution, the normalised velocity deficit measured 1.2 " f"diameters downstream from the turbine was {gamma0_sim:.4g}\%, a " f"{gamma0_err * 100:.4g}\% error against the measured value of " f"{gamma0_true:.4g}\%. ") summary_text += transect_summary report.content.add_text(summary_text) report.content.add_heading("Grid Convergence Studies", level=2) report.content.add_heading("Free Stream Velocity", level=3) report.content.add_text( "This section presents the convergence study for the free stream " "velocity ($U_\\infty$). For the final case, with grid resolution of " f"{case.dx}m, an asymptotic ratio of " f"{u_infty_convergence[0].asymptotic_ratio:.4g} was achieved " "(asymptotic range is indicated by a value $\\approx 1$). The free " f"stream velocity at zero grid resolution is {u_infty_exact:.4g}m/s. " "The grid resolution required for a fine-grid GCI of " f"{gci_required * 100}\% is {u_infty_gci:.4g}m.") caption = ("Free stream velocity ($U_\\infty$) per grid resolution " "with computational cells and error against value at zero grid " "resolution") report.content.add_table(u_infty_df, index=False, caption=caption) fig, ax = plt.subplots(figsize=(4, 2.75), dpi=300) u_infty_df.plot(ax=ax, x="# cells", y="error", marker='x') plt.yscale("log") plt.xscale("log") plot_name = "u_infty_convergence.png" plot_path = report_dir / plot_name fig.savefig(plot_path, bbox_inches='tight') # Add figure with caption caption = ("Free stream velocity error against value at zero grid " "resolution per grid resolution ") report.content.add_image(plot_name, caption, width="3.64in") report.content.add_heading("Wake Velocity", level=3) report.content.add_text( "This section presents the convergence study for the wake centerline " "velocity measured 1.2 diameters downstream from the turbine " "($U_{1.2D}$). For the final case, with grid resolution of " f"{case.dx}m, an asymptotic ratio of " f"{u_wake_convergence[0].asymptotic_ratio:.4g} was achieved " "(asymptotic range is indicated by a value $\\approx 1$). The free " f"stream velocity at zero grid resolution is {u_wake_exact:.4g}m/s. " "The grid resolution required for a fine-grid GCI of " f"{gci_required * 100}\% is {u_wake_gci:.4g}m.") caption = ("Wake centerline velocity 1.2 diameters downstream " "($U_{1.2D}$) per grid resolution with computational cells and " "error against value at zero grid resolution") report.content.add_table(u_wake_df, index=False, caption=caption) fig, ax = plt.subplots(figsize=(4, 2.75), dpi=300) u_wake_df.plot(ax=ax, x="# cells", y="error", marker='x') plt.yscale("log") plt.xscale("log") plot_name = "u_wake_convergence.png" plot_path = report_dir / plot_name fig.savefig(plot_path, bbox_inches='tight') # Add figure with caption caption = ("Wake velocity error against value at zero grid resolution " "per grid resolution ") report.content.add_image(plot_name, caption, width="3.64in") report.content.add_heading("Validation", level=3) report.content.add_text( "At zero grid resolution, the normalised deficit of $U_{1.2D}$, " f"($\\gamma_{{0(1.2D)}}$) is {gamma0_sim:.4g}\%, a " f"{gamma0_err * 100:.4g}\% error against the measured value of " f"{gamma0_true:.4g}\%.") report.content.add_heading("Wake Transects", level=2) report.content.add_text( "This section presents axial velocity transects along the turbine " "centreline and at cross-sections along the $y$-axis. Errors are " "reported relative to the experimental data given in [@mycek2014].") for i, transect in enumerate(global_validate): description = transect.attrs['description'] report.content.add_heading(description, level=3) transect_df = transect_grouped.get_group(description).drop("Transect", axis=1) transect_rmse = transect_df.iloc[-1, 1] report.content.add_text( "The root mean square error (RMSE) for this transect at the " f"finest grid resolution of {case.dx}m was {transect_rmse:.4g}.") caption = ("Root mean square error (RMSE) for the normalised " "velocity, $u^*_0$, per grid resolution.") report.content.add_table(transect_df, index=False, caption=caption) transect_true = transect.to_xarray() major_axis = f"${transect.attrs['major_axis']}^*$" transect_true_u0 = get_u0(transect_true, transect_true, 0.8) transect_true_u0.plot(ax=ustar_axs[i], x=major_axis, label='Experiment') ustar_axs[i].legend(loc='center left', bbox_to_anchor=(1, 0.5)) ustar_axs[i].grid() ustar_axs[i].set_title("") plot_name = f"transect_u0_{i}.png" plot_path = report_dir / plot_name ustar_figs[i].savefig(plot_path, bbox_inches='tight') # Add figure with caption caption = ("Normalised velocity, $u^*_0$, (m/s) per grid resolution " "comparison. Experimental data reverse engineered from " f"[@mycek2014, fig. {transect.attrs['figure']}].") report.content.add_image(plot_name, caption, width="5.68in") transect_true_gamma0 = get_gamma0(transect_true, transect_true) transect_true_gamma0.plot(ax=gamma_axs[i], x=major_axis, label='Experiment') gamma_axs[i].legend(loc='center left', bbox_to_anchor=(1, 0.5)) gamma_axs[i].grid() gamma_axs[i].set_title("") plot_name = f"transect_gamma0_{i}.png" plot_path = report_dir / plot_name gamma_figs[i].savefig(plot_path, bbox_inches='tight') # Add figure with caption caption = ("Normalised velocity deficit, $\gamma_0$, (%) per grid " "resolution comparison. Experimental data reverse " "engineered from [@mycek2014, fig. " f"{transect.attrs['figure']}].") report.content.add_image(plot_name, caption, width="5.68in") # Add section for the references report.content.add_heading("References", level=2) # Add report metadata os_name = platform.system() report.title = f"Grid Convergence Study ({os_name})" report.date = "today" # Write the report to file with open(report_dir / "report.md", "wt") as f: for line in report: f.write(line) # Convert file to docx or print report to stdout try: import pypandoc pypandoc.convert_file(f"{report_dir / 'report.md'}", 'docx', outputfile=f"{report_dir / 'report.docx'}", extra_args=['-C', f'--resource-path={report_dir}', '--bibliography=examples.bib', '--reference-doc=reference.docx']) except ImportError: print(report) def get_d3d_bin_path(): env = dict(os.environ) if 'D3D_BIN' in env: root = Path(env['D3D_BIN'].replace('"', '')) print('D3D_BIN found') else: root = Path("..") / "src" / "bin" print('D3D_BIN not found') print(f'Setting bin folder path to {root.resolve()}') return root.resolve() def find_project_dir(path, case): path = Path(path) files = list(Path(path).glob("**/case.yaml")) ignore_fields = ["stats_interval", "restart_interval"] for file in files: test = MycekStudy.from_yaml(file) if test.is_equal(case, ignore_fields): return file.parent return None def get_unique_dir(path, max_tries=1e6): parent = Path(path) for _ in range(int(max_tries)): name = uuid.uuid4().hex child = parent / name if not child.exists(): return child raise RuntimeError("Could not find unique directory name") def get_u0(da, transect, factor, case=None): if case is not None: da = get_reset_origin(da, (case.turb_pos_x, case.turb_pos_y, case.turb_pos_z)) da = get_normalised_dims(da, transect.attrs["$D$"]) da = get_normalised_data(da, factor) return da def get_gamma0(da, transect, case=None): if case is not None: da = get_reset_origin(da, (case.turb_pos_x, case.turb_pos_y, case.turb_pos_z)) da = get_normalised_dims(da, transect.attrs["$D$"]) da = get_normalised_data_deficit(da, transect.attrs["$U_\\infty$"], "$\gamma_0$") return da def plot_transects(case, validate, result, factor, ustar_ax, gamma_ax): for i, transect in enumerate(validate): transect_true = transect.to_xarray() # Compare transect transect_sim = result.faces.extract_z(-1, **transect) # Determine plot x-axis major_axis = f"${transect.attrs['major_axis']}^*$" # Create and save a u0 figure transect_sim_u0 = get_u0(transect_sim["$u$"], transect_true, factor, case) transect_sim_u0.plot(ax=ustar_ax[i], x=major_axis, label=f'{case.dx}m') # Create and save a gamma0 figure transect_sim_gamma0 = get_gamma0(transect_sim["$u$"], transect_true, case) transect_sim_gamma0.plot(ax=gamma_ax[i], x=major_axis, label=f'{case.dx}m') def get_rmse(estimated, observed): estimated = estimated[~np.isnan(estimated)] if len(estimated) == 0: return np.nan observed = observed[:len(estimated)] return np.sqrt(((estimated - observed[:len(estimated)]) ** 2).mean()) def get_transect_error(case, validate, result, factor, data): for i, transect in enumerate(validate): transect_true = transect.to_xarray() # Compare transect transect_sim = result.faces.extract_z(-1, **transect) transect_sim_u0 = get_u0(transect_sim["$u$"], transect_true, factor, case) transect_true_u0 = get_u0(transect_true, transect_true, transect_true.attrs["$U_\infty$"], case) # Calculate RMS error and store rmse = get_rmse(transect_sim_u0.values, transect_true_u0.values) data["resolution (m)"].append(case.dx) data["Transect"].append(transect.attrs['description']) data["RMSE"].append(rmse) def get_cells(case): top = (case.x1 - case.x0) * (case.y1 - case.y0) * case.sigma bottom = case.dx * case.dy return top / bottom def check_positive(value): ivalue = int(value) if ivalue <= 0: msg = f"{value} is an invalid positive int value" raise argparse.ArgumentTypeError(msg) return ivalue if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest='MODEL', required=True) parent_parser = argparse.ArgumentParser(add_help=False) parent_parser.add_argument('--experiments', type=check_positive, choices=range(3, 6), default=5, help=("number of experiments to run - defaults " "to 5")) parser_fm = subparsers.add_parser('fm', parents=[parent_parser], help='execute flexible mesh model') parser_fm.add_argument('--threads', type=check_positive, default=1, help=("number of CPU threads to utilise - defaults " "to 1")) parser_structured = subparsers.add_parser('structured', parents=[parent_parser], help='execute structured model') args = parser.parse_args() if "threads" not in args: args.threads = 1 main(args.MODEL, args.experiments, args.threads)
36.003096
79
0.551896
2,686
23,258
4.567386
0.160834
0.018585
0.027388
0.014998
0.473264
0.422563
0.359798
0.314232
0.304777
0.272742
0
0.0184
0.350374
23,258
645
80
36.058915
0.793567
0.046436
0
0.264706
0
0
0.20645
0.023802
0
0
0
0
0
1
0.024887
false
0
0.040724
0
0.08371
0.020362
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d95e400e7414be6bd28582167c1534a6fade0266
15,236
py
Python
GLM/GLM_Model/GLM_Model_GP.py
ys7yoo/npglm
98cc040fff8a861e2d7e210fef049207f1714b2a
[ "MIT" ]
9
2020-11-20T17:43:36.000Z
2021-02-26T22:18:59.000Z
GLM/GLM_Model/GLM_Model_GP.py
ys7yoo/npglm
98cc040fff8a861e2d7e210fef049207f1714b2a
[ "MIT" ]
1
2021-02-04T13:51:17.000Z
2021-02-04T23:56:07.000Z
GLM/GLM_Model/GLM_Model_GP.py
ys7yoo/npglm
98cc040fff8a861e2d7e210fef049207f1714b2a
[ "MIT" ]
1
2020-11-22T19:36:35.000Z
2020-11-22T19:36:35.000Z
import numpy as np import matplotlib.pyplot as plt import torch import scipy from GLM.GLM_Model import GLM_Model, PyTorchObj from scipy.optimize import minimize, Bounds from tqdm import tqdm class GLM_Model_GP(GLM_Model.GLM_Model): def __init__(self, params): super().__init__(params) self.kernel_prep_dict = None self.first_time_train_this_covariate = None self.covariate_training = None self.total_likelihood = None self.total_exp = None self.total_kld = None def add_covariate(self, covariate): super().add_covariate(covariate) self.register_parameter(name=f'{covariate.name}_u', param=covariate.time.time_dict['u']) self.bound_duration_check(covariate) def bound_duration_check(self, covariate): filter_inducing_max = covariate.time.time_dict_t['u']().max() filter_inducing_min = covariate.time.time_dict_t['u']().min() inducing_bdd_max = covariate.bounds_params['u'][1] inducing_bdd_min = covariate.bounds_params['u'][0] if filter_inducing_max > inducing_bdd_max: raise ValueError(f'Upper Bound for {covariate.name} Filter less than initial maximum inducing point') if filter_inducing_min < inducing_bdd_min: raise ValueError(f'Lower Bound for {covariate.name} Filter greater than initial minimum inducing point') def train_variational_parameters(self, kernel_prep_dict, i): self.kernel_prep_dict = kernel_prep_dict self.update_time_bounds() for covariate_name, covariate in self.covariates.items(): if covariate.etc_params['use_basis_form']: continue if i <= 2 or (i > 2 and i % 2 == 0): params_to_optimize = [param for param in self.state_dict().keys() if (param.startswith(covariate_name) and not (param.endswith('_hyper'))) and not (param.endswith('_u'))] else: params_to_optimize = [param for param in self.state_dict().keys() if (param.startswith(covariate_name) and not (param.endswith('_hyper')))] params_to_optimize.append('baseline') for name, param in self.named_parameters(): if name not in params_to_optimize: param.requires_grad = False else: param.requires_grad = True self.update_covariate_gp_objects() self.set_training_parameters(params_to_optimize) # self.optimizer = torch.optim.LBFGS(self.training_parameters, lr=1, history_size=10, max_iter=self.params.gp_variational_iter, line_search_fn='strong_wolfe') # optimizer_closure = self.nll_closure() self.first_time_train_this_covariate = True self.covariate_training = covariate_name self.total_likelihood = torch.zeros(1, dtype=self.params.torch_d_type) self.total_exp = torch.zeros(self.y.shape[0], dtype=self.params.torch_d_type) self.total_kld = torch.zeros(1, dtype=self.params.torch_d_type) maxiter = self.params.gp_variational_iter with tqdm(total=maxiter) as pbar: def verbose(xk): pbar.update(1) obj = PyTorchObj.PyTorchObjective(self, params_to_optimize, self.scipy_closure) xL = scipy.optimize.minimize(obj.fun, obj.x0, method='TNC', jac=obj.jac, callback=verbose, options={'gtol': 1e-6, 'disp': True, 'maxiter': maxiter}) self.update_covariate_design_matrices() self.update_time_bounds() print('done') def add_noise_parameter(self): for covariate_name, covariate in self.covariates.items(): if covariate.etc_params['use_basis_form']: continue covariate.add_noise_param(self) def train_hyperparameters(self, kernel_prep_dict, i): self.kernel_prep_dict = kernel_prep_dict self.update_gp_param_bounds() if i > 4: self.add_noise_parameter() for covariate_name, covariate in self.covariates.items(): if covariate.etc_params['use_basis_form']: continue params_to_optimize = [param for param in self.state_dict().keys() if (param.startswith(covariate_name) and param.endswith('_hyper'))] for name, param in self.named_parameters(): if name not in params_to_optimize: param.requires_grad = False else: param.requires_grad = True # params_to_optimize = [param for param in self.state_dict().keys() if (not param.startswith('History') and # param.endswith('_hyper'))] self.update_covariate_gp_objects() self.set_training_parameters(params_to_optimize) # self.optimizer = torch.optim.LBFGS(self.training_parameters, lr=0.3, history_size=5, max_iter=self.params.gp_hyperparameter_iter, line_search_fn='strong_wolfe') self.first_time_train_this_covariate = True self.covariate_training = covariate_name self.total_likelihood = torch.zeros(1, dtype=self.params.torch_d_type) self.total_exp = torch.zeros(self.y.shape[0], dtype=self.params.torch_d_type) self.total_kld = torch.zeros(1, dtype=self.params.torch_d_type) # optimizer_closure = self.nll_closure_hyper() # self.zero_grad() # print(self.optimizer.step(optimizer_closure)) maxiter = self.params.gp_hyperparameter_iter with tqdm(total=maxiter) as pbar: def verbose(xk): pbar.update(1) obj = PyTorchObj.PyTorchObjective(self, params_to_optimize, self.scipy_closure) xL = scipy.optimize.minimize(obj.fun, obj.x0, method='TNC', jac=obj.jac, callback=verbose, options={'gtol': 1e-6, 'disp': True, 'maxiter': maxiter}) print('done') def scipy_closure(self): self.zero_grad() # TODO self.update_covariate_gp_objects(update_all=False) loss = self.get_nlog_likelihood() return loss def nll_closure(self): def closure(): self.optimizer.zero_grad() # TODO self.update_covariate_gp_objects(update_all=False) loss = self.get_nlog_likelihood() loss.backward() return loss return closure def nll_closure_hyper(self): def closure(): self.optimizer.zero_grad() # TODO self.update_covariate_gp_objects(update_all=False) loss = self.get_nlog_likelihood() loss.backward() return loss return closure def update_covariate_gp_objects(self, update_all=True): if update_all: with torch.no_grad(): for covariate_name, covariate in self.covariates.items(): covariate.gp_obj.update_kernels() covariate.gp_obj.compute_needed_chol_and_inv(self.kernel_prep_dict) self.zero_grad() else: self.covariates[self.covariate_training].gp_obj.update_kernels() self.covariates[self.covariate_training].gp_obj.compute_needed_chol_and_inv(self.kernel_prep_dict) def update_gp_param_bounds(self): for covariate_name, covariate in self.covariates.items(): covariate.update_gp_param_bounds() def update_time_bounds(self): for covariate_name, covariate in self.covariates.items(): covariate.time.update_with_new_bounds('u') def update_covariate_design_matrices(self): for covariate_name, covariate in self.covariates.items(): covariate.update_design_matrix() def get_nlog_likelihood(self, optimize_hyper=False): total_likelihood = torch.zeros(1, dtype=self.params.torch_d_type) total_exp = torch.zeros(self.y.shape[0], dtype=self.params.torch_d_type) total_kld = torch.zeros(1, dtype=self.params.torch_d_type) for covariate_name, cov in self.covariates.items(): if covariate_name != self.covariate_training and not self.first_time_train_this_covariate: continue ll, e_arg, gaussian_term = cov.get_log_likelihood_terms() total_likelihood += self.y @ ll total_exp += e_arg total_kld += gaussian_term if covariate_name != self.covariate_training and self.first_time_train_this_covariate: self.total_likelihood += self.y @ ll self.total_exp += e_arg self.total_kld += gaussian_term if self.first_time_train_this_covariate: total_exp = torch.sum(torch.exp(total_exp + self.baseline * torch.ones(self.y.shape[0], dtype=self.params.torch_d_type))) total_likelihood = total_likelihood + self.y @ (self.baseline * torch.ones(self.y.shape[0], dtype=self.params.torch_d_type)) nll = -1 * (total_likelihood - self.params.delta * total_exp + total_kld) self.first_time_train_this_covariate = False else: total_exp = torch.sum(torch.exp(total_exp + self.total_exp + self.baseline * torch.ones(self.y.shape[0], dtype=self.params.torch_d_type))) total_likelihood = total_likelihood + self.total_likelihood + self.y @ (self.baseline * torch.ones(self.y.shape[0], dtype=self.params.torch_d_type)) nll = -1 * (total_likelihood - self.params.delta * total_exp + total_kld + self.total_kld) return nll def get_nats_per_bin(self, y, exp_arg): lambda_0 = torch.sum(y) / (y.shape[0] * self.params.delta) nats_per_bin = y * exp_arg - self.params.delta * torch.exp(exp_arg) nats_per_bin = nats_per_bin - (y * torch.log(lambda_0) - self.params.delta * lambda_0 * torch.ones_like(y, dtype=self.params.torch_d_type)) # nats_per_bin = nats_per_bin - (y * np.log(lambda_0) - self.params.delta * lambda_0 * np.ones_like(y)) total_num_spikes = torch.sum(y) nll_test_mean = torch.sum(nats_per_bin) / total_num_spikes return nll_test_mean def get_loss(self): total_likelihood = torch.zeros(1, dtype=self.params.torch_d_type) total_exp = torch.zeros(self.y.shape[0], dtype=self.params.torch_d_type) for covariate_name, cov in self.covariates.items(): ll, e_arg = cov.loss() total_likelihood += self.y @ ll total_exp += e_arg total_exp = (total_exp + self.baseline * torch.ones(self.y.shape[0], dtype=self.params.torch_d_type)) total_likelihood = total_likelihood + self.y @ (self.baseline * torch.ones(self.y.shape[0], dtype=self.params.torch_d_type)) loss = -1 * (total_likelihood - self.params.delta * torch.sum(torch.exp(total_exp))) loss = self.get_nats_per_bin(self.y, total_exp) return loss def get_test_loss(self): total_likelihood = torch.zeros(1, dtype=self.params.torch_d_type) total_exp = torch.zeros(self.y_test.shape[0], dtype=self.params.torch_d_type) for covariate_name, cov in self.covariates.items(): ll, e_arg = cov.test_loss() total_likelihood += self.y_test @ ll total_exp += e_arg total_exp = (total_exp + self.baseline * torch.ones(self.y_test.shape[0], dtype=self.params.torch_d_type)) total_likelihood = total_likelihood + self.y_test @ (self.baseline * torch.ones(self.y_test.shape[0], dtype=self.params.torch_d_type)) loss = -1 * (total_likelihood - self.params.delta * torch.sum(torch.exp(total_exp))) loss = self.get_nats_per_bin(self.y_test, total_exp) return loss def plot_covariates(self, evolution_df_dict, timer_obj): timer_obj.time_waste_start() with torch.no_grad(): nll = self.get_loss() nll_test = self.get_test_loss() plt.style.use("ggplot") fig, axs = plt.subplots(2, int(np.ceil(len(self.covariates.keys())/2)), figsize=(3*len(self.covariates.keys()), 10)) axs = axs.flatten() for dx, (name, covariate) in enumerate(self.covariates.items()): if name == 'History': axs[dx].set_ylim([-7, 2]) plot_mean, plot_std, plot_time, entire_mean, entire_std, entire_time = self.covariates[name].get_values_to_plot() plot_time, plot_mean, plot_std = zip(*sorted(zip(plot_time, plot_mean, plot_std))) plot_time = np.array(plot_time) plot_mean = np.array(plot_mean) plot_std = np.array(plot_std) axs[dx].plot(plot_time, plot_mean, label='posterior mean', color='tomato') axs[dx].fill_between(plot_time, plot_mean - 2 * plot_std, plot_mean + 2 * plot_std, alpha=0.3, color='salmon') if not covariate.etc_params['use_basis_form']: axs[dx].plot(self.covariates[name].time.time_dict_t['u']().data.detach().numpy(), np.zeros(self.covariates[name].time.time_dict['u'].shape[0]), 'o', color='orange', label='inducing points') axs[dx].axhline(y=0, linestyle='--', zorder=0) axs[dx].axvline(x=0, linestyle='--', zorder=0) axs[dx].set_title(name) axs[dx].legend() ev_dx = evolution_df_dict[name].shape[0] evolution_df_dict[name].at[ev_dx, 'plot_mean'] = np.copy(plot_mean) evolution_df_dict[name].at[ev_dx, 'plot_2std'] = np.copy(2 * plot_std) evolution_df_dict[name].at[ev_dx, 'plot_time'] = np.copy(plot_time) evolution_df_dict[name].at[ev_dx, 'entire_mean'] = np.copy(entire_mean) evolution_df_dict[name].at[ev_dx, 'entire_2std'] = np.copy(2 * entire_std) evolution_df_dict[name].at[ev_dx, 'entire_time'] = np.copy(entire_time) evolution_df_dict[name].at[ev_dx, 'nll'] = np.copy(nll.data.detach().numpy()) evolution_df_dict[name].at[ev_dx, 'nll_test'] = np.copy(nll_test.data.detach().numpy()) timer_obj.time_waste_end() evolution_df_dict[name].at[ev_dx, 'time_so_far'] = timer_obj.get_time() timer_obj.time_waste_start() evolution_df_dict[name].to_pickle(f'{self.params.gp_ev_path}_{name}') plt.subplots_adjust(hspace=1.0) plt.savefig(self.params.gp_filter_plot_path, dpi=300) print(f'nll: {nll_test.data.detach().numpy()}') plt.show() timer_obj.time_waste_end()
46.169697
174
0.616894
1,959
15,236
4.509954
0.127106
0.044143
0.037351
0.049802
0.68987
0.617091
0.559932
0.535031
0.498585
0.485456
0
0.007089
0.277829
15,236
329
175
46.31003
0.795874
0.051523
0
0.448133
0
0
0.03686
0.004365
0
0
0
0.00304
0
1
0.091286
false
0
0.029046
0
0.161826
0.012448
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d95eed5d862d9b62ea1af084b7b9d3c23fb6a1ce
13,127
py
Python
c-deps/krb5/src/tests/t_preauth.py
Yangjxxxxx/ZNBase
dcf993b73250dd5cb63041f4d9cf098941f67b2b
[ "MIT", "BSD-3-Clause" ]
1
2021-12-03T05:07:39.000Z
2021-12-03T05:07:39.000Z
c-deps/krb5/src/tests/t_preauth.py
Yangjxxxxx/ZNBase
dcf993b73250dd5cb63041f4d9cf098941f67b2b
[ "MIT", "BSD-3-Clause" ]
9
2020-05-13T16:28:13.000Z
2021-12-30T04:07:49.000Z
src/tests/t_preauth.py
frozencemetery/krb5
bb8fa495d00ccd931eec87a01b8920636cf7903e
[ "MIT" ]
4
2020-07-01T12:41:46.000Z
2022-01-26T03:05:30.000Z
from k5test import * # Test that the kdcpreauth client_keyblock() callback matches the key # indicated by the etype info, and returns NULL if no key was selected. testpreauth = os.path.join(buildtop, 'plugins', 'preauth', 'test', 'test.so') conf = {'plugins': {'kdcpreauth': {'module': 'test:' + testpreauth}, 'clpreauth': {'module': 'test:' + testpreauth}}} realm = K5Realm(create_host=False, get_creds=False, krb5_conf=conf) realm.run([kadminl, 'modprinc', '+requires_preauth', realm.user_princ]) realm.run([kadminl, 'setstr', realm.user_princ, 'teststring', 'testval']) realm.run([kadminl, 'addprinc', '-nokey', '+requires_preauth', 'nokeyuser']) realm.kinit(realm.user_princ, password('user'), expected_msg='testval') realm.kinit('nokeyuser', password('user'), expected_code=1, expected_msg='no key') # Preauth type -123 is the test preauth module type; 133 is FAST # PA-FX-COOKIE; 2 is encrypted timestamp. # Test normal preauth flow. mark('normal') msgs = ('Sending unauthenticated request', '/Additional pre-authentication required', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', 'Decrypted AS reply') realm.run(['./icred', realm.user_princ, password('user')], expected_msg='testval', expected_trace=msgs) # Test successful optimistic preauth. mark('optimistic') expected_trace = ('Attempting optimistic preauth', 'Processing preauth types: -123', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: -123', 'Decrypted AS reply') realm.run(['./icred', '-o', '-123', realm.user_princ, password('user')], expected_trace=expected_trace) # Test optimistic preauth failing on client, falling back to encrypted # timestamp. mark('optimistic (client failure)') msgs = ('Attempting optimistic preauth', 'Processing preauth types: -123', '/induced optimistic fail', 'Sending unauthenticated request', '/Additional pre-authentication required', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Encrypted timestamp (for ', 'module encrypted_timestamp (2) (real) returned: 0/Success', 'preauth for next request: PA-FX-COOKIE (133), PA-ENC-TIMESTAMP (2)', 'Decrypted AS reply') realm.run(['./icred', '-o', '-123', '-X', 'fail_optimistic', realm.user_princ, password('user')], expected_trace=msgs) # Test optimistic preauth failing on KDC, falling back to encrypted # timestamp. mark('optimistic (KDC failure)') realm.run([kadminl, 'setstr', realm.user_princ, 'failopt', 'yes']) msgs = ('Attempting optimistic preauth', 'Processing preauth types: -123', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: -123', '/Preauthentication failed', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Encrypted timestamp (for ', 'module encrypted_timestamp (2) (real) returned: 0/Success', 'preauth for next request: PA-FX-COOKIE (133), PA-ENC-TIMESTAMP (2)', 'Decrypted AS reply') realm.run(['./icred', '-o', '-123', realm.user_princ, password('user')], expected_trace=msgs) # Leave failopt set for the next test. # Test optimistic preauth failing on KDC, stopping because the test # module disabled fallback. mark('optimistic (KDC failure, no fallback)') msgs = ('Attempting optimistic preauth', 'Processing preauth types: -123', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: -123', '/Preauthentication failed') realm.run(['./icred', '-X', 'disable_fallback', '-o', '-123', realm.user_princ, password('user')], expected_code=1, expected_msg='Preauthentication failed', expected_trace=msgs) realm.run([kadminl, 'delstr', realm.user_princ, 'failopt']) # Test KDC_ERR_MORE_PREAUTH_DATA_REQUIRED and secure cookies. mark('second round-trip') realm.run([kadminl, 'setstr', realm.user_princ, '2rt', 'secondtrip']) msgs = ('Sending unauthenticated request', '/Additional pre-authentication required', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', '/More preauthentication data is required', 'Continuing preauth mech -123', 'Processing preauth types: -123, PA-FX-COOKIE (133)', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', 'Decrypted AS reply') realm.run(['./icred', realm.user_princ, password('user')], expected_msg='2rt: secondtrip', expected_trace=msgs) # Test client-side failure after KDC_ERR_MORE_PREAUTH_DATA_REQUIRED, # falling back to encrypted timestamp. mark('second round-trip (client failure)') msgs = ('Sending unauthenticated request', '/Additional pre-authentication required', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', '/More preauthentication data is required', 'Continuing preauth mech -123', 'Processing preauth types: -123, PA-FX-COOKIE (133)', '/induced 2rt fail', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Encrypted timestamp (for ', 'module encrypted_timestamp (2) (real) returned: 0/Success', 'preauth for next request: PA-FX-COOKIE (133), PA-ENC-TIMESTAMP (2)', 'Decrypted AS reply') realm.run(['./icred', '-X', 'fail_2rt', realm.user_princ, password('user')], expected_msg='2rt: secondtrip', expected_trace=msgs) # Test client-side failure after KDC_ERR_MORE_PREAUTH_DATA_REQUIRED, # stopping because the test module disabled fallback. mark('second round-trip (client failure, no fallback)') msgs = ('Sending unauthenticated request', '/Additional pre-authentication required', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', '/More preauthentication data is required', 'Continuing preauth mech -123', 'Processing preauth types: -123, PA-FX-COOKIE (133)', '/induced 2rt fail') realm.run(['./icred', '-X', 'fail_2rt', '-X', 'disable_fallback', realm.user_princ, password('user')], expected_code=1, expected_msg='Pre-authentication failed: induced 2rt fail', expected_trace=msgs) # Test KDC-side failure after KDC_ERR_MORE_PREAUTH_DATA_REQUIRED, # falling back to encrypted timestamp. mark('second round-trip (KDC failure)') realm.run([kadminl, 'setstr', realm.user_princ, 'fail2rt', 'yes']) msgs = ('Sending unauthenticated request', '/Additional pre-authentication required', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', '/More preauthentication data is required', 'Continuing preauth mech -123', 'Processing preauth types: -123, PA-FX-COOKIE (133)', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', '/Preauthentication failed', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Encrypted timestamp (for ', 'module encrypted_timestamp (2) (real) returned: 0/Success', 'preauth for next request: PA-FX-COOKIE (133), PA-ENC-TIMESTAMP (2)', 'Decrypted AS reply') realm.run(['./icred', realm.user_princ, password('user')], expected_msg='2rt: secondtrip', expected_trace=msgs) # Leave fail2rt set for the next test. # Test KDC-side failure after KDC_ERR_MORE_PREAUTH_DATA_REQUIRED, # stopping because the test module disabled fallback. mark('second round-trip (KDC failure, no fallback)') msgs = ('Sending unauthenticated request', '/Additional pre-authentication required', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', '/More preauthentication data is required', 'Continuing preauth mech -123', 'Processing preauth types: -123, PA-FX-COOKIE (133)', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', '/Preauthentication failed') realm.run(['./icred', '-X', 'disable_fallback', realm.user_princ, password('user')], expected_code=1, expected_msg='Preauthentication failed', expected_trace=msgs) realm.run([kadminl, 'delstr', realm.user_princ, 'fail2rt']) # Test tryagain flow by inducing a KDC_ERR_ENCTYPE_NOSUPP error on the KDC. mark('tryagain') realm.run([kadminl, 'setstr', realm.user_princ, 'err', 'testagain']) msgs = ('Sending unauthenticated request', '/Additional pre-authentication required', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', '/KDC has no support for encryption type', 'Recovering from KDC error 14 using preauth mech -123', 'Preauth tryagain input types (-123): -123, PA-FX-COOKIE (133)', 'Preauth module test (-123) tryagain returned: 0/Success', 'Followup preauth for next request: -123, PA-FX-COOKIE (133)', 'Decrypted AS reply') realm.run(['./icred', realm.user_princ, password('user')], expected_msg='tryagain: testagain', expected_trace=msgs) # Test a client-side tryagain failure, falling back to encrypted # timestamp. mark('tryagain (client failure)') msgs = ('Sending unauthenticated request', '/Additional pre-authentication required', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', '/KDC has no support for encryption type', 'Recovering from KDC error 14 using preauth mech -123', 'Preauth tryagain input types (-123): -123, PA-FX-COOKIE (133)', '/induced tryagain fail', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Encrypted timestamp (for ', 'module encrypted_timestamp (2) (real) returned: 0/Success', 'preauth for next request: PA-FX-COOKIE (133), PA-ENC-TIMESTAMP (2)', 'Decrypted AS reply') realm.run(['./icred', '-X', 'fail_tryagain', realm.user_princ, password('user')], expected_trace=msgs) # Test a client-side tryagain failure, stopping because the test # module disabled fallback. mark('tryagain (client failure, no fallback)') msgs = ('Sending unauthenticated request', '/Additional pre-authentication required', 'Preauthenticating using KDC method data', 'Processing preauth types:', 'Preauth module test (-123) (real) returned: 0/Success', 'Produced preauth for next request: PA-FX-COOKIE (133), -123', '/KDC has no support for encryption type', 'Recovering from KDC error 14 using preauth mech -123', 'Preauth tryagain input types (-123): -123, PA-FX-COOKIE (133)', '/induced tryagain fail') realm.run(['./icred', '-X', 'fail_tryagain', '-X', 'disable_fallback', realm.user_princ, password('user')], expected_code=1, expected_msg='KDC has no support for encryption type', expected_trace=msgs) # Test that multiple stepwise initial creds operations can be # performed with the same krb5_context, with proper tracking of # clpreauth module request handles. mark('interleaved') realm.run([kadminl, 'addprinc', '-pw', 'pw', 'u1']) realm.run([kadminl, 'addprinc', '+requires_preauth', '-pw', 'pw', 'u2']) realm.run([kadminl, 'addprinc', '+requires_preauth', '-pw', 'pw', 'u3']) realm.run([kadminl, 'setstr', 'u2', '2rt', 'extra']) out = realm.run(['./icinterleave', 'pw', 'u1', 'u2', 'u3']) if out != ('step 1\nstep 2\nstep 3\nstep 1\nfinish 1\nstep 2\nno attr\n' 'step 3\nno attr\nstep 2\n2rt: extra\nstep 3\nfinish 3\nstep 2\n' 'finish 2\n'): fail('unexpected output from icinterleave') success('Pre-authentication framework tests')
49.349624
79
0.665346
1,576
13,127
5.475888
0.120558
0.025029
0.031286
0.039166
0.829316
0.819235
0.793627
0.763152
0.728969
0.692005
0
0.032068
0.199436
13,127
265
80
49.535849
0.789133
0.11564
0
0.709677
0
0.032258
0.616049
0
0
0
0
0
0
1
0
false
0.069124
0.004608
0
0.004608
0
0
0
0
null
0
0
0
1
1
1
1
1
1
0
0
0
0
0
0
0
0
0
0
1
0
0
1
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
9
d96094c005965d2c5403a91fbbccf6c6f031c21a
4,303
py
Python
src/coreclr/scripts/antigen_unique_issues.py
KirillOsenkov/runtime
11742903dcc40a55e8688a1c61291459215f8ed0
[ "MIT" ]
1
2021-06-18T04:59:29.000Z
2021-06-18T04:59:29.000Z
src/coreclr/scripts/antigen_unique_issues.py
KirillOsenkov/runtime
11742903dcc40a55e8688a1c61291459215f8ed0
[ "MIT" ]
1
2021-11-11T02:02:54.000Z
2021-11-13T00:05:50.000Z
src/coreclr/scripts/antigen_unique_issues.py
KirillOsenkov/runtime
11742903dcc40a55e8688a1c61291459215f8ed0
[ "MIT" ]
1
2021-12-03T00:19:45.000Z
2021-12-03T00:19:45.000Z
#!/usr/bin/env python3 # ## Licensed to the .NET Foundation under one or more agreements. ## The .NET Foundation licenses this file to you under the MIT license. # ## # Title: antigen_unique_issues.py # # Notes: # # Script to identify unique issues from all partitions and print them on console. # ################################################################################ ################################################################################ # import sys import argparse import os from os import walk from coreclr_arguments import * import re parser = argparse.ArgumentParser(description="description") parser.add_argument("-issues_directory", help="Path to issues directory") unique_issue_dir_pattern = re.compile(r"\*\*\*\* .*UniqueIssue\d+") assertion_patterns = [re.compile(r"Assertion failed '(.*)' in '.*' during '(.*)'"), re.compile(r"Assert failure\(PID \d+ \[0x[0-9a-f]+], Thread: \d+ \[0x[0-9a-f]+]\):(.*)")] def setup_args(args): """ Setup the args. Args: args (ArgParse): args parsed by arg parser Returns: args (CoreclrArguments) """ coreclr_args = CoreclrArguments(args, require_built_core_root=False, require_built_product_dir=False, require_built_test_dir=False, default_build_type="Checked") coreclr_args.verify(args, "run_configuration", lambda unused: True, "Unable to set run_configuration") coreclr_args.verify(args, "issues_directory", lambda issues_directory: os.path.isdir(issues_directory), "issues_directory doesn't exist") return coreclr_args def print_unique_issues_summary(issues_directory): """Merge issues-summary-*-PartitionN.txt files from each partitions and print unique issues Args: issues_directory (string): Issues directory Returns: Number of issues found """ issues_found = 0 unique_issues_all_partitions = {} for file_path, dirs, files in walk(issues_directory, topdown=True): for file_name in files: if not file_name.startswith("issues-summary-") or "Partition" not in file_name: continue issues_summary_file = os.path.join(file_path, file_name) partition_name = file_path.split(os.sep)[-1] add_header = True unique_issues = [] with open(issues_summary_file, 'r') as sf: contents = sf.read() unique_issues = list(filter(None, re.split(unique_issue_dir_pattern, contents))) # Iterate over all unique issues of this partition for unique_issue in unique_issues: # Find the matching assertion message for assertion_pattern in assertion_patterns: issue_match = re.search(assertion_pattern, unique_issue) if issue_match is not None: assert_string = " ".join(issue_match.groups()) # Check if previous partitions has already seen this assert if assert_string not in unique_issues_all_partitions: unique_issues_all_partitions[assert_string] = unique_issue issues_found += 1 if add_header: print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% {} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%".format(partition_name)) add_header = False print(unique_issue.strip()) print("------------------------------------") break print("===== Found {} unique issues.".format(issues_found)) return issues_found def main(main_args): """Main entrypoint Args: main_args ([type]): Arguments to the script """ coreclr_args = setup_args(main_args) issues_directory = coreclr_args.issues_directory issues_found = print_unique_issues_summary(issues_directory) return 1 if issues_found > 0 else 0 if __name__ == "__main__": args = parser.parse_args() sys.exit(main(args))
36.466102
166
0.563096
455
4,303
5.087912
0.349451
0.067387
0.032829
0.032397
0.039741
0.033693
0
0
0
0
0
0.004225
0.284918
4,303
117
167
36.777778
0.748131
0.182198
0
0.033333
0
0.016667
0.152267
0.047488
0
0
0
0
0.116667
1
0.05
false
0
0.083333
0
0.183333
0.1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d9610b878d44c5a8266abce88c386c3e59afd553
1,448
py
Python
src/secml/ml/peval/metrics/c_metric_test_error.py
zangobot/secml
95a293e1201c24256eb7fe2f1d2125cd5f318c8c
[ "Apache-2.0" ]
63
2020-04-20T16:31:16.000Z
2022-03-29T01:05:35.000Z
src/secml/ml/peval/metrics/c_metric_test_error.py
zangobot/secml
95a293e1201c24256eb7fe2f1d2125cd5f318c8c
[ "Apache-2.0" ]
5
2020-04-21T11:31:39.000Z
2022-03-24T13:42:56.000Z
src/secml/ml/peval/metrics/c_metric_test_error.py
zangobot/secml
95a293e1201c24256eb7fe2f1d2125cd5f318c8c
[ "Apache-2.0" ]
8
2020-04-21T09:16:42.000Z
2022-02-23T16:28:43.000Z
""" .. module:: CMetricTestError :synopsis: Performance Metric: Test Error .. moduleauthor:: Marco Melis <marco.melis@unica.it> """ import sklearn.metrics as skm from secml.array import CArray from secml.ml.peval.metrics import CMetric class CMetricTestError(CMetric): """Performance evaluation metric: Test Error. Test Error score is the percentage (inside 0/1 range) of wrongly predicted labels (inverse of accuracy). The metric uses: - y_true (true ground labels) - y_pred (predicted labels) Attributes ---------- class_type : 'test-error' Examples -------- >>> from secml.ml.peval.metrics import CMetricTestError >>> from secml.array import CArray >>> peval = CMetricTestError() >>> print(peval.performance_score(CArray([0, 1, 2, 3]), CArray([0, 1, 1, 3]))) 0.25 """ __class_type = 'test-error' best_value = 0.0 def _performance_score(self, y_true, y_pred): """Computes the Accuracy score. Parameters ---------- y_true : CArray Ground truth (true) labels or target scores. y_pred : CArray Predicted labels, as returned by a CClassifier. Returns ------- metric : float Returns metric value as float. """ return 1.0 - float(skm.accuracy_score(y_true.tondarray(), y_pred.tondarray()))
24.542373
82
0.600138
166
1,448
5.13253
0.421687
0.052817
0.035211
0.046948
0.129108
0.068075
0
0
0
0
0
0.016346
0.281768
1,448
58
83
24.965517
0.802885
0.608425
0
0
0
0
0.02551
0
0
0
0
0
0
1
0.111111
false
0
0.333333
0
0.888889
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
1
d96292f6031d95ffe48e989555808517308f5c23
35,592
py
Python
titer_model/implementation-nextstrain-augur/base/process.py
blab/dengue
5eacc47fbd77c59e7342d5be4aa81f7d3b4ff0bf
[ "CC-BY-4.0", "MIT" ]
4
2019-03-31T22:03:48.000Z
2020-06-16T21:04:24.000Z
titer_model/implementation-nextstrain-augur/base/process.py
emmahodcroft/dengue-antigenic-dynamics
5eacc47fbd77c59e7342d5be4aa81f7d3b4ff0bf
[ "CC-BY-4.0", "MIT" ]
4
2018-10-12T02:13:10.000Z
2019-07-24T02:44:53.000Z
titer_model/implementation-nextstrain-augur/base/process.py
emmahodcroft/dengue-antigenic-dynamics
5eacc47fbd77c59e7342d5be4aa81f7d3b4ff0bf
[ "CC-BY-4.0", "MIT" ]
5
2018-09-10T23:14:09.000Z
2020-12-27T20:57:34.000Z
from __future__ import division, print_function import argparse import sys, os, time, gzip, glob from collections import defaultdict from base.config import combine_configs from base.io_util import make_dir, remove_dir, tree_to_json, write_json, myopen from base.sequences_process import sequence_set from base.utils import num_date, save_as_nexus, parse_date from base.tree import tree # from base.fitness_model import fitness_model from base.frequencies import alignment_frequencies, tree_frequencies, make_pivots from base.auspice_export import export_metadata_json, export_frequency_json, export_tip_frequency_json import numpy as np from datetime import datetime import json from pdb import set_trace from base.logger import logger from Bio import SeqIO from Bio import AlignIO import cPickle as pickle def collect_args(): parser = argparse.ArgumentParser( description = "Process (prepared) JSON(s)", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('-j', '--json', help="prepared JSON to process") parser.add_argument('--clean', default=False, action='store_true', help="clean build (remove previous checkpoints)") parser.add_argument('--tree_method', type=str, default='raxml', choices=["fasttree", "raxml", "iqtree"], help="specify the method used to build the tree") parser.add_argument('--no_tree', action='store_true', help="do not build a tree") return parser class process(object): """process influenza virus sequences in mutliple steps to allow visualization in browser * filtering and parsing of sequences * alignment * tree building * frequency estimation of clades and mutations * export as json """ def __init__(self, config): """ check config file, make necessary directories, set up logger """ super(process, self).__init__() self.config = combine_configs("process", config) # try: # assert(os.path.basename(os.getcwd()) == self.config["dir"]) # except AssertionError: # print("Run this script from within the {} directory".format(self.config["dir"])) # sys.exit(2) for p in self.config["output"].values(): if not os.path.isdir(p): os.makedirs(p) self.log = logger(self.config["output"]["data"], False) # parse the JSON into different data bits try: with open(self.config["in"], 'r') as fh: data = json.load(fh) except Exception as e: self.log.fatal("Error loading JSON. Error: {}".format(e)) self.info = data["info"] if "time_interval" in data["info"]: self.info["time_interval"] = [datetime.strptime(x, '%Y-%m-%d').date() for x in data["info"]["time_interval"]] self.info["lineage"] = data["info"]["lineage"] if 'leaves' in data: self.tree_leaves = data['leaves'] try: self.colors = data["colors"] except KeyError: self.log.notify("* colours have not been set") self.colors = False try: self.lat_longs = data["lat_longs"] except KeyError: self.log.notify("* latitude & longitudes have not been set") self.lat_longs = False # backwards compatability - set up file_dumps (need to rewrite sometime) # self.sequence_fname = self.input_data_path+'.fasta' self.file_dumps = {} self.output_path = os.path.join(self.config["output"]["data"], self.info["prefix"]) self.file_dumps['seqs'] = self.output_path + '_sequences.pkl.gz' self.file_dumps['tree'] = self.output_path + '_tree.newick' self.file_dumps['nodes'] = self.output_path + '_nodes.pkl.gz' if self.config["clean"] == True: self.log.notify("Removing intermediate files for a clean build") for f in glob.glob(self.output_path+"*"): os.remove(f) if "reference" in data: self.seqs = sequence_set(self.log, data["sequences"], data["reference"], self.info["date_format"]) else: self.log.fatal("No reference provided. Cannot continue.") # self.seqs = sequence_set(self.log, data["sequences"], False, self.info["date_format"]) # backward compatability self.reference_seq = self.seqs.reference_seq self.proteins = self.seqs.proteins for trait in self.info["traits_are_dates"]: self.seqs.convert_trait_to_numerical_date(trait, self.info["date_format"]) # Prepare titers if they are available. if "titers" in data: self.log.debug("Loaded %i titer measurements" % len(data["titers"])) # Convert titer dictionary indices from JSON-compatible strings back # to tuples. self.titers = {eval(key): value for key, value in data["titers"].iteritems()} ## usefull flag to set (from pathogen run file) to disable restoring self.try_to_restore = True def dump(self): ''' write the current state to file ''' self.log.warn("unsure if dump() works") from cPickle import dump from Bio import Phylo for attr_name, fname in self.file_dumps.iteritems(): if hasattr(self,attr_name): print("dumping",attr_name) #if attr_name=='seqs': self.seqs.all_seqs = None with myopen(fname, 'wb') as ofile: if attr_name=='nodes': continue elif attr_name=='tree': #biopython trees don't pickle well, write as newick + node info self.tree.dump(fname, self.file_dumps['nodes']) else: dump(getattr(self,attr_name), ofile, -1) def load(self, debug=False): ''' reconstruct instance from files ''' self.log.warn("unsure if load() works") from cPickle import load for attr_name, fname in self.file_dumps.iteritems(): if attr_name=='tree': continue if os.path.isfile(fname): with myopen(fname, 'r') as ifile: print('loading',attr_name,'from file',fname) setattr(self, attr_name, load(ifile)) tree_name = self.file_dumps['tree'] if os.path.isfile(tree_name): if os.path.isfile(self.file_dumps['nodes']): node_file = self.file_dumps['nodes'] else: node_file = None # load tree, build if no tree file available self.build_tree(tree_name, node_file, root='none', debug=debug) def align(self, codon_align=False, debug=False, fill_gaps=False): ''' (1) Align sequences, remove non-reference insertions NB step 1 is skipped if a valid aln file is found (2) Translate (3) Write to multi-fasta CODON ALIGNMENT IS NOT IMPLEMENTED ''' fnameStripped = self.output_path + "_aligned_stripped.mfa" if self.try_to_restore: self.seqs.try_restore_align_from_disk(fnameStripped) if not hasattr(self.seqs, "aln"): if codon_align: self.seqs.codon_align() else: self.seqs.align(self.config["subprocess_verbosity_level"], debug=debug) # need to redo everything self.try_to_restore = False self.seqs.strip_non_reference() if fill_gaps: self.seqs.make_gaps_ambiguous() else: self.seqs.make_terminal_gaps_ambiguous() AlignIO.write(self.seqs.aln, fnameStripped, 'fasta') if not self.seqs.reference_in_dataset: self.seqs.remove_reference_from_alignment() # if outgroup is not None: # self.seqs.clock_filter(n_iqd=3, plot=False, max_gaps=0.05, root_seq=outgroup) self.seqs.translate() # creates self.seqs.translations # save additional translations - disabled for now # for name, msa in self.seqs.translations.iteritems(): # SeqIO.write(msa, self.output_path + "_aligned_" + name + ".mfa", "fasta") def get_pivots_via_spacing(self): try: time_interval = self.info["time_interval"] assert("pivot_spacing" in self.config) except AssertionError: self.log.fatal("Cannot space pivots without prividing \"pivot_spacing\" in the config") except KeyError: self.log.fatal("Cannot space pivots without a time interval in the prepared JSON") return np.arange(time_interval[1].year+(time_interval[1].month-1)/12.0, time_interval[0].year+time_interval[0].month/12.0, self.config["pivot_spacing"]) def restore_mutation_frequencies(self): if self.try_to_restore: try: with open(self.output_path + "_mut_freqs.pickle", 'rb') as fh: pickle_seqs = pickle.load(fh) assert(pickle_seqs == set(self.seqs.seqs.keys())) pickled = pickle.load(fh) assert(len(pickled) == 3) self.mutation_frequencies = pickled[0] self.mutation_frequency_confidence = pickled[1] self.mutation_frequency_counts = pickled[2] self.log.notify("Successfully restored mutation frequencies") return except IOError: pass except AssertionError as err: self.log.notify("Tried to restore mutation frequencies but failed: {}".format(err)) #no need to remove - we'll overwrite it shortly self.mutation_frequencies = {} self.mutation_frequency_confidence = {} self.mutation_frequency_counts = {} def estimate_mutation_frequencies(self, inertia=0.0, min_freq=0.01, stiffness=20.0, pivots=24, region="global", include_set={}): ''' calculate the frequencies of mutation in a particular region currently the global frequencies should be estimated first because this defines the set of positions at which frequencies in other regions are estimated. ''' if not hasattr(self.seqs, 'aln'): self.log.warn("Align sequences first") return def filter_alignment(aln, region=None, lower_tp=None, upper_tp=None): from Bio.Align import MultipleSeqAlignment tmp = aln if region is not None: if type(region)==str: tmp = [s for s in tmp if s.attributes['region']==region] elif type(region)==list: tmp = [s for s in tmp if s.attributes['region'] in region] else: self.log.warn("region must be string or list") return if lower_tp is not None: tmp = [s for s in tmp if np.mean(s.attributes['num_date'])>=lower_tp] if upper_tp is not None: tmp = [s for s in tmp if np.mean(s.attributes['num_date'])<upper_tp] return MultipleSeqAlignment(tmp) if not hasattr(self, 'pivots'): tps = np.array([np.mean(x.attributes['num_date']) for x in self.seqs.seqs.values()]) self.pivots=make_pivots(pivots, tps) # else: # self.log.notify('estimate_mutation_frequencies: using self.pivots') if not hasattr(self, 'mutation_frequencies'): self.restore_mutation_frequencies() # loop over nucleotide sequences and translations and calcuate # region specific frequencies of mutations above a certain threshold if type(region)==str: region_name = region region_match = region elif type(region)==tuple: region_name=region[0] region_match=region[1] else: self.log.warn("region must be string or tuple") return # loop over different alignment types for prot, aln in [('nuc',self.seqs.aln)] + self.seqs.translations.items(): if (region_name,prot) in self.mutation_frequencies: self.log.notify("Skipping Frequency Estimation for region \"{}\", protein \"{}\"".format(region_name, prot)) continue self.log.notify("Starting Frequency Estimation for region \"{}\", protein \"{}\"".format(region_name, prot)) # determine set of positions that have to have a frequency calculated if prot in include_set: tmp_include_set = [x for x in include_set[prot]] else: tmp_include_set = [] tmp_aln = filter_alignment(aln, region = None if region=='global' else region_match, lower_tp=self.pivots[0], upper_tp=self.pivots[-1]) if ('global', prot) in self.mutation_frequencies: tmp_include_set += set([pos for (pos, mut) in self.mutation_frequencies[('global', prot)]]) time_points = [np.mean(x.attributes['num_date']) for x in tmp_aln] if len(time_points)==0: self.log.notify('no samples in region {} (protein: {})'.format(region_name, prot)) self.mutation_frequency_counts[region_name]=np.zeros_like(self.pivots) continue # instantiate alignment frequency aln_frequencies = alignment_frequencies(tmp_aln, time_points, self.pivots, ws=max(2,len(time_points)//10), inertia=inertia, stiffness=stiffness, method='SLSQP') if prot=='nuc': # if this is a nucleotide alignment, set all non-canonical states to N A = aln_frequencies.aln A[~((A=='A')|(A=='C')|(A=='G')|(A=='T')|('A'=='-'))] = 'N' aln_frequencies.mutation_frequencies(min_freq=min_freq, include_set=tmp_include_set, ignore_char='N' if prot=='nuc' else 'X') self.mutation_frequencies[(region_name,prot)] = aln_frequencies.frequencies self.mutation_frequency_confidence[(region_name,prot)] = aln_frequencies.calc_confidence() self.mutation_frequency_counts[region_name]=aln_frequencies.counts self.log.notify("Saving mutation frequencies (pickle)") with open(self.output_path + "_mut_freqs.pickle", 'wb') as fh: pickle.dump(set(self.seqs.seqs.keys()), fh, protocol=pickle.HIGHEST_PROTOCOL) pickle.dump((self.mutation_frequencies, self.mutation_frequency_confidence, self.mutation_frequency_counts), fh, protocol=pickle.HIGHEST_PROTOCOL) def global_frequencies(self, min_freq, average_global=False, inertia=2.0/12, stiffness=2.0*12): # set pivots and define groups of larger regions for frequency display pivots = self.get_pivots_via_spacing() acronyms = set([x[1] for x in self.info["regions"] if x[1]!=""]) region_groups = {str(x):[str(y[0]) for y in self.info["regions"] if y[1] == x] for x in acronyms} pop_sizes = {str(x):np.sum([y[-1] for y in self.info["regions"] if y[1] == x]) for x in acronyms} total_popsize = np.sum(pop_sizes.values()) # if global frequencies are to be calculated from the set of sequences, do the following if average_global==False: self.estimate_mutation_frequencies(pivots=pivots, min_freq=min_freq, inertia=np.exp(-inertia), stiffness=stiffness) for region in region_groups.iteritems(): self.estimate_mutation_frequencies(region=region, min_freq=min_freq, inertia=np.exp(-inertia), stiffness=stiffness) return # ELSE: # if global frequences are to be calculated from a weighted average of regional ones # the following applies: # determine sites whose frequencies need to be computed in all regions self.seqs.diversity_statistics() include_set = {} for prot in ['nuc'] + self.seqs.translations.keys(): include_set[prot] = np.where(np.sum(self.seqs.af[prot][:-2]**2, axis=0) <np.sum(self.seqs.af[prot][:-2], axis=0)**2-min_freq)[0] # estimate frequencies in individual regions for region in region_groups.iteritems(): self.estimate_mutation_frequencies(pivots=pivots, region=region, min_freq=min_freq, include_set=include_set, inertia=np.exp(-inertia), stiffness=stiffness) # perform a weighted average of frequencies across the regions to determine # global frequencies. # First: compute the weights accounting for seasonal variation and populations size weights = {region: np.array(self.mutation_frequency_counts[region], dtype = float) for region in acronyms} for region in weights: # map maximal count across time to 1.0, weigh by pop size weights[region] = np.maximum(0.1, weights[region]/weights[region].max()) weights[region]*=pop_sizes[region] # compute the normalizer total_weight = np.sum([weights[region] for region in acronyms],axis=0) # average regional frequencies to calculate global for prot in ['nuc'] + self.seqs.translations.keys(): gl_freqs, gl_counts, gl_confidence = {}, {}, {} all_muts = set() for region in acronyms: # list all unique mutations all_muts.update(self.mutation_frequencies[(region, prot)].keys()) for mut in all_muts: # compute the weighted average gl_freqs[mut] = np.sum([self.mutation_frequencies[(region, prot)][mut]*weights[region] for region in acronyms if mut in self.mutation_frequencies[(region, prot)]], axis=0)/total_weight gl_confidence[mut] = np.sqrt(np.sum([self.mutation_frequency_confidence[(region, prot)][mut]**2*weights[region] for region in acronyms if mut in self.mutation_frequencies[(region, prot)]], axis=0)/total_weight) gl_counts = np.sum([self.mutation_frequency_counts[region] for region in acronyms if mut in self.mutation_frequencies[(region, prot)]], axis=0) # save in mutation_frequency data structure self.mutation_frequencies[("global", prot)] = gl_freqs self.mutation_frequency_counts["global"] = gl_counts self.mutation_frequency_confidence[("global", prot)] = gl_confidence def save_tree_frequencies(self): """ Save tree frequencies to a pickle on disk. """ self.log.notify("Saving tree frequencies (pickle)") with open(self.output_path + "_tree_freqs.pickle", 'wb') as fh: pickle.dump(set(self.seqs.seqs.keys()), fh, protocol=pickle.HIGHEST_PROTOCOL) pickle.dump((self.tree_frequencies, self.tree_frequency_confidence, self.tree_frequency_counts, self.pivots), fh, protocol=pickle.HIGHEST_PROTOCOL) def restore_tree_frequencies(self): try: assert(self.try_to_restore == True) with open(self.output_path + "_tree_freqs.pickle", 'rb') as fh: pickle_seqs = pickle.load(fh) assert(pickle_seqs == set(self.seqs.seqs.keys())) pickled = pickle.load(fh) assert(len(pickled) == 4) self.tree_frequencies = pickled[0] self.tree_frequency_confidence = pickled[1] self.tree_frequency_counts = pickled[2] self.pivots = pickled[3] self.log.notify("Successfully restored tree frequencies") return except IOError: pass except AssertionError as err: self.log.notify("Tried to restore tree frequencies but failed: {}".format(err)) #no need to remove - we'll overwrite it shortly self.tree_frequencies = {} self.tree_frequency_confidence = {} self.tree_frequency_counts = {} def estimate_tree_frequencies(self, region='global', pivots=24, stiffness=20.0): ''' estimate frequencies of clades in the tree, possibly region specific ''' if not hasattr(self, 'tree_frequencies'): self.restore_tree_frequencies() if region in self.tree_frequencies: self.log.notify("Skipping tree frequency estimation for region: %s" % region) return if not hasattr(self, 'pivots'): tps = np.array([np.mean(x.attributes['num_date']) for x in self.seqs.seqs.values()]) self.pivots=make_pivots(pivots, tps) self.log.notify('Estimate tree frequencies for %s: using self.pivots' % (region)) # Omit strains sampled prior to the first pivot from frequency calculations. if region=='global': node_filter_func = lambda node: node.attr["num_date"] >= self.pivots[0] else: node_filter_func = lambda node: (node.attr['region'] == region) and (node.attr["num_date"] >= self.pivots[0]) tree_freqs = tree_frequencies(self.tree.tree, self.pivots, method='SLSQP', node_filter = node_filter_func, ws = max(2,self.tree.tree.count_terminals()//10), stiffness = stiffness) tree_freqs.estimate_clade_frequencies() conf = tree_freqs.calc_confidence() self.tree_frequencies[region] = tree_freqs.frequencies self.tree_frequency_confidence[region] = conf self.tree_frequency_counts[region] = tree_freqs.counts self.save_tree_frequencies() def build_tree(self): ''' (1) instantiate a tree object (process.tree) (2) If newick file doesn't exist or isn't valid: build a newick tree (normally RAxML) (3) Make a TimeTree ''' self.tree = tree(aln=self.seqs.aln, proteins=self.proteins, verbose=self.config["subprocess_verbosity_level"]) newick_file = self.output_path + ".newick" if self.try_to_restore and os.path.isfile(newick_file):# and self.tree.check_newick(newick_file): self.log.notify("Newick file \"{}\" can be used to restore".format(newick_file)) else: self.log.notify("Building newick tree.") self.tree.build_newick(newick_file, **self.config["newick_tree_options"]) def clock_filter(self): if self.config["clock_filter"] == False: return self.tree.tt.clock_filter(reroot='best', n_iqd=self.config["clock_filter"]["n_iqd"], plot=self.config["clock_filter"]["plot"]) leaves = [x for x in self.tree.tree.get_terminals()] for n in leaves: if n.bad_branch: self.tree.tt.tree.prune(n) print('pruning leaf ', n.name) if self.config["clock_filter"]["remove_deep_splits"]: self.tree.tt.tree.ladderize() current_root = self.tree.tt.tree.root if sum([x.branch_length for x in current_root])>0.1 \ and sum([x.count_terminals() for x in current_root.clades[:-1]])<5: new_root = current_root.clades[-1] new_root.up=False self.tree.tt.tree.root = new_root with open(self.output_path+"_outliers.txt", 'a') as ofile: for x in current_root.clades[:-1]: ofile.write("\n".join([leaf.name for leaf in x.get_terminals()])+'\n') self.tree.tt.prepare_tree() def timetree_setup_filter_run(self): def try_restore(): try: assert(os.path.isfile(self.output_path + "_timetree.new")) assert(os.path.isfile(self.output_path + "_timetree.pickle")) except AssertionError: return False self.log.notify("Attempting to restore timetree") with open(self.output_path+"_timetree.pickle", 'rb') as fh: pickled = pickle.load(fh) try: assert(self.config["timetree_options"] == pickled["timetree_options"]) assert(self.config["clock_filter"] == pickled["clock_filter_options"]) #assert(set(self.seqs.sequence_lookup.keys()) == set(pickled["original_seqs"])) except AssertionError as e: print(e) self.log.warn("treetime is out of date - rerunning") return False # this (treetime) newick is _after_ clock filtering and remove_outliers_clades # so these methods should not be rerun here self.tree.tt_from_file(self.output_path + "_timetree.new", nodefile=None, root=None) try: self.tree.restore_timetree_node_info(pickled["nodes"]) except KeyError: self.log.warn("treetime node info missing - rerunning") return False self.log.notify("TreeTime successfully restored.") return True if "temporal_confidence" in self.config: self.config["timetree_options"]["confidence"] = True self.config["timetree_options"]["use_marginal"] = True if self.try_to_restore: success = try_restore() else: success = False if not success: self.log.notify("Setting up TimeTree") self.tree.tt_from_file(self.output_path + ".newick", nodefile=None, root="best") self.log.notify("Running Clock Filter") self.clock_filter() self.tree.remove_outlier_clades() # this is deterministic self.log.notify("Reconstructing Ancestral Sequences, branch lengths & dating nodes") self.tree.timetree(**self.config["timetree_options"]) # do we ever not want to use timetree?? If so: # self.tree.ancestral(**kwargs) instead of self.tree.timetree self.tree.save_timetree(fprefix=self.output_path, ttopts=self.config["timetree_options"], cfopts=self.config["clock_filter"]) self.tree.add_translations() self.tree.refine() self.tree.layout() def matchClades(self, clades, offset=-1): ''' finds branches in the tree corresponding to named clades by searching for the oldest node with a particular genotype. - params - clades: a dictionary with clade names as keys and lists of genoypes as values - offset: the offset to be applied to the position specification, typically -1 to conform with counting starting at 0 as opposed to 1 "clade_annotation" is a label to a specific node in the tree that is used to hang a text label in auspice "clade_membership" is an attribute of every node in the tree that defines clade membership, used as coloring in auspice ''' def match(node, genotype): return all([node.translations[gene][pos+offset]==state if gene in node.translations else node.sequence[pos+offset]==state for gene, pos, state in genotype]) ## Label root nodes for each clade as clade_annotation via clades_to_nodes ## NOTE clades_to_nodes is used in the (full) frequencies export self.clades_to_nodes = {} for clade_name, genotype in clades.iteritems(): matching_nodes = filter(lambda x:match(x,genotype), self.tree.tree.get_nonterminals()) matching_nodes.sort(key=lambda x:x.numdate if hasattr(x,'numdate') else x.dist2root) if len(matching_nodes): self.clades_to_nodes[clade_name] = matching_nodes[0] self.clades_to_nodes[clade_name].attr['clade_annotation'] = clade_name else: print('matchClades: no match found for ', clade_name, genotype) for allele in genotype: partial_matches = filter(lambda x:match(x,[allele]), self.tree.tree.get_nonterminals()) print('Found %d partial matches for allele '%len(partial_matches), allele) ## Now preorder traverse the tree with state replacement to set the clade_membership via clade_annotation for node in self.tree.tree.find_clades(): node.attr['clade_membership'] = 'unassigned' ordered_clades = sorted(self.clades_to_nodes.keys(), key=lambda name: self.clades_to_nodes[name].numdate) for clade_annotation in ordered_clades: for node in self.clades_to_nodes[clade_annotation].find_clades(order='preorder'): node.attr['clade_membership'] = clade_annotation def annotate_fitness(self): """Run the fitness prediction model and annotate the tree's nodes with fitness values. Returns the resulting fitness model instance. """ if not hasattr(self, "tree_frequencies"): self.log.warn("Could not find tree frequencies.") return kwargs = { "tree": self.tree.tree, "frequencies": self.tree_frequencies, "time_interval": self.info["time_interval"], "pivots": np.around(self.pivots, 2) } if "predictors" in self.config: kwargs["predictor_input"] = self.config["predictors"] if "epitope_mask" in self.config: kwargs["epitope_masks_fname"] = self.config["epitope_mask"] if "epitope_mask_version" in self.config: kwargs["epitope_mask_version"] = self.config["epitope_mask_version"] if "tolerance_mask_version" in self.config: kwargs["tolerance_mask_version"] = self.config["tolerance_mask_version"] if self.config["subprocess_verbosity_level"] > 0: kwargs["verbose"] = 1 model = fitness_model(**kwargs) model.predict() return model def make_control_json(self, controls): controls_json = {} for super_cat, fields in controls.iteritems(): cat_count = {} for n in self.tree.tree.get_terminals(): tmp = cat_count for field in fields: tmp["name"] = field if field in n.attr: cat = n.attr[field] else: cat='unknown' if cat in tmp: tmp[cat]['count']+=1 else: tmp[cat] = {'count':1, 'subcats':{}} tmp = tmp[cat]['subcats'] controls_json[super_cat] = cat_count return controls_json def auspice_export(self): ''' export the tree, sequences, frequencies to json files for auspice visualization ''' prefix = os.path.join(self.config["output"]["auspice"], self.info["prefix"]) indent = 2 ## ENTROPY (alignment diversity) ## if "entropy" in self.config["auspice"]["extra_jsons"]: self.seqs.export_diversity(fname=prefix+'_entropy.json', indent=indent) ## TREE & SEQUENCES ## if hasattr(self, 'tree') and self.tree is not None: self.tree.export( path = prefix, extra_attr = self.config["auspice"]["extra_attr"] + ["muts", "aa_muts","attr", "clade"], indent = indent, write_seqs_json = "sequences" in self.config["auspice"]["extra_jsons"] ) ## FREQUENCIES ## if "frequencies" in self.config["auspice"]["extra_jsons"]: export_frequency_json(self, prefix=prefix, indent=indent) export_tip_frequency_json(self, prefix=prefix, indent=indent) ## METADATA ## export_metadata_json(self, prefix=prefix, indent=indent) def run_geo_inference(self): if self.config["geo_inference"] == False: self.log.notify("Not running geo inference") return try: kwargs = {"report_confidence": self.config["geo_inference_options"]["confidence"]} except KeyError: kwargs = {} ## try load pickle... try: assert(self.try_to_restore == True) with open(self.output_path + "_mugration.pickle", 'rb') as fh: options = pickle.load(fh) restored_data = pickle.load(fh) assert(options == self.config["geo_inference_options"]) assert(set(restored_data.keys()) == set([x.name for x in self.tree.tree.find_clades()])) except IOError: restored_data = False except AssertionError as err: restored_data = False self.log.notify("Tried to restore mutation frequencies but failed: {}".format(err)) # only run geo inference if lat + longs are defined. if not self.lat_longs or len(self.lat_longs)==0: self.log.notify("no geo inference - no specified lat/longs") return for geo_attr in self.config["geo_inference"]: try: self.tree.restore_geo_inference(restored_data, geo_attr, self.config["geo_inference_options"]["confidence"]) self.log.notify("Restored geo inference for {}".format(geo_attr)) except KeyError: try: kwargs["root_state"] = self.config["geo_inference_options"]["root_state"][geo_attr] except KeyError: pass self.log.notify("running geo inference for {} with parameters {}".format(geo_attr, kwargs)) self.tree.geo_inference(geo_attr, **kwargs) # SAVE MUGRATION RESULTS: attrs = set(self.tree.mugration_attrs) try: data = {} for node in self.tree.tree.find_clades(): assert(len(attrs - set(node.attr.keys()))==0) data[node.name] = {x:node.attr[x] for x in attrs} except AssertionError: self.log.warn("Error saving mugration data - will not be able to restore") return with open(self.output_path + "_mugration.pickle", 'wb') as fh: pickle.dump(self.config["geo_inference_options"], fh, protocol=pickle.HIGHEST_PROTOCOL) pickle.dump(data, fh, protocol=pickle.HIGHEST_PROTOCOL) self.log.notify("Saved mugration data (pickle)") def save_as_nexus(self): save_as_nexus(self.tree.tree, self.output_path + "_timeTree.nex") if __name__=="__main__": print("This shouldn't be called as a script.")
46.464752
158
0.595274
4,243
35,592
4.841857
0.151544
0.021417
0.017718
0.006231
0.297849
0.210524
0.164768
0.138143
0.11692
0.106698
0
0.004458
0.300489
35,592
765
159
46.52549
0.820701
0.143515
0
0.19145
0
0
0.129098
0.009005
0
0
0
0
0.039033
1
0.04461
false
0.005576
0.042751
0.001859
0.130112
0.01487
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d9629e18c5a751f1f05e83298b1aeab4711e6438
1,777
py
Python
nodux_contabilidad/nodux_contabilidad/doctype/nodux_item_price/nodux_item_price.py
jessica-tandazo/nodux_contabilidad
a9f853e167160b1d883b937d2edbf354fd14d144
[ "MIT" ]
null
null
null
nodux_contabilidad/nodux_contabilidad/doctype/nodux_item_price/nodux_item_price.py
jessica-tandazo/nodux_contabilidad
a9f853e167160b1d883b937d2edbf354fd14d144
[ "MIT" ]
null
null
null
nodux_contabilidad/nodux_contabilidad/doctype/nodux_item_price/nodux_item_price.py
jessica-tandazo/nodux_contabilidad
a9f853e167160b1d883b937d2edbf354fd14d144
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright (c) 2015, nodux and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document from frappe import throw, _ class NoduxItemPrice(Document): def validate(self): self.validate_item() self.validate_price_list() self.check_duplicate_item() self.update_price_list_details() self.update_item_details() def validate_item(self): if not frappe.db.exists("Item", self.item_code): throw(_("Item {0} not found").format(self.item_code)) def validate_price_list(self): enabled = frappe.db.get_value("Nodux Price List", self.price_list, "enabled") if not enabled: throw(_("Price List {0} is disabled").format(self.price_list)) def check_duplicate_item(self): if frappe.db.sql("""select name from `tabNodux Item Price` where item_code=%s and price_list=%s and name!=%s""", (self.item_code, self.price_list, self.name)): frappe.throw(_("Item {0} appears multiple times in Price List {1}").format(self.item_code, self.price_list), NoduxItemPriceDuplicateItem) # def update_price_list_details(self): # self.buying, self.selling, self.currency = \ # #frappe.db.get_value("Nodux Price List", {"name": self.price_list, "enabled": 1}, # frappe.db.get_value("Nodux Price List", {"name": self.price_list}, # ["buying", "selling", "currency"]) def update_price_list_details(self): self.buying, self.selling, self.currency = \ frappe.db.get_value("Nodux Price List", {"name": self.price_list, "enabled": 1}, ["buying", "selling", "currency"]) def update_item_details(self): self.item_name, self.item_description = frappe.db.get_value("Item", self.item_code, ["item_name", "description"])
36.265306
111
0.723692
253
1,777
4.869565
0.256917
0.138799
0.073864
0.064935
0.355519
0.293019
0.252435
0.228084
0.228084
0.228084
0
0.00712
0.130557
1,777
48
112
37.020833
0.790291
0.216657
0
0
0
0
0.204776
0
0
0
0
0
0
1
0.2
false
0
0.133333
0
0.366667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d962f71ef696f9f1cf377a6a911132ae292fa62f
799
py
Python
main/email.py
BTulkas/Foster_Finder
b3de87ce3a253bec3296446f7138f8a16b32f9d7
[ "MIT" ]
null
null
null
main/email.py
BTulkas/Foster_Finder
b3de87ce3a253bec3296446f7138f8a16b32f9d7
[ "MIT" ]
2
2021-09-12T08:31:22.000Z
2021-09-12T09:08:47.000Z
main/email.py
BTulkas/Foster_Finder
b3de87ce3a253bec3296446f7138f8a16b32f9d7
[ "MIT" ]
null
null
null
from flask import render_template from flask_mail import Message from main import mail, app def send_email(subject, sender, recipients, text_body, html_body): msg = Message(subject, sender=sender, recipients=recipients) msg.body = text_body msg.html = html_body mail.send(msg) def send_password_reset_email(clinic): token = clinic.get_password_reset_token() send_email('Foster Finder - Reset Your Password', sender=app.config['ADMIN'], recipients=[clinic.email], text_body=render_template('reset_password_email.txt', clinic=clinic, token=token), html_body=render_template('reset_password_email.html', clinic=clinic, token=token))
38.047619
69
0.640801
93
799
5.268817
0.322581
0.085714
0.073469
0.093878
0.146939
0.146939
0
0
0
0
0
0
0.274093
799
21
70
38.047619
0.844828
0
0
0
0
0
0.11125
0.06125
0
0
0
0
0
1
0.117647
false
0.294118
0.176471
0
0.294118
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
d966b6da1943e7fcc8c1aa8f39d2dde2c9b18bf1
779
py
Python
objectModel/Python/cdm/persistence/cdmfolder/types/projections/operation_add_artifact_attribute.py
rt112000/CDM
34bd34f9260140a8f8aa02bd87c23033f3daad4c
[ "CC-BY-4.0", "MIT" ]
884
2019-05-10T02:09:10.000Z
2022-03-31T14:02:00.000Z
objectModel/Python/cdm/persistence/cdmfolder/types/projections/operation_add_artifact_attribute.py
rt112000/CDM
34bd34f9260140a8f8aa02bd87c23033f3daad4c
[ "CC-BY-4.0", "MIT" ]
171
2019-06-10T11:34:37.000Z
2022-03-31T22:50:12.000Z
objectModel/Python/cdm/persistence/cdmfolder/types/projections/operation_add_artifact_attribute.py
rt112000/CDM
34bd34f9260140a8f8aa02bd87c23033f3daad4c
[ "CC-BY-4.0", "MIT" ]
340
2019-05-07T18:00:16.000Z
2022-03-31T12:00:15.000Z
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. from typing import Union from cdm.persistence.cdmfolder.types.projections.operation_base import OperationBase from cdm.persistence.cdmfolder.types.type_attribute import TypeAttribute from cdm.persistence.cdmfolder.types.entity_attribute import EntityAttribute from cdm.persistence.cdmfolder.types import AttributeGroupReference class OperationAddArtifactAttribute(OperationBase): """OperationAddArtifactAttribute class""" def __init__(self): super().__init__() self.newAttribute = None # type: Union[str, AttributeGroupReference, TypeAttribute, EntityAttribute] self.insertAtTop = None
41
109
0.803594
83
779
7.409639
0.566265
0.045528
0.117073
0.17561
0.20813
0
0
0
0
0
0
0
0.12837
779
18
110
43.277778
0.905744
0.335045
0
0
0
0
0
0
0
0
0
0
0
1
0.1
false
0
0.5
0
0.7
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
3
d96823b574d707b8c5884043e9c5fc59a212d82c
1,900
py
Python
ebr_board/database/queries.py
eugene-davis/ebr-board
f592a752e17e869a6fd35ef82398f97748dbdc78
[ "Apache-2.0" ]
null
null
null
ebr_board/database/queries.py
eugene-davis/ebr-board
f592a752e17e869a6fd35ef82398f97748dbdc78
[ "Apache-2.0" ]
4
2019-08-02T09:35:51.000Z
2019-08-05T04:45:47.000Z
ebr_board/database/queries.py
LaudateCorpus1/ebr-board
f592a752e17e869a6fd35ef82398f97748dbdc78
[ "Apache-2.0" ]
1
2021-09-14T03:58:40.000Z
2021-09-14T03:58:40.000Z
""" Query functions to run against ElasticSearch """ # pylint: disable=invalid-name from ebr_connector.schema.build_results import BuildResults detailed_build_info = { "includes": [ "br_build_date_time", "br_job_name", "br_job_url_key", "br_source", "br_build_id_key", "br_platform", "br_product", "br_status_key", "br_version_key", "br_tests_object", ], "excludes": [ "lhi*", "br_tests_object.br_tests_passed_object.*", "br_tests_object.br_tests_failed_object.*", "br_tests_object.br_tests_skipped_object.*", "br_tests_object.br_suites_object.*", ], } def make_query( # pylint: disable=too-many-arguments index, combined_filter, includes, excludes, agg=None, size=1, start=0 ): """ Simplifies the execution and usage of a typical query, including cleaning up the results. Args: index: index to search on combined_filter: combined set of filters to run the query with includes: list of fields to include on the results (keep as small as possible to improve execution time) excludes: list of fields to explicitly exclude from the results size: [Optional] number of results to return. Defaults to 1. Returns: List of dicts with results of the query. """ search = BuildResults().search(index=index) search = search.source(includes=includes, excludes=excludes) if agg: search = search.aggs.metric("fail_count", agg) search = search.query("bool", filter=[combined_filter])[0:1] search = search[start : start + size] response = search.execute() results = [] if agg: results = response["aggregations"]["fail_count"]["buckets"] else: for hit in response["hits"]["hits"]: results.append(hit["_source"]) return results
31.666667
113
0.647895
238
1,900
4.962185
0.436975
0.047417
0.066046
0.050804
0.078747
0.04403
0
0
0
0
0
0.003487
0.245263
1,900
59
114
32.20339
0.820084
0.315789
0
0.102564
0
0
0.291801
0.124598
0
0
0
0
0
1
0.025641
false
0.025641
0.025641
0
0.076923
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d96a378a19360aa836edef6494a1d0f976078638
4,714
py
Python
src/scripts/vnet/uri/dummy_app.py
amithbraj/vpp
edf1da94dc099c6e2ab1d455ce8652fada3cdb04
[ "Apache-2.0" ]
751
2017-07-13T06:16:46.000Z
2022-03-30T09:14:35.000Z
src/scripts/vnet/uri/dummy_app.py
amithbraj/vpp
edf1da94dc099c6e2ab1d455ce8652fada3cdb04
[ "Apache-2.0" ]
63
2018-06-11T09:48:35.000Z
2021-01-05T09:11:03.000Z
src/scripts/vnet/uri/dummy_app.py
amithbraj/vpp
edf1da94dc099c6e2ab1d455ce8652fada3cdb04
[ "Apache-2.0" ]
479
2017-07-13T06:17:26.000Z
2022-03-31T18:20:43.000Z
#!/usr/bin/env python3 import socket import sys import time import argparse # action can be reflect or drop action = "drop" test = 0 def test_data (data, n_rcvd): n_read = len (data); for i in range(n_read): expected = (n_rcvd + i) & 0xff byte_got = ord (data[i]) if (byte_got != expected): print("Difference at byte {}. Expected {} got {}" .format(n_rcvd + i, expected, byte_got)) return n_read def handle_connection (connection, client_address): print("Received connection from {}".format(repr(client_address))) n_rcvd = 0 try: while True: data = connection.recv(4096) if not data: break; if (test == 1): n_rcvd += test_data (data, n_rcvd) if (action != "drop"): connection.sendall(data) finally: connection.close() def run_tcp_server(ip, port): print("Starting TCP server {}:{}".format(repr(ip), repr(port))) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_address = (ip, int(port)) sock.bind(server_address) sock.listen(1) while True: connection, client_address = sock.accept() handle_connection (connection, client_address) def run_udp_server(ip, port): print("Starting UDP server {}:{}".format(repr(ip), repr(port))) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_address = (ip, int(port)) sock.bind(server_address) while True: data, addr = sock.recvfrom(4096) if (action != "drop"): #snd_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto (data, addr) def run_server(ip, port, proto): if (proto == "tcp"): run_tcp_server(ip, port) elif (proto == "udp"): run_udp_server(ip, port) def prepare_data(power): buf = [] for i in range (0, pow(2, power)): buf.append(i & 0xff) return bytearray(buf) def run_tcp_client(ip, port): print("Starting TCP client {}:{}".format(repr(ip), repr(port))) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = (ip, int(port)) sock.connect(server_address) data = prepare_data(16) n_rcvd = 0 n_sent = len (data) try: sock.sendall(data) timeout = time.time() + 2 while n_rcvd < n_sent and time.time() < timeout: tmp = sock.recv(1500) tmp = bytearray (tmp) n_read = len(tmp) for i in range(n_read): if (data[n_rcvd + i] != tmp[i]): print("Difference at byte {}. Sent {} got {}" .format(n_rcvd + i, data[n_rcvd + i], tmp[i])) n_rcvd += n_read if (n_rcvd < n_sent or n_rcvd > n_sent): print("Sent {} and got back {}".format(n_sent, n_rcvd)) else: print("Got back what we've sent!!"); finally: sock.close() def run_udp_client(ip, port): print("Starting UDP client {}:{}".format(repr(ip), repr(port))) n_packets = 100 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server_address = (ip, int(port)) data = prepare_data(10) try: for i in range (0, n_packets): sock.sendto(data, server_address) finally: sock.close() def run_client(ip, port, proto): if (proto == "tcp"): run_tcp_client(ip, port) elif (proto == "udp"): run_udp_client(ip, port) def run(mode, ip, port, proto): if (mode == "server"): run_server (ip, port, proto) elif (mode == "client"): run_client (ip, port, proto) else: raise Exception("Unknown mode. Only client and server supported") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-m', action='store', dest='mode') parser.add_argument('-i', action='store', dest='ip') parser.add_argument('-p', action='store', dest='port') parser.add_argument('-proto', action='store', dest='proto') parser.add_argument('-a', action='store', dest='action') parser.add_argument('-t', action='store', dest='test') results = parser.parse_args() action = results.action test = results.test run(results.mode, results.ip, results.port, results.proto) #if (len(sys.argv)) < 4: # raise Exception("Usage: ./dummy_app <mode> <ip> <port> [<action> <test>]") #if (len(sys.argv) == 6): # action = sys.argv[4] # test = int(sys.argv[5]) #run (sys.argv[1], sys.argv[2], int(sys.argv[3]))
33.197183
83
0.591854
635
4,714
4.234646
0.209449
0.027891
0.026776
0.040907
0.427296
0.257717
0.213834
0.195984
0.175902
0.159911
0
0.011491
0.261561
4,714
141
84
33.432624
0.760988
0.071065
0
0.291667
0
0
0.094966
0
0
0
0.001831
0
0
1
0.083333
false
0
0.033333
0
0.133333
0.075
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d96a84eccbdb4344152ec7775f2333ab5fdd6d60
2,806
py
Python
getData.py
siddsax/WD-GAN
c5f7d68394ea60760db3eacb5f059ebebef6060d
[ "BSD-3-Clause" ]
null
null
null
getData.py
siddsax/WD-GAN
c5f7d68394ea60760db3eacb5f059ebebef6060d
[ "BSD-3-Clause" ]
null
null
null
getData.py
siddsax/WD-GAN
c5f7d68394ea60760db3eacb5f059ebebef6060d
[ "BSD-3-Clause" ]
null
null
null
import torch from torch.utils import data import numpy as np import os import cv2 import torchvision.transforms as transforms from PIL import Image import random from PIL import ImageFile def get_transform(opt): transform_list = [] if opt.resize_or_crop == 'resize_and_crop': osize = [opt.loadSize_1, opt.loadSize_2] transform_list.append(transforms.Resize(osize, Image.BICUBIC)) transform_list.append(transforms.RandomCrop((opt.fineSize_1, opt.fineSize_2 ))) elif opt.resize_or_crop == 'crop': transform_list.append(transforms.RandomCrop(opt.fineSize)) elif opt.resize_or_crop == 'scale_width': transform_list.append(transforms.Lambda( lambda img: __scale_width(img, opt.fineSize))) elif opt.resize_or_crop == 'scale_width_and_crop': transform_list.append(transforms.Lambda( lambda img: __scale_width(img, opt.loadSize))) transform_list.append(transforms.RandomCrop(opt.fineSize)) elif opt.resize_or_crop == 'none': transform_list.append(transforms.Lambda( lambda img: __adjust(img))) else: raise ValueError('--resize_or_crop %s is not a valid option.' % opt.resize_or_crop) # if opt.isTrain and not opt.no_flip: # print("="*1000) # # exit() # transform_list.append(transforms.RandomHorizontalFlip()) transform_list += [transforms.ToTensor()] # transforms.Normalize((0.5, 0.5, 0.5), # (0.5, 0.5, 0.5))] return transforms.Compose(transform_list) class Dataset(data.Dataset): 'Characterizes a dataset for PyTorch' def __init__(self, opt): 'Initialization' self.transform = get_transform(opt) self.dataroot = opt.dataroot self.AB_paths = os.listdir(opt.dataroot) self.train = opt.train self.opt = opt def __len__(self): 'Denotes the total number of samples' return len(self.AB_paths) def __getitem__(self, index): AB_path = self.dataroot + '/' + self.AB_paths[index] AB = Image.open(AB_path).convert('RGB') if self.train: w, h = AB.size w2 = int(w / 2) B = AB.crop((w2, 0, w, h)).resize((self.opt.loadSize_1, self.opt.loadSize_2), Image.BICUBIC) else: B = AB seed = random.randint(0,2**32) random.seed(seed) # B = transforms.ToTensor()(B) B = self.transform(B) w_offset = random.randint(0, max(0, self.opt.loadSize_1 - self.opt.fineSize_1 - 1)) h_offset = random.randint(0, max(0, self.opt.loadSize_2 - self.opt.fineSize_2 - 1)) B = B[:, h_offset:h_offset + self.opt.fineSize_2, w_offset:w_offset + self.opt.fineSize_1] return B, 0
35.075
104
0.63186
372
2,806
4.55914
0.268817
0.084316
0.089623
0.136792
0.322524
0.306604
0.288325
0.232901
0.232901
0.159198
0
0.020932
0.250891
2,806
79
105
35.518987
0.785918
0.106914
0
0.118644
0
0
0.071207
0
0
0
0
0
0
1
0.067797
false
0
0.152542
0
0.288136
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d96b52d758ea1e34f2a09afa20f1c461838affe8
6,290
py
Python
bindings/python/test/time/test_time.py
verstaen/open-space-toolkit-physics
ca55011fd0de9aadacad84317fdce06985e5dbd8
[ "Apache-2.0" ]
null
null
null
bindings/python/test/time/test_time.py
verstaen/open-space-toolkit-physics
ca55011fd0de9aadacad84317fdce06985e5dbd8
[ "Apache-2.0" ]
null
null
null
bindings/python/test/time/test_time.py
verstaen/open-space-toolkit-physics
ca55011fd0de9aadacad84317fdce06985e5dbd8
[ "Apache-2.0" ]
null
null
null
################################################################################################################################################################ # @project Open Space Toolkit ▸ Physics # @file bindings/python/test/time/test_time.py # @author Lucas Brémond <lucas@loftorbital.com> # @license Apache License 2.0 ################################################################################################################################################################ import pytest from ostk.physics.time import Time ################################################################################################################################################################ def test_time_constructors (): assert Time(0, 0, 0) is not None ################################################################################################################################################################ def test_time_undefined (): assert Time.undefined() is not None ################################################################################################################################################################ def test_time_midnight (): assert Time.midnight() is not None ################################################################################################################################################################ def test_time_noon (): assert Time.noon() is not None ################################################################################################################################################################ def test_time_parse (): assert Time.parse('00:00:00') is not None assert Time.parse('00:00:00', Time.Format.Standard) is not None assert Time.parse('00:00:00', Time.Format.ISO8601) is not None ################################################################################################################################################################ def test_time_operators (): time = Time(0, 0, 0) assert (time == time) is not None assert (time != time) is not None ################################################################################################################################################################ def test_time_is_defined (): time = Time(0, 0, 0) assert time.is_defined() is not None ################################################################################################################################################################ def test_time_get_hour (): time = Time(0, 0, 0) assert time.get_hour() is not None ################################################################################################################################################################ def test_time_get_minute (): time = Time(0, 0, 0) assert time.get_minute() is not None ################################################################################################################################################################ def test_time_get_second (): time = Time(0, 0, 0) assert time.get_second() is not None ################################################################################################################################################################ def test_time_get_millisecond (): time = Time(0, 0, 0) assert time.get_millisecond() is not None ################################################################################################################################################################ def test_time_get_microsecond (): time = Time(0, 0, 0) assert time.get_microsecond() is not None ################################################################################################################################################################ def test_time_get_nanosecond (): time = Time(0, 0, 0) assert time.get_nanosecond() is not None ################################################################################################################################################################ def test_time_get_floating_seconds (): time = Time(0, 0, 0) assert time.get_floating_seconds() is not None ################################################################################################################################################################ def test_time_to_string (): time = Time(0, 0, 0) assert time.to_string() is not None assert time.to_string(Time.Format.Standard) is not None assert time.to_string(Time.Format.ISO8601) is not None ################################################################################################################################################################ def test_time_set_hour (): time = Time(0, 0, 0) time.set_hour(1) ################################################################################################################################################################ def test_time_set_minute (): time = Time(0, 0, 0) time.set_minute(1) ################################################################################################################################################################ def test_time_set_second (): time = Time(0, 0, 0) time.set_second(1) ################################################################################################################################################################ def test_time_set_millisecond (): time = Time(0, 0, 0) time.set_millisecond(1) ################################################################################################################################################################ def test_time_set_microsecond (): time = Time(0, 0, 0) time.set_microsecond(1) ################################################################################################################################################################ def test_time_set_nanosecond (): time = Time(0, 0, 0) time.set_nanosecond(1) ################################################################################################################################################################
35.337079
160
0.2531
392
6,290
3.867347
0.137755
0.044855
0.152375
0.078496
0.701187
0.651715
0.477573
0.258575
0.137203
0.05277
0
0.014915
0.093959
6,290
177
161
35.536723
0.250921
0.029889
0
0.246154
0
0
0.010634
0
0
0
0
0
0.307692
1
0.323077
false
0
0.030769
0
0.353846
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
2
d96bfa9969aa7535edbc947eef5fd3836a546bc4
61,602
py
Python
email_client.py
HideyoshiNakazone/duo-db-client
d847f59c4b4243cf359e2fca411f0e7a6864493b
[ "MIT" ]
null
null
null
email_client.py
HideyoshiNakazone/duo-db-client
d847f59c4b4243cf359e2fca411f0e7a6864493b
[ "MIT" ]
null
null
null
email_client.py
HideyoshiNakazone/duo-db-client
d847f59c4b4243cf359e2fca411f0e7a6864493b
[ "MIT" ]
null
null
null
from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from datetime import datetime, timedelta from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage from email.mime.text import MIMEText from email.header import Header import psycopg2.extensions import psycopg2 import smtplib import pickle import select import os EMAIL_ADDRESS = os.environ.get('EMAIL_ADDRESS') EMAIL_PASSWORD = os.environ.get('EMAIL_PASSWORD') db_conn = psycopg2.connect( host = "localhost", port = "6432", dbname = "server", user = "hideyoshi", password = "vhnb2901" ) db_conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) db = db_conn.cursor() db.execute('LISTEN novo_pedido') while 1: if not select.select([db_conn], [], [], 5) == ([], [], []): db_conn.poll() while db_conn.notifies: notify = db_conn.notifies.pop() id_pedido, c_cpf, id_servico, quantidade, valor_total, date = notify.payload.replace('(','').replace(')','').split(',') year,month,day = date.replace('"','').split()[0].split('-') hour,minute,sec = date.replace('"','').split()[1].split(':') sec = sec.split('.')[0] date = datetime(int(year),int(month),int(day),int(hour),int(minute),int(sec)) months = [ "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Augosto", "Setembro", "Outubro", "Novembro", "Dezembro"] month = months[date.month] week = [ "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado", "Domingo"] dow = week[date.weekday()] db.execute('SELECT DISTINCT nome FROM cliente, pedido WHERE cliente.cpf = pedido.cpf and pedido.id ='+id_pedido+';') c_nome = str(db.fetchall()).replace('[','').replace('(','').replace(')','').replace(']','').replace(',','').replace("'",'') db.execute('SELECT DISTINCT email FROM cliente, pedido WHERE cliente.cpf = pedido.cpf and pedido.id ='+id_pedido+';') c_email = str(db.fetchall()).replace('[','').replace('(','').replace(')','').replace(']','').replace(',','').replace("'",'') db.execute('SELECT DISTINCT nome FROM servico, pedido WHERE servico.id = id_servico AND pedido.id = '+id_pedido+';') p_nome = str(db.fetchall()).replace('[','').replace('(','').replace(')','').replace(']','').replace(',','').replace("'",'') db.execute("SELECT DISTINCT endereco.logradouro,endereco.complemento,endereco.numero,endereco.cidade,' - ',endereco.estado FROM endereco, cliente, pedido WHERE cliente.cpf = pedido.cpf AND cliente.id_endereco = endereco.id AND pedido.id = "+id_pedido+";") endereco = str(db.fetchall()).replace('[','').replace('(','').replace(')','').replace(']','').replace(',','').replace("'",'') msgRoot = MIMEMultipart('related') msgRoot['Subject'] = 'Compra realizada com Sucesso' msgRoot['From'] = EMAIL_ADDRESS msgRoot['To'] = c_email message = """\ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional //EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:v="urn:schemas-microsoft-com:vml"> <head> <!--[if gte mso 9]><xml><o:OfficeDocumentSettings><o:AllowPNG/><o:PixelsPerInch>96</o:PixelsPerInch></o:OfficeDocumentSettings></xml><![endif]--> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> <meta content="width=device-width" name="viewport"/> <!--[if !mso]><!--> <meta content="IE=edge" http-equiv="X-UA-Compatible"/> <!--<![endif]--> <title></title> <!--[if !mso]><!--> <link href="https://fonts.googleapis.com/css?family=Oswald" rel="stylesheet" type="text/css"/> <link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css"/> <link href="https://fonts.googleapis.com/css?family=Merriweather" rel="stylesheet" type="text/css"/> <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet" type="text/css"/> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro" rel="stylesheet" type="text/css"/> <!--<![endif]--> <style type="text/css"> body { margin: 0; padding: 0; } table, td, tr { vertical-align: top; border-collapse: collapse; } * { line-height: inherit; } a[x-apple-data-detectors=true] { color: inherit !important; text-decoration: none !important; } </style> <style id="media-query" type="text/css"> @media (max-width: 670px) { .block-grid, .col { min-width: 320px !important; max-width: 100% !important; display: block !important; } .block-grid { width: 100% !important; } .col { width: 100% !important; } .col>div { margin: 0 auto; } img.fullwidth, img.fullwidthOnMobile { max-width: 100% !important; } .no-stack .col { min-width: 0 !important; display: table-cell !important; } .no-stack.two-up .col { width: 50% !important; } .no-stack .col.num4 { width: 33% !important; } .no-stack .col.num8 { width: 66% !important; } .no-stack .col.num4 { width: 33% !important; } .no-stack .col.num3 { width: 25% !important; } .no-stack .col.num6 { width: 50% !important; } .no-stack .col.num9 { width: 75% !important; } .video-block { max-width: none !important; } .mobile_hide { min-height: 0px; max-height: 0px; max-width: 0px; display: none; overflow: hidden; font-size: 0px; } .desktop_hide { display: block !important; max-height: none !important; } } </style> </head> <body class="clean-body" style="margin: 0; padding: 0; -webkit-text-size-adjust: 100%; background-color: #482c71;"> <!--[if IE]><div class="ie-browser"><![endif]--> <table bgcolor="#482c71" cellpadding="0" cellspacing="0" class="nl-container" role="presentation" style="table-layout: fixed; vertical-align: top; min-width: 320px; Margin: 0 auto; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; background-color: #482c71; width: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td style="word-break: break-word; vertical-align: top;" valign="top"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td align="center" style="background-color:#482c71"><![endif]--> <div style="background-color:transparent;"> <div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: transparent;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:transparent"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="650" style="background-color:transparent;width:650px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:0px; padding-bottom:0px;"><![endif]--> <div class="col num12" style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top; width: 650px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:0px solid transparent; border-bottom:0px solid transparent; border-right:0px solid transparent; padding-top:0px; padding-bottom:0px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <div class="mobile_hide"> <table border="0" cellpadding="0" cellspacing="0" class="divider" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td class="divider_inner" style="word-break: break-word; vertical-align: top; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px;" valign="top"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="divider_content" height="15" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; border-top: 0px solid transparent; height: 15px; width: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td height="15" style="word-break: break-word; vertical-align: top; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top"><span></span></td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </div> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <div style="background-color:transparent;"> <div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: transparent;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:transparent"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="650" style="background-color:transparent;width:650px; border-top: 1px solid #C879F1; border-left: 1px solid #C879F1; border-bottom: 0px solid transparent; border-right: 1px solid #C879F1;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:10px; padding-bottom:0px;"><![endif]--> <div class="col num12" style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top; width: 648px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:1px solid #C879F1; border-left:1px solid #C879F1; border-bottom:0px solid transparent; border-right:1px solid #C879F1; padding-top:10px; padding-bottom:0px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <div align="center" class="img-container center autowidth fixedwidth" style="padding-right: 15px;padding-left: 15px;"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px"><td style="padding-right: 15px;padding-left: 15px;" align="center"><![endif]--><img align="center" alt="Image" border="0" class="center autowidth fixedwidth" src="cid:swirls_1.png" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 618px; display: block;" title="Image" width="618"/> <div style="font-size:1px;line-height:20px"> </div> <!--[if mso]></td></tr></table><![endif]--> </div> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <div style="background-color:transparent;"> <div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: transparent;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:transparent"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="650" style="background-color:transparent;width:650px; border-top: 0px solid transparent; border-left: 1px solid #C879F1; border-bottom: 0px solid transparent; border-right: 1px solid #C879F1;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:0px; padding-bottom:5px;"><![endif]--> <div class="col num12" style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top; width: 648px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:1px solid #C879F1; border-bottom:0px solid transparent; border-right:1px solid #C879F1; padding-top:0px; padding-bottom:5px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <div align="center" class="img-container center fixedwidth" style="padding-right: 0px;padding-left: 0px;"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px"><td style="padding-right: 0px;padding-left: 0px;" align="center"><![endif]--><img align="center" alt="Image" border="0" class="center fixedwidth" src="cid:logoflower.png" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 259px; display: block;" title="Image" width="259"/> <div style="font-size:1px;line-height:20px"> </div> <!--[if mso]></td></tr></table><![endif]--> </div> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <div style="background-color:transparent;"> <div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: transparent;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:transparent"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="650" style="background-color:transparent;width:650px; border-top: 0px solid transparent; border-left: 1px solid #C879F1; border-bottom: 0px solid transparent; border-right: 1px solid #C879F1;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:40px;"><![endif]--> <div class="col num12" style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top; width: 648px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:1px solid #C879F1; border-bottom:0px solid transparent; border-right:1px solid #C879F1; padding-top:5px; padding-bottom:40px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <table border="0" cellpadding="0" cellspacing="0" class="divider" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td class="divider_inner" style="word-break: break-word; vertical-align: top; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px;" valign="top"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="divider_content" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; border-top: 1px dotted #C879F1; width: 95%;" valign="top" width="95%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td style="word-break: break-word; vertical-align: top; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top"><span></span></td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 40px; padding-left: 40px; padding-top: 30px; padding-bottom: 15px; font-family: serif"><![endif]--> <div style="color:#E3E3E3;font-family:'Merriwheater', 'Georgia', serif;line-height:1.5;padding-top:30px;padding-right:40px;padding-bottom:15px;padding-left:40px;"> <div style="line-height: 1.5; font-size: 12px; font-family: 'Merriwheater', 'Georgia', serif; color: #E3E3E3; mso-line-height-alt: 18px;"> <p style="line-height: 1.5; word-break: break-word; text-align: center; font-family: Merriwheater, Georgia, serif; font-size: 30px; mso-line-height-alt: 45px; margin: 0;"><span style="font-size: 30px; color: #00ad99;">SUA RESERVA</span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 40px; padding-left: 40px; padding-top: 5px; padding-bottom: 20px; font-family: 'Trebuchet MS', Tahoma, sans-serif"><![endif]--> <div style="color:#E3E3E3;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;line-height:1.5;padding-top:5px;padding-right:40px;padding-bottom:20px;padding-left:40px;"> <div style="font-size: 12px; line-height: 1.5; font-family: 'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif; color: #E3E3E3; mso-line-height-alt: 18px;"> <p style="font-size: 20px; line-height: 1.5; text-align: center; word-break: break-word; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 30px; margin: 0;"><span style="font-size: 20px;"><span style="font-size: 18px;">"""+dow+", "+day+" "+month+" "+year+"""</span><br/><span style="font-size: 18px;">Serviço: """+p_nome+"""</span><br/><span style="font-size: 18px;">Duração: """+date.strftime("%H:%M")+" - "+(date+timedelta(hours=2)).strftime("%H:%M")+"""</span><br/></span></p> <div style="color:#E3E3E3;font-family:'Merriwheater', 'Georgia', serif;line-height:1.5;padding-top:30px;padding-right:40px;padding-bottom:15px;padding-left:40px;"> <div style="line-height: 1.5; font-size: 12px; font-family: 'Merriwheater', 'Georgia', serif; color: #E3E3E3; mso-line-height-alt: 18px;"> <p style="line-height: 1.5; word-break: break-word; text-align: center; font-family: Merriwheater, Georgia, serif; font-size: 30px; mso-line-height-alt: 45px; margin: 0;"><span style="font-size: 30px; color: #00ad99;">VALOR</span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 40px; padding-left: 40px; padding-top: 5px; padding-bottom: 20px; font-family: 'Trebuchet MS', Tahoma, sans-serif"><![endif]--> <div style="color:#E3E3E3;font-family:'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif;line-height:1.5;padding-top:5px;padding-right:40px;padding-bottom:20px;padding-left:40px;"> <div style="font-size: 12px; line-height: 1.5; font-family: 'Montserrat', 'Trebuchet MS', 'Lucida Grande', 'Lucida Sans Unicode', 'Lucida Sans', Tahoma, sans-serif; color: #E3E3E3; mso-line-height-alt: 18px;"> <p style="font-size: 20px; line-height: 1.5; text-align: center; word-break: break-word; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 30px; margin: 0;"><span style="font-size: 20px;"><span style="font-size: 18px;">R$ """+valor_total+"""</span><br/></span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <div style="background-color:transparent;"> <div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: transparent;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:transparent"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="650" style="background-color:transparent;width:650px; border-top: 0px solid transparent; border-left: 1px solid #C879F1; border-bottom: 0px solid transparent; border-right: 1px solid #C879F1;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:5px;"><![endif]--> <div class="col num12" style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top; width: 648px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:1px solid #C879F1; border-bottom:0px solid transparent; border-right:1px solid #C879F1; padding-top:5px; padding-bottom:5px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <div align="center" class="img-container center autowidth fullwidth" style="padding-right: 0px;padding-left: 0px;"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px"><td style="padding-right: 0px;padding-left: 0px;" align="center"><![endif]--> <div style="font-size:1px;line-height:10px"> </div><img align="center" alt="Image" border="0" class="center autowidth fullwidth" src="cid:diveinto.jpeg" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 648px; display: block;" title="Image" width="648"/> <!--[if mso]></td></tr></table><![endif]--> </div> <div class="mobile_hide"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 55px; padding-bottom: 0px; font-family: serif"><![endif]--> <div style="color:#FFFFFF;font-family:'Merriwheater', 'Georgia', serif;line-height:1.2;padding-top:55px;padding-right:10px;padding-bottom:0px;padding-left:10px;"> <div style="line-height: 1.2; font-family: 'Merriwheater', 'Georgia', serif; font-size: 12px; color: #FFFFFF; mso-line-height-alt: 14px;"> <p style="font-size: 38px; line-height: 1.2; text-align: center; word-break: break-word; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 46px; margin: 0;"><span style="font-size: 38px;">DIVE INTO RELAX</span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> </div> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top: 15px; padding-bottom: 0px; font-family: Georgia, 'Times New Roman', serif"><![endif]--> <div style="color:#FFFFFF;font-family:Georgia, Times, 'Times New Roman', serif;line-height:1.2;padding-top:15px;padding-right:0px;padding-bottom:0px;padding-left:0px;"> <div style="line-height: 1.2; font-family: Georgia, Times, 'Times New Roman', serif; font-size: 12px; color: #FFFFFF; mso-line-height-alt: 14px;"> <p style="line-height: 1.2; text-align: center; font-size: 28px; word-break: break-word; font-family: Georgia, Times, Times New Roman, serif; mso-line-height-alt: 34px; margin: 0;"><span style="font-size: 28px;"><em><span style="color: #00ad99;"><span style="">Enjoy Your Day Spa</span></span></em></span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <div style="background-color:transparent;"> <div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: transparent;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:transparent"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="650" style="background-color:transparent;width:650px; border-top: 0px solid transparent; border-left: 1px solid #C879F1; border-bottom: 0px solid transparent; border-right: 1px solid #C879F1;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:55px;"><![endif]--> <div class="col num12" style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top; width: 648px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:1px solid #C879F1; border-bottom:0px solid transparent; border-right:1px solid #C879F1; padding-top:5px; padding-bottom:55px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 40px; padding-left: 40px; padding-top: 10px; padding-bottom: 20px; font-family: serif"><![endif]--> <div style="color:#E3E3E3;font-family:'Merriwheater', 'Georgia', serif;line-height:1.5;padding-top:10px;padding-right:40px;padding-bottom:20px;padding-left:40px;"> <div style="font-size: 12px; line-height: 1.5; font-family: 'Merriwheater', 'Georgia', serif; color: #E3E3E3; mso-line-height-alt: 18px;"> <p style="font-size: 18px; line-height: 1.5; word-break: break-word; text-align: center; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 27px; margin: 0;"><span style="font-size: 18px;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec elementum nisl id neque ullamcorper, vel mattis nisl rutrum. Sed pulvinar aliquam dolor et euismod.</span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <div style="background-color:transparent;"> <div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: #3f2765;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:#3f2765;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:#3f2765"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="650" style="background-color:#3f2765;width:650px; border-top: 0px solid transparent; border-left: 1px solid #C879F1; border-bottom: 0px solid transparent; border-right: 1px solid #C879F1;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:30px; padding-bottom:5px;"><![endif]--> <div class="col num12" style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top; width: 648px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:1px solid #C879F1; border-bottom:0px solid transparent; border-right:1px solid #C879F1; padding-top:30px; padding-bottom:5px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <div align="center" class="img-container center fixedwidth" style="padding-right: 15px;padding-left: 15px;"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px"><td style="padding-right: 15px;padding-left: 15px;" align="center"><![endif]--> <div style="font-size:1px;line-height:15px"> </div><img align="center" alt="Image" border="0" class="center fixedwidth" src="cid:swirlup.png" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 291px; display: block;" title="Image" width="291"/> <div style="font-size:1px;line-height:10px"> </div> <!--[if mso]></td></tr></table><![endif]--> </div> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 30px; padding-bottom: 30px; font-family: serif"><![endif]--> <div style="color:#ffffff;font-family:'Merriwheater', 'Georgia', serif;line-height:1.2;padding-top:30px;padding-right:10px;padding-bottom:30px;padding-left:10px;"> <div style="line-height: 1.2; font-family: 'Merriwheater', 'Georgia', serif; font-size: 12px; color: #ffffff; mso-line-height-alt: 14px;"> <p style="line-height: 1.2; text-align: center; font-size: 30px; word-break: break-word; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 36px; margin: 0;"><span style="font-size: 30px;">TRATAMENTOS</span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <div style="background-color:transparent;"> <div class="block-grid four-up" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: #3f2765;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:#3f2765;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:#3f2765"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="162" style="background-color:#3f2765;width:162px; border-top: 0px solid transparent; border-left: 1px solid #C879F1; border-bottom: 0px solid #C879F1; border-right: 0px solid transparent;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:25px;"><![endif]--> <div class="col num3" style="max-width: 320px; min-width: 162px; display: table-cell; vertical-align: top; width: 161px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:1px solid #C879F1; border-bottom:0px solid #C879F1; border-right:0px solid transparent; padding-top:5px; padding-bottom:25px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <div align="center" class="img-container center autowidth" style="padding-right: 0px;padding-left: 0px;"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px"><td style="padding-right: 0px;padding-left: 0px;" align="center"><![endif]--><img align="center" alt="Alternate text" border="0" class="center autowidth" src="cid:bea_1.png" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 64px; display: block;" title="Alternate text" width="64"/> <!--[if mso]></td></tr></table><![endif]--> </div> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 0px; font-family: Georgia, 'Times New Roman', serif"><![endif]--> <div style="color:#00ad99;font-family:Georgia, Times, 'Times New Roman', serif;line-height:1.2;padding-top:10px;padding-right:10px;padding-bottom:0px;padding-left:10px;"> <div style="line-height: 1.2; font-family: Georgia, Times, 'Times New Roman', serif; font-size: 12px; color: #00ad99; mso-line-height-alt: 14px;"> <p style="line-height: 1.2; text-align: center; font-size: 16px; word-break: break-word; font-family: Georgia, Times, Times New Roman, serif; mso-line-height-alt: 19px; margin: 0;"><span style="font-size: 16px;"><strong><em>Head Massage</em></strong></span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 40px; padding-left: 40px; padding-top: 0px; padding-bottom: 0px; font-family: serif"><![endif]--> <div style="color:#ffffff;font-family:'Merriwheater', 'Georgia', serif;line-height:1.5;padding-top:0px;padding-right:40px;padding-bottom:0px;padding-left:40px;"> <div style="line-height: 1.5; font-size: 12px; font-family: 'Merriwheater', 'Georgia', serif; color: #ffffff; mso-line-height-alt: 18px;"> <p style="line-height: 1.5; font-size: 34px; text-align: center; word-break: break-word; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 51px; margin: 0;"><span style="font-size: 34px;">50$</span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <table border="0" cellpadding="0" cellspacing="0" class="divider" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td class="divider_inner" style="word-break: break-word; vertical-align: top; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px;" valign="top"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="divider_content" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; border-top: 2px solid transparent; width: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td style="word-break: break-word; vertical-align: top; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top"><span></span></td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td><td align="center" width="162" style="background-color:#3f2765;width:162px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:25px;"><![endif]--> <div class="col num3" style="max-width: 320px; min-width: 162px; display: table-cell; vertical-align: top; width: 162px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:0px solid transparent; border-bottom:0px solid transparent; border-right:0px solid transparent; padding-top:5px; padding-bottom:25px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <div align="center" class="img-container center autowidth" style="padding-right: 0px;padding-left: 0px;"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px"><td style="padding-right: 0px;padding-left: 0px;" align="center"><![endif]--><img align="center" alt="Alternate text" border="0" class="center autowidth" src="cid:feet.png" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 64px; display: block;" title="Alternate text" width="64"/> <!--[if mso]></td></tr></table><![endif]--> </div> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 0px; font-family: Georgia, 'Times New Roman', serif"><![endif]--> <div style="color:#00ad99;font-family:Georgia, Times, 'Times New Roman', serif;line-height:1.2;padding-top:10px;padding-right:10px;padding-bottom:0px;padding-left:10px;"> <div style="line-height: 1.2; font-family: Georgia, Times, 'Times New Roman', serif; font-size: 12px; color: #00ad99; mso-line-height-alt: 14px;"> <p style="line-height: 1.2; text-align: center; font-size: 16px; word-break: break-word; font-family: Georgia, Times, Times New Roman, serif; mso-line-height-alt: 19px; margin: 0;"><span style="font-size: 16px;"><strong><em>Feet Treatment</em></strong></span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 40px; padding-left: 40px; padding-top: 0px; padding-bottom: 0px; font-family: serif"><![endif]--> <div style="color:#ffffff;font-family:'Merriwheater', 'Georgia', serif;line-height:1.5;padding-top:0px;padding-right:40px;padding-bottom:0px;padding-left:40px;"> <div style="line-height: 1.5; font-size: 12px; font-family: 'Merriwheater', 'Georgia', serif; color: #ffffff; mso-line-height-alt: 18px;"> <p style="line-height: 1.5; font-size: 34px; text-align: center; word-break: break-word; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 51px; margin: 0;"><span style="font-size: 34px;">65$</span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <table border="0" cellpadding="0" cellspacing="0" class="divider" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td class="divider_inner" style="word-break: break-word; vertical-align: top; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px;" valign="top"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="divider_content" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; border-top: 2px solid transparent; width: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td style="word-break: break-word; vertical-align: top; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top"><span></span></td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td><td align="center" width="162" style="background-color:#3f2765;width:162px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:25px;"><![endif]--> <div class="col num3" style="max-width: 320px; min-width: 162px; display: table-cell; vertical-align: top; width: 162px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:0px solid transparent; border-bottom:0px solid transparent; border-right:0px solid transparent; padding-top:5px; padding-bottom:25px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <div align="center" class="img-container center autowidth" style="padding-right: 0px;padding-left: 0px;"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px"><td style="padding-right: 0px;padding-left: 0px;" align="center"><![endif]--><img align="center" alt="Alternate text" border="0" class="center autowidth" src="cid:massagstone.png" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 64px; display: block;" title="Alternate text" width="64"/> <!--[if mso]></td></tr></table><![endif]--> </div> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 0px; font-family: Georgia, 'Times New Roman', serif"><![endif]--> <div style="color:#00ad99;font-family:Georgia, Times, 'Times New Roman', serif;line-height:1.2;padding-top:10px;padding-right:10px;padding-bottom:0px;padding-left:10px;"> <div style="line-height: 1.2; font-family: Georgia, Times, 'Times New Roman', serif; font-size: 12px; color: #00ad99; mso-line-height-alt: 14px;"> <p style="line-height: 1.2; text-align: center; font-size: 16px; word-break: break-word; font-family: Georgia, Times, Times New Roman, serif; mso-line-height-alt: 19px; margin: 0;"><span style="font-size: 16px;"><strong><em>Stone massage</em></strong></span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 40px; padding-left: 40px; padding-top: 0px; padding-bottom: 0px; font-family: serif"><![endif]--> <div style="color:#ffffff;font-family:'Merriwheater', 'Georgia', serif;line-height:1.5;padding-top:0px;padding-right:40px;padding-bottom:0px;padding-left:40px;"> <div style="line-height: 1.5; font-size: 12px; font-family: 'Merriwheater', 'Georgia', serif; color: #ffffff; mso-line-height-alt: 18px;"> <p style="line-height: 1.5; font-size: 34px; text-align: center; word-break: break-word; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 51px; margin: 0;"><span style="font-size: 34px;">20$</span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <table border="0" cellpadding="0" cellspacing="0" class="divider" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td class="divider_inner" style="word-break: break-word; vertical-align: top; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px;" valign="top"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="divider_content" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; border-top: 2px solid transparent; width: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td style="word-break: break-word; vertical-align: top; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top"><span></span></td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td><td align="center" width="162" style="background-color:#3f2765;width:162px; border-top: 0px solid ; border-left: 0px solid ; border-bottom: 0px solid ; border-right: 1px solid #C879F1;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:5px; padding-bottom:25px;"><![endif]--> <div class="col num3" style="max-width: 320px; min-width: 162px; display: table-cell; vertical-align: top; width: 161px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid ; border-left:0px solid ; border-bottom:0px solid ; border-right:1px solid #C879F1; padding-top:5px; padding-bottom:25px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <div align="center" class="img-container center autowidth" style="padding-right: 0px;padding-left: 0px;"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px"><td style="padding-right: 0px;padding-left: 0px;" align="center"><![endif]--><img align="center" alt="Alternate text" border="0" class="center autowidth" src="cid:face.png" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 64px; display: block;" title="Alternate text" width="64"/> <!--[if mso]></td></tr></table><![endif]--> </div> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top: 10px; padding-bottom: 0px; font-family: Georgia, 'Times New Roman', serif"><![endif]--> <div style="color:#00ad99;font-family:Georgia, Times, 'Times New Roman', serif;line-height:1.2;padding-top:10px;padding-right:10px;padding-bottom:0px;padding-left:10px;"> <div style="line-height: 1.2; font-family: Georgia, Times, 'Times New Roman', serif; font-size: 12px; color: #00ad99; mso-line-height-alt: 14px;"> <p style="line-height: 1.2; text-align: center; font-size: 16px; word-break: break-word; font-family: Georgia, Times, Times New Roman, serif; mso-line-height-alt: 19px; margin: 0;"><span style="font-size: 16px;"><strong><em>Stone massage</em></strong></span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 40px; padding-left: 40px; padding-top: 0px; padding-bottom: 0px; font-family: serif"><![endif]--> <div style="color:#ffffff;font-family:'Merriwheater', 'Georgia', serif;line-height:1.5;padding-top:0px;padding-right:40px;padding-bottom:0px;padding-left:40px;"> <div style="line-height: 1.5; font-size: 12px; font-family: 'Merriwheater', 'Georgia', serif; color: #ffffff; mso-line-height-alt: 18px;"> <p style="line-height: 1.5; font-size: 34px; text-align: center; word-break: break-word; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 51px; margin: 0;"><span style="font-size: 34px;">35$</span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <table border="0" cellpadding="0" cellspacing="0" class="divider" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td class="divider_inner" style="word-break: break-word; vertical-align: top; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px;" valign="top"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="divider_content" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; border-top: 2px solid transparent; width: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td style="word-break: break-word; vertical-align: top; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top"><span></span></td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <div style="background-color:transparent;"> <div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: #3f2765;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:#3f2765;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:#3f2765"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="650" style="background-color:#3f2765;width:650px; border-top: 0px solid transparent; border-left: 1px solid #C879F1; border-bottom: 0px solid transparent; border-right: 1px solid #C879F1;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:0px; padding-bottom:40px;"><![endif]--> <div class="col num12" style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top; width: 648px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:1px solid #C879F1; border-bottom:0px solid transparent; border-right:1px solid #C879F1; padding-top:0px; padding-bottom:40px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <div align="center" class="img-container center fixedwidth" style="padding-right: 15px;padding-left: 15px;"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px"><td style="padding-right: 15px;padding-left: 15px;" align="center"><![endif]--> <div style="font-size:1px;line-height:15px"> </div><img align="center" alt="Image" border="0" class="center fixedwidth" src="cid:swirl.png" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 291px; display: block;" title="Image" width="291"/> <div style="font-size:1px;line-height:10px"> </div> <!--[if mso]></td></tr></table><![endif]--> </div> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <div style="background-color:transparent;"> <div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: transparent;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:transparent"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="650" style="background-color:transparent;width:650px; border-top: 0px solid transparent; border-left: 1px solid #C879F1; border-bottom: 1px solid #C879F1; border-right: 1px solid #C879F1;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 0px; padding-left: 0px; padding-top:0px; padding-bottom:0px;"><![endif]--> <div class="col num12" style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top; width: 648px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:1px solid #C879F1; border-bottom:1px solid #C879F1; border-right:1px solid #C879F1; padding-top:0px; padding-bottom:0px; padding-right: 0px; padding-left: 0px;"> <!--<![endif]--> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 40px; padding-left: 40px; padding-top: 35px; padding-bottom: 30px; font-family: serif"><![endif]--> <div style="color:#E3E3E3;font-family:'Merriwheater', 'Georgia', serif;line-height:1.5;padding-top:35px;padding-right:40px;padding-bottom:30px;padding-left:40px;"> <div style="line-height: 1.5; font-size: 12px; font-family: 'Merriwheater', 'Georgia', serif; color: #E3E3E3; mso-line-height-alt: 18px;"> <p style="line-height: 1.5; font-size: 14px; text-align: center; word-break: break-word; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 21px; margin: 0;"><span style="font-size: 14px;"><span style="font-size: 14px;"><em><span style="color: #00ad99; font-size: 14px;"><strong>Flower Spa</strong></span> </em>- Barkley street, 67 - Seattle</span></span></p> <p style="line-height: 1.5; font-size: 18px; text-align: center; word-break: break-word; font-family: Merriwheater, Georgia, serif; mso-line-height-alt: 27px; margin: 0;"><span style="font-size: 18px;"><span style="font-size: 14px;">www.example.com | bookings@example.com</span><br/><span style="font-size: 14px;">© All rights reserved </span><br/></span></p> </div> </div> <!--[if mso]></td></tr></table><![endif]--> <div align="center" class="img-container center autowidth fullwidth" style="padding-right: 15px;padding-left: 15px;"> <!--[if mso]><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr style="line-height:0px"><td style="padding-right: 15px;padding-left: 15px;" align="center"><![endif]--><img align="center" alt="Image" border="0" class="center autowidth fullwidth" src="cid:swirls_2.png" style="text-decoration: none; -ms-interpolation-mode: bicubic; height: auto; border: 0; width: 100%; max-width: 618px; display: block;" title="Image" width="618"/> <div style="font-size:1px;line-height:10px"> </div> <!--[if mso]></td></tr></table><![endif]--> </div> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <div style="background-color:transparent;"> <div class="block-grid" style="Margin: 0 auto; min-width: 320px; max-width: 650px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; background-color: transparent;"> <div style="border-collapse: collapse;display: table;width: 100%;background-color:transparent;"> <!--[if (mso)|(IE)]><table width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:transparent;"><tr><td align="center"><table cellpadding="0" cellspacing="0" border="0" style="width:650px"><tr class="layout-full-width" style="background-color:transparent"><![endif]--> <!--[if (mso)|(IE)]><td align="center" width="650" style="background-color:transparent;width:650px; border-top: 0px solid transparent; border-left: 0px solid transparent; border-bottom: 0px solid transparent; border-right: 0px solid transparent;" valign="top"><table width="100%" cellpadding="0" cellspacing="0" border="0"><tr><td style="padding-right: 10px; padding-left: 10px; padding-top:10px; padding-bottom:10px;"><![endif]--> <div class="col num12" style="min-width: 320px; max-width: 650px; display: table-cell; vertical-align: top; width: 650px;"> <div style="width:100% !important;"> <!--[if (!mso)&(!IE)]><!--> <div style="border-top:0px solid transparent; border-left:0px solid transparent; border-bottom:0px solid transparent; border-right:0px solid transparent; padding-top:10px; padding-bottom:10px; padding-right: 10px; padding-left: 10px;"> <!--<![endif]--> <div class="mobile_hide"> <table border="0" cellpadding="0" cellspacing="0" class="divider" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td class="divider_inner" style="word-break: break-word; vertical-align: top; min-width: 100%; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px;" valign="top"> <table align="center" border="0" cellpadding="0" cellspacing="0" class="divider_content" height="15" role="presentation" style="table-layout: fixed; vertical-align: top; border-spacing: 0; border-collapse: collapse; mso-table-lspace: 0pt; mso-table-rspace: 0pt; border-top: 0px solid transparent; height: 15px; width: 100%;" valign="top" width="100%"> <tbody> <tr style="vertical-align: top;" valign="top"> <td height="15" style="word-break: break-word; vertical-align: top; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;" valign="top"><span></span></td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </div> <!--[if (!mso)&(!IE)]><!--> </div> <!--<![endif]--> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> <!--[if (mso)|(IE)]></td></tr></table></td></tr></table><![endif]--> </div> </div> </div> <!--[if (mso)|(IE)]></td></tr></table><![endif]--> </td> </tr> </tbody> </table> <!--[if (IE)]></div><![endif]--> </body> </html>""" msgText = MIMEText(message, 'html') msgRoot.attach(msgText) images = [ ["./images/bea_1.png", "<bea_1.png>"], ["./images/diveinto.jpeg", "<diveinto.jpeg>"], ["./images/face.png", "<face.png>"], ["./images/feet.png", "<feet.png>"], ["./images/logoflower.png", "<logoflower.png>"], ["./images/massagstone.png", "<massagstone.png>"], ["./images/swirl.png", "<swirl.png>"], ["./images/swirls_1.png", "<swirls_1.png>"], ["./images/swirls_2.png", "<swirls_2.png>"], ["./images/swirlup.png", "<swirlup.png>"] ] for image in images: with open(image[0],'rb') as f: msgImage = MIMEImage(f.read()) f.close() msgImage.add_header('Content-ID', image[1]) msgRoot.attach(msgImage) with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD) smtp.send_message(msgRoot) smtp.quit() credentials = pickle.load(open("./token.pkl","rb")) service = build("calendar","v3",credentials=credentials) id = service.calendarList().list().execute()['items'][0]['id'] event = { 'summary': 'Horário marcado '+c_nome, 'location': endereco, 'description': 'Horário marcado com '+c_nome+' para '+p_nome+'.', 'start': { 'dateTime': date.strftime("%Y-%m-%dT%H:%M:%S"), 'timeZone': "America/Sao_Paulo", }, 'end': { 'dateTime': (date + timedelta(hours=4)).strftime("%Y-%m-%dT%H:%M:%S"), 'timeZone': "America/Sao_Paulo", }, 'reminders': { 'useDefault': False, 'overrides': [ {'method': 'email', 'minutes': 24 * 60}, {'method': 'email', 'minutes': 60}, {'method': 'popup', 'minutes': 30}, ], }, } event = service.events().insert(calendarId=id, body=event).execute()
75.678133
493
0.65967
8,590
61,602
4.722352
0.057043
0.016517
0.013805
0.046148
0.891335
0.880192
0.874128
0.871268
0.868507
0.865229
0
0.04795
0.112675
61,602
813
494
75.771218
0.694151
0
0
0.637076
0
0.285901
0.928574
0.235593
0
0
0
0
0
1
0
false
0.003916
0.061358
0
0.061358
0
0
0
0
null
0
0
0
1
1
1
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
8
d96d94b8b61da641fde0216154cbe46da6d86b8e
2,022
py
Python
containers/api/api/models/user.py
yveso/supertoll
0623c090ab97d5fb24dba6c18373c7cf8bc27e46
[ "MIT" ]
null
null
null
containers/api/api/models/user.py
yveso/supertoll
0623c090ab97d5fb24dba6c18373c7cf8bc27e46
[ "MIT" ]
8
2019-12-26T17:26:07.000Z
2022-02-26T10:41:53.000Z
containers/api/api/models/user.py
yveso/supertoll
0623c090ab97d5fb24dba6c18373c7cf8bc27e46
[ "MIT" ]
null
null
null
from datetime import datetime, timedelta from flask import current_app import jwt from api import db, bcrypt class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True, autoincrement=True) username = db.Column(db.String(128), unique=True, nullable=False) email = db.Column(db.String(128), unique=True, nullable=False) password_hash = db.Column(db.String(255), nullable=False) active = db.Column(db.Boolean(), default=True, nullable=False) created_date = db.Column( db.DateTime, default=datetime.utcnow, nullable=False ) def __init__(self, username, email, password): self.username = username self.email = email self.password_hash = bcrypt.generate_password_hash( password, current_app.config.get("BCRYPT_LOG_ROUNDS") ).decode() def to_json(self): return { "id": self.id, "username": self.username, "email": self.email, "active": self.active, } def encode_auth_token(self): try: payload = { "exp": datetime.utcnow() + timedelta( days=current_app.config.get("TOKEN_EXPIRATION_DAYS"), seconds=current_app.config.get("TOKEN_EXPIRATION_SECONDS"), ), "iat": datetime.utcnow(), "sub": self.id, } return jwt.encode( payload, current_app.config.get("SECRET_KEY"), algorithm="HS256", ) except Exception as e: return e @staticmethod def decode_auth_token(auth_token): try: payload = jwt.decode( auth_token, current_app.config.get("SECRET_KEY") ) return payload["sub"] except jwt.ExpiredSignatureError: return "Signature expired" except jwt.InvalidTokenError: return "Invalid token"
31.107692
79
0.573195
212
2,022
5.301887
0.353774
0.053381
0.053381
0.08452
0.185053
0.185053
0.074733
0.074733
0.074733
0
0
0.008772
0.323442
2,022
64
80
31.59375
0.812866
0
0
0.035714
0
0
0.076657
0.022255
0
0
0
0
0
1
0.071429
false
0.071429
0.071429
0.017857
0.392857
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
d96f3eb5e590bbf34c05fb157cdbcbd239587353
522
py
Python
examples/team.py
DarinMao/python-ccs
73cf6319320b1e13acdce9f7b79128e213e6750b
[ "MIT" ]
null
null
null
examples/team.py
DarinMao/python-ccs
73cf6319320b1e13acdce9f7b79128e213e6750b
[ "MIT" ]
null
null
null
examples/team.py
DarinMao/python-ccs
73cf6319320b1e13acdce9f7b79128e213e6750b
[ "MIT" ]
null
null
null
import ccs team = ccs.team(raw_input("Team Number: ")) summary = team.summary print "Team {} ({} {}) - {} images ({} points) - {}/{} {}".format( summary.number, summary.division, summary.location, summary.images, summary.score, summary.playtime, summary.scoretime, summary.warn) for image in team.images: print "\t{}: {}/{} vulns in {} ({} points, {} penalties) {}".format( image.name, image.found, image.found+image.remaining, image.time, image.score, image.penalties, image.warn)
43.5
74
0.637931
61
522
5.442623
0.442623
0.042169
0.090361
0
0
0
0
0
0
0
0
0
0.178161
522
12
75
43.5
0.773893
0
0
0
0
0
0.219885
0
0
0
0
0
0
0
null
null
0
0.090909
null
null
0.181818
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
1
d96ff25d9d5722c19fe4236bed106b32c2d92cde
10,795
py
Python
nova/virt/powervm/tasks/network.py
zjzh/nova
7bb21723171c59b93e28f5d508c2b6df39220f13
[ "Apache-2.0" ]
1,874
2015-01-04T05:18:34.000Z
2022-03-31T03:30:28.000Z
nova/virt/powervm/tasks/network.py
woraser/nova
fc3890667e4971e3f0f35ac921c2a6c25f72adec
[ "Apache-2.0" ]
132
2017-03-27T11:31:52.000Z
2022-03-30T08:45:02.000Z
nova/virt/powervm/tasks/network.py
woraser/nova
fc3890667e4971e3f0f35ac921c2a6c25f72adec
[ "Apache-2.0" ]
1,996
2015-01-04T15:11:51.000Z
2022-03-31T11:03:13.000Z
# Copyright 2015, 2017 IBM Corp. # # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import eventlet from oslo_log import log as logging from pypowervm.tasks import cna as pvm_cna from pypowervm.wrappers import managed_system as pvm_ms from pypowervm.wrappers import network as pvm_net from taskflow import task from nova import conf as cfg from nova import exception from nova.virt.powervm import vif from nova.virt.powervm import vm LOG = logging.getLogger(__name__) CONF = cfg.CONF SECURE_RMC_VSWITCH = 'MGMTSWITCH' SECURE_RMC_VLAN = 4094 class PlugVifs(task.Task): """The task to plug the Virtual Network Interfaces to a VM.""" def __init__(self, virt_api, adapter, instance, network_infos): """Create the task. Provides 'vm_cnas' - the list of the Virtual Machine's Client Network Adapters as they stand after all VIFs are plugged. May be None, in which case the Task requiring 'vm_cnas' should discover them afresh. :param virt_api: The VirtAPI for the operation. :param adapter: The pypowervm adapter. :param instance: The nova instance. :param network_infos: The network information containing the nova VIFs to create. """ self.virt_api = virt_api self.adapter = adapter self.instance = instance self.network_infos = network_infos or [] self.crt_network_infos, self.update_network_infos = [], [] # Cache of CNAs that is filled on initial _vif_exists() call. self.cnas = None super(PlugVifs, self).__init__( name='plug_vifs', provides='vm_cnas', requires=['lpar_wrap']) def _vif_exists(self, network_info): """Does the instance have a CNA for a given net? :param network_info: A network information dict. This method expects it to contain key 'address' (MAC address). :return: True if a CNA with the network_info's MAC address exists on the instance. False otherwise. """ if self.cnas is None: self.cnas = vm.get_cnas(self.adapter, self.instance) vifs = self.cnas return network_info['address'] in [vm.norm_mac(v.mac) for v in vifs] def execute(self, lpar_wrap): # Check to see if the LPAR is OK to add VIFs to. modifiable, reason = lpar_wrap.can_modify_io() if not modifiable: LOG.error("Unable to create VIF(s) for instance in the system's " "current state. The reason from the system is: %s", reason, instance=self.instance) raise exception.VirtualInterfaceCreateException() # We will have two types of network infos. One is for newly created # vifs. The others are those that exist, but should be re-'treated' for network_info in self.network_infos: if self._vif_exists(network_info): self.update_network_infos.append(network_info) else: self.crt_network_infos.append(network_info) # If there are no vifs to create or update, then just exit immediately. if not self.crt_network_infos and not self.update_network_infos: return [] # For existing VIFs that we just need to update, run the plug but do # not wait for the neutron event as that likely won't be sent (it was # already done). for network_info in self.update_network_infos: LOG.info("Updating VIF with mac %s for instance.", network_info['address'], instance=self.instance) vif.plug(self.adapter, self.instance, network_info, new_vif=False) # For the new VIFs, run the creates (and wait for the events back) try: with self.virt_api.wait_for_instance_event( self.instance, self._get_vif_events(), deadline=CONF.vif_plugging_timeout, error_callback=self._vif_callback_failed): for network_info in self.crt_network_infos: LOG.info('Creating VIF with mac %s for instance.', network_info['address'], instance=self.instance) new_vif = vif.plug( self.adapter, self.instance, network_info, new_vif=True) if self.cnas is not None: self.cnas.append(new_vif) except eventlet.timeout.Timeout: LOG.error('Error waiting for VIF to be created for instance.', instance=self.instance) raise exception.VirtualInterfaceCreateException() return self.cnas def _vif_callback_failed(self, event_name, instance): LOG.error('VIF Plug failure for callback on event %s for instance.', event_name, instance=self.instance) if CONF.vif_plugging_is_fatal: raise exception.VirtualInterfaceCreateException() def _get_vif_events(self): """Returns the VIF events that need to be received for a VIF plug. In order for a VIF plug to be successful, certain events should be received from other components within the OpenStack ecosystem. This method returns the events neutron needs for a given deploy. """ # See libvirt's driver.py -> _get_neutron_events method for # more information. if CONF.vif_plugging_is_fatal and CONF.vif_plugging_timeout: return [('network-vif-plugged', network_info['id']) for network_info in self.crt_network_infos if not network_info.get('active', True)] def revert(self, lpar_wrap, result, flow_failures): if not self.network_infos: return LOG.warning('VIF creation being rolled back for instance.', instance=self.instance) # Get the current adapters on the system cna_w_list = vm.get_cnas(self.adapter, self.instance) for network_info in self.crt_network_infos: try: vif.unplug(self.adapter, self.instance, network_info, cna_w_list=cna_w_list) except Exception: LOG.exception("An exception occurred during an unplug in the " "vif rollback. Ignoring.", instance=self.instance) class UnplugVifs(task.Task): """The task to unplug Virtual Network Interfaces from a VM.""" def __init__(self, adapter, instance, network_infos): """Create the task. :param adapter: The pypowervm adapter. :param instance: The nova instance. :param network_infos: The network information containing the nova VIFs to create. """ self.adapter = adapter self.instance = instance self.network_infos = network_infos or [] super(UnplugVifs, self).__init__(name='unplug_vifs') def execute(self): # If the LPAR is not in an OK state for deleting, then throw an # error up front. lpar_wrap = vm.get_instance_wrapper(self.adapter, self.instance) modifiable, reason = lpar_wrap.can_modify_io() if not modifiable: LOG.error("Unable to remove VIFs from instance in the system's " "current state. The reason reported by the system is: " "%s", reason, instance=self.instance) raise exception.VirtualInterfaceUnplugException(reason=reason) # Get all the current Client Network Adapters (CNA) on the VM itself. cna_w_list = vm.get_cnas(self.adapter, self.instance) # Walk through the VIFs and delete the corresponding CNA on the VM. for network_info in self.network_infos: vif.unplug(self.adapter, self.instance, network_info, cna_w_list=cna_w_list) class PlugMgmtVif(task.Task): """The task to plug the Management VIF into a VM.""" def __init__(self, adapter, instance): """Create the task. Requires 'vm_cnas' from PlugVifs. If None, this Task will retrieve the VM's list of CNAs. Provides the mgmt_cna. This may be None if no management device was created. This is the CNA of the mgmt vif for the VM. :param adapter: The pypowervm adapter. :param instance: The nova instance. """ self.adapter = adapter self.instance = instance super(PlugMgmtVif, self).__init__( name='plug_mgmt_vif', provides='mgmt_cna', requires=['vm_cnas']) def execute(self, vm_cnas): LOG.info('Plugging the Management Network Interface to instance.', instance=self.instance) # Determine if we need to create the secure RMC VIF. This should only # be needed if there is not a VIF on the secure RMC vSwitch vswitch = None vswitches = pvm_net.VSwitch.search( self.adapter, parent_type=pvm_ms.System.schema_type, parent_uuid=self.adapter.sys_uuid, name=SECURE_RMC_VSWITCH) if len(vswitches) == 1: vswitch = vswitches[0] if vswitch is None: LOG.warning('No management VIF created for instance due to lack ' 'of Management Virtual Switch', instance=self.instance) return None # This next check verifies that there are no existing NICs on the # vSwitch, so that the VM does not end up with multiple RMC VIFs. if vm_cnas is None: has_mgmt_vif = vm.get_cnas(self.adapter, self.instance, vswitch_uri=vswitch.href) else: has_mgmt_vif = vswitch.href in [cna.vswitch_uri for cna in vm_cnas] if has_mgmt_vif: LOG.debug('Management VIF already created for instance', instance=self.instance) return None lpar_uuid = vm.get_pvm_uuid(self.instance) return pvm_cna.crt_cna(self.adapter, None, lpar_uuid, SECURE_RMC_VLAN, vswitch=SECURE_RMC_VSWITCH, crt_vswitch=True)
41.519231
79
0.631774
1,408
10,795
4.697443
0.224432
0.045358
0.034472
0.031297
0.310402
0.275627
0.239643
0.194436
0.178561
0.166163
0
0.002378
0.298749
10,795
259
80
41.679537
0.871334
0.313201
0
0.275362
0
0
0.112771
0
0
0
0
0
0
1
0.072464
false
0
0.072464
0
0.224638
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d97012330ebae7c93600f55d0f782d19e5a41dae
5,752
py
Python
anti_sybil/graphs/generators/group_based.py
abramsymons/BrightID-AntiSybil
86161afe654f46475944ebdb3b5453a1723180d9
[ "ISC" ]
null
null
null
anti_sybil/graphs/generators/group_based.py
abramsymons/BrightID-AntiSybil
86161afe654f46475944ebdb3b5453a1723180d9
[ "ISC" ]
null
null
null
anti_sybil/graphs/generators/group_based.py
abramsymons/BrightID-AntiSybil
86161afe654f46475944ebdb3b5453a1723180d9
[ "ISC" ]
1
2020-03-28T05:05:19.000Z
2020-03-28T05:05:19.000Z
import random import networkx as nx from ..node import Node def generate(input_data): graph = nx.Graph() groups_size = [random.choice(range(input_data['min_group_nodes'], input_data['max_group_nodes']+1)) for i in range(input_data['num_groups'])] num_attacker = int(sum(groups_size) * input_data['num_attacker_to_num_honest']) num_sybil = int(input_data['num_sybil_to_num_attacker'] * num_attacker) categories = { 'Seed': {'nodes': [], 'num': input_data['num_seed_nodes']}, 'Honest': {'nodes': [], 'num': sum(groups_size) - input_data['num_seed_nodes'] - num_attacker}, 'Attacker': {'nodes': [], 'num': num_attacker}, 'Sybil': {'nodes': [], 'num': num_sybil}, } start_node = input_data.get('start_node', 0) counter = start_node for category in categories: for i in range(categories[category]['num']): node = Node(counter, category) categories[category]['nodes'].append(node) graph.add_node(node) counter += 1 non_sybils = categories['Honest']['nodes'] + \ categories['Seed']['nodes'] + categories['Attacker']['nodes'] random.shuffle(non_sybils) for group_num, size in enumerate(groups_size): group_name = 'group_{0}'.format(group_num) start_point = sum(groups_size[:group_num]) end_point = start_point + size groups_nodes = non_sybils[start_point:end_point] for node in groups_nodes: node.groups.add(group_name) groups = set(sum([list(node.groups) for node in non_sybils], [])) i = 0 while i < input_data['num_joint_node']: joint_node = random.choice(non_sybils) other_groups = groups - joint_node.groups if len(other_groups) > 0: random_group = random.choice(list(other_groups)) joint_node.groups.add(random_group) i += 1 if input_data['num_seed_groups'] != 0: seed_groups = ['seed_group_{0}'.format(i) for i in range(input_data['num_seed_groups'])] for node in categories['Seed']['nodes']: node.groups.add(random.choice(seed_groups)) for group in groups: nodes = [node for node in non_sybils if group in node.groups] nodes_degree = dict((node, 0) for node in nodes) min_degree = int(input_data['min_known_ratio'] * len(nodes)) avg_degree = int(input_data['avg_known_ratio'] * len(nodes)) max_degree = min( int(input_data['max_known_ratio'] * len(nodes)), len(nodes) - 1) low_degrees = range(min_degree, avg_degree) if min_degree != avg_degree else [min_degree] up_degrees = range(avg_degree, max_degree + 1) for i, node in enumerate(nodes): group_degree = sum(nodes_degree.values()) / (i+1) if group_degree < avg_degree: degree = random.choice(up_degrees) else: degree = random.choice(low_degrees) j = counter = 0 pairs = [] while j < degree: pair = random.choice(nodes) if node != pair and nodes_degree[pair] <= max_degree and pair not in pairs: graph.add_edge(node, pair) pairs.append(pair) j += 1 nodes_degree[node] += 1 else: counter += 1 if counter > 100*degree: # j += 1 raise Exception( "Can't find pair. group_degree={}".format(group_degree)) num_connection_to_attacker = max( int(input_data['sybil_to_attackers_con'] * categories['Attacker']['num']), 1) for i, node in enumerate(categories['Sybil']['nodes']): pairs = [] j = 0 while j < num_connection_to_attacker: pair = random.choice(categories['Attacker']['nodes']) if pair not in pairs: graph.add_edge(node, pair) pairs.append(pair) j += 1 for node in categories['Attacker']['nodes'] + categories['Sybil']['nodes']: node.groups.add('attacker') # Add inter-group connections i = 0 inter_group_pairs = [] while i < input_data['num_inter_group_con']: node = random.choice(non_sybils) pair = random.choice(non_sybils) if len(node.groups & pair.groups) == 0 and (node, pair) not in inter_group_pairs: graph.add_edge(node, pair) inter_group_pairs.append((node, pair)) i += 1 # sew graph parts together if not nx.is_connected(graph): components = list(nx.connected_components(graph)) biggest_comp = [] for i, component in enumerate(components): if len(component) > len(biggest_comp): biggest_comp = list(component) for component in components: if component == biggest_comp: continue non_sybils = False i = 0 while not non_sybils: i += 1 left_node = random.choice(list(component)) right_node = random.choice(biggest_comp) if left_node.node_type != 'Sybil' and right_node.node_type != 'Sybil': graph.add_edge(left_node, right_node) print( 'Add Edge: {0} --> {1}'.format(left_node, right_node)) non_sybils = True if i > len(biggest_comp): print(['%s %s'%(node.name, node.node_type) for node in component]) raise("Can't sew above component to the biggest_comp") return graph
42.607407
103
0.570932
703
5,752
4.439545
0.145092
0.049023
0.034604
0.020506
0.143223
0.084268
0.047421
0.032682
0.032682
0.032682
0
0.007844
0.312935
5,752
134
104
42.925373
0.781883
0.010257
0
0.155738
1
0
0.099314
0.012832
0
0
0
0
0
1
0.008197
false
0
0.02459
0
0.040984
0.016393
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
d9724df91f0d1e509249a814becdf43525ed1c7c
182
py
Python
Contest/ABC051/c/main.py
mpses/AtCoder
9c101fcc0a1394754fcf2385af54b05c30a5ae2a
[ "CC0-1.0" ]
null
null
null
Contest/ABC051/c/main.py
mpses/AtCoder
9c101fcc0a1394754fcf2385af54b05c30a5ae2a
[ "CC0-1.0" ]
null
null
null
Contest/ABC051/c/main.py
mpses/AtCoder
9c101fcc0a1394754fcf2385af54b05c30a5ae2a
[ "CC0-1.0" ]
null
null
null
#!/usr/bin/env python3 sx, sy, tx, ty = map(int, input().split()) x, y = tx - sx, ty - sy print("R"*x + "U"*-~y + "L"*-~x + "D"*-~y + "R" + "U"*y + "R"*-~x + "D"*-~y + "L"*-~x + "U")
45.5
92
0.401099
37
182
1.972973
0.513514
0.054795
0.082192
0
0
0
0
0
0
0
0
0.006849
0.197802
182
4
92
45.5
0.493151
0.115385
0
0
0
0
0.062112
0
0
0
0
0
0
1
0
true
0
0
0
0
0.333333
0
0
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
4
d97307bce111d22165208da1309beb39d698985c
92
py
Python
problems/chapter12/mshibatatt/001.py
tokuma09/algorithm_problems
58534620df73b230afbeb12de126174362625a78
[ "CC0-1.0" ]
1
2021-07-07T15:46:58.000Z
2021-07-07T15:46:58.000Z
problems/chapter12/mshibatatt/001.py
tokuma09/algorithm_problems
58534620df73b230afbeb12de126174362625a78
[ "CC0-1.0" ]
5
2021-06-05T14:16:41.000Z
2021-07-10T07:08:28.000Z
problems/chapter12/mshibatatt/001.py
tokuma09/algorithm_problems
58534620df73b230afbeb12de126174362625a78
[ "CC0-1.0" ]
null
null
null
a = list(map(int, input().split())) [i[0] for i in sorted(enumerate(a), key=lambda x:x[1])]
30.666667
55
0.619565
19
92
3
0.842105
0
0
0
0
0
0
0
0
0
0
0.024691
0.119565
92
3
55
30.666667
0.679012
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d9733cb8ddf1ffbcfc514f4195c8b460a2b0fff8
560
py
Python
typer-cli-python/source_code_step_2/rptodo/cli.py
syberflea/materials
54f44725b40edf00c1b523d7a85b34a85014d7eb
[ "MIT" ]
3,682
2018-05-07T19:45:24.000Z
2022-03-31T15:19:10.000Z
typer-cli-python/source_code_step_2/rptodo/cli.py
sribarrow/materials
c17c4a4d6f8487e59eac1df8c88ca92b73d6d2a5
[ "MIT" ]
148
2018-05-15T21:18:49.000Z
2022-03-21T11:25:39.000Z
typer-cli-python/source_code_step_2/rptodo/cli.py
sribarrow/materials
c17c4a4d6f8487e59eac1df8c88ca92b73d6d2a5
[ "MIT" ]
5,535
2018-05-25T23:36:08.000Z
2022-03-31T16:55:52.000Z
"""This module provides the RP To-Do CLI.""" from typing import Optional import typer from rptodo import __app_name__, __version__ app = typer.Typer() def _version_callback(value: bool) -> None: if value: typer.echo(f"{__app_name__} v{__version__}") raise typer.Exit() @app.callback() def main( version: Optional[bool] = typer.Option( None, "--version", "-v", help="Show the application's version and exit.", callback=_version_callback, is_eager=True, ) ) -> None: return
18.666667
56
0.623214
69
560
4.724638
0.565217
0.042945
0
0
0
0
0
0
0
0
0
0
0.255357
560
29
57
19.310345
0.781775
0.067857
0
0
0
0
0.155039
0
0
0
0
0
0
1
0.1
false
0
0.15
0.05
0.3
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d97515b3fc95c50563dceea347d6cfbeb7c8f9bf
4,629
py
Python
surrortg/devices/relay.py
bn102/surrortg-sdk
5f51515d0fd83741b3359b9a682c0a9afc38886f
[ "MIT" ]
21
2020-11-03T23:41:56.000Z
2022-03-21T04:11:46.000Z
surrortg/devices/relay.py
bn102/surrortg-sdk
5f51515d0fd83741b3359b9a682c0a9afc38886f
[ "MIT" ]
5
2021-02-11T14:36:03.000Z
2021-07-20T11:45:07.000Z
surrortg/devices/relay.py
bn102/surrortg-sdk
5f51515d0fd83741b3359b9a682c0a9afc38886f
[ "MIT" ]
11
2020-11-13T11:14:33.000Z
2022-03-21T04:11:51.000Z
import asyncio import logging import pigpio class Relay: """Simple to use relay class implemented with pigpio :param pin: GPIO pin number :type pin: int :param on_level_low: Determines the logic level of the on-state. If set to True, the relay is on when the GPIO pin state is LOW. Defaults to True. :type on_level_low: bool, optional :param initial_state_off: Determines whether the relay should be set to off-state when initialized. If set to False, the relay is set to on-state at init. Defaults to True. :type initial_state_off: bool, optional :raises RuntimeError: If cannot connect to pigpio daemon :raises RuntimeError: If methods are called after calling stop """ def __init__(self, pin, on_level_low=True, initial_state_off=True): self._pin = pin self._on_level_low = on_level_low self._stopped = False if on_level_low: self._on_level = pigpio.LOW self._off_level = pigpio.HIGH else: self._on_level = pigpio.HIGH self._off_level = pigpio.LOW self._pi = pigpio.pi() if not self._pi.connected: raise RuntimeError("Could not connect to pigpio daemon") self._pi.set_mode(self._pin, pigpio.OUTPUT) if initial_state_off: self.off() else: self.on() def on(self): """Turns the relay on""" self._check_if_stopped() self._pi.write(self._pin, self._on_level) def off(self): """Turns the relay off""" self._check_if_stopped() self._pi.write(self._pin, self._off_level) def toggle(self): """Toggles the relay's state Turns the relay on if the state was previously off, and vice versa. """ self._check_if_stopped() if self.is_on(): self.off() else: self.on() async def press_once(self, press_time): """Turns the relay on and off, waiting press_time seconds in between :param press_time: Time in seconds to wait between turning the relay on and off :type press_time: float or int """ assert isinstance(press_time, float) or isinstance( press_time, int ), "press_time should be float or int" self._check_if_stopped() if self.is_on(): logging.warning( "Relay is already on when pressing once! Will turn relay off " f"in {press_time} seconds." ) self.on() await asyncio.sleep(press_time) self.off() def is_on(self): """Checks if the relay is turned on :return: True if the relay is turned on :rtype: bool """ self._check_if_stopped() return self._pi.read(self._pin) == self._on_level def is_off(self): """Checks if the relay is turned off :return: True if the relay is turned off :rtype: bool """ self._check_if_stopped() return not self.is_on() def on_level_is_low(self): """Checks if the relay is on when the GPIO state is LOW :return: True if the relay is on when the GPIO state is LOW :rtype: bool """ self._check_if_stopped() return self._on_level_low def _check_if_stopped(self): if self._stopped: raise RuntimeError("Relay already stopped") def stop(self): """Sets the pin to input state and stops pigpio daemon connection""" self._check_if_stopped() self._pi.set_pull_up_down(self._pin, pigpio.PUD_OFF) self._pi.set_mode(self._pin, pigpio.INPUT) self._pi.stop() self._stopped = True if __name__ == "__main__": async def main(): relay = Relay(26) print(f"Relay on level is low: {relay.on_level_is_low()}") print(f"Relay is initially on: {relay.is_on()}") await asyncio.sleep(0.5) print("Turning the relay on") relay.on() await asyncio.sleep(1) print("Turning the relay off") relay.off() await asyncio.sleep(2) print("Pressing the relay once for 1 second") await relay.press_once(1) await asyncio.sleep(2) print("Toggle relay state") relay.toggle() print(f"Relay is now on: {relay.is_on()}") await asyncio.sleep(1) print("Toggle relay state again") relay.toggle() print(f"Relay is now off: {relay.is_off()}") relay.stop() asyncio.run(main())
28.054545
78
0.597969
639
4,629
4.13302
0.195618
0.054525
0.047709
0.054525
0.330178
0.274896
0.230973
0.10602
0.056797
0.056797
0
0.00314
0.311946
4,629
164
79
28.22561
0.82606
0.242817
0
0.280899
0
0
0.145531
0.008067
0
0
0
0
0.011236
1
0.101124
false
0
0.033708
0
0.179775
0.101124
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d976858493e0b3bdb11753531577c643cf5f3d49
8,322
py
Python
voice.py
ImPurpl3/egg
875f8105140544897e7b81af660e3da864b4cd54
[ "MIT" ]
null
null
null
voice.py
ImPurpl3/egg
875f8105140544897e7b81af660e3da864b4cd54
[ "MIT" ]
null
null
null
voice.py
ImPurpl3/egg
875f8105140544897e7b81af660e3da864b4cd54
[ "MIT" ]
1
2021-12-17T01:23:31.000Z
2021-12-17T01:23:31.000Z
""" MIT License Copyright (c) 2020 ValkyriaKing711 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import asyncio import os from asyncio import AbstractEventLoop from datetime import datetime from typing import TypeVar, Union import discord from async_timeout import timeout from cogs.utils import utils from discord import (AudioSource, FFmpegPCMAudio, Guild, PCMVolumeTransformer, TextChannel) from discord.ext import commands, tasks from discord.ext.commands import Cog, Context from youtube_dl import YoutubeDL utcnow = datetime.utcnow Y = TypeVar("Y", bound="YTDLSource") FFMPEG_EXECUTABLE = "ffmpeg" FFMPEG_OPTIONS = { "before_options": "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5", "options": "-vn" } ytdl = YoutubeDL({ "format": "bestaudio/best", "outtmpl": "downloads/%(autonumber)s-%(extractor)s-%(id)s-%(title)s.%(ext)s", "restrictfilenames": True, "noplaylist": True, "nocheckcertificate": True, "ignoreerrors": False, "logtostderr": False, "quiet": False, "verbose": True, "no_warnings": True, "default_search": "auto", "source_address": "0.0.0.0", "geo_bypass_country": "FI", "age_limit": 30 }) class YTDLSource(PCMVolumeTransformer): def __init__(self, source: AudioSource, *, data: dict, volume=1.0): super().__init__(source, volume) self.data = data self.title = data.get("title") self.url = data.get("url") @classmethod async def from_query(cls, query: str, *, loop: AbstractEventLoop = None, stream: bool = True, partial: bool = False, ctx: Context = None) -> Union[dict, Y]: if not stream and partial: raise ValueError("partial cannot be True when not streaming") loop = loop or asyncio.get_running_loop() data = await loop.run_in_executor( None, lambda: ytdl.extract_info(query, download=not stream) ) if "entries" in data: data = data["entries"][0] if ctx: data["context"] = ctx if partial: for key in ("formats", "http_headers", "downloader_options", "thumbnails", "url"): try: del data[key] except Exception: pass return data options = FFMPEG_OPTIONS.copy() if stream: source = data["url"] else: source = ytdl.prepare_filename(data) data["filename"] = source options.pop("before_options") return cls(FFmpegPCMAudio(source, **options), data=data) @classmethod async def regather_stream(cls, data: dict, *, loop: AbstractEventLoop = None) -> Y: loop = loop or asyncio.get_running_loop() ctx = data.get("context") data = await loop.run_in_executor( None, lambda: ytdl.extract_info(data["webpage_url"], download=False) ) if ctx: data["context"] = ctx return cls(FFmpegPCMAudio(data["url"]), data=data) class MusicPlayer: def __init__(self, ctx: Context): self.bot: utils.Bot = ctx.bot self._channel: TextChannel = ctx.channel self._cog: Cog = ctx.cog self._guild: Guild = ctx.guild self.next = asyncio.Event() self.queue = asyncio.Queue() self.current = None self.volume = 1.0 self.first_play_id = None self.skipped = None self.player_loop.start() # pylint: disable=no-member @tasks.loop() async def player_loop(self): self.next.clear() try: async with timeout(300): source = await self.queue.get() except asyncio.TimeoutError: print("timeout") return await self.destroy(self._guild) if not isinstance(source, YTDLSource): try: source = await YTDLSource.regather_stream( source, loop=self.bot.loop ) except Exception as e: embed = discord.Embed( description=f"```css\n{e}\n```", color=0xF6DECF, timestamp=utcnow() ) embed.set_author( name="An error occurred while processing the track.", icon_url=self._guild.me.display_avatar.url ) return await self._channel.send(embed=embed) ctx = source.data["context"] source.volume = self.volume self.current = source self._guild.voice_client.play( source, after=lambda _: self.bot.loop.call_soon_threadsafe(self.next.set) ) if self.skipped: embed = discord.Embed( description=f"**Now playing {self.current.data['title']}**", color=0xF6DECF, timestamp=utcnow() ) embed.set_author( name=f"Skipped {self.skipped.data['title']}", icon_url=self.skipped.data["skipper"].display_avatar.url, url=source.data["webpage_url"] ) self.skipped = None if source.data["is_live"]: duration = "🔴 LIVE" else: duration = utils.format_time(source.data["duration"]) embed.add_field(name="Uploader", value=source.data["uploader"]) embed.add_field(name="Duration", value=duration) embed.add_field(name="Requested by", value=ctx.author.mention) embed.set_thumbnail(url=source.data["thumbnail"]) await self._channel.send(embed=embed) elif ctx.message.id != self.first_play_id: embed = discord.Embed( color=0xF6DECF, timestamp=utcnow() ) embed.set_author( name=f"Now playing {source.title}", icon_url=ctx.author.display_avatar.url, url=source.data["webpage_url"] ) if source.data["is_live"]: duration = "🔴 LIVE" else: duration = utils.format_time(source.data["duration"]) embed.add_field(name="Uploader", value=source.data["uploader"]) embed.add_field(name="Duration", value=duration) embed.add_field(name="Requested by", value=ctx.author.mention) embed.set_thumbnail(url=source.data["thumbnail"]) await self._channel.send(embed=embed) await self.next.wait() source.cleanup() self.current = None filename = source.data.get("filename") if filename and os.path.isfile(filename): os.remove(filename) @player_loop.before_loop async def wait_until_ready(self): await self.bot.wait_until_ready() def destroy(self, guild: Guild): return self._cog.cleanup(guild)
32.76378
95
0.577866
921
8,322
5.121607
0.32139
0.02756
0.016536
0.021624
0.226415
0.206063
0.199703
0.186559
0.160271
0.140343
0
0.005332
0.323961
8,322
253
96
32.893281
0.832741
0.131939
0
0.276243
0
0.005525
0.124946
0.017378
0
0
0.003447
0
0
1
0.016575
false
0.01105
0.066298
0.005525
0.127072
0.005525
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d977def1eab47165344401c96a3e6718cbc8e63f
689
py
Python
solutions/Bulls and Cows/solution.py
nilax97/leetcode-solutions
d3c12f2b289662d199510e0431e177bbf3cda121
[ "MIT" ]
3
2021-06-06T22:03:15.000Z
2021-06-08T08:49:04.000Z
solutions/Bulls and Cows/solution.py
nilax97/leetcode-solutions
d3c12f2b289662d199510e0431e177bbf3cda121
[ "MIT" ]
null
null
null
solutions/Bulls and Cows/solution.py
nilax97/leetcode-solutions
d3c12f2b289662d199510e0431e177bbf3cda121
[ "MIT" ]
null
null
null
class Solution: def getHint(self, secret: str, guess: str) -> str: bull = 0 cow = 0 values = dict() for i in range(len(secret)): if secret[i] == guess[i]: bull += 1 elif secret[i] in values: values[secret[i]] += 1 else: values[secret[i]] = 1 for i in range(len(secret)): if secret[i] != guess[i]: if guess[i] in values: if values[guess[i]] > 0: cow +=1 values[guess[i]] -= 1 return str(bull) + "A" + str(cow) + "B"
31.318182
54
0.37881
77
689
3.38961
0.324675
0.1341
0.045977
0.084291
0.268199
0.268199
0.268199
0.268199
0.268199
0.268199
0
0.023188
0.499274
689
21
55
32.809524
0.733333
0
0
0.105263
0
0
0.002903
0
0
0
0
0
0
1
0.052632
false
0
0
0
0.157895
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d97890969781912a2513be62820c2cd00f1b4a65
131
py
Python
drf_gitlab_webhook/urls.py
Develatio/drf-gitlab-webhook
34a90a979da1b004886620a89e916b88a61e0c85
[ "MIT" ]
1
2019-01-19T22:06:31.000Z
2019-01-19T22:06:31.000Z
drf_gitlab_webhook/urls.py
Develatio/drf-gitlab-webhook
34a90a979da1b004886620a89e916b88a61e0c85
[ "MIT" ]
null
null
null
drf_gitlab_webhook/urls.py
Develatio/drf-gitlab-webhook
34a90a979da1b004886620a89e916b88a61e0c85
[ "MIT" ]
1
2019-05-09T16:56:04.000Z
2019-05-09T16:56:04.000Z
from django.conf.urls import url from . import classviews urlpatterns = [ url(r'^event/$', classviews.HookEvent.as_view()), ]
18.714286
53
0.709924
17
131
5.411765
0.764706
0
0
0
0
0
0
0
0
0
0
0
0.145038
131
6
54
21.833333
0.821429
0
0
0
0
0
0.061069
0
0
0
0
0
0
1
0
false
0
0.4
0
0.4
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
d9789ea5dc5332d1b7a15a1afc6b61a382b8814b
2,392
py
Python
tap_parquet/streams.py
berenddeboer/tap-parquet
d9c50ea92a68b7777e31ca622468e1dadd86d9ce
[ "Apache-2.0" ]
null
null
null
tap_parquet/streams.py
berenddeboer/tap-parquet
d9c50ea92a68b7777e31ca622468e1dadd86d9ce
[ "Apache-2.0" ]
4
2021-04-02T16:32:14.000Z
2021-11-09T22:54:03.000Z
tap_parquet/streams.py
berenddeboer/tap-parquet
d9c50ea92a68b7777e31ca622468e1dadd86d9ce
[ "Apache-2.0" ]
2
2021-11-09T06:44:46.000Z
2021-12-01T12:28:29.000Z
"""Stream class for tap-parquet.""" import requests from copy import deepcopy from pathlib import Path from typing import Any, Dict, Optional, Union, List, Iterable from singer_sdk.streams import Stream from singer_sdk.typing import ( ArrayType, BooleanType, DateTimeType, IntegerType, NumberType, ObjectType, PropertiesList, Property, StringType, JSONTypeHelper, ) import pyarrow.parquet as pq SCHEMAS_DIR = Path(__file__).parent / Path("./schemas") def get_jsonschema_type(ansi_type: str) -> JSONTypeHelper: """Return a JSONTypeHelper object for the given type name.""" if "int" in ansi_type: return IntegerType() if "string" in ansi_type: return StringType() if "bool" in ansi_type: return BooleanType() if "timestamp[ns]" in ansi_type: return DateTimeType() raise ValueError(f"Unmappable data type '{ansi_type}'.") class ParquetStream(Stream): """Stream class for Parquet streams.""" @property def filepath(self) -> str: """Return the filepath for the parquet stream.""" return self.config["filepath"] @property def schema(self) -> dict: """Dynamically detect the json schema for the stream. This is evaluated prior to any records being retrieved. """ properties: List[Property] = [] parquet_schema = pq.ParquetFile(self.filepath).schema_arrow for i in range(len(parquet_schema.names)): name, dtype = parquet_schema.names[i], parquet_schema.types[i] properties.append(Property(name, get_jsonschema_type(str(dtype)))) return PropertiesList(*properties).to_dict() def get_records(self, partition: Optional[dict] = None) -> Iterable[dict]: """Return a generator of row-type dictionary objects.""" try: parquet_file = pq.ParquetFile(self.filepath) except Exception as ex: raise IOError(f"Could not read from parquet file '{self.filepath}': {ex}") for i in range(parquet_file.num_row_groups): table = parquet_file.read_row_group(i) for batch in table.to_batches(): for row in zip(*batch.columns): yield { table.column_names[i]: val.as_py() for i, val in enumerate(row, start=0) }
31.473684
86
0.637542
285
2,392
5.231579
0.417544
0.032193
0.026828
0.042924
0
0
0
0
0
0
0
0.000567
0.26296
2,392
75
87
31.893333
0.84515
0.134615
0
0.037037
0
0
0.066271
0
0
0
0
0
0
1
0.074074
false
0
0.12963
0
0.333333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d978a101e4eebb559e09fff2906b2a39d73becb8
3,851
py
Python
ppt/app.py
fabioacarvalho/Projetos-Praticando
fa0b324c03a0b4bc5d0ed9d55bbc3ce48d67541b
[ "MIT" ]
null
null
null
ppt/app.py
fabioacarvalho/Projetos-Praticando
fa0b324c03a0b4bc5d0ed9d55bbc3ce48d67541b
[ "MIT" ]
null
null
null
ppt/app.py
fabioacarvalho/Projetos-Praticando
fa0b324c03a0b4bc5d0ed9d55bbc3ce48d67541b
[ "MIT" ]
null
null
null
import sys import random from design import * from PyQt5.QtWidgets import QMainWindow, QApplication from PyQt5 import QtGui ppt = ['Rock', 'Paper', 'Scissors'] game = [] def aChoice(): esc = random.choice(ppt) game.append(esc) class App(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super().__init__(parent) super().setupUi(self) self.windowStart.setPixmap(QtGui.QPixmap('./img/pptHome.png')) #self.stackedWidget.setCurrentWidget(self.page_1) #self.btnAddRegiao.clicked.connect(lambda: self.stackedWidget.setCurrentWidget(self.page_2)) self.btnRestart.clicked.connect(self.restart) self.btnRock.clicked.connect(self.rock) self.btnPaper.clicked.connect(self.paper) self.btnScissors.clicked.connect(self.scissors) def restart(self): self.stackedWidget.setCurrentWidget(self.page_1) game.clear() self.computador.setPixmap(QtGui.QPixmap('')) self.player.setPixmap(QtGui.QPixmap('')) self.infoText.setText('') def rock(self): self.stackedWidget.setCurrentWidget(self.page_2) self.player.setPixmap(QtGui.QPixmap('./img/rock.png')) game.append('Rock') aChoice() if game[1] == 'Rock': self.computador.setPixmap(QtGui.QPixmap('./img/rock.png')) self.infoText.setText('Nobody won, play again.') if game[1] == 'Paper': self.computador.setPixmap(QtGui.QPixmap('./img/paper.png')) self.infoText.setText('You lost, try again :(') self.infoText.setStyleSheet('color: #ffaa00; font: 20pt \"MS Shell Dlg 2\";\n') if game[1] == 'Scissors': self.computador.setPixmap(QtGui.QPixmap('./img/scissors.png')) self.infoText.setText('You win, congratulations!!! :)') self.infoText.setStyleSheet('color: rgb(85, 255, 127); font: 20pt \"MS Shell Dlg 2\";\n') def paper(self): self.stackedWidget.setCurrentWidget(self.page_2) self.player.setPixmap(QtGui.QPixmap('./img/paper.png')) game.append('Paper') aChoice() if game[1] == 'Paper': self.computador.setPixmap(QtGui.QPixmap('./img/paper.png')) self.infoText.setText('Nobody won, play again.') if game[1] == 'Scissors': self.computador.setPixmap(QtGui.QPixmap('./img/scissors.png')) self.infoText.setText('You lost, try again :(') self.infoText.setStyleSheet('color: #ffaa00; font: 20pt \"MS Shell Dlg 2\";\n') if game[1] == 'Rock': self.computador.setPixmap(QtGui.QPixmap('./img/rock.png')) self.infoText.setText('You win, congratulations!!! :)') self.infoText.setStyleSheet('color: rgb(85, 255, 127); font: 20pt \"MS Shell Dlg 2\";\n') def scissors(self): self.stackedWidget.setCurrentWidget(self.page_2) self.player.setPixmap(QtGui.QPixmap('./img/scissors.png')) game.append('Scissors') aChoice() if game[1] == 'Scissors': self.computador.setPixmap(QtGui.QPixmap('./img/scissors.png')) self.infoText.setText('Nobody won, play again.') if game[1] == 'Rock': self.computador.setPixmap(QtGui.QPixmap('./img/rock.png')) self.infoText.setText('You lost, try again :(') self.infoText.setStyleSheet('color: #ffaa00; font: 20pt \"MS Shell Dlg 2\";\n') if game[1] == 'Paper': self.computador.setPixmap(QtGui.QPixmap('./img/paper.png')) self.infoText.setText('You win, congratulations!!! :)') self.infoText.setStyleSheet('color: rgb(85, 255, 127); font: 20pt \"MS Shell Dlg 2\";\n') if __name__ == '__main__': qt = QApplication(sys.argv) app = App() app.show() qt.exec_()
36.67619
101
0.615684
445
3,851
5.274157
0.188764
0.081807
0.134214
0.132936
0.72092
0.692799
0.644227
0.624627
0.623775
0.623775
0
0.021805
0.225915
3,851
104
102
37.028846
0.765515
0.036095
0
0.5
0
0
0.226685
0
0
0
0
0
0
1
0.076923
false
0
0.064103
0
0.153846
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
d97defe4ab7d19c2df85621955ea08007777df4a
354
py
Python
test/test_format.py
gongso1st/geopy
9252f4b12197ff3c5e3fae50d9bae74974d5d20f
[ "MIT" ]
1
2019-07-17T14:38:52.000Z
2019-07-17T14:38:52.000Z
test/test_format.py
gongso1st/geopy
9252f4b12197ff3c5e3fae50d9bae74974d5d20f
[ "MIT" ]
null
null
null
test/test_format.py
gongso1st/geopy
9252f4b12197ff3c5e3fae50d9bae74974d5d20f
[ "MIT" ]
1
2020-06-03T01:42:17.000Z
2020-06-03T01:42:17.000Z
import unittest from geopy.point import Point from geopy.format import format_degrees class TestFormat(unittest.TestCase): @unittest.skip("") def test_format(self): """ format_degrees """ self.assertEqual( format_degrees(Point.parse_degrees('-13', '19', 0)), "-13 19\' 0.0\"" )
19.666667
64
0.584746
39
354
5.179487
0.487179
0.193069
0.049505
0
0
0
0
0
0
0
0
0.043651
0.288136
354
17
65
20.823529
0.757937
0.039548
0
0
0
0
0.057143
0
0
0
0
0
0.1
1
0.1
false
0
0.3
0
0.5
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d97e9bfb4e01d1a5a972e104691a2c436b4de3ca
653
py
Python
Sorts.py
marinajacks/nowcoder
5fafb9b12f56f111737e56358016206023c8067c
[ "MIT" ]
null
null
null
Sorts.py
marinajacks/nowcoder
5fafb9b12f56f111737e56358016206023c8067c
[ "MIT" ]
null
null
null
Sorts.py
marinajacks/nowcoder
5fafb9b12f56f111737e56358016206023c8067c
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Sun Oct 20 20:52:56 2019 @author: 陈彪,版权所有 这个是一个排序算法的总结,将所有的排序算法都重新写一遍,然后我们首先会分析算法的时间 复杂度,然后简单介绍一下这些算法的原理,最后使用python实现,然后我们会使用测试案例 来进行测试。 """ import random '''首先映入眼帘的就是冒泡排序,这是一个让人理解起来最简单的排序算法,这个算法的时间复 杂度是O(N^2),从下面的程序中也能看出来这个算法的时间复杂度确实是O(N^2). ''' def bubble(a): for i in range(len(a)): for j in range(i,len(a)): if(a[i]>a[j]): temp=a[i] a[i]=a[j] a[j]=temp return a if __name__=="__main__": a=[] for i in range(10): a.append(random.randint(10,40)) print(a) print(bubble(a)) print('hello world!')
15.926829
44
0.580398
90
653
4.122222
0.577778
0.032345
0.024259
0.037736
0.06469
0
0
0
0
0
0
0.043478
0.260337
653
41
45
15.926829
0.724638
0.2634
0
0
0
0
0.052493
0
0
0
0
0
0
1
0.0625
false
0
0.0625
0
0.1875
0.1875
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d97f0714641d6f4865c82aa054acf514505a58ff
722
py
Python
scripts/token.py
blockchain-jedi/erc20-contract-template
4364d131e5046d0534f6b92304e6f91b5e8adb23
[ "MIT" ]
null
null
null
scripts/token.py
blockchain-jedi/erc20-contract-template
4364d131e5046d0534f6b92304e6f91b5e8adb23
[ "MIT" ]
null
null
null
scripts/token.py
blockchain-jedi/erc20-contract-template
4364d131e5046d0534f6b92304e6f91b5e8adb23
[ "MIT" ]
null
null
null
# # Usage: # # % brownie console # >>> from scripts import token # >>> green = token.main() # >>> token.issue(green) # >>> token.transfer(green, accounts[1], accounts[2], 1) # from brownie import Token, accounts admin = accounts[0] issuer = accounts[1] holders = accounts[2:9] max_supply = pow(10, 18+9) # 1,000,000,000 def main(): return Token.deploy("Green", "GREEN", 18, admin, issuer, max_supply, {'from': admin}) def issue(token): amount = 1000 for account in holders: token.mint(account.address, amount, {'from': issuer}) amount = amount * 2 def transfer(token, sender, recipient, value): token.transfer(recipient.address, value, {'from': sender})
24.066667
89
0.624654
92
722
4.880435
0.413043
0.048998
0
0
0
0
0
0
0
0
0
0.051146
0.214681
722
29
90
24.896552
0.740741
0.278393
0
0
0
0
0.043137
0
0
0
0
0
0
1
0.214286
false
0
0.071429
0.071429
0.357143
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
1
d980d8c3ac914ab7b6744057703f0c8a2e3c1e3d
2,711
py
Python
nederlands.py
rec/neederlands
f5b71a768c9a51a06014a386ffafc8844943e4b2
[ "Unlicense" ]
1
2020-02-05T17:48:22.000Z
2020-02-05T17:48:22.000Z
nederlands.py
rec/nederlands
f5b71a768c9a51a06014a386ffafc8844943e4b2
[ "Unlicense" ]
null
null
null
nederlands.py
rec/nederlands
f5b71a768c9a51a06014a386ffafc8844943e4b2
[ "Unlicense" ]
null
null
null
import string WIKI_BESTAND = '/Users/tom/Downloads/\ nlwiktionary-20191020-pages-articles-multistream-index.txt' WOORD_BESTAND = 'woord-frequenties.txt' SLECHT_BESTAND = 'slechte-woorden.txt' BLACKLIST = {i.strip() for i in open(SLECHT_BESTAND)} AANTAL = 1000000000000000 MIN = 4 MIN_ACHTERVOEGSEL = 4 VOORVOEGSELS = ( 'aan', 'achter', 'achterop', 'af', 'be', 'bij', 'binnen', 'boven', 'door', 'er', 'goed', 'her', 'in', 'los', 'mee', 'mis', 'na', 'neer', 'om', 'onder', 'ont', 'op', 'over', 'samen', 'tegen', 'teleur', 'toe', 'tussen', 'uit', 'vast', 'ver', 'vol', 'voor', 'voorbe', 'vrij', 'weer', 'weg', 'zwart', ) is_woord = set(string.ascii_lowercase).issuperset def wikitionary(): for lijn in open(WIKI_BESTAND): _, _, woord = lijn.strip().split(':', maxsplit=2) if is_woord(woord): yield woord def freq(): for lijn in open(WOORD_BESTAND): woord, _ = lijn.strip().rsplit(maxsplit=1) yield woord def werkwoorden(woorden): alle = set() resultaat = {} for woord in woorden: if not (woord.endswith('en') or woord.endswith('gaan')): continue alle.add(woord) for v in VOORVOEGSELS: if not woord.startswith(v): continue achtervoegsel = woord[len(v):] if len(achtervoegsel) < MIN_ACHTERVOEGSEL: continue if achtervoegsel.startswith('ge') and achtervoegsel != 'geven': continue if achtervoegsel in BLACKLIST: continue resultaat.setdefault(achtervoegsel, []).append(woord) for achtervoegsel, lijst in resultaat.items(): if achtervoegsel in alle: lijst.append(achtervoegsel) lijst.sort() resultaat = {k: v for k, v in resultaat.items() if len(v) > 1} return sorted(resultaat.items(), key=lambda v: len(v[1]), reverse=True) def druck_werkwoorden(werkwoorden): for i, (k, v) in enumerate(werkwoorden): print(k) for j in v: print(' ', j) print() if i > AANTAL: break def classic_extract(): wiki = list(wikitionary()) ww = werkwoorden(wiki) druck_werkwoorden(ww) print() print('----------------') print() for i, (k, v) in enumerate(ww): if i > 10: break words = set(w for w in wiki if w.endswith(k)) print(k) for missing in sorted(words.difference(v)): print(' ', missing) if __name__ == '__main__': classic_extract()
20.231343
75
0.54408
300
2,711
4.83
0.426667
0.008282
0.008282
0.017943
0.023464
0.023464
0
0
0
0
0
0.017186
0.313169
2,711
133
76
20.383459
0.76101
0
0
0.130841
0
0
0.082995
0.007746
0
0
0
0
0
1
0.046729
false
0
0.009346
0
0.065421
0.074766
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d98213a54bed6fe63049234194f24aa16f814a04
384
py
Python
ds_utils/config.py
dylanjcastillo/nlp-snippets
1cb2a9d4ad5de72714a617ca223f5f822ca72aea
[ "MIT" ]
9
2021-01-29T04:48:30.000Z
2022-03-22T20:51:19.000Z
ds_utils/config.py
dylanjcastillo/nlp-snippets
1cb2a9d4ad5de72714a617ca223f5f822ca72aea
[ "MIT" ]
null
null
null
ds_utils/config.py
dylanjcastillo/nlp-snippets
1cb2a9d4ad5de72714a617ca223f5f822ca72aea
[ "MIT" ]
1
2021-07-10T18:17:01.000Z
2021-07-10T18:17:01.000Z
import os import random import numpy as np import pandas as pd def set_random_seed(seed=42): random.seed(seed) os.environ["PYTHONHASHSEED"] = str(seed) np.random.seed(seed) def set_display_options(): pd.set_option("max_colwidth", 1000) pd.set_option("max_rows", 50) pd.set_option("max_columns", 100) pd.options.display.float_format = "{:,.2f}".format
20.210526
54
0.700521
59
384
4.372881
0.474576
0.116279
0.162791
0.162791
0
0
0
0
0
0
0
0.037383
0.164063
384
18
55
21.333333
0.766355
0
0
0
0
0
0.135417
0
0
0
0
0
0
1
0.153846
false
0
0.307692
0
0.461538
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
2
d9829ca97d266ae282da297f5160c6bc599cfd00
158
py
Python
whileloop.py
muhrizky/DSC-DataCamp
3b8f8a7fd29f236a78e2330248d470403757d6b8
[ "MIT" ]
null
null
null
whileloop.py
muhrizky/DSC-DataCamp
3b8f8a7fd29f236a78e2330248d470403757d6b8
[ "MIT" ]
null
null
null
whileloop.py
muhrizky/DSC-DataCamp
3b8f8a7fd29f236a78e2330248d470403757d6b8
[ "MIT" ]
null
null
null
offset = -8 while offset != 0 : print('Benar') if offset > 0 : offset = offset -3 else: offset = offset +2 print(offset)
15.8
26
0.5
19
158
4.157895
0.526316
0.177215
0
0
0
0
0
0
0
0
0
0.051546
0.386076
158
10
27
15.8
0.762887
0
0
0
0
0
0.031447
0
0
0
0
0
0
1
0
false
0
0
0
0
0.25
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
d984472a164601e55d0346ed01540ed2b20dc88d
832
py
Python
config/tortoise.py
nythonore/fastapi-async
82f34dd421e573f96af1953cc1f72be565743df8
[ "MIT" ]
null
null
null
config/tortoise.py
nythonore/fastapi-async
82f34dd421e573f96af1953cc1f72be565743df8
[ "MIT" ]
null
null
null
config/tortoise.py
nythonore/fastapi-async
82f34dd421e573f96af1953cc1f72be565743df8
[ "MIT" ]
null
null
null
from tortoise.contrib.fastapi import register_tortoise as config_tortoise from config.settings import settings DB_URL = f'postgres://{settings.DB_USERNAME}:{settings.DB_PASSWORD}@{settings.DB_HOST}:{settings.DB_PORT}/{settings.DB_DATABASE}' TORTOISE_MODULES = ['app.example.model'] TORTOISE_ORM_MODULES = TORTOISE_MODULES TORTOISE_ORM_MODULES.append('aerich.models') TORTOISE_ORM = { 'connections': { 'default': DB_URL }, 'apps': { 'models': { 'models': TORTOISE_ORM_MODULES, 'default_connection': 'default' } } } def register_tortoise(app): config_tortoise( app, db_url=DB_URL, modules={'models': TORTOISE_MODULES}, generate_schemas=False, add_exception_handlers=True, )
24.470588
129
0.638221
87
832
5.793103
0.436782
0.119048
0.107143
0
0
0
0
0
0
0
0
0
0.251202
832
33
130
25.212121
0.808989
0
0
0
0
0.037037
0.254808
0.140625
0
0
0
0
0
1
0.037037
false
0.037037
0.074074
0
0.111111
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d9863370e480b53bf264ca69904724291538c799
105
py
Python
application/configuration/views.py
pernaess/ctrlpnl
e0636f3b19d4a5ec5e96120526f238888271391d
[ "MIT" ]
34
2020-01-27T15:07:25.000Z
2021-09-25T17:07:37.000Z
application/configuration/views.py
pernaess/ctrlpnl
e0636f3b19d4a5ec5e96120526f238888271391d
[ "MIT" ]
26
2020-01-29T12:24:42.000Z
2022-03-12T00:16:44.000Z
application/configuration/views.py
pernaess/ctrlpnl
e0636f3b19d4a5ec5e96120526f238888271391d
[ "MIT" ]
7
2020-01-27T11:42:11.000Z
2021-04-05T04:42:22.000Z
from django.shortcuts import redirect def login_redirect(request): return redirect('/account/login')
26.25
37
0.790476
13
105
6.307692
0.769231
0
0
0
0
0
0
0
0
0
0
0
0.114286
105
4
38
26.25
0.88172
0
0
0
0
0
0.132075
0
0
0
0
0
0
1
0.333333
false
0
0.333333
0.333333
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
1
1
1
0
0
6
d986985c57ee93c51e109add53b8920f894727ed
982
py
Python
setup.py
orange-kao/rpm-s3-mirror
4a08cdb47de33045c5e5bc8be1c5ee17bc169d56
[ "Apache-2.0" ]
null
null
null
setup.py
orange-kao/rpm-s3-mirror
4a08cdb47de33045c5e5bc8be1c5ee17bc169d56
[ "Apache-2.0" ]
4
2020-05-08T03:36:15.000Z
2022-03-31T10:51:18.000Z
setup.py
aiven/rpm-s3-mirror
55f049a92258eed3cc863135a964c10c25a3c25a
[ "Apache-2.0" ]
null
null
null
# Copyright (c) 2020 Aiven, Helsinki, Finland. https://aiven.io/ from setuptools import setup import version version = version.get_project_version("rpm_s3_mirror/version.py") setup( name="rpm_s3_mirror", packages=["rpm_s3_mirror"], version=version, description="Tool for syncing RPM repositories with S3", license="Apache 2.0", author="Aiven", author_email="willcoe@aiven.io", url="https://github.com/aiven/rpm-s3-mirror", install_requires=[ "defusedxml", "requests", "python-dateutil", "boto3", "lxml", ], entry_points={ "console_scripts": [ "rpm_s3_mirror = rpm_s3_mirror.__main__:main", ], }, classifiers=[ "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "Programming Language :: Python :: 3.7", "Natural Language :: English", ], )
26.540541
65
0.619145
103
982
5.708738
0.621359
0.05102
0.112245
0.061224
0
0
0
0
0
0
0
0.021622
0.246436
982
36
66
27.277778
0.772973
0.063136
0
0.09375
0
0
0.479303
0.055556
0
0
0
0
0
1
0
false
0
0.0625
0
0.0625
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d9869f57875e2690d3cd90cc8428e4dc9378e706
2,074
py
Python
tests/step_defs/test_search_steps.py
aura80/TAU_BDD_Reserved_Selenium_Python_New
cccaa437f1c8f4aa4f47f41ca2d5c0b1d3166035
[ "MIT" ]
null
null
null
tests/step_defs/test_search_steps.py
aura80/TAU_BDD_Reserved_Selenium_Python_New
cccaa437f1c8f4aa4f47f41ca2d5c0b1d3166035
[ "MIT" ]
null
null
null
tests/step_defs/test_search_steps.py
aura80/TAU_BDD_Reserved_Selenium_Python_New
cccaa437f1c8f4aa4f47f41ca2d5c0b1d3166035
[ "MIT" ]
null
null
null
import time from pytest_bdd import scenarios, when, then, given, parsers from pages.search import SearchTests from pages.register_page import RegisterPage # Scenarios scenarios('../features/test_register_search_scenario.feature') @given('open the page') def open_page(browser): negative = SearchTests(browser) negative.load_page() @when(parsers.cfparse('we wrote haine "{haine}" in the search field')) @when('we wrote haine "<haine>" in the search field') def check_email(browser, haine): negative = SearchTests(browser) negative.search_pijama_click(haine) @given('open the register page') def open_page(browser): utile = RegisterPage(browser) utile.load_page() @when('generate random email') def random_email(browser): utile = RegisterPage(browser) utile.get_random_mail(5) @when('generate random firstname lastname password') def random_name_pass(browser): utile = RegisterPage(browser) utile.get_random_string(8, 10, 8) time.sleep(5) @when('searching element fuste') def search_element(browser): utile = RegisterPage(browser) utile.get_search() @when('searching element assert') def search_cautare(browser): utile = RegisterPage(browser) utile.get_cautare() @when('searching element pijama') def search_cautare(browser): utile = RegisterPage(browser) utile.get_pijama() #utile.text_cautare() # steps @given('open the search page') def open_page(browser): search_page = SearchTests(browser) search_page.load_page() @when(parsers.cfparse('the user types "{searched_item}" in the search bar')) def search_product(browser, searched_item): # dam searched item ca arametru s aputem cauta cu orice valoare vrem noi ca daca nu tot timpul # scrie pijama search_page = SearchTests(browser) search_page.click_search_button() search_page.search_product(searched_item) @then(parsers.cfparse('each result contains "{searched_item}" in name')) def check_results(browser, searched_item): search_page = SearchTests(browser) search_page.check_results(searched_item)
28.410959
98
0.750241
274
2,074
5.507299
0.310219
0.095427
0.095427
0.12326
0.375083
0.277667
0.176276
0.116634
0.072896
0
0
0.003382
0.144648
2,074
73
99
28.410959
0.847238
0.067985
0
0.307692
0
0
0.219398
0.025415
0
0
0
0
0.019231
1
0.211538
false
0.038462
0.076923
0
0.288462
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
1
d987308ee279d5897c812d0ddad5761b6c09fe3e
8,668
py
Python
pendium/filesystem.py
LuRsT/Pendium
f71b3db987853df919c14f0be4238df00852a9a7
[ "Apache-2.0" ]
5
2015-05-07T21:26:06.000Z
2016-07-27T11:41:49.000Z
pendium/filesystem.py
LuRsT/Pendium
f71b3db987853df919c14f0be4238df00852a9a7
[ "Apache-2.0" ]
9
2017-12-21T20:22:16.000Z
2019-07-24T13:04:35.000Z
pendium/filesystem.py
LuRsT/Pendium
f71b3db987853df919c14f0be4238df00852a9a7
[ "Apache-2.0" ]
null
null
null
import codecs from logging import getLogger import os from pendium import app from pendium.plugins import IRenderPlugin from pendium.plugins import ISearchPlugin from yapsy.PluginManager import PluginManager log = getLogger(__name__) # Populate plugins lib_path = os.path.abspath(os.path.dirname(__file__)) manager = PluginManager() manager.setPluginPlaces([os.path.join(lib_path, "plugins")]) manager.setCategoriesFilter( {"Search": ISearchPlugin, "Render": IRenderPlugin,} ) manager.collectPlugins() class PathExists(Exception): pass class PathNotFound(Exception): pass class CannotRender(Exception): pass class NoSearchPluginAvailable(Exception): pass class Wiki(object): def __init__( self, basepath, extensions={}, default_renderer=None, plugins_config={}, has_vcs=False, ): self.basepath = basepath self.extensions = extensions self.default_renderer = default_renderer self.has_vcs = has_vcs self.vcs = None if self.has_vcs: try: from pendium import git_wrapper self.vcs = git_wrapper.GitWrapper(basepath) except: raise Exception("You need to install GitPython") # Plugin configuration for name, configuration in plugins_config.items(): for cat in ["Search", "Render"]: plugin = manager.getPluginByName(name, category=cat) if not plugin: continue msg = "Configuring plugin: %s with :%s" % (name, configuration) log.debug(msg) plugin.plugin_object.configure(configuration) def search(self, term): best_plugin_score = 0 best_plugin = None for plugin in manager.getPluginsOfCategory("Search"): if plugin.plugin_object.search_speed > best_plugin_score: best_plugin_score = plugin.plugin_object.search_speed best_plugin = plugin if best_plugin is None: raise NoSearchPluginAvailable log.debug("Searching with %s" % best_plugin.name) return best_plugin.plugin_object.search(self, term) def root(self): return self.get(".") def get(self, path): completepath = os.path.normpath(os.path.join(self.basepath, path)) if os.path.isdir(completepath): return WikiDir(self, path) else: return WikiFile(self, path) def refresh(self): if not self.has_vcs: return "" return self.vcs.refresh() class WikiPath(object): def __init__(self, wiki, path): self.path = path self.wiki = wiki self.abs_path = os.path.join(wiki.basepath, path) self.abs_path = os.path.normpath(self.abs_path) self.name = os.path.split(self.path)[1] self.is_node = False self.is_leaf = False if not os.path.exists(self.abs_path): raise PathNotFound(self.abs_path) def ancestor(self): if self.path == "": return None ancestor_dir = os.path.split(self.path)[0] return self.wiki.get(ancestor_dir) def ancestors(self): if self.ancestor(): return self.ancestor().ancestors() + [self.ancestor()] return [] def items(self): if not os.path.isdir(self.abs_path): self = self.ancestor() filenames = [] for f in os.listdir(self.abs_path): if f.find(".") == 0: continue if os.path.splitext(f)[1][1:] in app.config["BLACKLIST_EXTENSIONS"]: continue complete_path = os.path.join(self.path, f) filenames.append(self.wiki.get(complete_path)) return sorted(filenames, key=lambda Wiki: Wiki.is_leaf) @property def editable(self): if app.config["EDITABLE"]: return os.access(self.abs_path, os.W_OK) return False def delete(self): top = self.abs_path for root, dirs, files in os.walk(top, topdown=False): for name in files: log.debug("Will remove FILE: %s", os.path.join(root, name)) os.remove(os.path.join(root, name)) for name in dirs: log.debug("Will remove DIR: %s", os.path.join(root, name)) os.rmdir(os.path.join(root, name)) if self.is_node: log.debug("Will remove DIR: %s", self.abs_path) os.rmdir(self.abs_path) else: log.debug("Will remove FILE: %s", self.abs_path) os.remove(self.abs_path) if self.wiki.has_vcs: self.wiki.vcs.delete(path=self.path) class WikiFile(WikiPath): def __init__(self, *args, **kwargs): super(WikiFile, self).__init__(*args, **kwargs) self.is_leaf = True self.extension = os.path.splitext(self.name)[1][1:] self._content = "" def renderer(self): for plugin in manager.getPluginsOfCategory("Render"): log.debug("Testing for plugin %s", plugin.plugin_object.name) extensions = self.wiki.extensions.get(plugin.plugin_object.name, None) if extensions is None: continue # Try the next plugin if self.extension in extensions: log.debug(self.extension) log.debug(plugin.plugin_object.name) return plugin.plugin_object # If no renderer found and binary, give up if self.is_binary: return None # If is not binary and we have a default renderer # return it if self.wiki.default_renderer: return self.wiki.default_renderer return None @property def can_render(self): return bool(self.renderer()) def render(self): if self.can_render: renderer = self.renderer() return renderer.render(self.content()) # No renderer found if self.is_binary: return self.content(decode=False) return self.content() @property def is_binary(self): """ Return true if the file is binary. """ fin = open(self.abs_path, "rb") try: CHUNKSIZE = 1024 while 1: chunk = fin.read(CHUNKSIZE).decode("utf-8") if "\0" in chunk: # Found null byte return True if len(chunk) < CHUNKSIZE: break # Done finally: fin.close() return False @property def refs(self): """ Special property for Git refs """ if self.wiki.has_vcs: return self.wiki.vcs.file_refs(self.path) return [] def ref(self, ref): """ Update file content with appropriate reference from git to display older file versions """ try: content = self.wiki.vcs.show(filepath=self.path, ref=ref) self._content = content.decode("utf8") return True except: return False def content(self, content=None, decode=True): """ Helper method, needs refactoring """ if self._content and content is None: return self._content fp = open(self.abs_path, "r") ct = fp.read() if decode: ct = ct fp.close() if not content: self._content = ct return ct self._content = content if content == ct: return ct def save(self, comment=None): fp = codecs.open(self.abs_path, "w", "utf-8") fp.write(self._content) fp.close() if self.wiki.has_vcs: self.wiki.vcs.save(path=self.path, comment=comment) class WikiDir(WikiPath): def __init__(self, *args, **kwargs): super(WikiDir, self).__init__(*args, **kwargs) self.is_node = True def create_file(self, filename): new_abs_path = os.path.join(self.abs_path, filename) if os.path.exists(new_abs_path): raise PathExists(new_abs_path) fp = open(new_abs_path, "w") fp.close() return self.wiki.get(os.path.join(self.path, filename)) def create_directory(self, name): new_abs_path = os.path.join(self.abs_path, name) if os.path.exists(new_abs_path): raise PathExists(new_abs_path) os.makedirs(new_abs_path) np = self.wiki.get(os.path.join(self.path, name)) return np
27.782051
82
0.578565
1,034
8,668
4.72147
0.190522
0.03728
0.040557
0.017206
0.193773
0.122081
0.094224
0.055715
0.032773
0.020074
0
0.002884
0.320028
8,668
311
83
27.871383
0.825416
0.043955
0
0.201794
0
0
0.033015
0
0
0
0
0
0
1
0.103139
false
0.017937
0.035874
0.008969
0.318386
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d988d23ea27ce8a2b5e3d30a08db96c282196fd0
3,957
py
Python
sabcom/helpers.py
blackrhinoabm/sabcom
ec0d9c37e11a8bd49352539f3f16ef322e1b5cf8
[ "MIT" ]
6
2020-05-21T11:42:27.000Z
2020-10-20T03:00:22.000Z
sabcom/helpers.py
blackrhinoabm/sabcom
ec0d9c37e11a8bd49352539f3f16ef322e1b5cf8
[ "MIT" ]
2
2020-04-08T17:45:37.000Z
2020-09-22T16:13:27.000Z
sabcom/helpers.py
blackrhinoabm/sabcom
ec0d9c37e11a8bd49352539f3f16ef322e1b5cf8
[ "MIT" ]
4
2020-04-10T14:18:34.000Z
2020-10-31T16:18:30.000Z
import random import numpy as np import pandas as pd import math from sklearn import preprocessing import scipy.stats as stats def edge_in_cliq(edge, nodes_in_cliq): if edge[0] in nodes_in_cliq: return True else: return False def edges_to_remove_neighbourhood(all_edges, neighbourhood_density, nbh_nodes): neighbourhood_edges = [e for e in all_edges if edge_in_cliq(e, nbh_nodes)] sample_size = int(len(neighbourhood_edges) * (1-neighbourhood_density)) # sample random edges chosen_edges = random.sample(neighbourhood_edges, sample_size) return chosen_edges def what_neighbourhood(index, neighbourhood_nodes): for n in neighbourhood_nodes: if index in neighbourhood_nodes[n]: return n raise ValueError('Neighbourhood not found.') def what_coordinates(neighbourhood_name, dataset): for x in range(len(dataset)): if neighbourhood_name in dataset[x]: return dataset[x][1]['lon'], dataset[x][1]['lat'], raise ValueError("Corresponding coordinates not found") def what_informality(neighbourhood_name, dataset): for x in range(len(dataset)): if neighbourhood_name in dataset[x]: try: return dataset[x][1]['Informal_residential'] except: return None raise ValueError("Corresponding informality not found") def confidence_interval(data, av): sample_stdev = np.std(data) sigma = sample_stdev/math.sqrt(len(data)) return stats.t.interval(alpha=0.95, df=24, loc=av, scale=sigma) def generate_district_data(number_of_agents, path, max_districts=None): """ Transforms input data on informal residential, initial infections, and population and transforms it to a list of organised data for the simulation. :param number_of_agents: number of agents in the simulation, integer :param max_districts: (optional) maximum amount of districts simulated, integer :return: data set containing district data for simulation, list """ informal_residential = pd.read_csv('{}/f_informality.csv'.format(path))#.iloc[:-1] inital_infections = pd.read_csv('{}/f_initial_cases.csv'.format(path), index_col=1) inital_infections = inital_infections.sort_index() population = pd.read_csv('{}/f_population.csv'.format(path)) # normalise district informality x = informal_residential[['Informal_residential']].values.astype(float) min_max_scaler = preprocessing.MinMaxScaler() x_scaled = min_max_scaler.fit_transform(x) informal_residential['Informal_residential'] = pd.DataFrame(x_scaled) population['Informal_residential'] = informal_residential['Informal_residential'] # determine smallest district based on number of agents smallest_size = population['Population'].sum() / number_of_agents # generate data set for model input districts_data = [] for i in range(len(population)): if population['Population'].iloc[i] > smallest_size: districts_data.append( [int(population['WardID'].iloc[i]), {'Population': population['Population'].iloc[i], #'lon': population['lon'].iloc[i], #'lat': population['lat'].iloc[i], 'Informal_residential': population['Informal_residential'].iloc[i], 'Cases_With_Subdistricts': inital_infections.loc[population['WardID'].iloc[i]][ 'Cases'], }, ]) if max_districts is None: max_districts = len(districts_data) # this can be manually shortened to study dynamics in some districts return districts_data[:max_districts]
39.57
120
0.645438
458
3,957
5.382096
0.312227
0.092495
0.028398
0.061663
0.091684
0.060041
0.060041
0.060041
0.060041
0.060041
0
0.004108
0.261815
3,957
99
121
39.969697
0.839781
0.16275
0
0.063492
0
0
0.116371
0.013745
0
0
0
0
0
1
0.111111
false
0
0.095238
0
0.349206
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d989087921d1b51a7238e387777319d8107f335c
767
py
Python
tests/io_test.py
wgfi110/speech
59a3e2d8d2d99d31cf32e06c1a0751eb36a3c02b
[ "Apache-2.0" ]
642
2017-09-27T01:11:16.000Z
2022-03-29T11:02:08.000Z
tests/io_test.py
wgfi110/speech
59a3e2d8d2d99d31cf32e06c1a0751eb36a3c02b
[ "Apache-2.0" ]
54
2017-10-06T18:21:42.000Z
2021-01-15T07:10:21.000Z
tests/io_test.py
wgfi110/speech
59a3e2d8d2d99d31cf32e06c1a0751eb36a3c02b
[ "Apache-2.0" ]
176
2017-09-27T16:10:08.000Z
2022-03-15T03:43:07.000Z
import tempfile import speech.models import speech.loader import shared def test_save(): freq_dim = 120 model = speech.models.Model(freq_dim, shared.model_config) batch_size = 2 data_json = "test.json" preproc = speech.loader.Preprocessor(data_json) save_dir = tempfile.mkdtemp() speech.save(model, preproc, save_dir) s_model, s_preproc = speech.load(save_dir) assert hasattr(s_preproc, 'mean') assert hasattr(s_preproc, 'std') assert hasattr(s_preproc, 'int_to_char') assert hasattr(s_preproc, 'char_to_int') msd = model.state_dict() for k, v in s_model.state_dict().items(): assert k in msd assert hasattr(s_model, 'encoder_dim') assert hasattr(s_model, 'is_cuda')
23.96875
51
0.680574
109
767
4.541284
0.394495
0.157576
0.169697
0.169697
0
0
0
0
0
0
0
0.006656
0.216428
767
31
52
24.741935
0.816972
0
0
0
0
0
0.073012
0
0
0
0
0
0.304348
1
0.043478
false
0
0.173913
0
0.217391
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
d989c05c96298ca370a7889007b9e02fb326abb5
928
py
Python
image_analyse/Image CDF and PDF.py
TheRockerfly/data_mining_portfolio
a84f1a1a9dc9fec668b81e012e9d130d91227598
[ "MIT" ]
null
null
null
image_analyse/Image CDF and PDF.py
TheRockerfly/data_mining_portfolio
a84f1a1a9dc9fec668b81e012e9d130d91227598
[ "MIT" ]
null
null
null
image_analyse/Image CDF and PDF.py
TheRockerfly/data_mining_portfolio
a84f1a1a9dc9fec668b81e012e9d130d91227598
[ "MIT" ]
null
null
null
import matplotlib.pyplot as plt # TODO: port away from matplotlib to a seaborn # Probability Distribution Function (PDF). # Cumulative Distribution Function (CDF) # TODO: put all of these functions within a custom function image = plt.imread('900px-Astronaut-EVA.jpg') plt.subplot(2, 1, 1) plt.imshow(image, cmap='gray') plt.title('Original image') plt.axis('off') pixels = image.flatten() # Display a histogram of the pixels in the bottom subplot plt.subplot(2, 1, 2) pdf = plt.hist(pixels, bins=64, range=(0, 256), normed=False, color='red', alpha=0.4) plt.grid('off') # Use plt.twinx() to overlay the CDF in the bottom subplot plt.twinx() # Display a cumulative histogram of the pixels cdf = plt.hist(pixels, bins=64, range=(0, 256), normed=True, cumulative=True, color='blue', alpha=0.4) plt.xlim((0, 256)) plt.grid('off') plt.title('PDF - red & CDF - blue (original image)') plt.show()
29.935484
79
0.693966
147
928
4.380952
0.462585
0.037267
0.034161
0.037267
0.170807
0.10559
0.10559
0.10559
0.10559
0
0
0.037371
0.163793
928
30
80
30.933333
0.792526
0.366379
0
0.111111
0
0
0.165517
0.039655
0
0
0
0.033333
0
1
0
false
0
0.055556
0
0.055556
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
1
d98a64a68a68150c17a5ba9fa0b9485585e96dc4
35
py
Python
yolo/model_zoo/__init__.py
ioangatop/yolo
c65a72337369572bc07090f39123e2bf6ff5f4a3
[ "MIT" ]
1
2021-06-28T01:22:38.000Z
2021-06-28T01:22:38.000Z
yolo/model_zoo/__init__.py
ioangatop/yolo
c65a72337369572bc07090f39123e2bf6ff5f4a3
[ "MIT" ]
null
null
null
yolo/model_zoo/__init__.py
ioangatop/yolo
c65a72337369572bc07090f39123e2bf6ff5f4a3
[ "MIT" ]
null
null
null
from .model_zoo import load_weights
35
35
0.885714
6
35
4.833333
1
0
0
0
0
0
0
0
0
0
0
0
0.085714
35
1
35
35
0.90625
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
5
d98b62aa0fdb706a6f4cb4c830afcb3e8f4fca20
282
py
Python
test_logger/demo.py
payalkutana/logging_logger
7dc7ccaee63e922b7c7f699a5d0b4e1317a27502
[ "MIT" ]
null
null
null
test_logger/demo.py
payalkutana/logging_logger
7dc7ccaee63e922b7c7f699a5d0b4e1317a27502
[ "MIT" ]
null
null
null
test_logger/demo.py
payalkutana/logging_logger
7dc7ccaee63e922b7c7f699a5d0b4e1317a27502
[ "MIT" ]
null
null
null
from logging_logger import loggerClass import logging loggerClass.WritetoScreen(loggerClass,logging.INFO,"testing...", '%(levelname)s:%(message)s') loggerClass.Writetofile(loggerClass,'sample.log',logging.WARNING,"testing...", '%(levelname)s:%(message)s')
31.333333
78
0.70922
29
282
6.862069
0.517241
0.160804
0.170854
0.241206
0.251256
0
0
0
0
0
0
0
0.12766
282
8
79
35.25
0.808943
0
0
0.333333
0
0
0.283688
0.177305
0
0
0
0
0
1
0
true
0
0.333333
0
0.333333
0
1
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
5
d98be932a3e4d84d93b13cf5f54ee3801d2adc54
111
py
Python
LearnPython3TheHardWay/ex8.py
lanjing99/UsePython
19a84e3ef65dc326cf9c4bfccbf2d99c22f858a4
[ "MIT" ]
null
null
null
LearnPython3TheHardWay/ex8.py
lanjing99/UsePython
19a84e3ef65dc326cf9c4bfccbf2d99c22f858a4
[ "MIT" ]
null
null
null
LearnPython3TheHardWay/ex8.py
lanjing99/UsePython
19a84e3ef65dc326cf9c4bfccbf2d99c22f858a4
[ "MIT" ]
null
null
null
formatter = "{} {} {} {}" print(formatter.format(1, 2, 3, 4)) print(formatter.format("a", "b", "c", "d", "r"))
27.75
48
0.522523
16
111
3.625
0.75
0.482759
0.689655
0
0
0
0
0
0
0
0
0.041667
0.135135
111
3
49
37
0.5625
0
0
0
0
0
0.144144
0
0
0
0
0
0
1
0
false
0
0
0
0
0.666667
1
0
0
null
1
1
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
5
d98cbe93e213130d35e4010a52b1592965b94b18
14,115
py
Python
src/matching/games/hospital_resident.py
drvinceknight/matching
da18fc12c880a1292a04d06824b5c17e68349e83
[ "MIT" ]
null
null
null
src/matching/games/hospital_resident.py
drvinceknight/matching
da18fc12c880a1292a04d06824b5c17e68349e83
[ "MIT" ]
null
null
null
src/matching/games/hospital_resident.py
drvinceknight/matching
da18fc12c880a1292a04d06824b5c17e68349e83
[ "MIT" ]
null
null
null
""" The HR solver and algorithm. """ from matching import Game, Matching from matching import Player as Resident from matching.players import Hospital from .util import delete_pair, match_pair class HospitalResident(Game): """ A class for solving instances of the hospital-resident assignment problem (HR). In this case, a blocking pair is any resident-hospital pair that satisfies **all** of the following: - They are present in each other's preference lists; - either the resident is unmatched, or they prefer the hospital to their current match; - either the hospital is under-subscribed, or they prefer the resident to at least one of their current matches. Parameters ---------- residents : list of Player The residents in the matching game. Each resident must rank a subset of those in :code:`hospitals`. hospitals : list of Hospital The hospitals in the matching game. Each hospital must rank all of (and only) the residents which rank it. Attributes ---------- matching : Matching or None Once the game is solved, a matching is available as a :code:`Matching` object with the hospitals as keys and their resident matches as values. Initialises as :code:`None`. blocking_pairs : list of (Player, Hospital) or None Initialises as `None`. Otherwise, a list of the resident-hospital blocking pairs. """ def __init__(self, residents=None, hospitals=None): self.residents = residents self.hospitals = hospitals super().__init__() self._check_inputs() @classmethod def create_from_dictionaries( cls, resident_prefs, hospital_prefs, capacities ): """ Create an instance of :code:`HospitalResident` from two preference dictionaries and capacities. """ residents, hospitals = _make_players( resident_prefs, hospital_prefs, capacities ) game = cls(residents, hospitals) return game def solve(self, optimal="resident"): """ Solve the instance of HR using either the resident- or hospital-oriented algorithm. Return the matching. """ self._matching = Matching( hospital_resident(self.residents, self.hospitals, optimal) ) return self.matching def check_validity(self): """ Check whether the current matching is valid. """ self._check_resident_matching() self._check_hospital_capacity() self._check_hospital_matching() return True def check_stability(self): """ Check for the existence of any blocking pairs in the current matching, thus determining the stability of the matching. """ blocking_pairs = [] for resident in self.residents: for hospital in self.hospitals: if ( _check_mutual_preference(resident, hospital) and _check_resident_unhappy(resident, hospital) and _check_hospital_unhappy(resident, hospital) ): blocking_pairs.append((resident, hospital)) self.blocking_pairs = blocking_pairs return not any(blocking_pairs) def _check_resident_matching(self): """ Check that no resident is matched to an unacceptable hospital. """ errors = [] for resident in self.residents: if ( resident.matching is not None and resident.matching not in resident.prefs ): errors.append( ValueError( f"{resident} is matched to {resident.matching} but " "they do not appear in their preference list: " f"{resident.prefs}." ) ) if errors: raise Exception(*errors) return True def _check_hospital_capacity(self): """ Check that no hospital is over-subscribed. """ errors = [] for hospital in self.hospitals: if len(hospital.matching) > hospital.capacity: errors.append( ValueError( f"{hospital} is matched to {hospital.matching} which " f"is over their capacity of {hospital.capacity}." ) ) if errors: raise Exception(*errors) return True def _check_hospital_matching(self): """ Check that no hospital is matched to an unacceptable resident. """ errors = [] for hospital in self.hospitals: for resident in hospital.matching: if resident not in hospital.prefs: errors.append( ValueError( f"{hospital} has {resident} in their matching but " "they do not appear in their preference list: " f"{hospital.prefs}." ) ) if errors: raise Exception(*errors) return True def _check_inputs(self): """ Raise an error if any of the conditions of the game have been broken. """ self._check_resident_prefs() self._check_hospital_prefs() def _check_resident_prefs(self): """ Make sure that the residents' preferences are all subsets of the available hospital names. Otherwise, raise an error. """ errors = [] for resident in self.residents: if not set(resident.prefs).issubset(set(self.hospitals)): errors.append( ValueError( f"{resident} has ranked a non-hospital: " f"{set(resident.prefs)} != {set(self.hospitals)}" ) ) if errors: raise Exception(*errors) return True def _check_hospital_prefs(self): """ Make sure that every hospital ranks all and only those residents that have ranked it. Otherwise, raise an error. """ errors = [] for hospital in self.hospitals: residents_that_ranked = [ res for res in self.residents if hospital in res.prefs ] if set(hospital.prefs) != set(residents_that_ranked): errors.append( ValueError( f"{hospital} has not ranked all the residents that " f"ranked it: {set(hospital.prefs)} != " f"{set(residents_that_ranked)}." ) ) if errors: raise Exception(*errors) return True def _check_mutual_preference(resident, hospital): """ Determine whether two players each have a preference of the other. """ return resident in hospital.prefs and hospital in resident.prefs def _check_resident_unhappy(resident, hospital): """ Determine whether a resident is unhappy because they are unmatched, or they prefer the hospital to their current match. """ return resident.matching is None or resident.prefers( hospital, resident.matching ) def _check_hospital_unhappy(resident, hospital): """ Determine whether a hospital is unhappy because they are under-subscribed, or they prefer the resident to at least one of their current matches. """ return len(hospital.matching) < hospital.capacity or any( [hospital.prefers(resident, match) for match in hospital.matching] ) def unmatch_pair(resident, hospital): """ Unmatch a (resident, hospital)-pair. """ resident.unmatch() hospital.unmatch(resident) def hospital_resident(residents, hospitals, optimal="resident"): """ Solve an instance of HR using an adapted Gale-Shapley algorithm. A unique, stable and optimal matching is found for the given set of residents and hospitals. The optimality of the matching is found with respect to one party and is subsequently the worst stable matching for the other. Parameters ---------- residents : list of Player The residents in the game. Each resident must rank a non-empty subset of the elements of ``hospitals``. hospitals : list of Hospital The hospitals in the game. Each hospital must rank all the residents that have ranked them. optimal : str, optional Which party the matching should be optimised for. Must be one of ``"resident"`` and ``"hospital"``. Defaults to the former. Returns ------- matching : Matching A dictionary-like object where the keys are the members of ``hospitals``, and the values are their matches ranked by preference. """ if optimal == "resident": return resident_optimal(residents, hospitals) if optimal == "hospital": return hospital_optimal(hospitals) def resident_optimal(residents, hospitals): """ Solve the instance of HR to be resident-optimal. The algorithm is as follows: 0. Set all residents to be unmatched, and all hospitals to be totally unsubscribed. 1. Take any unmatched resident with a non-empty preference list, :math:`r`, and consider their most preferred hospital, :math:`h`. Match them to one another. 2. If, as a result of this new matching, :math:`h` is now over-subscribed, find the worst resident currently assigned to :math:`h`, :math:`r'`. Set :math:`r'` to be unmatched and remove them from :math:`h`'s matching. Otherwise, go to 3. 3. If :math:`h` is at capacity (fully subscribed) then find their worst current match :math:`r'`. Then, for each successor, :math:`s`, to :math:`r'` in the preference list of :math:`h`, delete the pair :math:`(s, h)` from the game. Otherwise, go to 4. 4. Go to 1 until there are no such residents left, then end. """ free_residents = residents[:] while free_residents: resident = free_residents.pop() hospital = resident.get_favourite() match_pair(resident, hospital) if len(hospital.matching) > hospital.capacity: worst = hospital.get_worst_match() unmatch_pair(worst, hospital) free_residents.append(worst) if len(hospital.matching) == hospital.capacity: successors = hospital.get_successors() for successor in successors: delete_pair(hospital, successor) if not successor.prefs: free_residents.remove(successor) return {r: r.matching for r in hospitals} def hospital_optimal(hospitals): """ Solve the instance of HR to be hospital-optimal. The algorithm is as follows: 0. Set all residents to be unmatched, and all hospitals to be totally unsubscribed. 1. Take any hospital, :math:`h`, that is under-subscribed and whose preference list contains any resident they are not currently assigned to, and consider their most preferred such resident, :math:`r`. 2. If :math:`r` is currently matched, say to :math:`h'`, then unmatch them from one another. In any case, match :math:`r` to :math:`h` and go to 3. 3. For each successor, :math:`s`, to :math:`h` in the preference list of :math:`r`, delete the pair :math:`(r, s)` from the game. 4. Go to 1 until there are no such hospitals left, then end. """ free_hospitals = hospitals[:] while free_hospitals: hospital = free_hospitals.pop() resident = hospital.get_favourite() if resident.matching: curr_match = resident.matching unmatch_pair(resident, curr_match) if curr_match not in free_hospitals: free_hospitals.append(curr_match) match_pair(resident, hospital) if len(hospital.matching) < hospital.capacity and [ res for res in hospital.prefs if res not in hospital.matching ]: free_hospitals.append(hospital) successors = resident.get_successors() for successor in successors: delete_pair(resident, successor) if ( not [ res for res in successor.prefs if res not in successor.matching ] and successor in free_hospitals ): free_hospitals.remove(successor) return {r: r.matching for r in hospitals} def _make_players(resident_prefs, hospital_prefs, capacities): """ Make a set of residents and hospitals from the dictionaries given, and add their preferences. """ resident_dict, hospital_dict = _make_instances( resident_prefs, hospital_prefs, capacities ) for resident_name, resident in resident_dict.items(): prefs = [hospital_dict[name] for name in resident_prefs[resident_name]] resident.set_prefs(prefs) for hospital_name, hospital in hospital_dict.items(): prefs = [resident_dict[name] for name in hospital_prefs[hospital_name]] hospital.set_prefs(prefs) residents = list(resident_dict.values()) hospitals = list(hospital_dict.values()) return residents, hospitals def _make_instances(resident_prefs, hospital_prefs, capacities): """ Create ``Player`` (resident) and ``Hospital`` instances for the names in each dictionary. """ resident_dict, hospital_dict = {}, {} for resident_name in resident_prefs: resident = Resident(name=resident_name) resident_dict[resident_name] = resident for hospital_name in hospital_prefs: capacity = capacities[hospital_name] hospital = Hospital(name=hospital_name, capacity=capacity) hospital_dict[hospital_name] = hospital return resident_dict, hospital_dict
34.426829
80
0.616932
1,646
14,115
5.190765
0.136695
0.022823
0.009129
0.01264
0.384129
0.280197
0.20529
0.168539
0.149813
0.115871
0
0.001533
0.306624
14,115
409
81
34.511002
0.871462
0.365639
0
0.278049
0
0
0.064821
0.010882
0
0
0
0
0
1
0.097561
false
0
0.019512
0
0.209756
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d98e4516cf482bd1a8b30548c1119b56db7376b4
2,931
py
Python
solutions/rank-1/prepare_data.py
mattmotoki/ashrae-great-energy-predictor-3-solution-analysis
8a5260049d4537c57c37a78e77f2fba13c55177d
[ "MIT" ]
48
2020-03-18T11:34:49.000Z
2022-03-31T18:30:00.000Z
solutions/rank-1/prepare_data.py
mattmotoki/ashrae-great-energy-predictor-3-solution-analysis
8a5260049d4537c57c37a78e77f2fba13c55177d
[ "MIT" ]
40
2020-03-24T18:17:51.000Z
2022-03-12T00:30:30.000Z
solutions/rank-1/prepare_data.py
mattmotoki/ashrae-great-energy-predictor-3-solution-analysis
8a5260049d4537c57c37a78e77f2fba13c55177d
[ "MIT" ]
24
2020-04-18T02:52:47.000Z
2022-01-22T19:13:16.000Z
#!/usr/bin/env python # coding: utf-8 # based on public kernel https://www.kaggle.com/corochann/ashrae-feather-format-for-fast-loading import os import random import gc import tqdm import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def prepare(root, output): train_df = pd.read_csv(os.path.join(root, 'train.csv')) test_df = pd.read_csv(os.path.join(root, 'test.csv')) building_meta_df = pd.read_csv(os.path.join(root, 'building_metadata.csv')) sample_submission = pd.read_csv(os.path.join(root, 'sample_submission.csv')) weather_train_df = pd.read_csv(os.path.join(root, 'weather_train.csv')) weather_test_df = pd.read_csv(os.path.join(root, 'weather_test.csv')) train_df['timestamp'] = pd.to_datetime(train_df['timestamp']) test_df['timestamp'] = pd.to_datetime(test_df['timestamp']) weather_train_df['timestamp'] = pd.to_datetime(weather_train_df['timestamp']) weather_test_df['timestamp'] = pd.to_datetime(weather_test_df['timestamp']) # # Save data in feather format train_df.to_feather(os.path.join(output,'train.feather')) test_df.to_feather(os.path.join(output,'test.feather')) weather_train_df.to_feather(os.path.join(output,'weather_train.feather')) weather_test_df.to_feather(os.path.join(output,'weather_test.feather')) building_meta_df.to_feather(os.path.join(output,'building_metadata.feather')) sample_submission.to_feather(os.path.join(output,'sample_submission.feather')) # # Read data in feather format train_df = pd.read_feather(os.path.join(output, 'train.feather')) weather_train_df = pd.read_feather(os.path.join(output, 'weather_train.feather')) test_df = pd.read_feather(os.path.join(output, 'test.feather')) weather_test_df = pd.read_feather(os.path.join(output, 'weather_test.feather')) building_meta_df = pd.read_feather(os.path.join(output, 'building_metadata.feather')) sample_submission = pd.read_feather(os.path.join(output, 'sample_submission.feather')) # # Count zero streak train_df = train_df.merge(building_meta_df, on='building_id', how='left') train_df = train_df.merge(weather_train_df, on=['site_id', 'timestamp'], how='left') train_df['black_count']=0 for bid in train_df.building_id.unique(): df = train_df[train_df.building_id==bid] for meter in df.meter.unique(): dfm = df[df.meter == meter] b = (dfm.meter_reading == 0).astype(int) train_df.loc[(train_df.building_id==bid) & (train_df.meter == meter), 'black_count'] = b.groupby((~b.astype(bool)).cumsum()).cumsum() #train_df[train_df.building_id == 0].meter_reading.plot() #train_df[train_df.building_id == 0].black_count.plot() train_df.to_feather(os.path.join(output, 'train_black.feather')) if __name__ == '__main__': root = 'input' output = 'processed' prepare(root, output)
40.708333
145
0.716479
445
2,931
4.460674
0.197753
0.095214
0.095718
0.111335
0.609068
0.561713
0.467003
0.416625
0.285139
0.117884
0
0.001974
0.13579
2,931
71
146
41.28169
0.781682
0.107813
0
0
0
0
0.189708
0.070661
0
0
0
0
0
1
0.022222
false
0
0.177778
0
0.2
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d98fb88b15b7a7bd1330a40dd1ecdb89f69e5b99
23,531
py
Python
models/triangular_lattice.py
macthecadillac/Interacting-Fermions
6122d2a7e67533b28e581929995ce8e2a2ad41fc
[ "BSD-3-Clause" ]
1
2020-07-29T06:06:12.000Z
2020-07-29T06:06:12.000Z
models/triangular_lattice.py
macthecadillac/Interacting-Fermions
6122d2a7e67533b28e581929995ce8e2a2ad41fc
[ "BSD-3-Clause" ]
null
null
null
models/triangular_lattice.py
macthecadillac/Interacting-Fermions
6122d2a7e67533b28e581929995ce8e2a2ad41fc
[ "BSD-3-Clause" ]
null
null
null
import copy import functools import os import numpy as np from scipy import sparse from spinsys import constructors, half, dmrg, exceptions from cffi import FFI class SiteVector(constructors.PeriodicBCSiteVector): def __init__(self, ordered_pair, Nx, Ny): super().__init__(ordered_pair, Nx, Ny) def angle_with(self, some_site): """Returns the angle * 2 between (some_site - self) with the horizontal. Only works on nearest neighbors """ Δx, Δy = some_site - self if Δx == 0: if Δy != 0: return -2 * np.pi / 3 elif Δy == 0: if Δx != 0: return 0 else: return 2 * np.pi / 3 def a1_hop(self, stride): vec = self.xhop(stride) if vec == self: raise exceptions.SameSite return vec def a2_hop(self, stride): vec = self.xhop(-1 * stride).yhop(stride) if vec == self: raise exceptions.SameSite return vec def a3_hop(self, stride): vec = self.yhop(-stride) if vec == self: raise exceptions.SameSite return vec def b1_hop(self, stride): """hop in the a1 - a3 aka b1 direction. Useful for second nearest neighbor coupling interactions """ vec = self.xhop(stride).yhop(stride) if vec == self: raise exceptions.SameSite return vec def b2_hop(self, stride): vec = self.xhop(-2 * stride).yhop(stride) if vec == self: raise exceptions.SameSite return vec def b3_hop(self, stride): vec = self.b1_hop(-stride).b2_hop(-stride) if vec == self: raise exceptions.SameSite return vec def _neighboring_sites(self, strides, funcs): neighbors = [] for stride in strides: for func in funcs: try: neighbors.append(func(stride)) except exceptions.SameSite: continue return neighbors @property def nearest_neighboring_sites(self, all=False): strides = [1, -1] if all else [1] funcs = [self.a1_hop, self.a2_hop, self.a3_hop] return self._neighboring_sites(strides, funcs) @property def second_neighboring_sites(self, all=False): """with the all option enabled the method will enumerate all the sites that are second neighbors to the current site. Otherwise it will only enumerate the sites along the b1, b2 and b3 directions """ strides = [1, -1] if all else [1] funcs = [self.b1_hop, self.b2_hop, self.b3_hop] return self._neighboring_sites(strides, funcs) @property def third_neighboring_sites(self, all=False): strides = [2, -2] if all else [2] funcs = [self.a1_hop, self.a2_hop, self.a3_hop] return self._neighboring_sites(strides, funcs) class SemiPeriodicBCSiteVector(SiteVector): """A version of SiteVector that is periodic only along the x direction """ def __init__(self, ordered_pair, Nx, Ny): super().__init__(ordered_pair, Nx, Ny) def diff(self, other): """Finds the shortest distance from this site to the other""" Δx = self.x - other.x Δy = self.y - other.y return (Δx, Δy) def yhop(self, stride): new_vec = copy.copy(self) new_y = self.y + stride if new_y // self.Ny == self.x // self.Ny: new_vec.y = new_y else: raise exceptions.OutOfBoundsError("Hopping off the lattice") return new_vec @property def neighboring_sites(self): neighbors = [] funcs = [self.xhop, self.yhop] for Δ in [1, -1]: for func in funcs: try: neighbors.append(func(Δ).lattice_index) except exceptions.OutOfBoundsError: continue try: neighbors.append(self.xhop(Δ).yhop(-Δ).lattice_index) except exceptions.OutOfBoundsError: continue return neighbors @functools.lru_cache(maxsize=None) def _generate_bonds(Nx, Ny): N = Nx * Ny vec = SiteVector((0, 0), Nx, Ny) # range_orders = [set(), set(), set()] # sets de-duplicates the list of bonds range_orders = [[], [], []] for i in range(N): nearest_neighbor = vec.nearest_neighboring_sites second_neighbor = vec.second_neighboring_sites third_neighbor = vec.third_neighboring_sites neighbors = [nearest_neighbor, second_neighbor, third_neighbor] for leap, bonds in enumerate(range_orders): for n in neighbors[leap]: # sort them so identical bonds will always have the same hash bond = sorted((vec, n)) bonds.append(tuple(bond)) vec = vec.next_site() return range_orders @functools.lru_cache(maxsize=None) def _gen_full_ops(N): σ_p = constructors.raising() σ_m = constructors.lowering() σz = constructors.sigmaz() p_mats = [half.full_matrix(σ_p, k, N) for k in range(N)] m_mats = [half.full_matrix(σ_m, k, N) for k in range(N)] z_mats = [half.full_matrix(σz, k, N) for k in range(N)] return p_mats, m_mats, z_mats def _gen_z_pm_ops(N, bonds): """generate the H_z and H_pm components of the Hamiltonian""" H_pm = H_z = 0 p_mats, m_mats, z_mats = _gen_full_ops(N) for bond in bonds: site1, site2 = bond i, j = site1.lattice_index, site2.lattice_index H_pm += p_mats[i].dot(m_mats[j]) + m_mats[i].dot(p_mats[j]) H_z += z_mats[i].dot(z_mats[j]) return H_pm, H_z @functools.lru_cache(maxsize=None) def hamiltonian_dp_components(Nx, Ny): """Generate the reusable pieces of the hamiltonian""" N = Nx * Ny nearest, second, third = _generate_bonds(Nx, Ny) H_pm1, H_z1 = _gen_z_pm_ops(N, nearest) H_pm2, H_z2 = _gen_z_pm_ops(N, second) H_pm3, H_z3 = _gen_z_pm_ops(N, third) H_ppmm = H_pmz = 0 p_mats, m_mats, z_mats = _gen_full_ops(N) for bond in nearest: site1, site2 = bond i, j = site1.lattice_index, site2.lattice_index γ = np.exp(1j * site1.angle_with(site2)) H_ppmm += \ γ * p_mats[i].dot(p_mats[j]) + \ γ.conj() * m_mats[i].dot(m_mats[j]) H_pmz += 1j * (γ.conj() * z_mats[i].dot(p_mats[j]) - γ * z_mats[i].dot(m_mats[j]) + γ.conj() * p_mats[i].dot(z_mats[j]) - γ * m_mats[i].dot(z_mats[j])) return H_pm1, H_z1, H_ppmm, H_pmz, H_pm2, H_z2, H_z3, H_pm3 def hamiltonian_dp(Nx, Ny, J_pm=0, J_z=0, J_ppmm=0, J_pmz=0, J2=0, J3=0): """Generates hamiltonian for the triangular lattice model with direct product Parameters -------------------- Nx: int number of sites along the x-direction Ny: int number of sites along the y-direction J_pm: float J_+- parameter J_z: float J_z parameter J_ppmm: float J_++-- parameter J_pmz: float J_+-z parameter J2: float second nearest neighbor interaction parameter J3: float third nearest neighbor interaction parameter Returns -------------------- H: scipy.sparse.csc_matrix """ components = hamiltonian_dp_components(Nx, Ny) H_pm1, H_z1, H_ppmm, H_pmz, H_pm2, H_z2, H_z3, H_pm3 = components nearest_neighbor_terms = J_pm * H_pm1 + J_z * H_z1 + J_ppmm * H_ppmm + J_pmz * H_pmz second_neighbor_terms = third_neighbor_terms = 0 if not J2 == 0: second_neighbor_terms = J2 * (H_pm2 + J_z / J_pm * H_z2) if not J3 == 0: third_neighbor_terms = J3 * (H_pm3 + J_z / J_pm * H_z3) return nearest_neighbor_terms + second_neighbor_terms + third_neighbor_terms class DMRG_Hamiltonian(dmrg.Hamiltonian): def __init__(self, Nx, Ny, J_pm=0, J_z=0, J_ppmm=0, J_pmz=0): self.generators = { '+': constructors.raising(), '-': constructors.lowering(), 'z': constructors.sigmaz() } self.N = Nx * Ny self.Nx = Nx self.Ny = Ny self.J_pm = J_pm self.J_z = J_z self.J_ppmm = J_ppmm self.J_pmz = J_pmz super().__init__() def initialize_storage(self): init_block = sparse.csc_matrix(([], ([], [])), dims=[2, 2]) init_ops = self.generators self.storage = dmrg.Storage(init_block, init_block, init_ops) def newsite_ops(self, size): return dict((i, sparse.kron(sparse.eye(size // 2), self.generators[i])) for i in self.generators.keys()) # TODO: Inconsistent shapes error at runtime def block_newsite_interaction(self, block_key): block_side, curr_site = block_key site = SemiPeriodicBCSiteVector.from_index(curr_site, self.Nx, self.Ny) neighbors = [i for i in site.neighboring_sites if i < curr_site] H_pm_new = H_z_new = H_ppmm_new = H_pmz_new = 0 for i in neighbors: key = (block_side, i + 1) block_ops = self.storage.get_item(key).ops site_ops = self.generators H_pm_new += \ sparse.kron(block_ops['+'], site_ops['-']) + \ sparse.kron(block_ops['-'], site_ops['+']) H_z_new += sparse.kron(block_ops['z'], site_ops['z']) H_ppmm_new += \ sparse.kron(block_ops['+'], site_ops['+']) + \ sparse.kron(block_ops['-'], site_ops['-']) H_pmz_new += \ sparse.kron(block_ops['z'], site_ops['+']) + \ sparse.kron(block_ops['z'], site_ops['-']) + \ sparse.kron(block_ops['+'], site_ops['z']) + \ sparse.kron(block_ops['-'], site_ops['z']) return self.J_pm * H_pm_new + self.J_z * H_z_new + \ self.J_ppmm * H_ppmm_new + self.J_pmz * H_pmz_new ########################################################## ### FFI wrapper code for functions implemented in Rust ### ########################################################## ffi = FFI() modpath = os.path.dirname(__file__) rootdir = os.path.split(modpath)[0] rust_dir = os.path.join(rootdir, "rust", "triangular_lattice_ext") # Only define the following functions if the shared object is compiled or else # Python is going to throw exceptions on import. # The header file only exists if the Rust shared object is compiled. if os.path.exists(os.path.join(rust_dir, "triangular_lattice_ext.h")): with open(os.path.join(rust_dir, "triangular_lattice_ext.h")) as header: # remove directives from header file since cffi can't process directives yet h = [line for line in header.readlines() if not line[0] == "#"] ffi.cdef(''.join(h)) _lib = ffi.dlopen(os.path.join(rust_dir, "target", "release", "libtriangular_lattice_ext.so")) class CoordMatrix: """A class that encapsulates the matrix and provides methods that would help memoery management across the FFI boundary """ def __init__(self, mat): """Initializer Parameters -------------------- mat: CoordMatrix """ self.__obj = mat # the pointer to the pointers to the arrays self.data = np.frombuffer(ffi.buffer(mat.data.ptr, mat.data.len * 16), np.complex128) self.col = np.frombuffer(ffi.buffer(mat.col.ptr, mat.col.len * 4), np.int32) self.row = np.frombuffer(ffi.buffer(mat.row.ptr, mat.row.len * 4), np.int32) self.ncols = mat.ncols self.nrows = mat.nrows def __enter__(self): """For use with context manager""" return self def __exit__(self, exc_type, exc_value, traceback): """For use with context manager""" self.data = None self.col = None self.row = None _lib.request_free(self.__obj) # deallocates Rust object self.__obj = None def to_csc(self): """Returns a CSC matrix""" return sparse.csc_matrix((self.data, (self.col, self.row)), shape=(self.nrows, self.ncols)) def to_csr(self): """Returns a CSR matrix""" return sparse.csr_matrix((self.data, (self.col, self.row)), shape=(self.nrows, self.ncols)) def h_ss_z_consv_k(Nx, Ny, kx, ky, l): """construct the H_z matrix in the given momentum configuration Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone l: int Returns -------------------- H: scipy.sparse.csr_matrix """ mat = _lib.k_h_ss_z(Nx, Ny, kx, ky, l) with CoordMatrix(mat) as coordmat: H = coordmat.to_csr() return H def h_ss_xy_consv_k(Nx, Ny, kx, ky, l): """construct the H_xy matrix in the given momentum configuration Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone l: int Returns -------------------- H: scipy.sparse.csr_matrix """ mat = _lib.k_h_ss_xy(Nx, Ny, kx, ky, l) with CoordMatrix(mat) as coordmat: H = coordmat.to_csr() return H def h_ss_ppmm_consv_k(Nx, Ny, kx, ky, l): """construct the H_ppmm matrix in the given momentum configuration Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone l: int Returns -------------------- H: scipy.sparse.csr_matrix """ mat = _lib.k_h_ss_ppmm(Nx, Ny, kx, ky, l) with CoordMatrix(mat) as coordmat: H = coordmat.to_csr() return H def h_ss_pmz_consv_k(Nx, Ny, kx, ky, l): """construct the H_pmz matrix in the given momentum configuration Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone l: int Returns -------------------- H: scipy.sparse.csr_matrix """ mat = _lib.k_h_ss_pmz(Nx, Ny, kx, ky, l) with CoordMatrix(mat) as coordmat: H = coordmat.to_csr() return H def h_sss_chi_consv_k(Nx, Ny, kx, ky): """construct the H_chi matrix in the given momentum configuration Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone Returns -------------------- H: scipy.sparse.csr_matrix """ mat = _lib.k_h_sss_chi(Nx, Ny, kx, ky) with CoordMatrix(mat) as coordmat: H = coordmat.to_csr() return H def h_ss_z_consv_k_s(Nx, Ny, kx, ky, nup, l): """construct the H_z matrix in the given momentum configuration Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone nup: int the total number of sites with a spin-up l: int Returns -------------------- H: scipy.sparse.csr_matrix """ mat = _lib.ks_h_ss_z(Nx, Ny, kx, ky, nup, l) with CoordMatrix(mat) as coordmat: H = coordmat.to_csr() return H def h_ss_xy_consv_k_s(Nx, Ny, kx, ky, nup, l): """construct the H_xy matrix in the given momentum configuration Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone nup: int the total number of sites with a spin-up l: int Returns -------------------- H: scipy.sparse.csr_matrix """ mat = _lib.ks_h_ss_xy(Nx, Ny, kx, ky, nup, l) with CoordMatrix(mat) as coordmat: H = coordmat.to_csr() return H def h_sss_chi_consv_k_s(Nx, Ny, kx, ky, nup): """construct the H_chi matrix in the given momentum configuration Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone nup: int Returns -------------------- H: scipy.sparse.csr_matrix """ mat = _lib.ks_h_sss_chi(Nx, Ny, kx, ky, nup) with CoordMatrix(mat) as coordmat: H = coordmat.to_csr() return H def ss_z_consv_k(Nx, Ny, kx, ky, l): """construct the Σsz_i * sz_j operators with the given separation with translational symmetry taken into account Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Ny / 2π in a [0, 2π) Brillouin zone l: int the separation between sites: |i - j| Returns -------------------- ss_z: scipy.sparse.csr_matrix """ mat = _lib.k_ss_z(Nx, Ny, kx, ky, l) with CoordMatrix(mat) as coordmat: op = coordmat.to_csr() return op def ss_xy_consv_k(Nx, Ny, kx, ky, l): """construct the Σ(sx_i * sx_j + sy_i * sy_j) operators with the given separation with translational symmetry taken into account Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Ny / 2π in a [0, 2π) Brillouin zone l: int the separation between sites: |i - j| Returns -------------------- ss_xy: scipy.sparse.csr_matrix """ mat = _lib.k_ss_xy(Nx, Ny, kx, ky, l) with CoordMatrix(mat) as coordmat: op = coordmat.to_csr() return op def ss_z_consv_k_s(Nx, Ny, kx, ky, nup, l): """construct the Σsz_i * sz_j operators with the given separation with translational symmetry taken into account Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Ny / 2π in a [0, 2π) Brillouin zone nup: int the total number of sites with a spin-up l: int the separation between sites: |i - j| Returns -------------------- ss_z: scipy.sparse.csr_matrix """ mat = _lib.ks_ss_z(Nx, Ny, kx, ky, nup, l) with CoordMatrix(mat) as coordmat: op = coordmat.to_csr() return op def ss_xy_consv_k_s(Nx, Ny, kx, ky, nup, l): """construct the Σ(sx_i * sx_j + sy_i * sy_j) operators with the given separation with translational symmetry taken into account Parameters -------------------- Nx: int lattice length in the x-direction Ny: int lattice length in the y-direction kx: int the x-component of lattice momentum * Nx / 2π in a [0, 2π) Brillouin zone ky: int the y-component of lattice momentum * Ny / 2π in a [0, 2π) Brillouin zone nup: int the total number of sites with a spin-up l: int the separation between sites: |i - j| Returns -------------------- ss_xy: scipy.sparse.csr_matrix """ mat = _lib.ks_ss_xy(Nx, Ny, kx, ky, nup, l) with CoordMatrix(mat) as coordmat: op = coordmat.to_csr() return op def min_necessary_ks(Nx, Ny): """Returns the momentum that we absolutely need to compute Parameters -------------------- Nx: int Ny: int Returns -------------------- list of ints """ ks = [] arrs = [] for kx in range(Nx): for ky in range(Ny): arr = np.outer(np.exp(2j * np.pi * kx * np.arange(Nx) / Nx), np.exp(2j * np.pi * ky * np.arange(Ny) / Ny)) for arr0 in arrs: if np.allclose(arr0, arr) or np.allclose(arr0, arr.conjugate()): break else: ks.append((kx, ky)) arrs.append(arr) return ks
32.411846
88
0.537164
3,109
23,531
3.900289
0.116115
0.012865
0.011875
0.015834
0.614877
0.578921
0.541069
0.521854
0.507834
0.492495
0
0.013106
0.344992
23,531
725
89
32.456552
0.773633
0.33662
0
0.312694
0
0
0.012049
0.00738
0
0
0
0.001379
0
1
0.133127
false
0
0.021672
0.003096
0.287926
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d990ddde01350e477f961c78fce1ed2af6c8f78a
16,528
py
Python
stgelpDL/dev/edfiles.py
dmitryv56/stgelpDL
a3dbe9f1a4ff19586dfdfac01748634b47389a6e
[ "MIT" ]
null
null
null
stgelpDL/dev/edfiles.py
dmitryv56/stgelpDL
a3dbe9f1a4ff19586dfdfac01748634b47389a6e
[ "MIT" ]
null
null
null
stgelpDL/dev/edfiles.py
dmitryv56/stgelpDL
a3dbe9f1a4ff19586dfdfac01748634b47389a6e
[ "MIT" ]
null
null
null
import pandas as pd import copy from pathlib import Path import pandas as pd import numpy as np import math from datetime import datetime,timedelta import matplotlib.pyplot as plt from predictor.utility import msg2log def Forcast_imbalance_edit(): ds = pd.read_csv("~/LaLaguna/stgelpDL/dataLaLaguna/ElHiero_24092020_27102020.csv") src_col_name = "Forcasting" src1_col_name = "Real_demand" dst_col_name = "FrcImbalance" ds[dst_col_name] =[round(ds[src_col_name][i]-ds[src1_col_name][i],2) for i in range(len(ds)) ] ds.to_csv("~/LaLaguna/stgelpDL/dataLaLaguna/ElHiero_24092020_27102020_CommonAnalyze.csv", index=False) return def WindTurbine_edit(): ds = pd.read_csv("~/LaLaguna/stgelpDL/dataLaLaguna/ElHiero_24092020_20102020_WindGenPower.csv") aux_col_name = "Programmed_demand" dest_col_name="Real_demand" src_col_name="WindGen_Power_" ds[aux_col_name]=[ 0.0 for i in range(len(ds[aux_col_name]))] ds[dest_col_name]=ds[src_col_name] ds.to_csv("~/LaLaguna/stgelpDL/dataLaLaguna/editedElHiero_24092020_20102020_WindGenPower.csv", index=False) return def profivateHouse_edit(): ds = pd.read_csv("~/LaLaguna/stgelpDL/dataLaLaguna/__PrivateHouseElectricityConsumption_21012020.csv") col_name='lasts' dt_col_name='Date Time' aux_col_name="Programmed_demand" data_col_name="Demand" v=ds[col_name].values for i in range (len(ds[col_name].values)): a=v[i].split('-') v[i]='T'+a[0]+":00.000+02:00" ds[col_name]=copy.copy(v) for i in range(len(ds[col_name])): ds[dt_col_name][i] =ds[dt_col_name][i] + v[i] ds1 =ds.drop([col_name], axis=1) add_col=[] for i in range(len(ds[dt_col_name])): add_col.append(ds[data_col_name].values[i] * 2 ) ds1[aux_col_name]=add_col ds1.to_csv("~/LaLaguna/stgelpDL/dataLaLaguna/PrivateHouseElectricityConsumption_21012020.csv", index=False) pass def powerSolarPlant_edit(): # ds = pd.read_csv("~/LaLaguna/stgelpDL/dataLaLaguna/__PowerGenOfSolarPlant_21012020.csv") ds = pd.read_csv("~/LaLaguna/stgelpDL/dataLaLaguna/__SolarPlantPowerGen_21012020.csv") # col_name = 'lasts' dt_col_name = 'Date Time' aux_col_name = "Programmed_demand" data_col_name = "PowerGen" v = ds[dt_col_name].values for i in range(len(ds[dt_col_name].values)): a = v[i].split(' ') b=a[0].split('.') if len(a[1])<5: a[1]='0'+a[1] v[i]='2020-'+b[1]+"-"+b[0]+'T'+a[1]+':00.000+02:00' ds[dt_col_name] = copy.copy(v) # ds1 = ds.drop([col_name], axis=1) add_col = [] for i in range(len(ds[dt_col_name])): add_col.append(ds[data_col_name].values[i] * 2) ds[aux_col_name] = add_col # ds1.to_csv("~/LaLaguna/stgelpDL/dataLaLaguna/PowerGenOfSolarPlant_21012020.csv", index=False) ds.to_csv("~/LaLaguna/stgelpDL/dataLaLaguna/SolarPlantPowerGen_21012020_21012020.csv", index=False) pass def powerSolarPlant_Imbalance(): # ds = pd.read_csv("~/LaLaguna/stgelpDL/dataLaLaguna/__PowerGenOfSolarPlant_21012020.csv") ds = pd.read_csv("~/LaLaguna/stgelpDL/dataLaLaguna/SolarPlantPowerGen_21012020.csv") # col_name = 'lasts' dt_col_name = 'Date Time' aux_col_name = "Programmed_demand" data_col_name = "PowerGen" ds["Imbalance"] = [ds[aux_col_name].values[i]-ds[data_col_name].values[i] for i in range(len(ds)) ] ds.to_csv("~/LaLaguna/stgelpDL/dataLaLaguna/SolarPlantPowerGen_21012020.csv", index=False) pass def powerElHiero_edit(): ds = pd.read_csv("~/LaLaguna/stgelpDL/dataLaLaguna/_ElHiero_24092020_20102020_additionalData.csv") dt_col_name = 'Date Time' aux_col_name = "Programmed_demand" data_col_name = "PowerGen" v = ds[dt_col_name].values for i in range(len(ds[dt_col_name].values)): a = v[i].split(' ') b = a[0].split('.') if len(a[1]) < 5: a[1] = '0' + a[1] v[i] = '2020-' + b[1] + "-" + b[0] + 'T' + a[1] + ':00.000+02:00' ds[dt_col_name] = copy.copy(v) ds.to_csv("~/LaLaguna/stgelpDL/dataLaLaguna/ElHiero_24092020_20102020_additionalData.csv", index=False) pass def datosElHiero_edit(): # ds = pd.read_csv("~/LaLaguna/stgelpDL/dataLaLaguna/__PowerGenOfSolarPlant_21012020.csv") ds = pd.read_csv("~/LaLaguna/stgelpDL/dataLaLaguna/Datos_de_El_Hierro_2016.csv") # col_name = 'lasts' dt_col_name = 'Date Time' v = ds[dt_col_name].values for i in range(len(ds[dt_col_name].values)): a = v[i].split(' ') #29-12-2016 3:00:00 b=a[0].split('-') # dd mm year a0new="{}-{}-{}".format(b[2],b[1],b[0]) c=a[1].split(':') #h mm ss if len(c[0])<2: c[0]='0{}'.format(c[0]) a1new='{}:{}:{}.000+00:00'.format(c[0],c[1],c[2]) v[i]="{}T{}".format(a0new,a1new) ds[dt_col_name] = copy.copy(v) ds.to_csv("~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016.", index=False) pass def datosElHiero_PerDay(): src_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016.csv" dst_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016_Days.csv" ds = pd.read_csv(src_csv) # col_name = 'lasts' dt_col_name = 'Date Time' data_col_name = 'Real_demand' v=ds[data_col_name].values n_v=len(v) col_names=["{}:{}".format(int(i/6), (i%6)*10) for i in range(144)] v_dict = {col_names[i]:[] for i in range(144)} # d_dict = {"Date Time": [ds[dt_col_name][i] for i in range(0, n_v, 144)]} # d_dict={"Date": [pd.to_datetime(ds[dt_col_name][i],dayfirst=True).date() for i in range(0,n_v,144)]} d_dict = {"Date": [pd.to_datetime(ds[dt_col_name][i], dayfirst=True).date().strftime('%Y-%m-%d') for i in range(0, n_v, 144)]} for i in range(n_v): v_dict[col_names[i%144]].append(v[i]) # last list 365-size, we add v[0] d={**d_dict,**v_dict} ds1=pd.DataFrame(d) ds1.to_csv(dst_csv) return def datosElHiero_PerTimeStamps(): src_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016.csv" dst_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016_TimeStamps.csv" ds = pd.read_csv(src_csv) # col_name = 'lasts' dt_col_name = 'Date Time' data_col_name = 'Real_demand' v=ds[data_col_name].values n_v=len(v) col_names= [pd.to_datetime(ds[dt_col_name][i], dayfirst=True).date().strftime('%Y-%m-%d') for i in range(0, n_v, 144)] row_names=["{}:{}".format(int(i/6), (i%6)*10) for i in range(144)] v_dict={} # v_dict = {item:[] for item in col_names} # d_dict = {"Date Time": [ds[dt_col_name][i] for i in range(0, n_v, 144)]} # d_dict={"Date": [pd.to_datetime(ds[dt_col_name][i],dayfirst=True).date() for i in range(0,n_v,144)]} d_dict = {"Date": [pd.to_datetime(ds[dt_col_name][i], dayfirst=True).date().strftime('%Y-%m-%d') for i in range(0, n_v, 144)]} d_dict = {"Timestamp": row_names} n_start=0 n_series=144 # obsefvation points n_features=366 # days for icol in col_names: v_dict[icol]=v[n_start:n_start+n_series].tolist() n_start=n_start+n_series # last list 365-size, we add v[0] d={**d_dict,**v_dict} ds1=pd.DataFrame(d) ds1.to_csv(dst_csv) return def datosElHiero_PerTimeStamps(): dst_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016-Est.csv" src_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016_TimeStamps.csv" ds = pd.read_csv(src_csv) # col_name = 'lasts' dt_col_name = 'Timestamp' d_dst={} vts=ds['Timestamp'].values.tolist() vts.append('ave') vts.append('std') vts.append('min') vts.append('max') d_dst["RowName"]=vts for col in ds.columns: if 'Unnamed' in col or 'Timestamp' in col: continue v=ds[col].values.tolist() a=np.array(v) ave=a.mean() std=a.std() minv=a.min() maxv=a.max() v.append(round(ave,3)) v.append(round(std,3)) v.append(round(minv,2)) v.append(round(maxv,2)) d_dst[col]=v ds1 = pd.DataFrame(d_dst) n_ds1=len(ds1) ave = [] std = [] minv = [] maxv = [] for i in range(n_ds1): v=[] for col in ds1.columns[1:]: v.append(ds1[col][i]) a=np.array(v) ave.append(round(a.mean(),3)) std.append(round(a.std(),3)) minv.append(round(a.min(),2)) maxv.append(round(a.max(),2)) ds1['ave']=ave ds1['std'] = std ds1['min'] = minv ds1['max'] = maxv ds1.to_csv(dst_csv) return """ transform time series (feature in source dataset) matrix Nrows * Mcols. The source dataset must comprise a timestamp feature(column) named 'dt_col_name' or index column. The 'data_col_name'- feature must be a time series (TS) are ordered by index ot timestamp feature('dt_col_name') , that is, the observation must be equidistant and without gaps. Additional, the beginning timestamp must be 00:00:00 (or 0 for index). The 'period' and 'direction' determine the formation of the matrix. If the 'direction' is along the 'X'- axis, then the segments of the TS corresponding to the 'period' are the rows of the matrix. Column names are derived from observation times within a period, for example, "00: 00,00: 10, ..., 23:50" to 10 minutes discretization and a period of 1 day. If the direction is along 'Y'-axis, then the segment of the TS corresponding to the 'period' are the column of matrix. The column names are derived from the period in the timestamp, i.g. data string if the period is 1 day like as '2016-03-27', and row names are derived from observations within period, for example, "00:00,...,23:50". """ def ts2matrix(source_csv:str=None, dest_csv:str=None, dt_col_name:str="Date Time", data_col_name:str='Real_demand', outRowIndex="rowNames", discret:int=10,period:object=None, direction:str='x', title:str="", f:object=None): if source_csv is None or not Path(source_csv).exists() : msg="The source dataset path is invalid: {}".format(source_csv) msg2log(None,msg,f) return None ds=pd.read_csv(source_csv) if dt_col_name not in ds.columns or data_col_name not in ds.columns: msg = "{} or {} not found in the dataset {}".format(dt_col_name,data_col_name, source_csv) msg2log(None, msg, f) return None folder_csv=Path(source_csv).parent dest_csv = Path(folder_csv / "{}_{}".format(title,data_col_name)).with_suffix(".csv") dest_se_csv = Path(folder_csv / "{}_{}_StatEst".format(title, data_col_name)).with_suffix(".csv") if direction=="X" or direction == "x": dsMatrix = ts2matrix_X(ds=ds, dt_col_name=dt_col_name, data_col_name=data_col_name,outRowIndex=outRowIndex, discret=discret, period=period, f=f) elif direction=="Y" or direction == "y": dsMatrix = ts2matrix_Y(ds=ds, dt_col_name=dt_col_name, data_col_name=data_col_name, outRowIndex=outRowIndex, discret=discret, period=period, f=f) else: msg = "{} invalid direction ".format(direction) msg2log(None, msg, f) return None dsMatrix.to_csv(dest_csv) dsMatrixStatEst=ts2matrix_statest(ds=dsMatrix, rowIndexName=outRowIndex, f=f) dsMatrixStatEst.to_csv(dest_se_csv) return def ts2matrix_X(ds:pd.DataFrame=None, dt_col_name:str='Date Time',data_col_name:str='Real_demand', outRowIndex:str="rowNames", discret:int=10,period:int=144, f:object=None)->pd.DataFrame: # src_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016.csv" # dst_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016_Days.csv" # ds = pd.read_csv(src_csv) # # col_name = 'lasts' # dt_col_name = 'Date Time' # data_col_name = 'Real_demand' h_period_sr=60/discret # hour in sample resolution, 6 d_period_sr = period # day period in sample resolution, 144 v=ds[data_col_name].values n_v=len(v) if n_v%d_period_sr!=0: msg="Time series size is {} and it is not multiply of {} period".format(n_v,d_period_sr) msg2log(None,msg,f) return None col_names = ["{}:{}".format(int(i / h_period_sr), int((i % h_period_sr) * 10)) for i in range(d_period_sr)] v_dict = {col_names[i]:[] for i in range(d_period_sr)} d_dict = {outRowIndex: [pd.to_datetime(ds[dt_col_name][i], dayfirst=True).date().strftime('%Y-%m-%d') \ for i in range(0, n_v, d_period_sr)]} for i in range(n_v): v_dict[col_names[i%144]].append(v[i]) d={**d_dict,**v_dict} ds1=pd.DataFrame(d) # ds1.to_csv(dst_csv) return ds1 def ts2matrix_Y(ds:pd.DataFrame=None, dt_col_name:str='Date Time',data_col_name:str='Real_demand', outRowIndex:str="rowNames", discret:int=10,period:int=144, f:object=None)->pd.DataFrame: # src_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016.csv" # dst_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016_TimeStamps.csv" # ds = pd.read_csv(src_csv) # # col_name = 'lasts' # dt_col_name = 'Date Time' # data_col_name = 'Real_demand' # # v=ds[data_col_name].values n_v=len(v) h_period_sr = 60 / discret # hour in sample resolution, 6 d_period_sr = period # day period in sample resolution, 144 v = ds[data_col_name].values n_v = len(v) if n_v % d_period_sr != 0: msg = "Time series size is {} and it is not multiply of {} period".format(n_v, d_period_sr) msg2log(None, msg, f) return None col_names= [pd.to_datetime(ds[dt_col_name][i], dayfirst=True).date().strftime('%Y-%m-%d') for i in range(0, n_v, d_period_sr)] row_names=["{}:{}".format(int(i/h_period_sr), int((i%h_period_sr)*10)) for i in range(d_period_sr)] v_dict={} d_dict = {outRowIndex: row_names} n_start=0 n_series=d_period_sr # obsefvation points n_features=366 # days for icol in col_names: v_dict[icol]=v[n_start:n_start+n_series].tolist() n_start=n_start+n_series d={**d_dict,**v_dict} ds1=pd.DataFrame(d) # ds1.to_csv(dst_csv) return ds1 def ts2matrix_statest(ds:pd.DataFrame=None,rowIndexName:str="rowNames",f:object=None): # dst_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016-Est.csv" # src_csv="~/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016_TimeStamps.csv" # ds = pd.read_csv(src_csv) # col_name = 'lasts' dt_col_name = rowIndexName d_dst={} vts=ds[rowIndexName].values.tolist() vts.append('ave') vts.append('std') vts.append('min') vts.append('max') d_dst[rowIndexName]=vts for col in ds.columns: if 'Unnamed' in col or rowIndexName in col: continue v=ds[col].values.tolist() a=np.array(v) ave=a.mean() std=a.std() minv=a.min() maxv=a.max() v.append(round(ave,3)) v.append(round(std,3)) v.append(round(minv,2)) v.append(round(maxv,2)) d_dst[col]=v ds1 = pd.DataFrame(d_dst) n_ds1=len(ds1) ave = [] std = [] minv = [] maxv = [] for i in range(n_ds1): v=[] for col in ds1.columns[1:]: v.append(ds1[col][i]) a=np.array(v) ave.append(round(a.mean(),3)) std.append(round(a.std(),3)) minv.append(round(a.min(),2)) maxv.append(round(a.max(),2)) ds1['ave']=ave ds1['std'] = std ds1['min'] = minv ds1['max'] = maxv # ds1.to_csv(dst_csv) return ds1 if __name__=="__main__": # privateHouse_edit() # powerSolarPlant_edit() # powerElHiero_edit() #WindTurbine_edit() # Forcast_imbalance_edit() # powerSolarPlant_Imbalance() # powerSolarPlant_analysis() # datosElHiero_edit() # datosElHiero_PerDay() # datosElHiero_PerTimeStamps() # datosElHiero_PerTimeStamps() src_csv = "/home/dmitryv/LaLaguna/stgelpDL/dataLaLaguna/Data_ElHierro_2016.csv" with open("loglog.log",'w+') as ff: ts2matrix(source_csv=src_csv, dt_col_name = "Date Time", data_col_name= 'Real_demand', outRowIndex = "rowNames", discret = 10, period=144, direction = 'x', title = "X_direction", f=ff) ts2matrix(source_csv=src_csv, dt_col_name="Date Time", data_col_name='Real_demand', outRowIndex="rowNames", discret=10, period=144, direction='y', title="Y_direction", f=ff) pass
35.697624
130
0.647749
2,560
16,528
3.960938
0.101563
0.077318
0.040828
0.091716
0.761736
0.723274
0.706016
0.672781
0.641913
0.619034
0
0.042902
0.201779
16,528
462
131
35.774892
0.725688
0.131534
0
0.647619
0
0
0.182067
0.107751
0
0
0
0
0
1
0.044444
false
0.019048
0.028571
0
0.11746
0
0
0
0
null
0
0
0
0
1
1
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
d9913fd01e1b721da362c3a1ba14143f873c7a20
5,450
py
Python
knoema/source_data/get_indic_id.py
zmmyc/ksh
5869908714ea87a297a8fc19ecafd7d3cf15e889
[ "MIT" ]
1
2022-03-30T06:50:42.000Z
2022-03-30T06:50:42.000Z
knoema/source_data/get_indic_id.py
zmmyc/ksh
5869908714ea87a297a8fc19ecafd7d3cf15e889
[ "MIT" ]
null
null
null
knoema/source_data/get_indic_id.py
zmmyc/ksh
5869908714ea87a297a8fc19ecafd7d3cf15e889
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import requests, json from bs4 import BeautifulSoup from mspider.spider import MSpider class Get_indic_idSpider(MSpider): def __init__(self): self.name = "get_count_id" self.indics = ['GDP', 'GDP-based-on-PPP', 'Real-GDP-growth', 'GDP-per-capita', 'GDP-per-capita-based-on-PPP', 'Inflation-rate', 'Unemployment-rate', 'Current-account-balance', 'Current-account-balance-as-a-share-of-GDP', 'Government-gross-debt-as-a-share-of-GDP', 'Poverty-rate', 'International-reserves', 'Primary-energy-production', 'Primary-energy-consumption', 'Energy-intensity', 'Energy-imports', 'Alternative-and-nuclear-energy-use', 'Fossil-fuel-energy-consumption', 'Diesel-price', 'Gasoline-price', 'Air-transport-freight', 'Number-of-air-passengers-carried', 'Volume-of-goods-transported-by-railways', 'Number-of-passengers-carried-by-railways', 'Length-of-rail-lines', 'Road-density', 'Share-of-the-Internet-users', 'Share-of-households-with-Internet', 'Number-of-mobile-cellular-subscriptions', 'Military-expenditure', 'Military-expenditure-as-a-share-of-GDP', 'Arms-exports', 'Arms-imports', 'Exports', 'Goods-exports', 'Service-exports', 'Merchandise-exports', 'Food-exports', 'Fuel-exports', 'High-technology-exports', 'High-technology-exports-as-a-share-of-exports', 'Imports', 'Goods-imports', 'Service-imports', 'Merchandise-imports', 'Food-imports', 'Fuel-imports', 'Number-of-arrivals', 'Number-of-departures', 'Tourism-expenditures', 'Tourism-expenditures-as-a-share-of-imports', 'Expenditures-for-passenger-transport-items', 'Expenditures-for-travel-items', 'Tourism-receipts', 'Tourism-receipts-as-a-share-of-exports', 'Receipts-for-passenger-transport-items', 'Receipts-for-travel-items', 'CO2-emissions', 'CO2-emissions-per-capita', 'CO2-emissions-intensity', 'Quantity-of-municipal-waste-collected', 'Human-development-index', 'Ease-of-doing-business-index', 'Global-competitiveness-index', 'Corruption-perceptions-index', 'Index-of-economic-freedom', 'Press-freedom-index', 'Political-rights-index', 'Civil-liberties-index', 'Property-rights-index', 'Prosperity-index', 'Happiness', 'Population', 'Population-growth-rate', 'Population-density', 'Urban-population', 'Birth-rate', 'Death-rate', 'Fertility-rate', 'Population-aged-0-14-years', 'Population-aged-15-64-years', 'Population-aged-65-years-and-above', 'Female-population', 'Employment-to-population-ratio', 'Land-area', 'Agricultural-land-area', 'Agricultural-land-as-a-share-of-land-area', 'Forest-area-as-a-share-of-land-area', 'Agriculture-value-added-per-worker', 'Food-production-index', 'Livestock-production-index', 'Crop-production-index', 'Cereal-production', 'Cereal-yield', 'Land-under-cereal-production', 'Number-of-tractors', 'Fertilizer-consumption', 'Neonatal-mortality-rate', 'Infant-mortality-rate', 'Child-mortality-rate', 'Maternal-mortality-ratio', 'Life-expectancy', 'Health-expenditure-as-a-share-of-GDP', 'Health-expenditure-per-capita', 'HIV-prevalence', 'Incidence-of-tuberculosis', 'Female-obesity-prevalence', 'Male-obesity-prevalence', 'Education-expenditure', 'Primary-enrollment', 'Duration-of-primary-education', 'Duration-of-secondary-education', 'Pupil-teacher-ratio-in-primary-education', 'Pupil-teacher-ratio-in-secondary-education', 'Adult-literacy-rate', 'Youth-literacy-rate', 'Homicide-rate', 'Number-of-homicides', 'Number-of-homicides-by-firearm', 'Share-of-homicides-by-firearm', 'Homicides-by-firearm-rate', 'Assault-rate', 'Kidnapping-rate', 'Robbery-rate', 'Rape-rate', 'Burglary-rate', 'Private-car-theft-rate', 'Motor-vehicle-theft-rate', 'Burglary-and-housebreaking-rate', 'Poverty-rate-at-dollar19-a-day', 'Poverty-rate-at-dollar32-a-day', 'Poverty-rate-at-national-poverty-line', 'Rural-poverty-rate', 'Urban-poverty-rate', 'GINI-index', 'Income-share-held-by-lowest-10percent', 'Income-share-held-by-highest-10percent', 'Prevalence-of-undernourishment', 'Number-of-undernourished-people', 'Food-deficit', 'Dietary-energy-supply-adequacy', 'Precipitation', 'Precipitation-volume', 'Rainfall-index', 'Volume-of-groundwater-produced', 'Volume-of-surface-water-produced', 'Internal-renewable-water-resources-per-capita', 'Renewable-water-resources-per-capita', 'Dependency-ratio', 'Freshwater-withdrawals', 'Water-productivity', 'RandD-expenditure', 'Number-of-researchers-in-RandD', 'Number-of-technicians-in-RandD', 'Number-of-scientific-journal-articles', 'Number-of-patent-applications'] self.urls = ['https://knoema.com/atlas/United-States-of-America/%s' %(indic) for indic in self.indics] self.source = list(zip(self.indics, self.urls)) self.file = open('./indicators.json', 'w', encoding='utf-8') super(Get_indic_idSpider, self).__init__(self.basic_func, self.source) def basic_func(self, index, src_item): indic, url = src_item html = self.sess.get(url).text soup = BeautifulSoup(html, 'lxml') payload_data = json.loads(soup.find('input', {'name': 'datadescriptor'}).attrs['value']) item = {} item['id'] = str(payload_data['Stub'][0]['Members'][0]) item['name'] = indic # print(item) self.save_item(item) def save_item(self, item): content = json.dumps(item, ensure_ascii=False) + '\n' self.file.write(content) self.file.flush() if __name__=="__main__": spider = Get_indic_idSpider() # spider.test() spider.crawl() spider.file.close()
147.297297
4,232
0.728807
697
5,450
5.651363
0.420373
0.026403
0.018279
0.022848
0.075654
0.021325
0
0
0
0
0
0.004984
0.079633
5,450
37
4,233
147.297297
0.780303
0.008624
0
0
0
0
0.691111
0.476111
0
0
0
0
0
1
0.107143
false
0.035714
0.142857
0
0.285714
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
1
0
0
0
0
0
0
1
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
d99172d582203a6c9d89885e87dc7fdf395331ed
2,556
py
Python
Programming Assignment 3/min Cut.py
TheRevanchist/Design-and-Analysis-of-Algorithms-Part-1
e41e3a1117258fb6f635c3c734675215dbce5263
[ "MIT" ]
1
2020-08-02T12:01:56.000Z
2020-08-02T12:01:56.000Z
Programming Assignment 3/min Cut.py
TheRevanchist/Design-and-Analysis-of-Algorithms-Part-1
e41e3a1117258fb6f635c3c734675215dbce5263
[ "MIT" ]
null
null
null
Programming Assignment 3/min Cut.py
TheRevanchist/Design-and-Analysis-of-Algorithms-Part-1
e41e3a1117258fb6f635c3c734675215dbce5263
[ "MIT" ]
null
null
null
from random import choice from copy import deepcopy def minCut(G): # the function which randomly chooses the edges and fuses the nodes which are linked with that edge # input: the graph G, represented by a dictionary # output: the min cut # while the graph has more than two nodes, randomly choose two nodes and fuse them while len(G) > 2: vertex1 = choice(list(G.keys())) vertex2 = choice(G[vertex1]) fuse(vertex1, vertex2, G) # pop the second element, return the length of it which is the min cut return len(G.popitem()[1]) def fuse(node1, node2, G): # the function which fuses nodes based on the randomly chosen edge # it also removes the self edges # input: node1 - the first node # node2 - the second node # G - the graph # add the edges of node2 to node1 G[node1].extend(G[node2]) # look at all edges of node2, then go to the nodes which are linked with those # edges and change the direction from node2 to node1 for edge in G[node2]: lst = G[edge] for i in range(0, len(lst)): if lst[i] == node2: lst[i] = node1 # remove self-loops from node1 while node1 in G[node1]: G[node1].remove(node1) # remove node2 from the graph del G[node2] # read the file lista = "D:/Workbench/Online Courses/Design and Analysis of Algorithms, Part 1/Programming Assignment 3/file.txt" f = open(lista, 'r') line_list = f.readlines() G = {int(line.split()[0]): [int(val) for val in line.split()[1:] if val] for line in line_list if line} # initialize the value of mincut to a very large number mincut = 10000000000000 # iterate a thousand times with different random choices to get the min cut value # In theory the number of iterations should be n^2logn, which in our case would be 305600 # On a decent computer, it would take days to run it, so instead I chose to run a thousand iterations # The probability of getting the wrong min cut is bigger than 1/200, but it still should be small enough # Obviously, the theoretical guarantee here is lacking, but at worst case it should give us a good min cut. for i in range(1000): curr = minCut(deepcopy(G)) if curr < mincut: mincut = curr # print the best value from mincut print str(mincut)
40.571429
115
0.618153
381
2,556
4.141732
0.427822
0.019011
0.01711
0.021546
0.032953
0.032953
0
0
0
0
0
0.035388
0.314554
2,556
63
116
40.571429
0.865297
0.521127
0
0
0
0.035714
0.091954
0
0
0
0
0
0
0
null
null
0
0.071429
null
null
0.035714
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
1
d99179f5f0c295d6288591b72b99cc96a11e545c
5,223
py
Python
python/tvm/tensor_graph/core2/nn/functional/convolution.py
QinHan-Erin/AMOS
634bf48edf4015e4a69a8c32d49b96bce2b5f16f
[ "Apache-2.0" ]
22
2022-03-18T07:29:31.000Z
2022-03-23T14:54:32.000Z
python/tvm/tensor_graph/core2/nn/functional/convolution.py
QinHan-Erin/AMOS
634bf48edf4015e4a69a8c32d49b96bce2b5f16f
[ "Apache-2.0" ]
null
null
null
python/tvm/tensor_graph/core2/nn/functional/convolution.py
QinHan-Erin/AMOS
634bf48edf4015e4a69a8c32d49b96bce2b5f16f
[ "Apache-2.0" ]
2
2022-03-18T08:26:34.000Z
2022-03-20T06:02:48.000Z
import tvm from tvm.tensor_graph.core2.graph.concrete import Compute, Tensor from .padding import zero_pad2d ###################################################################### # for functional, all states are inputs, data from inside functionals # can only be constants ###################################################################### def conv2d_nchw(inputs, weight, bias=None, stride=1, padding=0, dilation=1, groups=1, output_dtype="float32", requires_grad=False): """Convolution 2d NCHW layout Args: ----------------------------- inputs : Tensor shape [batch, channel, height, width] weight : Tensor shape [out_channel, channel // groups, kernel_height, kernel_width] bias : (optional:None) Tensor shape [out_channel] stride : (optional:1) int or tuple padding : (optional:0) int or tuple dilation: (optional:1) int groups : (optional:1) int ----------------------------- Returns: ----------------------------- Tensor shape [batch, out_channel, output_height, output_width] ----------------------------- """ batch_size, in_channel, in_h, in_w = inputs.shape out_channel, channel_per_group, k_h, k_w = weight.shape assert channel_per_group * groups == in_channel, "%d vs. %d" % (channel_per_group * groups, in_channel) out_channel_per_group = out_channel // groups assert out_channel_per_group * groups == out_channel stride = (stride, stride) if isinstance(stride, (int, tvm.tir.IntImm)) else stride padding = (padding, padding) if isinstance(padding, (int, tvm.tir.IntImm)) else padding dilation = (dilation, dilation) if isinstance(dilation, (int, tvm.tir.IntImm)) else dilation assert isinstance(stride, tuple) and len(stride) == 2 assert isinstance(padding, tuple) and len(padding) == 2 assert isinstance(dilation, tuple) and len(dilation) == 2 out_h = (in_h + 2 * padding[0] - dilation[0] * (k_h - 1) - 1) // stride[0] + 1 out_w = (in_w + 2 * padding[1] - dilation[1] * (k_w - 1) - 1) // stride[1] + 1 padded = zero_pad2d(inputs, padding=padding, output_dtype=output_dtype, requires_grad=requires_grad) conv_out_shape = (batch_size, out_channel, out_h, out_w) if bias is not None: if groups > 1: def _inner_conv2d_nchw(padded, weight, bias): def _for_spatial(b, c, h, w): def _for_reduce(rc, rw, rh): return (padded[b, c // out_channel_per_group * channel_per_group + rc, h * stride[0] + rh * dilation[0], w * stride[1] + rw * dilation[1]] * weight[c, rc, rh, rw]) + bias[c] / (channel_per_group*k_w*k_h) return _for_reduce, [channel_per_group, k_w, k_h], "sum" return _for_spatial conv_out = Compute(conv_out_shape, output_dtype, padded, weight, bias, fhint=_inner_conv2d_nchw, name="conv2d_nchw", requires_grad=requires_grad) return conv_out else: def _inner_conv2d_nchw(padded, weight, bias): def _for_spatial(b, c, h, w): def _for_reduce(rc, rw, rh): return (padded[b, rc, h * stride[0] + rh * dilation[0], w * stride[1] + rw * dilation[1]] * weight[c, rc, rh, rw]) + bias[c] / (channel_per_group*k_w*k_h) return _for_reduce, [channel_per_group, k_w, k_h], "sum" return _for_spatial conv_out = Compute(conv_out_shape, output_dtype, padded, weight, bias, fhint=_inner_conv2d_nchw, name="conv2d_nchw", requires_grad=requires_grad) return conv_out else: if groups > 1: def _inner_conv2d_nchw(padded, weight): def _for_spatial(b, c, h, w): def _for_reduce(rc, rw, rh): return (padded[b, c // out_channel_per_group * channel_per_group + rc, h * stride[0] + rh * dilation[0], w * stride[1] + rw * dilation[1]] * weight[c, rc, rh, rw]) return _for_reduce, [channel_per_group, k_w, k_h], "sum" return _for_spatial conv_out = Compute(conv_out_shape, output_dtype, padded, weight, fhint=_inner_conv2d_nchw, name="conv2d_nchw", requires_grad=requires_grad) return conv_out else: def _inner_conv2d_nchw(padded, weight): def _for_spatial(b, c, h, w): def _for_reduce(rc, rw, rh): return (padded[b, rc, h * stride[0] + rh * dilation[0], w * stride[1] + rw * dilation[1]] * weight[c, rc, rh, rw]) return _for_reduce, [channel_per_group, k_w, k_h], "sum" return _for_spatial conv_out = Compute(conv_out_shape, output_dtype, padded, weight, fhint=_inner_conv2d_nchw, name="conv2d_nchw", requires_grad=requires_grad) return conv_out
45.815789
107
0.551216
645
5,223
4.193798
0.141085
0.055453
0.083179
0.041405
0.55268
0.531608
0.509427
0.509427
0.509427
0.502773
0
0.016996
0.301551
5,223
114
108
45.815789
0.724507
0.125407
0
0.7
0
0
0.016571
0
0
0
0
0
0.071429
1
0.185714
false
0
0.042857
0.057143
0.457143
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d992c4a228423f90ecb2adf20087008d8ce1a6bc
1,352
py
Python
geneticalgorithm2/cache.py
its4avin/geneticalgorithm2
59663ce92a92a0278b5220c32a63a3a2b839d4b1
[ "MIT" ]
1
2021-04-14T18:11:34.000Z
2021-04-14T18:11:34.000Z
geneticalgorithm2/cache.py
its4avin/geneticalgorithm2
59663ce92a92a0278b5220c32a63a3a2b839d4b1
[ "MIT" ]
null
null
null
geneticalgorithm2/cache.py
its4avin/geneticalgorithm2
59663ce92a92a0278b5220c32a63a3a2b839d4b1
[ "MIT" ]
null
null
null
import numpy as np from functools import lru_cache, wraps #from fastcache import clru_cache def np_lru_cache(*args, **kwargs): """ LRU cache implementation for functions whose FIRST parameter is a numpy array forked from: https://gist.github.com/Susensio/61f4fee01150caaac1e10fc5f005eb75 """ def decorator(function): @wraps(function) def wrapper(np_array): return cached_wrapper( tuple(np_array)) @lru_cache(*args, **kwargs) #@clru_cache(*args, **kwargs) def cached_wrapper(hashable_array): return function(np.array(hashable_array)) # copy lru_cache attributes over too wrapper.cache_info = cached_wrapper.cache_info wrapper.cache_clear = cached_wrapper.cache_clear return wrapper return decorator if __name__ == '__main__': ar = np.random.randint(0, 100, (1000, 100)) f = lambda arr: np.std(arr + arr/(1 + arr**2) - arr + np.sin(arr) * np.cos(arr) + 2) def no_c(arr): return f(arr) @np_lru_cache(maxsize = 700, typed = True) def with_c(arr): return f(arr) #%time for _ in range(50): [no_c(arr) for arr in ar[np.random.rand(ar.shape[0]).argsort()]] #%time for _ in range(50): [with_c(arr) for arr in ar[np.random.rand(ar.shape[0]).argsort()]]
23.719298
97
0.633136
187
1,352
4.390374
0.395722
0.058465
0.054811
0.043849
0.17296
0.099878
0.099878
0.099878
0.099878
0.099878
0
0.039331
0.247781
1,352
56
98
24.142857
0.767945
0.323965
0
0.090909
0
0
0.00905
0
0
0
0
0
0
1
0.272727
false
0
0.090909
0.181818
0.636364
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
d993489a11a177d4b9b259fdaaa7c8fc02befc02
4,951
py
Python
tests/test_auto_scan_rnn.py
neonhuang/Paddle2ONNX
96640ccbeea1ae4e628dde20b3dbb1c3b4ef2702
[ "Apache-2.0" ]
95
2019-09-27T14:26:59.000Z
2020-12-08T01:20:28.000Z
tests/test_auto_scan_rnn.py
neonhuang/Paddle2ONNX
96640ccbeea1ae4e628dde20b3dbb1c3b4ef2702
[ "Apache-2.0" ]
51
2018-04-04T22:39:30.000Z
2019-08-28T20:19:14.000Z
tests/test_auto_scan_rnn.py
neonhuang/Paddle2ONNX
96640ccbeea1ae4e628dde20b3dbb1c3b4ef2702
[ "Apache-2.0" ]
22
2019-09-03T08:50:04.000Z
2020-12-02T11:05:42.000Z
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License" # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from auto_scan_test import OPConvertAutoScanTest, BaseNet from hypothesis import reproduce_failure import hypothesis.strategies as st import numpy as np import unittest import paddle class Net0(BaseNet): """ simple Net """ def __init__(self, config=None): super(Net0, self).__init__(config) self.lstm = paddle.nn.LSTM( input_size=self.config["input_size"], hidden_size=self.config["hidden_size"], num_layers=self.config["num_layers"], direction=self.config["direction"], time_major=self.config["time_major"]) def forward(self, inputs, prev_h, prev_c): """ forward """ y, (h, c) = self.lstm(inputs, (prev_h, prev_c)) return y class Net1(BaseNet): """ simple Net """ def __init__(self, config=None): super(Net1, self).__init__(config) self.gru = paddle.nn.GRU(input_size=self.config["input_size"], hidden_size=self.config["hidden_size"], num_layers=self.config["num_layers"], direction=self.config["direction"], time_major=self.config["time_major"]) def forward(self, inputs, prev_h): """ forward """ y, h = self.gru(inputs, prev_h) return y class TestRNNConvert0(OPConvertAutoScanTest): """ api: paddle.nn.LSTM OPset version: 7, 9, 15 """ def sample_convert_config(self, draw): input_shape = draw( st.lists( st.integers( min_value=4, max_value=10), min_size=3, max_size=3)) dtype = draw(st.sampled_from(["float32"])) hidden_size = 32 num_layers = 2 time_major = draw(st.booleans()) if time_major == True: t, b, input_size = input_shape else: b, t, input_size = input_shape direction = draw(st.sampled_from(["forward", "bidirect"])) if direction == "forward": num_directions = 1 else: num_directions = 2 prev_h_shape = [num_layers * num_directions, b, hidden_size] prev_c_shape = [num_layers * num_directions, b, hidden_size] config = { "op_names": ["rnn"], "test_data_shapes": [input_shape, prev_h_shape, prev_c_shape], "test_data_types": [[dtype], [dtype], [dtype]], "opset_version": [7, 9, 15], "input_spec_shape": [], "input_size": input_size, "hidden_size": hidden_size, "num_layers": num_layers, "direction": direction, "time_major": time_major, } models = Net0(config) return (config, models) def test(self): self.run_and_statis(max_examples=30) class TestRNNConvert1(OPConvertAutoScanTest): """ api: paddle.nn.GRU OPset version: 7, 9, 15 """ def sample_convert_config(self, draw): input_shape = draw( st.lists( st.integers( min_value=4, max_value=10), min_size=3, max_size=3)) dtype = draw(st.sampled_from(["float32"])) hidden_size = 32 num_layers = 2 time_major = draw(st.booleans()) if time_major == True: t, b, input_size = input_shape else: b, t, input_size = input_shape direction = draw(st.sampled_from(["forward", "bidirect"])) if direction == "forward": num_directions = 1 else: num_directions = 2 prev_h_shape = [num_layers * num_directions, b, hidden_size] config = { "op_names": ["rnn"], "test_data_shapes": [input_shape, prev_h_shape], "test_data_types": [[dtype], [dtype]], "opset_version": [7, 9, 15], "input_spec_shape": [], "input_size": input_size, "hidden_size": hidden_size, "num_layers": num_layers, "direction": direction, "time_major": time_major, } models = Net1(config) return (config, models) def test(self): self.run_and_statis(max_examples=30) if __name__ == "__main__": unittest.main()
29.470238
74
0.576045
585
4,951
4.622222
0.268376
0.048077
0.031065
0.028107
0.657914
0.650148
0.636834
0.636834
0.636834
0.605769
0
0.017626
0.312462
4,951
167
75
29.646707
0.776733
0.143001
0
0.711538
0
0
0.099125
0
0
0
0
0
0
1
0.076923
false
0
0.057692
0
0.211538
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
d993b7be2006ba21a11c5f625ad4f43b0951e1e1
706
py
Python
project_organizer/migrations/0009_project_manager_from_time_project_manager_until_time.py
c-Door-in/dvmn-project-organizer
6e7ccdf6d0e6adfed83be8babd750d6c6f75a83e
[ "MIT" ]
null
null
null
project_organizer/migrations/0009_project_manager_from_time_project_manager_until_time.py
c-Door-in/dvmn-project-organizer
6e7ccdf6d0e6adfed83be8babd750d6c6f75a83e
[ "MIT" ]
null
null
null
project_organizer/migrations/0009_project_manager_from_time_project_manager_until_time.py
c-Door-in/dvmn-project-organizer
6e7ccdf6d0e6adfed83be8babd750d6c6f75a83e
[ "MIT" ]
null
null
null
# Generated by Django 4.0.1 on 2022-01-28 00:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('project_organizer', '0008_rename_tg_id_student_tg_user_project_manager_tg_user_and_more'), ] operations = [ migrations.AddField( model_name='project_manager', name='from_time', field=models.TimeField(blank=True, null=True, verbose_name='Available from a time'), ), migrations.AddField( model_name='project_manager', name='until_time', field=models.TimeField(blank=True, null=True, verbose_name='Available until a time'), ), ]
29.416667
100
0.643059
83
706
5.216867
0.542169
0.096998
0.106236
0.124711
0.489607
0.489607
0.489607
0.281755
0.281755
0.281755
0
0.035985
0.252125
706
23
101
30.695652
0.784091
0.063739
0
0.352941
1
0
0.265554
0.100152
0
0
0
0
0
1
0
false
0
0.058824
0
0.235294
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
d996560fd986f9243110269ae81896011add1a35
842
py
Python
tests/test_users_organizations.py
uilianries/bintray-python
ab06edcf33663a5095c6c2121c19fbe2c1409127
[ "MIT" ]
4
2019-07-02T14:37:55.000Z
2022-01-20T13:37:01.000Z
tests/test_users_organizations.py
uilianries/bintray-python
ab06edcf33663a5095c6c2121c19fbe2c1409127
[ "MIT" ]
53
2019-07-02T17:13:47.000Z
2022-03-15T11:55:41.000Z
tests/test_users_organizations.py
uilianries/bintray-python
ab06edcf33663a5095c6c2121c19fbe2c1409127
[ "MIT" ]
null
null
null
from bintray.bintray import Bintray def test_get_user(): bintray = Bintray() response = bintray.get_user("uilianries") assert response.get("name") == "uilianries" assert response.get("error") == False assert response.get("statusCode") == 200 def test_get_organization(): bintray = Bintray() response = bintray.get_organization("jfrog") assert response.get("name") == "jfrog" assert response.get("error") == False assert response.get("statusCode") == 200 def test_get_followers(): bintray = Bintray() response = bintray.get_followers("uilianries") assert [{'name': 'solvingj'}, {'error': False, 'statusCode': 200}] == response def test_search_user(): bintray = Bintray() response = bintray.search_user("uilianries") assert {'error': False, 'statusCode': 200} in response
28.066667
82
0.675772
94
842
5.925532
0.223404
0.150808
0.183124
0.208259
0.479354
0.240575
0.240575
0.240575
0.240575
0.240575
0
0.017291
0.175772
842
29
83
29.034483
0.785303
0
0
0.380952
0
0
0.154394
0
0
0
0
0
0.380952
1
0.190476
false
0
0.047619
0
0.238095
0
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
793f2b848c3758a8f7dae311e7d721594f8e8f09
3,424
py
Python
setup.py
HEmile/problog
576b6fd305f72b12125111c8d4d62cf8a7bbda0f
[ "Apache-2.0" ]
189
2019-05-27T08:20:10.000Z
2022-03-28T09:29:22.000Z
setup.py
HEmile/problog
576b6fd305f72b12125111c8d4d62cf8a7bbda0f
[ "Apache-2.0" ]
60
2019-06-11T15:07:48.000Z
2022-03-25T02:31:23.000Z
setup.py
HEmile/problog
576b6fd305f72b12125111c8d4d62cf8a7bbda0f
[ "Apache-2.0" ]
33
2019-07-03T13:14:24.000Z
2022-02-20T01:07:15.000Z
#! /usr/bin/env python import sys import os version_file = os.path.join( os.path.abspath(os.path.dirname(__file__)), "problog/version.py" ) version = {} with open(version_file) as fp: exec(fp.read(), version) version = version["version"] if __name__ == "__main__" and len(sys.argv) == 1: from problog import setup as problog_setup problog_setup.install() elif __name__ == "__main__": from setuptools import setup, find_packages from setuptools.command.install import install class ProbLogInstall(install): def run(self): install.run(self) before_dir = os.getcwd() sys.path.insert(0, self.install_lib) from problog import setup as problog_setup try: problog_setup.install() except Exception as err: print("Optional ProbLog installation failed: %s" % err, file=sys.stderr) os.chdir(before_dir) package_data = { "problog": [ "bin/darwin/cnf2dDNNF_wine", "bin/darwin/dsharp", "bin/darwin/maxsatz", "bin/linux/dsharp", "bin/linux/maxsatz", "bin/source/maxsatz/maxsatz2009.c", "bin/windows/dsharp.exe", "bin/windows/maxsatz.exe", "bin/windows/libgcc_s_dw2-1.dll", "bin/windows/libstdc++-6.dll", "web/*.py", "web/editor_local.html" "web/editor_adv.html", "web/js/problog_editor.js", "library/*.pl", "library/*.py", "library/nlp4plp.d/*", ] } setup( name="problog", version=version, description="ProbLog2: Probabilistic Logic Programming toolbox", url="https://dtai.cs.kuleuven.be/problog", author="ProbLog team", author_email="anton.dries@cs.kuleuven.be", license="Apache Software License", classifiers=[ "Development Status :: 4 - Beta", "License :: OSI Approved :: Apache Software License", "Intended Audience :: Science/Research", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Prolog", "Topic :: Scientific/Engineering :: Artificial Intelligence", ], keywords="prolog probabilistic logic", packages=find_packages(), extras_require={"sdd": ["pysdd>=0.2.6"]}, entry_points={"console_scripts": ["problog=problog.tasks:main"]}, package_data=package_data, cmdclass={"install": ProbLogInstall}, ) def increment_release(v): v = v.split(".") if len(v) == 4: v = v[:3] + [str(int(v[3]) + 1)] else: v = v[:4] return ".".join(v) def increment_dev(v): v = v.split(".") if len(v) == 4: v = v[:3] + [str(int(v[3]) + 1), "dev1"] else: v = v[:4] + ["dev" + str(int(v[4][3:]) + 1)] return ".".join(v) def increment_version_dev(): v = increment_dev(version) os.path.dirname(__file__) with open(version_file, "w") as f: f.write("version = '%s'\n" % v) def increment_version_release(): v = increment_release(version) with open(version_file, "w") as f: f.write("version = '%s'\n" % v)
29.517241
88
0.561332
394
3,424
4.730964
0.388325
0.008584
0.053648
0.055794
0.151824
0.109442
0.109442
0.070815
0.070815
0.070815
0
0.015226
0.290304
3,424
115
89
29.773913
0.751852
0.006133
0
0.168421
0
0
0.313639
0.081717
0
0
0
0
0
1
0.052632
false
0
0.063158
0
0.147368
0.010526
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0