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
714ec7d33bab5008ec611874fc87d94cc9deca3c
9,769
py
Python
venv/Lib/site-packages/pygsheets/client.py
13rilliant/Python-CMS
56c4f3f1cbdd81020aa690ab92d0e26d042458c1
[ "MIT" ]
1
2019-04-22T14:22:38.000Z
2019-04-22T14:22:38.000Z
venv/Lib/site-packages/pygsheets/client.py
13rilliant/Python-Updates-Text-Files-from-Sheets
56c4f3f1cbdd81020aa690ab92d0e26d042458c1
[ "MIT" ]
null
null
null
venv/Lib/site-packages/pygsheets/client.py
13rilliant/Python-Updates-Text-Files-from-Sheets
56c4f3f1cbdd81020aa690ab92d0e26d042458c1
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*-. import re import warnings import os import logging from pygsheets.drive import DriveAPIWrapper from pygsheets.sheet import SheetAPIWrapper from pygsheets.spreadsheet import Spreadsheet from pygsheets.exceptions import SpreadsheetNotFound, NoValidUrlKeyFound from pygsheets.custom_types import ValueRenderOption, DateTimeRenderOption from google_auth_httplib2 import AuthorizedHttp GOOGLE_SHEET_CELL_UPDATES_LIMIT = 50000 _url_key_re_v1 = re.compile(r'key=([^&#]+)') _url_key_re_v2 = re.compile(r"/spreadsheets/d/([a-zA-Z0-9-_]+)") _email_patttern = re.compile(r"\"?([-a-zA-Z0-9.`?{}]+@[-a-zA-Z0-9.]+\.\w+)\"?") # _domain_pattern = re.compile("(?!-)[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE) _deprecated_keyword_mapping = { 'parent_id': 'folder', } class Client(object): """Create or access Google spreadsheets. Exposes members to create new spreadsheets or open existing ones. Use `authorize` to instantiate an instance of this class. >>> import pygsheets >>> c = pygsheets.authorize() The sheet API service object is stored in the sheet property and the drive API service object in the drive property. >>> c.sheet.get('<SPREADSHEET ID>') >>> c.drive.delete('<FILE ID>') :param credentials: The credentials object returned by google-auth or google-auth-oauthlib. :param retries: (Optional) Number of times to retry a connection before raising a TimeOut error. Default: 3 :param http: The underlying HTTP object to use to make requests. If not specified, a :class:`httplib2.Http` instance will be constructed. """ spreadsheet_cls = Spreadsheet def __init__(self, credentials, retries=3, http=None): self.oauth = credentials self.logger = logging.getLogger(__name__) http = AuthorizedHttp(credentials, http=http) data_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data") self.sheet = SheetAPIWrapper(http, data_path, retries=retries) self.drive = DriveAPIWrapper(http, data_path) @property def teamDriveId(self): """ Enable team drive support Deprecated: use client.drive.enable_team_drive(team_drive_id=?) """ return self.drive.team_drive_id @teamDriveId.setter def teamDriveId(self, value): warnings.warn("Depricated please use drive.enable_team_drive") self.drive.enable_team_drive(value) def spreadsheet_ids(self, query=None): """Get a list of all spreadsheet ids present in the Google Drive or TeamDrive accessed.""" return [x['id'] for x in self.drive.spreadsheet_metadata(query)] def spreadsheet_titles(self, query=None): """Get a list of all spreadsheet titles present in the Google Drive or TeamDrive accessed.""" return [x['name'] for x in self.drive.spreadsheet_metadata(query)] def create(self, title, template=None, folder=None, **kwargs): """Create a new spreadsheet. The title will always be set to the given value (even overwriting the templates title). The template can either be a `spreadsheet resource <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets#resource-spreadsheet>`_ or an instance of :class:`~pygsheets.Spreadsheet`. In both cases undefined values will be ignored. :param title: Title of the new spreadsheet. :param template: A template to create the new spreadsheet from. :param folder: The Id of the folder this sheet will be stored in. :param kwargs: Standard parameters (see reference for details). :return: :class:`~pygsheets.Spreadsheet` """ result = self.sheet.create(title, template=template, **kwargs) if folder: self.drive.move_file(result['spreadsheetId'], old_folder=self.drive.spreadsheet_metadata(query="name = '" + title + "'")[0]['parents'][0], new_folder=folder) return self.spreadsheet_cls(self, jsonsheet=result) def open(self, title): """Open a spreadsheet by title. In a case where there are several sheets with the same title, the first one found is returned. >>> import pygsheets >>> c = pygsheets.authorize() >>> c.open('TestSheet') :param title: A title of a spreadsheet. :returns: :class:`~pygsheets.Spreadsheet` :raises pygsheets.SpreadsheetNotFound: No spreadsheet with the given title was found. """ try: spreadsheet = list(filter(lambda x: x['name'] == title, self.drive.spreadsheet_metadata()))[0] return self.open_by_key(spreadsheet['id']) except (KeyError, IndexError): raise SpreadsheetNotFound('Could not find a spreadsheet with title %s.' % title) def open_by_key(self, key): """Open a spreadsheet by key. >>> import pygsheets >>> c = pygsheets.authorize() >>> c.open_by_key('0BmgG6nO_6dprdS1MN3d3MkdPa142WFRrdnRRUWl1UFE') :param key: The key of a spreadsheet. (can be found in the sheet URL) :returns: :class:`~pygsheets.Spreadsheet` :raises pygsheets.SpreadsheetNotFound: The given spreadsheet ID was not found. """ response = self.sheet.get(key, fields='properties,sheets/properties,spreadsheetId,namedRanges', includeGridData=False) return self.spreadsheet_cls(self, response) def open_by_url(self, url): """Open a spreadsheet by URL. >>> import pygsheets >>> c = pygsheets.authorize() >>> c.open_by_url('https://docs.google.com/spreadsheet/ccc?key=0Bm...FE&hl') :param url: URL of a spreadsheet as it appears in a browser. :returns: :class:`~pygsheets.Spreadsheet` :raises pygsheets.SpreadsheetNotFound: No spreadsheet was found with the given URL. """ m1 = _url_key_re_v1.search(url) if m1: return self.open_by_key(m1.group(1)) else: m2 = _url_key_re_v2.search(url) if m2: return self.open_by_key(m2.group(1)) else: raise NoValidUrlKeyFound def open_all(self, query=''): """Opens all available spreadsheets. Result can be filtered when specifying the query parameter. On the details on how to form the query: `Reference <https://developers.google.com/drive/v3/web/search-parameters>`_ :param query: (Optional) Can be used to filter the returned metadata. :returns: A list of :class:`~pygsheets.Spreadsheet`. """ return [self.open_by_key(key) for key in self.spreadsheet_ids(query=query)] def open_as_json(self, key): """Return a json representation of the spreadsheet. See `Reference <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets#Spreadsheet>`__ for details. """ return self.sheet.get(key, fields='properties,sheets/properties,sheets/protectedRanges,' 'spreadsheetId,namedRanges', includeGridData=False) def get_range(self, spreadsheet_id, value_range, major_dimension='ROWS', value_render_option=ValueRenderOption.FORMATTED_VALUE, date_time_render_option=DateTimeRenderOption.SERIAL_NUMBER): """Returns a range of values from a spreadsheet. The caller must specify the spreadsheet ID and a range. Reference: `request <https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get>`__ :param spreadsheet_id: The ID of the spreadsheet to retrieve data from. :param value_range: The A1 notation of the values to retrieve. :param major_dimension: The major dimension that results should use. For example, if the spreadsheet data is: A1=1,B1=2,A2=3,B2=4, then requesting range=A1:B2,majorDimension=ROWS will return [[1,2],[3,4]], whereas requesting range=A1:B2,majorDimension=COLUMNS will return [[1,3],[2,4]]. :param value_render_option: How values should be represented in the output. The default render option is `ValueRenderOption.FORMATTED_VALUE`. :param date_time_render_option: How dates, times, and durations should be represented in the output. This is ignored if `valueRenderOption` is `FORMATTED_VALUE`. The default dateTime render option is [`DateTimeRenderOption.SERIAL_NUMBER`]. :return: An array of arrays with the values fetched. Returns an empty array if no values were fetched. Values are dynamically typed as int, float or string. """ result = self.sheet.values_get(spreadsheet_id, value_range, major_dimension, value_render_option, date_time_render_option) try: return result['values'] except KeyError: return [['']]
46.519048
142
0.614085
1,124
9,769
5.224199
0.261566
0.018392
0.025545
0.01703
0.224114
0.171832
0.149012
0.131131
0.101158
0.047343
0
0.010132
0.292763
9,769
210
143
46.519048
0.839774
0.527587
0
0.073171
0
0
0.083066
0.045983
0
0
0
0
0
1
0.146341
false
0
0.121951
0
0.439024
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
714ecc8f34f21f3f5078c51278dfea154ffd4835
1,511
py
Python
model/group_contact.py
NatalyAristova/Training_python
e95a2b9e25238285d705a880fd94d73f173c3a31
[ "Apache-2.0" ]
null
null
null
model/group_contact.py
NatalyAristova/Training_python
e95a2b9e25238285d705a880fd94d73f173c3a31
[ "Apache-2.0" ]
null
null
null
model/group_contact.py
NatalyAristova/Training_python
e95a2b9e25238285d705a880fd94d73f173c3a31
[ "Apache-2.0" ]
null
null
null
from sys import maxsize class Group_contact: def __init__(self,firstname=None, middlename=None, lastname=None, nickname=None, title=None, company=None, address=None, home=None, mobile=None, work=None, fax=None, email=None, email2=None, email3=None, byear=None, address2=None, phone2=None, notes=None, all_phones_from_home_page=None, id=None, all_emails_from_home_page=None): self.firstname=firstname self.middlename=middlename self.lastname=lastname self.nickname=nickname self.title=title self.company=company self.address=address self.home=home self.mobile=mobile self.work=work self.fax=fax self.email=email self.email2 = email2 self.email3 = email3 self.byear=byear self.address2=address2 self.phone2=phone2 self.notes=notes self.id = id self.all_phones_from_home_page=all_phones_from_home_page self.all_emails_from_home_page = all_emails_from_home_page def __repr__(self): return "%s:%s:%s:%s:%s:%s" % (self.id, self.lastname, self.firstname, self.middlename, self.nickname, self.title) def __eq__(self, other): return (self.id is None or other.id is None or self.id == other.id) and (self.lastname, self.firstname) == (other.lastname, other.firstname) def id_or_max(self): if self.id: return int(self.id) else: return maxsize
36.853659
148
0.650563
204
1,511
4.627451
0.22549
0.050847
0.076271
0.054025
0.139831
0
0
0
0
0
0
0.010582
0.249504
1,511
41
149
36.853659
0.821869
0
0
0
0
0
0.011243
0
0
0
0
0
0
1
0.114286
false
0
0.028571
0.057143
0.285714
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
714fe59976a41e4840adb621109e180ee047b25c
5,567
py
Python
demo.py
cbsudux/minimal-hand
893c252e7e818a9a96b279023ea8a78a88fb0a4d
[ "MIT" ]
null
null
null
demo.py
cbsudux/minimal-hand
893c252e7e818a9a96b279023ea8a78a88fb0a4d
[ "MIT" ]
null
null
null
demo.py
cbsudux/minimal-hand
893c252e7e818a9a96b279023ea8a78a88fb0a4d
[ "MIT" ]
null
null
null
import argparse import cv2 import keyboard import numpy as np import open3d as o3d import os import pygame from transforms3d.axangles import axangle2mat import config from hand_mesh import HandMesh from kinematics import mpii_to_mano from utils import OneEuroFilter, imresize from wrappers import ModelPipeline from utils import * def video_to_images(vid_file, img_folder=None, return_info=False): if img_folder is None: img_folder = osp.join('/tmp', osp.basename(vid_file).replace('.', '_')) os.makedirs(img_folder, exist_ok=True) command = ['ffmpeg', '-i', vid_file, '-f', 'image2', '-v', 'error', f'{img_folder}/%06d.png'] print(f'Running \"{" ".join(command)}\"') subprocess.call(command) print(f'Images saved to \"{img_folder}\"') img_shape = cv2.imread(osp.join(img_folder, '000001.png')).shape if return_info: return img_folder, len(os.listdir(img_folder)), img_shape else: return img_folder def run(args): ############ output visualization ############ # view_mat = axangle2mat([1, 0, 0], np.pi) # align different coordinate systems # window_size = 1080 # hand_mesh = HandMesh(config.HAND_MESH_MODEL_PATH) # mesh = o3d.geometry.TriangleMesh() # mesh.triangles = o3d.utility.Vector3iVector(hand_mesh.faces) # mesh.vertices = \ # o3d.utility.Vector3dVector(np.matmul(view_mat, hand_mesh.verts.T).T * 1000) # mesh.compute_vertex_normals() # viewer = o3d.visualization.Visualizer() # viewer.create_window( # width=window_size + 1, height=window_size + 1, # window_name='Minimal Hand - output' # ) # viewer.add_geometry(mesh) # view_control = viewer.get_view_control() # cam_params = view_control.convert_to_pinhole_camera_parameters() # extrinsic = cam_params.extrinsic.copy() # extrinsic[0:3, 3] = 0 # cam_params.extrinsic = extrinsic # cam_params.intrinsic.set_intrinsics( # window_size + 1, window_size + 1, config.CAM_FX, config.CAM_FY, # window_size // 2, window_size // 2 # ) # view_control.convert_from_pinhole_camera_parameters(cam_params) # view_control.set_constant_z_far(1000) # render_option = viewer.get_render_option() # render_option.load_from_json('./render_option.json') # viewer.update_renderer() # ############ input visualization ############ # pygame.init() # display = pygame.display.set_mode((window_size, window_size)) # pygame.display.set_caption('Minimal Hand - input') # ############ misc ############ # mesh_smoother = OneEuroFilter(4.0, 0.0) # clock = pygame.time.Clock() ############ Move all of above code to local to render ########### video_file = args.vid_file if not os.path.isfile(video_file): exit(f'Input video \"{video_file}\" does not exist!') output_path = os.path.join(args.output_folder, os.path.basename(video_file).replace('.mp4', '')) os.makedirs(output_path, exist_ok=True) image_folder, num_frames, img_shape = video_to_images(video_file, return_info=True) print(f'Input video number of frames {num_frames}') orig_height, orig_width = img_shape[:2] # total_time = time.time() import pdb; pdb.set_trace() image_file_names = [ osp.join(image_folder, x) for x in os.listdir(image_folder) if x.endswith('.png') or x.endswith('.jpg') ] model = ModelPipeline() for i in image_file_names: # What do all these conditions check for? frame_large = x if frame_large is None: continue if frame_large.shape[0] > frame_large.shape[1]: margin = int((frame_large.shape[0] - frame_large.shape[1]) / 2) frame_large = frame_large[margin:-margin] else: margin = int((frame_large.shape[1] - frame_large.shape[0]) / 2) frame_large = frame_large[:, margin:-margin] frame_large = np.flip(frame_large, axis=1).copy() # why? Camera flip? frame = imresize(frame_large, (128, 128)) # needed ######## Golden lines, run this here ######### _, theta_mpii = model.process(frame) theta_mano = mpii_to_mano(theta_mpii) ######## Save theta_mano and pass as input to local ######## v = hand_mesh.set_abs_quat(theta_mano) v *= 2 # for better visualization v = v * 1000 + np.array([0, 0, 400]) v = mesh_smoother.process(v) mesh.triangles = o3d.utility.Vector3iVector(hand_mesh.faces) mesh.vertices = o3d.utility.Vector3dVector(np.matmul(view_mat, v.T).T) mesh.paint_uniform_color(config.HAND_COLOR) mesh.compute_triangle_normals() mesh.compute_vertex_normals() # for some version of open3d you may need `viewer.update_geometry(mesh)` viewer.update_geometry() viewer.poll_events() display.blit( pygame.surfarray.make_surface( np.transpose( imresize(frame_large, (window_size, window_size) ), (1, 0, 2)) ), (0, 0) ) pygame.display.update() if keyboard.is_pressed("esc"): break clock.tick(30) # What's this do? If it adds delay remove it if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--vid_file', type=str, help='input video path or youtube link') args = parser.parse_args() run(args)
33.136905
100
0.629064
713
5,567
4.680224
0.333801
0.047947
0.02697
0.014384
0.10938
0.099491
0.099491
0.079712
0.060533
0.060533
0
0.021201
0.237471
5,567
167
101
33.335329
0.7649
0.303934
0
0.022222
0
0
0.073724
0.005671
0
0
0
0
0
1
0.022222
false
0
0.166667
0
0.211111
0.033333
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
7150fca7ddfd290e2618756c7d1c3d98b7e62c0b
11,824
py
Python
tests/test_akismet.py
cclauss/akismet
7b65bc163d6947a3013d01bf9accf1bc6c0781ca
[ "BSD-3-Clause" ]
9
2015-07-21T01:43:05.000Z
2021-04-01T12:53:32.000Z
tests/test_akismet.py
cclauss/akismet
7b65bc163d6947a3013d01bf9accf1bc6c0781ca
[ "BSD-3-Clause" ]
3
2015-09-28T09:01:17.000Z
2021-11-18T08:19:36.000Z
tests/test_akismet.py
cclauss/akismet
7b65bc163d6947a3013d01bf9accf1bc6c0781ca
[ "BSD-3-Clause" ]
7
2015-09-27T03:14:44.000Z
2021-12-05T22:48:44.000Z
import datetime import os import sys import unittest from unittest import mock import akismet class AkismetTests(unittest.TestCase): api_key = os.getenv("TEST_AKISMET_API_KEY") blog_url = os.getenv("TEST_AKISMET_BLOG_URL") api_key_env_var = "PYTHON_AKISMET_API_KEY" blog_url_env_var = "PYTHON_AKISMET_BLOG_URL" def setUp(self): self.api = akismet.Akismet(key=self.api_key, blog_url=self.blog_url) class AkismetConfigurationTests(AkismetTests): """ Tests configuration of the Akismet class. """ def test_config_from_args(self): """ Configuring via explicit arguments succeeds. """ api = akismet.Akismet(key=self.api_key, blog_url=self.blog_url) self.assertEqual(self.api_key, api.api_key) self.assertEqual(self.blog_url, api.blog_url) def test_bad_config_args(self): """ Configuring with bad arguments fails. """ with self.assertRaises(akismet.APIKeyError): akismet.Akismet(key="invalid", blog_url="http://invalid") def test_config_from_env(self): """ Configuring via environment variables succeeds. """ try: os.environ[self.api_key_env_var] = self.api_key os.environ[self.blog_url_env_var] = self.blog_url api = akismet.Akismet(key=None, blog_url=None) self.assertEqual(self.api_key, api.api_key) self.assertEqual(self.blog_url, api.blog_url) api = akismet.Akismet() self.assertEqual(self.api_key, api.api_key) self.assertEqual(self.blog_url, api.blog_url) finally: os.environ[self.api_key_env_var] = "" os.environ[self.blog_url_env_var] = "" def test_bad_config_env(self): """ Configuring with bad environment variables fails. """ try: os.environ[self.api_key_env_var] = "invalid" os.environ[self.blog_url_env_var] = "http://invalid" with self.assertRaises(akismet.APIKeyError): akismet.Akismet() finally: os.environ[self.api_key_env_var] = "" os.environ[self.blog_url_env_var] = "" def test_bad_url(self): """ Configuring with a bad URL fails. """ bad_urls = ( "example.com", "ftp://example.com", "www.example.com", "http//example.com", "https//example.com", ) for url in bad_urls: with self.assertRaises(akismet.ConfigurationError): akismet.Akismet(key=self.api_key, blog_url=url) def test_missing_config(self): """ Instantiating without any configuration fails. """ with self.assertRaises(akismet.ConfigurationError): akismet.Akismet(key=None, blog_url=None) with self.assertRaises(akismet.ConfigurationError): akismet.Akismet() def test_user_agent(self): """ The Akismet class creates the correct user-agent string. """ api = akismet.Akismet(key=self.api_key, blog_url=self.blog_url) expected_agent = "Python/{} | akismet.py/{}".format( "{}.{}".format(*sys.version_info[:2]), akismet.__version__ ) self.assertEqual(expected_agent, api.user_agent_header["User-Agent"]) class AkismetAPITests(AkismetTests): """ Tests implementation of the Akismet API. """ base_kwargs = { "user_ip": "127.0.0.1", "user_agent": "Mozilla", # Always send this when testing; Akismet recognizes it as a # test query and does not train/learn from it. "is_test": 1, } def test_verify_key_valid(self): """ The verify_key operation succeeds with a valid key and URL. """ self.assertTrue(akismet.Akismet.verify_key(self.api_key, self.blog_url)) def test_verify_key_invalid(self): """ The verify_key operation fails with an invalid key and URL. """ self.assertFalse(akismet.Akismet.verify_key("invalid", "http://invalid")) def test_comment_check_spam(self): """ The comment_check method correctly identifies spam. """ check_kwargs = { # Akismet guarantees this will be classified spam. "comment_author": "viagra-test-123", **self.base_kwargs, } self.assertTrue(self.api.comment_check(**check_kwargs)) def test_comment_check_not_spam(self): """ The comment_check method correctly identifies non-spam. """ check_kwargs = { # Akismet guarantees this will not be classified spam. "user_role": "administrator", **self.base_kwargs, } self.assertFalse(self.api.comment_check(**check_kwargs)) def test_submit_spam(self): """ The submit_spam method succeeds. """ spam_kwargs = { "comment_type": "comment", "comment_author": "viagra-test-123", "comment_content": "viagra-test-123", **self.base_kwargs, } self.assertTrue(self.api.submit_spam(**spam_kwargs)) def test_submit_ham(self): """ The submit_ham method succeeds. """ ham_kwargs = { "comment_type": "comment", "comment_author": "Legitimate Author", "comment_content": "This is a legitimate comment.", "user_role": "administrator", **self.base_kwargs, } self.assertTrue(self.api.submit_ham(**ham_kwargs)) def test_unexpected_verify_key_response(self): """ Unexpected verify_key API responses are correctly handled. """ post_mock = mock.MagicMock() with mock.patch("requests.post", post_mock): with self.assertRaises(akismet.ProtocolError): akismet.Akismet.verify_key(self.api_key, self.blog_url) def test_unexpected_comment_check_response(self): """ Unexpected comment_check API responses are correctly handled. """ post_mock = mock.MagicMock() with mock.patch("requests.post", post_mock): with self.assertRaises(akismet.ProtocolError): check_kwargs = {"comment_author": "viagra-test-123", **self.base_kwargs} self.api.comment_check(**check_kwargs) def test_unexpected_submit_spam_response(self): """ Unexpected submit_spam API responses are correctly handled. """ post_mock = mock.MagicMock() with mock.patch("requests.post", post_mock): with self.assertRaises(akismet.ProtocolError): spam_kwargs = { "comment_type": "comment", "comment_author": "viagra-test-123", "comment_content": "viagra-test-123", **self.base_kwargs, } self.api.submit_spam(**spam_kwargs) def test_unexpected_submit_ham_response(self): """ Unexpected submit_ham API responses are correctly handled. """ post_mock = mock.MagicMock() with mock.patch("requests.post", post_mock): with self.assertRaises(akismet.ProtocolError): ham_kwargs = { "comment_type": "comment", "comment_author": "Legitimate Author", "comment_content": "This is a legitimate comment.", "user_role": "administrator", **self.base_kwargs, } self.api.submit_ham(**ham_kwargs) class AkismetRequestTests(AkismetTests): """ Tests the requests constructed by the Akismet class. """ def _get_mock(self, text): """ Create a mock for requests.post() returning expected text. """ post_mock = mock.MagicMock() post_mock.return_value.text = text return post_mock def _mock_request(self, method, endpoint, text, method_kwargs): """ Issue a mocked request and verify requests.post() was called with the correct arguments. """ method_kwargs.update(user_ip="127.0.0.1", user_agent="Mozilla", is_test=1) expected_kwargs = {"blog": self.blog_url, **method_kwargs} post_mock = self._get_mock(text) with mock.patch("requests.post", post_mock): getattr(self.api, method)(**method_kwargs) post_mock.assert_called_with( endpoint.format(self.api_key), data=expected_kwargs, headers=akismet.Akismet.user_agent_header, ) def test_verify_key(self): """ The request issued by verify_key() is correct. """ post_mock = self._get_mock("valid") with mock.patch("requests.post", post_mock): akismet.Akismet.verify_key(self.api_key, self.blog_url) post_mock.assert_called_with( akismet.Akismet.VERIFY_KEY_URL, data={"key": self.api_key, "blog": self.blog_url}, headers=akismet.Akismet.user_agent_header, ) def test_comment_check(self): """ The request issued by comment_check() is correct. """ self._mock_request( "comment_check", akismet.Akismet.COMMENT_CHECK_URL, "true", {"comment_author": "viagra-test-123"}, ) def test_submit_spam(self): """ The request issued by submit_spam() is correct. """ self._mock_request( "submit_spam", akismet.Akismet.SUBMIT_SPAM_URL, akismet.Akismet.SUBMIT_SUCCESS_RESPONSE, {"comment_content": "Bad comment", "comment_author": "viagra-test-123"}, ) def test_submit_ham(self): """ The request issued by submit_ham() is correct. """ self._mock_request( "submit_ham", akismet.Akismet.SUBMIT_HAM_URL, akismet.Akismet.SUBMIT_SUCCESS_RESPONSE, { "comment_content": "Good comment", "comment_author": "Legitimate commenter", }, ) def test_full_kwargs(self): """ All optional Akismet arguments are correctly passed through. """ modified_timestamp = datetime.datetime.now() posted_timestamp = modified_timestamp - datetime.timedelta(seconds=30) full_kwargs = { "referrer": "http://www.example.com/", "permalink": "http://www.example.com/#comment123", "comment_type": "comment", "comment_author": "Legitimate Author", "comment_author_email": "email@example.com", "comment_author_url": "http://www.example.com/", "comment_content": "This is a fine comment.", "comment_date_gmt": posted_timestamp.isoformat(), "comment_post_modified_gmt": modified_timestamp.isoformat(), "blog_lang": "en_us", "blog_charset": "utf-8", "user_role": "administrator", "recheck_reason": "edit", } self._mock_request( "comment_check", akismet.Akismet.COMMENT_CHECK_URL, "false", full_kwargs ) def test_unknown_kwargs(self): """ Unknown Akismet arguments are correctly rejected. """ bad_kwargs = {"bad_arg": "bad_val"} with self.assertRaises(akismet.UnknownArgumentError): self._mock_request( "comment_check", akismet.Akismet.COMMENT_CHECK_URL, "false", bad_kwargs )
31.87062
88
0.58931
1,282
11,824
5.177847
0.152886
0.031636
0.02561
0.040675
0.561916
0.511299
0.481772
0.414432
0.294667
0.277644
0
0.005455
0.302267
11,824
370
89
31.956757
0.799152
0.139039
0
0.401869
0
0
0.154412
0.009559
0
0
0
0
0.116822
1
0.121495
false
0
0.028037
0
0.196262
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
7151993c0f8145d0e1fdf8168c7b895118af0892
2,581
py
Python
experimenting/dataset/datamodule.py
gaurvigoyal/lifting_events_to_3d_hpe
66d27eb7534f81a95d9f68e17cc534ef2a2c9b1c
[ "Apache-2.0" ]
19
2021-04-16T11:43:34.000Z
2022-01-07T10:21:42.000Z
experimenting/dataset/datamodule.py
gaurvigoyal/lifting_events_to_3d_hpe
66d27eb7534f81a95d9f68e17cc534ef2a2c9b1c
[ "Apache-2.0" ]
4
2021-04-16T14:07:38.000Z
2022-02-12T16:35:22.000Z
experimenting/dataset/datamodule.py
gianscarpe/event-camera
8bb60a281adb9e2c961b5e12c24c9bbbba1876d5
[ "Apache-2.0" ]
5
2021-04-23T16:30:37.000Z
2022-02-12T01:42:14.000Z
import pytorch_lightning as pl from torch.utils.data import DataLoader, Dataset from .core import BaseCore from .factory import BaseDataFactory class DataModule(pl.LightningDataModule): def __init__( self, dataset_factory: BaseDataFactory, core: BaseCore, aug_train_config, aug_test_config, batch_size: int, num_workers: int, train_val_split: float = 0.8, ): super().__init__() self.core = core self.batch_size = batch_size self.num_workers = num_workers self.dataset_factory = dataset_factory self.aug_train_config = aug_train_config self.aug_test_config = aug_test_config self.train_val_split = train_val_split def prepare_data(self, *args, **kwargs): pass def setup(self, stage=None): self.dataset_factory.set_dataset_core(self.core) ( self.train_indexes, self.val_indexes, self.test_indexes, ) = self.dataset_factory.get_train_test_split(self.train_val_split) self.train_dataset = self.dataset_factory.get_dataset( self.train_indexes, self.aug_train_config ) self.val_dataset = self.dataset_factory.get_dataset( self.val_indexes, self.aug_test_config ) self.test_dataset = self.dataset_factory.get_dataset( self.test_indexes, self.aug_test_config ) def train_dataloader(self): return get_dataloader(self.train_dataset, self.batch_size, self.num_workers) def val_dataloader(self): return get_dataloader( self.val_dataset, self.batch_size, shuffle=False, num_workers=self.num_workers, ) def test_dataloader(self): return get_dataloader( self.test_dataset, self.batch_size, shuffle=False, num_workers=self.num_workers, ) def test_frames_only_dataloader(self): return get_dataloader( self.dataset_factory.get_frame_only_dataset( self.test_indexes, self.aug_test_config ), self.batch_size, shuffle=False, num_workers=self.num_workers, ) def get_dataloader( dataset: Dataset, batch_size: int, num_workers: int = 12, shuffle=True ) -> DataLoader: loader = DataLoader( dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_workers, pin_memory=True, ) return loader
28.362637
84
0.631538
298
2,581
5.114094
0.191275
0.085302
0.094488
0.068898
0.416011
0.385827
0.237533
0.167979
0.116798
0.116798
0
0.0022
0.295622
2,581
90
85
28.677778
0.836084
0
0
0.181818
0
0
0
0
0
0
0
0
0
1
0.103896
false
0.012987
0.051948
0.051948
0.233766
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
7152cc15e7baaacfb5a36373bdeff28f520d9e9f
2,906
py
Python
sevn-interface/SEVN/resources/SEVN_walkthrough/running_folder/analysis_3_pandas.py
giulianoiorio/PeTar
f6a849552b3d8e47c5e08fe90fed05bf38bc407d
[ "MIT" ]
null
null
null
sevn-interface/SEVN/resources/SEVN_walkthrough/running_folder/analysis_3_pandas.py
giulianoiorio/PeTar
f6a849552b3d8e47c5e08fe90fed05bf38bc407d
[ "MIT" ]
null
null
null
sevn-interface/SEVN/resources/SEVN_walkthrough/running_folder/analysis_3_pandas.py
giulianoiorio/PeTar
f6a849552b3d8e47c5e08fe90fed05bf38bc407d
[ "MIT" ]
null
null
null
import pandas as pd import matplotlib.pyplot as plt import numpy as np #Load file dt=pd.read_csv("sevn_output/output_0.csv") #Give a look to the columns print(dt.columns) #Consider only the final states dt=dt.drop_duplicates(["ID","name"], keep='last') #Load evolved file dte=pd.read_csv("sevn_output/evolved_0.dat",sep='\s+') #Give a look to the columns print(dte.columns) dte=dte.rename(columns={'#ID': 'ID','Mass_0':"Mzams_0", 'Mass_1':"Mzams_1"}) #After change print(dte.columns) #Join the two dataset dt = dt.merge(dte, on=["ID","name"], how="inner", suffixes=("","_ini") ) # - on: column(s, can be a list of columns) to match during the merge of the two tables. The colum(s) has(have) to be present in both the tables # - how: type of join to use, see documentation here and the next slide # - suffixes: columns with the same name in the two tables (not used in on) will be renamed adding these suffixes. #Give a look to the columns print(dt.columns) #Create filter indexes idx0 = (dt.RemnantType_0==6) idx1 = (dt.RemnantType_1==6) idxb0 = idx0 & dt.Semimajor.notnull() idxb1 = idx1 & dt.Semimajor.notnull() idxm0 = idxb0 & (dt.GWtime + dt.BWorldtime <= 14000) idxm1 = idxb1 & (dt.GWtime + dt.BWorldtime <= 14000) #Filter and join masses AllBH = pd.concat([dt[idx0].Mass_0,dt[idx1].Mass_1]) BoundBH = pd.concat([dt[idxb0].Mass_0,dt[idxb1].Mass_1]) MergingBH = pd.concat([dt[idxm0].Mass_0,dt[idxm1].Mass_1]) #Filter and join initial masses AllBHzams = pd.concat([dt[idx0].Mzams_0,dt[idx1].Mzams_1]) BoundBHzams = pd.concat([dt[idxb0].Mzams_0,dt[idxb1].Mzams_1]) MergingBHzams = pd.concat([dt[idxm0].Mzams_0,dt[idxm1].Mzams_1]) #Filter and join initial semimajor axis AllBHa = pd.concat([dt[idx0].a,dt[idx1].a]) BoundBHa = pd.concat([dt[idxb0].a,dt[idxb1].a]) MergingBHa = pd.concat([dt[idxm0].a,dt[idxm1].a]) #Plot plt.figure(figsize=(10,5)) plt.subplot(1,2,1) plt.scatter(AllBHzams,AllBH,zorder=1,edgecolor="k",s=30,label="All") plt.scatter(BoundBHzams,BoundBH,zorder=2,edgecolor="k",s=30, label="Bound") plt.scatter(MergingBHzams,MergingBH,zorder=3,edgecolor="k",s=30, label="Merging") plt.plot(np.linspace(0,140),np.linspace(0,140),ls="dashed",c="gray") plt.xscale("log") plt.yscale("log") plt.ylabel("BH mass [M$_\odot$]",fontsize=18) plt.xlabel("$M\mathrm{zams}$ [M$_\odot$]",fontsize=18) plt.gca().tick_params(axis='both', which='major', labelsize=18) plt.legend(fontsize=16) plt.subplot(1,2,2) plt.scatter(AllBHa,AllBH,zorder=1,edgecolor="k",s=30,label="All") plt.scatter(BoundBHa,BoundBH,zorder=2,edgecolor="k",s=30,label="Bound") plt.scatter(MergingBHa,MergingBH,zorder=3,edgecolor="k",s=30,label="Merging") plt.xscale("log") plt.yscale("log") plt.xlabel("Semimajor initial [R$_\odot$]",fontsize=18) plt.ylabel("BH mass [M$_\odot$]",fontsize=18) plt.gca().tick_params(axis='both', which='major', labelsize=18) plt.tight_layout() plt.savefig("analysis3.png") plt.show()
34.595238
144
0.719202
500
2,906
4.114
0.326
0.035002
0.043753
0.037919
0.34808
0.284881
0.284881
0.248906
0.248906
0.191541
0
0.04173
0.092911
2,906
83
145
35.012048
0.738619
0.208878
0
0.235294
0
0
0.128778
0.021463
0
0
0
0
0
1
0
false
0
0.058824
0
0.058824
0.078431
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
71530e1943a52265477429affe05d43b9f82d449
2,152
py
Python
office365/sharepoint/portal/group_site_manager.py
rikeshtailor/Office365-REST-Python-Client
ca7bfa1b22212137bb4e984c0457632163e89a43
[ "MIT" ]
null
null
null
office365/sharepoint/portal/group_site_manager.py
rikeshtailor/Office365-REST-Python-Client
ca7bfa1b22212137bb4e984c0457632163e89a43
[ "MIT" ]
null
null
null
office365/sharepoint/portal/group_site_manager.py
rikeshtailor/Office365-REST-Python-Client
ca7bfa1b22212137bb4e984c0457632163e89a43
[ "MIT" ]
null
null
null
from office365.runtime.client_object import ClientObject from office365.runtime.client_result import ClientResult from office365.runtime.http.http_method import HttpMethod from office365.runtime.queries.service_operation_query import ServiceOperationQuery from office365.runtime.resource_path import ResourcePath from office365.sharepoint.portal.group_creation_params import GroupCreationInformation from office365.sharepoint.portal.group_site_info import GroupSiteInfo class GroupSiteManager(ClientObject): def __init__(self, context): super(GroupSiteManager, self).__init__(context, ResourcePath("GroupSiteManager"), None) def create_group_ex(self, display_name, alias, is_public, optional_params=None): """ Create a modern site :param str display_name: :param str alias: :param bool is_public: :param office365.sharepoint.portal.group_creation_params.GroupCreationParams or None optional_params: """ payload = GroupCreationInformation(display_name, alias, is_public, optional_params) result = ClientResult(self.context, GroupSiteInfo()) qry = ServiceOperationQuery(self, "CreateGroupEx", None, payload, None, result) self.context.add_query(qry) return result def delete(self, site_url): """ Deletes a SharePoint Team site :type site_url: str """ payload = { "siteUrl": site_url } qry = ServiceOperationQuery(self, "Delete", None, payload) self.context.add_query(qry) return self def get_status(self, group_id): """Get the status of a SharePoint site :type group_id: str """ result = ClientResult(self.context, GroupSiteInfo()) qry = ServiceOperationQuery(self, "GetSiteStatus", None, {'groupId': group_id}, None, result) self.context.add_query(qry) def _construct_status_request(request): request.method = HttpMethod.Get request.url += "?groupId='{0}'".format(group_id) self.context.before_execute(_construct_status_request) return result
37.754386
109
0.701208
233
2,152
6.266094
0.32618
0.062329
0.068493
0.061644
0.30137
0.275342
0.191781
0.09589
0
0
0
0.014784
0.214219
2,152
56
110
38.428571
0.84861
0.138476
0
0.21875
0
0
0.043553
0
0
0
0
0
0
1
0.15625
false
0
0.21875
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
7157c50528da6262c46158a9ce6e62a7c31b48be
3,229
py
Python
aligner/grow_diag_final.py
ecalder6/MT-HW2
1356aeb374a6e4d0b0ae819684bf314039948c56
[ "MIT" ]
null
null
null
aligner/grow_diag_final.py
ecalder6/MT-HW2
1356aeb374a6e4d0b0ae819684bf314039948c56
[ "MIT" ]
null
null
null
aligner/grow_diag_final.py
ecalder6/MT-HW2
1356aeb374a6e4d0b0ae819684bf314039948c56
[ "MIT" ]
null
null
null
import optparse import sys def make_set(data, s, e_vocab, f_vocab, aligned, reverse): for pair in data.split(): cur = pair.split('-') if reverse: e_vocab.add(int(cur[1])) f_vocab.add(int(cur[0])) aligned.add(int(cur[0])) s.add((int(cur[1]), int(cur[0]))) else: e_vocab.add(int(cur[0])) f_vocab.add(int(cur[1])) aligned.add(int(cur[0])) s.add((int(cur[0]), int(cur[1]))) def grow_diag_final_and(e2f_data, f2e_data): directions = [(-1,0),(0,-1),(1,0),(0,1),(-1,-1),(-1,1),(1,-1),(1,1)] for (i, (e2f, f2e)) in enumerate(zip(open(e2f_data), open(f2e_data))): e2f_set, f2e_set, e_vocab, f_vocab, e_aligned, f_aligned = set(), set(), set(), set(), set(), set() make_set(e2f, e2f_set, e_vocab, f_vocab, e_aligned, False) make_set(f2e, f2e_set, e_vocab, f_vocab, f_aligned, True) alignment = e2f_set & f2e_set union_alignment = e2f_set | f2e_set grow_diag(e_vocab, f_vocab, e_aligned, f_aligned, alignment, union_alignment, directions) final(e_vocab, f_vocab, e_aligned, f_aligned, alignment, union_alignment, True) for e, f in alignment: sys.stdout.write("%i-%i " % (e,f)) sys.stdout.write("\n") def grow_diag(e_vocab, f_vocab, e_alignment, f_alignment, alignment, union_alignment, directions): prev_len = 0 while prev_len != len(alignment): prev_len = len(alignment) for e in e_vocab: for f in f_vocab: if (e, f) in alignment: for d in directions: en, fn = e + d[0], f + d[1] if (en not in e_alignment or fn not in f_alignment) and (en, fn) in union_alignment: alignment.add((en, fn)) e_alignment.add(en) f_alignment.add(fn) def final(e_vocab, f_vocab, e_alignment, f_alignment, alignment, union_alignment, final_and): for e in e_vocab: for f in f_vocab: c = False if final_and: c = e not in e_alignment and f not in f_alignment else: c = e not in e_alignment or f not in f_alignment if c and (e, f) in union_alignment: alignment.add((e, f)) e_alignment.add(e) f_alignment.add(f) def main(): optparser = optparse.OptionParser() optparser.add_option("-d", "--data", dest="train", default="data/alignment", help="Data filename prefix (default=data)") optparser.add_option("-e", "--e2f", dest="e2f", default="ef", help="Suffix of English to French filename (default=ef)") optparser.add_option("-f", "--f2e", dest="f2e", default="fe", help="Suffix of French to English filename (default=fe)") optparser.add_option("-a", "--final_and", dest="final_and", action="store_true", help="Whether to use Final-And version of the algorithm") (opts, args) = optparser.parse_args() e2f_data = "%s.%s" % (opts.train, opts.e2f) f2e_data = "%s.%s" % (opts.train, opts.f2e) grow_diag_final_and(e2f_data, f2e_data) if __name__ == "__main__": main()
44.232877
142
0.577888
482
3,229
3.661826
0.165975
0.040793
0.031728
0.054391
0.449858
0.315014
0.256657
0.232861
0.177904
0.147309
0
0.023595
0.278105
3,229
72
143
44.847222
0.733591
0
0
0.123077
0
0
0.09043
0
0
0
0
0
0
1
0.076923
false
0
0.030769
0
0.107692
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
715823dd8a36dcb9c1e16c0545d16a02d319badc
2,567
py
Python
tests/test_tbears_db.py
Transcranial-Solutions/t-bears
4712b8bb425814c444ee75f3220a31df934982aa
[ "Apache-2.0" ]
35
2018-08-24T03:39:35.000Z
2021-08-21T23:35:57.000Z
tests/test_tbears_db.py
Transcranial-Solutions/t-bears
4712b8bb425814c444ee75f3220a31df934982aa
[ "Apache-2.0" ]
40
2018-08-24T05:35:54.000Z
2021-12-15T08:23:38.000Z
tests/test_tbears_db.py
Transcranial-Solutions/t-bears
4712b8bb425814c444ee75f3220a31df934982aa
[ "Apache-2.0" ]
22
2018-08-28T15:11:46.000Z
2021-12-01T23:34:45.000Z
# -*- coding: utf-8 -*- # Copyright 2017-2018 ICON Foundation # # 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 os import shutil import unittest from tbears.block_manager.tbears_db import TbearsDB DIRECTORY_PATH = os.path.abspath((os.path.dirname(__file__))) DB_PATH = os.path.join(DIRECTORY_PATH, './.tbears_db') class TestTBearsDB(unittest.TestCase): def setUp(self): self.TBEARS_DB = TbearsDB(TbearsDB.make_db(DB_PATH)) self.test_key = b'test_key' self.test_value = b'test_value' def tearDown(self): self.TBEARS_DB.close() shutil.rmtree(DB_PATH) def test_put_and_get(self): # Put and get self.TBEARS_DB.put(self.test_key, self.test_value) ret = self.TBEARS_DB.get(self.test_key) self.assertEqual(ret, self.test_value) # overwrite overwrite_value = b'test_value_overwrite' self.TBEARS_DB.put(self.test_key, overwrite_value) ret = self.TBEARS_DB.get(self.test_key) self.assertEqual(ret, overwrite_value) # get invalid key ret = self.TBEARS_DB.get(b'invalid_key') self.assertIsNone(ret) # put invalid type self.assertRaises(TypeError, self.TBEARS_DB.put, 'test_key', self.test_value) self.assertRaises(TypeError, self.TBEARS_DB.put, self.test_key, 123) def test_delete(self): self.TBEARS_DB.put(self.test_key, self.test_value) ret = self.TBEARS_DB.get(self.test_key) self.assertEqual(ret, self.test_value) self.TBEARS_DB.delete(self.test_key) ret = self.TBEARS_DB.get(self.test_key) self.assertIsNone(ret) def test_iterator(self): self.TBEARS_DB.put(b'key1', b'value1') self.TBEARS_DB.put(b'key2', b'value2') self.TBEARS_DB.put(b'key3', b'value3') self.TBEARS_DB.put(b'key4', b'value4') i = 1 for _, actual_value in self.TBEARS_DB.iterator(): expected_value = ('value' + str(i)).encode() self.assertEqual(expected_value, actual_value) i += 1
33.776316
85
0.679782
373
2,567
4.50134
0.329759
0.095295
0.128648
0.080405
0.319238
0.252531
0.238237
0.168553
0.168553
0.148898
0
0.012871
0.213089
2,567
75
86
34.226667
0.818317
0.245423
0
0.232558
0
0
0.059437
0
0
0
0
0
0.186047
1
0.116279
false
0
0.093023
0
0.232558
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
715db019834eea3cecfac08bf5fe333bb00487eb
3,658
py
Python
samples/destroy_vm.py
jm66/pyvmomi-community-samples
5ca4a50b767500e07b9bce9fba70240bfa963a4e
[ "Apache-2.0" ]
4
2016-01-04T06:19:56.000Z
2018-09-09T01:03:07.000Z
samples/destroy_vm.py
zhangjiahaol/pyvmomi-community-samples
905ec34edfbd151531832e98b6a0748fa6ff5e0e
[ "Apache-2.0" ]
12
2019-04-17T02:47:25.000Z
2021-04-02T09:15:37.000Z
samples/destroy_vm.py
zhangjiahaol/pyvmomi-community-samples
905ec34edfbd151531832e98b6a0748fa6ff5e0e
[ "Apache-2.0" ]
15
2018-04-26T05:18:12.000Z
2021-11-06T04:44:58.000Z
#!/usr/bin/env python # Copyright 2015 Michael Rice <michael@michaelrice.org> # # 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 __future__ import print_function import atexit from pyVim import connect from pyVmomi import vim from tools import cli from tools import tasks def setup_args(): """Adds additional ARGS to allow the vm name or uuid to be set. """ parser = cli.build_arg_parser() # using j here because -u is used for user parser.add_argument('-j', '--uuid', help='BIOS UUID of the VirtualMachine you want ' 'to destroy.') parser.add_argument('-n', '--name', help='DNS Name of the VirtualMachine you want to ' 'destroy.') parser.add_argument('-i', '--ip', help='IP Address of the VirtualMachine you want to ' 'destroy') parser.add_argument('-v', '--vm', help='VM name of the VirtualMachine you want ' 'to destroy.') my_args = parser.parse_args() return cli.prompt_for_password(my_args) def get_obj(content, vimtype, name): """Create contrainer view and search for object in it""" obj = None container = content.viewManager.CreateContainerView( content.rootFolder, vimtype, True) for c in container.view: if name: if c.name == name: obj = c break else: obj = c break container.Destroy() return obj ARGS = setup_args() SI = None try: SI = connect.SmartConnectNoSSL(host=ARGS.host, user=ARGS.user, pwd=ARGS.password, port=ARGS.port) atexit.register(connect.Disconnect, SI) except (IOError, vim.fault.InvalidLogin): pass if not SI: raise SystemExit("Unable to connect to host with supplied credentials.") VM = None if ARGS.vm: VM = get_obj(SI.content, [vim.VirtualMachine], ARGS.vm) elif ARGS.uuid: VM = SI.content.searchIndex.FindByUuid(None, ARGS.uuid, True, False) elif ARGS.name: VM = SI.content.searchIndex.FindByDnsName(None, ARGS.name, True) elif ARGS.ip: VM = SI.content.searchIndex.FindByIp(None, ARGS.ip, True) if VM is None: raise SystemExit( "Unable to locate VirtualMachine. Arguments given: " "vm - {0} , uuid - {1} , name - {2} , ip - {3}" .format(ARGS.vm, ARGS.uuid, ARGS.name, ARGS.ip) ) print("Found: {0}".format(VM.name)) print("The current powerState is: {0}".format(VM.runtime.powerState)) if format(VM.runtime.powerState) == "poweredOn": print("Attempting to power off {0}".format(VM.name)) TASK = VM.PowerOffVM_Task() tasks.wait_for_tasks(SI, [TASK]) print("{0}".format(TASK.info.state)) print("Destroying VM from vSphere.") TASK = VM.Destroy_Task() tasks.wait_for_tasks(SI, [TASK]) print("Done.")
31.264957
76
0.594587
458
3,658
4.69214
0.40393
0.02792
0.031643
0.040949
0.122383
0.122383
0.122383
0.122383
0.072592
0.072592
0
0.006277
0.303171
3,658
116
77
31.534483
0.836799
0.209677
0
0.103896
0
0.012987
0.171859
0
0
0
0
0
0
1
0.025974
false
0.038961
0.077922
0
0.12987
0.090909
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
71602e883fba7821b66ac710b8b6c9c76a964d73
5,193
py
Python
VirtualStage/BackgroundMatting/fixed_threshold.py
chris-han/ailab
b77d90f9089fa8003095843aa5de718fe73965a7
[ "MIT" ]
null
null
null
VirtualStage/BackgroundMatting/fixed_threshold.py
chris-han/ailab
b77d90f9089fa8003095843aa5de718fe73965a7
[ "MIT" ]
null
null
null
VirtualStage/BackgroundMatting/fixed_threshold.py
chris-han/ailab
b77d90f9089fa8003095843aa5de718fe73965a7
[ "MIT" ]
null
null
null
import os def fixed_split(videos, thresholds, mask_suffix, overlap=0, background_path="/"): # crop target background video frames backgrounds = [os.path.join(background_path, f[:-4]) for f in os.listdir(background_path) if f.endswith(".mp4")] print(f"Splitting {len(backgrounds)} target background videos vertically by a fixed threshold") for i, background in enumerate(backgrounds): if i >= (len(thresholds)) or not thresholds[i]: continue try: os.makedirs(background + "_up") os.makedirs(background + "_dw") except FileExistsError: continue threshold = int(thresholds[i]) iup_region = f"iw:{threshold + overlap}:0:0" idw_region = f"iw:ih-{threshold + overlap}:0:{threshold - overlap}" cmd=( f"ffmpeg -i \"{os.path.join(background, '%04d_img.png')}\" " f'-filter:v "crop={iup_region}" ' f"\"{os.path.join(background+'_up', '%04d_img.png')}\"" " > split_background_logs.txt 2>&1" ) code = os.system( cmd ) if code != 0: exit(code) code = os.system( f"ffmpeg -i \"{os.path.join(background, '%04d_img.png')}\" " f'-filter:v "crop={idw_region}" ' f"\"{os.path.join(background+'_dw', '%04d_img.png')}\"" " > split_background_logs.txt 2>&1" ) if code != 0: exit(code) print(f"Splitting {len(videos)} videos vertically by a fixed threshold") for i, video in enumerate(videos): if i >= (len(thresholds)) or not thresholds[i]: continue try: os.makedirs(video + "_up") os.makedirs(video + "_dw") except FileExistsError: continue threshold = int(thresholds[i]) iup_region = f"iw:{threshold + overlap}:0:0" idw_region = f"iw:ih-{threshold + overlap}:0:{threshold - overlap}" # crop target background single image cmd = ( f"ffmpeg -y -i \"{video+'.png'}\" " f'-filter:v \"crop={iup_region}\" ' f"\"{video+'_up.png'}\"" " > split_logs.txt 2>&1" ) code = os.system( cmd ) if code != 0: exit(code) code = os.system( f"ffmpeg -y -i \"{video+'.png'}\" " f'-filter:v "crop={idw_region}" ' f"\"{video+'_dw.png'}\"" " > split_logs.txt 2>&1" ) if code != 0: exit(code) # crop color images cmd=( f"ffmpeg -i \"{os.path.join(video, '%04d_img.png')}\" " f'-filter:v "crop={iup_region}" ' f"\"{os.path.join(video+'_up', '%04d_img.png')}\"" " > split_logs.txt 2>&1" ) code = os.system( cmd ) if code != 0: exit(code) code = os.system( f"ffmpeg -i \"{os.path.join(video, '%04d_img.png')}\" " f'-filter:v "crop={idw_region}" ' f"\"{os.path.join(video+'_dw', '%04d_img.png')}\"" " > split_logs.txt 2>&1" ) if code != 0: exit(code) # crop mask images code = os.system( f"ffmpeg -i \"{os.path.join(video, '%04d')}{mask_suffix}.png\" " f'-filter:v "crop={iup_region}" ' f"\"{os.path.join(video+'_up', '%04d')}{mask_suffix}.png\"" " > split_logs.txt 2>&1" ) if code != 0: exit(code) code = os.system( f"ffmpeg -i \"{os.path.join(video, '%04d')}{mask_suffix}.png\" " f'-filter:v "crop={idw_region}" ' f"\"{os.path.join(video+'_dw', '%04d')}{mask_suffix}.png\"" " > split_logs.txt 2>&1" ) if code != 0: exit(code) print(f" Splitted {video} ({i+1}/{len(videos)})") def fixed_merge(videos, factors, output_dir, suffix, outputs_list, overlap=0): print(f"Reconstructing {len(videos)} output images") for i, video in enumerate(videos): if i < (len(factors)) and factors[i]: # video split, merging out_path = os.path.join(output_dir, os.path.basename(video)).replace( "\\", "/" ) try: os.makedirs(out_path + suffix) except FileExistsError: continue outpup = (out_path + "_up" + suffix).replace("\\", "/") outpdw = (out_path + "_dw" + suffix).replace("\\", "/") for o in outputs_list: code = os.system( f"ffmpeg -i \"{outpup}/%04d_{o}.png\" -i \"{outpdw}/%04d_{o}.png\" " f'-filter_complex "[0:0]crop=iw:ih-{overlap}:0:0[v0];' f"[1:0]crop=iw:ih-{overlap}:0:{overlap}[v1];" f'[v0][v1]vstack" ' f"\"{out_path + suffix}/%04d_{o}.png\" -hide_banner" " > merge_logs.txt" ) if code != 0: exit(code) print(f" Merged {video} ({i+1}/{len(videos)})")
33.720779
116
0.48238
615
5,193
3.960976
0.15122
0.036946
0.057471
0.04064
0.655993
0.641215
0.610837
0.599754
0.560345
0.516831
0
0.023084
0.349316
5,193
153
117
33.941176
0.69784
0.024456
0
0.611111
0
0.007937
0.259684
0.04585
0
0
0
0
0
1
0.015873
false
0
0.007937
0
0.02381
0.039683
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
7160d131d6077709c38251321b7619b34bcdeab7
7,041
py
Python
hn2016_falwa/utilities.py
veredsil/hn2016_falwa
53035ac838860dd8a8d85619f16cc9785dee8655
[ "MIT" ]
null
null
null
hn2016_falwa/utilities.py
veredsil/hn2016_falwa
53035ac838860dd8a8d85619f16cc9785dee8655
[ "MIT" ]
null
null
null
hn2016_falwa/utilities.py
veredsil/hn2016_falwa
53035ac838860dd8a8d85619f16cc9785dee8655
[ "MIT" ]
null
null
null
import numpy as np from math import pi,exp def static_stability(height,area,theta,s_et=None,n_et=None): """ The function "static_stability" computes the vertical gradient (z-derivative) of hemispheric-averaged potential temperature, i.e. d\tilde{theta}/dz in the def- inition of QGPV in eq.(3) of Huang and Nakamura (2016), by central differencing. At the boundary, the static stability is estimated by forward/backward differen- cing involving two adjacent z-grid points: i.e. stat_n[0] = (t0_n[1]-t0_n[0])/(height[1]-height[0]) stat_n[-1] = (t0_n[-2]-t0_n[-1])/(height[-2]-height[-1]) Please make inquiries and report issues via Github: https://github.com/csyhuang/hn2016_falwa/issues Parameters ---------- height : sequence or array_like Array of z-coordinate [in meters] with dimension = (kmax), equally spaced area : ndarray Two-dimension numpy array specifying differential areal element of each grid point; dimension = (nlat, nlon). theta : ndarray Matrix of potential temperature [K] with dimension (kmax,nlat,nlon) or (kmax,nlat) s_et : int, optional Index of the latitude that defines the boundary of the Southern hemispheric domain; initialized as nlat/2 if not input n_et : int, optional Index of the latitude that defines the boundary of the Southern hemispheric domain; initialized as nlat/2 if not input Returns ------- t0_n : sequence or array_like Area-weighted average of potential temperature (\tilde{\theta} in HN16) in the Northern hemispheric domain with dimension = (kmax) t0_s : sequence or array_like Area-weighted average of potential temperature (\tilde{\theta} in HN16) in the Southern hemispheric domain with dimension = (kmax) stat_n : sequence or array_like Static stability (d\tilde{\theta}/dz in HN16) in the Northern hemispheric domain with dimension = (kmax) stat_s : sequence or array_like Static stability (d\tilde{\theta}/dz in HN16) in the Southern hemispheric domain with dimension = (kmax) """ nlat = theta.shape[1] if s_et==None: s_et = nlat//2 if n_et==None: n_et = nlat//2 stat_n = np.zeros(theta.shape[0]) stat_s = np.zeros(theta.shape[0]) if theta.ndim==3: zonal_mean = np.mean(theta,axis=-1) elif theta.ndim==2: zonal_mean = theta if area.ndim==2: area_zonal_mean = np.mean(area,axis=-1) elif area.ndim==1: area_zonal_mean = area csm_n_et = np.sum(area_zonal_mean[-n_et:]) csm_s_et = np.sum(area_zonal_mean[:s_et]) t0_n = np.sum(zonal_mean[:,-n_et:]*area_zonal_mean[np.newaxis,-n_et:],axis=-1)/csm_n_et t0_s = np.sum(zonal_mean[:,:s_et]*area_zonal_mean[np.newaxis,:s_et],axis=-1)/csm_s_et stat_n[1:-1] = (t0_n[2:]-t0_n[:-2])/(height[2:]-height[:-2]) stat_s[1:-1] = (t0_s[2:]-t0_s[:-2])/(height[2:]-height[:-2]) stat_n[0] = (t0_n[1]-t0_n[0])/(height[1]-height[0]) stat_n[-1] = (t0_n[-2]-t0_n[-1])/(height[-2]-height[-1]) stat_s[0] = (t0_s[1]-t0_s[0])/(height[1]-height[0]) stat_s[-1] = (t0_s[-2]-t0_s[-1])/(height[-2]-height[-1]) return t0_n,t0_s,stat_n,stat_s def compute_qgpv_givenvort(omega,nlat,nlon,kmax,unih,ylat,avort,potential_temp, t0_cn,t0_cs,stat_cn,stat_cs,nlat_s=None,scale_height=7000.): """ The function "compute_qgpv_givenvort" computes the quasi-geostrophic potential vorticity based on the absolute vorticity, potential temperature and static stability given. Please make inquiries and report issues via Github: https://github.com/csyhuang/hn2016_falwa/issues Parameters ---------- omega : float, optional Rotation rate of the planet. nlat : int Latitudinal dimension of the latitude grid. nlon : int Longitudinal dimension of the longitude grid. kmax : int Vertical dimension of the height grid. unih : sequence or array_like Numpy array of height in [meters]; dimension = (kmax) ylat : sequence or array_like Numpy array of latitudes in [degrees]; dimension = (nlat) avort : ndarray Three-dimension numpy array of absolute vorticity (i.e. relative vorticity + 2*Omega*sin(lat)) in [1/s]; dimension = (kmax x nlat x nlon) potential_temp : ndarray Three-dimension numpy array of potential temperature in [K]; dimension = (kmax x nlat x nlon) t0_cn : sequence or array_like Area-weighted average of potential temperature (\tilde{\theta} in HN16) in the Northern hemispheric domain with dimension = (kmax) t0_cs : sequence or array_like Area-weighted average of potential temperature (\tilde{\theta} in HN16) in the Southern hemispheric domain with dimension = (kmax) stat_cn : sequence or array_like Static stability (d\tilde{\theta}/dz in HN16) in the Northern hemispheric domain with dimension = (kmax) stat_cs : sequence or array_like Static stability (d\tilde{\theta}/dz in HN16) in the Southern hemispheric domain with dimension = (kmax) scale_height : float Scale height of the atmosphere in [m] with default value 7000. Returns ------- QGPV : ndarray Three-dimension numpy array of quasi-geostrophic potential vorticity; dimension = (kmax x nlat x nlon) dzdiv : ndarray Three-dimension numpy array of the stretching term in QGPV; dimension = (kmax x nlat x nlon) """ if nlat_s==None: nlat_s=nlat//2 clat = np.cos(ylat*pi/180.) clat = np.abs(clat) # Just to avoid the negative value at poles # --- Next, calculate PV --- av2 = np.empty_like(potential_temp) # dv/d(lon) av3 = np.empty_like(potential_temp) # du/d(lat) qgpv = np.empty_like(potential_temp) # av1+av2+av3+dzdiv av1 = np.ones((kmax,nlat,nlon)) * 2*omega*np.sin(ylat[np.newaxis,:,np.newaxis]*pi/180.) # Calculate the z-divergence term zdiv = np.empty_like(potential_temp) dzdiv = np.empty_like(potential_temp) for kk in range(kmax): # This is more efficient zdiv[kk,:nlat_s,:] = exp(-unih[kk]/scale_height)*(potential_temp[kk,:nlat_s,:]-t0_cs[kk])/stat_cs[kk] zdiv[kk,-nlat_s:,:] = exp(-unih[kk]/scale_height)*(potential_temp[kk,-nlat_s:,:]-t0_cn[kk])/stat_cn[kk] dzdiv[1:kmax-1,:,:] = np.exp(unih[1:kmax-1,np.newaxis,np.newaxis]/scale_height)* \ (zdiv[2:kmax,:,:]-zdiv[0:kmax-2,:,:]) \ /(unih[2:kmax,np.newaxis,np.newaxis]-unih[0:kmax-2,np.newaxis,np.newaxis]) dzdiv[0,:,:] = exp(unih[0]/scale_height)*(zdiv[1,:,:]-zdiv[0,:,:])/ \ (unih[1,np.newaxis,np.newaxis]-unih[0,np.newaxis,np.newaxis]) dzdiv[kmax-1,:,:] = exp(unih[kmax-1]/scale_height)*(zdiv[kmax-1,:,:]-zdiv[kmax-2,:,:])/ \ (unih[kmax-1,np.newaxis,np.newaxis]-unih[kmax-2,np.newaxis,np.newaxis]) qgpv = avort+dzdiv * av1 return qgpv, dzdiv
40.234286
111
0.656441
1,078
7,041
4.164193
0.180891
0.036088
0.036757
0.046558
0.524838
0.474493
0.355981
0.34217
0.34217
0.34217
0
0.029082
0.213748
7,041
174
112
40.465517
0.781792
0.581452
0
0
0
0
0
0
0
0
0
0
0
1
0.037736
false
0
0.037736
0
0.113208
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
7160dc5984a5a68781b1f9dc71bfe52a6ee535f4
12,570
py
Python
src/command_modules/azure-cli-iot/azure/cli/command_modules/iot/_params.py
JennyLawrance/azure-cli
cb9ca4b694110806b31803a95f9f315b2fde6410
[ "MIT" ]
null
null
null
src/command_modules/azure-cli-iot/azure/cli/command_modules/iot/_params.py
JennyLawrance/azure-cli
cb9ca4b694110806b31803a95f9f315b2fde6410
[ "MIT" ]
null
null
null
src/command_modules/azure-cli-iot/azure/cli/command_modules/iot/_params.py
JennyLawrance/azure-cli
cb9ca4b694110806b31803a95f9f315b2fde6410
[ "MIT" ]
null
null
null
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from argcomplete.completers import FilesCompleter from knack.arguments import CLIArgumentType from azure.cli.core.commands.parameters import (get_location_type, file_type, get_resource_name_completion_list, get_enum_type, get_three_state_flag) from azure.mgmt.iothub.models.iot_hub_client_enums import IotHubSku from azure.mgmt.iothubprovisioningservices.models.iot_dps_client_enums import (IotDpsSku, AllocationPolicy, AccessRightsDescription) from .custom import KeyType, SimpleAccessRights from ._validators import validate_policy_permissions from ._completers import get_device_id_completion_list hub_name_type = CLIArgumentType( completer=get_resource_name_completion_list('Microsoft.Devices/IotHubs'), help='IoT Hub name.') dps_name_type = CLIArgumentType( options_list=['--dps-name'], completer=get_resource_name_completion_list('Microsoft.Devices/ProvisioningServices'), help='IoT Provisioning Service name') def load_arguments(self, _): # pylint: disable=too-many-statements # Arguments for IoT DPS with self.argument_context('iot dps') as c: c.argument('dps_name', dps_name_type, options_list=['--name', '-n'], id_part='name') with self.argument_context('iot dps create') as c: c.argument('location', get_location_type(self.cli_ctx), help='Location of your IoT Provisioning Service. Default is the location of target resource group.') c.argument('sku', arg_type=get_enum_type(IotDpsSku), help='Pricing tier for the IoT provisioning service.') c.argument('unit', help='Units in your IoT Provisioning Service.', type=int) for subgroup in ['access-policy', 'linked-hub', 'certificate']: with self.argument_context('iot dps {}'.format(subgroup)) as c: c.argument('dps_name', options_list=['--dps-name'], id_part=None) with self.argument_context('iot dps access-policy') as c: c.argument('access_policy_name', options_list=['--access-policy-name', '--name', '-n'], help='A friendly name for DPS access policy.') with self.argument_context('iot dps access-policy create') as c: c.argument('rights', options_list=['--rights', '-r'], nargs='+', arg_type=get_enum_type(AccessRightsDescription), help='Access rights for the IoT provisioning service. Use space-separated list for multiple rights.') c.argument('primary_key', help='Primary SAS key value.') c.argument('secondary_key', help='Secondary SAS key value.') with self.argument_context('iot dps access-policy update') as c: c.argument('rights', options_list=['--rights', '-r'], nargs='+', arg_type=get_enum_type(AccessRightsDescription), help='Access rights for the IoT provisioning service. Use space-separated list for multiple rights.') c.argument('primary_key', help='Primary SAS key value.') c.argument('secondary_key', help='Secondary SAS key value.') with self.argument_context('iot dps linked-hub') as c: c.argument('linked_hub', options_list=['--linked-hub'], help='Host name of linked IoT Hub.') with self.argument_context('iot dps linked-hub create') as c: c.argument('connection_string', help='Connection string of the IoT hub.') c.argument('location', get_location_type(self.cli_ctx), help='Location of the IoT hub.') c.argument('apply_allocation_policy', help='A boolean indicating whether to apply allocation policy to the IoT hub.', arg_type=get_three_state_flag()) c.argument('allocation_weight', help='Allocation weight of the IoT hub.') with self.argument_context('iot dps linked-hub update') as c: c.argument('apply_allocation_policy', help='A boolean indicating whether to apply allocation policy to the Iot hub.', arg_type=get_three_state_flag()) c.argument('allocation_weight', help='Allocation weight of the IoT hub.') with self.argument_context('iot dps allocation-policy update') as c: c.argument('allocation_policy', options_list=['--policy', '-p'], arg_type=get_enum_type(AllocationPolicy), help='Allocation policy for the IoT provisioning service.') with self.argument_context('iot dps certificate') as c: c.argument('certificate_path', options_list=['--path', '-p'], type=file_type, completer=FilesCompleter([".cer", ".pem"]), help='The path to the file containing the certificate.') c.argument('certificate_name', options_list=['--certificate-name', '--name', '-n'], help='A friendly name for the certificate.') c.argument('etag', options_list=['--etag', '-e'], help='Entity Tag (etag) of the object.') # Arguments for IoT Hub with self.argument_context('iot') as c: c.argument('device_id', options_list=['--device-id', '-d'], help='Device Id.', completer=get_device_id_completion_list) with self.argument_context('iot hub') as c: c.argument('hub_name', hub_name_type, options_list=['--name', '-n'], id_part='name') c.argument('etag', options_list=['--etag', '-e'], help='Entity Tag (etag) of the object.') for subgroup in ['consumer-group', 'policy', 'job', 'certificate']: with self.argument_context('iot hub {}'.format(subgroup)) as c: c.argument('hub_name', options_list=['--hub-name']) with self.argument_context('iot device') as c: c.argument('hub_name', hub_name_type) with self.argument_context('iot hub certificate') as c: c.argument('certificate_path', options_list=['--path', '-p'], type=file_type, completer=FilesCompleter([".cer", ".pem"]), help='The path to the file containing the certificate.') c.argument('certificate_name', options_list=['--name', '-n'], help='A friendly name for the certificate.') with self.argument_context('iot hub consumer-group') as c: c.argument('consumer_group_name', options_list=['--name', '-n'], id_part='child_name_2', help='Event hub consumer group name.') c.argument('event_hub_name', id_part='child_name_1', help='Event hub endpoint name.') with self.argument_context('iot hub policy') as c: c.argument('policy_name', options_list=['--name', '-n'], id_part='child_name_1', help='Shared access policy name.') permission_values = ', '.join([x.value for x in SimpleAccessRights]) c.argument('permissions', nargs='*', validator=validate_policy_permissions, type=str.lower, help='Permissions of shared access policy. Use space-separated list for multiple permissions. ' 'Possible values: {}'.format(permission_values)) with self.argument_context('iot hub job') as c: c.argument('job_id', id_part='child_name_1', help='Job Id.') with self.argument_context('iot hub create') as c: c.argument('hub_name', completer=None) c.argument('location', get_location_type(self.cli_ctx), help='Location of your IoT Hub. Default is the location of target resource group.') c.argument('sku', arg_type=get_enum_type(IotHubSku), help='Pricing tier for Azure IoT Hub. Default value is F1, which is free. ' 'Note that only one free IoT hub instance is allowed in each ' 'subscription. Exception will be thrown if free instances exceed one.') c.argument('unit', help='Units in your IoT Hub.', type=int) c.argument('partition_count', help='The number of partitions for device-to-cloud messages.', type=int) with self.argument_context('iot hub show-connection-string') as c: c.argument('policy_name', help='Shared access policy to use.') c.argument('key_type', arg_type=get_enum_type(KeyType), options_list=['--key'], help='The key to use.') with self.argument_context('iot device create') as c: c.argument('device_id', completer=None) with self.argument_context('iot device create', arg_group='X.509 Certificate') as c: c.argument('x509', action='store_true', help='Use X.509 certificate for device authentication.') c.argument('primary_thumbprint', help='Primary X.509 certificate thumbprint to authenticate device.') c.argument('secondary_thumbprint', help='Secondary X.509 certificate thumbprint to authenticate device.') c.argument('valid_days', type=int, help='Number of days the generated self-signed X.509 certificate should be ' 'valid for. Default validity is 365 days.') c.argument('output_dir', help='Output directory for generated self-signed X.509 certificate. ' 'Default is current working directory.') with self.argument_context('iot device list') as c: c.argument('top', help='Maximum number of device identities to return.', type=int) with self.argument_context('iot device delete') as c: c.argument('etag', help='ETag of the target device. It is used for the purpose of optimistic ' 'concurrency. Delete operation will be performed only if the specified ' 'ETag matches the value maintained by the server, indicating that the ' 'device identity has not been modified since it was retrieved. Default ' 'value is set to wildcard character (*) to force an unconditional ' 'delete.') with self.argument_context('iot device show-connection-string') as c: c.argument('top', type=int, help='Maximum number of connection strings to return.') c.argument('key_type', arg_type=get_enum_type(KeyType), options_list=['--key'], help='The key to use.') with self.argument_context('iot device message') as c: c.argument('lock_token', help='Message lock token.') with self.argument_context('iot device message send', arg_group='Messaging') as c: c.argument('data', help='Device-to-cloud message body.') c.argument('message_id', help='Device-to-cloud message Id.') c.argument('correlation_id', help='Device-to-cloud message correlation Id.') c.argument('user_id', help='Device-to-cloud message user Id.') with self.argument_context('iot device message receive') as c: c.argument('lock_timeout', type=int, help='In case a message returned to this call, this specifies the amount of ' 'time in seconds, the message will be invisible to other receive calls.') with self.argument_context('iot device export') as c: c.argument('blob_container_uri', help='Blob Shared Access Signature URI with write access to a blob container.' 'This is used to output the status of the job and the results.') c.argument('include_keys', action='store_true', help='If set, keys are exported normally. Otherwise, keys are set to null in ' 'export output.') with self.argument_context('iot device import') as c: c.argument('input_blob_container_uri', help='Blob Shared Access Signature URI with read access to a blob container.' 'This blob contains the operations to be performed on the identity ' 'registry ') c.argument('output_blob_container_uri', help='Blob Shared Access Signature URI with write access to a blob container.' 'This is used to output the status of the job and the results.')
61.019417
120
0.631344
1,579
12,570
4.886637
0.177961
0.072317
0.064282
0.092405
0.60057
0.55845
0.434552
0.387895
0.348237
0.299508
0
0.003044
0.242084
12,570
205
121
61.317073
0.806865
0.033095
0
0.192547
0
0
0.415857
0.016631
0
0
0
0
0
1
0.006211
false
0
0.055901
0
0.062112
0.012422
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
7160eb99604d70299eb40716235e949ffc576a16
3,280
py
Python
metrics-calculator/tests/integration/test_s3.py
nhsconnect/prm-practice-migration-dashboard
40c8760f409834d05bde4fb015aa5f8765acaa82
[ "0BSD" ]
null
null
null
metrics-calculator/tests/integration/test_s3.py
nhsconnect/prm-practice-migration-dashboard
40c8760f409834d05bde4fb015aa5f8765acaa82
[ "0BSD" ]
null
null
null
metrics-calculator/tests/integration/test_s3.py
nhsconnect/prm-practice-migration-dashboard
40c8760f409834d05bde4fb015aa5f8765acaa82
[ "0BSD" ]
null
null
null
import boto3 import gzip from moto import mock_s3 import pytest import os from chalicelib.s3 import read_object_s3, write_object_s3, objects_exist from tests.builders.file import build_gzip_csv @pytest.fixture(scope='function') def aws_credentials(): """Mocked AWS Credentials for moto.""" os.environ['AWS_ACCESS_KEY_ID'] = 'testing' os.environ['AWS_SECRET_ACCESS_KEY'] = 'testing' os.environ['AWS_SECURITY_TOKEN'] = 'testing' os.environ['AWS_SESSION_TOKEN'] = 'testing' os.environ['AWS_DEFAULT_REGION'] = 'us-east-1' @pytest.fixture(scope='function') def s3(aws_credentials): with mock_s3(): yield boto3.resource('s3', region_name='us-east-1') @mock_s3 def test_read_object_s3_returns_object_content(s3): bucket = s3.create_bucket(Bucket="test_bucket") s3_object = bucket.Object("test_object.csv.gz") gzipped_content = build_gzip_csv( header=["id", "message", "comment"], rows=[["123", "A message", "A comment"], [ "321", "Another message", "Another comment"]], ) s3_object.put( Body=gzipped_content ) expected = "id,message,comment\n123,A message,A comment\n321,Another message,Another comment" csv_stream = read_object_s3(s3, "s3://test_bucket/test_object.csv.gz") with gzip.open(csv_stream, mode="rt") as f: actual = f.read() assert actual == expected @mock_s3 def test_write_object_s3_writes_object_content(s3): s3.create_bucket(Bucket="test_bucket") json_string = b'{"fruit": "mango"}' write_object_s3(s3, "s3://test_bucket/test_object.json", json_string) s3_object_response = s3.Object("test_bucket", "test_object.json").get() assert s3_object_response["Body"].read() == json_string @mock_s3 def test_write_object_s3_writes_object_content_with_metadata(s3): s3.create_bucket(Bucket="test_bucket") json_string = b'{"fruit": "mango"}' metadata = { "start_date": "start-date", "end_date": "end-date" } write_object_s3(s3, "s3://test_bucket/test_object.json", json_string, metadata) s3_object_response = s3.Object("test_bucket", "test_object.json").get() assert s3_object_response["Metadata"] == metadata @mock_s3 def test_objects_exist_returns_true_when_all_objects_exist(s3): s3.create_bucket(Bucket="test_bucket") object_one = "object-one" object_two = "object-two" write_object_s3(s3, f"s3://test_bucket/{object_one}", 'object-one-content') write_object_s3(s3, f"s3://test_bucket/{object_two}", 'object-two-content') result = objects_exist(s3, "test_bucket", [object_one, object_two]) assert result @mock_s3 def test_objects_exist_returns_false_when_only_one_object_exists(s3): s3.create_bucket(Bucket="test_bucket") object_one = "object-one" object_two = "object-two" write_object_s3(s3, f"s3://test_bucket/{object_one}", 'object-one-content') result = objects_exist(s3, "test_bucket", [object_one, object_two]) assert not result @mock_s3 def test_objects_exist_returns_false_when_no_objects_exist(s3): s3.create_bucket(Bucket="test_bucket") object_one = "object-one" object_two = "object-two" result = objects_exist(s3, "test_bucket", [object_one, object_two]) assert not result
28.521739
97
0.710366
468
3,280
4.643162
0.207265
0.078233
0.075932
0.069949
0.592269
0.543488
0.529682
0.514956
0.50023
0.484584
0
0.026354
0.155488
3,280
114
98
28.77193
0.758123
0.009756
0
0.38961
0
0.012987
0.266502
0.072178
0
0
0
0
0.077922
1
0.103896
false
0
0.090909
0
0.194805
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
716145a9d2a82e68a98031ac79781824db56e9c8
13,528
py
Python
image_analogy/losses/patch_matcher.py
kaldap/image-analogies
0867aedfae7dfc0d27c42805a3d07f7b9eb7eaa2
[ "MIT" ]
3,722
2016-02-28T18:03:51.000Z
2022-03-29T18:03:30.000Z
image_analogy/losses/patch_matcher.py
germanmad/image-analogies
066626149ccb96b0a0488ca7ea4fc992aa62b727
[ "MIT" ]
58
2016-02-28T03:23:43.000Z
2022-03-11T23:14:08.000Z
image_analogy/losses/patch_matcher.py
germanmad/image-analogies
066626149ccb96b0a0488ca7ea4fc992aa62b727
[ "MIT" ]
351
2016-03-05T03:22:48.000Z
2022-03-01T09:06:33.000Z
import numpy as np import scipy.interpolate import scipy.ndimage from sklearn.feature_extraction.image import extract_patches_2d, reconstruct_from_patches_2d def _calc_patch_grid_dims(shape, patch_size, patch_stride): x_w, x_h, x_c = shape num_rows = 1 + (x_h - patch_size) // patch_stride num_cols = 1 + (x_w - patch_size) // patch_stride return num_rows, num_cols def make_patch_grid(x, patch_size, patch_stride=1): '''x shape: (num_channels, rows, cols)''' x = x.transpose(2, 1, 0) patches = extract_patches_2d(x, (patch_size, patch_size)) x_w, x_h, x_c = x.shape num_rows, num_cols = _calc_patch_grid_dims(x.shape, patch_size, patch_stride) patches = patches.reshape((num_rows, num_cols, patch_size, patch_size, x_c)) patches = patches.transpose((0, 1, 4, 2, 3)) #patches = np.rollaxis(patches, -1, 2) return patches def combine_patches_grid(in_patches, out_shape): '''Reconstruct an image from these `patches` input shape: (rows, cols, channels, patch_row, patch_col) ''' num_rows, num_cols = in_patches.shape[:2] num_channels = in_patches.shape[-3] patch_size = in_patches.shape[-1] num_patches = num_rows * num_cols in_patches = np.reshape(in_patches, (num_patches, num_channels, patch_size, patch_size)) # (patches, channels, pr, pc) in_patches = np.transpose(in_patches, (0, 2, 3, 1)) # (patches, p, p, channels) recon = reconstruct_from_patches_2d(in_patches, out_shape) return recon.transpose(2, 1, 0).astype(np.float32) class PatchMatcher(object): '''A matcher of image patches inspired by the PatchMatch algorithm. image shape: (width, height, channels) ''' def __init__(self, input_shape, target_img, patch_size=1, patch_stride=1, jump_size=0.5, num_propagation_steps=5, num_random_steps=5, random_max_radius=1.0, random_scale=0.5): self.input_shape = input_shape self.patch_size = patch_size self.patch_stride = patch_stride self.jump_size = jump_size self.num_propagation_steps = num_propagation_steps self.num_random_steps = num_random_steps self.random_max_radius = random_max_radius self.random_scale = random_scale self.num_input_rows, self.num_input_cols = _calc_patch_grid_dims(input_shape, patch_size, patch_stride) self.target_patches = make_patch_grid(target_img, patch_size) self.target_patches_normed = self.normalize_patches(self.target_patches) self.coords = np.random.uniform(0.0, 1.0, # TODO: switch to pixels (2, self.num_input_rows, self.num_input_cols))# * [[[self.num_input_rows]],[[self.num_input_cols]]] self.similarity = np.zeros(input_shape[:2:-1], dtype=np.float32) self.min_propagration_row = 1.0 / self.num_input_rows self.min_propagration_col = 1.0 / self.num_input_cols self.delta_row = np.array([[[self.min_propagration_row]], [[0.0]]]) self.delta_col = np.array([[[0.0]], [[self.min_propagration_col]]]) def update(self, input_img, reverse_propagation=False): input_patches = self.get_patches_for(input_img) self.update_with_patches(self.normalize_patches(input_patches), reverse_propagation=reverse_propagation) def update_with_patches(self, input_patches, reverse_propagation=False): self._propagate(input_patches, reverse_propagation=reverse_propagation) self._random_update(input_patches) def get_patches_for(self, img): return make_patch_grid(img, self.patch_size); def normalize_patches(self, patches): norm = np.sqrt(np.sum(np.square(patches), axis=(2, 3, 4), keepdims=True)) return patches / norm def _propagate(self, input_patches, reverse_propagation=False): if reverse_propagation: roll_direction = 1 else: roll_direction = -1 sign = float(roll_direction) for step_i in range(self.num_propagation_steps): new_coords = self.clip_coords(np.roll(self.coords, roll_direction, 1) + self.delta_row * sign) coords_row, similarity_row = self.eval_state(new_coords, input_patches) new_coords = self.clip_coords(np.roll(self.coords, roll_direction, 2) + self.delta_col * sign) coords_col, similarity_col = self.eval_state(new_coords, input_patches) self.coords, self.similarity = self.take_best(coords_row, similarity_row, coords_col, similarity_col) def _random_update(self, input_patches): for alpha in range(1, self.num_random_steps + 1): # NOTE this should actually stop when the move is < 1 new_coords = self.clip_coords(self.coords + np.random.uniform(-self.random_max_radius, self.random_max_radius, self.coords.shape) * self.random_scale ** alpha) self.coords, self.similarity = self.eval_state(new_coords, input_patches) def eval_state(self, new_coords, input_patches): new_similarity = self.patch_similarity(input_patches, new_coords) delta_similarity = new_similarity - self.similarity coords = np.where(delta_similarity > 0, new_coords, self.coords) best_similarity = np.where(delta_similarity > 0, new_similarity, self.similarity) return coords, best_similarity def take_best(self, coords_a, similarity_a, coords_b, similarity_b): delta_similarity = similarity_a - similarity_b best_coords = np.where(delta_similarity > 0, coords_a, coords_b) best_similarity = np.where(delta_similarity > 0, similarity_a, similarity_b) return best_coords, best_similarity def patch_similarity(self, source, coords): '''Check the similarity of the patches specified in coords.''' target_vals = self.lookup_coords(self.target_patches_normed, coords) err = source * target_vals return np.sum(err, axis=(2, 3, 4)) def clip_coords(self, coords): # TODO: should this all be in pixel space? coords = np.clip(coords, 0.0, 1.0) return coords def lookup_coords(self, x, coords): x_shape = np.expand_dims(np.expand_dims(x.shape, -1), -1) i_coords = np.round(coords * (x_shape[:2] - 1)).astype('int32') return x[i_coords[0], i_coords[1]] def get_reconstruction(self, patches=None, combined=None): if combined is not None: patches = make_patch_grid(combined, self.patch_size) if patches is None: patches = self.target_patches patches = self.lookup_coords(patches, self.coords) recon = combine_patches_grid(patches, self.input_shape) return recon def scale(self, new_shape, new_target_img): '''Create a new matcher of the given shape and replace its state with a scaled up version of the current matcher's state. ''' new_matcher = PatchMatcher(new_shape, new_target_img, patch_size=self.patch_size, patch_stride=self.patch_stride, jump_size=self.jump_size, num_propagation_steps=self.num_propagation_steps, num_random_steps=self.num_random_steps, random_max_radius=self.random_max_radius, random_scale=self.random_scale) new_matcher.coords = congrid(self.coords, new_matcher.coords.shape, method='neighbour') new_matcher.similarity = congrid(self.similarity, new_matcher.coords.shape, method='neighbour') return new_matcher def congrid(a, newdims, method='linear', centre=False, minusone=False): '''Arbitrary resampling of source array to new dimension sizes. Currently only supports maintaining the same number of dimensions. To use 1-D arrays, first promote them to shape (x,1). Uses the same parameters and creates the same co-ordinate lookup points as IDL''s congrid routine, which apparently originally came from a VAX/VMS routine of the same name. method: neighbour - closest value from original data nearest and linear - uses n x 1-D interpolations using scipy.interpolate.interp1d (see Numerical Recipes for validity of use of n 1-D interpolations) spline - uses ndimage.map_coordinates centre: True - interpolation points are at the centres of the bins False - points are at the front edge of the bin minusone: For example- inarray.shape = (i,j) & new dimensions = (x,y) False - inarray is resampled by factors of (i/x) * (j/y) True - inarray is resampled by(i-1)/(x-1) * (j-1)/(y-1) This prevents extrapolation one element beyond bounds of input array. ''' if not a.dtype in [np.float64, np.float32]: a = np.cast[float](a) m1 = np.cast[int](minusone) ofs = np.cast[int](centre) * 0.5 old = np.array( a.shape ) ndims = len( a.shape ) if len( newdims ) != ndims: print("[congrid] dimensions error. " \ "This routine currently only support " \ "rebinning to the same number of dimensions.") return None newdims = np.asarray( newdims, dtype=float ) dimlist = [] if method == 'neighbour': for i in range( ndims ): base = np.indices(newdims)[i] dimlist.append( (old[i] - m1) / (newdims[i] - m1) \ * (base + ofs) - ofs ) cd = np.array( dimlist ).round().astype(int) newa = a[list( cd )] return newa elif method in ['nearest','linear']: # calculate new dims for i in range( ndims ): base = np.arange( newdims[i] ) dimlist.append( (old[i] - m1) / (newdims[i] - m1) \ * (base + ofs) - ofs ) # specify old dims olddims = [np.arange(i, dtype = np.float) for i in list( a.shape )] # first interpolation - for ndims = any mint = scipy.interpolate.interp1d( olddims[-1], a, kind=method ) newa = mint( dimlist[-1] ) trorder = [ndims - 1] + range( ndims - 1 ) for i in range( ndims - 2, -1, -1 ): newa = newa.transpose( trorder ) mint = scipy.interpolate.interp1d( olddims[i], newa, kind=method ) newa = mint( dimlist[i] ) if ndims > 1: # need one more transpose to return to original dimensions newa = newa.transpose( trorder ) return newa elif method in ['spline']: oslices = [ slice(0,j) for j in old ] oldcoords = np.ogrid[oslices] nslices = [ slice(0,j) for j in list(newdims) ] newcoords = np.mgrid[nslices] newcoords_dims = range(np.rank(newcoords)) #make first index last newcoords_dims.append(newcoords_dims.pop(0)) newcoords_tr = newcoords.transpose(newcoords_dims) # makes a view that affects newcoords newcoords_tr += ofs deltas = (np.asarray(old) - m1) / (newdims - m1) newcoords_tr *= deltas newcoords_tr -= ofs newa = scipy.ndimage.map_coordinates(a, newcoords) return newa else: print("Congrid error: Unrecognized interpolation type.\n", \ "Currently only \'neighbour\', \'nearest\',\'linear\',", \ "and \'spline\' are supported.") return None if __name__ == '__main__': import sys import time from scipy.misc import imsave from image_analogy.img_utils import load_image, preprocess_image, deprocess_image content_image_path, style_image_path, output_prefix = sys.argv[1:] jump_size = 1.0 num_steps = 7 patch_size = 1 patch_stride = 1 feat_chans = 512 feat_style_shape = (feat_chans, 12, 18) feat_style = np.random.uniform(0.0, 1.0, feat_style_shape) feat_in_shape = (feat_chans, 17, 10) feat_in = np.random.uniform(0.0, 1.0, feat_in_shape) matcher = PatchMatcher(feat_in_shape[::-1], feat_style, patch_size=patch_size) feat_in_normed = matcher.normalize_patches(matcher.get_patches_for(feat_in)) for i in range(num_steps): matcher.update_with_patches(feat_in_normed) r = matcher.get_reconstruction() content_img_img = load_image(content_image_path) content_n_channels, content_n_rows, content_n_cols = content_img_img.shape[::-1] content_img = preprocess_image(content_img_img, content_n_cols, content_n_rows)[0]#.transpose((2,1,0)) style_img = load_image(style_image_path) style_n_channels, style_n_rows, style_n_cols = content_img_img.shape[::-1] style_img = preprocess_image( load_image(style_image_path), style_n_cols, style_n_rows)[0]#.transpose((2,1,0)) pg = make_patch_grid(content_img, patch_size) result = combine_patches_grid(pg, content_img.shape[::-1]) outimg = deprocess_image(result, contrast_percent=0) imsave(output_prefix + '_bestre.png', outimg) # # # matcher = PatchMatcher((content_n_cols, content_n_rows, content_n_channels), style_img, patch_size=patch_size) for i in range(num_steps): start = time.time() matcher.update(content_img, reverse_propagation=bool(i % 2)) print(matcher.similarity.min(), matcher.similarity.max(), matcher.similarity.mean()) end = time.time() #print end-start start = time.time() result = matcher.get_reconstruction(patches=matcher.target_patches) print(result.shape) end = time.time() print(end-start) outimg = deprocess_image(result, contrast_percent=0) # # imsave takes (rows, cols, channels) imsave(output_prefix + '_best.png', outimg)
43.922078
171
0.671348
1,874
13,528
4.601387
0.173959
0.02818
0.021106
0.016236
0.272527
0.168851
0.103096
0.051026
0.030848
0.022962
0
0.015261
0.225015
13,528
307
172
44.065147
0.80723
0.14385
0
0.106977
0
0
0.028296
0.002015
0
0
0
0.003257
0
1
0.083721
false
0
0.037209
0.004651
0.204651
0.023256
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
7161bb83a934c99f17f3988c15fe48d8592c6f29
1,247
py
Python
rllib/agents/ppo/tests/test_appo.py
noahshpak/ray
edd783bc327760a4892ab89222ee551e42df15b9
[ "Apache-2.0" ]
2
2020-02-17T17:36:23.000Z
2020-08-24T19:59:18.000Z
rllib/agents/ppo/tests/test_appo.py
noahshpak/ray
edd783bc327760a4892ab89222ee551e42df15b9
[ "Apache-2.0" ]
8
2020-11-13T19:02:47.000Z
2022-03-12T00:44:51.000Z
rllib/agents/ppo/tests/test_appo.py
noahshpak/ray
edd783bc327760a4892ab89222ee551e42df15b9
[ "Apache-2.0" ]
1
2021-07-26T07:17:06.000Z
2021-07-26T07:17:06.000Z
import unittest import ray import ray.rllib.agents.ppo as ppo from ray.rllib.utils.test_utils import check_compute_single_action, \ framework_iterator class TestAPPO(unittest.TestCase): @classmethod def setUpClass(cls): ray.init() @classmethod def tearDownClass(cls): ray.shutdown() def test_appo_compilation(self): """Test whether an APPOTrainer can be built with both frameworks.""" config = ppo.appo.DEFAULT_CONFIG.copy() config["num_workers"] = 1 num_iterations = 2 for _ in framework_iterator(config, frameworks=("torch", "tf")): _config = config.copy() trainer = ppo.APPOTrainer(config=_config, env="CartPole-v0") for i in range(num_iterations): print(trainer.train()) check_compute_single_action(trainer) _config = config.copy() _config["vtrace"] = True trainer = ppo.APPOTrainer(config=_config, env="CartPole-v0") for i in range(num_iterations): print(trainer.train()) check_compute_single_action(trainer) if __name__ == "__main__": import pytest import sys sys.exit(pytest.main(["-v", __file__]))
29
76
0.630313
142
1,247
5.274648
0.478873
0.064085
0.072096
0.096128
0.315087
0.315087
0.315087
0.315087
0.315087
0.315087
0
0.004367
0.265437
1,247
42
77
29.690476
0.813319
0.049719
0
0.375
0
0
0.047498
0
0
0
0
0
0
1
0.09375
false
0
0.1875
0
0.3125
0.0625
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
716227dcc03cade8b73786f23f543f0e5e37ee6c
2,516
py
Python
ezeeai/utils/hooks.py
jmarine/ezeeai
091b4ce3bc5794c534084bff3301b15ba8a9be1a
[ "Apache-2.0" ]
19
2019-06-12T03:14:59.000Z
2021-05-31T16:02:53.000Z
ezeeai/utils/hooks.py
jmarine/ezeeai
091b4ce3bc5794c534084bff3301b15ba8a9be1a
[ "Apache-2.0" ]
29
2019-06-27T10:15:38.000Z
2022-03-11T23:46:36.000Z
ezeeai/utils/hooks.py
jmarine/ezeeai
091b4ce3bc5794c534084bff3301b15ba8a9be1a
[ "Apache-2.0" ]
10
2019-05-14T17:45:44.000Z
2020-08-26T13:25:04.000Z
from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.training import session_run_hook from tensorflow.python.training.basic_session_run_hooks import NeverTriggerTimer, SecondOrStepTimer from tensorflow.python.training.session_run_hook import SessionRunArgs from tensorflow.python.util.tf_export import tf_export import smtplib from email.mime.text import MIMEText @tf_export("train.EmailAtStepHook") class EmailAtStepHook(session_run_hook.SessionRunHook): def __init__(self, user_info, server_info, every_n_iter=None, every_n_secs=None, at_end=False): only_log_at_end = ( at_end and (every_n_iter is None) and (every_n_secs is None)) if (not only_log_at_end and (every_n_iter is None) == (every_n_secs is None)): raise ValueError( "either at_end and/or exactly one of every_n_iter and every_n_secs " "must be provided.") if every_n_iter is not None and every_n_iter <= 0: raise ValueError("invalid every_n_iter=%s." % every_n_iter) self._timer = ( NeverTriggerTimer() if only_log_at_end else SecondOrStepTimer(every_secs=every_n_secs, every_steps=every_n_iter)) self._log_at_end = at_end self._user_info = user_info self._server_info = server_info self._timer.reset() self._iter_count = 0 def begin(self): pass def before_run(self, run_context): # pylint: disable=unused-argument self._should_trigger = self._timer.should_trigger_for_step(self._iter_count) def after_run(self, run_context, run_values): _ = run_context if self._should_trigger: self._send_email() self._iter_count += 1 def end(self, session): if self._log_at_end: self._send_email() def _send_email(self): smtpserver = 'smtp.gmail.com:587' header = 'From: %s' % self._server_info['email_address'] header += 'To: %s' % self._user_info['email_address'] header += 'Subject: %s' % "Training finished" message = header + "Training finished" server = smtplib.SMTP(smtpserver) server.starttls() server.login(self._server_info['login'], self._server_info['password']) problems = server.sendmail(self._server_info['email_address'], self._user_info['email_address'], message) server.quit()
37
113
0.68124
332
2,516
4.76506
0.304217
0.053097
0.05689
0.053097
0.127054
0.030341
0.030341
0.030341
0
0
0
0.003104
0.231717
2,516
67
114
37.552239
0.815313
0.012321
0
0.037736
0
0
0.108739
0.008458
0
0
0
0
0
1
0.113208
false
0.037736
0.169811
0
0.301887
0.018868
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
7164421f4b7f16666c296653efa901ece81b5485
3,999
py
Python
quizzes/00.organize.me/hackerrank/sorted_set/server2.py
JiniousChoi/encyclopedia-in-code
77bc551a03a2a3e3808e50016ece14adb5cfbd96
[ "MIT" ]
2
2018-07-20T10:15:49.000Z
2018-07-20T10:16:54.000Z
quizzes/00.organize.me/hackerrank/sorted_set/server2.py
JiniousChoi/encyclopedia-in-code
77bc551a03a2a3e3808e50016ece14adb5cfbd96
[ "MIT" ]
2
2018-06-26T09:12:44.000Z
2019-12-18T00:09:14.000Z
quizzes/00.organize.me/hackerrank/sorted_set/server2.py
JiniousChoi/encyclopedia-in-code
77bc551a03a2a3e3808e50016ece14adb5cfbd96
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import socket, threading from queue import Queue import sys, struct # NOTE: Use this path to create the UDS Server socket SERVER_SOCKET_PATH = "./socket"; class Result: def __init__(self): self._evt = threading.Event() self._result = None def set_result(self, value): self._result = value self._evt.set() def result(self): self._evt.wait() return self._result class ActorExit(Exception): pass class Actor(object): def __init__(self): self._mailbox = Queue() def send(self, msg): self._mailbox.put(msg) def recv(self): msg = self._mailbox.get() if msg is ActorExit: raise ActorExit() return msg def close(self): self.send(ActorExit) def start(self): self._terminated = threading.Event() t = threading.Thread(target=self._bootstrap) t.daemon = True t.start() def _bootstrap(self): try: self.run() except ActorExit: pass finally: self._terminated.set() def join(self): self._terminated.wait() def run(self): while True: msg = self.recv() class Worker(Actor): def __init__(self): super().__init__() self.db = {} def submit(self, values): r = Result() self.send((values, r)) return r def run(self): while True: values, r = self.recv() r.set_result(self.execute(values)) def execute(self, values): cmd, *opts = values print('[*]', cmd, opts) if cmd == 1: #add s, k, v = opts self.db.setdefault(s, {}) self.db[s][k] = v return [0] elif cmd == 2: #remove s, k = opts if s in self.db and k in self.db[s]: self.db[s].pop(k) return [0] elif cmd == 3: #get size s = opts[0] size = len(self.db[s]) if s in self.db else 0 return [1, size] elif cmd == 4: #get value s, k = opts if s in self.db and k in self.db[s]: score = self.db[s][k] else: score = 0 return [1, score] elif cmd == 5: #range *sets, _, lower, upper = opts res = [] for s in sets: if s not in self.db: continue for k,v in self.db[s].items(): if lower <= v <= upper: res.append((k,v)) res.sort() return [len(res)*2] + [e for kv in res for e in kv] elif cmd == 6: #disconnect return None else: raise Exception("Not supported CMD(%s)" % (cmd)) FMT = "!L" def read_number_from_socket(connection): return struct.unpack(FMT, connection.recv(4))[0] def write_number_to_socket(connection, number): connection.send(struct.pack(FMT, number)) def process_client_connection(connection, worker): while True: value_num = read_number_from_socket(connection) values = [] for _ in range(value_num): values.append(read_number_from_socket(connection)) res = worker.submit(values) if res.result() == None: break for num in res.result(): write_number_to_socket(connection, num) connection.close() def main(): worker = Worker() worker.start() s = socket.socket(socket.AF_UNIX) s.bind(SERVER_SOCKET_PATH) s.listen(1) while True: cl, addr = s.accept() t = threading.Thread(target = process_client_connection, args=(cl, worker)) t.start() #worker.close() s.close() if __name__ == '__main__': main()
24.838509
83
0.507877
481
3,999
4.081081
0.268191
0.039735
0.024962
0.013754
0.130922
0.030565
0.030565
0.030565
0.030565
0.030565
0
0.007264
0.380345
3,999
160
84
24.99375
0.784907
0.032008
0
0.166667
0
0
0.010875
0
0
0
0
0
0
1
0.150794
false
0.015873
0.02381
0.007937
0.285714
0.007937
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
716d93f8130aaab6f0fe666657a995579882463d
698
py
Python
ros_aruco.py
esteng/guiding-multi-step
3f0db0ba70b5851cc83878f4ed48cf82342a2ddf
[ "BSD-2-Clause" ]
69
2019-09-30T13:42:02.000Z
2022-03-28T08:37:51.000Z
ros_aruco.py
esteng/guiding-multi-step
3f0db0ba70b5851cc83878f4ed48cf82342a2ddf
[ "BSD-2-Clause" ]
5
2019-10-23T20:03:42.000Z
2021-07-10T09:43:50.000Z
ros_aruco.py
esteng/guiding-multi-step
3f0db0ba70b5851cc83878f4ed48cf82342a2ddf
[ "BSD-2-Clause" ]
18
2019-11-17T20:57:46.000Z
2022-03-15T10:46:25.000Z
""" Calibrate with the ROS package aruco_detect """ import rospy import roslib from geometry_msgs.msg import Transform class ROSArUcoCalibrate: def __init__(self, aruco_tag_len=0.0795): print("Please roslaunch roslaunch aruco_detect aruco_detect.launch before you run!") self.aruco_tf_topic = "/fiducial_transforms" self._aruco_tf_info_sub = rospy.Subscriber(self.aruco_tf_topic, Transform, self._tfCb) self.aruco_tf = None def _tfCb(self, tf_msg): if tf_msg is None: rospy.logwarn("_tfCb: tf_msg is None!") self.aruco_tf = tf_msg def get_tf(self): aruco_tf = self.aruco_tf return aruco_tf
24.928571
94
0.679083
97
698
4.556701
0.463918
0.162896
0.174208
0.072398
0
0
0
0
0
0
0
0.009452
0.24212
698
27
95
25.851852
0.826087
0.061605
0
0
0
0
0.181115
0
0
0
0
0
0
1
0.1875
false
0
0.1875
0
0.5
0.0625
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
716e210884f18d925519c5ee8a6aa1f846b9c04f
3,977
py
Python
utils/utils.py
mmalandra-kb4/service-metrics-gatherer
f9a795a43d491ef59a32121ab4ed5c2c62cb968b
[ "Apache-2.0" ]
null
null
null
utils/utils.py
mmalandra-kb4/service-metrics-gatherer
f9a795a43d491ef59a32121ab4ed5c2c62cb968b
[ "Apache-2.0" ]
null
null
null
utils/utils.py
mmalandra-kb4/service-metrics-gatherer
f9a795a43d491ef59a32121ab4ed5c2c62cb968b
[ "Apache-2.0" ]
2
2022-01-28T18:31:21.000Z
2022-03-03T14:42:48.000Z
""" * Copyright 2019 EPAM Systems * * 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 logging import re import os import json from urllib.parse import urlparse import datetime logger = logging.getLogger("metricsGatherer.utils") def remove_credentials_from_url(url): parsed_url = urlparse(url) new_netloc = re.sub("^.+?:.+?@", "", parsed_url.netloc) return url.replace(parsed_url.netloc, new_netloc) def get_credentials_from_url(url): parsed_url = urlparse(url) new_netloc = re.search("^(.+?):(.+?)@", parsed_url.netloc) try: username = new_netloc.group(1).strip() password = new_netloc.group(2).strip() return username, password except: # noqa return "", "" def read_json_file(folder, filename, to_json=False): """Read fixture from file""" with open(os.path.join(folder, filename), "r") as file: return file.read() if not to_json else json.loads(file.read()) def is_the_time_for_task_starting(allowed_start_time, allowed_end_time): start = datetime.time(int(allowed_start_time.split(":")[0]), int(allowed_start_time.split(":")[1])) end = datetime.time(int(allowed_end_time.split(":")[0]), int(allowed_end_time.split(":")[1])) now_time = datetime.datetime.now().time() if start > end: return (now_time >= start and now_time <= datetime.time(23, 59)) or\ (now_time >= datetime.time(0, 0) and now_time <= end) return now_time >= start and now_time <= end def take_the_date_to_check(): now_time = datetime.datetime.now().time() if (now_time >= datetime.time(12, 0) and now_time <= datetime.time(23, 59)): return datetime.datetime.now() return datetime.datetime.now() - datetime.timedelta(days=1) def build_url(main_url, url_params): """Build url by concating url and url_params""" return main_url + "/" + "/".join(url_params) def unite_project_name(project_id, prefix): return prefix + project_id def parse_conditions(conditions): parsed_conditions = [] for condition in conditions.split("|"): if not condition.strip(): continue chosen_operator = "" for operator in [">=", "<=", "==", "=", "<", ">"]: if operator in condition: chosen_operator = operator break condition_changed = condition.replace(chosen_operator, " ").split() if len(condition_changed) == 2: metric_score = None try: metric_score = int(condition_changed[1].strip()) except: # noqa try: metric_score = float(condition_changed[1].strip()) except: # noqa pass if metric_score is not None: parsed_conditions.append( (condition_changed[0].strip(), chosen_operator, metric_score)) return parsed_conditions def compare_metrics(cur_metric, metric_threshold, operator): if operator == ">=": return cur_metric >= metric_threshold if operator == ">": return cur_metric > metric_threshold if operator == "<=": return cur_metric <= metric_threshold if operator == "<": return cur_metric < metric_threshold if operator in ["==", "="]: return cur_metric == metric_threshold return False def convert_metrics_to_string(cur_metrics): return ";".join(["%s:%s" % (metric[0], metric[1]) for metric in cur_metrics])
33.70339
103
0.647473
509
3,977
4.868369
0.302554
0.033898
0.03632
0.058111
0.254237
0.204197
0.17837
0.135593
0.110573
0.110573
0
0.011079
0.228313
3,977
117
104
33.991453
0.796351
0.163943
0
0.128205
0
0
0.022995
0.006354
0
0
0
0
0
1
0.128205
false
0.038462
0.076923
0.025641
0.435897
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
717008cf6d0ff4d98caa231046b8d209403318a1
6,193
py
Python
unityparser/commands.py
socialpoint-labs/unity-yaml-parser
91c175140ed32aed301bc34d4311f370da69a8ba
[ "MIT" ]
76
2019-06-17T13:17:59.000Z
2022-03-11T19:39:24.000Z
unityparser/commands.py
socialpoint-labs/unity-yaml-parser
91c175140ed32aed301bc34d4311f370da69a8ba
[ "MIT" ]
17
2019-06-07T09:04:27.000Z
2022-02-16T19:01:38.000Z
unityparser/commands.py
socialpoint-labs/unity-yaml-parser
91c175140ed32aed301bc34d4311f370da69a8ba
[ "MIT" ]
9
2019-10-08T16:07:35.000Z
2021-12-08T15:27:00.000Z
import re from argparse import ArgumentParser from multiprocessing import Pool, Manager, Process from pathlib import Path from .utils import UnityDocument YAML_HEADER = '%YAML' class UnityProjectTester: """ Class to run tests on a given Unity project folder """ AVAILABLE_COMMANDS = ('test_no_yaml_is_modified',) def __init__(self): self.options = None def run(self): top_parser = ArgumentParser() subparser = top_parser.add_subparsers() subparser.required = True for cmd in UnityProjectTester.AVAILABLE_COMMANDS: fn = getattr(self, cmd) parser = subparser.add_parser(cmd, help=fn.__doc__) parser.set_defaults(func=fn) top_parser.add_argument('project_path', help='Path to the Unity project folder') top_parser.add_argument('--exclude', help='Exclude regexp when searching project files. Can be specified multiple times.', default=None, action='append') top_parser.add_argument('--keep-changes', help='If a file changes after serialization, do not revert the changes.', default=False, action='store_true') top_parser.add_argument('--dry-run', help='Dont\'t modify.', default=False, action='store_true') try: self.options = top_parser.parse_args() except TypeError: top_parser.print_help() return 2 # run given function self.options.func() def test_no_yaml_is_modified(self): """ Recurse the whole project folder looking for '.asset' files, load and save them all, and check that there are no modifications """ if self.options.dry_run: print("Dry-run mode enabled: YAMLs won't be dumped.") if self.options.keep_changes: print("Keep changes mode will not have any effect during dry run.") elif self.options.keep_changes: print("Keep changes mode enabled: Changes to files will be kept.") project_path = Path(self.options.project_path) asset_file_paths = [p for p in project_path.rglob('*.asset')] print("Found {} '.asset' files".format(len(asset_file_paths))) def is_path_included(path): # compare regexp against absolute path return not any(rexp.search(str(path.resolve())) for rexp in rexps) if self.options.exclude is not None: rexps = [re.compile(rexp) for rexp in self.options.exclude] valid_file_paths = [p for p in filter(is_path_included, asset_file_paths)] print("Excluded {} '.asset' files".format(len(asset_file_paths) - len(valid_file_paths))) else: valid_file_paths = asset_file_paths file_results = [] with Manager() as manager: print_queue = manager.Queue() diff_list = manager.list() queue_process = Process(target=UnityProjectTester.read_output, args=(print_queue,)) queue_process.start() with Pool() as pool: for f in valid_file_paths: async_res = pool.apply_async(UnityProjectTester.open_and_save, (f, print_queue, diff_list, self.options.keep_changes, self.options.dry_run)) file_results.append((f, async_res)) pool.close() pool.join() # signal end of queue with None token print_queue.put(None) queue_process.join() error_results = list(filter(lambda r: not r[1].successful(), file_results)) if len(error_results): # raise the first exception file_path, result = error_results[0] print("Python process evaluating file {} failed with the following exception:".format( file_path.resolve()), flush=True) result.get() if len(diff_list): print("{} files are different now:".format(len(diff_list))) print('\n'.join([str(f.resolve()) for f in diff_list])) @staticmethod def read_output(print_queue): msg = print_queue.get() while msg is not None: print(msg, flush=True) msg = print_queue.get() @staticmethod def open_and_save(asset_file_path, print_queue, diff_list, keep_changes=False, dry_run=False): # check YAML version header, save original content with open(str(asset_file_path), 'rb') as fp: header = fp.read(len(YAML_HEADER)) try: is_yaml_file = header.decode('utf-8') == YAML_HEADER except UnicodeDecodeError: is_yaml_file = False finally: if not is_yaml_file: print_queue.put("Ignoring non-yaml file {}".format(asset_file_path)) return else: fp.seek(0) print_queue.put("Processing {}".format(asset_file_path)) a_file_content = fp.read() doc = UnityDocument.load_yaml(str(asset_file_path)) if dry_run: return try: doc.dump_yaml() with open(str(asset_file_path), 'rb') as fp: b_file_content = fp.read() # compare if a_file_content != b_file_content: diff_list.append(asset_file_path) if not keep_changes: with open(str(asset_file_path), 'wb') as fp: fp.write(a_file_content) except Exception: with open(str(asset_file_path), 'wb') as fp: fp.write(a_file_content) raise if __name__ == '__main__': # None is considered successful code = UnityProjectTester().run() or 0 exit(code)
39.698718
117
0.56467
712
6,193
4.689607
0.29073
0.037736
0.03504
0.023959
0.129979
0.101827
0.092243
0.072477
0.04732
0.02935
0
0.001484
0.347005
6,193
155
118
39.954839
0.824184
0.061844
0
0.173554
0
0
0.11308
0.004169
0
0
0
0
0
1
0.049587
false
0
0.041322
0.008264
0.140496
0.165289
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
71707cf255fd21e42d8d8ac95ead6668d4d78aed
582
py
Python
DP/Leetcode 221. Maximal Square.py
kaizhengny/LeetCode
67d64536ab80f4966699fe7460d165f2a98d6a82
[ "MIT" ]
31
2020-06-23T00:40:04.000Z
2022-01-08T11:06:24.000Z
DP/Leetcode 221. Maximal Square.py
kaizhengny/LeetCode
67d64536ab80f4966699fe7460d165f2a98d6a82
[ "MIT" ]
null
null
null
DP/Leetcode 221. Maximal Square.py
kaizhengny/LeetCode
67d64536ab80f4966699fe7460d165f2a98d6a82
[ "MIT" ]
7
2020-04-30T08:46:03.000Z
2021-08-28T16:25:54.000Z
class Solution: def maximalSquare(self, matrix: List[List[str]]) -> int: if not matrix: return 0 m, n = len(matrix), len(matrix[0]) dp = [[0]*n for _ in range(m)] res = 0 for i in range(m): dp[i][0] = int(matrix[i][0]) for j in range(n): dp[0][j] = int(matrix[0][j]) for i in range(1, m): for j in range(1, n): if matrix[i][j] == '1': dp[i][j] = min(dp[i-1][j],dp[i-1][j-1],dp[i][j-1])+1 res = max(res, dp[i][j]) return res**2
36.375
72
0.429553
99
582
2.515152
0.272727
0.072289
0.048193
0.088353
0.048193
0
0
0
0
0
0
0.046961
0.378007
582
16
73
36.375
0.640884
0
0
0
0
0
0.001715
0
0
0
0
0
0
1
0.0625
false
0
0
0
0.1875
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
7171d1486ab6a395eb9ff27ecf4115ab48da0237
3,767
py
Python
dokang/harvesters/__init__.py
Polyconseil/dokang
b0ab3e4aabfb97adb2a2e877a42fc1896e5fcf08
[ "BSD-3-Clause" ]
6
2016-07-04T17:16:42.000Z
2018-11-13T08:10:21.000Z
dokang/harvesters/__init__.py
Polyconseil/dokang
b0ab3e4aabfb97adb2a2e877a42fc1896e5fcf08
[ "BSD-3-Clause" ]
6
2016-02-23T15:08:51.000Z
2017-01-02T11:57:45.000Z
dokang/harvesters/__init__.py
Polyconseil/dokang
b0ab3e4aabfb97adb2a2e877a42fc1896e5fcf08
[ "BSD-3-Clause" ]
5
2015-04-05T14:07:11.000Z
2017-04-13T14:08:02.000Z
# -*- coding: utf-8 -*- # Copyright (c) Polyconseil SAS. All rights reserved. import hashlib import json import logging import os import re from .html import html_config, HtmlHarvester # pylint: disable=unused-import from .sphinx import ( # pylint: disable=unused-import sphinx_config, sphinx_rtd_config, SphinxHarvester, ReadTheDocsSphinxHarvester ) logger = logging.getLogger(__name__) def _must_process_path(path, include, exclude): for exp in include: if exp.match(path): return True for exp in exclude: if exp.match(path): return False return True def _compute_hash(path): h = hashlib.md5() with open(path, 'rb') as fp: while 1: buff = fp.read(8192) if not buff: break h.update(buff) return h.hexdigest() def harvest_set(base_dir, doc_set, config, hashes, force): """Harvest a document set and return documents as dictionaries. ``config`` is the harvester configuration. It should contain a key for each supported file extensions. ``hashes`` is a dictionary that links the path of each indexed file to its hash. It is used to decide whether the document should be indexed again. ``force`` indicates whether to reindex a document even if it has not ben modified since the last indexation. This function is a generator. It yields dictionaries. Each dictionary should represent a document and contain the following keys in addition to the keys returned by the harvester itself. Each text-like value should be a string (in Python 3) or a unicode object (in Python 2). path The path of the document relative to the root of the document set. set The id of the document set. It should be ``doc_set``. """ config_copy = config.copy() include = [re.compile(exp) for exp in config_copy.pop('include') or ()] exclude = [re.compile(exp) for exp in config_copy.pop('exclude') or ()] extensions = config_copy for dir_path, _dir_names, file_names in os.walk(base_dir): for filename in file_names: path = os.path.join(dir_path, filename) relative_path = os.path.relpath(path, base_dir) if not _must_process_path(relative_path, include, exclude): logger.debug('Excluded file "%s": include/exclude rules.', relative_path) continue _, extension = os.path.splitext(filename) extension = extension.lstrip('.') # remove leading dot harvester_class = extensions.get(extension) if harvester_class is None: logger.debug('Excluded file "%s": no harvester found for %s.', relative_path, extension) continue current_hash = _compute_hash(path) indexed_hash = hashes.get(relative_path) if not force and (indexed_hash == current_hash): logger.debug('Excluded file: "%s": not modified since last indexation.', relative_path) continue try: logger.debug('Indexing file "%s"', relative_path) doc = harvester_class().harvest_file(path) except Exception: # pylint: disable=broad-except logger.exception("Could not index document %s", path) else: if doc: if relative_path == 'index.html': with open(os.path.join(base_dir, '.dokang'), 'w') as fp: json.dump({'title': doc['title']}, fp) doc['path'] = relative_path doc['set'] = doc_set doc['hash'] = current_hash yield doc
38.050505
104
0.617733
475
3,767
4.783158
0.355789
0.047535
0.014085
0.03037
0.078345
0.029049
0.029049
0.029049
0.029049
0
0
0.003398
0.296788
3,767
98
105
38.438776
0.854285
0.271834
0
0.107692
0
0
0.092002
0
0
0
0
0
0
1
0.046154
false
0
0.107692
0
0.215385
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
717345e66810546b06a5a6c9cdbe99a57810c275
357
py
Python
src/fuckbot/ticker.py
Zer0-One/fuckbot
02f5a112988e25a9f04a9a941a55f11cf51c3d8f
[ "BSD-2-Clause" ]
null
null
null
src/fuckbot/ticker.py
Zer0-One/fuckbot
02f5a112988e25a9f04a9a941a55f11cf51c3d8f
[ "BSD-2-Clause" ]
null
null
null
src/fuckbot/ticker.py
Zer0-One/fuckbot
02f5a112988e25a9f04a9a941a55f11cf51c3d8f
[ "BSD-2-Clause" ]
1
2022-01-24T21:20:43.000Z
2022-01-24T21:20:43.000Z
import discord import logging TRADING_API_URL='https://cloud.iexapis.com/stable/stock/{0}/quote' TRADING_API_ICON='https://iextrading.com/favicon.ico' def ticker_embed(symbol): ticker = discord.Embed(title=f"{symbol}".upper(), type="rich", color=3029236, url=TRADING_API_URL.format(symbol)) ticker.set_author(name="IEXTrading") return ticker
29.75
117
0.756303
51
357
5.137255
0.666667
0.114504
0.099237
0
0
0
0
0
0
0
0
0.024615
0.089636
357
11
118
32.454545
0.781538
0
0
0
0
0
0.291317
0
0
0
0
0
0
1
0.125
false
0
0.25
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
7173dccce721752a801b4b3463958745f87a8a0c
9,769
py
Python
minos/lib/util/StateSet.py
johny-c/minos
660e991f44118382f4a3cb7566670c4159d33fe3
[ "MIT" ]
1
2020-02-18T08:19:32.000Z
2020-02-18T08:19:32.000Z
minos/lib/util/StateSet.py
johny-c/minos
660e991f44118382f4a3cb7566670c4159d33fe3
[ "MIT" ]
4
2019-12-27T12:44:58.000Z
2021-05-07T17:41:09.000Z
minos/lib/util/StateSet.py
johny-c/minos
660e991f44118382f4a3cb7566670c4159d33fe3
[ "MIT" ]
1
2019-10-15T00:28:39.000Z
2019-10-15T00:28:39.000Z
import bz2 import csv import collections import math from enum import Enum class Select(Enum): FIRST = 'first' RANGE_KEY = 'range_key' RANGE_VALUE = 'range_value' class SelectPolicy: def __init__(self, policy, field=None): self.policy = policy self.field = field class StateSet: """ Wrapper for set of episode val/test states """ def __init__(self, scenes_file=None, states_files=None, scene_filter=None, episode_filter=None, max_states_per_scene=None, select_policy=SelectPolicy(Select.FIRST)): self.states = [] self.scenes = [] self.scenes_by_id = {} self.states_by_scene = {} self.select_policy = select_policy if scenes_file: self._load_scenes(scenes_file, scene_filter) if states_files: if type(states_files) is str: self._load_states(states_files, max_states_per_scene, episode_filter) elif isinstance(states_files, collections.Iterable): for states_file in states_files: self._load_states(states_file, max_states_per_scene, episode_filter) self._embed_states_in_scenes() def get_splits(self, max_states_per_scene=None): """Get dictionary of StateSets keyed by scene 'set' i.e. dataset split""" scenes_by_split = {} for scene in self.scenes: scenes_by_split.setdefault(scene['set'], []).append(scene) state_sets_dict = {} for split, scenes in scenes_by_split.items(): ss = StateSet() ss._populate_from_lists(scenes, self.states_by_scene, max_states_per_scene) state_sets_dict[split] = ss return state_sets_dict def get_scenes(self): return self.scenes def get_states(self): return self.states def get_states_by_scene_id(self, scene_id): return self.states_by_scene[scene_id] def _select_n_states(self, states, n): # Select n states from big list of states policy = self.select_policy.policy field = self.select_policy.field if n is not None and n < len(states): if policy == Select.FIRST: if field is not None: # sort by field states = sorted(states, key=lambda x: x[field]) return states[:n] elif policy == Select.RANGE_KEY: # sort by field states = sorted(states, key=lambda x: x[field]) # select by evenly dividing indices r = len(states)/float(n) selected = [] for i in range(n): si = int(math.floor(math.ceil(r*i)/2)) selected.append(states[si]) return selected elif policy == Select.RANGE_VALUE: # sort by field and get range (value) states = sorted(states, key=lambda x: x[field]) fmin = states[0][field] fmax = states[-1][field] # print('Range is %f to %f' % (fmin,fmax)) # from range, divide up into n buckets r = (fmax-fmin)/float(n) buckets = [] for i in range(n): buckets.append([]) for state in states: bi = int(min(math.ceil((state[field] - fmin)/r), n-1)) buckets[bi].append(state) # make sure all buckets have something for i, bucket in enumerate(buckets): if len(bucket) == 0: # print('Nothing in bucket %d' % i) # still some from other buckets pi = max(i-1, 0) ni = min(i+1, n-1) nlen = len(buckets[ni]) plen = len(buckets[pi]) if nlen > plen: # take half from bucket[ni] and put in current bucket k = math.floor(nlen/2) buckets[i] = buckets[ni][:k] buckets[ni] = buckets[ni][k:] else: k = math.floor(plen/2) buckets[i] = buckets[pi][:k] buckets[pi] = buckets[pi][k:] selected = [] for bucket in buckets: bii = math.floor(len(bucket)/2) selected.append(bucket[bii]) return selected else: raise ValueError('Unsupported select_policy ' + policy) else: return states def _populate_from_lists(self, my_scenes, my_states_by_scene, max_states_per_scene): self.scenes = my_scenes for scene in my_scenes: scene_id = scene['id'] self.scenes_by_id[scene_id] = scene if scene_id in my_states_by_scene: my_states = self._select_n_states(my_states_by_scene[scene_id], max_states_per_scene) self.states_by_scene[scene_id] = my_states self.states += my_states def _load_scenes(self, filename, scene_filter): with bz2.open(filename, 'rt') if filename.endswith('bz2') else open(filename) as f: reader = csv.DictReader(f) self.scenes = [] for r in reader: for v in ['nrooms', 'nobjects', 'nlevels']: if v in r: r[v] = int(r[v]) for v in ['dimX', 'dimY', 'dimZ', 'floorArea']: if v in r: r[v] = float(r[v]) if scene_filter and not scene_filter(r): continue self.scenes.append(r) self.scenes_by_id[r['id']] = r self.scenes.sort(key=lambda x: x['nobjects']) def _load_states(self, filename, max_states_per_scene, state_filter): with bz2.open(filename, 'rt') if filename.endswith('bz2') else open(filename) as f: reader = csv.DictReader(f) all_states = [r for r in reader] # Convert scene state and group by sceneId counter = 0 for r in all_states: for v in ['startX', 'startY', 'startZ', 'startAngle', 'goalX', 'goalY', 'goalZ', 'dist', 'pathDist']: r[v] = float(r[v]) if v in r else None for v in ['episodeId', 'pathNumDoors', 'pathNumRooms', 'level']: r[v] = int(r[v]) if v in r else None scene_id = r['sceneId'] scene_states = self.states_by_scene.setdefault(scene_id, []) rec = { 'episode_id': counter, 'scene_id': r['sceneId'], 'room_id': r['roomId'], 'start': {'position': [r['startX'], r['startY'], r['startZ']], 'angle': r['startAngle']}, 'goal': {'id': r['goalObjectId'], 'position': [r['goalX'], r['goalY'], r['goalZ']]}, 'dist': r['dist'] } for k in ['pathDist', 'pathNumRooms', 'pathRoomIds', 'pathNumDoors', 'pathDoorIds', 'level']: if k in r: rec[k] = r[k] if not state_filter or state_filter(rec): scene_states.append(rec) counter = counter + 1 # Filter down to states per scene and create big list of all scenes states = [] for scene_id, scene_states in self.states_by_scene.items(): self.states_by_scene[scene_id] = self._select_n_states(scene_states, max_states_per_scene) states += self.states_by_scene[scene_id] self.states = states def _embed_states_in_scenes(self): for state in self.states: scene_id = state['scene_id'] if scene_id in self.scenes_by_id: self.scenes_by_id[scene_id].setdefault('states', []).append(state) scenes_with_no_states = [] for i, scene in enumerate(self.scenes): if 'states' not in scene or len(scene['states']) == 0: scenes_with_no_states.append(scene['id']) del self.scenes_by_id[scene['id']] self.scenes = [s for s in self.scenes if s['id'] not in scenes_with_no_states] #print('Removed scenes with no episode states: ' + ','.join(scenes_with_no_states)) def main(): import argparse # Argument processing parser = argparse.ArgumentParser(description='Load state set') parser.add_argument('-n', '--limit', type=int, help='Number of states per scene') parser.add_argument('--select', default=Select.FIRST, type=Select, help='Number of states per scene') parser.add_argument('--field', default=None, help='Field to use for selection') parser.add_argument('--scenes', type=str, default=None, help='Scenes file to load') parser.add_argument('input', help='Input file to load') args = parser.parse_args() state_set = StateSet(scenes_file=args.scenes, states_files=args.input, max_states_per_scene=args.limit, select_policy=SelectPolicy(args.select, args.field)) for state in state_set.states: print(state) if __name__ == "__main__": main()
41.747863
117
0.522469
1,145
9,769
4.262882
0.172926
0.030117
0.037287
0.034829
0.198525
0.159394
0.118418
0.085228
0.071707
0.054087
0
0.003274
0.374757
9,769
233
118
41.927039
0.795842
0.070632
0
0.125
0
0
0.068044
0
0
0
0
0
0
1
0.0625
false
0
0.03125
0.015625
0.166667
0.005208
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
7175fb970f1844dacf40b20065573654fbebe36d
4,053
py
Python
cqlsh_tests/cqlsh_tools.py
vincewhite/cassandra-dtest
a01dce6af73a8656e8740227a811fe63025fb3f4
[ "Apache-2.0" ]
null
null
null
cqlsh_tests/cqlsh_tools.py
vincewhite/cassandra-dtest
a01dce6af73a8656e8740227a811fe63025fb3f4
[ "Apache-2.0" ]
null
null
null
cqlsh_tests/cqlsh_tools.py
vincewhite/cassandra-dtest
a01dce6af73a8656e8740227a811fe63025fb3f4
[ "Apache-2.0" ]
null
null
null
import csv import random import cassandra from cassandra.cluster import ResultSet from typing import List class DummyColorMap(object): def __getitem__(self, *args): return '' def csv_rows(filename, delimiter=None): """ Given a filename, opens a csv file and yields it line by line. """ reader_opts = {} if delimiter is not None: reader_opts['delimiter'] = delimiter with open(filename, 'rb') as csvfile: for row in csv.reader(csvfile, **reader_opts): yield row def assert_csvs_items_equal(filename1, filename2): with open(filename1, 'r') as x, open(filename2, 'r') as y: assert list(x.readlines()) == list(y.readlines()) def random_list(gen=None, n=None): if gen is None: def gen(): return random.randint(-1000, 1000) if n is None: def length(): return random.randint(1, 5) else: def length(): return n return [gen() for _ in range(length())] def write_rows_to_csv(filename, data): with open(filename, 'wb') as csvfile: writer = csv.writer(csvfile) for row in data: writer.writerow(row) csvfile.close def deserialize_date_fallback_int(byts, protocol_version): timestamp_ms = cassandra.marshal.int64_unpack(byts) try: return cassandra.util.datetime_from_timestamp(timestamp_ms / 1000.0) except OverflowError: return timestamp_ms def monkeypatch_driver(): """ Monkeypatches the `cassandra` driver module in the same way that clqsh does. Returns a dictionary containing the original values of the monkeypatched names. """ cache = {'BytesType_deserialize': cassandra.cqltypes.BytesType.deserialize, 'DateType_deserialize': cassandra.cqltypes.DateType.deserialize, 'support_empty_values': cassandra.cqltypes.CassandraType.support_empty_values} cassandra.cqltypes.BytesType.deserialize = staticmethod(lambda byts, protocol_version: bytearray(byts)) cassandra.cqltypes.DateType.deserialize = staticmethod(deserialize_date_fallback_int) cassandra.cqltypes.CassandraType.support_empty_values = True if hasattr(cassandra, 'deserializers'): cache['DesDateType'] = cassandra.deserializers.DesDateType del cassandra.deserializers.DesDateType return cache def unmonkeypatch_driver(cache): """ Given a dictionary that was used to cache parts of `cassandra` for monkeypatching, restore those values to the `cassandra` module. """ cassandra.cqltypes.BytesType.deserialize = staticmethod(cache['BytesType_deserialize']) cassandra.cqltypes.DateType.deserialize = staticmethod(cache['DateType_deserialize']) cassandra.cqltypes.CassandraType.support_empty_values = cache['support_empty_values'] if hasattr(cassandra, 'deserializers'): cassandra.deserializers.DesDateType = cache['DesDateType'] def assert_resultset_contains(got: ResultSet, expected: List[tuple]) -> None: """ So this is slow. I would hope a ResultSet has the capability of pulling data by PK or clustering, however I'm not finding it atm. As such, this method isn't intended for use with large datasets. :param got: ResultSet, expect schema of [a, b] :param expected: list of tuples with 2 members corresponding with a/b schema of ResultSet """ # Adding a touch of sanity check so people don't mis-use this. n^2 is bad. assert len(expected) <= 1000, 'This is a slow comparison method. Don\'t use for > 1000 tuples.' # First quick check: if we have a different count, we can just die. assert len(got.current_rows) == len(expected) for t in expected: assert len(t) == 2, 'Got unexpected tuple len. Expected 2, got tuple: {}'.format(t) found = False for row in got.current_rows: if found: break if row.a == t[0] and row.b == t[1]: found = True assert found, 'Failed to find expected row: {}'.format(t)
33.495868
107
0.683691
514
4,053
5.293774
0.371595
0.056229
0.033076
0.040794
0.172731
0.052922
0
0
0
0
0
0.011129
0.224032
4,053
120
108
33.775
0.854054
0.202813
0
0.057143
0
0
0.097041
0.013363
0
0
0
0
0.1
1
0.171429
false
0
0.071429
0.057143
0.371429
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
71764b0e93fc239b103c34e487ed538048a2ed7d
5,394
py
Python
tests/unit/sagemaker/tensorflow/test_estimator_init.py
LastRemote/sagemaker-python-sdk
fddf29d9e4383cd3f939253eef47ee79a464dd37
[ "Apache-2.0" ]
1,690
2017-11-29T20:13:37.000Z
2022-03-31T12:58:11.000Z
tests/unit/sagemaker/tensorflow/test_estimator_init.py
LastRemote/sagemaker-python-sdk
fddf29d9e4383cd3f939253eef47ee79a464dd37
[ "Apache-2.0" ]
2,762
2017-12-04T05:18:03.000Z
2022-03-31T23:40:11.000Z
tests/unit/sagemaker/tensorflow/test_estimator_init.py
LastRemote/sagemaker-python-sdk
fddf29d9e4383cd3f939253eef47ee79a464dd37
[ "Apache-2.0" ]
961
2017-11-30T16:44:03.000Z
2022-03-30T23:12:09.000Z
# Copyright Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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 __future__ import absolute_import from mock import Mock, patch from packaging import version import pytest from sagemaker.tensorflow import TensorFlow REGION = "us-west-2" ENV_INPUT = {"env_key1": "env_val1", "env_key2": "env_val2", "env_key3": "env_val3"} @pytest.fixture() def sagemaker_session(): return Mock(name="sagemaker_session", boto_region_name=REGION) def _build_tf(sagemaker_session, **kwargs): return TensorFlow( sagemaker_session=sagemaker_session, entry_point="dummy.py", role="dummy-role", instance_count=1, instance_type="ml.c4.xlarge", **kwargs, ) @patch("sagemaker.fw_utils.python_deprecation_warning") def test_estimator_py2_deprecation_warning(warning, sagemaker_session): estimator = _build_tf(sagemaker_session, framework_version="2.1.1", py_version="py2") assert estimator.py_version == "py2" warning.assert_called_with("tensorflow", "2.1.1") def test_py2_version_deprecated(sagemaker_session): with pytest.raises(AttributeError) as e: _build_tf(sagemaker_session, framework_version="2.1.2", py_version="py2") msg = ( "Python 2 containers are only available with 2.1.1 and lower versions. " "Please use a Python 3 container." ) assert msg in str(e.value) def test_py2_version_is_not_deprecated(sagemaker_session): estimator = _build_tf(sagemaker_session, framework_version="1.15.0", py_version="py2") assert estimator.py_version == "py2" estimator = _build_tf(sagemaker_session, framework_version="2.0.0", py_version="py2") assert estimator.py_version == "py2" def test_framework_name(sagemaker_session): tf = _build_tf(sagemaker_session, framework_version="1.15.2", py_version="py3") assert tf._framework_name == "tensorflow" def test_tf_add_environment_variables(sagemaker_session): tf = _build_tf( sagemaker_session, framework_version="1.15.2", py_version="py3", environment=ENV_INPUT, ) assert tf.environment == ENV_INPUT def test_tf_miss_environment_variables(sagemaker_session): tf = _build_tf( sagemaker_session, framework_version="1.15.2", py_version="py3", environment=None, ) assert not tf.environment def test_enable_sm_metrics(sagemaker_session): tf = _build_tf( sagemaker_session, framework_version="1.15.2", py_version="py3", enable_sagemaker_metrics=True, ) assert tf.enable_sagemaker_metrics def test_disable_sm_metrics(sagemaker_session): tf = _build_tf( sagemaker_session, framework_version="1.15.2", py_version="py3", enable_sagemaker_metrics=False, ) assert not tf.enable_sagemaker_metrics def test_disable_sm_metrics_if_fw_ver_is_less_than_1_15( sagemaker_session, tensorflow_training_version, tensorflow_training_py_version ): if version.Version(tensorflow_training_version) > version.Version("1.14"): pytest.skip("This test is for TF 1.14 and lower.") tf = _build_tf( sagemaker_session, framework_version=tensorflow_training_version, py_version=tensorflow_training_py_version, image_uri="old-image", ) assert tf.enable_sagemaker_metrics is None def test_enable_sm_metrics_if_fw_ver_is_at_least_1_15( sagemaker_session, tensorflow_training_version, tensorflow_training_py_version ): if version.Version(tensorflow_training_version) < version.Version("1.15"): pytest.skip("This test is for TF 1.15 and higher.") tf = _build_tf( sagemaker_session, framework_version=tensorflow_training_version, py_version=tensorflow_training_py_version, ) assert tf.enable_sagemaker_metrics def test_require_image_uri_if_fw_ver_is_less_than_1_11( sagemaker_session, tensorflow_training_version, tensorflow_training_py_version ): if version.Version(tensorflow_training_version) > version.Version("1.10"): pytest.skip("This test is for TF 1.10 and lower.") with pytest.raises(ValueError) as e: _build_tf( sagemaker_session, framework_version=tensorflow_training_version, py_version=tensorflow_training_py_version, ) expected_msg = ( "TF {version} supports only legacy mode. Please supply the image URI directly with " "'image_uri=520713654638.dkr.ecr.{region}.amazonaws.com/" "sagemaker-tensorflow:{version}-cpu-py2' and set 'model_dir=False'. If you are using any " "legacy parameters (training_steps, evaluation_steps, checkpoint_path, requirements_file), " "make sure to pass them directly as hyperparameters instead." ).format(version=tensorflow_training_version, region=REGION) assert expected_msg in str(e.value)
32.890244
100
0.725436
715
5,394
5.155245
0.26014
0.121541
0.05643
0.081118
0.505155
0.482366
0.477482
0.456321
0.397179
0.317689
0
0.02479
0.184835
5,394
163
101
33.092025
0.813509
0.099184
0
0.333333
0
0.008772
0.178291
0.028683
0
0
0
0
0.114035
1
0.114035
false
0.008772
0.04386
0.017544
0.175439
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
71770ce551bdcd43974b0f18b616fb25201796c0
827
py
Python
testing.py
sofwerx/mycroft-articlekeyword-skill
7cab109db512d3a6465db241b18018e9415f4a9f
[ "Unlicense" ]
null
null
null
testing.py
sofwerx/mycroft-articlekeyword-skill
7cab109db512d3a6465db241b18018e9415f4a9f
[ "Unlicense" ]
null
null
null
testing.py
sofwerx/mycroft-articlekeyword-skill
7cab109db512d3a6465db241b18018e9415f4a9f
[ "Unlicense" ]
null
null
null
import subprocess proc = subprocess.Popen(['python3', 'articlekeywords.py', 'aih.txt' , '5'], stdout=subprocess.PIPE ) #print(type(proc.communicate()[0])) # path = '/opt/mycroft/skills/mycroft-bitcoinprice-skill/' text = proc.stdout.read() rows = text.splitlines() #print(text.splitlines()) count = 0 s = "" for row in rows: divide = row.split() wordCount = len(divide) if wordCount > 1: count = count + 1 s += str(count) s += " " s += str(divide[1]) s += " " print(s) # with open(path + 'out.csv', 'r') as content_file: # text = content_file.read() # self.speak_dialog("bitcoin.price", data={'price': str(text)}) #file_path = '/opt/mycroft/skills/mycroft-bitcoinprice-skill/out.csv' #wordCount = 10 # # text = Path(file_path).read_text() # #print(exit_code)
21.205128
101
0.622733
109
827
4.66055
0.504587
0.027559
0.055118
0.07874
0.173228
0.173228
0.173228
0
0
0
0
0.013493
0.19347
827
39
102
21.205128
0.748126
0.474002
0
0.125
0
0
0.082742
0
0
0
0
0
0
1
0
false
0
0.0625
0
0.0625
0.0625
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
717864c0c5586a731d9e7b34b779d6af81159c7a
4,509
py
Python
slcyGeneral.py
mirrorcoloured/slcypi
c47975b3523f770d12a521c82e2dfca181e3f35b
[ "MIT" ]
null
null
null
slcyGeneral.py
mirrorcoloured/slcypi
c47975b3523f770d12a521c82e2dfca181e3f35b
[ "MIT" ]
null
null
null
slcyGeneral.py
mirrorcoloured/slcypi
c47975b3523f770d12a521c82e2dfca181e3f35b
[ "MIT" ]
null
null
null
# Python 2.7.1 import RPi.GPIO as GPIO from twython import Twython import time import sys import os import pygame APP_KEY='zmmlyAJzMDIntLpDYmSH98gbw' APP_SECRET='ksfSVa2hxvTQKYy4UR9tjpb57CAynMJDsygz9qOyzlH24NVwpW' OAUTH_TOKEN='794094183841566720-BagrHW91yH8C3Mdh9SOlBfpL6wrSVRW' OAUTH_TOKEN_SECRET='d0Uucq2dkSHrFHZGLM1X8Hw05d80ajKYGl1zTRxZQSKTm' applepislcy = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) ### GENERAL ### def Cleanup(): GPIO.cleanup() def Sleep(seconds): """Puts the program to sleep""" time.sleep(seconds) def Alert(channel): """Simple alert function for testing event interrupts""" print('Alert on channel',channel) def TimeString(): """Returns the current time""" t = time.localtime() return str(t[0])+'.'+str(t[1])+'.'+str(t[2])+'.'+str(t[3])+'.'+str(t[4])+'.'+str(t[5]) def LoadPins(mapping,inp): """Organizes an input into a pin mapping dict mapping <list>, ['IA','IB'] inp <dict>, <list>, <int> {'IA':1,'IB':2}, [1,2] """ if type(inp) is int and len(mapping) == 1: return {mapping[0]:inp} elif type(inp) is list and len(mapping) == len(inp): o = {} for i in range(len(inp)): o[mapping[i]] = inp[i] return o elif type(inp) is dict: return inp else: print('Invalid input for pins:',inp,type(inp)) print('Expected:',mapping) return {} def BoolToSign(inp): """Converts boolean bits into signed bits 0 -> -1 1 -> 1""" return (inp * 2) - 1 def SignToBool(inp): """Converts signed bits into boolean bits -1 -> 0 1 -> 1""" return (inp + 1) / 2 ### PYGAME ### def WindowSetup(size=(300,50),caption='',text='',background=(0,0,0),foreground=(255,255,255)): """Sets up a pygame window to take keyboard input size <tuple>, width by height caption <str>, window title bar text <str>, text to display in window, accepts \n background <tuple>, foreground <tuple>, (r,g,b) color """ pygame.init() screen = pygame.display.set_mode(size,0,32) pygame.display.set_caption(caption) myfont = pygame.font.SysFont('Monospace',15) labels = [] lines = text.split('\n') for line in lines: labels.append(myfont.render(line,1,foreground)) screen.fill(background) y = 0 for label in labels: screen.blit(label, (0,y)) y += 15 pygame.display.update() def InputLoop(eventmap): """Begins a pygame loop, mapping key inputs to functions eventmap <dict>, {pygame.K_t:myfunction} """ index = 0 while True: events = pygame.event.get() for event in events: if event.type == pygame.KEYDOWN: #print("{0}: You pressed {1:c}".format ( index , event.key )) if event.key in eventmap: eventmap[event.key]() elif event.type == pygame.QUIT: pygame.quit() sys.exit() def InputLoopDemo(): def dog(): print('woof') def cat(): print('meow') def fish(): print('blub') WindowSetup(caption='pet simulator',text='d for dog\nc for cat\nf for fish') InputLoop({pygame.K_d:dog, pygame.K_c:cat, pygame.K_f:fish}) ### TWITTER ### def Tweet(twit,statustext): """Tweets a message twit <Twython>, create with Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) statustext <str>, must be <= 140 characters """ if len(statustext) > 140: print('ERROR: Character limit 140 exceeded:',len(statustext)) else: twit.update_status(status=statustext) def TweetPicture(twit,file,statustext): """Tweets a message with a picture twit <Twython>, create with Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) file <str>, path and filename to picture statustext <str>, must be <= 140 characters """ photo = open(file, 'rb') response = twitter.upload_media(media=photo) twit.update_status(status=statustext, media_ids=[response['media_id']]) def TweetVideo(twit,file,statustext): """Tweets a message with a video twit <Twython>, create with Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) file <str>, path and filename to video statustext <str>, must be <= 140 characters """ video = open(file, 'rb') response = twitter.upload_video(media=video, media_type='video/mp4') twit.update_status(status=statustext, media_ids=[response['media_id']])
30.883562
94
0.635174
599
4,509
4.712855
0.338898
0.035423
0.028339
0.022671
0.239816
0.22848
0.172512
0.172512
0.146298
0.146298
0
0.033114
0.223109
4,509
145
95
31.096552
0.772766
0.287425
0
0.046512
0
0
0.117492
0.056106
0
0
0
0
0
1
0.186047
false
0
0.069767
0
0.337209
0.081395
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
717a01e3e2c90ae46a5bad6b2a2010bbac8dace6
1,856
py
Python
python/pyarmnn/scripts/generate_docs.py
PetervdPerk-NXP/pyarmnn-release
2008c270f7c7c84a930842c845138628c8b95713
[ "MIT" ]
7
2020-02-27T07:45:14.000Z
2021-01-25T12:07:12.000Z
python/pyarmnn/scripts/generate_docs.py
MitchellTesla/PyArmNN
cbe37a0364b00f32ac2a8ced74eed5d576a0d52c
[ "MIT" ]
5
2020-07-28T15:01:12.000Z
2022-02-04T18:24:02.000Z
python/pyarmnn/scripts/generate_docs.py
MitchellTesla/PyArmNN
cbe37a0364b00f32ac2a8ced74eed5d576a0d52c
[ "MIT" ]
3
2020-07-31T11:41:24.000Z
2021-06-06T07:58:39.000Z
# Copyright © 2019 Arm Ltd. All rights reserved. # Copyright 2020 NXP # SPDX-License-Identifier: MIT import os import tarfile import pyarmnn as ann import shutil from typing import List, Union from pdoc.cli import main package_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..') def __copy_file_to_dir(file_paths: Union[List[str], str], target_dir_path: str): """Copies multiple files to a directory. Args: file_paths (Union[List(str)]): List of files to copy target_dir_path (str): Target directory. Returns: None """ file_paths = [] + file_paths if not (os.path.exists(target_dir_path) and os.path.isdir(target_dir_path)): os.makedirs(target_dir_path) for file_path in file_paths: if not (os.path.exists(file_path) and os.path.isfile(file_path)): raise RuntimeError('Not a file: {}'.format(file_path)) file_name = os.path.basename(file_path) shutil.copyfile(file_path, os.path.join(str(target_dir_path), file_name)) def archive_docs(path: str, version: str): """Creates an archive. Args: path (str): Path which will be archived. version (str): Version of Arm NN. Returns: None """ output_filename = f'pyarmnn_docs-{version}.tar' with tarfile.open(os.path.join(package_dir, output_filename), "w") as tar: tar.add(path) if __name__ == "__main__": readme_filename = os.path.join(package_dir, '..', '..', 'README.md') with open(readme_filename, 'r') as readme_file: top_level_pyarmnn_doc = ''.join(readme_file.readlines()) ann.__doc__ = top_level_pyarmnn_doc main() target_path = os.path.join(package_dir, 'docs') archive_docs(target_path, ann.__version__)
27.701493
82
0.644935
256
1,856
4.402344
0.351563
0.063886
0.06921
0.045253
0.136646
0.04614
0.04614
0
0
0
0
0.005662
0.238685
1,856
66
83
28.121212
0.791224
0.210129
0
0
0
0
0.051608
0.019447
0
0
0
0
0
1
0.071429
false
0
0.214286
0
0.285714
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
71801cfc804d913976cbde0f2c680802285aa66d
817
py
Python
code/send.py
CamouOkau/messenger_new_years_bot
38f3c26b6c5b4dae7fe48f8b61680ec903c0deac
[ "MIT" ]
null
null
null
code/send.py
CamouOkau/messenger_new_years_bot
38f3c26b6c5b4dae7fe48f8b61680ec903c0deac
[ "MIT" ]
null
null
null
code/send.py
CamouOkau/messenger_new_years_bot
38f3c26b6c5b4dae7fe48f8b61680ec903c0deac
[ "MIT" ]
null
null
null
import sys import time from datetime import datetime from bot import FbMessengerBot if __name__ == "__main__": if len(sys.argv) < 3: print("No email or password provided") else: bot = FbMessengerBot(sys.argv[1], sys.argv[2]) with open("users.txt", "r") as file: users = dict.fromkeys(file.read().split("\n")) for user in users: users[user] = bot.uid(user) with open("message.txt", "r") as file: message = file.read() time_now = datetime.now() send_time = datetime(time_now.year + 1, 1, 1) wait_time = (send_time - time_now).total_seconds() print("Waiting...") time.sleep(wait_time) for uid in users.values(): bot.send_message(message, uid) bot.logout()
29.178571
58
0.575275
107
817
4.233645
0.457944
0.046358
0.02649
0.04415
0
0
0
0
0
0
0
0.010417
0.294982
817
27
59
30.259259
0.776042
0
0
0
0
0
0.086903
0
0
0
0
0
0
1
0
false
0.043478
0.173913
0
0.173913
0.086957
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
71803fa300d2ccbae9efe9edab91921379251431
4,361
py
Python
senlin_tempest_plugin/api/policies/test_policy_update_negative.py
ghanshyammann/senlin-tempest-plugin
9f33bbe723eb381f93c2248a6a277efef3d92ec3
[ "Apache-2.0" ]
null
null
null
senlin_tempest_plugin/api/policies/test_policy_update_negative.py
ghanshyammann/senlin-tempest-plugin
9f33bbe723eb381f93c2248a6a277efef3d92ec3
[ "Apache-2.0" ]
null
null
null
senlin_tempest_plugin/api/policies/test_policy_update_negative.py
ghanshyammann/senlin-tempest-plugin
9f33bbe723eb381f93c2248a6a277efef3d92ec3
[ "Apache-2.0" ]
null
null
null
# 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 tempest.lib import decorators from tempest.lib import exceptions from senlin_tempest_plugin.api import base from senlin_tempest_plugin.common import utils class TestPolicyUpdateNegativeNotFound(base.BaseSenlinAPITest): @decorators.attr(type=['negative']) @decorators.idempotent_id('5df90d82-9889-4c6f-824c-30272bcfa767') def test_policy_update_policy_not_found(self): ex = self.assertRaises(exceptions.NotFound, self.client.update_obj, 'policies', '5df90d82-9889-4c6f-824c-30272bcfa767', {'policy': {'name': 'new-name'}}) message = ex.resp_body['error']['message'] self.assertEqual( "The policy '5df90d82-9889-4c6f-824c-30272bcfa767' " "could not be found.", str(message)) @decorators.attr(type=['negative']) @decorators.idempotent_id('29414add-9cba-4b72-a7bb-36718671dcab') def test_policy_update_policy_invalid_param(self): ex = self.assertRaises(exceptions.BadRequest, self.client.update_obj, 'policies', '5df90d82-9889-4c6f-824c-30272bcfa767', {'policy': {'boo': 'foo'}}) message = ex.resp_body['error']['message'] self.assertEqual( "Additional properties are not allowed (u'boo' was " "unexpected)", str(message)) @decorators.attr(type=['negative']) @decorators.idempotent_id('bf26ed1e-1d26-4472-b4c8-0bcca1c0a838') def test_policy_update_policy_empty_param(self): ex = self.assertRaises(exceptions.BadRequest, self.client.update_obj, 'policies', '5df90d82-9889-4c6f-824c-30272bcfa767', {}) message = ex.resp_body['error']['message'] self.assertEqual( "Malformed request data, missing 'policy' key in " "request body.", str(message)) class TestPolicyUpdateNegativeBadRequest(base.BaseSenlinAPITest): def setUp(self): super(TestPolicyUpdateNegativeBadRequest, self).setUp() # Create a policy policy_id = utils.create_a_policy(self) self.addCleanup(utils.delete_a_policy, self, policy_id) self.policy_id = policy_id @decorators.attr(type=['negative']) @decorators.idempotent_id('31242de5-55ac-4589-87a1-a9940e4beca2') def test_policy_update_no_property_updated(self): # No property is updated. params = { 'policy': {} } # Verify badrequest exception(400) is raised. ex = self.assertRaises(exceptions.BadRequest, self.client.update_obj, 'policies', self.policy_id, params) message = ex.resp_body['error']['message'] self.assertEqual( "'name' is a required property", str(message)) @decorators.attr(type=['negative']) @decorators.idempotent_id('d2ca7de6-0069-48c9-b3de-ee975a2428dc') def test_policy_update_spec_not_updatable(self): # Try to update spec of policy. # Note: name is the only property that can be updated # after policy is created. params = { 'policy': { 'name': 'new-name', 'spec': {'k1': 'v1'} } } # Verify badrequest exception(400) is raised. ex = self.assertRaises(exceptions.BadRequest, self.client.update_obj, 'policies', self.policy_id, params) message = ex.resp_body['error']['message'] self.assertEqual( "Additional properties are not allowed (u'spec' was " "unexpected)", str(message))
40.37963
75
0.616372
468
4,361
5.628205
0.361111
0.022779
0.034169
0.049355
0.474563
0.409643
0.409643
0.373197
0.339787
0.273728
0
0.062599
0.278377
4,361
107
76
40.757009
0.774388
0.173584
0
0.458333
0
0
0.215342
0.090934
0
0
0
0
0.138889
1
0.083333
false
0
0.055556
0
0.166667
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
71820cfe7864a17de8d5ffb455a24ec586958eca
4,363
py
Python
tests/test_vmax.py
qinfeng2011/wltp
317ad38fb96599a29d22e40f69b6aeb4d205611d
[ "Apache-2.0" ]
null
null
null
tests/test_vmax.py
qinfeng2011/wltp
317ad38fb96599a29d22e40f69b6aeb4d205611d
[ "Apache-2.0" ]
null
null
null
tests/test_vmax.py
qinfeng2011/wltp
317ad38fb96599a29d22e40f69b6aeb4d205611d
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2019 European Commission (JRC); # Licensed under the EUPL (the 'Licence'); # You may not use this work except in compliance with the Licence. # You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl import functools as fnt import logging import random import numpy as np import numpy.testing as npt import pandas as pd import pytest from pandas import IndexSlice as _ix from wltp import engine, vehicle, downscale, vmax from wltp.io import gear_names, veh_names from . import vehdb logging.basicConfig(level=logging.DEBUG) log = logging.getLogger(__name__) def test_v_max(h5_accdb): from . import conftest veh_samples = None # DEBUG: to reduce clutter in the console. # veh_samples = 12 # DEBUG: to study buggy cars. # veh_samples = [76] # diff det_by_nlim # veh_samples = [3, 21, 22, 104, ] # diff gear # veh_samples = [38] # diff vmax order higher 1st # veh_samples = [31] # [23] def make_v_maxes(vehnum): props, wot, n2vs = vehdb.load_vehicle_accdb(h5_accdb, vehnum) wot = wot.rename({"Pwot": "p"}, axis=1) wot["n"] = wot.index gwots = engine.interpolate_wot_on_v_grid(wot, n2vs) gwots = engine.calc_p_avail_in_gwots(gwots, SM=0.1) gwots["p_resist"] = vehicle.calc_road_load_power( gwots.index, props.f0, props.f1, props.f2 ) rec = vmax.calc_v_max(gwots) return (props["v_max"], rec.v_max, props["gear_v_max"], rec.g_vmax, rec.wot) def _package_wots_df(gear_wot_dfs): assert gear_wot_dfs ## Merge all index values into the index of the 1st DF, # or else, themerged-df contains n-gear dupes in each index-value. # # first_df, *rest_dfs = gear_wot_dfs.values() # full_index = np.unique(np.hstack(df.index for df in gear_wot_dfs)) # first_df = first_df.reindex(full_index) wots_df = pd.concat( # [first_df] + rest_dfs, gear_wot_dfs.values(), axis=1, # join="inner", keys=gear_names(gear_wot_dfs.keys()), names=["item", "gear"], verify_integrity=True, ) return wots_df veh_nums = vehdb.all_vehnums(h5_accdb) if not isinstance(veh_samples, (list, tuple)): veh_samples = random.sample(veh_nums, veh_samples) if veh_samples else veh_nums recs = [make_v_maxes(vehnum) for vehnum in veh_samples] vehres = pd.DataFrame( recs, columns="vmax_accdb vmax_python gmax_accdb gmax_python wot".split(), index=veh_names(veh_samples), ).astype({"gmax_accdb": "Int64", "gmax_python": "Int64"}) wots_df = pd.concat( vehres["wot"].values, keys=veh_names(veh_samples), names=["vehicle"] ) vehres = vehres.drop("wot", axis=1) vehres["vmax_diff"] = (vehres["vmax_python"] - vehres["vmax_accdb"]).abs() vehres["gmax_diff"] = (vehres["gmax_python"] - vehres["gmax_accdb"]).abs() with pd.option_context( "display.max_rows", 130, "display.max_columns", 20, "display.width", 120, # "display.precision", # 4, # "display.chop_threshold", # 1e-8, "display.float_format", "{:0.2f}".format, ): print( f"++ nones: {vehres.vmax_python.sum()} (out of {len(veh_samples)})" f"\n++++\n{vehres}" # f"\n++++\n{wots_df.sample(80, axis=0)}" ) with pd.option_context( "display.max_columns", 20, "display.width", 120, "display.float_format", "{:0.4f}".format, ): print(f"\n++++\n{vehres.describe().T}") vehres = vehres.dropna(axis=1) # npt.assert_array_equal(vmaxes["vmax_python"], vmaxes["vmax_accdb"]) aggregate_tol = 1e-4 # The digits copied from terminal. assert ( vehres["vmax_diff"].describe() - [125.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000] < aggregate_tol ).all() assert ( vehres["gmax_diff"].describe() - [125.0000, 0.1040, 0.3552, 0.0000, 0.0000, 0.0000, 0.0000, 2.0000] < aggregate_tol ).all() assert (vehres["vmax_diff"] == 0).sum() == 125 and ( vehres["gmax_diff"] == 0 ).sum() == 125
32.080882
87
0.603942
603
4,363
4.170813
0.366501
0.055666
0.035785
0.035785
0.135984
0.122068
0.07992
0.07992
0.015507
0.015507
0
0.049444
0.258309
4,363
135
88
32.318519
0.72775
0.231492
0
0.244444
0
0
0.142513
0.016571
0
0
0
0
0.044444
1
0.033333
false
0
0.133333
0
0.188889
0.022222
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
718275b3e8d58cfc1c69bd90b16b90b94fc076c8
881
py
Python
util/canonicaljson.py
giuseppe/quay
a1b7e4b51974edfe86f66788621011eef2667e6a
[ "Apache-2.0" ]
2,027
2019-11-12T18:05:48.000Z
2022-03-31T22:25:04.000Z
util/canonicaljson.py
giuseppe/quay
a1b7e4b51974edfe86f66788621011eef2667e6a
[ "Apache-2.0" ]
496
2019-11-12T18:13:37.000Z
2022-03-31T10:43:45.000Z
util/canonicaljson.py
giuseppe/quay
a1b7e4b51974edfe86f66788621011eef2667e6a
[ "Apache-2.0" ]
249
2019-11-12T18:02:27.000Z
2022-03-22T12:19:19.000Z
import collections def canonicalize(json_obj, preserve_sequence_order=True): """ This function canonicalizes a Python object that will be serialized as JSON. Example usage: json.dumps(canonicalize(my_obj)) Args: json_obj (object): the Python object that will later be serialized as JSON. Returns: object: json_obj now sorted to its canonical form. """ if isinstance(json_obj, collections.MutableMapping): sorted_obj = sorted( { key: canonicalize(val, preserve_sequence_order) for key, val in json_obj.items() }.items() ) return collections.OrderedDict(sorted_obj) elif isinstance(json_obj, (list, tuple)): seq = [canonicalize(val, preserve_sequence_order) for val in json_obj] return seq if preserve_sequence_order else sorted(seq) return json_obj
32.62963
96
0.681044
110
881
5.281818
0.454545
0.096386
0.144578
0.068847
0.134251
0.134251
0
0
0
0
0
0
0.245176
881
26
97
33.884615
0.873684
0.30874
0
0
0
0
0
0
0
0
0
0
0
1
0.076923
false
0
0.076923
0
0.384615
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
71829ce0488364233ac4688992792bd2903978d0
1,170
py
Python
datasette_plugin_geo/inspect.py
russss/datasette-geo
d4cecc020848bbde91e9e17bf352f7c70bc3dccf
[ "Apache-2.0" ]
9
2019-05-02T14:44:57.000Z
2022-01-19T20:56:50.000Z
datasette_plugin_geo/inspect.py
russss/datasette-geo
d4cecc020848bbde91e9e17bf352f7c70bc3dccf
[ "Apache-2.0" ]
5
2019-04-30T12:22:03.000Z
2021-05-29T20:08:42.000Z
datasette_plugin_geo/inspect.py
russss/datasette-geo
d4cecc020848bbde91e9e17bf352f7c70bc3dccf
[ "Apache-2.0" ]
2
2019-07-31T19:16:43.000Z
2021-05-28T20:12:36.000Z
from datasette import hookimpl from datasette.utils import detect_spatialite from shapely import wkt def get_spatial_tables(conn): if not detect_spatialite(conn): return {} spatial_tables = {} c = conn.cursor() c.execute( """SELECT f_table_name, f_geometry_column, srid, spatial_index_enabled FROM geometry_columns""" ) for row in c.fetchall(): if row[3] != 1: print( "Column {column} in table {table} has no spatial index; datasette-geo will ignore it.".format( column=row[1], table=row[0] ) ) continue spatial_tables[row[0]] = row[1] return spatial_tables def get_bounds(conn, spatial_tables): c = conn.cursor() res = {} for table, column in spatial_tables.items(): c.execute( "SELECT AsText(Envelope(GUnion({column}))) FROM {table}".format( table=table, column=column ) ) data = c.fetchone()[0] if data is None: continue bbox = wkt.loads(data) res[table] = bbox.bounds return res
26.590909
110
0.564957
137
1,170
4.70073
0.423358
0.121118
0.059006
0.055901
0.074534
0
0
0
0
0
0
0.008997
0.335043
1,170
43
111
27.209302
0.818766
0
0
0.171429
0
0.028571
0.130435
0.032136
0
0
0
0
0
1
0.057143
false
0
0.085714
0
0.228571
0.028571
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
7182cc9e1a275d7846a31a780b10f6ed97021067
1,440
py
Python
microcosm_pubsub/context.py
Sinon/microcosm-pubsub
c98a188fcd5b3f358c7171dae0c39a33c5774a4e
[ "Apache-2.0" ]
5
2016-07-23T21:20:50.000Z
2021-07-15T00:27:47.000Z
microcosm_pubsub/context.py
Sinon/microcosm-pubsub
c98a188fcd5b3f358c7171dae0c39a33c5774a4e
[ "Apache-2.0" ]
76
2016-03-22T23:41:21.000Z
2020-07-27T17:35:36.000Z
microcosm_pubsub/context.py
Sinon/microcosm-pubsub
c98a188fcd5b3f358c7171dae0c39a33c5774a4e
[ "Apache-2.0" ]
8
2016-06-01T18:43:41.000Z
2021-04-27T20:22:15.000Z
""" Message context. """ from typing import Dict from microcosm.api import defaults, typed from microcosm.config.types import boolean from microcosm_logging.decorators import logger from microcosm_pubsub.constants import TTL_KEY, URI_KEY from microcosm_pubsub.message import SQSMessage @defaults( enable_ttl=typed(boolean, default_value=True), initial_ttl=typed(int, default_value=32), ) @logger class SQSMessageContext: """ Factory for per-message contexts. """ def __init__(self, graph): self.enable_ttl = graph.config.sqs_message_context.enable_ttl self.initial_ttl = graph.config.sqs_message_context.initial_ttl def __call__(self, context: SQSMessage, **kwargs) -> Dict[str, str]: """ Create a new context from a message. """ return self.from_sqs_message(context, **kwargs) def from_sqs_message(self, message: SQSMessage, **kwargs): context: Dict = dict(message.opaque_data) context.update( # include the message id message_id=message.message_id, **kwargs, ) # include the TTL (if enabled) if self.enable_ttl: ttl = message.ttl if message.ttl is not None else self.initial_ttl context[TTL_KEY] = str(ttl - 1) # include the URI (if there is one) if message.uri: context[URI_KEY] = message.uri return context
26.181818
78
0.6625
180
1,440
5.1
0.344444
0.070806
0.055556
0.037037
0.067538
0.067538
0
0
0
0
0
0.002775
0.249306
1,440
54
79
26.666667
0.846438
0.120833
0
0
0
0
0
0
0
0
0
0
0
1
0.103448
false
0
0.206897
0
0.413793
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
71860bda1bd4506337b0b07e0b43aaca3e5c2511
2,185
py
Python
azure_ml/pytorch_classifier/train_parameterized.py
murdockcrc/python-tricks
57f7ad9c00a045c1f9f18f89bed6e73be6c85b69
[ "MIT" ]
null
null
null
azure_ml/pytorch_classifier/train_parameterized.py
murdockcrc/python-tricks
57f7ad9c00a045c1f9f18f89bed6e73be6c85b69
[ "MIT" ]
null
null
null
azure_ml/pytorch_classifier/train_parameterized.py
murdockcrc/python-tricks
57f7ad9c00a045c1f9f18f89bed6e73be6c85b69
[ "MIT" ]
null
null
null
import os import argparse import torch import torch.optim as optim import torchvision import torchvision.transforms as transforms from model import Net from azureml.core import Run run = Run.get_context() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( '--data_path', type=str, help='Path to the training data' ) parser.add_argument( '--learning_rate', type=float, default=0.001, help='Learning rate for SGD' ) parser.add_argument( '--momentum', type=float, default=0.9, help='Momentum for SGD' ) args = parser.parse_args() print("===== DATA =====") print("DATA PATH: " + args.data_path) print("LIST FILES IN DATA PATH...") print(os.listdir(args.data_path)) print("================") # prepare DataLoader for CIFAR10 data transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ]) trainset = torchvision.datasets.CIFAR10( root=args.data_path, train=True, download=False, transform=transform, ) trainloader = torch.utils.data.DataLoader( trainset, batch_size=4, shuffle=True, num_workers=2 ) # define convolutional network net = Net() # set up pytorch loss / optimizer criterion = torch.nn.CrossEntropyLoss() optimizer = optim.SGD( net.parameters(), lr=args.learning_rate, momentum=args.momentum, ) # train the network for epoch in range(2): running_loss = 0.0 for i, data in enumerate(trainloader, 0): # unpack the data inputs, labels = data # zero the parameter gradients optimizer.zero_grad() # forward + backward + optimize outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() # print statistics running_loss += loss.item() if i % 2000 == 1999: loss = running_loss / 2000 run.log('loss', loss) # log loss metric to AML print(f'epoch={epoch + 1}, batch={i + 1:5}: loss {loss:.2f}') running_loss = 0.0 print('Finished Training')
23
69
0.622426
269
2,185
4.959108
0.420074
0.035982
0.011244
0.014993
0.008996
0.008996
0.008996
0.008996
0.008996
0.008996
0
0.0281
0.250801
2,185
95
70
23
0.786805
0.105263
0
0.09589
0
0
0.126927
0
0
0
0
0
0
1
0
false
0
0.109589
0
0.109589
0.09589
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
7187ac8a1ef00393974831033262a38cc227b4e0
3,063
py
Python
catalyst/core/callbacks/formatters.py
cgarciae/catalyst
391ff89ab0d9a1961b88719e894f917ac0fb7fc3
[ "Apache-2.0" ]
1
2019-11-26T06:41:33.000Z
2019-11-26T06:41:33.000Z
catalyst/core/callbacks/formatters.py
cgarciae/catalyst
391ff89ab0d9a1961b88719e894f917ac0fb7fc3
[ "Apache-2.0" ]
null
null
null
catalyst/core/callbacks/formatters.py
cgarciae/catalyst
391ff89ab0d9a1961b88719e894f917ac0fb7fc3
[ "Apache-2.0" ]
null
null
null
from abc import ABC, abstractmethod from datetime import datetime import json import logging from catalyst import utils from catalyst.core import _State class MetricsFormatter(ABC, logging.Formatter): """ Abstract metrics formatter """ def __init__(self, message_prefix): """ Args: message_prefix: logging format string that will be prepended to message """ super().__init__(f"{message_prefix}{{message}}", style="{") @abstractmethod def _format_message(self, state: _State): pass def format(self, record: logging.LogRecord): """ Format message string """ # noinspection PyUnresolvedReferences state = record.state record.msg = self._format_message(state) return super().format(record) class TxtMetricsFormatter(MetricsFormatter): """ Translate batch metrics in human-readable format. This class is used by ``logging.Logger`` to make a string from record. For details refer to official docs for 'logging' module. Note: This is inner class used by Logger callback, no need to use it directly! """ def __init__(self): """ Initializes the ``TxtMetricsFormatter`` """ super().__init__("[{asctime}] ") def _format_metrics(self, metrics): # metrics : dict[str: dict[str: float]] metrics_formatted = {} for key, value in metrics.items(): metrics_formatted_ = [ utils.format_metric(m_name, m_value) for m_name, m_value in sorted(value.items()) ] metrics_formatted_ = " | ".join(metrics_formatted_) metrics_formatted[key] = metrics_formatted_ return metrics_formatted def _format_message(self, state: _State): message = [""] metrics = self._format_metrics(state.metric_manager.epoch_values) for key, value in metrics.items(): message.append( f"{state.stage_epoch_log}/{state.num_epochs} " f"* Epoch {state.epoch_log} ({key}): {value}" ) message = "\n".join(message) return message class JsonMetricsFormatter(MetricsFormatter): """ Translate batch metrics in json format. This class is used by ``logging.Logger`` to make a string from record. For details refer to official docs for 'logging' module. Note: This is inner class used by Logger callback, no need to use it directly! """ def __init__(self): """ Initializes the ``JsonMetricsFormatter`` """ super().__init__("") def _format_message(self, state: _State): res = dict( metirics=state.metric_manager.epoch_values.copy(), epoch=state.epoch, time=datetime.now().isoformat() ) return json.dumps(res, indent=True, ensure_ascii=False) __all__ = ["MetricsFormatter", "TxtMetricsFormatter", "JsonMetricsFormatter"]
27.845455
77
0.615083
326
3,063
5.558282
0.319018
0.06181
0.018212
0.033113
0.362031
0.286976
0.209713
0.209713
0.209713
0.209713
0
0
0.286321
3,063
109
78
28.100917
0.828911
0.267058
0
0.14
0
0
0.090244
0.033659
0
0
0
0
0
1
0.16
false
0.02
0.12
0
0.42
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
7187ff57f53912dbb2c2ffb581f78542068a9ec6
7,612
py
Python
fuzzy/fuzzy.py
Suraj1127/fuzzy-matcher
a3a6ecc6954d79ca65e2517f93db44cc432e7a90
[ "MIT" ]
null
null
null
fuzzy/fuzzy.py
Suraj1127/fuzzy-matcher
a3a6ecc6954d79ca65e2517f93db44cc432e7a90
[ "MIT" ]
null
null
null
fuzzy/fuzzy.py
Suraj1127/fuzzy-matcher
a3a6ecc6954d79ca65e2517f93db44cc432e7a90
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 """ Description: Python script to append the common columns in one sheet from another sheet using fuzzy matching. """ import pip def import_or_install(package): try: __import__(package) except ImportError: pip.main(['install', package]) import os import sys import argparse import_or_install('numpy') import_or_install('pandas') import_or_install('fuzzywuzzy') import numpy as np import pandas as pd from fuzzywuzzy import process, fuzz class FuzzyMatcher: """ FuzzyMatcher class to perform the fuzzy matching. """ def __init__(self, df_1, df_2, columns_1, columns_2, append_in='second'): """ The constructor takes five arguments. The last argument 'append_in' is optional. Parameters: df_1: the first table in pandas.DataFrame format or the name of the CSV file for the first table df_2: the second table in pandas.DataFrame format or the name of the CSV file for the second table columns_1: list of common columns in the first table columns_2: list of common columns in the second table append_in (optional): 'first' if the common columns are to be appended in the first table 'second' if the common columns are to be appended in the second table """ if type(df_1) == str: df_1 = pd.read_csv(df_1) if type(df_2) == str: df_2 = pd.read_csv(df_2) df_1.columns = df_1.columns.str.lower().str.strip() df_2.columns = df_2.columns.str.lower().str.strip() columns_1 = [i.lower().strip() for i in columns_1] columns_2 = [i.lower().strip() for i in columns_2] if append_in == 'first': temp = df_1 df_1 = df_2 df_2 = temp temp = columns_1 columns_1 = columns_2 columns_2 = temp self.df_1 = df_1.rename(columns=dict(zip(columns_1, columns_2))) self.columns = columns_2 self.df_2 = self._fuzzy_match(self.df_1, df_2, self.columns[0]) @staticmethod def _string_matching(name, collection, mapping_): """ Returns similar name using fuzzy matching. """ if name in collection: return name if name in mapping_: return mapping_[name] similar = process.extractOne(name, collection, scorer=fuzz.ratio)[0] mapping_[name] = similar return similar def _fuzzy_match(self, df_1_t, df_2_t, common_column_t): """ Returns dataframe with the common column appended. Notice that the appended columns end with '_t'. """ collection = set(df_1_t[common_column_t]) mapping_ = {} df_2_t[common_column_t + '_t'] = df_2_t[common_column_t].apply(self._string_matching, args=(collection, mapping_)) return df_2_t @property def fuzzy_match(self): """ Returns the dataframe consisting of all the appended columns. """ for i_t, common_column in enumerate(self.columns[1:], start=1): self.df_2[common_column + '_t'] = np.nan group_1 = self.df_1.groupby(self.columns[:i_t]) group_2 = self.df_2.groupby([i + '_t' for i in self.columns[:i_t]]) for key, df_slice_2 in group_2: df_slice_1 = group_1.get_group(key) df_slice_2 = self._fuzzy_match(df_slice_1, df_slice_2, common_column) self.df_2.loc[df_slice_2.index, common_column + '_t'] = df_slice_2.loc[:, common_column + '_t'] return self.df_2 def save(self, filename): """ Saves the result dataframe to a CSV file, filename. """ self.df_2.to_csv(filename) def parse_args(parser): """ Parsing and configuration of the command line arguments. """ parser = argparse.ArgumentParser() parser.add_argument('--firstcsv', type=str, required=True, help='CSV file for first table.') parser.add_argument('--secondcsv', type=str, required=True, help='CSV file for second table.') parser.add_argument('--destination', type=str, default='output.csv', help='Destination filename.') parser.add_argument('--commoncolumns1', type=str, required=True, help='Common columns for first table.') parser.add_argument('--commoncolumns2', type=str, required=True, help='Common columns for second table in the same order.') parser.add_argument("--in", dest="_in", default='second', choices=['second', 'first'], help='Table to append the columns. ') return check_args(parser.parse_args()) def check_args(args): """ Checking the arguments if they are entered properly. Validations performed: 1. Compulsory arguments are entered. 2. The entered filenames are present in the current folder. 3. The entered column names are present in the corresponding files. 4. If the destination filename is already present in the directory, ask the user if it can be overwritten. """ # for --firstcsv and --secondcsv for filename in [args.firstcsv, args.secondcsv]: if not os.path.isfile(filename): raise Exception("File {} is not present in the currrent folder.".format(filename)) # --commoncolumns1 commoncolumns1 = [i.strip().lower() for i in args.commoncolumns1.split(',')] temp = set(commoncolumns1) - set(pd.read_csv(args.firstcsv, nrows=1).columns.str.lower().str.strip()) if temp: raise Exception("The following columns are not present in the file, {}:\n{}".format(args.firstcsv, temp)) # --commoncolumns2 commoncolumns2 = [i.strip().lower() for i in args.commoncolumns2.split(',')] temp = set(commoncolumns2) - set(pd.read_csv(args.secondcsv, nrows=1).columns.str.lower().str.strip()) if temp: raise Exception("The following columns are not present in the file, {}:\n{}".format(args.secondcsv, temp)) # --destination if os.path.isfile(args.destination): print("The file {} already exists. Do you want to overwrite it? y/n".format(args.destination)) ans = input().strip().lower() if ans == 'n': print("Please enter different destination filename and run the script again.") sys.exit() return args if __name__ == "__main__": # instantiate the ArgumentParser class and parse the arguments parser = argparse.ArgumentParser() arguments = parse_args(parser) # save the arguments as some variables which later would be passed to FuzzyMatcher class filename_1 = arguments.firstcsv filename_2 = arguments.secondcsv result_filename = arguments.destination # clean and lowercase-ize the columns names common_columns_1 = [i.strip().lower() for i in arguments.commoncolumns1.split(',')] common_columns_2 = [i.strip().lower() for i in arguments.commoncolumns2.split(',')] # instantiate the FuzzyMatcher object, perform the fuzzy match, and save the result to the destination CSV file fuzzy_matcher = FuzzyMatcher(filename_1, filename_2, common_columns_1, common_columns_2, append_in=arguments._in) fuzzy_matcher.fuzzy_match fuzzy_matcher.save(result_filename)
35.078341
128
0.626379
994
7,612
4.6167
0.207243
0.013075
0.009152
0.013946
0.208106
0.185879
0.154718
0.115929
0.08455
0.08455
0
0.016667
0.274829
7,612
217
129
35.078341
0.814674
0.237126
0
0.039604
0
0
0.115036
0
0
0
0
0
0
1
0.079208
false
0
0.128713
0
0.287129
0.019802
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
718a2a5b0f6feb828e1a124e9a30a273db18a144
9,770
py
Python
exoatlas/visualizations/panels/BubblePanel.py
zkbt/exopop
5e8b9d391fe9e2d39c623d7ccd7eca8fd0f0f3f8
[ "MIT" ]
4
2020-06-24T16:38:27.000Z
2022-01-23T01:57:19.000Z
exoatlas/visualizations/panels/BubblePanel.py
zkbt/exopop
5e8b9d391fe9e2d39c623d7ccd7eca8fd0f0f3f8
[ "MIT" ]
4
2018-09-20T23:12:30.000Z
2019-05-15T15:31:58.000Z
exoatlas/visualizations/panels/BubblePanel.py
zkbt/exopop
5e8b9d391fe9e2d39c623d7ccd7eca8fd0f0f3f8
[ "MIT" ]
null
null
null
from .Panel import * __all__ = ['BubblePanel'] default_size = plt.matplotlib.rcParams['lines.markersize']**2 class BubblePanel(Panel): ''' BubblePanel is a general wrapper for making scatter plots where planets are represented as bubbles that can have informative sizes and/or colors. ''' def __init__(self, xaxis=None, yaxis=None, size=None, size_normalization=None, color=None, cmap='plasma', vmin=None, vmax=None, color_normalization=None, **kw): ''' Initialize a plotting panel. Parameters ---------- size : PlottableAxis, str, float, None What should the sizes of points be or encode? size_normalization : float If sizes depend on quantities, how should they be normalized? color : PlottableAxis, str, float, None What should the colors of points be or encode? cmap : str, cmap from plt.matplotlib.cm If the colors depend on quantities, what cmap should be used for them? vmin : float, astropy.units.quantity.Quantity If the colors depend on quantities, what should the bottom of the cmap be? vmax : float, astropy.units.quantity.Quantity If the colors depend on quantities, what should the top of the cmap be? color_normalization : matplotlib.colors.Normalize If color depend on quantities, how should the values be normalized. If color_normalization is defined, any values provided here for vmin and vmax will be ignored. **kw : dict Other keywords will be passed on to *all* Panel/Plottable initializations (which may include x, y, size, and color). If you need more fine-grained control over which axis gets which keyword, consider initializing those panels one-by-one. ''' # initialize the basics of the panel with the plottable axes Panel.__init__(self, xaxis=xaxis, yaxis=yaxis, **kw) # set up how we should scale the sizes of points size = clean_axis(size) try: # try to make a variable size axis self.plottable['size'] = size(panel=self, **kw) default_size_normalization = self.plottable['size'].size_normalization except TypeError: # otherwise, use a single size for all points self.plottable['size'] = size default_size_normalization = 1 #self.plottable['x'].panel = self #self.plottable['y'].panel = self # make sure a size normalization has been defined self.size_normalization = size_normalization or default_size_normalization # set up how we should set the colors of points color = clean_axis(color) try: # try to make a variable color axis self.plottable['color'] = color(panel=self, **kw) default_lim = self.plottable['color'].lim except TypeError: # otherwise, use a single color for all points self.plottable['color'] = color default_lim = [None, None] # if an actual cmap was provided, use it if isinstance(cmap, plt.matplotlib.colors.Colormap): self.cmap = cmap # otherwise, treat the cmap as a string key else: self.cmap = plt.matplotlib.cm.cmap_d[cmap] # make sure the color map limits are set self.vmin = vmin or default_lim[0] self.vmax = vmax or default_lim[1] # if a custom normalization is used, reset vmin + vmax self.color_normalization = color_normalization if isinstance(self.color_normalization, plt.matplotlib.colors.Normalize): # pull the normalization's min/max for information self.vmin = color_normalization.vmin self.vmax = color_normalization.vmax # apply (x,y) axis labels, scales, limits appropriately for axis in 'xy': for attribute in ['label', 'scale', 'lim']: setattr(self, f'{axis}{attribute}', getattr(self.plottable[axis], attribute)) #DEBUG self.summarize() def get_sizes(self): ''' The sizes of the bubbles. Returns ------- s : an input for plt.scatter Either a single scalar, or an array with variable sizes for each bubble according to some quantity. ''' # should we ignore any variable size instructions? if self.pop.respond_to_size == False: size = self.pop.plotkw.get('s', None) # if desired, set variable sizes elif isinstance(self.plottable['size'], PlottableAxis): # get the raw values for the sizes x = self.plottable['size'].value() # calculate the normalized size size = default_size*x/self.size_normalization # otherwise, set a single size else: # get default, first from pop and then from panel size = self.pop.plotkw.get('s', self.plottable['size']) # return a valid input to plt.scatter(s=...) return size def get_colors(self): ''' The colors of the bubbles. Returns ------- c : an input for plt.scatter Either a single color, or an array with variable colors for each bubble according to some quantity. ''' # should we ignore any variable color instructions? if self.pop.respond_to_color == False: color = self.pop.color # should we use a variable color? elif isinstance(self.plottable['color'], PlottableAxis): # get the raw values to go into the color x = self.plottable['color'].value() # FIXME - make sure to check vmin/vmax are valid #if (self.vmin is None) or (self.vmax is None): # raise AtlasError(f''' # It looks like you're trying to use # {self.plottable['color']} to set variable # colors for bubbles. To do so, please make # sure it has finite values defined for its # .vmin and .vmax attributes. # ''') # make sure we have *some* normalizer defined f = plt.matplotlib.colors.Normalize self.color_normalization = (self.color_normalization or f(vmin=self.vmin, vmax=self.vmax)) normalized = self.color_normalization(x) color = self.cmap(normalized) # finally, should we just use a default color? else: # get default, first from pop and then from panel color = self.pop.color if color is None: color = self.plottable['color'] # return a valid input to any one of the following: # plt.scatter(c=...) # plt.scatter(edgecolors=...) # plt.scatter(facecolors=...) return color def kw(self, key=None, **kwargs): ''' Do a little decision-making about the plotting keyword arguments, pulling defaults from each population where needed. Parameter --------- key : str The population for which we should pull keywords. If None, go with the current population. **kwargs : dict All other keywords will be directed toward overwriting individual population defaults. ''' # identify the population we're working with if key is None: key = self.key #else: self.point_at(key) # define some default keywords, which can be over-written default = dict(s=self.get_sizes(), marker=self.pop.marker, linewidth=self.pop.linewidth, alpha=self.pop.alpha, zorder=self.pop.zorder, label=self.pop.label) # sort out whether faces and/or edges should get color c=self.get_colors() if self.pop.filled: default['facecolors'] = c else: default['facecolors'] = 'none' if self.pop.outlined: default['edgecolors'] = c else: default['edgecolors'] = 'none' # if any other keywords are provided, overwrite these defaults for k, v in kwargs.items(): default[k] = v return default def plot(self, key, ax=None, labelkw={}, **kwargs): ''' Add the points for a particular population to this panel. Parameters ---------- key : str The population (as an item in the self.pops dictionary) to add. ax : Into what ax should we place this plot? If None, use default. labelkw : dict Keywords for labeling the planet names. **kwargs : dict Any extra keywords will be passed on to `scatter` ''' # focus attention on that population self.point_at(key) # make sure we're plotting into the appropriate axes try: plt.sca(self.ax) except AttributeError: self.setup(ax=ax) # add the scattered points self.scattered[key] = self.ax.scatter(self.x, self.y, **self.kw(key,**kwargs)) # set the scales, limits, labels self.finish_plot(labelkw=labelkw)
35.787546
91
0.570624
1,151
9,770
4.79583
0.238923
0.037681
0.022826
0.009239
0.199094
0.143297
0.096196
0.076449
0.064493
0.064493
0
0.000629
0.349028
9,770
272
92
35.919118
0.867296
0.458444
0
0.142857
0
0
0.036636
0
0
0
0
0.003676
0
1
0.05102
false
0
0.010204
0
0.102041
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
718d447c90c45e89882aa6196cb3c3ab761ce174
2,207
py
Python
githubintro-fe2d832af2bad7d6b27d036c205cc9d8414b2183/CommunicationAnimation.py
TatendaNoreen/Python
df9799bbea84af03c1fb3b29fada1e16c04bab80
[ "MIT" ]
null
null
null
githubintro-fe2d832af2bad7d6b27d036c205cc9d8414b2183/CommunicationAnimation.py
TatendaNoreen/Python
df9799bbea84af03c1fb3b29fada1e16c04bab80
[ "MIT" ]
null
null
null
githubintro-fe2d832af2bad7d6b27d036c205cc9d8414b2183/CommunicationAnimation.py
TatendaNoreen/Python
df9799bbea84af03c1fb3b29fada1e16c04bab80
[ "MIT" ]
null
null
null
import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot import agentframework import csv import matplotlib.animation #create environment in which agents will operate environment=[] #read csv downloaded file f = open('in.txt', newline='') reader = csv.reader(f, quoting=csv.QUOTE_NONNUMERIC) for row in reader: rowlist=[] # A list of rows environment.append(rowlist) for value in row: # A list of value #print(value) # Floats rowlist.append(value) f.close() # Don't close until you are done with the reader; # the data is read on request. #def distance_between(agents_row_a, agents_row_b): # return (((agents_row_a.x - agents_row_b.x)**2) + # ((agents_row_a.y - agents_row_b.y)**2))**0.5 num_of_agents = 10 num_of_iterations = 10 neighbourhood = 20 fig = matplotlib.pyplot.figure(figsize=(7, 7)) ax = fig.add_axes([0, 0, 1, 1]) # Make the agents and connecting with the environment. agents = [] def update(frame_number): fig.clear() for i in range(num_of_agents): agents.append(agentframework.Agent(environment,agents)) # Move and eat agents with every move or iteration. for j in range(num_of_iterations): for i in range(num_of_agents): agents[i].move() agents[i].eat() agents[i].share_with_neighbours(neighbourhood) # Loop through the agents in self.agents . # Calculate the distance between self and the current other agent: # distance = self.distance_between(agent) # If distance is less than or equal to the neighbourhood # Sum self.store and agent.store . # Divide sum by two to calculate average. # self.store = average # agent.store = average # End if # End loop # plot matplotlib.pyplot.xlim(0, 299) matplotlib.pyplot.ylim(0, 299) for i in range(num_of_agents): matplotlib.pyplot.scatter(agents[i].x,agents[i].y) matplotlib.pyplot.imshow(environment) animation = matplotlib.animation.FuncAnimation(fig, update, interval=1) matplotlib.pyplot.show()
24.797753
71
0.645673
299
2,207
4.662207
0.394649
0.080344
0.031564
0.034433
0.055954
0.055954
0.055954
0.040172
0
0
0
0.015235
0.256457
2,207
88
72
25.079545
0.834247
0.366561
0
0.081081
0
0
0.008017
0
0
0
0
0
0
1
0.027027
false
0
0.135135
0
0.162162
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
718e43027722775db4c64b0811dfc59a1835349b
2,418
py
Python
ibis/udf/validate.py
rtpsw/ibis
d7318fdf87121cd8fadbcf0369a2b217aab3053a
[ "Apache-2.0" ]
986
2017-06-07T07:33:01.000Z
2022-03-31T13:00:46.000Z
ibis/udf/validate.py
marlenezw/ibis
14b9baf3e1021e8698e7f0ae3c0ae5747543431c
[ "Apache-2.0" ]
2,623
2017-06-07T18:29:11.000Z
2022-03-31T20:27:31.000Z
ibis/udf/validate.py
marlenezw/ibis
14b9baf3e1021e8698e7f0ae3c0ae5747543431c
[ "Apache-2.0" ]
238
2017-06-26T19:02:58.000Z
2022-03-31T15:18:29.000Z
"""Validation for UDFs. Warning: This is an experimental module and API here can change without notice. DO NOT USE DIRECTLY. """ from inspect import Parameter, Signature, signature from typing import Any, Callable, List import ibis.common.exceptions as com from ibis.expr.datatypes import DataType def _parameter_count(funcsig: Signature) -> int: """Get the number of positional-or-keyword or position-only parameters in a function signature. Parameters ---------- funcsig : inspect.Signature A UDF signature Returns ------- int The number of parameters """ return sum( param.kind in {param.POSITIONAL_OR_KEYWORD, param.POSITIONAL_ONLY} for param in funcsig.parameters.values() if param.default is Parameter.empty ) def validate_input_type( input_type: List[DataType], func: Callable ) -> Signature: """Check that the declared number of inputs (the length of `input_type`) and the number of inputs to `func` are equal. If the signature of `func` uses *args, then no check is done (since no check can be done). Parameters ---------- input_type : List[DataType] func : callable Returns ------- inspect.Signature """ funcsig = signature(func) params = funcsig.parameters.values() # We can only do validation if all the positional arguments are explicit # (i.e. no *args) if not any(param.kind is Parameter.VAR_POSITIONAL for param in params): declared_parameter_count = len(input_type) function_parameter_count = _parameter_count(funcsig) if declared_parameter_count != function_parameter_count: raise TypeError( 'Function signature {!r} has {:d} parameters, ' 'input_type has {:d}. These must match. Non-column ' 'parameters must be defined as keyword only, i.e., ' 'def foo(col, *, function_param).'.format( func.__name__, function_parameter_count, declared_parameter_count, ) ) return funcsig def validate_output_type(output_type: Any) -> None: """Check that the output type is a single datatype.""" if isinstance(output_type, list): raise com.IbisTypeError( 'The output type of a UDF must be a single datatype.' )
28.447059
79
0.639371
295
2,418
5.118644
0.379661
0.074172
0.021854
0.027815
0.043709
0.043709
0
0
0
0
0
0
0.273366
2,418
84
80
28.785714
0.859419
0.324235
0
0
0
0
0.149508
0
0
0
0
0
0
1
0.085714
false
0
0.114286
0
0.257143
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
71915f8963ebf873674df05ecd7d2ac82cadfb43
5,629
py
Python
packages/stattik/stattik/schema/schema.py
stattikcms/stattik
5c96d600d105461edb95a11d8050dee3c32edd1e
[ "MIT" ]
1
2021-11-05T06:24:28.000Z
2021-11-05T06:24:28.000Z
packages/stattik/stattik/schema/schema.py
stattikcms/stattik
5c96d600d105461edb95a11d8050dee3c32edd1e
[ "MIT" ]
null
null
null
packages/stattik/stattik/schema/schema.py
stattikcms/stattik
5c96d600d105461edb95a11d8050dee3c32edd1e
[ "MIT" ]
null
null
null
import inspect from ariadne import make_executable_schema, QueryType, MutationType, SubscriptionType from .resolver import * # # Schema # class GrammarError(Exception): pass keywords = ['query', 'mutation', 'subscription', 'source'] class SchemaMetaDict(dict): ''' Dictionary that allows decorated schema entry functions to be overloaded ''' def __setitem__(self, key, value): if key in self and callable(value) and hasattr(value, 'name'): value.next_func = self[key] if not hasattr(value.next_func, 'name'): raise GrammarError(f'Redefinition of {key}. Perhaps an earlier {key} is missing @_') super().__setitem__(key, value) def __getitem__(self, key): #if key not in self and key.isupper() and key[:1] != '_': if key not in self and key.isupper() and not key[:1] in keywords: return key.upper() else: return super().__getitem__(key) def _query_decorator(name): def decorate(func): func.tag = 'query' func.name = name return func return decorate def _mutation_decorator(name): def decorate(func): func.tag = 'mutation' func.name = name return func return decorate def _subscription_decorator(name): def decorate(func): func.tag = 'subscription' func.name = name return func return decorate def _source_decorator(name): def decorate(func): func.tag = 'source' func.name = name return func return decorate class SchemaMeta(type): @classmethod def __prepare__(meta, *args, **kwargs): d = SchemaMetaDict() d['query'] = _query_decorator d['mutation'] = _mutation_decorator d['subscription'] = _subscription_decorator d['source'] = _source_decorator return d def __new__(meta, selfname, bases, attributes): #del attributes['_'] for key in keywords: del attributes[key] self = super().__new__(meta, selfname, bases, attributes) self._build(list(attributes.items())) return self class Schema(metaclass=SchemaMeta): def __init__(self, parent=None): self.parent = parent self.children = [] if parent: parent.add_child(self) self.db = parent.db else: self.db = self self.entries = self.__class__.entries @classmethod def produce(self, parent=None): schema = self(parent) return schema def add_child(self, schema): self.children.append(schema) def get_gql(self): gql = [inspect.getdoc(self)] for child in self.children: gql.append(child.get_gql()) return "\n".join(gql) def register(self): for entry in self.entries: entry.register(self) for child in self.children: child.register() def add(self, r): self.entries.append(r) @classmethod def __collect_functions(self, definitions): ''' Collect all of the tagged grammar entries ''' entries = [ (name, value) for name, value in definitions if callable(value) and hasattr(value, 'name') ] return entries @classmethod def _build(self, definitions): if vars(self).get('_build', False): return # Collect all of the entry functions from the class definition functions = self.__collect_functions(definitions) self.entries = self.__build_entries(functions) @classmethod def __build_entries(self, functions): entries = [] errors = '' for name, func in functions: entry = self._build_entry(func) entries.append(entry) return entries @classmethod def _build_entry(self, func): tag = func.tag name = func.name prodname = func.__name__ unwrapped = inspect.unwrap(func) filename = unwrapped.__code__.co_filename lineno = unwrapped.__code__.co_firstlineno logger.debug(f"_build_entry:tag: {tag}") logger.debug(f"_build_entry:name: {name}") logger.debug(f"_build_entry:prodname: {prodname}") logger.debug(f"_build_entry:unwrapped: {unwrapped}") #entry = Resolver(name, func, prodname=prodname, filename=filename, lineno=lineno) entry = entry_factories[tag](self, name, func, prodname=prodname, filename=filename, lineno=lineno) logger.debug(f"_build_entry:entry: {entry}") return entry # This is for testing or in case you don't want a database as the root schema class RootSchema(Schema): """ type Query { dummy: Int! } type Mutation { setDummy(val: Int!): Int } type Subscription { dummy: Int } """ instance = None def __init__(self, parent=None): super().__init__(parent) Schema.instance = self self.query_type = QueryType() self.mutation_type = MutationType() self.subscription_type = SubscriptionType() @classmethod def produce(self): if self.instance: return self.instance self.instance = schema = self() return schema def make_executable(self): self.register() #return make_executable_schema(type_defs, self.query) return make_executable_schema( self.get_gql(), self.query_type, self.mutation_type, self.subscription_type )
28.004975
107
0.607035
625
5,629
5.2624
0.2224
0.017026
0.018243
0.025844
0.258133
0.174217
0.138948
0.085436
0.018243
0
0
0.000504
0.294724
5,629
201
108
28.004975
0.82796
0.103393
0
0.234043
0
0
0.064998
0.009084
0
0
0
0
0
1
0.177305
false
0.007092
0.021277
0
0.390071
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
7193df3e00cf1bbbc7e779239b2adfcf9b4f4173
78,616
py
Python
toontown/battle/DistributedBattleBaseAI.py
DankMickey/Project-Altis-Educational-Source
0a74999fb52d4e690a41b984703119f63c372d20
[ "Apache-2.0" ]
1
2021-06-25T02:56:32.000Z
2021-06-25T02:56:32.000Z
toontown/battle/DistributedBattleBaseAI.py
kool601/Project-Altis-Educational-Source
0a74999fb52d4e690a41b984703119f63c372d20
[ "Apache-2.0" ]
null
null
null
toontown/battle/DistributedBattleBaseAI.py
kool601/Project-Altis-Educational-Source
0a74999fb52d4e690a41b984703119f63c372d20
[ "Apache-2.0" ]
2
2017-12-20T17:46:56.000Z
2021-06-25T02:56:36.000Z
import random from otp.ai.AIBase import * from direct.distributed.ClockDelta import * from toontown.battle.BattleBase import * from toontown.battle.BattleCalculatorAI import * from toontown.toonbase.ToontownBattleGlobals import * from toontown.battle.SuitBattleGlobals import * from pandac.PandaModules import * from toontown.battle import BattleExperienceAI from direct.distributed import DistributedObjectAI from direct.fsm import ClassicFSM, State from direct.fsm import State from direct.task import Task from direct.directnotify import DirectNotifyGlobal from toontown.ai import DatabaseObject from toontown.toon import DistributedToonAI from toontown.toon import InventoryBase from toontown.toonbase import ToontownGlobals from toontown.toon import NPCToons from otp.ai.MagicWordGlobal import * from toontown.pets import DistributedPetProxyAI class DistributedBattleBaseAI(DistributedObjectAI.DistributedObjectAI, BattleBase): notify = DirectNotifyGlobal.directNotify.newCategory('DistributedBattleBaseAI') def __init__(self, air, zoneId, finishCallback = None, maxSuits = 4, bossBattle = 0, tutorialFlag = 0, interactivePropTrackBonus = -1): DistributedObjectAI.DistributedObjectAI.__init__(self, air) self.serialNum = 0 self.zoneId = zoneId self.maxSuits = maxSuits self.setBossBattle(bossBattle) self.tutorialFlag = tutorialFlag self.interactivePropTrackBonus = interactivePropTrackBonus self.finishCallback = finishCallback self.avatarExitEvents = [] self.responses = {} self.adjustingResponses = {} self.joinResponses = {} self.adjustingSuits = [] self.adjustingToons = [] self.numSuitsEver = 0 BattleBase.__init__(self) self.streetBattle = 1 self.pos = Point3(0, 0, 0) self.initialSuitPos = Point3(0, 0, 0) self.toonExp = {} self.toonOrigQuests = {} self.toonItems = {} self.toonOrigMerits = {} self.toonMerits = {} self.toonParts = {} self.battleCalc = BattleCalculatorAI(self, tutorialFlag) if self.air.suitInvasionManager.getInvading(): mult = getInvasionMultiplier() self.battleCalc.setSkillCreditMultiplier(mult) if self.air.holidayManager.isMoreXpHolidayRunning(): mult = getMoreXpHolidayMultiplier() self.battleCalc.setSkillCreditMultiplier(mult) self.fsm = None self.clearAttacks() self.ignoreFaceOffDone = 0 self.needAdjust = 0 self.movieHasBeenMade = 0 self.movieHasPlayed = 0 self.rewardHasPlayed = 0 self.movieRequested = 0 self.ignoreResponses = 0 self.ignoreAdjustingResponses = 0 self.taskNames = [] self.exitedToons = [] self.suitsKilled = [] self.suitsKilledThisBattle = [] self.suitsKilledPerFloor = [] self.suitsEncountered = [] self.newToons = [] self.newSuits = [] self.numNPCAttacks = 0 self.npcAttacks = {} self.pets = {} self.fireCount = 0 self.fsm = ClassicFSM.ClassicFSM('DistributedBattleAI', [State.State('FaceOff', self.enterFaceOff, self.exitFaceOff, ['WaitForInput', 'Resume']), State.State('WaitForJoin', self.enterWaitForJoin, self.exitWaitForJoin, ['WaitForInput', 'Resume']), State.State('WaitForInput', self.enterWaitForInput, self.exitWaitForInput, ['MakeMovie', 'Resume']), State.State('MakeMovie', self.enterMakeMovie, self.exitMakeMovie, ['PlayMovie', 'Resume']), State.State('PlayMovie', self.enterPlayMovie, self.exitPlayMovie, ['WaitForJoin', 'Reward', 'Resume']), State.State('Reward', self.enterReward, self.exitReward, ['Resume']), State.State('Resume', self.enterResume, self.exitResume, []), State.State('Off', self.enterOff, self.exitOff, ['FaceOff', 'WaitForJoin'])], 'Off', 'Off') self.joinableFsm = ClassicFSM.ClassicFSM('Joinable', [State.State('Joinable', self.enterJoinable, self.exitJoinable, ['Unjoinable']), State.State('Unjoinable', self.enterUnjoinable, self.exitUnjoinable, ['Joinable'])], 'Unjoinable', 'Unjoinable') self.joinableFsm.enterInitialState() self.runableFsm = ClassicFSM.ClassicFSM('Runable', [State.State('Runable', self.enterRunable, self.exitRunable, ['Unrunable']), State.State('Unrunable', self.enterUnrunable, self.exitUnrunable, ['Runable'])], 'Unrunable', 'Unrunable') self.runableFsm.enterInitialState() self.adjustFsm = ClassicFSM.ClassicFSM('Adjust', [State.State('Adjusting', self.enterAdjusting, self.exitAdjusting, ['NotAdjusting', 'Adjusting']), State.State('NotAdjusting', self.enterNotAdjusting, self.exitNotAdjusting, ['Adjusting'])], 'NotAdjusting', 'NotAdjusting') self.adjustFsm.enterInitialState() self.fsm.enterInitialState() self.startTime = globalClock.getRealTime() self.adjustingTimer = Timer() def clearAttacks(self): self.toonAttacks = {} self.suitAttacks = getDefaultSuitAttacks() def requestDelete(self): if hasattr(self, 'fsm'): self.fsm.request('Off') self.__removeTaskName(self.uniqueName('make-movie')) DistributedObjectAI.DistributedObjectAI.requestDelete(self) def delete(self): self.notify.debug('deleting battle') self.fsm.request('Off') self.ignoreAll() self.__removeAllTasks() del self.fsm del self.joinableFsm del self.runableFsm del self.adjustFsm self.__cleanupJoinResponses() self.timer.stop() del self.timer self.adjustingTimer.stop() del self.adjustingTimer self.battleCalc.cleanup() del self.battleCalc for suit in self.suits: del suit.battleTrap del self.finishCallback for petProxy in self.pets.values(): petProxy.requestDelete() DistributedObjectAI.DistributedObjectAI.delete(self) def pause(self): self.timer.stop() self.adjustingTimer.stop() def unpause(self): self.timer.resume() self.adjustingTimer.resume() def abortBattle(self): self.notify.debug('%s.abortBattle() called.' % self.doId) toonsCopy = self.toons[:] for toonId in toonsCopy: self.__removeToon(toonId) if self.fsm.getCurrentState().getName() == 'PlayMovie' or self.fsm.getCurrentState().getName() == 'MakeMovie': self.exitedToons.append(toonId) self.d_setMembers() self.b_setState('Resume') self.__removeAllTasks() self.timer.stop() self.adjustingTimer.stop() def __removeSuit(self, suit): self.notify.debug('__removeSuit(%d)' % suit.doId) self.suits.remove(suit) self.activeSuits.remove(suit) if self.luredSuits.count(suit) == 1: self.luredSuits.remove(suit) self.suitGone = 1 del suit.battleTrap def findSuit(self, id): for s in self.suits: if s.doId == id: return s return None def __removeTaskName(self, name): if self.taskNames.count(name): self.taskNames.remove(name) self.notify.debug('removeTaskName() - %s' % name) taskMgr.remove(name) def __removeAllTasks(self): for n in self.taskNames: self.notify.debug('removeAllTasks() - %s' % n) taskMgr.remove(n) self.taskNames = [] def __removeToonTasks(self, toonId): name = self.taskName('running-toon-%d' % toonId) self.__removeTaskName(name) name = self.taskName('to-pending-av-%d' % toonId) self.__removeTaskName(name) def getLevelDoId(self): return 0 def getBattleCellId(self): return 0 def getPosition(self): self.notify.debug('getPosition() - %s' % self.pos) return [self.pos[0], self.pos[1], self.pos[2]] def getInitialSuitPos(self): p = [] p.append(self.initialSuitPos[0]) p.append(self.initialSuitPos[1]) p.append(self.initialSuitPos[2]) return p def setBossBattle(self, bossBattle): self.bossBattle = bossBattle def getBossBattle(self): return self.bossBattle def b_setState(self, state): self.notify.debug('network:setState(%s)' % state) stime = globalClock.getRealTime() + SERVER_BUFFER_TIME self.sendUpdate('setState', [state, globalClockDelta.localToNetworkTime(stime)]) self.setState(state) def setState(self, state): self.fsm.request(state) def getState(self): return [self.fsm.getCurrentState().getName(), globalClockDelta.getRealNetworkTime()] def d_setMembers(self): self.notify.debug('network:setMembers()') self.sendUpdate('setMembers', self.getMembers()) def getMembers(self): suits = [] for s in self.suits: suits.append(s.doId) joiningSuits = '' for s in self.joiningSuits: joiningSuits += str(suits.index(s.doId)) pendingSuits = '' for s in self.pendingSuits: pendingSuits += str(suits.index(s.doId)) activeSuits = '' for s in self.activeSuits: activeSuits += str(suits.index(s.doId)) luredSuits = '' for s in self.luredSuits: luredSuits += str(suits.index(s.doId)) suitTraps = '' for s in self.suits: if s.battleTrap == NO_TRAP: suitTraps += '9' elif s.battleTrap == BattleCalculatorAI.TRAP_CONFLICT: suitTraps += '9' else: suitTraps += str(s.battleTrap) toons = [] for t in self.toons: toons.append(t) joiningToons = '' for t in self.joiningToons: joiningToons += str(toons.index(t)) pendingToons = '' for t in self.pendingToons: pendingToons += str(toons.index(t)) activeToons = '' for t in self.activeToons: activeToons += str(toons.index(t)) runningToons = '' for t in self.runningToons: runningToons += str(toons.index(t)) self.notify.debug('getMembers() - suits: %s joiningSuits: %s pendingSuits: %s activeSuits: %s luredSuits: %s suitTraps: %s toons: %s joiningToons: %s pendingToons: %s activeToons: %s runningToons: %s' % (suits, joiningSuits, pendingSuits, activeSuits, luredSuits, suitTraps, toons, joiningToons, pendingToons, activeToons, runningToons)) return [suits, joiningSuits, pendingSuits, activeSuits, luredSuits, suitTraps, toons, joiningToons, pendingToons, activeToons, runningToons, globalClockDelta.getRealNetworkTime()] def d_adjust(self): self.notify.debug('network:adjust()') self.sendUpdate('adjust', [globalClockDelta.getRealNetworkTime()]) def getInteractivePropTrackBonus(self): return self.interactivePropTrackBonus def getZoneId(self): return self.zoneId def getTaskZoneId(self): return self.zoneId def d_setMovie(self): self.notify.debug('network:setMovie()') self.sendUpdate('setMovie', self.getMovie()) self.__updateEncounteredCogs() def getMovie(self): suitIds = [] for s in self.activeSuits: suitIds.append(s.doId) p = [self.movieHasBeenMade] p.append(self.activeToons) p.append(suitIds) for t in self.activeToons: if t in self.toonAttacks: ta = self.toonAttacks[t] index = -1 id = ta[TOON_ID_COL] if id != -1: index = self.activeToons.index(id) track = ta[TOON_TRACK_COL] if (track == NO_ATTACK or attackAffectsGroup(track, ta[TOON_LVL_COL])) and track != NPCSOS and track != PETSOS: target = -1 if track == HEAL: if ta[TOON_LVL_COL] == 1: ta[TOON_HPBONUS_COL] = random.randint(0, 10000) elif track == SOS or track == NPCSOS or track == PETSOS: target = ta[TOON_TGT_COL] elif track == HEAL: if self.activeToons.count(ta[TOON_TGT_COL]) != 0: target = self.activeToons.index(ta[TOON_TGT_COL]) else: target = -1 elif suitIds.count(ta[TOON_TGT_COL]) != 0: target = suitIds.index(ta[TOON_TGT_COL]) else: target = -1 p = p + [index, track, ta[TOON_LVL_COL], target] p = p + ta[4:] else: index = self.activeToons.index(t) attack = getToonAttack(index) p = p + attack for i in range(4 - len(self.activeToons)): p = p + getToonAttack(-1) for sa in self.suitAttacks: index = -1 id = sa[SUIT_ID_COL] if id != -1: index = suitIds.index(id) if sa[SUIT_ATK_COL] == -1: targetIndex = -1 else: targetIndex = sa[SUIT_TGT_COL] if targetIndex == -1: self.notify.debug('suit attack: %d must be group' % sa[SUIT_ATK_COL]) else: toonId = self.activeToons[targetIndex] p = p + [index, sa[SUIT_ATK_COL], targetIndex] sa[SUIT_TAUNT_COL] = 0 if sa[SUIT_ATK_COL] != -1: suit = self.findSuit(id) sa[SUIT_TAUNT_COL] = getAttackTauntIndexFromIndex(suit, sa[SUIT_ATK_COL]) p = p + sa[3:] return p def d_setChosenToonAttacks(self): self.notify.debug('network:setChosenToonAttacks()') self.sendUpdate('setChosenToonAttacks', self.getChosenToonAttacks()) def getChosenToonAttacks(self): ids = [] tracks = [] levels = [] targets = [] for t in self.activeToons: if t in self.toonAttacks: ta = self.toonAttacks[t] else: ta = getToonAttack(t) ids.append(t) tracks.append(ta[TOON_TRACK_COL]) levels.append(ta[TOON_LVL_COL]) targets.append(ta[TOON_TGT_COL]) return [ids, tracks, levels, targets] def d_setBattleExperience(self): self.notify.debug('network:setBattleExperience()') self.sendUpdate('setBattleExperience', self.getBattleExperience()) def getBattleExperience(self): returnValue = BattleExperienceAI.getBattleExperience(4, self.activeToons, self.toonExp, self.battleCalc.toonSkillPtsGained, self.toonOrigQuests, self.toonItems, self.toonOrigMerits, self.toonMerits, self.toonParts, self.suitsKilled, self.helpfulToons) return returnValue def getToonUberStatus(self): fieldList = [] uberIndex = LAST_REGULAR_GAG_LEVEL + 1 for toon in self.activeToons: toonList = [] for trackIndex in range(MAX_TRACK_INDEX): toonList.append(toon.inventory.numItem(track, uberIndex)) fieldList.append(encodeUber(toonList)) return fieldList def addSuit(self, suit): self.notify.debug('addSuit(%d)' % suit.doId) self.newSuits.append(suit) self.suits.append(suit) suit.battleTrap = NO_TRAP self.numSuitsEver += 1 def __joinSuit(self, suit): self.joiningSuits.append(suit) toPendingTime = MAX_JOIN_T + SERVER_BUFFER_TIME taskName = self.taskName('to-pending-av-%d' % suit.doId) self.__addJoinResponse(suit.doId, taskName) self.taskNames.append(taskName) taskMgr.doMethodLater(toPendingTime, self.__serverJoinDone, taskName, extraArgs=(suit.doId, taskName)) def __serverJoinDone(self, avId, taskName): self.notify.debug('join for av: %d timed out on server' % avId) self.__removeTaskName(taskName) self.__makeAvPending(avId) return Task.done def __makeAvPending(self, avId): self.notify.debug('__makeAvPending(%d)' % avId) self.__removeJoinResponse(avId) self.__removeTaskName(self.taskName('to-pending-av-%d' % avId)) if self.toons.count(avId) > 0: self.joiningToons.remove(avId) self.pendingToons.append(avId) else: suit = self.findSuit(avId) if suit != None: if not suit.isEmpty(): if not self.joiningSuits.count(suit) == 1: self.notify.warning('__makeAvPending(%d) in zone: %d' % (avId, self.zoneId)) self.notify.warning('toons: %s' % self.toons) self.notify.warning('joining toons: %s' % self.joiningToons) self.notify.warning('pending toons: %s' % self.pendingToons) self.notify.warning('suits: %s' % self.suits) self.notify.warning('joining suits: %s' % self.joiningSuits) self.notify.warning('pending suits: %s' % self.pendingSuits) self.joiningSuits.remove(suit) self.pendingSuits.append(suit) else: self.notify.warning('makeAvPending() %d not in toons or suits' % avId) return self.d_setMembers() self.needAdjust = 1 self.__requestAdjust() def suitRequestJoin(self, suit): self.notify.debug('suitRequestJoin(%d)' % suit.getDoId()) if self.suitCanJoin(): self.addSuit(suit) self.__joinSuit(suit) self.d_setMembers() suit.prepareToJoinBattle() return 1 else: self.notify.warning('suitRequestJoin() - not joinable - joinable state: %s max suits: %d' % (self.joinableFsm.getCurrentState().getName(), self.maxSuits)) return 0 def addToon(self, avId): self.notify.debug('addToon(%d)' % avId) toon = self.getToon(avId) if toon == None: return 0 toon.stopToonUp() event = simbase.air.getAvatarExitEvent(avId) self.avatarExitEvents.append(event) self.accept(event, self.__handleUnexpectedExit, extraArgs=[avId]) event = 'inSafezone-%s' % avId self.avatarExitEvents.append(event) self.accept(event, self.__handleSuddenExit, extraArgs=[avId, 0]) self.newToons.append(avId) self.toons.append(avId) toon = simbase.air.doId2do.get(avId) if toon: if hasattr(self, 'doId'): toon.b_setBattleId(self.doId) else: toon.b_setBattleId(-1) messageToonAdded = 'Battle adding toon %s' % avId messenger.send(messageToonAdded, [avId]) if self.fsm != None and self.fsm.getCurrentState().getName() == 'PlayMovie': self.responses[avId] = 1 else: self.responses[avId] = 0 self.adjustingResponses[avId] = 0 if avId not in self.toonExp: p = [] for t in Tracks: p.append(toon.experience.getExp(t)) self.toonExp[avId] = p if avId not in self.toonOrigMerits: self.toonOrigMerits[avId] = toon.cogMerits[:] if avId not in self.toonMerits: self.toonMerits[avId] = [0, 0, 0, 0, 0] if avId not in self.toonOrigQuests: flattenedQuests = [] for quest in toon.quests: flattenedQuests.extend(quest) self.toonOrigQuests[avId] = flattenedQuests if avId not in self.toonItems: self.toonItems[avId] = ([], []) return 1 def __joinToon(self, avId, pos): self.joiningToons.append(avId) toPendingTime = MAX_JOIN_T + SERVER_BUFFER_TIME taskName = self.taskName('to-pending-av-%d' % avId) self.__addJoinResponse(avId, taskName, toon=1) taskMgr.doMethodLater(toPendingTime, self.__serverJoinDone, taskName, extraArgs=(avId, taskName)) self.taskNames.append(taskName) def __updateEncounteredCogs(self): for toon in self.activeToons: if toon in self.newToons: for suit in self.activeSuits: if hasattr(suit, 'dna'): self.suitsEncountered.append({'type': suit.dna.name, 'activeToons': self.activeToons[:]}) else: self.notify.warning('Suit has no DNA in zone %s: toons involved = %s' % (self.zoneId, self.activeToons)) return self.newToons.remove(toon) for suit in self.activeSuits: if suit in self.newSuits: if hasattr(suit, 'dna'): self.suitsEncountered.append({'type': suit.dna.name, 'activeToons': self.activeToons[:]}) else: self.notify.warning('Suit has no DNA in zone %s: toons involved = %s' % (self.zoneId, self.activeToons)) return self.newSuits.remove(suit) def __makeToonRun(self, toonId, updateAttacks): self.activeToons.remove(toonId) self.toonGone = 1 self.runningToons.append(toonId) taskName = self.taskName('running-toon-%d' % toonId) taskMgr.doMethodLater(TOON_RUN_T, self.__serverRunDone, taskName, extraArgs=(toonId, updateAttacks, taskName)) self.taskNames.append(taskName) def __serverRunDone(self, toonId, updateAttacks, taskName): self.notify.debug('run for toon: %d timed out on server' % toonId) self.__removeTaskName(taskName) self.__removeToon(toonId) self.d_setMembers() if len(self.toons) == 0: self.notify.debug('last toon is gone - battle is finished') self.b_setState('Resume') else: if updateAttacks == 1: self.d_setChosenToonAttacks() self.needAdjust = 1 self.__requestAdjust() return Task.done def __requestAdjust(self): if not self.fsm: return cstate = self.fsm.getCurrentState().getName() if cstate == 'WaitForInput' or cstate == 'WaitForJoin': if self.adjustFsm.getCurrentState().getName() == 'NotAdjusting': if self.needAdjust == 1: self.d_adjust() self.adjustingSuits = [] for s in self.pendingSuits: self.adjustingSuits.append(s) self.adjustingToons = [] for t in self.pendingToons: self.adjustingToons.append(t) self.adjustFsm.request('Adjusting') else: self.notify.debug('requestAdjust() - dont need to') else: self.notify.debug('requestAdjust() - already adjusting') else: self.notify.debug('requestAdjust() - in state: %s' % cstate) def __handleUnexpectedExit(self, avId): #TODO: fixme #disconnectCode = self.air.getAvatarDisconnectReason(avId) disconnectCode = "placeHolder dc code, need self.air.getAvatarDisconnectReason(avId)" self.notify.warning('toon: %d exited unexpectedly, reason %s' % (avId, disconnectCode)) #userAborted = disconnectCode == ToontownGlobals.DisconnectCloseWindow #TODO: fixme userAborted = False self.__handleSuddenExit(avId, userAborted) def __handleSuddenExit(self, avId, userAborted): self.__removeToon(avId, userAborted=userAborted) if self.fsm.getCurrentState().getName() == 'PlayMovie' or self.fsm.getCurrentState().getName() == 'MakeMovie': self.exitedToons.append(avId) self.d_setMembers() if len(self.toons) == 0: self.notify.debug('last toon is gone - battle is finished') self.__removeAllTasks() self.timer.stop() self.adjustingTimer.stop() self.b_setState('Resume') else: self.needAdjust = 1 self.__requestAdjust() def __removeSuit(self, suit): self.notify.debug('__removeSuit(%d)' % suit.doId) self.suits.remove(suit) self.activeSuits.remove(suit) if self.luredSuits.count(suit) == 1: self.luredSuits.remove(suit) self.suitGone = 1 del suit.battleTrap def __removeToon(self, toonId, userAborted = 0): self.notify.debug('__removeToon(%d)' % toonId) if self.toons.count(toonId) == 0: return self.battleCalc.toonLeftBattle(toonId) self.__removeToonTasks(toonId) self.toons.remove(toonId) if self.joiningToons.count(toonId) == 1: self.joiningToons.remove(toonId) if self.pendingToons.count(toonId) == 1: self.pendingToons.remove(toonId) if self.activeToons.count(toonId) == 1: activeToonIdx = self.activeToons.index(toonId) self.notify.debug('removing activeToons[%d], updating suitAttacks SUIT_HP_COL to match' % activeToonIdx) for i in range(len(self.suitAttacks)): if activeToonIdx < len(self.suitAttacks[i][SUIT_HP_COL]): del self.suitAttacks[i][SUIT_HP_COL][activeToonIdx] else: self.notify.warning("suitAttacks %d doesn't have an HP column for active toon index %d" % (i, activeToonIdx)) self.activeToons.remove(toonId) if self.runningToons.count(toonId) == 1: self.runningToons.remove(toonId) if self.adjustingToons.count(toonId) == 1: self.notify.warning('removeToon() - toon: %d was adjusting!' % toonId) self.adjustingToons.remove(toonId) self.toonGone = 1 if toonId in self.pets: self.pets[toonId].requestDelete() del self.pets[toonId] self.__removeResponse(toonId) self.__removeAdjustingResponse(toonId) self.__removeJoinResponses(toonId) event = simbase.air.getAvatarExitEvent(toonId) self.avatarExitEvents.remove(event) self.ignore(event) event = 'inSafezone-%s' % toonId self.avatarExitEvents.remove(event) self.ignore(event) toon = simbase.air.doId2do.get(toonId) if toon: toon.b_setBattleId(0) messageToonReleased = 'Battle releasing toon %s' % toon.doId messenger.send(messageToonReleased, [toon.doId]) if not userAborted: toon = self.getToon(toonId) if toon != None: toon.hpOwnedByBattle = 0 toon.d_setHp(toon.hp) toon.d_setInventory(toon.inventory.makeNetString()) self.air.cogPageManager.toonEncounteredCogs(toon, self.suitsEncountered, self.getTaskZoneId()) elif len(self.suits) > 0 and not self.streetBattle: self.notify.info('toon %d aborted non-street battle; clearing inventory and hp.' % toonId) toon = DistributedToonAI.DistributedToonAI(self.air) toon.doId = toonId empty = InventoryBase.InventoryBase(toon) toon.b_setInventory(empty.makeNetString()) toon.b_setHp(0) db = DatabaseObject.DatabaseObject(self.air, toonId) db.storeObject(toon, ['setInventory', 'setHp']) self.notify.info('killing mem leak from temporary DistributedToonAI %d' % toonId) toon.deleteDummy() def getToon(self, toonId): if toonId in self.air.doId2do: return self.air.doId2do[toonId] else: self.notify.warning('getToon() - toon: %d not in repository!' % toonId) return def toonRequestRun(self): toonId = self.air.getAvatarIdFromSender() if self.ignoreResponses == 1: self.notify.debug('ignoring response from toon: %d' % toonId) return self.notify.debug('toonRequestRun(%d)' % toonId) if not self.isRunable(): self.notify.warning('toonRequestRun() - not runable') return updateAttacks = 0 if self.activeToons.count(toonId) == 0: self.notify.warning('toon tried to run, but not found in activeToons: %d' % toonId) return for toon in self.activeToons: if toon in self.toonAttacks: ta = self.toonAttacks[toon] track = ta[TOON_TRACK_COL] level = ta[TOON_LVL_COL] if ta[TOON_TGT_COL] == toonId or track == HEAL and attackAffectsGroup(track, level) and len(self.activeToons) <= 2: healerId = ta[TOON_ID_COL] self.notify.debug('resetting toon: %ds attack' % healerId) self.toonAttacks[toon] = getToonAttack(toon, track=UN_ATTACK) self.responses[healerId] = 0 updateAttacks = 1 self.__makeToonRun(toonId, updateAttacks) self.d_setMembers() self.needAdjust = 1 self.__requestAdjust() def toonRequestJoin(self, x, y, z): toonId = self.air.getAvatarIdFromSender() self.notify.debug('toonRequestJoin(%d)' % toonId) self.signupToon(toonId, x, y, z) def toonDied(self): toonId = self.air.getAvatarIdFromSender() self.notify.debug('toonDied(%d)' % toonId) if toonId in self.toons: toon = self.getToon(toonId) if toon: toon.hp = -1 toon.inventory.zeroInv(1) self.__handleSuddenExit(toonId, 0) def signupToon(self, toonId, x, y, z): if self.toons.count(toonId): return if self.toonCanJoin(): if self.addToon(toonId): self.__joinToon(toonId, Point3(x, y, z)) self.d_setMembers() else: self.notify.warning('toonRequestJoin() - not joinable') self.d_denyLocalToonJoin(toonId) def d_denyLocalToonJoin(self, toonId): self.notify.debug('network: denyLocalToonJoin(%d)' % toonId) self.sendUpdateToAvatarId(toonId, 'denyLocalToonJoin', []) def resetResponses(self): self.responses = {} for t in self.toons: self.responses[t] = 0 self.ignoreResponses = 0 def allToonsResponded(self): for t in self.toons: if self.responses[t] == 0: return 0 self.ignoreResponses = 1 return 1 def __allPendingActiveToonsResponded(self): for t in self.pendingToons + self.activeToons: if self.responses[t] == 0: return 0 self.ignoreResponses = 1 return 1 def __allActiveToonsResponded(self): for t in self.activeToons: if self.responses[t] == 0: return 0 self.ignoreResponses = 1 return 1 def __removeResponse(self, toonId): del self.responses[toonId] if self.ignoreResponses == 0 and len(self.toons) > 0: currStateName = self.fsm.getCurrentState().getName() if currStateName == 'WaitForInput': if self.__allActiveToonsResponded(): self.notify.debug('removeResponse() - dont wait for movie') self.__requestMovie() elif currStateName == 'PlayMovie': if self.__allPendingActiveToonsResponded(): self.notify.debug('removeResponse() - surprise movie done') self.__movieDone() elif currStateName == 'Reward' or currStateName == 'BuildingReward': if self.__allActiveToonsResponded(): self.notify.debug('removeResponse() - surprise reward done') self.handleRewardDone() def __resetAdjustingResponses(self): self.adjustingResponses = {} for t in self.toons: self.adjustingResponses[t] = 0 self.ignoreAdjustingResponses = 0 def __allAdjustingToonsResponded(self): for t in self.toons: if self.adjustingResponses[t] == 0: return 0 self.ignoreAdjustingResponses = 1 return 1 def __removeAdjustingResponse(self, toonId): if toonId in self.adjustingResponses: del self.adjustingResponses[toonId] if self.ignoreAdjustingResponses == 0 and len(self.toons) > 0: if self.__allAdjustingToonsResponded(): self.__adjustDone() def __addJoinResponse(self, avId, taskName, toon = 0): if toon == 1: for jr in self.joinResponses.values(): jr[avId] = 0 self.joinResponses[avId] = {} for t in self.toons: self.joinResponses[avId][t] = 0 self.joinResponses[avId]['taskName'] = taskName def __removeJoinResponses(self, avId): self.__removeJoinResponse(avId) removedOne = 0 for j in self.joinResponses.values(): if avId in j: del j[avId] removedOne = 1 if removedOne == 1: for t in self.joiningToons: if self.__allToonsRespondedJoin(t): self.__makeAvPending(t) def __removeJoinResponse(self, avId): if avId in self.joinResponses: taskMgr.remove(self.joinResponses[avId]['taskName']) del self.joinResponses[avId] def __allToonsRespondedJoin(self, avId): jr = self.joinResponses[avId] for t in self.toons: if jr[t] == 0: return 0 return 1 def __cleanupJoinResponses(self): for jr in self.joinResponses.values(): taskMgr.remove(jr['taskName']) del jr def adjustDone(self): toonId = self.air.getAvatarIdFromSender() if self.ignoreAdjustingResponses == 1: self.notify.debug('adjustDone() - ignoring toon: %d' % toonId) return elif self.adjustFsm.getCurrentState().getName() != 'Adjusting': self.notify.warning('adjustDone() - in state %s' % self.fsm.getCurrentState().getName()) return elif self.toons.count(toonId) == 0: self.notify.warning('adjustDone() - toon: %d not in toon list' % toonId) return self.adjustingResponses[toonId] += 1 self.notify.debug('toon: %d done adjusting' % toonId) if self.__allAdjustingToonsResponded(): self.__adjustDone() def timeout(self): toonId = self.air.getAvatarIdFromSender() if self.ignoreResponses == 1: self.notify.debug('timeout() - ignoring toon: %d' % toonId) return elif self.fsm.getCurrentState().getName() != 'WaitForInput': self.notify.warning('timeout() - in state: %s' % self.fsm.getCurrentState().getName()) return elif self.toons.count(toonId) == 0: self.notify.warning('timeout() - toon: %d not in toon list' % toonId) return self.toonAttacks[toonId] = getToonAttack(toonId) self.d_setChosenToonAttacks() self.responses[toonId] += 1 self.notify.debug('toon: %d timed out' % toonId) if self.__allActiveToonsResponded(): self.__requestMovie(timeout=1) def movieDone(self): toonId = self.air.getAvatarIdFromSender() if self.ignoreResponses == 1: self.notify.debug('movieDone() - ignoring toon: %d' % toonId) return elif self.fsm.getCurrentState().getName() != 'PlayMovie': self.notify.warning('movieDone() - in state %s' % self.fsm.getCurrentState().getName()) return elif self.toons.count(toonId) == 0: self.notify.warning('movieDone() - toon: %d not in toon list' % toonId) return self.responses[toonId] += 1 self.notify.debug('toon: %d done with movie' % toonId) if self.__allPendingActiveToonsResponded(): self.__movieDone() else: self.timer.stop() self.timer.startCallback(TIMEOUT_PER_USER, self.__serverMovieDone) def rewardDone(self): toonId = self.air.getAvatarIdFromSender() stateName = self.fsm.getCurrentState().getName() if self.ignoreResponses == 1: self.notify.debug('rewardDone() - ignoring toon: %d' % toonId) return elif stateName not in ('Reward', 'BuildingReward', 'FactoryReward', 'MintReward', 'StageReward', 'CountryClubReward'): self.notify.warning('rewardDone() - in state %s' % stateName) return elif self.toons.count(toonId) == 0: self.notify.warning('rewardDone() - toon: %d not in toon list' % toonId) return self.responses[toonId] += 1 self.notify.debug('toon: %d done with reward' % toonId) if self.__allActiveToonsResponded(): self.handleRewardDone() else: self.timer.stop() self.timer.startCallback(TIMEOUT_PER_USER, self.serverRewardDone) def assignRewards(self): if self.rewardHasPlayed == 1: self.notify.debug('handleRewardDone() - reward has already played') return self.rewardHasPlayed = 1 BattleExperienceAI.assignRewards(self.activeToons, self.battleCalc.toonSkillPtsGained, self.suitsKilled, self.getTaskZoneId(), self.helpfulToons) def joinDone(self, avId): toonId = self.air.getAvatarIdFromSender() if self.toons.count(toonId) == 0: self.notify.warning('joinDone() - toon: %d not in toon list' % toonId) return if avId not in self.joinResponses: self.notify.debug('joinDone() - no entry for: %d - ignoring: %d' % (avId, toonId)) return jr = self.joinResponses[avId] if toonId in jr: jr[toonId] += 1 self.notify.debug('client with localToon: %d done joining av: %d' % (toonId, avId)) if self.__allToonsRespondedJoin(avId): self.__makeAvPending(avId) def requestAttack(self, track, level, av): toonId = self.air.getAvatarIdFromSender() if self.ignoreResponses == 1: self.notify.debug('requestAttack() - ignoring toon: %d' % toonId) return elif self.fsm.getCurrentState().getName() != 'WaitForInput': self.notify.warning('requestAttack() - in state: %s' % self.fsm.getCurrentState().getName()) return elif self.activeToons.count(toonId) == 0: self.notify.warning('requestAttack() - toon: %d not in toon list' % toonId) return self.notify.debug('requestAttack(%d, %d, %d, %d)' % (toonId, track, level, av)) toon = self.getToon(toonId) if toon == None: self.notify.warning('requestAttack() - no toon: %d' % toonId) return validResponse = 1 if track == SOS: self.notify.debug('toon: %d calls for help' % toonId) self.air.writeServerEvent('friendSOS', toonId, '%s' % av) self.toonAttacks[toonId] = getToonAttack(toonId, track=SOS, target=av) elif track == NPCSOS: self.notify.debug('toon: %d calls for help' % toonId) self.air.writeServerEvent('NPCSOS', toonId, '%s' % av) toon = self.getToon(toonId) if toon == None: return if av in toon.NPCFriendsDict: npcCollision = 0 if av in self.npcAttacks: callingToon = self.npcAttacks[av] if self.activeToons.count(callingToon) == 1: self.toonAttacks[toonId] = getToonAttack(toonId, track=PASS) npcCollision = 1 if npcCollision == 0: self.toonAttacks[toonId] = getToonAttack(toonId, track=NPCSOS, level=5, target=av) self.numNPCAttacks += 1 self.npcAttacks[av] = toonId elif track == PETSOS: self.notify.debug('toon: %d calls for pet: %d' % (toonId, av)) self.air.writeServerEvent('PETSOS', toonId, '%s' % av) toon = self.getToon(toonId) if toon == None: return if not self.validate(toonId, level in toon.petTrickPhrases, 'requestAttack: invalid pet trickId: %s' % level): return self.toonAttacks[toonId] = getToonAttack(toonId, track=PETSOS, level=level, target=av) elif track == UN_ATTACK: self.notify.debug('toon: %d changed its mind' % toonId) self.toonAttacks[toonId] = getToonAttack(toonId, track=UN_ATTACK) if toonId in self.responses: self.responses[toonId] = 0 validResponse = 0 elif track == PASS: self.toonAttacks[toonId] = getToonAttack(toonId, track=PASS) elif track == FIRE: if simbase.air.doId2do[toonId].getPinkSlips() < self.getFireCount() + 1: #Not allowed to fire, force them to pass >:D self.toonAttacks[toonId] = getToonAttack(toonId, track=PASS) else: #Allowed to fire self.setFireCount(self.fireCount + 1) self.toonAttacks[toonId] = getToonAttack(toonId, track=FIRE, target=av) else: if not self.validate(toonId, track >= 0 and track <= MAX_TRACK_INDEX, 'requestAttack: invalid track %s' % track): return if not self.validate(toonId, level >= 0 and level <= MAX_LEVEL_INDEX, 'requestAttack: invalid level %s' % level): return if toon.inventory.numItem(track, level) == 0: self.notify.warning('requestAttack() - toon has no item track: %d level: %d' % (track, level)) self.toonAttacks[toonId] = getToonAttack(toonId) return if track == HEAL: if self.runningToons.count(av) == 1 or attackAffectsGroup(track, level) and len(self.activeToons) < 2: self.toonAttacks[toonId] = getToonAttack(toonId, track=UN_ATTACK) validResponse = 0 else: self.toonAttacks[toonId] = getToonAttack(toonId, track=track, level=level, target=av) else: self.toonAttacks[toonId] = getToonAttack(toonId, track=track, level=level, target=av) if av == -1 and not attackAffectsGroup(track, level): validResponse = 0 self.d_setChosenToonAttacks() if validResponse == 1: self.responses[toonId] += 1 self.notify.debug('toon: %d chose an attack' % toonId) if self.__allActiveToonsResponded(): self.__requestMovie() def requestPetProxy(self, av): toonId = self.air.getAvatarIdFromSender() if self.ignoreResponses == 1: self.notify.debug('requestPetProxy() - ignoring toon: %d' % toonId) return elif self.fsm.getCurrentState().getName() != 'WaitForInput': self.notify.warning('requestPetProxy() - in state: %s' % self.fsm.getCurrentState().getName()) return elif self.activeToons.count(toonId) == 0: self.notify.warning('requestPetProxy() - toon: %d not in toon list' % toonId) return self.notify.debug('requestPetProxy(%s, %s)' % (toonId, av)) toon = self.getToon(toonId) if toon == None: self.notify.warning('requestPetProxy() - no toon: %d' % toonId) return petId = toon.getPetId() zoneId = self.zoneId if petId == av: if not toonId in self.pets: def handleGetPetProxy(success, pet, petId = petId, zoneId = zoneId, toonId = toonId): if success: petProxy = DistributedPetProxyAI.DistributedPetProxyAI(self.air) petProxy.setOwnerId(pet.getOwnerId()) petProxy.setPetName(pet.getPetName()) petProxy.setTraitSeed(pet.getTraitSeed()) petProxy.setSafeZone(pet.getSafeZone()) petProxy.setForgetfulness(pet.getForgetfulness()) petProxy.setBoredomThreshold(pet.getBoredomThreshold()) petProxy.setRestlessnessThreshold(pet.getRestlessnessThreshold()) petProxy.setPlayfulnessThreshold(pet.getPlayfulnessThreshold()) petProxy.setLonelinessThreshold(pet.getLonelinessThreshold()) petProxy.setSadnessThreshold(pet.getSadnessThreshold()) petProxy.setFatigueThreshold(pet.getFatigueThreshold()) petProxy.setHungerThreshold(pet.getHungerThreshold()) petProxy.setConfusionThreshold(pet.getConfusionThreshold()) petProxy.setExcitementThreshold(pet.getExcitementThreshold()) petProxy.setAngerThreshold(pet.getAngerThreshold()) petProxy.setSurpriseThreshold(pet.getSurpriseThreshold()) petProxy.setAffectionThreshold(pet.getAffectionThreshold()) petProxy.setHead(pet.getHead()) petProxy.setEars(pet.getEars()) petProxy.setNose(pet.getNose()) petProxy.setTail(pet.getTail()) petProxy.setBodyTexture(pet.getBodyTexture()) petProxy.setColor(pet.getColor()) petProxy.setColorScale(pet.getColorScale()) petProxy.setEyeColor(pet.getEyeColor()) petProxy.setGender(pet.getGender()) petProxy.setLastSeenTimestamp(pet.getLastSeenTimestamp()) petProxy.setBoredom(pet.getBoredom()) petProxy.setRestlessness(pet.getRestlessness()) petProxy.setPlayfulness(pet.getPlayfulness()) petProxy.setLoneliness(pet.getLoneliness()) petProxy.setSadness(pet.getSadness()) petProxy.setAffection(pet.getAffection()) petProxy.setHunger(pet.getHunger()) petProxy.setConfusion(pet.getConfusion()) petProxy.setExcitement(pet.getExcitement()) petProxy.setFatigue(pet.getFatigue()) petProxy.setAnger(pet.getAnger()) petProxy.setSurprise(pet.getSurprise()) petProxy.setTrickAptitudes(pet.getTrickAptitudes()) pet.requestDelete() def deleted(task): petProxy.doNotDeallocateChannel = True petProxy.generateWithRequiredAndId(petId, self.air.districtId, self.zoneId) petProxy.broadcastDominantMood() self.pets[toonId] = petProxy return task.done self.acceptOnce(self.air.getAvatarExitEvent(petId), lambda: taskMgr.doMethodLater(0, deleted, self.uniqueName('petdel-%d' % petId))) else: self.notify.warning('error generating petProxy: %s' % petId) self.getPetProxyObject(petId, handleGetPetProxy) def suitCanJoin(self): return len(self.suits) < self.maxSuits and self.isJoinable() def toonCanJoin(self): return len(self.toons) < 4 and self.isJoinable() def __requestMovie(self, timeout = 0): if self.adjustFsm.getCurrentState().getName() == 'Adjusting': self.notify.debug('__requestMovie() - in Adjusting') self.movieRequested = 1 else: movieDelay = 0 if len(self.activeToons) == 0: self.notify.warning('only pending toons left in battle %s, toons = %s' % (self.doId, self.toons)) elif len(self.activeSuits) == 0: self.notify.warning('only pending suits left in battle %s, suits = %s' % (self.doId, self.suits)) elif len(self.activeToons) > 1 and not timeout: movieDelay = 1 self.fsm.request('MakeMovie') if movieDelay: taskMgr.doMethodLater(0.8, self.__makeMovie, self.uniqueName('make-movie')) self.taskNames.append(self.uniqueName('make-movie')) else: self.__makeMovie() def __makeMovie(self, task = None): self.notify.debug('makeMovie()') if self._DOAI_requestedDelete: self.notify.warning('battle %s requested delete, then __makeMovie was called!' % self.doId) if hasattr(self, 'levelDoId'): self.notify.warning('battle %s in level %s' % (self.doId, self.levelDoId)) return self.__removeTaskName(self.uniqueName('make-movie')) if self.movieHasBeenMade == 1: self.notify.debug('__makeMovie() - movie has already been made') return self.movieRequested = 0 self.movieHasBeenMade = 1 self.movieHasPlayed = 0 self.rewardHasPlayed = 0 for t in self.activeToons: if t not in self.toonAttacks: self.toonAttacks[t] = getToonAttack(t) attack = self.toonAttacks[t] if attack[TOON_TRACK_COL] == PASS or attack[TOON_TRACK_COL] == UN_ATTACK: self.toonAttacks[t] = getToonAttack(t) if self.toonAttacks[t][TOON_TRACK_COL] != NO_ATTACK: self.addHelpfulToon(t) self.battleCalc.calculateRound() for t in self.activeToons: self.sendEarnedExperience(t) toon = self.getToon(t) if toon != None: toon.hpOwnedByBattle = 1 if toon.immortalMode: toon.toonUp(toon.maxHp) self.d_setMovie() self.b_setState('PlayMovie') return Task.done def sendEarnedExperience(self, toonId): toon = self.getToon(toonId) if toon != None: expList = self.battleCalc.toonSkillPtsGained.get(toonId, None) if expList == None: toon.d_setEarnedExperience([]) else: roundList = [] for exp in expList: roundList.append(int(exp + 0.5)) toon.d_setEarnedExperience(roundList) def enterOff(self): return def exitOff(self): return def enterFaceOff(self): return def exitFaceOff(self): return def enterWaitForJoin(self): self.notify.debug('enterWaitForJoin()') if len(self.activeSuits) > 0: self.b_setState('WaitForInput') else: self.notify.debug('enterWaitForJoin() - no active suits') self.runableFsm.request('Runable') self.resetResponses() self.__requestAdjust() def exitWaitForJoin(self): pass def enterWaitForInput(self): self.notify.debug('enterWaitForInput()') self.joinableFsm.request('Joinable') self.runableFsm.request('Runable') self.resetResponses() self.__requestAdjust() if not self.tutorialFlag: self.timer.startCallback(SERVER_INPUT_TIMEOUT, self.__serverTimedOut) self.npcAttacks = {} for toonId in self.toons: if bboard.get('autoRestock-%s' % toonId, False): toon = self.air.doId2do.get(toonId) if toon is not None: toon.doRestock(0) def exitWaitForInput(self): self.npcAttacks = {} self.timer.stop() def __serverTimedOut(self): self.notify.debug('wait for input timed out on server') self.ignoreResponses = 1 self.__requestMovie(timeout=1) def enterMakeMovie(self): self.notify.debug('enterMakeMovie()') self.runableFsm.request('Unrunable') self.resetResponses() def exitMakeMovie(self): pass def enterPlayMovie(self): self.notify.debug('enterPlayMovie()') self.joinableFsm.request('Joinable') self.runableFsm.request('Unrunable') self.resetResponses() movieTime = TOON_ATTACK_TIME * (len(self.activeToons) + self.numNPCAttacks) + SUIT_ATTACK_TIME * len(self.activeSuits) + SERVER_BUFFER_TIME self.numNPCAttacks = 0 self.notify.debug('estimated upper bound of movie time: %f' % movieTime) self.timer.startCallback(movieTime, self.__serverMovieDone) def __serverMovieDone(self): self.notify.debug('movie timed out on server') self.ignoreResponses = 1 self.__movieDone() def serverRewardDone(self): self.notify.debug('reward timed out on server') self.ignoreResponses = 1 self.handleRewardDone() def handleRewardDone(self): self.b_setState('Resume') def exitPlayMovie(self): self.timer.stop() def __movieDone(self): self.notify.debug('__movieDone() - movie is finished') if self.movieHasPlayed == 1: self.notify.debug('__movieDone() - movie had already finished') return self.movieHasBeenMade = 0 self.movieHasPlayed = 1 self.ignoreResponses = 1 needUpdate = 0 toonHpDict = {} for toon in self.activeToons: toonHpDict[toon] = [0, 0, 0] actualToon = self.getToon(toon) self.notify.debug('BEFORE ROUND: toon: %d hp: %d' % (toon, actualToon.hp)) deadSuits = [] trapDict = {} suitsLuredOntoTraps = [] npcTrapAttacks = [] for activeToon in self.activeToons + self.exitedToons: if activeToon in self.toonAttacks: attack = self.toonAttacks[activeToon] track = attack[TOON_TRACK_COL] npc_level = None if track == NPCSOS: track, npc_level, npc_hp = NPCToons.getNPCTrackLevelHp(attack[TOON_TGT_COL]) if track == None: track = NPCSOS elif track == TRAP: npcTrapAttacks.append(attack) toon = self.getToon(attack[TOON_ID_COL]) av = attack[TOON_TGT_COL] if toon != None and av in toon.NPCFriendsDict: toon.NPCFriendsDict[av] -= 1 if toon.NPCFriendsDict[av] <= 0: del toon.NPCFriendsDict[av] toon.d_setNPCFriendsDict(toon.NPCFriendsDict) continue if track != NO_ATTACK: toonId = attack[TOON_ID_COL] level = attack[TOON_LVL_COL] if npc_level != None: level = npc_level if attack[TOON_TRACK_COL] == NPCSOS: toon = self.getToon(toonId) av = attack[TOON_TGT_COL] if toon != None and av in toon.NPCFriendsDict: toon.NPCFriendsDict[av] -= 1 if toon.NPCFriendsDict[av] <= 0: del toon.NPCFriendsDict[av] toon.d_setNPCFriendsDict(toon.NPCFriendsDict) elif track == PETSOS: pass elif track == FIRE: pass elif track != SOS: toon = self.getToon(toonId) if toon != None: check = toon.inventory.useItem(track, level) if check == -1: self.air.writeServerEvent('suspicious', toonId, 'Toon generating movie for non-existant gag track %s level %s' % (track, level)) self.notify.warning('generating movie for non-existant gag track %s level %s! avId: %s' % (track, level, toonId)) toon.d_setInventory(toon.inventory.makeNetString()) hps = attack[TOON_HP_COL] if track == SOS: self.notify.debug('toon: %d called for help' % toonId) elif track == NPCSOS: self.notify.debug('toon: %d called for help' % toonId) elif track == PETSOS: self.notify.debug('toon: %d called for pet' % toonId) for i in range(len(self.activeToons)): toon = self.getToon(self.activeToons[i]) if toon != None: if i < len(hps): hp = hps[i] if hp > 0: toonHpDict[toon.doId][0] += hp self.notify.debug('pet heal: toon: %d healed for hp: %d' % (toon.doId, hp)) else: self.notify.warning('Invalid targetIndex %s in hps %s.' % (i, hps)) elif track == NPC_RESTOCK_GAGS: for at in self.activeToons: toon = self.getToon(at) if toon != None: toon.inventory.NPCMaxOutInv(npc_level) toon.d_setInventory(toon.inventory.makeNetString()) elif track == HEAL: if levelAffectsGroup(HEAL, level): for i in range(len(self.activeToons)): at = self.activeToons[i] if at != toonId or attack[TOON_TRACK_COL] == NPCSOS: toon = self.getToon(at) if toon != None: if i < len(hps): hp = hps[i] else: self.notify.warning('Invalid targetIndex %s in hps %s.' % (i, hps)) hp = 0 toonHpDict[toon.doId][0] += hp self.notify.debug('HEAL: toon: %d healed for hp: %d' % (toon.doId, hp)) else: targetId = attack[TOON_TGT_COL] toon = self.getToon(targetId) if toon != None and targetId in self.activeToons: targetIndex = self.activeToons.index(targetId) if targetIndex < len(hps): hp = hps[targetIndex] else: self.notify.warning('Invalid targetIndex %s in hps %s.' % (targetIndex, hps)) hp = 0 toonHpDict[toon.doId][0] += hp elif attackAffectsGroup(track, level, attack[TOON_TRACK_COL]): for suit in self.activeSuits: targetIndex = self.activeSuits.index(suit) if targetIndex < 0 or targetIndex >= len(hps): self.notify.warning('Got attack (%s, %s) on target suit %s, but hps has only %s entries: %s' % (track, level, targetIndex, len(hps), hps)) else: hp = hps[targetIndex] if hp > 0 and track == LURE: if suit.battleTrap == UBER_GAG_LEVEL_INDEX: pass suit.battleTrap = NO_TRAP needUpdate = 1 if suit.doId in trapDict: del trapDict[suit.doId] if suitsLuredOntoTraps.count(suit) == 0: suitsLuredOntoTraps.append(suit) if track == TRAP: targetId = suit.doId if targetId in trapDict: trapDict[targetId].append(attack) else: trapDict[targetId] = [attack] needUpdate = 1 died = attack[SUIT_DIED_COL] & 1 << targetIndex if died != 0: if deadSuits.count(suit) == 0: deadSuits.append(suit) else: targetId = attack[TOON_TGT_COL] target = self.findSuit(targetId) if target != None: targetIndex = self.activeSuits.index(target) if targetIndex < 0 or targetIndex >= len(hps): self.notify.warning('Got attack (%s, %s) on target suit %s, but hps has only %s entries: %s' % (track, level, targetIndex, len(hps), hps)) else: hp = hps[targetIndex] if track == TRAP: if targetId in trapDict: trapDict[targetId].append(attack) else: trapDict[targetId] = [attack] if hp > 0 and track == LURE: oldBattleTrap = target.battleTrap if oldBattleTrap == UBER_GAG_LEVEL_INDEX: pass target.battleTrap = NO_TRAP needUpdate = 1 if target.doId in trapDict: del trapDict[target.doId] if suitsLuredOntoTraps.count(target) == 0: suitsLuredOntoTraps.append(target) if oldBattleTrap == UBER_GAG_LEVEL_INDEX: for otherSuit in self.activeSuits: if not otherSuit == target: otherSuit.battleTrap = NO_TRAP if otherSuit.doId in trapDict: del trapDict[otherSuit.doId] died = attack[SUIT_DIED_COL] & 1 << targetIndex if died != 0: if deadSuits.count(target) == 0: deadSuits.append(target) self.exitedToons = [] for suitKey in trapDict.keys(): attackList = trapDict[suitKey] attack = attackList[0] target = self.findSuit(attack[TOON_TGT_COL]) if attack[TOON_LVL_COL] == UBER_GAG_LEVEL_INDEX: targetId = suitKey target = self.findSuit(targetId) if len(attackList) == 1: if suitsLuredOntoTraps.count(target) == 0: self.notify.debug('movieDone() - trap set') target.battleTrap = attack[TOON_LVL_COL] needUpdate = 1 else: target.battleTrap = NO_TRAP else: self.notify.debug('movieDone() - traps collided') if target != None: target.battleTrap = NO_TRAP if self.battleCalc.trainTrapTriggered: self.notify.debug('Train trap triggered, clearing all traps') for otherSuit in self.activeSuits: self.notify.debug('suit =%d, oldBattleTrap=%d' % (otherSuit.doId, otherSuit.battleTrap)) otherSuit.battleTrap = NO_TRAP currLuredSuits = self.battleCalc.getLuredSuits() if len(self.luredSuits) == len(currLuredSuits): for suit in self.luredSuits: if currLuredSuits.count(suit.doId) == 0: needUpdate = 1 break else: needUpdate = 1 self.luredSuits = [] for i in currLuredSuits: suit = self.air.doId2do[i] self.luredSuits.append(suit) self.notify.debug('movieDone() - suit: %d is lured' % i) for attack in npcTrapAttacks: track, level, hp = NPCToons.getNPCTrackLevelHp(attack[TOON_TGT_COL]) for suit in self.activeSuits: if self.luredSuits.count(suit) == 0 and suit.battleTrap == NO_TRAP: suit.battleTrap = level needUpdate = 1 for suit in deadSuits: self.notify.debug('removing dead suit: %d' % suit.doId) if suit.isDeleted(): self.notify.debug('whoops, suit %d is deleted.' % suit.doId) else: self.notify.debug('suit had revives? %d' % suit.getMaxSkeleRevives()) encounter = {'type': suit.dna.name, 'level': suit.getActualLevel(), 'track': suit.dna.dept, 'isSkelecog': suit.getSkelecog(), 'isForeman': suit.isForeman(), 'isVP': 0, 'isCFO': 0, 'isSupervisor': suit.isSupervisor(), 'isVirtual': suit.isVirtual(), 'hasRevives': suit.getMaxSkeleRevives(), 'activeToons': self.activeToons[:]} self.suitsKilled.append(encounter) self.suitsKilledThisBattle.append(encounter) self.air.suitInvasionManager.handleSuitDefeated() self.__removeSuit(suit) needUpdate = 1 suit.resume() lastActiveSuitDied = 0 if len(self.activeSuits) == 0 and len(self.pendingSuits) == 0: lastActiveSuitDied = 1 for i in range(4): attack = self.suitAttacks[i][SUIT_ATK_COL] if attack != NO_ATTACK: suitId = self.suitAttacks[i][SUIT_ID_COL] suit = self.findSuit(suitId) if suit == None: self.notify.warning('movieDone() - suit: %d is gone!' % suitId) continue if not (hasattr(suit, 'dna') and suit.dna): toonId = self.air.getAvatarIdFromSender() self.notify.warning('_movieDone avoiding crash, sender=%s but suit has no dna' % toonId) self.air.writeServerEvent('suspicious', toonId, '_movieDone avoiding crash, suit has no dna') continue adict = getSuitAttack(suit.getStyleName(), suit.getLevel(), attack) hps = self.suitAttacks[i][SUIT_HP_COL] if adict['group'] == ATK_TGT_GROUP: for activeToon in self.activeToons: toon = self.getToon(activeToon) if toon != None: targetIndex = self.activeToons.index(activeToon) toonDied = self.suitAttacks[i][TOON_DIED_COL] & 1 << targetIndex if targetIndex >= len(hps): self.notify.warning('DAMAGE: toon %s is no longer in battle!' % activeToon) else: hp = hps[targetIndex] if hp > 0: self.notify.debug('DAMAGE: toon: %d hit for dmg: %d' % (activeToon, hp)) if toonDied != 0: toonHpDict[toon.doId][2] = 1 toonHpDict[toon.doId][1] += hp elif adict['group'] == ATK_TGT_SINGLE: targetIndex = self.suitAttacks[i][SUIT_TGT_COL] if targetIndex >= len(self.activeToons): self.notify.warning('movieDone() - toon: %d gone!' % targetIndex) break toonId = self.activeToons[targetIndex] toon = self.getToon(toonId) toonDied = self.suitAttacks[i][TOON_DIED_COL] & 1 << targetIndex if targetIndex >= len(hps): self.notify.warning('DAMAGE: toon %s is no longer in battle!' % toonId) else: hp = hps[targetIndex] if hp > 0: self.notify.debug('DAMAGE: toon: %d hit for dmg: %d' % (toonId, hp)) if toonDied != 0: toonHpDict[toon.doId][2] = 1 toonHpDict[toon.doId][1] += hp deadToons = [] for activeToon in self.activeToons: hp = toonHpDict[activeToon] toon = self.getToon(activeToon) if toon != None: self.notify.debug('AFTER ROUND: currtoonHP: %d toonMAX: %d hheal: %d damage: %d' % (toon.hp, toon.maxHp, hp[0], hp[1])) toon.hpOwnedByBattle = 0 hpDelta = hp[0] - hp[1] if hpDelta >= 0: toon.toonUp(hpDelta, quietly=1) else: toon.takeDamage(-hpDelta, quietly=1) if toon.hp <= 0: self.notify.debug('movieDone() - toon: %d was killed' % activeToon) toon.inventory.zeroInv(1) deadToons.append(activeToon) self.notify.debug('AFTER ROUND: toon: %d setHp: %d' % (toon.doId, toon.hp)) if toon.unlimitedGags: toon.doRestock(noUber=0, noPaid=0) for deadToon in deadToons: self.__removeToon(deadToon) needUpdate = 1 self.clearAttacks() self.d_setMovie() self.d_setChosenToonAttacks() self.localMovieDone(needUpdate, deadToons, deadSuits, lastActiveSuitDied) def enterResume(self): for suit in self.suits: self.notify.info('battle done, resuming suit: %d' % suit.doId) if suit.isDeleted(): self.notify.info('whoops, suit %d is deleted.' % suit.doId) else: suit.resume() self.suits = [] self.joiningSuits = [] self.pendingSuits = [] self.adjustingSuits = [] self.activeSuits = [] self.luredSuits = [] for toonId in self.toons: toon = simbase.air.doId2do.get(toonId) if toon: toon.b_setBattleId(0) messageToonReleased = 'Battle releasing toon %s' % toon.doId messenger.send(messageToonReleased, [toon.doId]) for exitEvent in self.avatarExitEvents: self.ignore(exitEvent) eventMsg = {} for encounter in self.suitsKilledThisBattle: cog = encounter['type'] level = encounter['level'] msgName = '%s%s' % (cog, level) if encounter['isSkelecog']: msgName += '+' if msgName in eventMsg: eventMsg[msgName] += 1 else: eventMsg[msgName] = 1 msgText = '' for msgName, count in eventMsg.items(): if msgText != '': msgText += ',' msgText += '%s%s' % (count, msgName) self.air.writeServerEvent('battleCogsDefeated', self.doId, '%s|%s' % (msgText, self.getTaskZoneId())) def exitResume(self): pass def isJoinable(self): return self.joinableFsm.getCurrentState().getName() == 'Joinable' def enterJoinable(self): self.notify.debug('enterJoinable()') def exitJoinable(self): pass def enterUnjoinable(self): self.notify.debug('enterUnjoinable()') def exitUnjoinable(self): pass def isRunable(self): return self.runableFsm.getCurrentState().getName() == 'Runable' def enterRunable(self): self.notify.debug('enterRunable()') def exitRunable(self): pass def enterUnrunable(self): self.notify.debug('enterUnrunable()') def exitUnrunable(self): pass def __estimateAdjustTime(self): self.needAdjust = 0 adjustTime = 0 if len(self.pendingSuits) > 0 or self.suitGone == 1: self.suitGone = 0 pos0 = self.suitPendingPoints[0][0] pos1 = self.suitPoints[0][0][0] adjustTime = self.calcSuitMoveTime(pos0, pos1) if len(self.pendingToons) > 0 or self.toonGone == 1: self.toonGone = 0 if adjustTime == 0: pos0 = self.toonPendingPoints[0][0] pos1 = self.toonPoints[0][0][0] adjustTime = self.calcToonMoveTime(pos0, pos1) return adjustTime def enterAdjusting(self): self.notify.debug('enterAdjusting()') self.timer.stop() self.__resetAdjustingResponses() self.adjustingTimer.startCallback(self.__estimateAdjustTime() + SERVER_BUFFER_TIME, self.__serverAdjustingDone) def __serverAdjustingDone(self): if self.needAdjust == 1: self.adjustFsm.request('NotAdjusting') self.__requestAdjust() else: self.notify.debug('adjusting timed out on the server') self.ignoreAdjustingResponses = 1 self.__adjustDone() def exitAdjusting(self): currStateName = self.fsm.getCurrentState().getName() if currStateName == 'WaitForInput': self.timer.restart() elif currStateName == 'WaitForJoin': self.b_setState('WaitForInput') self.adjustingTimer.stop() def __addTrainTrapForNewSuits(self): hasTrainTrap = False trapInfo = None for otherSuit in self.activeSuits: if otherSuit.battleTrap == UBER_GAG_LEVEL_INDEX: hasTrainTrap = True if hasTrainTrap: for curSuit in self.activeSuits: if not curSuit.battleTrap == UBER_GAG_LEVEL_INDEX: oldBattleTrap = curSuit.battleTrap curSuit.battleTrap = UBER_GAG_LEVEL_INDEX self.battleCalc.addTrainTrapForJoiningSuit(curSuit.doId) self.notify.debug('setting traintrack trap for joining suit %d oldTrap=%s' % (curSuit.doId, oldBattleTrap)) def __adjustDone(self): for s in self.adjustingSuits: self.pendingSuits.remove(s) self.activeSuits.append(s) self.adjustingSuits = [] for toon in self.adjustingToons: if self.pendingToons.count(toon) == 1: self.pendingToons.remove(toon) else: self.notify.warning('adjustDone() - toon: %d not pending!' % toon.doId) if self.activeToons.count(toon) == 0: self.activeToons.append(toon) self.ignoreResponses = 0 self.sendEarnedExperience(toon) else: self.notify.warning('adjustDone() - toon: %d already active!' % toon.doId) self.adjustingToons = [] self.__addTrainTrapForNewSuits() self.d_setMembers() self.adjustFsm.request('NotAdjusting') if self.needAdjust == 1: self.notify.debug('__adjustDone() - need to adjust again') self.__requestAdjust() def enterNotAdjusting(self): self.notify.debug('enterNotAdjusting()') if self.movieRequested == 1: if len(self.activeToons) > 0 and self.__allActiveToonsResponded(): self.__requestMovie() def exitNotAdjusting(self): pass def getPetProxyObject(self, petId, callback): doneEvent = 'generate-%d' % petId def handlePetProxyRead(pet): callback(1, pet) self.air.sendActivate(petId, self.air.districtId, 0) self.acceptOnce(doneEvent, handlePetProxyRead) def _getNextSerialNum(self): num = self.serialNum self.serialNum += 1 return num def setFireCount(self, amount): self.fireCount = amount def getFireCount(self): return self.fireCount @magicWord(category=CATEGORY_PROGRAMMER) def skipMovie(): invoker = spellbook.getInvoker() battleId = invoker.getBattleId() if not battleId: return 'You are not currently in a battle!' battle = simbase.air.doId2do.get(battleId) battle._DistributedBattleBaseAI__movieDone() return 'Battle movie skipped.'
42.221267
279
0.551567
7,380
78,616
5.80542
0.107317
0.036178
0.034661
0.009756
0.347563
0.276398
0.220638
0.186747
0.154047
0.14072
0
0.006696
0.348415
78,616
1,861
280
42.243955
0.829693
0.00262
0
0.387077
0
0.001812
0.087457
0.001824
0
0
0
0.000537
0
1
0.076087
false
0.010266
0.012681
0.009662
0.144324
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
719665fcbb1b48dc2e95347865f8f0d20166bbd8
2,127
py
Python
conf/constants.py
codingwangfeng/GoodGoodName
02bfeb3ae65fd9ba0354f5b67237fcad4c0e11cb
[ "MIT" ]
null
null
null
conf/constants.py
codingwangfeng/GoodGoodName
02bfeb3ae65fd9ba0354f5b67237fcad4c0e11cb
[ "MIT" ]
null
null
null
conf/constants.py
codingwangfeng/GoodGoodName
02bfeb3ae65fd9ba0354f5b67237fcad4c0e11cb
[ "MIT" ]
null
null
null
# -*-coding:utf-8-*- # from functools import reduce from functools import reduce SANCAI_jixiang = [1, 3, 5, 7, 8, 11, 13, 15, 16, 18, 21, 23, 24, 25, 31, 32, 33, 35, 37, 39, 41, 45, 47, 48, 52, 57, 61, 63, 65, 67, 68, 81] # 吉祥运暗示数(代表健全,幸福,名誉等) SANCAI_xiaoji = [6, 17, 26, 27, 29, 30, 38, 49, 51, 55, 58, 71, 73, 75] # 次吉祥运暗示数(代表多少有些障碍,但能获得吉运) SANCAI_xiong = [2, 4, 9, 10, 12, 14, 19, 20, 22, 28, 34, 36, 40, 42, 43, 44, 46, 50, 53, 54, 56, 59, 60, 62, 64, 66, 69, 70, 72, 74, 76, 77, 78, 79, 80] # 凶数运暗示数(代表逆境,沉浮,薄弱,病难,困难,多灾等) SANCAI_wise = [3, 13, 16, 21, 23, 29, 31, 37, 39, 41, 45, 47] # 首领运暗示数(智慧 )仁勇全备,立上位,能领导众人) SANCAI_wealth = [15, 16, 24, 29, 32, 33, 41, 52] # 财富运暗示数(多钱财,富贵,白手可获巨财) SANCAI_artist = [13, 14, 18, 26, 29, 33, 35, 38, 48] # 艺能运暗示数(富有艺术天才,对审美,艺术,演艺,体育有通达之能) SANCAI_goodwife = [5, 6, 11, 13, 15, 16, 24, 32, 35] # 女德运暗示数(具有妇德,品性温良,助夫爱子) SANCAI_death = [21, 23, 26, 28, 29, 33, 39] # 女性孤寡运暗示数(难觅夫君,家庭不和,夫妻两虎相斗,离婚,严重者夫妻一方早亡) SANCAI_alone = [4, 10, 12, 14, 22, 28, 34] # 孤独运暗示数(妻凌夫或夫克妻) SANCAI_merry = [5, 6, 15, 16, 32, 39, 41] # 双妻运暗示数 SANCAI_stubbon = [7, 17, 18, 25, 27, 28, 37, 47] # 刚情运暗示数(性刚固执,意气用事) SANCAI_gentle = [5, 6, 11, 15, 16, 24, 31, 32, 35] # 温和运暗示数(性情平和,能得上下信望) # 可以自己配置觉得好的数字 # 参考好的搭配 refer_good_num_list = [SANCAI_jixiang, SANCAI_xiaoji, SANCAI_wise, SANCAI_wealth, SANCAI_artist, SANCAI_goodwife, SANCAI_merry, SANCAI_gentle] # 自己设定的好的搭配 good_num_list = [SANCAI_jixiang, SANCAI_xiaoji, SANCAI_wise, SANCAI_wealth, SANCAI_artist, SANCAI_goodwife, SANCAI_merry, SANCAI_gentle] # 参考坏的搭配 refer_bad_num_list = [SANCAI_xiong, SANCAI_death, SANCAI_alone, SANCAI_stubbon] # 自己设定的坏的搭配 bad_num_list = [SANCAI_xiong, SANCAI_death, SANCAI_alone] good_num_set = set(reduce((lambda x, y: x + y), good_num_list, [])) bad_num_set = set(reduce((lambda x, y: x + y), bad_num_list, [])) print('五格好分值:', good_num_set) print('五格差分值:', bad_num_set) # 筛选出有好没坏的三才五格 best_num_set = [x for x in good_num_set if x not in bad_num_set] print('想要的三才五格数字:', best_num_set) RESULT_UNKNOWN = '结果未知'
49.465116
120
0.640809
367
2,127
3.53406
0.476839
0.037008
0.040093
0.038551
0.285274
0.269854
0.269854
0.269854
0.269854
0.164996
0
0.174501
0.199812
2,127
42
121
50.642857
0.587544
0.181946
0
0.066667
0
0
0.015125
0
0
0
0
0
0
1
0
false
0
0.033333
0
0.033333
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
7196e863b7922259efe8d454892b5eb76fb7593e
27,897
py
Python
bzt/modules/blazemeter/blazemeter_reporter.py
beachwood23/taurus
698ac747bae5d4940a879a8526add67c11ef42da
[ "Apache-2.0" ]
null
null
null
bzt/modules/blazemeter/blazemeter_reporter.py
beachwood23/taurus
698ac747bae5d4940a879a8526add67c11ef42da
[ "Apache-2.0" ]
34
2017-08-31T22:54:12.000Z
2022-03-16T00:39:48.000Z
bzt/modules/blazemeter/blazemeter_reporter.py
beachwood23/taurus
698ac747bae5d4940a879a8526add67c11ef42da
[ "Apache-2.0" ]
null
null
null
""" Module for reporting into http://www.blazemeter.com/ service Copyright 2015 BlazeMeter 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. """ import copy import logging import os import platform import sys import time import traceback import zipfile from collections import defaultdict, OrderedDict from io import BytesIO from urllib.error import HTTPError import requests from bzt import TaurusInternalException, TaurusConfigError, TaurusNetworkError from bzt.bza import User, Session, Test from bzt.engine import Reporter, Singletone from bzt.utils import b, humanize_bytes, iteritems, open_browser, BetterDict, to_json, dehumanize_time from bzt.modules.aggregator import AggregatorListener, DataPoint, KPISet, ResultsProvider, ConsolidatingAggregator from bzt.modules.monitoring import Monitoring, MonitoringListener from bzt.modules.blazemeter.project_finder import ProjectFinder from bzt.modules.blazemeter.const import NOTE_SIZE_LIMIT class BlazeMeterUploader(Reporter, AggregatorListener, MonitoringListener, Singletone): """ Reporter class :type _test: bzt.bza.Test :type _master: bzt.bza.Master :type _session: bzt.bza.Session """ def __init__(self): super(BlazeMeterUploader, self).__init__() self.browser_open = 'start' self.kpi_buffer = [] self.send_interval = 30 self._last_status_check = time.time() self.send_data = True self.upload_artifacts = True self.send_monitoring = True self.monitoring_buffer = None self.public_report = False self.last_dispatch = 0 self.results_url = None self._user = User() self._test = None self._master = None self._session = None self.first_ts = sys.maxsize self.last_ts = 0 self.report_name = None self._dpoint_serializer = DatapointSerializer(self) def prepare(self): """ Read options for uploading, check that they're sane """ super(BlazeMeterUploader, self).prepare() self.send_interval = dehumanize_time(self.settings.get("send-interval", self.send_interval)) self.send_monitoring = self.settings.get("send-monitoring", self.send_monitoring) monitoring_buffer_limit = self.settings.get("monitoring-buffer-limit", 500) self.monitoring_buffer = MonitoringBuffer(monitoring_buffer_limit, self.log) self.browser_open = self.settings.get("browser-open", self.browser_open) self.public_report = self.settings.get("public-report", self.public_report) self.upload_artifacts = self.parameters.get("upload-artifacts", self.upload_artifacts) self._dpoint_serializer.multi = self.settings.get("report-times-multiplier", self._dpoint_serializer.multi) token = self.settings.get("token", "") if not token: self.log.warning("No BlazeMeter API key provided, will upload anonymously") self._user.token = token # usual fields self._user.logger_limit = self.settings.get("request-logging-limit", self._user.logger_limit) self._user.address = self.settings.get("address", self._user.address).rstrip("/") self._user.data_address = self.settings.get("data-address", self._user.data_address).rstrip("/") self._user.timeout = dehumanize_time(self.settings.get("timeout", self._user.timeout)) if isinstance(self._user.http_session, requests.Session): self.log.debug("Installing http client") self._user.http_session = self.engine.get_http_client() self._user.http_request = self._user.http_session.request # direct data feeding case sess_id = self.parameters.get("session-id") if sess_id: self._session = Session(self._user, {'id': sess_id}) self._session['userId'] = self.parameters.get("user-id", None) self._session['testId'] = self.parameters.get("test-id", None) self._test = Test(self._user, {'id': self._session['testId']}) exc = TaurusConfigError("Need signature for session") self._session.data_signature = self.parameters.get("signature", exc) self._session.kpi_target = self.parameters.get("kpi-target", self._session.kpi_target) self.send_data = self.parameters.get("send-data", self.send_data) else: try: self._user.ping() # to check connectivity and auth except HTTPError: self.log.error("Cannot reach online results storage, maybe the address/token is wrong") raise if token: wsp = self._user.accounts().workspaces() if not wsp: raise TaurusNetworkError("Your account has no active workspaces, please contact BlazeMeter support") finder = ProjectFinder(self.parameters, self.settings, self._user, wsp, self.log) self._test = finder.resolve_external_test() else: self._test = Test(self._user, {'id': None}) self.report_name = self.parameters.get("report-name", self.settings.get("report-name", self.report_name)) if self.report_name == 'ask' and sys.stdin.isatty(): self.report_name = input("Please enter report-name: ") if isinstance(self.engine.aggregator, ResultsProvider): self.engine.aggregator.add_listener(self) for service in self.engine.services: if isinstance(service, Monitoring): service.add_listener(self) def startup(self): """ Initiate online test """ super(BlazeMeterUploader, self).startup() self._user.log = self.log.getChild(self.__class__.__name__) if not self._session: url = self._start_online() self.log.info("Started data feeding: %s", url) if self.browser_open in ('start', 'both'): open_browser(url) if self._user.token and self.public_report: report_link = self._master.make_report_public() self.log.info("Public report link: %s", report_link) def _start_online(self): """ Start online test """ self.log.info("Initiating data feeding...") if self._test['id']: self._session, self._master = self._test.start_external() else: self._session, self._master, self.results_url = self._test.start_anonymous_external_test() self._test['id'] = self._session['testId'] if self._test.token: self.results_url = self._master.address + '/app/#/masters/%s' % self._master['id'] if self.report_name: self._session.set({"name": str(self.report_name)}) return self.results_url def __get_jtls_and_more(self): """ Compress all files in artifacts dir to single zipfile :rtype: (io.BytesIO,dict) """ mfile = BytesIO() listing = {} logs = set() for handler in self.engine.log.parent.handlers: if isinstance(handler, logging.FileHandler): logs.add(handler.baseFilename) max_file_size = self.settings.get('artifact-upload-size-limit', 10) * 1024 * 1024 # 10MB with zipfile.ZipFile(mfile, mode='w', compression=zipfile.ZIP_DEFLATED, allowZip64=True) as zfh: for root, _, files in os.walk(self.engine.artifacts_dir): for filename in files: full_path = os.path.join(root, filename) if full_path in logs: logs.remove(full_path) fsize = os.path.getsize(full_path) if fsize <= max_file_size: zfh.write(full_path, os.path.join(os.path.relpath(root, self.engine.artifacts_dir), filename)) listing[full_path] = fsize else: msg = "File %s exceeds maximum size quota of %s and won't be included into upload" self.log.warning(msg, filename, max_file_size) for filename in logs: # upload logs unconditionally zfh.write(filename, os.path.basename(filename)) listing[filename] = os.path.getsize(filename) return mfile, listing def __upload_artifacts(self): """ If token provided, upload artifacts folder contents and bzt.log """ if not self._session.token: return worker_index = self.engine.config.get('modules').get('shellexec').get('env').get('TAURUS_INDEX_ALL') if worker_index: suffix = '-%s' % worker_index else: suffix = '' artifacts_zip = "artifacts%s.zip" % suffix mfile, zip_listing = self.__get_jtls_and_more() self.log.info("Uploading all artifacts as %s ...", artifacts_zip) self._session.upload_file(artifacts_zip, mfile.getvalue()) self._session.upload_file(artifacts_zip + '.tail.bz', self.__format_listing(zip_listing)) handlers = self.engine.log.parent.handlers for handler in handlers: if isinstance(handler, logging.FileHandler): fname = handler.baseFilename self.log.info("Uploading %s", fname) fhead, ftail = os.path.splitext(os.path.split(fname)[-1]) modified_name = fhead + suffix + ftail with open(fname, 'rb') as _file: self._session.upload_file(modified_name, _file.read()) _file.seek(-4096, 2) tail = _file.read() tail = tail[tail.index(b("\n")) + 1:] self._session.upload_file(modified_name + ".tail.bz", tail) def post_process(self): """ Upload results if possible """ if not self._session: self.log.debug("No feeding session obtained, nothing to finalize") return self.log.debug("KPI bulk buffer len in post-proc: %s", len(self.kpi_buffer)) try: self.log.info("Sending remaining KPI data to server...") if self.send_data: self.__send_data(self.kpi_buffer, False, True) self.kpi_buffer = [] if self.send_monitoring: self.__send_monitoring() finally: self._postproc_phase2() if self.results_url: if self.browser_open in ('end', 'both'): open_browser(self.results_url) self.log.info("Online report link: %s", self.results_url) def _postproc_phase2(self): try: if self.upload_artifacts: self.__upload_artifacts() except (IOError, TaurusNetworkError): self.log.warning("Failed artifact upload: %s", traceback.format_exc()) finally: self._last_status_check = self.parameters.get('forced-last-check', self._last_status_check) self.log.debug("Set last check time to: %s", self._last_status_check) tries = self.send_interval # NOTE: you dirty one... while not self._last_status_check and tries > 0: self.log.info("Waiting for ping...") time.sleep(self.send_interval) tries -= 1 self._postproc_phase3() def _postproc_phase3(self): try: if self.send_data: self.end_online() if self._user.token and self.engine.stopping_reason: exc_class = self.engine.stopping_reason.__class__.__name__ note = "%s: %s" % (exc_class, str(self.engine.stopping_reason)) self.append_note_to_session(note) if self._master: self.append_note_to_master(note) except KeyboardInterrupt: raise except BaseException as exc: self.log.debug("Failed to finish online: %s", traceback.format_exc()) self.log.warning("Failed to finish online: %s", exc) def end_online(self): """ Finish online test """ if not self._session: self.log.debug("Feeding not started, so not stopping") else: self.log.info("Ending data feeding...") if self._user.token: self._session.stop() else: self._session.stop_anonymous() def append_note_to_session(self, note): self._session.fetch() if 'note' in self._session: note = self._session['note'] + '\n' + note note = note.strip() if note: self._session.set({'note': note[:NOTE_SIZE_LIMIT]}) def append_note_to_master(self, note): self._master.fetch() if 'note' in self._master: note = self._master['note'] + '\n' + note note = note.strip() if note: self._master.set({'note': note[:NOTE_SIZE_LIMIT]}) def check(self): """ Send data if any in buffer """ self.log.debug("KPI bulk buffer len: %s", len(self.kpi_buffer)) if self.last_dispatch < (time.time() - self.send_interval): self.last_dispatch = time.time() if self.send_data and len(self.kpi_buffer): self.__send_data(self.kpi_buffer) self.kpi_buffer = [] if self.send_monitoring: self.__send_monitoring() return super(BlazeMeterUploader, self).check() def __send_data(self, data, do_check=True, is_final=False): """ :type data: list[bzt.modules.aggregator.DataPoint] """ if not self._session: return self.engine.aggregator.converter(data) serialized = self._dpoint_serializer.get_kpi_body(data, is_final) self._session.send_kpi_data(serialized, do_check) def aggregated_second(self, data): """ Send online data :param data: DataPoint """ if self.send_data: self.kpi_buffer.append(data) def monitoring_data(self, data): if self.send_monitoring: self.monitoring_buffer.record_data(data) def __send_monitoring(self): engine_id = self.engine.config.get('modules').get('shellexec').get('env').get('TAURUS_INDEX_ALL', '') if not engine_id: engine_id = "0" data = self.monitoring_buffer.get_monitoring_json(self._session) self._session.send_monitoring_data(engine_id, data) def __format_listing(self, zip_listing): lines = [] for fname in sorted(zip_listing.keys()): bytestr = humanize_bytes(zip_listing[fname]) if fname.startswith(self.engine.artifacts_dir): fname = fname[len(self.engine.artifacts_dir) + 1:] lines.append(bytestr + " " + fname) return "\n".join(lines) class MonitoringBuffer(object): def __init__(self, size_limit, parent_log): self.size_limit = size_limit self.data = defaultdict(OrderedDict) self.log = parent_log.getChild(self.__class__.__name__) # data :: dict(datasource -> dict(interval -> datapoint)) # datapoint :: dict(metric -> value) def record_data(self, data): for monitoring_item in data: item = copy.deepcopy(monitoring_item) source = item.pop('source') timestamp = int(item['ts']) item['interval'] = 1 buff = self.data[source] if timestamp in buff: buff[timestamp].update(item) else: buff[timestamp] = item sources = list(self.data) for source in sources: if len(self.data[source]) > self.size_limit: self._downsample(self.data[source]) self.log.debug("Monitoring buffer size '%s': %s", source, len(self.data[source])) def _downsample(self, buff): size = 1 while len(buff) > self.size_limit: self._merge_small_intervals(buff, size) size += 1 def _merge_small_intervals(self, buff, size): timestamps = list(buff) merged_already = set() for left, right in zip(timestamps, timestamps[1:]): if left in merged_already: continue if buff[left]['interval'] <= size: self._merge_datapoints(buff[left], buff[right]) buff.pop(right) merged_already.add(left) merged_already.add(right) @staticmethod def _merge_datapoints(left, right): sum_size = float(left['interval'] + right['interval']) for metric in set(right): if metric in ('ts', 'interval'): continue if metric in left: left[metric] = (left[metric] * left['interval'] + right[metric] * right['interval']) / sum_size else: left[metric] = right[metric] left['interval'] = sum_size def get_monitoring_json(self, session): """ :type session: Session """ results = {} hosts = [] kpis = {} for source, buff in iteritems(self.data): for timestamp, item in iteritems(buff): if source == 'local': source = platform.node() if source not in results: results[source] = { "name": source, "intervals": OrderedDict() } if source not in hosts: hosts.append(source) src = results[source] tstmp = timestamp * 1000 tstmp_key = '%d' % tstmp if tstmp_key not in src['intervals']: src['intervals'][tstmp_key] = { "start": tstmp, "duration": item['interval'] * 1000, "indicators": {} } for field, value in iteritems(item): if field.lower().startswith('conn-all'): field = 'Connections' elif field.lower().startswith('cpu'): field = 'CPU' elif field.lower().startswith('mem'): field = 'Memory' value *= 100 elif field == 'bytes-recv' or field.lower().startswith('net'): field = 'Network I/O' elif field == 'engine-loop': field = 'Busy Taurus' else: continue # maybe one day BZA will accept all other metrics... if field not in kpis: kpis[field] = field src['intervals'][tstmp_key]['indicators'][field] = { "value": value, "name": field, "std": 0, "mean": 0, "sum": 0, "min": 0, "max": 0, "sumOfSquares": 0, "n": 1 } kpis = {"Network I/O": "Network I/O", "Memory": "Memory", "CPU": "CPU", "Connections": "Connections"} return { "reportInfo": { "sessionId": session['id'], "timestamp": time.time(), "userId": session['userId'], "testId": session['testId'], "type": "MONITOR", "testName": "" }, "kpis": kpis, "hosts": hosts, "results": results } class DatapointSerializer(object): def __init__(self, owner): """ :type owner: BlazeMeterUploader """ super(DatapointSerializer, self).__init__() self.owner = owner self.multi = 1000 # miltiplier factor for reporting def get_kpi_body(self, data_buffer, is_final): # - reporting format: # {labels: <data>, # see below # sourceID: <id of BlazeMeterClient object>, # [is_final: True]} # for last report # # - elements of 'data' are described in __get_label() # # - elements of 'intervals' are described in __get_interval() # every interval contains info about response codes that were received on it. report_items = BetterDict() if data_buffer: self.owner.first_ts = min(self.owner.first_ts, data_buffer[0][DataPoint.TIMESTAMP]) self.owner.last_ts = max(self.owner.last_ts, data_buffer[-1][DataPoint.TIMESTAMP]) # following data is received in the cumulative way for label, kpi_set in iteritems(data_buffer[-1][DataPoint.CUMULATIVE]): report_item = self.__get_label(label, kpi_set) self.__add_errors(report_item, kpi_set) # 'Errors' tab report_items[label] = report_item # fill 'Timeline Report' tab with intervals data # intervals are received in the additive way if report_items: for dpoint in data_buffer: time_stamp = dpoint[DataPoint.TIMESTAMP] for label, kpi_set in iteritems(dpoint[DataPoint.CURRENT]): exc = TaurusInternalException('Cumulative KPISet is non-consistent') report_item = report_items.get(label, exc) report_item['intervals'].append(self.__get_interval(kpi_set, time_stamp)) report_items = [report_items[key] for key in sorted(report_items.keys())] # convert dict to list data = {"labels": report_items, "sourceID": id(self.owner)} if is_final: data['final'] = True return to_json(data) @staticmethod def __add_errors(report_item, kpi_set): errors = kpi_set[KPISet.ERRORS] for error in errors: if error["type"] == KPISet.ERRTYPE_ERROR: report_item['errors'].append({ 'm': error['msg'], "rc": error['rc'], "count": error['cnt'], }) elif error["type"] == KPISet.ERRTYPE_SUBSAMPLE: report_item['failedEmbeddedResources'].append({ "count": error['cnt'], "rm": error['msg'], "rc": error['rc'], "url": list(error['urls'])[0] if error['urls'] else None, }) else: report_item['assertions'].append({ 'failureMessage': error['msg'], 'name': error['tag'] if error['tag'] else 'All Assertions', 'failures': error['cnt'] }) def __get_label(self, name, cumul): return { "n": cumul[KPISet.SAMPLE_COUNT], # total count of samples "name": name if name else 'ALL', # label "interval": 1, # not used "intervals": [], # list of intervals, fill later "samplesNotCounted": 0, # not used "assertionsNotCounted": 0, # not used "failedEmbeddedResources": [], # not used "failedEmbeddedResourcesSpilloverCount": 0, # not used "otherErrorsCount": 0, # not used "errors": [], # list of errors, fill later "assertions": [], # list of assertions, fill later "percentileHistogram": [], # not used "percentileHistogramLatency": [], # not used "percentileHistogramBytes": [], # not used "empty": False, # not used "summary": self.__get_summary(cumul) # summary info } def __get_summary(self, cumul): return { "first": self.owner.first_ts, "last": self.owner.last_ts, "duration": self.owner.last_ts - self.owner.first_ts, "failed": cumul[KPISet.FAILURES], "hits": cumul[KPISet.SAMPLE_COUNT], "avg": int(self.multi * cumul[KPISet.AVG_RESP_TIME]), "min": int(self.multi * cumul[KPISet.PERCENTILES]["0.0"]) if "0.0" in cumul[KPISet.PERCENTILES] else 0, "max": int(self.multi * cumul[KPISet.PERCENTILES]["100.0"]) if "100.0" in cumul[KPISet.PERCENTILES] else 0, "std": int(self.multi * cumul[KPISet.STDEV_RESP_TIME]), "tp90": int(self.multi * cumul[KPISet.PERCENTILES]["90.0"]) if "90.0" in cumul[KPISet.PERCENTILES] else 0, "tp95": int(self.multi * cumul[KPISet.PERCENTILES]["95.0"]) if "95.0" in cumul[KPISet.PERCENTILES] else 0, "tp99": int(self.multi * cumul[KPISet.PERCENTILES]["99.0"]) if "99.0" in cumul[KPISet.PERCENTILES] else 0, "latencyAvg": int(self.multi * cumul[KPISet.AVG_LATENCY]), "latencyMax": 0, "latencyMin": 0, "latencySTD": 0, "bytes": cumul[KPISet.BYTE_COUNT], "bytesMax": 0, "bytesMin": 0, "bytesAvg": int(cumul[KPISet.BYTE_COUNT] / float(cumul[KPISet.SAMPLE_COUNT])), "bytesSTD": 0, "otherErrorsSpillcount": 0, } def __get_interval(self, item, time_stamp): # rc_list - list of info about response codes: # {'n': <number of code encounters>, # 'f': <number of failed request (e.q. important for assertions)> # 'rc': <string value of response code>} rc_list = [] for r_code, cnt in iteritems(item[KPISet.RESP_CODES]): fails = [err['cnt'] for err in item[KPISet.ERRORS] if str(err['rc']) == r_code] rc_list.append({"n": cnt, 'f': fails, "rc": r_code}) return { "ec": item[KPISet.FAILURES], "ts": time_stamp, "na": item[KPISet.CONCURRENCY], "n": item[KPISet.SAMPLE_COUNT], "failed": item[KPISet.FAILURES], "rc": rc_list, "t": { "min": int(self.multi * item[KPISet.PERCENTILES]["0.0"]) if "0.0" in item[KPISet.PERCENTILES] else 0, "max": int(self.multi * item[KPISet.PERCENTILES]["100.0"]) if "100.0" in item[ KPISet.PERCENTILES] else 0, "sum": self.multi * item[KPISet.AVG_RESP_TIME] * item[KPISet.SAMPLE_COUNT], "n": item[KPISet.SAMPLE_COUNT], "std": self.multi * item[KPISet.STDEV_RESP_TIME], "avg": self.multi * item[KPISet.AVG_RESP_TIME] }, "lt": { "min": 0, "max": 0, "sum": self.multi * item[KPISet.AVG_LATENCY] * item[KPISet.SAMPLE_COUNT], "n": item[KPISet.SAMPLE_COUNT], "std": 0, "avg": self.multi * item[KPISet.AVG_LATENCY] }, "by": { "min": 0, "max": 0, "sum": item[KPISet.BYTE_COUNT], "n": item[KPISet.SAMPLE_COUNT], "std": 0, "avg": item[KPISet.BYTE_COUNT] / float(item[KPISet.SAMPLE_COUNT]) }, }
40.547965
120
0.566979
3,094
27,897
4.936005
0.175501
0.022328
0.012768
0.008905
0.183408
0.117012
0.070259
0.03955
0.027632
0.020953
0
0.007744
0.319568
27,897
687
121
40.606987
0.796808
0.085601
0
0.138196
0
0
0.099897
0.009827
0
0
0
0
0.007678
1
0.057582
false
0
0.038388
0.003839
0.12476
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
71975dd9b4598f0884460876d889b91d528834d3
20,434
py
Python
nitorch/nn/losses/_spatial.py
wyli/nitorch
3ecd18944cf45fb9193c4c6ffc32953c4d1c71ac
[ "MIT" ]
1
2021-04-09T21:24:47.000Z
2021-04-09T21:24:47.000Z
nitorch/nn/losses/_spatial.py
wyli/nitorch
3ecd18944cf45fb9193c4c6ffc32953c4d1c71ac
[ "MIT" ]
null
null
null
nitorch/nn/losses/_spatial.py
wyli/nitorch
3ecd18944cf45fb9193c4c6ffc32953c4d1c71ac
[ "MIT" ]
null
null
null
""" Losses that assume an underlying spatial organization (gradients, curvature, etc.) """ import torch import torch.nn as tnn from nitorch.core.pyutils import make_list, prod from nitorch.core.utils import slice_tensor from nitorch.spatial import diff1d from ._base import Loss class LocalFeatures(tnn.Module): """Base class for feature extractors. Is it really useful? """ def __init__(self, bound='dct2', voxel_size=1, *args, **kwargs): """ Parameters ---------- bound : BoundType, default='dct2' Boundary conditions, used to compute derivatives at the edges. voxel_size : float or list[float], default=1 Voxel size """ super().__init__(*args, **kwargs) self.bound = bound self.voxel_size = voxel_size class Diff(LocalFeatures): """Finite differences.""" def __init__(self, order=1, side='c', dim=None, *args, **kwargs): """ Parameters ---------- order : int, default=1 Finite differences order side : {'c', 'f', 'b'} or list[{'c', 'f', 'b'}], default='c' Type of finite-differencesto extract about each voxel: * 'c' : central -> `g[i] = (x[i+1] - x[i-1])/2` * 'f' : forward -> `g[i] = (x[i+1] - x[i])` * 'b' : backward -> `g[i] = (x[i] - x[i-1])` dim : int or list[int], optional Dimensions along which to compute the finite differences. By default, all except the first two (batch and channel). bound : BoundType or list[BoundType], default='dct2' Boundary conditions, used to compute derivatives at the edges. voxel_size : float or list[float], default=1 Voxel size reduction : {'mean', 'sum'} or callable, default='mean' Type of reduction to apply. """ super().__init__(*args, **kwargs) self.order = order self.side = side self.dim = dim def forward(self, x, **overload): """ Parameters ---------- x : tensor Input tensor with shape (batch, channel, *spatial) overload : dict All parameters defined at build time can be overridden at call time. Returns ------- g : tensor Finite differences with shape (batch, channel, *spatial, len(dim), len(side)) If `dim` or `side` are scalars, not lists, their respective dimension is dropped in the output tensor. E.g., if `side='c'`, the output shape is (batch, channel, *spatial, len(dim)) """ order = overload.get('order', self.order) side = make_list(overload.get('side', self.side)) drop_side_dim = not isinstance(side, (tuple, list)) side = make_list(side) dim = overload.get('dim', self.dim) dim = list(range(2, x.dim())) if dim is None else dim drop_dim_dim = not isinstance(dim, (tuple, list)) dim = make_list(dim) nb_dim = len(dim) voxel_size = overload.get('voxel_size', self.voxel_size) voxel_size = make_list(voxel_size, nb_dim) bound = make_list(overload.get('bound', self.bound), nb_dim) diffs = [] for d, vx, bnd in zip(dim, voxel_size, bound): sides = [] for s in side: grad = diff1d(x, order=order, dim=d, voxel_size=vx, side=s, bound=bnd) sides.append(grad) sides = torch.stack(sides, dim=-1) diffs.append(sides) diffs = torch.stack(diffs, dim=-2) if drop_dim_dim: diffs = slice_tensor(diffs, 0, dim=-2) if drop_side_dim: diffs = slice_tensor(diffs, 0, dim=-1) return diffs class MembraneLoss(Loss): """Compute the membrane energy (squared gradients) of a tensor. The membrane energy of a field is the integral of its squared gradient magnitude (l2 norm). This class extends this concept to other norms of the gradient (l1, l{1,2}). In the l2 case, if we name "f" the unit of the field and "m" the spatial unit of a voxel, the output loss has unit `(f/m)**2`. If `factor` is used to weight each voxel by its volume (as should be done in a proper integration) the unit becomes `(f/m)**2 * m**d = f**2 * m**(d-2)`. In the l1 case, it is `f/m` in the absence of weighting and `f * m**(d-1)` with volume weighting. """ def __init__(self, voxel_size=1, factor=1, bound='dct2', l1=None, *args, **kwargs): """ Parameters ---------- voxel_size : float or list[float], default=1 Voxel size. Useful for anisotropic tensors (where the sampling rate is higher in some directions than others). factor : float or list[float], default=1 Scale the loss by a per-dimension factor. Useful when working with resized tensor to compensate for different number of voxels. bound : BoundType, default='dct2' Boundary conditions, used to compute derivatives at the edges. l1 : bool or int or list[int], default=None Dimensions along which to apply a square root reduction ('l1 norm'), after taking the square. Dimensions are those of the gradient map with shape (batch, channel, *spatial, direction, side) * False: nowhere == (squared) l2 norm * True: everywhere == l1 norm * Otherwise: l_{1,2} norm (group sparsity) """ super().__init__(*args, **kwargs) self.voxel_size = voxel_size self.factor = factor self.bound = bound self.l1 = l1 def forward(self, x, **overload): """ Parameters ---------- x : tensor Input tensor overload : dict All parameters defined at build time can be overridden at call time. Returns ------- loss : scalar or tensor The output shape depends on the type of reduction used. If 'mean' or 'sum', this function returns a scalar. """ nb_dim = x.dim() - 2 voxel_size = make_list(overload.get('voxel_size', self.voxel_size), nb_dim) factor = make_list(overload.get('factor', self.factor), nb_dim) bound = make_list(overload.get('bound', self.bound), nb_dim) l1 = overload.get('l1', self.l1) # Compute spatial gradients # # TODO: when penalty == 'l2', for some boundary conditions, there's no # need to compute both forward and backward gradients as they are # the same (but shifted). For now, to avoid having to detect which # cases can be accelerated, I always compute both (more general). loss = Diff(side=['f', 'b'], bound=bound, voxel_size=voxel_size)(x) loss = loss.square() # Apply l1 if l1 not in (None, False): if l1 is True: loss = loss.sqrt() else: l1 = make_list(l1) loss = loss.sum(dim=l1).sqrt() # TODO: use self.reduction instead of sum? # Reduce loss = super().forward(loss) # Scale factor = prod(factor) if factor != 1: loss = loss * factor return loss class BendingLoss(Loss): """Compute the bending energy (squared gradients) of a tensor. The bending energy of a field is the integral of its squared second-order derivatives magnitude (l2 norm). This class extends this concept to other norms of the gradient (l1, l{1,2}). In the l2 case, if we name "f" the unit of the field and "m" the spatial unit of a voxel, the output loss has unit `(f/m**2)**2`. If `factor` is used to weight each voxel by its volume (as should be done in a proper integration) the unit becomes `(f/m**2)**2 * m**d = f**2 * m**(d-4)`. In the l1 case, it is `f/m**2` in the absence of weighting and `f * m**(d-2)` with volume weighting. """ def __init__(self, voxel_size=1, factor=1, bound='dct2', l1=None, *args, **kwargs): """ Parameters ---------- voxel_size : float or list[float], default=1 Voxel size. Useful for anisotropic tensors (where the sampling rate is higher in some directions than others). factor : float or list[float], default=1 Scale the loss by a per-dimension factor. Useful when working with resized tensor to compensate for different number of voxels. bound : BoundType, default='dct2' Boundary conditions, used to compute derivatives at the edges. l1 : bool or int or list[int], default=None Dimensions along which to apply a square root reduction ('l1 norm'), after taking the square. Dimensions are those of the gradient map with shape (batch, channel, *spatial, direction) * False: nowhere == (squared) l2 norm * True: everywhere == l1 norm * Otherwise: l_{1,2} norm (group sparsity) """ super().__init__(*args, **kwargs) self.voxel_size = voxel_size self.factor = factor self.bound = bound self.l1 = l1 def forward(self, x, **overload): """ Parameters ---------- x : tensor Input tensor overload : dict All parameters defined at build time can be overridden at call time. Returns ------- loss : scalar or tensor The output shape depends on the type of reduction used. If 'mean' or 'sum', this function returns a scalar. """ nb_dim = x.dim() - 2 voxel_size = make_list(overload.get('voxel_size', self.voxel_size), nb_dim) factor = make_list(overload.get('factor', self.factor), nb_dim) bound = make_list(overload.get('bound', self.bound), nb_dim) l1 = overload.get('l1', self.l1) # Compute spatial gradients loss = Diff(order=2, side='c', bound=bound, voxel_size=voxel_size)(x) loss = loss.square() # Apply l1 if l1 not in (None, False): if l1 is True: loss = loss.sqrt() else: l1 = make_list(l1) loss = loss.sum(dim=l1).sqrt() # Reduce loss = super().forward(loss) # Scale factor = prod(factor) if factor != 1: loss = loss * factor return loss class LameShearLoss(Loss): """Strain-part of the (Linear)-Elastic energy (penalty on shears). = second Lame constant = shear modulus The shear energy of a deformation field is the integral of the square magnitude (l2 norm) of the symetric part diagonal terms of its Jacobian. This class extends this concept to other norms of the gradient (l1, l{1,2}). In the l2 case, E = sum_{i != j} (dv[i]/dx[j]) ** 2. """ def __init__(self, voxel_size=1, factor=1, bound='dct2', l1=None, exclude_zooms=False, *args, **kwargs): """ Parameters ---------- voxel_size : float or list[float], default=1 Voxel size. Useful for anisotropic tensors (where the sampling rate is higher in some directions than others). factor : float or list[float], default=1 Scale the loss by a per-dimension factor. Useful when working with resized tensor to compensate for different number of voxels. bound : BoundType, default='dct2' Boundary conditions, used to compute derivatives at the edges. l1 : bool or int or list[int], default=None Dimensions along which to apply a square root reduction ('l1 norm'), after taking the square. Dimensions are those of the gradient map with shape (batch, channel, *spatial, side) * False: nowhere == (squared) l2 norm * True: everywhere == l1 norm * Otherwise: l_{1,2} norm (group sparsity) Here, `channel` map to elements of the Jacobian matrix, while `side` map to the combination of sides (forward/backward) used when extracting finite differences. Therefore, the number of channels is dim*(dim+1)//2 and the number of sides is 4. exclude_zooms : bool, default=False Do not include diagonal elements of the Jacobian in the penalty (i.e., penalize only shears) """ super().__init__(*args, **kwargs) self.voxel_size = voxel_size self.factor = factor self.bound = bound self.l1 = l1 self.exclude_zooms = exclude_zooms def forward(self, x, **overload): """ Parameters ---------- x : (batch, ndim, *spatial) tensor Input displacement tensor (in channel first order) overload : dict All parameters defined at build time can be overridden at call time. Returns ------- loss : scalar or tensor The output shape depends on the type of reduction used. If 'mean' or 'sum', this function returns a scalar. """ nb_dim = x.dim() - 2 voxel_size = make_list(overload.get('voxel_size', self.voxel_size), nb_dim) factor = make_list(overload.get('factor', self.factor), nb_dim) bound = make_list(overload.get('bound', self.bound), nb_dim) l1 = overload.get('l1', self.l1) exclude_zooms = overload.get('exclude_zooms', self.exclude_zooms) # Compute spatial gradients loss_diag = [] # diagonal elements of the Jacobian loss_offdiag = [] # off-diagonal elements of hte (symmetric) Jacobian for i in range(nb_dim): # symmetric part x_i = x[:, i:i+1, ...] subloss_diag = [] subloss_offdiag = [] for j in range(nb_dim): for side_i in ('f', 'b'): diff = Diff(dim=[j+2], side=side_i, bound=bound, voxel_size=voxel_size) diff_ij = diff(x_i) if i == j: # diagonal elements if not exclude_zooms: subloss_diag.append(diff_ij) else: # off diagonal elements x_j = x[:, j:j+1, ...] for side_j in ('f', 'b'): diff = Diff(dim=[i+2], side=side_j, bound=bound, voxel_size=voxel_size) diff_ji = diff(x_j) subloss_offdiag.append((diff_ij + diff_ji)/2) if not exclude_zooms: loss_diag.append(torch.stack(subloss_diag, dim=-1)) loss_offdiag.append(torch.stack(subloss_offdiag, dim=-1)) if not exclude_zooms: loss_diag = torch.cat(loss_diag, dim=1) loss_offdiag = torch.cat(loss_offdiag, dim=1) if l1 not in (None, False): # Apply l1 reduction if l1 is True: if not exclude_zooms: loss_diag = loss_diag.abs() loss_offdiag = loss_offdiag.abs() else: l1 = make_list(l1) if not exclude_zooms: loss_diag = loss_diag.square().sum(dim=l1, keepdim=True).sqrt() loss_offdiag = loss_offdiag.square().sum(dim=l1, keepdim=True).sqrt() else: # Apply l2 reduction if not exclude_zooms: loss_diag = loss_diag.square() loss_offdiag = loss_offdiag.square() # Mean reduction across sides if not exclude_zooms: loss_diag = loss_diag.mean(dim=-1) loss_offdiag = loss_offdiag.mean(dim=-1) # Weighted reduction across elements if not exclude_zooms: if loss_diag.shape[1] == 1: # element dimension already reduced -> we need a small hack loss = (loss_diag.square() + 2*loss_offdiag.square()) / (nb_dim**2) loss = loss.sum(dim=1, keepdim=True).sqrt() else: # simple weighted average loss = (loss_diag.sum(dim=1, keepdim=True) + loss_offdiag.sum(dim=1, keepdim=True)*2) / (nb_dim**2) else: loss = loss_offdiag.sum(dim=1, keepdim=True)*2 / (nb_dim**2) # Reduce loss = super().forward(loss) # Scale factor = prod(factor) if factor != 1: loss = loss * factor return loss class LameZoomLoss(Loss): """Compression-part of the (Linear)-Elastic energy (penalty on volume change). = first Lame constant The compression energy of a deformation field is the integral of the square magnitude (l2 norm) of the trace its Jacobian. This class extends this concept to other norms of the gradient (l1, l{1,2}). In the l2 case, E = sum_{ij} (dv[i]/dx[j] + dv[j]/dx[i]) ** 2. """ def __init__(self, voxel_size=1, factor=1, bound='dct2', l1=None, *args, **kwargs): """ Parameters ---------- voxel_size : float or list[float], default=1 Voxel size. Useful for anisotropic tensors (where the sampling rate is higher in some directions than others). factor : float or list[float], default=1 Scale the loss by a per-dimension factor. Useful when working with resized tensor to compensate for different number of voxels. bound : BoundType, default='dct2' Boundary conditions, used to compute derivatives at the edges. l1 : bool or int or list[int], default=None Dimensions along which to apply a square root reduction ('l1 norm'), after taking the square. Dimensions are those of the gradient map with shape (batch, channel, *spatial, direction, side) * False: nowhere == (squared) l2 norm * True: everywhere == l1 norm * Otherwise: l_{1,2} norm (group sparsity) """ super().__init__(*args, **kwargs) self.voxel_size = voxel_size self.factor = factor self.bound = bound self.l1 = l1 def forward(self, x, **overload): """ Parameters ---------- x : tensor Input tensor overload : dict All parameters defined at build time can be overridden at call time. Returns ------- loss : scalar or tensor The output shape depends on the type of reduction used. If 'mean' or 'sum', this function returns a scalar. """ nb_dim = x.dim() - 2 voxel_size = make_list(overload.get('voxel_size', self.voxel_size), nb_dim) factor = make_list(overload.get('factor', self.factor), nb_dim) bound = make_list(overload.get('bound', self.bound), nb_dim) l1 = overload.get('l1', self.l1) # Compute spatial gradients loss = [] for i in range(nb_dim): x_i = x[:, i:i+1, ...] diff = Diff(dim=[i], side=['f', 'b'], bound=bound, voxel_size=voxel_size) loss.append(diff(x_i)) loss = torch.cat(loss, dim=1) loss = loss.square() # Apply l1 if l1 not in (None, False): if l1 is True: loss = loss.sqrt() else: l1 = make_list(l1) loss = loss.sum(dim=l1, keepdim=True).sqrt() # Mean reduction across sides loss = loss.mean(dim=-1) # Reduce loss = super().forward(loss) # Scale factor = prod(factor) if factor != 1: loss = loss * factor return loss
35.414211
90
0.553049
2,571
20,434
4.306496
0.119409
0.04552
0.016438
0.024025
0.711163
0.673952
0.659772
0.629606
0.613891
0.597995
0
0.014615
0.343692
20,434
576
91
35.475694
0.810976
0.465401
0
0.57971
0
0
0.017748
0
0
0
0
0.001736
0
1
0.05314
false
0
0.028986
0
0.135266
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
719876b6e33d3caa67b41082a88c72293d4411b5
2,801
py
Python
launch/twist_mux_launch.py
nuclearsandwich-ros/twist_mux-release
d92dcda0255e727b899d3bac62ef3d89c19cb38e
[ "Apache-2.0" ]
31
2017-11-25T17:13:00.000Z
2022-01-20T14:39:12.000Z
launch/twist_mux_launch.py
nuclearsandwich-ros/twist_mux-release
d92dcda0255e727b899d3bac62ef3d89c19cb38e
[ "Apache-2.0" ]
27
2015-05-22T13:35:04.000Z
2021-12-29T07:26:02.000Z
launch/twist_mux_launch.py
nuclearsandwich-ros/twist_mux-release
d92dcda0255e727b899d3bac62ef3d89c19cb38e
[ "Apache-2.0" ]
51
2015-10-16T11:41:24.000Z
2022-03-28T07:33:24.000Z
#!/usr/bin/env python3 # Copyright 2020 Gaitech Korea Co., Ltd. # # 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. # Author: Brighten Lee import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import DeclareLaunchArgument from launch.substitutions import LaunchConfiguration from launch_ros.actions import Node def generate_launch_description(): default_config_locks = os.path.join(get_package_share_directory('twist_mux'), 'config', 'twist_mux_locks.yaml') default_config_topics = os.path.join(get_package_share_directory('twist_mux'), 'config', 'twist_mux_topics.yaml') default_config_joystick = os.path.join(get_package_share_directory('twist_mux'), 'config', 'joystick.yaml') return LaunchDescription([ DeclareLaunchArgument( 'config_locks', default_value=default_config_locks, description='Default locks config file'), DeclareLaunchArgument( 'config_topics', default_value=default_config_topics, description='Default topics config file'), DeclareLaunchArgument( 'config_joy', default_value=default_config_joystick, description='Default joystick config file'), DeclareLaunchArgument( 'cmd_vel_out', default_value='twist_mux/cmd_vel', description='cmd vel output topic'), Node( package='twist_mux', executable='twist_mux', output='screen', remappings={('/cmd_vel_out', LaunchConfiguration('cmd_vel_out'))}, parameters=[ LaunchConfiguration('config_locks'), LaunchConfiguration('config_topics'), LaunchConfiguration('config_joy')] ), Node( package='twist_mux', executable='twist_marker', output='screen', remappings={('/twist', LaunchConfiguration('cmd_vel_out'))}, parameters=[{ 'frame_id': 'base_link', 'scale': 1.0, 'vertical_position': 2.0}]) ])
38.902778
84
0.63513
294
2,801
5.836735
0.42517
0.041958
0.034965
0.055944
0.177156
0.132867
0.09324
0.09324
0.09324
0.09324
0
0.006417
0.276687
2,801
71
85
39.450704
0.840573
0.21528
0
0.2
0
0
0.195144
0.00962
0
0
0
0
0
1
0.02
false
0
0.12
0
0.16
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
7199385be37350560f528085cc7c3bcbd212b172
5,298
py
Python
Tests/testLiveService.py
psu-capstone-teamD/ElementalAuth
d896efad5a3e4cb453c324afc456aa82f82da239
[ "MIT" ]
2
2017-08-21T00:52:35.000Z
2018-10-31T17:38:42.000Z
Tests/testLiveService.py
psu-capstone-teamD/ElementalAuth
d896efad5a3e4cb453c324afc456aa82f82da239
[ "MIT" ]
27
2017-07-27T21:10:35.000Z
2017-08-24T21:19:23.000Z
Tests/testLiveService.py
psu-capstone-teamD/ElementalAuth
d896efad5a3e4cb453c324afc456aa82f82da239
[ "MIT" ]
2
2017-07-08T00:57:08.000Z
2017-07-24T19:21:12.000Z
import sys import unittest import requests_mock from mock import patch sys.path.append('services/LiveService') from LiveService import LiveService L = LiveService() baseURL = "https://yanexx65s8e1.live.elementalclouddev.com/api" class LiveServiceTest(unittest.TestCase): '''@patch('services.LiveService.LiveService.time', return_value=1502345833) def testSetHeaders(self, mock_time): headers = L.setHeaders("/schedules") self.assertEqual(headers, {'X-Auth-Expires': '1502345863', 'X-Auth-Key': '9c9a72cd3a8feec48539f1943afbef8d', 'Content-type': 'application/xml', 'X-Auth-User': '', 'Accept': 'application/xml'})''' @requests_mock.Mocker() def testGetStatus(self, m): m.get(baseURL + "/live_events/150/status", status_code=200) resp = L.getLiveEventStatus(150) self.assertEqual(resp.status_code, 200) @requests_mock.Mocker() def testGetEvents(self, m): m.get(baseURL + "/live_events", status_code=200) m.get(baseURL + "/live_events?filter=running", status_code=200) resp = L.getLiveEvents(None) self.assertEqual(resp.status_code, 200) resp = L.getLiveEvents("running") self.assertEqual(resp.status_code, 200) @requests_mock.Mocker() def testGetEvent(self, m): m.get(baseURL + "/live_events/164", status_code=200) resp = L.getLiveEvent(164) self.assertEqual(resp.status_code, 200) @requests_mock.Mocker() def testGetSchedules(self, m): m.get(baseURL + "/schedules", status_code=200) resp = L.getSchedules() self.assertEqual(resp.status_code, 200) @requests_mock.Mocker() def testGetLiveProfiles(self, m): m.get(baseURL + "/live_event_profiles", status_code=200) resp = L.getLiveProfiles() self.assertEqual(resp.status_code, 200) @requests_mock.Mocker() def testGetLiveProfile(self, m): m.get(baseURL + "/live_event_profiles/11", status_code=200) resp = L.getLiveProfile(11) self.assertEqual(resp.status_code, 200) @requests_mock.Mocker() def testCreateLiveEvent(self, m): with open('Tests/test_XML/live_event.xml', 'r') as infile: xml = infile.read() m.post(baseURL + "/live_events", status_code=201) resp = L.createEvent(xml) self.assertEqual(resp.status_code, 201) @requests_mock.Mocker() def testCreateSchedule(self, m): with open('Tests/test_XML/schedule.xml', 'r') as infile: xml = infile.read() m.post(baseURL + "/schedules", status_code=201) resp = L.createSchedule(xml) self.assertEqual(resp.status_code, 201) @requests_mock.Mocker() def testCreateProfile(self, m): with open('Tests/test_XML/schedule.xml', 'r') as infile: xml = infile.read() m.post(baseURL + "/schedules", status_code=201) resp = L.createSchedule(xml) self.assertEqual(resp.status_code, 201) @requests_mock.Mocker() def testUpdateEvent(self, m): with open('Tests/test_XML/live_event.xml', 'r') as infile: xml = infile.read() m.put(baseURL + "/live_events/50", status_code=200) resp = L.updateLiveEvent(50, xml) self.assertEqual(resp.status_code, 200) @requests_mock.Mocker() def testUpdatePlaylist(self, m): with open('Tests/test_XML/live_event.xml', 'r') as infile: xml = infile.read() m.post(baseURL + "/live_events/92/playlist", status_code=200) resp = L.updatePlaylist(92, xml) self.assertEqual(resp.status_code, 200) @requests_mock.Mocker() def testUpdateSchedule(self, m): with open('Tests/test_XML/schedule.xml', 'r') as infile: xml = infile.read() m.put(baseURL + "/schedules/13", status_code=200) resp = L.updateSchedule(13, xml) self.assertEqual(resp.status_code, 200) @requests_mock.Mocker() def testUpdateProfile(self, m): with open('Tests/test_XML/live_profile.xml', 'r') as infile: xml = infile.read() m.put(baseURL + "/live_event_profiles/33", status_code=200) resp = L.updateProfile(33, xml) self.assertEqual(resp.status_code, 200) @requests_mock.Mocker() def testRemoveLiveEvent(self, m): m.delete(baseURL + "/live_events/191", status_code=200) resp = L.removeEvent(191) self.assertEqual(resp.status_code, 200) @requests_mock.Mocker() def testRemoveSchedule(self, m): m.delete(baseURL + "/schedules/13", status_code=200) resp = L.removeSchedule(13) self.assertEqual(resp.status_code, 200) @requests_mock.Mocker() def testRemoveProfile(self, m): m.delete(baseURL + "/live_event_profiles/33", status_code=200) resp = L.removeProfile(33) self.assertEqual(resp.status_code, 200) @requests_mock.Mocker() def testStartEvent(self, m): m.post(baseURL + "/live_events/50/start", status_code=200) resp = L.startLiveEvent(50) self.assertEqual(resp.status_code, 200) if __name__ == '__main__': unittest.main()
35.557047
85
0.634957
631
5,298
5.18542
0.187005
0.110024
0.119193
0.137531
0.660147
0.580379
0.535147
0.511308
0.462408
0.462408
0
0.048841
0.234806
5,298
148
86
35.797297
0.758263
0.089656
0
0.460177
0
0
0.125914
0.075799
0
0
0
0
0.159292
1
0.150442
false
0
0.044248
0
0.20354
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
719a305b1e0f6ee4015df4fc0e1d42b61d553b49
1,611
py
Python
employee/views/check_rental.py
odrolliv13/Hex-Photos
d1b42b63394783164f843fe6343491f04fe11e0c
[ "Apache-2.0" ]
null
null
null
employee/views/check_rental.py
odrolliv13/Hex-Photos
d1b42b63394783164f843fe6343491f04fe11e0c
[ "Apache-2.0" ]
null
null
null
employee/views/check_rental.py
odrolliv13/Hex-Photos
d1b42b63394783164f843fe6343491f04fe11e0c
[ "Apache-2.0" ]
null
null
null
from django import forms from django.conf import settings from django.http import HttpResponse, HttpResponseRedirect, Http404 from manager import models as pmod from . import templater from django.conf import settings import decimal, datetime # This view will display all users and then on a new page display all the current rentals for a given user def process_request(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/shop') if request.user.is_staff == False: return HttpResponseRedirect('/shop') if request.urlparams[0] == "": #This form will display all users form = CheckRentalForm(initial ={ 'user': "", }) if request.method == 'POST': form = CheckRentalForm(request.POST) if form.is_valid(): #From here the page will redirect to show all the current rentals for the user picked complete = "/employee/customer_rentals/" + str(form.cleaned_data['user'].id) return HttpResponseRedirect(complete) tvars = { 'form': form, } return templater.render_to_response(request, 'return_rental.html', tvars) else: try: complete_rental = pmod.Rental.objects.get(id=request.urlparams[0]) form = CheckRentalForm(initial ={ 'user': "", }) except: pass form = "dfd" tvars = { 'form': form, } return templater.render_to_response(request, 'return_rental.html', tvars) class CheckRentalForm(forms.Form): user = forms.ModelChoiceField(queryset=pmod.User.objects.exclude(is_active=False), label="User", widget=forms.Select(attrs={'class':'form-control'}))
30.980769
150
0.703911
201
1,611
5.572139
0.437811
0.035714
0.025
0.035714
0.289286
0.128571
0.128571
0.128571
0.128571
0.128571
0
0.00382
0.187461
1,611
52
150
30.980769
0.851795
0.136561
0
0.4
0
0
0.090501
0.020194
0
0
0
0
0
1
0.025
false
0.025
0.175
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
719d88c236122420bab454b120302ded66f22838
828
py
Python
var/spack/repos/builtin/packages/py-cyvcf2/package.py
jeanbez/spack
f4e51ce8f366c85bf5aa0eafe078677b42dae1ba
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
var/spack/repos/builtin/packages/py-cyvcf2/package.py
jeanbez/spack
f4e51ce8f366c85bf5aa0eafe078677b42dae1ba
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
8
2021-11-09T20:28:40.000Z
2022-03-15T03:26:33.000Z
var/spack/repos/builtin/packages/py-cyvcf2/package.py
jeanbez/spack
f4e51ce8f366c85bf5aa0eafe078677b42dae1ba
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
2
2019-02-08T20:37:20.000Z
2019-03-31T15:19:26.000Z
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack.package import * class PyCyvcf2(PythonPackage): """fast vcf parsing with cython + htslib""" homepage = "https://github.com/brentp/cyvcf2" pypi = "cyvcf2/cyvcf2-0.11.7.tar.gz" version('0.11.7', sha256='a4b6229b89a0a1043684c65cbdd702c366a8800dc3591fb44c4b5a08640cbeec') depends_on('python@2.7:', type=('build', 'run')) depends_on('py-setuptools', type='build') depends_on('py-cython@0.23.3:', type='build') depends_on('py-numpy', type=('build', 'run')) depends_on('py-coloredlogs', type=('build', 'run')) depends_on('py-click', type=('build', 'run')) depends_on('curl')
31.846154
96
0.689614
109
828
5.174312
0.623853
0.111702
0.097518
0.134752
0.230496
0.12234
0
0
0
0
0
0.099859
0.141304
828
25
97
33.12
0.69339
0.274155
0
0
0
0
0.415541
0.153716
0
0
0
0
0
1
0
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
719e7932fde71fc017391588fcca49763cf61208
5,283
py
Python
test_soundcard.py
flying-sheep/SoundCard
b476c8142b460fc8161d374b282fe846d72a0780
[ "BSD-3-Clause" ]
1
2020-01-27T00:59:12.000Z
2020-01-27T00:59:12.000Z
test_soundcard.py
flying-sheep/SoundCard
b476c8142b460fc8161d374b282fe846d72a0780
[ "BSD-3-Clause" ]
null
null
null
test_soundcard.py
flying-sheep/SoundCard
b476c8142b460fc8161d374b282fe846d72a0780
[ "BSD-3-Clause" ]
null
null
null
import sys import soundcard import numpy import pytest ones = numpy.ones(1024) signal = numpy.concatenate([[ones], [-ones]]).T def test_speakers(): for speaker in soundcard.all_speakers(): assert isinstance(speaker.name, str) assert hasattr(speaker, 'id') assert isinstance(speaker.channels, int) assert speaker.channels > 0 def test_microphones(): for microphone in soundcard.all_microphones(): assert isinstance(microphone.name, str) assert hasattr(microphone, 'id') assert isinstance(microphone.channels, int) assert microphone.channels > 0 def test_default_playback(): soundcard.default_speaker().play(signal, 44100, channels=2) def test_default_record(): recording = soundcard.default_microphone().record(1024, 44100) assert len(recording == 1024) def test_default_blockless_record(): recording = soundcard.default_microphone().record(None, 44100) @pytest.fixture def loopback_speaker(): import sys if sys.platform == 'win32': # must install https://www.vb-audio.com/Cable/index.htm return soundcard.get_speaker('Cable') elif sys.platform == 'darwin': # must install soundflower return soundcard.get_speaker('Soundflower64') elif sys.platform == 'linux': # pacmd load-module module-null-sink channels=6 rate=48000 return soundcard.get_speaker('Null') else: raise RuntimeError('Unknown platform {}'.format(sys.platform)) @pytest.fixture def loopback_player(loopback_speaker): with loopback_speaker.player(48000, channels=2, blocksize=512) as player: yield player @pytest.fixture def loopback_microphone(): if sys.platform == 'win32': # must install https://www.vb-audio.com/Cable/index.htm return soundcard.get_microphone('Cable') elif sys.platform == 'darwin': # must install soundflower return soundcard.get_microphone('Soundflower64') elif sys.platform == 'linux': return soundcard.get_microphone('Null', include_loopback=True) else: raise RuntimeError('Unknown platform {}'.format(sys.platform)) @pytest.fixture def loopback_recorder(loopback_microphone): with loopback_microphone.recorder(48000, channels=2, blocksize=512) as recorder: yield recorder def test_loopback_playback(loopback_player, loopback_recorder): loopback_player.play(signal) recording = loopback_recorder.record(1024*10) assert recording.shape[1] == 2 left, right = recording.T assert left.mean() > 0 assert right.mean() < 0 assert (left > 0.5).sum() == len(signal) assert (right < -0.5).sum() == len(signal) def test_loopback_reverse_recorder_channelmap(loopback_player, loopback_microphone): with loopback_microphone.recorder(48000, channels=[1, 0], blocksize=512) as loopback_recorder: loopback_player.play(signal) recording = loopback_recorder.record(1024*12) assert recording.shape[1] == 2 left, right = recording.T assert right.mean() > 0 assert left.mean() < 0 assert (right > 0.5).sum() == len(signal) assert (left < -0.5).sum() == len(signal) def test_loopback_reverse_player_channelmap(loopback_speaker, loopback_recorder): with loopback_speaker.player(48000, channels=[1, 0], blocksize=512) as loopback_player: loopback_player.play(signal) recording = loopback_recorder.record(1024*12) assert recording.shape[1] == 2 left, right = recording.T assert right.mean() > 0 assert left.mean() < 0 assert (right > 0.5).sum() == len(signal) assert (left < -0.5).sum() == len(signal) def test_loopback_mono_player_channelmap(loopback_speaker, loopback_recorder): with loopback_speaker.player(48000, channels=[0], blocksize=512) as loopback_player: loopback_player.play(signal[:,0]) recording = loopback_recorder.record(1024*12) assert recording.shape[1] == 2 left, right = recording.T assert left.mean() > 0 if sys.platform == 'linux': # unmapped channels on linux are filled with the mean of other channels assert right.mean() < left.mean() else: assert abs(right.mean()) < 0.01 # something like zero assert (left > 0.5).sum() == len(signal) def test_loopback_mono_recorder_channelmap(loopback_player, loopback_microphone): with loopback_microphone.recorder(48000, channels=[0], blocksize=512) as loopback_recorder: loopback_player.play(signal) recording = loopback_recorder.record(1024*12) assert len(recording.shape) == 1 or recording.shape[1] == 1 assert recording.mean() > 0 assert (recording > 0.5).sum() == len(signal) def test_loopback_multichannel_channelmap(loopback_speaker, loopback_microphone): with loopback_speaker.player(48000, channels=[2, 0], blocksize=512) as loopback_player: with loopback_microphone.recorder(48000, channels=[2, 0], blocksize=512) as loopback_recorder: loopback_player.play(signal) recording = loopback_recorder.record(1024*12) assert len(recording.shape) == 2 left, right = recording.T assert left.mean() > 0 assert right.mean() < 0 assert (left > 0.5).sum() == len(signal) assert (right < -0.5).sum() == len(signal)
38.845588
102
0.696952
662
5,283
5.432024
0.163142
0.050612
0.013904
0.022247
0.676307
0.657953
0.622358
0.59594
0.556174
0.548109
0
0.046955
0.18569
5,283
135
103
39.133333
0.788935
0.057543
0
0.477876
0
0
0.024744
0
0
0
0
0
0.327434
1
0.132743
false
0
0.044248
0
0.230089
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
719fd87192b7b49949a8b70a475fd96677b03575
6,137
py
Python
osr_odometry/scripts/osr_odom_ackerman2.py
ljb2208/osr-rover-code
f4791d835cd760446777a226d37bb3114256affd
[ "Apache-2.0" ]
null
null
null
osr_odometry/scripts/osr_odom_ackerman2.py
ljb2208/osr-rover-code
f4791d835cd760446777a226d37bb3114256affd
[ "Apache-2.0" ]
null
null
null
osr_odometry/scripts/osr_odom_ackerman2.py
ljb2208/osr-rover-code
f4791d835cd760446777a226d37bb3114256affd
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python import time from osr_msgs.msg import Joystick, Commands, Encoder, RunStop from nav_msgs.msg import Odometry from geometry_msgs.msg import Point, Pose, Quaternion, Twist, Vector3 import rospy import tf import math import numpy class Odometry2(): def __init__(self, baseFrame, wheelTrack, mpt, d4, maxTickPerSec, pubTF=False): self.encValid = False self.priorTime = rospy.Time.now() self.priorEncs = [0,0,0,0,0,0] self.mpt = mpt self.pubTF = pubTF # distance between wheels self.wheelTrack = wheelTrack self.d4 = d4 self.baseFrame = baseFrame self.maxTickPerSec = maxTickPerSec self.x = 0.0 self.y = 0.0 self.th = 0.0 self.odomPub = rospy.Publisher("/odom", Odometry, queue_size = 1) if self.pubTF: self.odomBroadcaster = tf.TransformBroadcaster() self.twistCovar = numpy.diag([0.001, 0.001, 0.001, 0.1, 0.1, 0.1]).ravel() self.poseCovar = numpy.diag([0.001, 0.001, 0.001, 0.1, 0.1, 0.1]).ravel() def onEncoderMessage(self, message): self.calculateOdometry(message) def isValid(self, message): dencLeft = abs(message.rel_enc[1] - self.priorEncs[1]) dencRight = abs(message.rel_enc[4] - self.priorEncs[4]) dt = self.getElapsedTime(message.header.stamp) if (dencLeft/dt) > self.maxTickPerSec: rospy.logwarn("Invalid relative encoder value on left wheel. No odom calculated") return False if (dencRight/dt) > self.maxTickPerSec: rospy.logwarn("Invalid relative encoder value on right wheel. No odom calculated") return False return True def publishTransform(self, x, y, quaternion, timestamp): self.odomBroadcaster.sendTransform( (x, y, 0), (quaternion.x, quaternion.y, quaternion.z, quaternion.w), timestamp, self.baseFrame, "odom") def publishOdomMessage(self, x, y, vx, vy, vth, quaternion, timestamp): odom = Odometry() odom.header.frame_id = "odom" odom.child_frame_id = self.baseFrame odom.header.stamp = timestamp odom.pose.pose.position.x = x odom.pose.pose.position.y = y odom.pose.pose.position.z = 0 odom.pose.covariance = self.poseCovar odom.pose.pose.orientation = quaternion odom.twist.twist.linear.x = vx odom.twist.twist.linear.y = vy odom.twist.twist.linear.z = 0 odom.twist.twist.angular.z = vth odom.twist.covariance = self.twistCovar self.odomPub.publish(odom) def getElapsedTime(self, timestamp, save=False): dt = (timestamp - self.priorTime).to_sec() if save: self.priorTime = timestamp return dt def calculateTurnRadius(self, dLeft, dRight): dlr = dLeft - dRight # calculate radius of turn if dlr != 0 and dLeft != 0 and dRight != 0: lv = self.d4 + dLeft / dRight * self.d4 # print ("lv: " + str(lv)) r = lv / (1 - (dLeft / dRight)) else: r = 0 dist = (dLeft + dRight) / 2 # calculate angle change if (r != 0): dTheta = dist / -r else: dTheta = 0 return r, dTheta def calculateOdometry(self, message): currentTime = message.header.stamp encs = message.rel_enc if not self.isValid(message): return dt = self.getElapsedTime(currentTime, save=True) dLeft = self.mpt * (encs[1] - self.priorEncs[1]) dRight = self.mpt * (encs[4] - self.priorEncs[4]) # dth = (dRight - dLeft) / self.wheelTrack radius, dTheta = self.calculateTurnRadius(dLeft, dRight) # calculate centre of turn circle xOrig = self.x + radius * math.cos(self.th) yOrig = self.y + radius * math.sin(self.th) # calculate new co-ordinates xNew = xOrig + (self.x - xOrig) * math.cos(dTheta) - (self.y - yOrig) * math.sin(dTheta) yNew = yOrig + (self.x - xOrig) * math.sin(dTheta) + (self.y - yOrig) * math.cos(dTheta) #calculate change in x,y values dx = xNew - self.x dy = yNew - self.y self.th += dTheta if (self.th > (math.pi * 2)): self.th -= (math.pi * 2) elif (self.th < (-math.pi * 2)): self.th += (math.pi * 2) self.x = xNew self.y = yNew # convert to ros co-ords xRos = self.y yRos = -self.x vxRos = dy / dt vyRos = -dx / dt vth = dTheta /dt quaternion = self.getQuaternion(self.th) if self.pubTF: self.publishTransform(xRos, yRos, quaternion, currentTime) self.publishOdomMessage(xRos, yRos, vxRos, vyRos, vth, quaternion, currentTime) self.priorEncs = encs def getQuaternion(self, th): quaternion = Quaternion() quaternion.x = 0.0 quaternion.y = 0.0 quaternion.z = math.sin(th / 2.0) quaternion.w = math.cos(th / 2.0) return quaternion if __name__ == '__main__': rospy.init_node('osr_odometry2') rospy.loginfo("Starting the osr odometry2 node") baseFrame = rospy.get_param("/odometry/base_frame_id", "base_link") # mpt = rospy.get_param("/odometry/mpt", 0.000026322) mpt = rospy.get_param("/odometry/mpt", 0.000100708) wheelTrack = rospy.get_param("/odometry/wheel_track", 0.455) d4 = rospy.get_param("/odometry/d4", 0.2559) maxTickPerSec = rospy.get_param("/odometry/maxTickPerSec", 8000) publishTF = rospy.get_param("~publishTF", False) odom = Odometry2(baseFrame, wheelTrack, mpt, d4, maxTickPerSec, pubTF=publishTF) encSub = rospy.Subscriber("/encoder", Encoder, odom.onEncoderMessage) rate = rospy.Rate(20) while not rospy.is_shutdown(): rate.sleep()
30.532338
96
0.579599
739
6,137
4.763194
0.247632
0.005682
0.025852
0.035795
0.139205
0.126136
0.082955
0.067045
0.067045
0.067045
0
0.030026
0.305361
6,137
200
97
30.685
0.795684
0.053772
0
0.044776
0
0
0.054021
0.011564
0
0
0
0
0
1
0.067164
false
0
0.059701
0
0.186567
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
71a0b40b2d964c1cdacc2a99529ad40612493ff0
4,199
py
Python
src/simulation-conditioning/utilities/data-generation-scripts/Wavefield_Marmousi_pml_401x301_1000-1287_120-232_4k_20kp100_A_train.py
alisiahkoohi/importance-of-transfer-learning
bb4c7943f4ff64a2f1785503328b4cbb4f5111aa
[ "MIT" ]
null
null
null
src/simulation-conditioning/utilities/data-generation-scripts/Wavefield_Marmousi_pml_401x301_1000-1287_120-232_4k_20kp100_A_train.py
alisiahkoohi/importance-of-transfer-learning
bb4c7943f4ff64a2f1785503328b4cbb4f5111aa
[ "MIT" ]
4
2020-09-25T22:32:41.000Z
2022-02-09T23:36:02.000Z
src/simulation-conditioning/utilities/data-generation-scripts/Wavefield_Marmousi_pml_401x301_1000-1287_120-232_4k_20kp100_A_train.py
slimgroup/Software.siahkoohi2019itl
bb4c7943f4ff64a2f1785503328b4cbb4f5111aa
[ "MIT" ]
null
null
null
import numpy as np import h5py import os from devito.logger import info from devito import TimeFunction, clear_cache from examples.seismic.acoustic import AcousticWaveSolver from examples.seismic import Model, RickerSource, Receiver, TimeAxis from math import floor from scipy.interpolate import griddata import argparse parser = argparse.ArgumentParser(description='') parser.add_argument('--data_path', dest='data_path', type=str, default='/home/ec2-user/data', help='raw data path') parser.add_argument('--save_dir', dest='save_dir', type=str, default='/home/ec2-user/data', help='saving directory') args = parser.parse_args() data_path = args.data_path save_dir = args.save_dir origin = (0., 0.) spacing=(7.5, 7.5) tn=1100. nbpml=40 # Define your vp in km/sec (x, z) vp = np.fromfile(os.path.join(data_path, 'vp_marmousi_bi'), dtype='float32', sep="") vp = np.reshape(vp, (1601, 401)) # vp = vp[400:1401, 0:401] shape=[401, 301] values = np.zeros([vp.shape[0]*vp.shape[1], ]) points = np.zeros([vp.shape[0]*vp.shape[1], 2]) k = 0 for indx in range(0, vp.shape[0]): for indy in range(0, vp.shape[1]): values[k] = vp[indx, indy] points[k, 0] = indx points[k, 1] = indy k = k + 1 # nx, ny = shape[0], shape[1] X, Y = np.meshgrid(np.array(np.linspace(1000, 1287, shape[0])), np.array(np.linspace(120, 232, shape[1]))) int_vp = griddata(points, values, (X, Y), method='cubic') int_vp = np.transpose(int_vp) vp = int_vp # create model model = Model(origin, spacing, shape, 2, vp, nbpml=nbpml) # Derive timestepping from model spacing dt = model.critical_dt t0 = 0.0 nt = int(1 + (tn-t0) / dt) # Number of timesteps time = np.linspace(t0, tn, nt) # Discretized time axis datasize0 = int(np.shape(range(0, shape[0], 4))[0]) datasize1 = int(np.shape(range(100, nt, 20))[0]) datasize = datasize0*datasize1 strTrainA = os.path.join(save_dir, 'Wavefield_Marmousi_pml_401x301_1000-1287_120-232_4k_20kp100_A_train.hdf5') strTrainB = os.path.join(save_dir, 'Wavefield_Marmousi_pml_401x301_1000-1287_120-232_4k_20kp100_B_train.hdf5') dataset_train = "train_dataset" file_trainA = h5py.File(strTrainA, 'w-') datasetA = file_trainA.create_dataset(dataset_train, (datasize, shape[0]+2*nbpml, shape[1]+2*nbpml)) file_trainB = h5py.File(strTrainB, 'w-') datasetB = file_trainB.create_dataset(dataset_train, (datasize, shape[0]+2*nbpml, shape[1]+2*nbpml)) num_rec = 601 rec_samp = np.linspace(0., model.domain_size[0], num=num_rec); rec_samp = rec_samp[1]-rec_samp[0] time_range = TimeAxis(start=t0, stop=tn, step=dt) src = RickerSource(name='src', grid=model.grid, f0=0.025, time_range=time_range, space_order=1, npoint=1) src.coordinates.data[0, :] = np.array([1*spacing[0], 2*spacing[1]]).astype(np.float32) rec = Receiver(name='rec', grid=model.grid, time_range=time_range, npoint=num_rec) rec.coordinates.data[:, 0] = np.linspace(0., model.domain_size[0], num=num_rec) rec.coordinates.data[:, 1:] = src.coordinates.data[0, 1:] solverbad = AcousticWaveSolver(model, source=src, receiver=rec, kernel='OT2', isic=True, space_order=2, freesurface=False) solvergood = AcousticWaveSolver(model, source=src, receiver=rec, kernel='OT2', isic=True, space_order=20, freesurface=False) ulocgood = TimeFunction(name="u", grid=model.grid, time_order=2, space_order=20, save=nt) ulocbad = TimeFunction(name="u", grid=model.grid, time_order=2, space_order=2, save=nt) kk = 0 for xsrc in range(0, shape[0], 4): clear_cache() ulocgood.data.fill(0.) ulocbad.data.fill(0.) src.coordinates.data[0, :] = np.array([xsrc*spacing[0], 2*spacing[1]]).astype(np.float32) rec.coordinates.data[:, 0] = np.linspace(0., model.domain_size[0], num=num_rec) rec.coordinates.data[:, 1:] = src.coordinates.data[0, 1:] _, ulocgood, _ = solvergood.forward(m=model.m, src=src, time=nt-1, save=True) _, ulocbad, _ = solverbad.forward(m=model.m, src=src, time=nt-1, save=True) datasetA[kk:(kk+datasize1), :, :] = np.array(ulocgood.data[range(100, nt, 20), :, :]) datasetB[kk:(kk+datasize1), :, :] = np.array(ulocbad.data[range(100, nt, 20), :, :]) kk = kk + datasize1 file_trainA.close() file_trainB.close()
34.702479
116
0.700881
676
4,199
4.233728
0.263314
0.018868
0.033543
0.026555
0.402166
0.354997
0.336827
0.336827
0.297694
0.274284
0
0.062346
0.129078
4,199
120
117
34.991667
0.720263
0.042391
0
0.04878
0
0
0.076252
0.035883
0
0
0
0
0
1
0
false
0
0.121951
0
0.121951
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
71a3ec3949c4d0b824f364cf880c163e7d4093ec
749
py
Python
JumpscaleCore/clients/tcprouter/TCPRouterFactory.py
gneumann333/jumpscaleX_core
777d249fa3668c6e802c2f765f4b82fb39c3e5fa
[ "Apache-2.0" ]
1
2020-06-21T11:18:52.000Z
2020-06-21T11:18:52.000Z
JumpscaleCore/clients/tcprouter/TCPRouterFactory.py
gneumann333/jumpscaleX_core
777d249fa3668c6e802c2f765f4b82fb39c3e5fa
[ "Apache-2.0" ]
644
2019-08-25T10:19:56.000Z
2020-12-23T09:41:04.000Z
JumpscaleCore/clients/tcprouter/TCPRouterFactory.py
gneumann333/jumpscaleX_core
777d249fa3668c6e802c2f765f4b82fb39c3e5fa
[ "Apache-2.0" ]
11
2019-08-29T21:38:50.000Z
2020-06-21T11:18:55.000Z
from Jumpscale import j from .TCPRouterClient import TCPRouterClient JSConfigs = j.baseclasses.object_config_collection class TCPRouterFactory(JSConfigs): __jslocation__ = "j.clients.tcp_router" _CHILDCLASS = TCPRouterClient def test(self): """ kosmos 'j.clients.tcp_router.test()' """ # get a client instance (TO CHECK: secret is already assigned to backend) cl = self.get( "test_instance", local_ip="0.0.0.0", local_port=18000, remote_url="127.0.0.1", remote_port=6379, secret="test", ) # connect to backend cl.connect() # stop connection cl.stop() print("TEST OK")
22.029412
81
0.580774
82
749
5.134146
0.585366
0.019002
0.052257
0.08076
0
0
0
0
0
0
0
0.037328
0.320427
749
33
82
22.69697
0.789784
0.192256
0
0
0
0
0.103627
0
0
0
0
0
0
1
0.055556
false
0
0.111111
0
0.333333
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
0
0
0
0
0
1
0
71a54794818c1c14503bf2853a8ad157b14a963f
8,837
py
Python
nmrglue/fileio/spinsolve.py
miguelarbesu/nmrglue
6ca36de7af1a2cf109f40bf5afe9c1ce73c9dcdc
[ "BSD-3-Clause" ]
null
null
null
nmrglue/fileio/spinsolve.py
miguelarbesu/nmrglue
6ca36de7af1a2cf109f40bf5afe9c1ce73c9dcdc
[ "BSD-3-Clause" ]
null
null
null
nmrglue/fileio/spinsolve.py
miguelarbesu/nmrglue
6ca36de7af1a2cf109f40bf5afe9c1ce73c9dcdc
[ "BSD-3-Clause" ]
null
null
null
""" Functions for reading Magritek Spinsolve binary (dx/1d) files and parameter (acqu.par/proc.par) files. """ import os from warnings import warn import numpy as np from . import fileiobase from . import jcampdx __developer_info__ = """ Spinsolve is the software used on the Magritek benchtop NMR devices. A spectrum is saved in a folder with several files. The spectral data is stored in these files: 'data.1d' (FID), 'spectrum.1d' (Fourier transformed) and 'spectrum_processed.1d' (FT + processed by spinsolve) Optional spectral data (System->Prefs->Setup->Global data storage): 'nmr_fid.dx' (FID stored in `JCAMP-DX standard <http://www.jcamp-dx.org/>`), 'spectrum.csv' and 'spectrum_processed.csv' (FT + processed by Spinsovle with ppm for each point and intensity delimited by ';') Other files: 'acqu.par' - all parameters that are used for acquisition 'Protocol.par' - text file used to reload data back into the Spinsolve software 'processing.script' - text file to transfer Spinsolve software protocol settings into MNOVA The Spinsolve Expert software has a slightly different output: [Needs to be double checked as I do not have access to this software -LCageman] - Output into JCAMP-DX is not possible - 'spectrum_processed.1d' is not generated - (new) 'fid.1d' - seems to be the same as 'data.1d' - (new) 'proc.par' - contains processing parameters in the same style as 'acqu.par' - (new) .pt1 files - seem to be plot files specific for the expert software, cannot be read by NMRglue """ def read(dir='.', specfile=None, acqupar="acqu.par", procpar="proc.par"): """ Reads spinsolve files from a directory When no spectrum filename is given (specfile), the following list is tried, in that specific order ["nmr_fid.dx", "data.1d", "fid.1d", "spectrum.1d", "spectrum_processed.1d"] To use the resolution enhanced spectrum use the './Enhanced' folder as input. Note that spectrum.1d and spectrum_processed.1d contain only data in the frequency domain, so no Fourier transformation is needed. Also, use dic["spectrum"]["xaxis"] to plot the x-axis Parameters ---------- dir : str Directory to read from specfile : str, optional Filename to import spectral data from. None uses standard filename from: ["nmr_fid.dx", "data.1d", "fid.1d", "spectrum.1d", "spectrum_processed.1d"] acqupar : str, optional Filename for acquisition parameters. None uses standard name. procpar : str, optional Filename for processing parameters. None uses standard name. Returns ------- dic : dict All parameters that can be present in the data folder: dic["spectrum"] - First bytes of spectrum(_processed).1d dic["acqu"] - Parameters present in acqu.par dic["proc"] - Parameters present in proc.par dic["dx"] - - Parameters present in the header of nmr_fid.dx data : ndarray Array of NMR data """ if os.path.isdir(dir) is not True: raise IOError("directory %s does not exist" % (dir)) # Create empty dic dic = {"spectrum": {}, "acqu": {}, "proc":{}, "dx":{}} # Read in acqu.par and write to dic acqupar = os.path.join(dir, acqupar) if os.path.isfile(acqupar): with open(acqupar, "r") as f: info = f.readlines() for line in info: line = line.replace("\n", "") k, v = line.split("=") dic["acqu"][k.strip()] = v.strip() # Read in proc.par and write to dic procpar = os.path.join(dir,procpar) if os.path.isfile(procpar): with open(procpar, "r") as f: info = f.readlines() for line in info: line = line.replace("\n", "") k, v = line.split("=") dic["proc"][k.strip()] = v.strip() # Define which spectrumfile to take, using 'specfile' when defined, otherwise # the files in 'priority_list' are tried, in that particular order priority_list = ["nmr_fid.dx", "data.1d", "fid.1d", "spectrum.1d", "spectrum_processed.1d", None] if specfile: inputfile = os.path.join(dir, specfile) if not os.path.isfile(inputfile): raise IOError("File %s does not exist" % (inputfile)) else: for priority in priority_list: if priority == None: raise IOError("directory %s does not contain spectral data" % (dir)) inputfile = os.path.join(dir, priority) if os.path.isfile(inputfile): break # Detect which file we are dealing with from the extension and read in the spectral data # Reading .dx file using existing nmrglue.fileio.jcampdx module if inputfile.split('.')[-1] == "dx": dic["dx"], raw_data = jcampdx.read(inputfile) data = np.empty((int(dic["dx"]["$TD"][0]), ), dtype='complex128') data = raw_data[0][:] + 1j * raw_data[1][:] # Reading .1d files elif inputfile.split('.')[-1] == "1d": with open(inputfile, "rb") as f: raw_data = f.read() # Write out parameters from the first 32 bytes into dic["spectrum"] keys = ["owner", "format", "version", "dataType", "xDim", "yDim", "zDim", "qDim"] for i, k in enumerate(keys): start = i * 4 end = start + 4 value = int.from_bytes( raw_data[start:end], "little") dic["spectrum"][k] = value data = np.frombuffer(raw_data[end:], "<f") # The first 1/3 of the file is xaxis data (s or ppm) split = data.shape[-1] // 3 xscale = data[0 : split] dic["spectrum"]["xaxis"] = xscale # The rest is real and imaginary data points interleaved data = data[split : : 2] + 1j * data[split + 1 : : 2] else: raise IOError("File %s cannot be interpreted, use .dx or .1d instead" % (inputfile)) return dic,data def guess_udic(dic,data): """ Guess parameters of universal dictionary from dic, data pair. Parameters ---------- dic : dict Dictionary of JCAMP-DX, acqu, proc and spectrum parameters. data : ndarray Array of NMR data. Returns ------- udic : dict Universal dictionary of spectral parameters. """ # Create an empty universal dictionary udic = fileiobase.create_blank_udic(1) # Update defalt parameters, first acqu.par parameters in dic are tried, then JCAMP-DX header parameters # size if data is not None: udic[0]["size"] = len(data) else: warn('No data, cannot set udic size') # sw try: udic[0]['sw'] = float(dic['acqu']['bandwidth']) * 1000 except KeyError: try: udic[0]['sw'] = float(dic['dx']['$SW'][0]) * float(dic['dx']['$BF1'][0]) except KeyError: try: if dic["spectrum"]["freqdata"]: udic[0]['sw'] = dic["spectrum"]["xaxis"][-1] - dic["spectrum"]["xaxis"][0] elif data is not None: udic[0]['sw'] = len(data) / dic["spectrum"]["xaxis"][-1] else: warn("Cannot set spectral width - set manually using: 'udic[0]['sw'] = x' where x is the spectral width in Hz") except KeyError: warn("Cannot set spectral width - set manually using: 'udic[0]['sw'] = x' where x is the spectral width in Hz") # obs try: udic[0]['obs'] = float(dic['acqu']['b1Freq']) except KeyError: try: udic[0]['obs'] = float(dic['dx']['$BF1'][0]) except KeyError: warn("Cannot set observe frequency - set manually using: 'udic[0]['obs'] = x' where x is magnetic field in MHz") # car try: udic[0]['car'] = float(dic['acqu']['lowestFrequency']) + (float(dic['acqu']['bandwidth']) * 1000 / 2) except KeyError: try: udic[0]['car'] = (float(dic['dx']['$REFERENCEPOINT'][0]) * -1 ) + (float(dic['dx']['$SW'][0]) * udic[0]['obs'] / 2) except KeyError: try: udic[0]['car'] = (float(dic['dx']['$BF1'][0]) - float(dic['dx']['$SF'][0])) * 1000000 except KeyError: warn("Cannot set carrier - try: 'udic[0]['car'] = x * udic[0]['obs']' where x is the center of the spectrum in ppm") # label try: udic[0]['label'] = dic['acqu']['rxChannel'] except KeyError: try: label_value = dic['dx'][".OBSERVENUCLEUS"][0].replace("^", "") udic[0]["label"] = label_value except KeyError: warn("Cannot set observed nucleus label") #keys left to default # udic[0]['complex'] # udic[0]['encoding'] # udic[0]['time'] = True # udic[0]['freq'] = False return udic
37.764957
132
0.593188
1,177
8,837
4.425658
0.254036
0.021117
0.013822
0.009215
0.212901
0.149549
0.105586
0.094836
0.094836
0.094836
0
0.016102
0.269096
8,837
233
133
37.927039
0.79037
0.278715
0
0.265625
0
0.070313
0.377132
0.01949
0
0
0
0
0
1
0.015625
false
0
0.039063
0
0.070313
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
71a6a1b4c00b5723fdf1d5cebd6d02a67810c5fb
21,781
py
Python
src/navigation_analytics/navigation_data.py
mielgosez/navigation_analytics
3c382e8200afe4d37fa0880f155bf1bb2f48b83f
[ "MIT" ]
null
null
null
src/navigation_analytics/navigation_data.py
mielgosez/navigation_analytics
3c382e8200afe4d37fa0880f155bf1bb2f48b83f
[ "MIT" ]
null
null
null
src/navigation_analytics/navigation_data.py
mielgosez/navigation_analytics
3c382e8200afe4d37fa0880f155bf1bb2f48b83f
[ "MIT" ]
null
null
null
import logging import copy import pickle import pandas as pd class BaseClass: def __init__(self, input_data: pd.DataFrame, logger: logging.Logger, metadata: dict): self.__input_data = input_data self.__logger = logger self.__metadata = metadata @property def logger(self): return self.__logger @property def metadata(self): return self.__metadata @property def input_data(self): return self.__input_data @input_data.setter def input_data(self, new_input_data: pd.DataFrame): self.__input_data = new_input_data @property def events_id(self): return self.__metadata['metadata']['primary_keys']['events'] @property def session_id(self): return self.__metadata['metadata']['primary_keys']['sessions'] @property def page_id(self): return self.__metadata['metadata']['primary_keys']['pages'] @property def group_id(self): return self.metadata['metadata']['valid_values']['groups']['group_id'] @property def valid_groups(self): return self.metadata['metadata']['valid_values']['groups']['valid'] @property def action_id(self): return self.metadata['metadata']['valid_values']['actions']['action_id'] @property def valid_actions(self): return self.metadata['metadata']['valid_values']['actions']['valid'] @property def search_action(self): return self.metadata['metadata']['valid_values']['actions']['search_action'] @property def visit_action(self): return self.metadata['metadata']['valid_values']['actions']['visit_action'] @property def timestamp_id(self): return self.metadata['metadata']['datetime'] @property def kpi_duration(self): return self.metadata['metadata']['valid_values']['kpis']['duration_page'] @property def kpi_position(self): return self.metadata['metadata']['valid_values']['kpis']['result_position'] @property def kpi_number_results(self): return self.metadata['metadata']['valid_values']['kpis']['number_results'] class DataValidator(BaseClass): def __init__(self, logger: logging.Logger, metadata: dict, input_data: pd.DataFrame): super().__init__(logger=logger, metadata=metadata, input_data=input_data) self.default_pipeline() # Pipelines def default_pipeline(self): self.check_events_are_unique() self.check_groups_are_valid() self.check_one_group_per_session() # Validation Rules def check_events_are_unique(self): """ Verifies that event identifier is primary key of input data. :return: Validation """ number_rows = self.input_data.shape[0] events_id = self.metadata['metadata']['primary_keys']['events'] number_events = len(self.input_data[events_id].unique()) if number_rows == number_events: self.logger.info(f'Validation - Events are unique: {number_rows} rows and {number_events} events.') else: self.logger.error(f'Validation - Events are not unique: {number_rows} rows and {number_events} events.') def check_groups_are_valid(self): """ Verifies that groups matches with those declared in metadata. :return: Validation """ group_id = self.metadata['metadata']['valid_values']['groups']['group_id'] groups_in_data = list(self.input_data[group_id].unique()) group_valid_names = list(self.metadata['metadata']['valid_values']['groups']['valid']) if set(groups_in_data) == set(group_valid_names): self.logger.info(f'Validation - Groups are valid: {", ".join(group_valid_names)}.') else: self.logger.error(f'Validation - Group names are not valid: ' f'Names in data are {", ".join(groups_in_data)}. ' f'Names in metadata are {", ".join(group_valid_names)}.') def check_one_group_per_session(self): """ Verifies that there's at most one group per session. :return: Validation """ group_id = self.metadata['metadata']['valid_values']['groups']['group_id'] session_id = self.metadata['metadata']['primary_keys']['sessions'] max_num_groups = self.input_data.groupby(session_id)[group_id].apply(lambda x: len(set(x))).max() if max_num_groups == 1: self.logger.info(f'Validation - Just one group per session.') else: self.logger.error(f'Validation - Groups per session is different to one. ' f'Maximum number of groups per session detected in data set is: {max_num_groups}') class SessionAnalyzer(BaseClass): def __init__(self, input_data: pd.DataFrame, metadata: dict, logger: logging.Logger): super().__init__(logger=logger, metadata=metadata, input_data=input_data) self.__results = dict() self.__session_data = self.create_session_look_up() self.__page_data = self.create_page_look_up() self.__page_data_out = self.create_page_look_up_out() self.__search_table = self.create_search_table() self.__duration_table = self.create_duration_table() def filter_session_by_group(self, group_id: str): """ Filter session by group id provided in the input. This is expected to be a recurrent operation. :param group_id: :return: """ if group_id not in self.valid_groups: self.logger.error(f'{group_id} is not a valid group.') return self.session_data.loc[self.session_data[self.group_id] == group_id, :] # Metrics def compute_click_through_rate(self, group_id: str = None): """ This function computes the click through rate, understanding this quantity as the ratio of searches ending up in a session landing in a page. Session Attribute. :param group_id: :return: """ result = None if group_id is None: key = 'click_through_rate' sub_key = 'all' # Merging sessions with page ids df = copy.deepcopy(self.session_data.merge(self.page_data, on=self.session_id, how='left')) # Computing boolean vector: True means session has a visit, False otherwise. result = df.groupby(by=self.session_id)[self.action_id].apply(lambda x: self.visit_action in set(x)) else: key = 'click_through_rate' sub_key = group_id if group_id in self.valid_groups: # Filtering sessions by required group. filtered_sessions = self.filter_session_by_group(group_id=group_id) df = copy.deepcopy(filtered_sessions.merge(self.page_data, on=self.session_id, how='left')) result = df.groupby(by='session_id').action.apply(lambda x: 'visitPage' in set(x)) else: self.logger.error(f'{group_id} is not a valid group.') # Computing ctr ctr = sum(result) / len(result) self.logger.info(f'Click Through Rate is equal to: {ctr}') # Storing results update_result = self.kpi_results try: update_result[key][key].append(ctr) update_result[key]['group'].append(sub_key) except KeyError: update_result[key] = dict() update_result[key][key] = [ctr] update_result[key]['group'] = [sub_key] self.kpi_results = update_result return ctr def compute_search_frequency(self, group_id: str = None, number_ranking: int = 10): """ Get the most common first result per session. This is a Session Attribute. :param number_ranking: Number of results to visualize. :param group_id: :return: """ if group_id is None: key = 'search_frequency' sub_key = 'all' df_sessions = self.session_data.copy() else: key = 'search_frequency' sub_key = group_id df_sessions = self.filter_session_by_group(group_id=group_id) df = df_sessions.merge(self.page_data, on=self.session_id, how='left') # Merge with duration table to retrieve datestamp data. df_all = df.merge(self.duration_table, on=self.page_id, how='left') df_all.dropna(inplace=True) # Most common first result df_all = df_all.groupby('session_id').apply(lambda x: x.loc[x[self.timestamp_id] == min(x[self.timestamp_id]), [self.kpi_position, self.timestamp_id]]) # Result result = df_all[self.kpi_position].value_counts(normalize=True)[:number_ranking] self.logger.info(f'Most common result is {result.index[0]}') # Store result updated_results = self.kpi_results try: updated_results[key][key].extend(list(result.values)) updated_results[key]['position'].extend(list(result.index)) updated_results[key]['group'].extend([sub_key]*len(result.index)) except KeyError: updated_results[key] = dict() updated_results[key][key] = list(result.values) updated_results[key]['position'] = list(result.index) updated_results[key]['group'] = [sub_key]*len(result.index) self.kpi_results = updated_results return result def compute_zero_result_rate(self, group_id: str = None): """ Computes the proportion of searches that end up in no results. :param group_id: :return: """ df = self.search_table.copy() # Compute number of searches resulting in found elements. df['success'] = [True if item == 0 else False for item in df[self.kpi_number_results]] if group_id is None: key = 'zero_result_rate' sub_key = 'all' result = df['success'] else: key = 'zero_result_rate' sub_key = group_id df_sessions = self.filter_session_by_group(group_id=group_id) df_pages = df_sessions.merge(self.page_data, on=self.session_id, how='left') df = df.merge(df_pages, on=self.page_id, how='left') df.dropna(inplace=True) result = df['success'] # Computing result value = sum(result) / len(result) self.logger.info(f'Zero result rate is: {value}') # Storing result. updated_results = self.kpi_results try: updated_results[key][key].append(value) updated_results[key]['group'].append(sub_key) except KeyError: updated_results[key] = dict() updated_results[key][key] = [value] updated_results[key]['group'] = [sub_key] self.kpi_results = updated_results return value def compute_session_length(self, group_id: str = None): """ Compute session's length :param group_id: :return: """ if group_id is None: key = 'session_length' sub_key = 'all' df = self.input_data else: key = 'session_length' sub_key = group_id df = self.filter_session_by_group(group_id=group_id) df = df.merge(self.input_data, on=self.session_id, how='left') # Compute results value = df.groupby(self.session_id)[self.timestamp_id].apply(lambda x: (max(x) - min(x)).total_seconds()) time_value = df.groupby(self.session_id)[self.timestamp_id].min() # Store results updated_results = self.kpi_results try: updated_results[key][key].extend(list(value.values)) updated_results[key]['session_date'].extend(list(time_value.values)) updated_results[key]['session_id'].extend(list(value.index)) updated_results[key]['group'].extend([sub_key]*len(value.index)) except KeyError: updated_results[key] = dict() updated_results[key][key] = list(value.values) updated_results[key]['session_date'] = list(time_value.values) updated_results[key]['session_id'] = list(value.index) updated_results[key]['group'] = [sub_key]*len(value.index) self.kpi_results = updated_results return value # Instantiation def update_data(self): self.page_data = self.create_page_look_up() self.page_data_out = self.create_page_look_up_out() self.session_data = self.create_session_look_up() self.duration_table = self.create_duration_table() self.search_table = self.create_search_table() def create_session_look_up(self): return self.input_data[[self.session_id, self.group_id]].drop_duplicates() def create_page_look_up_out(self): return self.input_data[[self.session_id, self.page_id]].drop_duplicates() def create_page_look_up(self): return self.input_data[[self.session_id, self.page_id, self.action_id]].drop_duplicates() def create_search_table(self): """ Preserves just search results from original dataset. :return: Information relevant only to searches """ local_df = self.input_data.copy() local_df = local_df.loc[local_df[self.action_id] == self.search_action, [self.events_id, self.timestamp_id, self.page_id, self.kpi_number_results]] return local_df def create_duration_table(self): """ Preserves just search results from original dataset. :return: Information relevant only to searches """ local_df = self.input_data.copy() local_df = local_df.loc[local_df[self.action_id] != self.search_action, [self.timestamp_id, self.page_id, self.kpi_position, self.kpi_duration]] # Remove redundant information on position and duration local_df = local_df.groupby(self.page_id).max() no_duration_info = local_df[self.kpi_duration].isna() no_position_info = local_df[self.kpi_position].isna() self.logger.warning(f'{no_position_info.sum()} NA values for {self.kpi_position}.') self.logger.warning(f'{no_duration_info.sum()} NA values for {self.kpi_duration}.') # Remove those observations where position of results do not exist while there is duration no_position_but_duration = [(2 * item[1] - item[0]) != 2 for item in zip(no_duration_info, no_position_info)] position_but_duration = [(2 * item[1] - item[0]) == 2 for item in zip(no_duration_info, no_position_info)] kpi_results = self.kpi_results kpi_results['invalid_results'] = local_df.loc[position_but_duration, :].copy() self.kpi_results = kpi_results self.logger.warning(f'{sum([not item for item in no_position_but_duration])} ' f'NA values for position with duration.') local_df = local_df.loc[no_position_but_duration, :] # The rest of cases fill 0 local_df.fillna(0, inplace=True) local_df.reset_index(inplace=True) local_df.sort_values(by=[self.timestamp_id, self.page_id], inplace=True) return local_df # Getters and setters @property def session_data(self): return self.__session_data @session_data.setter def session_data(self, new_session_data: pd.DataFrame): self.__session_data = new_session_data @property def page_data(self): return self.__page_data @page_data.setter def page_data(self, new_page_data: pd.DataFrame): self.__page_data = new_page_data @property def page_data_out(self): return self.__page_data_out @page_data_out.setter def page_data_out(self, new_page_data_out: pd.DataFrame): self.__page_data_out = new_page_data_out @property def number_sessions(self): return self.session_data.shape[0] @property def number_pages(self): return self.page_data.shape[0] @property def duration_table(self): return self.__duration_table @duration_table.setter def duration_table(self, new_duration_table: pd.DataFrame): self.__duration_table = new_duration_table @property def search_table(self): return self.__search_table @search_table.setter def search_table(self, new_search_table: pd.DataFrame): self.__search_table = new_search_table @property def kpi_results(self): return self.__results @kpi_results.setter def kpi_results(self, results: dict): self.__results = results class NavigationDataAnalyzer: def __init__(self, input_data: pd.DataFrame, metadata: dict, logger_level: int = logging.WARNING): self.__logger = logging.Logger(name='default_logger', level=logger_level) self.__input_data = input_data self.__metadata = metadata self.__data_validator = DataValidator(input_data=input_data, metadata=metadata, logger=self.logger) self.__session_analyzer = SessionAnalyzer(input_data=input_data, metadata=metadata, logger=self.logger) def get_number_events(self, group_name: str = None): """ Method used to retrieve the number of events in the dataset. It can be also be filtered by group name. This function assumes that events are the primary key of the dataset. :param group_name: Name of the study groups as defined in metadata (['valid_values']['groups']['valid']) :return: Number of events in the dataset (in total or per group) """ groups_id = self.metadata['metadata']['valid_values']['groups']['group_id'] valid_groups = self.metadata['metadata']['valid_values']['groups']['valid'] if group_name is None: return self.input_data.shape[0] else: if group_name in valid_groups: return self.input_data.loc[self.input_data[groups_id] == group_name].shape[0] else: self.logger.error(f'{group_name} is not a valid group name. ' f'Please select among those listed here: {", ".join(valid_groups)}') def save(self, name: str = 'navigation_data_analyzer.pickle'): objects_to_store = dict() objects_to_store['metadata'] = self.metadata objects_to_store['input_data'] = self.input_data objects_to_store['kpi_results'] = self.session_analyzer.kpi_results with open(name, 'wb') as fp: pickle.dump(objects_to_store, fp) @staticmethod def load(filepath: str): with open(filepath, 'rb') as fp: existing_object = pickle.load(fp) instance_object = NavigationDataAnalyzer(input_data=existing_object['input_data'], metadata=existing_object['metadata']) instance_object.session_analyzer.kpi_results = existing_object['kpi_results'] return instance_object def to_excel(self, filename: str): excel_writer = pd.ExcelWriter(filename) self.session_analyzer.session_data.to_excel(excel_writer, sheet_name='session_data', index=False) self.session_analyzer.page_data_out.to_excel(excel_writer, sheet_name='page_data', index=False) self.session_analyzer.duration_table.to_excel(excel_writer, sheet_name='duration_table', index=False) self.session_analyzer.search_table.to_excel(excel_writer, sheet_name='search_table', index=False) for key, value in self.session_analyzer.kpi_results.items(): results = pd.DataFrame(value) results.to_excel(excel_writer, sheet_name=f'kpi_{key}', index=False) groups_df = pd.DataFrame({'group': self.session_analyzer.valid_groups}) groups_df.to_excel(excel_writer, sheet_name='groups', index=False) excel_writer.save() excel_writer.close() # Getters and Setters @property def session_analyzer(self): return self.__session_analyzer @property def data_validator(self): return self.__data_validator @property def input_data(self): return self.__input_data @input_data.setter def input_data(self, new_input_data: pd.DataFrame): self.data_validator.input_data = new_input_data self.data_validator.default_pipeline() self.__input_data = new_input_data @property def metadata(self): return self.__metadata @metadata.setter def metadata(self, new_metadata: dict): self.__input_data = new_metadata @property def logger(self): return self.__logger @logger.setter def logger(self, new_logger): self.__logger = new_logger
40.186347
120
0.620724
2,659
21,781
4.802933
0.103422
0.036646
0.035079
0.02584
0.532065
0.436614
0.374051
0.314619
0.222222
0.17618
0
0.001271
0.277352
21,781
541
121
40.260628
0.810102
0.093338
0
0.340852
0
0
0.111899
0.010615
0
0
0
0
0
1
0.155388
false
0
0.010025
0.080201
0.280702
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
71ad91d94d2021895fed2197ad1e1027179c068d
5,844
py
Python
oneflow/python/test/ops/test_object_bbox_scale.py
caishenghang/oneflow
db239cc9f98e551823bf6ce2d4395bd5c339b1c5
[ "Apache-2.0" ]
2
2021-09-10T00:19:49.000Z
2021-11-16T11:27:20.000Z
oneflow/python/test/ops/test_object_bbox_scale.py
duijiudanggecl/oneflow
d2096ae14cf847509394a3b717021e2bd1d72f62
[ "Apache-2.0" ]
null
null
null
oneflow/python/test/ops/test_object_bbox_scale.py
duijiudanggecl/oneflow
d2096ae14cf847509394a3b717021e2bd1d72f62
[ "Apache-2.0" ]
1
2021-11-10T07:57:01.000Z
2021-11-10T07:57:01.000Z
""" Copyright 2020 The OneFlow 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. """ import unittest import os import random import cv2 import numpy as np import oneflow as flow import oneflow.typing as oft def _random_sample_images(anno_file, image_dir, batch_size): from pycocotools.coco import COCO image_files = [] image_ids = [] batch_group_id = -1 coco = COCO(anno_file) img_ids = coco.getImgIds() while len(image_files) < batch_size: rand_img_id = random.choice(img_ids) img_h = coco.imgs[rand_img_id]["height"] img_w = coco.imgs[rand_img_id]["width"] group_id = int(img_h / img_w) if batch_group_id == -1: batch_group_id = group_id if group_id != batch_group_id: continue anno_ids = coco.getAnnIds(imgIds=[rand_img_id]) if len(anno_ids) == 0: continue image_files.append(os.path.join(image_dir, coco.imgs[rand_img_id]["file_name"])) image_ids.append(rand_img_id) assert len(image_files) == len(image_ids) images = [cv2.imread(image_file).astype(np.single) for image_file in image_files] bbox_list = _get_images_bbox_list(coco, image_ids) return images, bbox_list def _get_images_bbox_list(coco, image_ids): bbox_list = [] for img_id in image_ids: anno_ids = coco.getAnnIds(imgIds=[img_id]) anno_ids = list( filter(lambda anno_id: coco.anns[anno_id]["iscrowd"] == 0, anno_ids) ) bbox_array = np.array( [coco.anns[anno_id]["bbox"] for anno_id in anno_ids], dtype=np.single ) bbox_list.append(bbox_array) return bbox_list def _get_images_static_shape(images): image_shapes = [image.shape for image in images] image_static_shape = np.amax(image_shapes, axis=0) assert isinstance( image_static_shape, np.ndarray ), "image_shapes: {}, image_static_shape: {}".format( str(image_shapes), str(image_static_shape) ) image_static_shape = image_static_shape.tolist() image_static_shape.insert(0, len(image_shapes)) return image_static_shape def _get_bbox_static_shape(bbox_list): bbox_shapes = [bbox.shape for bbox in bbox_list] bbox_static_shape = np.amax(bbox_shapes, axis=0) assert isinstance( bbox_static_shape, np.ndarray ), "bbox_shapes: {}, bbox_static_shape: {}".format( str(bbox_shapes), str(bbox_static_shape) ) bbox_static_shape = bbox_static_shape.tolist() bbox_static_shape.insert(0, len(bbox_list)) return bbox_static_shape def _of_target_resize_bbox_scale(images, bbox_list, target_size, max_size): image_shape = _get_images_static_shape(images) bbox_shape = _get_bbox_static_shape(bbox_list) flow.clear_default_session() func_config = flow.FunctionConfig() func_config.default_data_type(flow.float) func_config.default_logical_view(flow.scope.mirrored_view()) @flow.global_function(function_config=func_config) def target_resize_bbox_scale_job( image_def: oft.ListListNumpy.Placeholder( shape=tuple(image_shape), dtype=flow.float ), bbox_def: oft.ListListNumpy.Placeholder( shape=tuple(bbox_shape), dtype=flow.float ), ): images_buffer = flow.tensor_list_to_tensor_buffer(image_def) resized_images_buffer, new_size, scale = flow.image_target_resize( images_buffer, target_size=target_size, max_size=max_size ) bbox_buffer = flow.tensor_list_to_tensor_buffer(bbox_def) scaled_bbox = flow.object_bbox_scale(bbox_buffer, scale) scaled_bbox_list = flow.tensor_buffer_to_tensor_list( scaled_bbox, shape=bbox_shape[1:], dtype=flow.float ) return scaled_bbox_list, new_size input_image_list = [np.expand_dims(image, axis=0) for image in images] input_bbox_list = [np.expand_dims(bbox, axis=0) for bbox in bbox_list] output_bbox_list, output_image_size = target_resize_bbox_scale_job( [input_image_list], [input_bbox_list] ).get() return output_bbox_list.numpy_lists()[0], output_image_size.numpy_list()[0] def _compare_bbox_scale( test_case, anno_file, image_dir, batch_size, target_size, max_size, print_debug_info=False, ): images, bbox_list = _random_sample_images(anno_file, image_dir, batch_size) of_bbox_list, image_size_list = _of_target_resize_bbox_scale( images, bbox_list, target_size, max_size ) for image, bbox, of_bbox, image_size in zip( images, bbox_list, of_bbox_list, image_size_list ): w, h = image_size oh, ow = image.shape[0:2] scale_h = h / oh scale_w = w / ow bbox[:, 0] *= scale_w bbox[:, 1] *= scale_h bbox[:, 2] *= scale_w bbox[:, 3] *= scale_h test_case.assertTrue(np.allclose(bbox, of_bbox)) @flow.unittest.skip_unless_1n1d() class TestObjectBboxScale(flow.unittest.TestCase): def test_object_bbox_scale(test_case): _compare_bbox_scale( test_case, "/dataset/mscoco_2017/annotations/instances_val2017.json", "/dataset/mscoco_2017/val2017", 4, 800, 1333, ) if __name__ == "__main__": unittest.main()
32.287293
88
0.688912
829
5,844
4.494572
0.241255
0.05153
0.040258
0.020397
0.283682
0.165325
0.085883
0.052067
0.052067
0.028986
0
0.012059
0.219541
5,844
180
89
32.466667
0.804867
0.099418
0
0.080882
0
0
0.038059
0.015794
0
0
0
0
0.029412
1
0.058824
false
0
0.058824
0
0.169118
0.007353
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
71ae6ca7d57af38b1b86f8540325942204357879
1,767
py
Python
vagrant/kafka/bin/init.py
BertRaeymaekers/scrapbook
3c8483d4594356fbc84deb8d6496db3d856492c1
[ "MIT" ]
null
null
null
vagrant/kafka/bin/init.py
BertRaeymaekers/scrapbook
3c8483d4594356fbc84deb8d6496db3d856492c1
[ "MIT" ]
null
null
null
vagrant/kafka/bin/init.py
BertRaeymaekers/scrapbook
3c8483d4594356fbc84deb8d6496db3d856492c1
[ "MIT" ]
null
null
null
#! /usr/bin/env python3 import json import os.path import jinja2 DEFAULT_PARAMS = { "ansible_user": "vagrant" } if __name__ == "__main__": # Reading configuration here = os.path.dirname(os.path.realpath(__file__ + "/../")) with open(here + "/config.json", "r") as rf: config = json.load(rf) print(json.dumps(config, sort_keys=True, indent=4)) # Generating an inventory file with open(here + "/playbook/inventory/hosts", "w") as inventory: inventory.write("[kafka]\n") for host in config["hosts"]: # Setting default values and updating them when more specific. params = dict() params.update(DEFAULT_PARAMS) params.update(config["params"]) params.update(config["hosts"][host]) # Setting some extra ansible paramters. params["ansible_ssh_host"] = params["ip"] inventory.write("%s\t%s\n" % (host, " ".join(("%s=%s" % (k,v) for k,v in params.items())))) # Generating the Vagrantfile env = jinja2.Environment(loader=jinja2.FileSystemLoader(here + "/templates/")) template = env.get_template('Vagrantfile.j2') template.stream(**config).dump(here + '/vagrant/Vagrantfile') # Generating group vars for kafka with open(here + "/playbook/group_vars/kafka.yml", "w") as gv: gv.write("---\n") gv.write("hosts:\n") for (host, params) in config["hosts"].items(): gv.write(" %s: '%s.%s'\n" % (params["ip"], params["hostname"], config["params"]["domain" ])) gv.write("kafka:\n") gv.write(" hosts:\n") for (host, params) in config["hosts"].items(): gv.write(" - %s.%s\n" % (params["hostname"], config["params"]["domain" ]))
35.34
107
0.589134
217
1,767
4.705069
0.400922
0.041136
0.03526
0.031342
0.168462
0.105779
0.105779
0.105779
0.105779
0.105779
0
0.004428
0.233164
1,767
49
108
36.061224
0.749077
0.13073
0
0.125
0
0
0.206671
0.035971
0
0
0
0
0
1
0
false
0
0.09375
0
0.09375
0.03125
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
71aed94e4374b265d7146087fcd15cb6a8415441
883
py
Python
harvest/models/beastsimulator.py
lmaurits/harvest
df6b549096da8ae2f4ed38aa2be19c7e82fa60e3
[ "BSD-2-Clause" ]
1
2016-10-23T13:24:44.000Z
2016-10-23T13:24:44.000Z
harvest/models/beastsimulator.py
lmaurits/harvest
df6b549096da8ae2f4ed38aa2be19c7e82fa60e3
[ "BSD-2-Clause" ]
null
null
null
harvest/models/beastsimulator.py
lmaurits/harvest
df6b549096da8ae2f4ed38aa2be19c7e82fa60e3
[ "BSD-2-Clause" ]
null
null
null
import os import harvest.dataframe from harvest.models.simulator import Simulator class BeastSimulator(Simulator): def __init__(self, tree, n_features): Simulator.__init__(self, tree, n_features) def generate_beast_xml(self): # Subclasses should implement this return None def generate_data(self): # Generate BEAST XML file to do simulation xml = self.generate_beast_xml() temp_filename = xml.write_file(overwrite=True) # Run BEAST simulation os.system("beast %s > /dev/null" % temp_filename) # Delete BEAST XML file os.remove(temp_filename) # Read simulated data data = harvest.dataframe.read_from_beast_xml(xml.output_filename) # Delete simualted data os.remove(xml.output_filename) self.data = data self.data.datatype = self.datatype
30.448276
73
0.673839
108
883
5.287037
0.425926
0.070053
0.084063
0.045534
0.073555
0
0
0
0
0
0
0
0.251416
883
28
74
31.535714
0.863843
0.178935
0
0
0
0
0.027855
0
0
0
0
0
0
1
0.176471
false
0
0.176471
0.058824
0.470588
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
71af526fe8ec36b7ab5df62ce53a7484137b158f
770
py
Python
assimilator.py
DutChen18/slime-clusters-cuda
186d198665a017cf0eacde33765b6cb3cb4aecb5
[ "MIT" ]
null
null
null
assimilator.py
DutChen18/slime-clusters-cuda
186d198665a017cf0eacde33765b6cb3cb4aecb5
[ "MIT" ]
null
null
null
assimilator.py
DutChen18/slime-clusters-cuda
186d198665a017cf0eacde33765b6cb3cb4aecb5
[ "MIT" ]
null
null
null
# pylint: skip-file import os from assimilator import * from Boinc import boinc_project_path class SlimeClustersAssimilator(Assimilator): def __init__(self): Assimilator.__init__(self) def assimilate_handler(self, wu, results, canonical_result): if canonical_result == None: return src_file = self.get_file_path(canonical_result) dst_dir = boinc_project_path.project_path('slime-clusters') dst_file = os.path.join(dst_dir, 'results.txt') if not os.path.exists(dst_dir): os.makedirs(dst_dir) with open(src_file, 'r') as src, open(dst_file, 'a') as dst: dst.writelines(src.readlines()) if __name__ == "__main__": SlimeClustersAssimilator().run()
29.615385
68
0.661039
95
770
4.989474
0.473684
0.050633
0.067511
0
0
0
0
0
0
0
0
0
0.237662
770
26
69
29.615385
0.807496
0.022078
0
0
0
0
0.046543
0
0
0
0
0
0
1
0.111111
false
0
0.166667
0
0.388889
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
71af9d8ca1143528cfcbc75651debdacf07e53c4
12,343
py
Python
modin/core/execution/ray/implementations/cudf_on_ray/dataframe/dataframe.py
Rubtsowa/modin
6550939753c76e896ef2bfd65bb9468d6ad161d7
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
modin/core/execution/ray/implementations/cudf_on_ray/dataframe/dataframe.py
Rubtsowa/modin
6550939753c76e896ef2bfd65bb9468d6ad161d7
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
modin/core/execution/ray/implementations/cudf_on_ray/dataframe/dataframe.py
Rubtsowa/modin
6550939753c76e896ef2bfd65bb9468d6ad161d7
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
# Licensed to Modin Development Team under one or more contributor license agreements. # See the NOTICE file distributed with this work for additional information regarding # copyright ownership. The Modin Development Team licenses this file to you 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. """Module houses class that implements ``PandasOnRayDataframe`` class using cuDF.""" import numpy as np import ray from ..partitioning.partition import cuDFOnRayDataframePartition from ..partitioning.partition_manager import cuDFOnRayDataframePartitionManager from modin.core.execution.ray.implementations.pandas_on_ray.dataframe.dataframe import ( PandasOnRayDataframe, ) from modin.error_message import ErrorMessage class cuDFOnRayDataframe(PandasOnRayDataframe): """ The class implements the interface in ``PandasOnRayDataframe`` using cuDF. Parameters ---------- partitions : np.ndarray A 2D NumPy array of partitions. index : sequence The index for the dataframe. Converted to a ``pandas.Index``. columns : sequence The columns object for the dataframe. Converted to a ``pandas.Index``. row_lengths : list, optional The length of each partition in the rows. The "height" of each of the block partitions. Is computed if not provided. column_widths : list, optional The width of each partition in the columns. The "width" of each of the block partitions. Is computed if not provided. dtypes : pandas.Series, optional The data types for the dataframe columns. """ _partition_mgr_cls = cuDFOnRayDataframePartitionManager def synchronize_labels(self, axis=None): """ Synchronize labels by applying the index object (Index or Columns) to the partitions eagerly. Parameters ---------- axis : {0, 1, None}, default: None The axis to apply to. If None, it applies to both axes. """ ErrorMessage.catch_bugs_and_request_email( axis is not None and axis not in [0, 1] ) cum_row_lengths = np.cumsum([0] + self._row_lengths) cum_col_widths = np.cumsum([0] + self._column_widths) def apply_idx_objs(df, idx, cols, axis): # cudf does not support set_axis. It only supports rename with 1-to-1 mapping. # Therefore, we need to create the dictionary that have the relationship between # current index and new ones. idx = {df.index[i]: idx[i] for i in range(len(idx))} cols = {df.index[i]: cols[i] for i in range(len(cols))} if axis == 0: return df.rename(index=idx) elif axis == 1: return df.rename(columns=cols) else: return df.rename(index=idx, columns=cols) keys = np.array( [ [ self._partitions[i][j].apply( apply_idx_objs, idx=self.index[ slice(cum_row_lengths[i], cum_row_lengths[i + 1]) ], cols=self.columns[ slice(cum_col_widths[j], cum_col_widths[j + 1]) ], axis=axis, ) for j in range(len(self._partitions[i])) ] for i in range(len(self._partitions)) ] ) self._partitions = np.array( [ [ cuDFOnRayDataframePartition( self._partitions[i][j].get_gpu_manager(), keys[i][j], self._partitions[i][j]._length_cache, self._partitions[i][j]._width_cache, ) for j in range(len(keys[i])) ] for i in range(len(keys)) ] ) def mask( self, row_indices=None, row_numeric_idx=None, col_indices=None, col_numeric_idx=None, ): """ Lazily select columns or rows from given indices. Parameters ---------- row_indices : list of hashable, optional The row labels to extract. row_numeric_idx : list of int, optional The row indices to extract. col_indices : list of hashable, optional The column labels to extract. col_numeric_idx : list of int, optional The column indices to extract. Returns ------- cuDFOnRayDataframe A new ``cuDFOnRayDataframe`` from the mask provided. Notes ----- If both `row_indices` and `row_numeric_idx` are set, `row_indices` will be used. The same rule applied to `col_indices` and `col_numeric_idx`. """ if isinstance(row_numeric_idx, slice) and ( row_numeric_idx == slice(None) or row_numeric_idx == slice(0, None) ): row_numeric_idx = None if isinstance(col_numeric_idx, slice) and ( col_numeric_idx == slice(None) or col_numeric_idx == slice(0, None) ): col_numeric_idx = None if ( row_indices is None and row_numeric_idx is None and col_indices is None and col_numeric_idx is None ): return self.copy() if row_indices is not None: row_numeric_idx = self.index.get_indexer_for(row_indices) if row_numeric_idx is not None: row_partitions_list = self._get_dict_of_block_index(0, row_numeric_idx) if isinstance(row_numeric_idx, slice): # Row lengths for slice are calculated as the length of the slice # on the partition. Often this will be the same length as the current # length, but sometimes it is different, thus the extra calculation. new_row_lengths = [ len(range(*idx.indices(self._row_lengths[p]))) for p, idx in row_partitions_list.items() ] # Use the slice to calculate the new row index new_index = self.index[row_numeric_idx] else: new_row_lengths = [len(idx) for _, idx in row_partitions_list.items()] new_index = self.index[sorted(row_numeric_idx)] else: row_partitions_list = { i: slice(None) for i in range(len(self._row_lengths)) } new_row_lengths = self._row_lengths new_index = self.index if col_indices is not None: col_numeric_idx = self.columns.get_indexer_for(col_indices) if col_numeric_idx is not None: col_partitions_list = self._get_dict_of_block_index(1, col_numeric_idx) if isinstance(col_numeric_idx, slice): # Column widths for slice are calculated as the length of the slice # on the partition. Often this will be the same length as the current # length, but sometimes it is different, thus the extra calculation. new_col_widths = [ len(range(*idx.indices(self._column_widths[p]))) for p, idx in col_partitions_list.items() ] # Use the slice to calculate the new columns new_columns = self.columns[col_numeric_idx] assert sum(new_col_widths) == len( new_columns ), "{} != {}.\n{}\n{}\n{}".format( sum(new_col_widths), len(new_columns), col_numeric_idx, self._column_widths, col_partitions_list, ) if self._dtypes is not None: new_dtypes = self.dtypes[col_numeric_idx] else: new_dtypes = None else: new_col_widths = [len(idx) for _, idx in col_partitions_list.items()] new_columns = self.columns[sorted(col_numeric_idx)] if self._dtypes is not None: new_dtypes = self.dtypes.iloc[sorted(col_numeric_idx)] else: new_dtypes = None else: col_partitions_list = { i: slice(None) for i in range(len(self._column_widths)) } new_col_widths = self._column_widths new_columns = self.columns if self._dtypes is not None: new_dtypes = self.dtypes else: new_dtypes = None key_and_gpus = np.array( [ [ [ self._partitions[row_idx][col_idx].mask( row_internal_indices, col_internal_indices ), self._partitions[row_idx][col_idx].get_gpu_manager(), ] for col_idx, col_internal_indices in col_partitions_list.items() if isinstance(col_internal_indices, slice) or len(col_internal_indices) > 0 ] for row_idx, row_internal_indices in row_partitions_list.items() if isinstance(row_internal_indices, slice) or len(row_internal_indices) > 0 ] ) shape = key_and_gpus.shape[:2] keys = ray.get(key_and_gpus[:, :, 0].flatten().tolist()) gpu_managers = key_and_gpus[:, :, 1].flatten().tolist() new_partitions = self._partition_mgr_cls._create_partitions( keys, gpu_managers ).reshape(shape) intermediate = self.__constructor__( new_partitions, new_index, new_columns, new_row_lengths, new_col_widths, new_dtypes, ) # Check if monotonically increasing, return if it is. Fast track code path for # common case to keep it fast. if ( row_numeric_idx is None or isinstance(row_numeric_idx, slice) or len(row_numeric_idx) == 1 or np.all(row_numeric_idx[1:] >= row_numeric_idx[:-1]) ) and ( col_numeric_idx is None or isinstance(col_numeric_idx, slice) or len(col_numeric_idx) == 1 or np.all(col_numeric_idx[1:] >= col_numeric_idx[:-1]) ): return intermediate # The new labels are often smaller than the old labels, so we can't reuse the # original order values because those were mapped to the original data. We have # to reorder here based on the expected order from within the data. # We create a dictionary mapping the position of the numeric index with respect # to all others, then recreate that order by mapping the new order values from # the old. This information is sent to `_reorder_labels`. if row_numeric_idx is not None: row_order_mapping = dict( zip(sorted(row_numeric_idx), range(len(row_numeric_idx))) ) new_row_order = [row_order_mapping[idx] for idx in row_numeric_idx] else: new_row_order = None if col_numeric_idx is not None: col_order_mapping = dict( zip(sorted(col_numeric_idx), range(len(col_numeric_idx))) ) new_col_order = [col_order_mapping[idx] for idx in col_numeric_idx] else: new_col_order = None return intermediate._reorder_labels( row_numeric_idx=new_row_order, col_numeric_idx=new_col_order )
41.006645
101
0.573767
1,480
12,343
4.564865
0.184459
0.075488
0.051954
0.009769
0.367969
0.272647
0.181172
0.164002
0.103908
0.103908
0
0.004014
0.354047
12,343
300
102
41.143333
0.843346
0.291663
0
0.145729
0
0
0.002498
0
0
0
0
0
0.005025
1
0.015075
false
0
0.030151
0
0.085427
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
71afcdef0e0e86f29155c36a2d10beb1ffdab1ce
1,527
py
Python
Exoplanet_Population.py
mw5868/University
076c9b001dbfe3765607877be4f89ccf86a88331
[ "MIT" ]
null
null
null
Exoplanet_Population.py
mw5868/University
076c9b001dbfe3765607877be4f89ccf86a88331
[ "MIT" ]
null
null
null
Exoplanet_Population.py
mw5868/University
076c9b001dbfe3765607877be4f89ccf86a88331
[ "MIT" ]
null
null
null
from astropy.table import Table, Column import matplotlib.pyplot as plt #url = "https://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI?table=exoplanets&select=pl_hostname,ra,dec&order=dec&format=csv" url = "https://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI?table=exoplanets" # This API returns Hostname, RA and Dec t = Table.read(url, format="csv") t_b = t[t["pl_letter"] == "b"] t_c = t[t["pl_letter"] == "c"] t_d = t[t["pl_letter"] == "d"] t_e = t[t["pl_letter"] == "e"] t_f = t[t["pl_letter"] == "f"] t_g = t[t["pl_letter"] == "g"] t_h = t[t["pl_letter"] == "h"] t_i = t[t["pl_letter"] == "i"] fig = plt.figure() ax = fig.add_subplot(1,1,1,aspect="equal") ax.scatter(t_b["ra"],t_b["dec"],color="Black",label = "2 Planets") ax.scatter(t_c["ra"],t_c["dec"],color="red", label = "3 Planets") ax.scatter(t_d["ra"],t_d["dec"],color="blue", label = "4 Planets") ax.scatter(t_e["ra"],t_e["dec"],color="green", label = "5 Planets") ax.scatter(t_f["ra"],t_f["dec"],color="yellow", label = "6 Planets") ax.scatter(t_g["ra"],t_g["dec"],color="purple", label = "7 Planets") ax.scatter(t_h["ra"],t_h["dec"],color="orange", label = "8 Planets") ax.scatter(t_i["ra"],t_i["dec"],color="cyan", label = "9 Planets") ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) ax.set_xlim(360,0) ax.set_ylim(-90,90) ax.set_ylabel("DEC") ax.set_xlabel("RA") ax.set_title("Positions of Explanets by number of planets in system") plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.show()
42.416667
144
0.668631
287
1,527
3.407666
0.33101
0.01636
0.03272
0.0818
0.241309
0.241309
0.241309
0.241309
0.241309
0.241309
0
0.022302
0.089718
1,527
36
145
42.416667
0.681295
0.118533
0
0
0
0.033333
0.286245
0
0
0
0
0
0
1
0
false
0
0.066667
0
0.066667
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
71b199d12891c79153389fe28f6188e598ac7c21
792
py
Python
src/pe_problem74.py
henrimitte/Project-Euler
77fd9f5b076d1ca2e5ed4ef94bf8d32d9ed611eb
[ "MIT" ]
null
null
null
src/pe_problem74.py
henrimitte/Project-Euler
77fd9f5b076d1ca2e5ed4ef94bf8d32d9ed611eb
[ "MIT" ]
null
null
null
src/pe_problem74.py
henrimitte/Project-Euler
77fd9f5b076d1ca2e5ed4ef94bf8d32d9ed611eb
[ "MIT" ]
null
null
null
from tools import factorial def solve(): fa = tuple(factorial(x) for x in range(10)) def _sum_factorial_of_digits(n: int) -> int: s = 0 while n > 0: s += fa[n % 10] n //= 10 return s limit = 1000000 loops = [0 for x in range(limit)] for i in range(limit): if not loops[i]: loop_not_found = True chain = [i] n = i while loop_not_found: n = _sum_factorial_of_digits(n) if n in chain: loop_not_found = False else: chain.append(n) loops[i] = len(chain) sixty = sum(filter(lambda v: v == 60, loops)) // 60 print(sixty) if __name__ == '__main__': solve()
22.628571
55
0.474747
103
792
3.436893
0.427184
0.059322
0.101695
0.062147
0.118644
0
0
0
0
0
0
0.043956
0.425505
792
34
56
23.294118
0.734066
0
0
0
0
0
0.010101
0
0
0
0
0
0
1
0.074074
false
0
0.037037
0
0.148148
0.037037
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
71b28ef18b75d4bcb886bea855f0ba76dd2bc9f2
27,966
py
Python
thingsboard_gateway/connectors/modbus/modbus_connector.py
ferguscan/thingsboard-gateway
bc20fdb8e46f840b8538a010db2714ec6071fa5b
[ "Apache-2.0" ]
null
null
null
thingsboard_gateway/connectors/modbus/modbus_connector.py
ferguscan/thingsboard-gateway
bc20fdb8e46f840b8538a010db2714ec6071fa5b
[ "Apache-2.0" ]
null
null
null
thingsboard_gateway/connectors/modbus/modbus_connector.py
ferguscan/thingsboard-gateway
bc20fdb8e46f840b8538a010db2714ec6071fa5b
[ "Apache-2.0" ]
null
null
null
# Copyright 2022. ThingsBoard # # 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 threading import Thread from time import sleep, time from queue import Queue from random import choice from string import ascii_lowercase from thingsboard_gateway.tb_utility.tb_utility import TBUtility # Try import Pymodbus library or install it and import try: from pymodbus.constants import Defaults except ImportError: print("Modbus library not found - installing...") TBUtility.install_package("pymodbus", ">=2.3.0") TBUtility.install_package('pyserial') from pymodbus.constants import Defaults try: from twisted.internet import reactor except ImportError: TBUtility.install_package('twisted') from twisted.internet import reactor from twisted.internet import reactor from pymodbus.bit_write_message import WriteSingleCoilResponse, WriteMultipleCoilsResponse from pymodbus.register_write_message import WriteMultipleRegistersResponse, WriteSingleRegisterResponse from pymodbus.register_read_message import ReadRegistersResponseBase from pymodbus.bit_read_message import ReadBitsResponseBase from pymodbus.client.sync import ModbusTcpClient, ModbusUdpClient, ModbusSerialClient from pymodbus.client.sync import ModbusRtuFramer, ModbusSocketFramer, ModbusAsciiFramer from pymodbus.exceptions import ConnectionException from pymodbus.server.asynchronous import StartTcpServer, StartUdpServer, StartSerialServer, StopServer from pymodbus.device import ModbusDeviceIdentification from pymodbus.version import version from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext from pymodbus.datastore import ModbusSparseDataBlock from thingsboard_gateway.connectors.connector import Connector, log from thingsboard_gateway.connectors.modbus.constants import * from thingsboard_gateway.connectors.modbus.slave import Slave from thingsboard_gateway.connectors.modbus.backward_compability_adapter import BackwardCompatibilityAdapter from thingsboard_gateway.connectors.modbus.bytes_modbus_downlink_converter import BytesModbusDownlinkConverter CONVERTED_DATA_SECTIONS = [ATTRIBUTES_PARAMETER, TELEMETRY_PARAMETER] FRAMER_TYPE = { 'rtu': ModbusRtuFramer, 'socket': ModbusSocketFramer, 'ascii': ModbusAsciiFramer } SLAVE_TYPE = { 'tcp': StartTcpServer, 'udp': StartUdpServer, 'serial': StartSerialServer } FUNCTION_TYPE = { 'coils_initializer': 'co', 'holding_registers': 'hr', 'input_registers': 'ir', 'discrete_inputs': 'di' } FUNCTION_CODE_WRITE = { 'holding_registers': (6, 16), 'coils_initializer': (5, 15) } FUNCTION_CODE_READ = { 'holding_registers': 3, 'coils_initializer': 1, 'input_registers': 4, 'discrete_inputs': 2 } class ModbusConnector(Connector, Thread): process_requests = Queue(-1) def __init__(self, gateway, config, connector_type): self.statistics = {STATISTIC_MESSAGE_RECEIVED_PARAMETER: 0, STATISTIC_MESSAGE_SENT_PARAMETER: 0} super().__init__() self.__gateway = gateway self._connector_type = connector_type self.__backward_compatibility_adapter = BackwardCompatibilityAdapter(config, gateway.get_config_path()) self.__config = self.__backward_compatibility_adapter.convert() self.setName(self.__config.get("name", 'Modbus Default ' + ''.join(choice(ascii_lowercase) for _ in range(5)))) self.__connected = False self.__stopped = False self.daemon = True if self.__config.get('slave'): self.__slave_thread = Thread(target=self.__configure_and_run_slave, args=(self.__config['slave'],), daemon=True, name='Gateway as a slave') self.__slave_thread.start() if config['slave'].get('sendDataToThingsBoard', False): self.__modify_main_config() self.__slaves = [] self.__load_slaves() def is_connected(self): return self.__connected def open(self): self.__stopped = False self.start() def run(self): self.__connected = True while True: if not self.__stopped and not ModbusConnector.process_requests.empty(): thread = Thread(target=self.__process_slaves, daemon=True) thread.start() if self.__stopped: break sleep(.2) @staticmethod def __configure_and_run_slave(config): identity = None if config.get('identity'): identity = ModbusDeviceIdentification() identity.VendorName = config['identity'].get('vendorName', '') identity.ProductCode = config['identity'].get('productCode', '') identity.VendorUrl = config['identity'].get('vendorUrl', '') identity.ProductName = config['identity'].get('productName', '') identity.ModelName = config['identity'].get('ModelName', '') identity.MajorMinorRevision = version.short() blocks = {} for (key, value) in config.get('values').items(): values = {} converter = BytesModbusDownlinkConverter({}) for item in value: for section in ('attributes', 'timeseries', 'attributeUpdates', 'rpc'): for val in item.get(section, []): function_code = FUNCTION_CODE_WRITE[key][0] if val['objectsCount'] <= 1 else \ FUNCTION_CODE_WRITE[key][1] converted_value = converter.convert( {**val, 'device': config.get('deviceName', 'Gateway'), 'functionCode': function_code, 'byteOrder': config['byteOrder'], 'wordOrder': config['wordOrder']}, {'data': {'params': val['value']}}) values[val['address'] + 1] = converted_value blocks[FUNCTION_TYPE[key]] = ModbusSparseDataBlock(values) context = ModbusServerContext(slaves=ModbusSlaveContext(**blocks), single=True) SLAVE_TYPE[config['type']](context, identity=identity, address=(config.get('host'), config.get('port')) if ( config['type'] == 'tcp' or 'udp') else None, port=config.get('port') if config['type'] == 'serial' else None, framer=FRAMER_TYPE[config['method']]) def __modify_main_config(self): config = self.__config['slave'] values = config.pop('values') device = config for (register, reg_values) in values.items(): for value in reg_values: for section in ('attributes', 'timeseries', 'attributeUpdates', 'rpc'): if not device.get(section): device[section] = [] for item in value.get(section, []): device[section].append({**item, 'functionCode': FUNCTION_CODE_READ[ register] if section not in ('attributeUpdates', 'rpc') else item['functionCode']}) self.__config['master']['slaves'].append(device) def __load_slaves(self): self.__slaves = [ Slave(**{**device, 'connector': self, 'gateway': self.__gateway, 'callback': ModbusConnector.callback}) for device in self.__config.get('master', {'slaves': []}).get('slaves', [])] @classmethod def callback(cls, slave): cls.process_requests.put(slave) @property def connector_type(self): return self._connector_type def __convert_and_save_data(self, config_tuple): device, current_device_config, config, device_responses = config_tuple converted_data = {} try: converted_data = device.config[UPLINK_PREFIX + CONVERTER_PARAMETER].convert( config=config, data=device_responses) except Exception as e: log.error(e) to_send = {DEVICE_NAME_PARAMETER: converted_data[DEVICE_NAME_PARAMETER], DEVICE_TYPE_PARAMETER: converted_data[DEVICE_TYPE_PARAMETER], TELEMETRY_PARAMETER: [], ATTRIBUTES_PARAMETER: [] } if current_device_config.get('sendDataOnlyOnChange'): self.statistics[STATISTIC_MESSAGE_RECEIVED_PARAMETER] += 1 for converted_data_section in CONVERTED_DATA_SECTIONS: for current_section_dict in converted_data[converted_data_section]: for key, value in current_section_dict.items(): if device.config[LAST_PREFIX + converted_data_section].get(key) is None or \ device.config[LAST_PREFIX + converted_data_section][key] != value: device.config[LAST_PREFIX + converted_data_section][key] = value to_send[converted_data_section].append({key: value}) elif converted_data and current_device_config.get('sendDataOnlyOnChange') is None or \ not current_device_config.get('sendDataOnlyOnChange'): self.statistics[STATISTIC_MESSAGE_RECEIVED_PARAMETER] += 1 for converted_data_section in CONVERTED_DATA_SECTIONS: device.config[LAST_PREFIX + converted_data_section] = converted_data[ converted_data_section] to_send[converted_data_section] = converted_data[converted_data_section] if to_send.get(ATTRIBUTES_PARAMETER) or to_send.get(TELEMETRY_PARAMETER): self.__gateway.send_to_storage(self.get_name(), to_send) self.statistics[STATISTIC_MESSAGE_SENT_PARAMETER] += 1 def close(self): self.__stopped = True self.__stop_connections_to_masters() if reactor.running: StopServer() log.info('%s has been stopped.', self.get_name()) def get_name(self): return self.name def __process_slaves(self): # TODO: write documentation device = ModbusConnector.process_requests.get() device_responses = {'timeseries': {}, 'attributes': {}} current_device_config = {} try: for config_section in device_responses: if device.config.get(config_section) is not None: current_device_config = device.config self.__connect_to_current_master(device) if not device.config['master'].is_socket_open() or not len( current_device_config[config_section]): continue # Reading data from device for interested_data in range(len(current_device_config[config_section])): current_data = current_device_config[config_section][interested_data] current_data[DEVICE_NAME_PARAMETER] = device input_data = self.__function_to_device(device, current_data) device_responses[config_section][current_data[TAG_PARAMETER]] = { "data_sent": current_data, "input_data": input_data} log.debug("Checking %s for device %s", config_section, device) log.debug('Device response: ', device_responses) if device_responses.get('timeseries') or device_responses.get('attributes'): self.__convert_and_save_data((device, current_device_config, { **current_device_config, BYTE_ORDER_PARAMETER: current_device_config.get(BYTE_ORDER_PARAMETER, device.byte_order), WORD_ORDER_PARAMETER: current_device_config.get(WORD_ORDER_PARAMETER, device.word_order) }, device_responses)) except ConnectionException: sleep(5) log.error("Connection lost! Reconnecting...") except Exception as e: log.exception(e) def __connect_to_current_master(self, device=None): # TODO: write documentation connect_attempt_count = 5 connect_attempt_time_ms = 100 wait_after_failed_attempts_ms = 300000 if device.config.get('master') is None: device.config['master'], device.config['available_functions'] = self.__configure_master(device.config) if connect_attempt_count < 1: connect_attempt_count = 1 connect_attempt_time_ms = device.config.get('connectAttemptTimeMs', connect_attempt_time_ms) if connect_attempt_time_ms < 500: connect_attempt_time_ms = 500 wait_after_failed_attempts_ms = device.config.get('waitAfterFailedAttemptsMs', wait_after_failed_attempts_ms) if wait_after_failed_attempts_ms < 1000: wait_after_failed_attempts_ms = 1000 current_time = time() * 1000 if not device.config['master'].is_socket_open(): if device.config['connection_attempt'] >= connect_attempt_count and current_time - device.config[ 'last_connection_attempt_time'] >= wait_after_failed_attempts_ms: device.config['connection_attempt'] = 0 while not device.config['master'].is_socket_open() \ and device.config['connection_attempt'] < connect_attempt_count \ and current_time - device.config.get('last_connection_attempt_time', 0) >= connect_attempt_time_ms: device.config['connection_attempt'] = device.config[ 'connection_attempt'] + 1 device.config['last_connection_attempt_time'] = current_time log.debug("Modbus trying connect to %s", device) device.config['master'].connect() if device.config['connection_attempt'] == connect_attempt_count: log.warn("Maximum attempt count (%i) for device \"%s\" - encountered.", connect_attempt_count, device) if device.config['connection_attempt'] >= 0 and device.config['master'].is_socket_open(): device.config['connection_attempt'] = 0 device.config['last_connection_attempt_time'] = current_time @staticmethod def __configure_master(config): current_config = config current_config["rtu"] = FRAMER_TYPE[current_config['method']] if current_config.get('type') == 'tcp': master = ModbusTcpClient(current_config["host"], current_config["port"], current_config["rtu"], timeout=current_config["timeout"], retry_on_empty=current_config["retry_on_empty"], retry_on_invalid=current_config["retry_on_invalid"], retries=current_config["retries"]) elif current_config.get(TYPE_PARAMETER) == 'udp': master = ModbusUdpClient(current_config["host"], current_config["port"], current_config["rtu"], timeout=current_config["timeout"], retry_on_empty=current_config["retry_on_empty"], retry_on_invalid=current_config["retry_on_invalid"], retries=current_config["retries"]) elif current_config.get(TYPE_PARAMETER) == 'serial': master = ModbusSerialClient(method=current_config["method"], port=current_config["port"], timeout=current_config["timeout"], retry_on_empty=current_config["retry_on_empty"], retry_on_invalid=current_config["retry_on_invalid"], retries=current_config["retries"], baudrate=current_config["baudrate"], stopbits=current_config["stopbits"], bytesize=current_config["bytesize"], parity=current_config["parity"], strict=current_config["strict"]) else: raise Exception("Invalid Modbus transport type.") available_functions = { 1: master.read_coils, 2: master.read_discrete_inputs, 3: master.read_holding_registers, 4: master.read_input_registers, 5: master.write_coil, 6: master.write_register, 15: master.write_coils, 16: master.write_registers, } return master, available_functions def __stop_connections_to_masters(self): for slave in self.__slaves: if slave.config.get('master') is not None and slave.config.get('master').is_socket_open(): slave.config['master'].close() @staticmethod def __function_to_device(device, config): function_code = config.get('functionCode') result = None if function_code == 1: result = device.config['available_functions'][function_code](address=config[ADDRESS_PARAMETER], count=config.get(OBJECTS_COUNT_PARAMETER, config.get("registersCount", config.get( "registerCount", 1))) * 8, unit=device.config['unitId']) elif function_code in (2, 3, 4): result = device.config['available_functions'][function_code](address=config[ADDRESS_PARAMETER], count=config.get(OBJECTS_COUNT_PARAMETER, config.get("registersCount", config.get( "registerCount", 1))), unit=device.config['unitId']) elif function_code in (5, 15): result = device.config['available_functions'][function_code](address=config[ADDRESS_PARAMETER], value=config[PAYLOAD_PARAMETER], unit=device.config['unitId'] * 8) elif function_code in (6, 16): result = device.config['available_functions'][function_code](address=config[ADDRESS_PARAMETER], values=config[PAYLOAD_PARAMETER], unit=device.config['unitId']) else: log.error("Unknown Modbus function with code: %s", function_code) log.debug("With result %s", str(result)) if "Exception" in str(result): log.exception(result) return result def on_attributes_update(self, content): try: device = tuple(filter(lambda slave: slave.name == content[DEVICE_SECTION_PARAMETER], self.__slaves))[0] for attribute_updates_command_config in device.config['attributeUpdates']: for attribute_updated in content[DATA_PARAMETER]: if attribute_updates_command_config[TAG_PARAMETER] == attribute_updated: to_process = { DEVICE_SECTION_PARAMETER: content[DEVICE_SECTION_PARAMETER], DATA_PARAMETER: { RPC_METHOD_PARAMETER: attribute_updated, RPC_PARAMS_PARAMETER: content[DATA_PARAMETER][attribute_updated] } } attribute_updates_command_config['byteOrder'] = device.byte_order or 'LITTLE' attribute_updates_command_config['wordOrder'] = device.word_order or 'LITTLE' self.__process_request(to_process, attribute_updates_command_config, request_type='attributeUpdates') except Exception as e: log.exception(e) def server_side_rpc_handler(self, server_rpc_request): try: if server_rpc_request.get(DEVICE_SECTION_PARAMETER) is not None: log.debug("Modbus connector received rpc request for %s with server_rpc_request: %s", server_rpc_request[DEVICE_SECTION_PARAMETER], server_rpc_request) device = tuple( filter( lambda slave: slave.name == server_rpc_request[DEVICE_SECTION_PARAMETER], self.__slaves ) )[0] if isinstance(device.config[RPC_SECTION], dict): rpc_command_config = device.config[RPC_SECTION].get( server_rpc_request[DATA_PARAMETER][RPC_METHOD_PARAMETER]) if rpc_command_config is not None: self.__process_request(server_rpc_request, rpc_command_config) elif isinstance(device.config[RPC_SECTION], list): for rpc_command_config in device.config[RPC_SECTION]: if rpc_command_config[TAG_PARAMETER] == server_rpc_request[DATA_PARAMETER][ RPC_METHOD_PARAMETER]: self.__process_request(server_rpc_request, rpc_command_config) break else: log.error("Received rpc request, but method %s not found in config for %s.", server_rpc_request[DATA_PARAMETER].get(RPC_METHOD_PARAMETER), self.get_name()) self.__gateway.send_rpc_reply(server_rpc_request[DEVICE_SECTION_PARAMETER], server_rpc_request[DATA_PARAMETER][RPC_ID_PARAMETER], {server_rpc_request[DATA_PARAMETER][ RPC_METHOD_PARAMETER]: "METHOD NOT FOUND!"}) else: log.debug("Received RPC to connector: %r", server_rpc_request) except Exception as e: log.exception(e) def __process_request(self, content, rpc_command_config, request_type='RPC'): log.debug('Processing %s request', request_type) if rpc_command_config is not None: device = tuple(filter(lambda slave: slave.name == content[DEVICE_SECTION_PARAMETER], self.__slaves))[0] rpc_command_config[UNIT_ID_PARAMETER] = device.config['unitId'] rpc_command_config[BYTE_ORDER_PARAMETER] = device.config.get("byteOrder", "LITTLE") rpc_command_config[WORD_ORDER_PARAMETER] = device.config.get("wordOrder", "LITTLE") self.__connect_to_current_master(device) if rpc_command_config.get(FUNCTION_CODE_PARAMETER) in (6, 16): converted_data = device.config[DOWNLINK_PREFIX + CONVERTER_PARAMETER].convert(rpc_command_config, content) try: rpc_command_config[PAYLOAD_PARAMETER] = converted_data[0] except IndexError and TypeError: rpc_command_config[PAYLOAD_PARAMETER] = converted_data elif rpc_command_config.get(FUNCTION_CODE_PARAMETER) in (5, 15): converted_data = device.config[DOWNLINK_PREFIX + CONVERTER_PARAMETER].convert(rpc_command_config, content) rpc_command_config[PAYLOAD_PARAMETER] = converted_data try: response = self.__function_to_device(device, rpc_command_config) except Exception as e: log.exception(e) response = e if isinstance(response, (ReadRegistersResponseBase, ReadBitsResponseBase)): to_converter = { RPC_SECTION: {content[DATA_PARAMETER][RPC_METHOD_PARAMETER]: {"data_sent": rpc_command_config, "input_data": response}}} response = device.config[ UPLINK_PREFIX + CONVERTER_PARAMETER].convert( config={**device.config, BYTE_ORDER_PARAMETER: device.byte_order, WORD_ORDER_PARAMETER: device.word_order }, data=to_converter) log.debug("Received %s method: %s, result: %r", request_type, content[DATA_PARAMETER][RPC_METHOD_PARAMETER], response) elif isinstance(response, (WriteMultipleRegistersResponse, WriteMultipleCoilsResponse, WriteSingleCoilResponse, WriteSingleRegisterResponse)): log.debug("Write %r", str(response)) response = {"success": True} if content.get(RPC_ID_PARAMETER) or ( content.get(DATA_PARAMETER) is not None and content[DATA_PARAMETER].get(RPC_ID_PARAMETER)): if isinstance(response, Exception): self.__gateway.send_rpc_reply(content[DEVICE_SECTION_PARAMETER], content[DATA_PARAMETER][RPC_ID_PARAMETER], {content[DATA_PARAMETER][RPC_METHOD_PARAMETER]: str(response)}) else: self.__gateway.send_rpc_reply(content[DEVICE_SECTION_PARAMETER], content[DATA_PARAMETER][RPC_ID_PARAMETER], response) log.debug("%r", response)
50.389189
121
0.567582
2,584
27,966
5.833978
0.140867
0.052537
0.021227
0.01539
0.381957
0.307927
0.2601
0.213665
0.164113
0.129486
0
0.005671
0.350569
27,966
554
122
50.480144
0.824359
0.025567
0
0.210989
0
0
0.084616
0.005803
0
0
0
0.001805
0
1
0.043956
false
0
0.065934
0.006593
0.125275
0.002198
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
71b2acdd2d92ff5dd5a3e30aa5f776064be270a0
966
py
Python
specs/test_gru_on_flat_babyai.py
xwu20/wmg_agent
25378c8fc54eb6e0e8c9d969760a72e843572f09
[ "MIT" ]
23
2020-07-08T15:58:51.000Z
2022-01-13T04:22:03.000Z
specs/test_gru_on_flat_babyai.py
xwu20/wmg_agent
25378c8fc54eb6e0e8c9d969760a72e843572f09
[ "MIT" ]
3
2021-06-08T21:58:37.000Z
2022-01-13T03:00:32.000Z
specs/test_gru_on_flat_babyai.py
xwu20/wmg_agent
25378c8fc54eb6e0e8c9d969760a72e843572f09
[ "MIT" ]
11
2020-07-31T11:13:29.000Z
2021-11-10T08:37:12.000Z
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. ### CONTROLS (non-tunable) ### # general TYPE_OF_RUN = test_episodes # train, test, test_episodes, render NUM_EPISODES_TO_TEST = 1000 MIN_FINAL_REWARD_FOR_SUCCESS = 1.0 LOAD_MODEL_FROM = models/gru_flat_babyai.pth SAVE_MODELS_TO = None # worker.py ENV = BabyAI_Env ENV_RANDOM_SEED = 1 AGENT_RANDOM_SEED = 1 REPORTING_INTERVAL = 1 TOTAL_STEPS = 1 ANNEAL_LR = False # A3cAgent AGENT_NET = GRU_Network # BabyAI_Env BABYAI_ENV_LEVEL = BabyAI-GoToLocal-v0 USE_SUCCESS_RATE = True SUCCESS_RATE_THRESHOLD = 0.99 HELDOUT_TESTING = False NUM_TEST_EPISODES = 10000 OBS_ENCODER = Flat BINARY_REWARD = True ### HYPERPARAMETERS (tunable) ### # A3cAgent A3C_T_MAX = 4 LEARNING_RATE = 4e-05 DISCOUNT_FACTOR = 0.9 GRADIENT_CLIP = 512.0 ENTROPY_TERM_STRENGTH = 0.02 ADAM_EPS = 1e-12 REWARD_SCALE = 2.0 WEIGHT_DECAY = 0. # RNNs NUM_RNN_UNITS = 96 OBS_EMBED_SIZE = 512 AC_HIDDEN_LAYER_SIZE = 4096
19.714286
65
0.774327
153
966
4.522876
0.69281
0.052023
0.034682
0
0
0
0
0
0
0
0
0.060606
0.145963
966
48
66
20.125
0.778182
0.219462
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
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
71b31d76fcd9783bbf00ab94b135126e5908e931
3,474
bzl
Python
haskell/private/actions/runghc.bzl
meisterT/rules_haskell
7c0a867fc23da104ea8cbff26864894abcf137bc
[ "Apache-2.0" ]
null
null
null
haskell/private/actions/runghc.bzl
meisterT/rules_haskell
7c0a867fc23da104ea8cbff26864894abcf137bc
[ "Apache-2.0" ]
null
null
null
haskell/private/actions/runghc.bzl
meisterT/rules_haskell
7c0a867fc23da104ea8cbff26864894abcf137bc
[ "Apache-2.0" ]
null
null
null
"""runghc support""" load(":private/context.bzl", "render_env") load(":private/packages.bzl", "expose_packages", "pkg_info_to_compile_flags") load( ":private/path_utils.bzl", "link_libraries", "ln", "target_unique_name", ) load( ":private/set.bzl", "set", ) load(":providers.bzl", "get_ghci_extra_libs") load("@bazel_skylib//lib:shell.bzl", "shell") def build_haskell_runghc( hs, runghc_wrapper, user_compile_flags, extra_args, hs_info, cc_info, output, package_databases, version, lib_info = None): """Build runghc script. Args: hs: Haskell context. hs_info: HaskellInfo. package_databases: package caches excluding the cache file of the package we're creating a runghc for. lib_info: If we're building runghc for a library target, pass HaskellLibraryInfo here, otherwise it should be None. Returns: None. """ (pkg_info_inputs, args) = pkg_info_to_compile_flags( hs, pkg_info = expose_packages( package_ids = hs.package_ids, package_databases = package_databases, version = version, ), prefix = "runghc-", ) if lib_info != None: for idir in set.to_list(hs_info.import_dirs): args += ["-i{0}".format(idir)] (ghci_extra_libs, ghc_env) = get_ghci_extra_libs( hs, cc_info, path_prefix = "$RULES_HASKELL_EXEC_ROOT", ) link_libraries(ghci_extra_libs, args) runghc_file = hs.actions.declare_file(target_unique_name(hs, "runghc")) # Extra arguments. # `compiler flags` is the default set of arguments for runghc, # augmented by `extra_args`. # The ordering is important, first compiler flags (from toolchain # and local rule), then from `extra_args`. This way the more # specific arguments are listed last, and then have more priority in # GHC. # Note that most flags for GHCI do have their negative value, so a # negative flag in `extra_args` can disable a positive flag set # in `user_compile_flags`, such as `-XNoOverloadedStrings` will disable # `-XOverloadedStrings`. args += hs.toolchain.compiler_flags + user_compile_flags + hs.toolchain.repl_ghci_args # ghc args need to be wrapped up in "--ghc-arg=" when passing to runghc runcompile_flags = ["--ghc-arg=%s" % a for a in args] runcompile_flags += extra_args hs.actions.expand_template( template = runghc_wrapper, output = runghc_file, substitutions = { "{ENV}": render_env(ghc_env), "{TOOL}": hs.tools.runghc.path, "{CC}": hs.toolchain.cc_wrapper.executable.path, "{ARGS}": " ".join([shell.quote(a) for a in runcompile_flags]), }, is_executable = True, ) # XXX We create a symlink here because we need to force # hs.tools.runghc and the best way to do that is # to use hs.actions.run. That action, in turn must produce # a result, so using ln seems to be the only sane choice. extra_inputs = depset(transitive = [ depset([ hs.tools.runghc, runghc_file, ]), package_databases, pkg_info_inputs, ghci_extra_libs, hs_info.source_files, hs.toolchain.cc_wrapper.runfiles.files, ]) ln(hs, runghc_file, output, extra_inputs)
31.017857
90
0.627231
445
3,474
4.685393
0.379775
0.016787
0.031175
0.015348
0.020144
0
0
0
0
0
0
0.000396
0.272309
3,474
111
91
31.297297
0.824367
0.335636
0
0.128571
0
0
0.137885
0.053994
0
0
0
0
0
1
0.014286
false
0
0.014286
0
0.028571
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
71b4b6265ccad83e3c8c7743ef9150f9f16b46b0
8,456
py
Python
tests/dicom/test_header_tweaks.py
pymedphys/pymedphys-archive-2019
6bb7c8d0da2e93ff56469bb47e65b15ece2ea25e
[ "Apache-2.0" ]
1
2020-12-20T14:13:56.000Z
2020-12-20T14:13:56.000Z
tests/dicom/test_header_tweaks.py
pymedphys/pymedphys-archive-2019
6bb7c8d0da2e93ff56469bb47e65b15ece2ea25e
[ "Apache-2.0" ]
6
2020-10-06T15:36:46.000Z
2022-02-27T05:15:17.000Z
tests/dicom/test_header_tweaks.py
cpbhatt/pymedphys
177b3db8e2a6e83c44835d0007d1d5c7a420fd99
[ "Apache-2.0" ]
1
2020-12-20T14:14:00.000Z
2020-12-20T14:14:00.000Z
# Copyright (C) 2019 Cancer Care Associates # 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 os import subprocess import uuid import numpy as np import pydicom from pymedphys._dicom.create import dicom_dataset_from_dict from pymedphys._dicom.header import ( RED_adjustment_map_from_structure_names, adjust_machine_name, adjust_RED_by_structure_name, adjust_rel_elec_density, ) from pymedphys._dicom.utilities import remove_file HERE = os.path.dirname(__file__) ORIGINAL_DICOM_FILENAME = os.path.join( HERE, "scratch", "original-{}.dcm".format(str(uuid.uuid4())) ) ADJUSTED_DICOM_FILENAME = os.path.join( HERE, "scratch", "adjusted-{}.dcm".format(str(uuid.uuid4())) ) def compare_dicom_cli(command, original, expected): pydicom.write_file(ORIGINAL_DICOM_FILENAME, original) try: subprocess.check_call(command) cli_adjusted_ds = pydicom.read_file(ADJUSTED_DICOM_FILENAME, force=True) assert str(cli_adjusted_ds) == str(expected) finally: remove_file(ORIGINAL_DICOM_FILENAME) remove_file(ADJUSTED_DICOM_FILENAME) def test_adjust_machine_name(): new_name = "new_name" original_ds = dicom_dataset_from_dict( { "BeamSequence": [ {"TreatmentMachineName": "hello"}, {"TreatmentMachineName": "george"}, ] } ) expected_ds = dicom_dataset_from_dict( { "BeamSequence": [ {"TreatmentMachineName": new_name}, {"TreatmentMachineName": new_name}, ] } ) adjusted_ds = adjust_machine_name(original_ds, new_name) assert adjusted_ds != original_ds assert adjusted_ds == expected_ds command = "pymedphys dicom adjust-machine-name".split() + [ ORIGINAL_DICOM_FILENAME, ADJUSTED_DICOM_FILENAME, new_name, ] compare_dicom_cli(command, original_ds, expected_ds) def test_electron_density_append(): adjustment_map = { "to_be_changed 1": 1.0, "to_be_changed 2": 0.5, "to_be_changed 3": 1.5, } excess_adjustment_map = {**adjustment_map, **{"this_structure_doesnt_exist": 1.0}} original_ds = dicom_dataset_from_dict( { "StructureSetROISequence": [ {"ROINumber": 1, "ROIName": "to_be_changed 1"}, {"ROINumber": 2, "ROIName": "dont_change_me"}, {"ROINumber": 10, "ROIName": "to_be_changed 2"}, {"ROINumber": 99, "ROIName": "to_be_changed 3"}, ], "RTROIObservationsSequence": [ { "ReferencedROINumber": 1, "ROIPhysicalPropertiesSequence": [ { "ROIPhysicalProperty": "EFFECTIVE_Z", "ROIPhysicalPropertyValue": 6, } ], }, {"ReferencedROINumber": 2}, {"ReferencedROINumber": 10}, { "ReferencedROINumber": 99, "ROIPhysicalPropertiesSequence": [ { "ROIPhysicalProperty": "REL_ELEC_DENSITY", "ROIPhysicalPropertyValue": 0, } ], }, ], } ) expected_ds = dicom_dataset_from_dict( { "RTROIObservationsSequence": [ { "ReferencedROINumber": 1, "ROIPhysicalPropertiesSequence": [ { "ROIPhysicalProperty": "EFFECTIVE_Z", "ROIPhysicalPropertyValue": 6, }, { "ROIPhysicalProperty": "REL_ELEC_DENSITY", "ROIPhysicalPropertyValue": adjustment_map[ "to_be_changed 1" ], }, ], }, {"ReferencedROINumber": 2}, { "ReferencedROINumber": 10, "ROIPhysicalPropertiesSequence": [ { "ROIPhysicalProperty": "REL_ELEC_DENSITY", "ROIPhysicalPropertyValue": adjustment_map[ "to_be_changed 2" ], } ], }, { "ReferencedROINumber": 99, "ROIPhysicalPropertiesSequence": [ { "ROIPhysicalProperty": "REL_ELEC_DENSITY", "ROIPhysicalPropertyValue": adjustment_map[ "to_be_changed 3" ], } ], }, ] }, template_ds=original_ds, ) adjusted_ds = adjust_rel_elec_density(original_ds, adjustment_map) assert adjusted_ds != original_ds assert str(expected_ds) == str(adjusted_ds) adjusted_with_excess_ds = adjust_rel_elec_density( original_ds, excess_adjustment_map, ignore_missing_structure=True ) assert adjusted_with_excess_ds != original_ds assert str(expected_ds) == str(adjusted_with_excess_ds) excess_adjustment_map_as_list = [ ["{}".format(key), item] for key, item in excess_adjustment_map.items() ] excess_adjustment_map_flat = np.concatenate(excess_adjustment_map_as_list).tolist() command = ( "pymedphys dicom adjust-RED -i ".split() + [ORIGINAL_DICOM_FILENAME, ADJUSTED_DICOM_FILENAME] + excess_adjustment_map_flat ) compare_dicom_cli(command, original_ds, expected_ds) def test_structure_name_parse(): structure_names = [ "a RED=1", "b", "c", "d RED=2.2", "e red = 3", "f", "g Red: 4.7", "h RED=0.5 ", ] expected_adjustment_map = { "a RED=1": 1, "d RED=2.2": 2.2, "e red = 3": 3, "g Red: 4.7": 4.7, "h RED=0.5 ": 0.5, } adjustment_map = RED_adjustment_map_from_structure_names(structure_names) assert expected_adjustment_map == adjustment_map def test_structure_name_based_RED_append(): electron_density_to_use = 0.5 original_ds = dicom_dataset_from_dict( { "StructureSetROISequence": [ { "ROINumber": 1, "ROIName": "a_structure RED={}".format(electron_density_to_use), }, {"ROINumber": 2, "ROIName": "dont_change_me"}, ], "RTROIObservationsSequence": [ {"ReferencedROINumber": 1}, {"ReferencedROINumber": 2}, ], } ) expected_ds = dicom_dataset_from_dict( { "RTROIObservationsSequence": [ { "ReferencedROINumber": 1, "ROIPhysicalPropertiesSequence": [ { "ROIPhysicalProperty": "REL_ELEC_DENSITY", "ROIPhysicalPropertyValue": electron_density_to_use, } ], }, {"ReferencedROINumber": 2}, ] }, template_ds=original_ds, ) adjusted_ds = adjust_RED_by_structure_name(original_ds) assert adjusted_ds != original_ds assert str(expected_ds) == str(adjusted_ds) command = "pymedphys dicom adjust-RED-by-structure-name".split() + [ ORIGINAL_DICOM_FILENAME, ADJUSTED_DICOM_FILENAME, ] compare_dicom_cli(command, original_ds, expected_ds)
30.637681
87
0.534532
743
8,456
5.746972
0.23284
0.057845
0.023185
0.032787
0.534192
0.464403
0.404918
0.322717
0.259016
0.211007
0
0.015106
0.373699
8,456
275
88
30.749091
0.791163
0.06658
0
0.327273
0
0
0.2068
0.068891
0
0
0
0
0.045455
1
0.022727
false
0
0.036364
0
0.059091
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
71b4b95cd8eac603e64cc2b55ede32f9146ce21d
1,929
py
Python
tests/components/http/test_data_validator.py
itewk/home-assistant
769cf19052f8c9ef374d8ba8ae7705ccc7bf4cf4
[ "Apache-2.0" ]
23
2017-11-15T21:03:53.000Z
2021-03-29T21:33:48.000Z
tests/components/http/test_data_validator.py
itewk/home-assistant
769cf19052f8c9ef374d8ba8ae7705ccc7bf4cf4
[ "Apache-2.0" ]
39
2016-12-16T12:40:34.000Z
2017-02-13T17:53:42.000Z
tests/components/http/test_data_validator.py
itewk/home-assistant
769cf19052f8c9ef374d8ba8ae7705ccc7bf4cf4
[ "Apache-2.0" ]
10
2018-01-01T00:12:51.000Z
2021-12-21T23:08:05.000Z
"""Test data validator decorator.""" from unittest.mock import Mock from aiohttp import web import voluptuous as vol from homeassistant.components.http import HomeAssistantView from homeassistant.components.http.data_validator import RequestDataValidator async def get_client(aiohttp_client, validator): """Generate a client that hits a view decorated with validator.""" app = web.Application() app["hass"] = Mock(is_running=True) class TestView(HomeAssistantView): url = "/" name = "test" requires_auth = False @validator async def post(self, request, data): """Test method.""" return b"" TestView().register(app, app.router) client = await aiohttp_client(app) return client async def test_validator(aiohttp_client): """Test the validator.""" client = await get_client( aiohttp_client, RequestDataValidator(vol.Schema({vol.Required("test"): str})) ) resp = await client.post("/", json={"test": "bla"}) assert resp.status == 200 resp = await client.post("/", json={"test": 100}) assert resp.status == 400 resp = await client.post("/") assert resp.status == 400 async def test_validator_allow_empty(aiohttp_client): """Test the validator with empty data.""" client = await get_client( aiohttp_client, RequestDataValidator( vol.Schema( { # Although we allow empty, our schema should still be able # to validate an empty dict. vol.Optional("test"): str } ), allow_empty=True, ), ) resp = await client.post("/", json={"test": "bla"}) assert resp.status == 200 resp = await client.post("/", json={"test": 100}) assert resp.status == 400 resp = await client.post("/") assert resp.status == 200
27.169014
85
0.610679
216
1,929
5.375
0.356481
0.067183
0.077519
0.098191
0.385874
0.335917
0.335917
0.335917
0.335917
0.229113
0
0.017094
0.272162
1,929
70
86
27.557143
0.809829
0.059616
0
0.347826
0
0
0.027158
0
0
0
0
0
0.130435
1
0
false
0
0.108696
0
0.23913
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
71b4ce87227b2fcaa01e098fed2fec676e7173d5
7,410
py
Python
Conversely_Frontend/app/Server/ukjp/templates.py
sam-aldis/Conversley
1fc30d6b768cc03f727229a52e0879fac3af1e3a
[ "MIT" ]
null
null
null
Conversely_Frontend/app/Server/ukjp/templates.py
sam-aldis/Conversley
1fc30d6b768cc03f727229a52e0879fac3af1e3a
[ "MIT" ]
null
null
null
Conversely_Frontend/app/Server/ukjp/templates.py
sam-aldis/Conversley
1fc30d6b768cc03f727229a52e0879fac3af1e3a
[ "MIT" ]
null
null
null
import days STAGE_INIT = 0 STAGE_CHALLENGE_INIT = 1 STAGE_BOOKED = 2 def createJSONTemplate(data): pass messages = [ "Hey {{first_name}}, thankyou for your enquiry to be one of our Transformation Challengers", "We have 2 Challenges available for you:\n\nThe 8 Week Bikini Challenge which helps you shed 3-9kg of unwanted body fat, flattens your tummy and tones your arms, abs, legs and butt.\n\nOr our 9in6 Challenge which helps you drop 9+kgs of pure fat in just 6 Weeks.", "Please choose which challenge information you would like below..." ] callbacks = { "INIT_8WBC" : [ { "type": "message", "text" : "Thank you {{first_name}},\n\ The FREE 8 Week Bikini Challenge is a done for you - step by step PROVEN program that helps you lose the 3-7kg of unwanted body fat, flatten your tummy and tone your arms, legs and butt.\n\ \n\ This is your chance to transform your body in just 8 weeks for FREE" }, { "type" : "message", "text" : "In exchange for the program being FREE....we ask that you allow us to share your transformation story on our Facebook fan page for marketing purposes to help motivate and inspire the ladies of Perth. \n\ (Please note, a small refundable deposit applies to keep you motivated throughout the 8 weeks)" }, { "type": "message", "text": "The challenge is starting Monday 12th of June and to start your 8 Week Bikini Challenge, we just require you to attend the upcoming information meeting at the facility to quickly go over the program in person. \n\ \n\ There is absolutely no high pressure sales or obligation to join. Simply a meet and chat.\n\ \n\ To RSVP to the meeting click a suitable date below" }, { "type" : "json", "template" : "init_8wbc" } ], "INIT_9IN6" : [ { "type" : "message", "text" : "Thank you {{first_name}},\n\ The 9in6 Transformation Challenge is a done for you - step by step PROVEN program that helps you lose 9kg kilos of unwanted body fat, flatten your tummy and tone your arms, legs and butt in just 6 weeks.\n\ \ \nThis is your chance to transform your body in just 6 weeks for FREE!" }, { "type" : "message", "text" : "In exchange for the program, we ask that you allow us to showcase your transformation story on our Facebook fan page for marketing purposes to help motivate and inspire the ladies of Perth. When you complete the program its FREE. \n\ Please note, a small refundable \"incentive deposit\" applies to keep you motivated throughout the 6 weeks." }, { "type" : "message", "text" : "The challenge is starting Monday 12th of June and to start your 9kg 6-week challenge, we require you to attend the upcoming information meeting where we explain the program in person. \n\ \n\ There is absolutely no high pressure sales or obligation to join at the end, just an opportunity for you learn about the program and how you can lose 9kg in 6 weeks for FREE\n\ \n\ To RSVP to the meeting click a suitable date below" }, { "type" : "json", "template" : "init_9in6" } ], "TIME_TABLE_8WBC" : [ { "type" : "message", "text" : "Sure here's our lesson time table.." }, { "type" : "file", "url" : "http://thetransformationcentre.com.au/img/timetable.pdf" }, { "type" : "json", "template" : "init_8wbc" } ] } def build_json_templates(): JSON_TEMPLATES = { "init" :{ "template_type" : "generic", "elements" : [ { "title" : "The Transformation Centre", "image_url" : "http://thetransformationcentre.com.au/img/spinner/1.png", "subtitle":"Choose one of our Challenges below", "buttons":[ { "type":"postback", "payload":"INIT_8WBC", "title":"8 Week Bikini Challenge" },{ "type":"postback", "title":"9kg 6 Week Challenge", "payload":"INIT_9IN6" } ] } ] }, "init_8wbc" : { "template_type" : "generic", "elements" : [ { "title" : "8 Week Bikini Challenge Meeting", "subtitle":"RSVP by clicking a suitable data below", "buttons":[ # { # "type":"postback", # "payload":"BOOK_CONSULT_8WBC_DATE_" + days.getAppointmentDates(1)[2] + "_DAY_" + days.getAppointmentDates(1)[0] + "_TIME_" + days.getAppointmentTimesForDay(days.getAppointmentDates(1)[0])[1], # "title":days.getAppointmentDates(1)[0].title() + " " + days.getAppointmentTimesForDay(days.getAppointmentDates(1)[0])[0] + " " + days.getAppointmentDates(1)[1] # } # }, { "type":"postback", "title": "Sat 10th June 09.45", "payload":"BOOK_CONSULT_8WBC_DATE_10.05.2017_DAY_SATURDAY_TIME_0945" } ] } ] }, "init_9in6" : { "template_type" : "generic", "elements" : [ { "title" : "9kg 6 Week Challenge Info Meeting", "subtitle":"RSVP by clicking a suitable date below", "buttons":[ # { # "type":"postback", # "payload":"BOOK_CONSULT_9KG6WK_DATE_" + days.getAppointmentDates(1)[2] + "_DAY_" + days.getAppointmentDates(1)[0] + "_TIME_" + days.getAppointmentTimesForDay(days.getAppointmentDates(1)[0])[1], # "title":days.getAppointmentDates(1)[0].title() + " " + days.getAppointmentTimesForDay(days.getAppointmentDates(1)[0])[0] + " " + days.getAppointmentDates(1)[1] # } { "type":"postback", "title": "Sat 10th June 09.45", "payload":"BOOK_CONSULT_8WBC_DATE_10.05.2017_DAY_SATURDAY_TIME_0945" } # ,{ # "type":"postback", # "title": days.getAppointmentDates(2)[0].title() + " " + days.getAppointmentTimesForDay(days.getAppointmentDates(2)[0])[0] + " " + days.getAppointmentDates(2)[1], # "payload":"BOOK_CONSULT_9KG6WK_DATE_" + days.getAppointmentDates(2)[2] + "_DAY_" + days.getAppointmentDates(2)[0] + "_TIME_" + days.getAppointmentTimesForDay(days.getAppointmentDates(2)[0])[1] # } ] } ] } } return JSON_TEMPLATES
47.197452
276
0.523752
786
7,410
4.85369
0.272265
0.108519
0.075491
0.052425
0.701704
0.638008
0.572739
0.504849
0.456619
0.418349
0
0.029539
0.374089
7,410
157
277
47.197452
0.793014
0.15668
0
0.294118
0
0.058824
0.237927
0.017969
0
0
0
0
0
1
0.014706
false
0.007353
0.007353
0
0.029412
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
71b54a23f9d4b30c276bd6f326098f146a43547e
1,349
py
Python
var/spack/repos/builtin/packages/pagmo2/package.py
jeanbez/spack
f4e51ce8f366c85bf5aa0eafe078677b42dae1ba
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
var/spack/repos/builtin/packages/pagmo2/package.py
jeanbez/spack
f4e51ce8f366c85bf5aa0eafe078677b42dae1ba
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
8
2021-11-09T20:28:40.000Z
2022-03-15T03:26:33.000Z
var/spack/repos/builtin/packages/pagmo2/package.py
jeanbez/spack
f4e51ce8f366c85bf5aa0eafe078677b42dae1ba
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
2
2019-02-08T20:37:20.000Z
2019-03-31T15:19:26.000Z
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack.package import * class Pagmo2(CMakePackage): """Parallel Global Multiobjective Optimizer (and its Python alter ego PyGMO) is a C++ / Python platform to perform parallel computations of optimisation tasks (global and local) via the asynchronous generalized island model.""" homepage = "https://esa.github.io/pagmo2/" url = "https://github.com/esa/pagmo2/archive/v2.18.0.tar.gz" git = "https://github.com/esa/pagmo2.git" maintainers = ['liuyangzhuan'] version('master', branch='master') version('2.18.0', sha256='5ad40bf3aa91857a808d6b632d9e1020341a33f1a4115d7a2b78b78fd063ae31') depends_on('boost+system+serialization+thread') depends_on('intel-tbb') depends_on('mpi') depends_on('cmake@3.1:', type='build') variant('shared', default=True, description='Build shared libraries') def cmake_args(self): spec = self.spec args = [ '-DCMAKE_C_COMPILER=%s' % spec['mpi'].mpicc, '-DCMAKE_CXX_COMPILER=%s' % spec['mpi'].mpicxx, self.define_from_variant('BUILD_SHARED_LIBS', 'shared'), ] return args
33.725
96
0.679021
164
1,349
5.506098
0.682927
0.039867
0.031008
0.037652
0.050941
0
0
0
0
0
0
0.063477
0.194218
1,349
39
97
34.589744
0.767249
0.30467
0
0
0
0.047619
0.402399
0.153762
0
0
0
0
0
1
0.047619
false
0
0.047619
0
0.380952
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
71b725d9d3a609a2e8415f6bcdfe99ef3f2dd580
4,984
py
Python
interferogram/sentinel/fetchCalES.py
earthobservatory/ariamh-pub
f33731e127f38ff33b02e02c07b16793c07651a6
[ "Apache-2.0" ]
4
2019-11-19T03:35:35.000Z
2020-12-07T18:43:11.000Z
interferogram/sentinel/fetchCalES.py
earthobservatory/ariamh-pub
f33731e127f38ff33b02e02c07b16793c07651a6
[ "Apache-2.0" ]
3
2019-06-05T03:35:55.000Z
2020-04-09T14:16:08.000Z
interferogram/sentinel/fetchCalES.py
earthobservatory/ariamh-pub
f33731e127f38ff33b02e02c07b16793c07651a6
[ "Apache-2.0" ]
6
2019-08-23T22:53:11.000Z
2021-11-06T15:15:30.000Z
#!/usr/bin/env python3 import os, sys, re, json, requests, datetime, tarfile, argparse from pprint import pprint import numpy as np from utils.UrlUtils import UrlUtils server = 'https://qc.sentinel1.eo.esa.int/' cal_re = re.compile(r'S1\w_AUX_CAL') def cmdLineParse(): ''' Command line parser. ''' parser = argparse.ArgumentParser(description='Fetch calibration auxiliary files ingested into HySDS') parser.add_argument('-o', '--output', dest='outdir', type=str, default='.', help='Path to output directory') parser.add_argument('-d', '--dry-run', dest='dry_run', action='store_true', help="Don't download anything; just output the URLs") return parser.parse_args() def download_file(url, outdir='.', session=None): ''' Download file to specified directory. ''' if session is None: session = requests.session() path = "%s.tgz" % os.path.join(outdir, os.path.basename(url)) print('Downloading URL: ', url) request = session.get(url, stream=True, verify=False) request.raise_for_status() with open(path,'wb') as f: for chunk in request.iter_content(chunk_size=1024): if chunk: f.write(chunk) f.flush() return path def untar_file(path, outdir): ''' Extract aux cal files. ''' if not tarfile.is_tarfile(path): raise RuntimeError("%s is not a tarfile." % path) with tarfile.open(path) as f: f.extractall(outdir) def get_active_ids(es_url): """Query for the active calibration IDs.""" query = { "query":{ "bool":{ "must":[ {"term":{"_id": "S1_AUX_CAL_ACTIVE"}}, ] } }, "sort":[ { "starttime": { "order": "desc" } } ] } es_index = "grq_*_s1-aux_cal_active" if es_url.endswith('/'): search_url = '%s%s/_search' % (es_url, es_index) else: search_url = '%s/%s/_search' % (es_url, es_index) r = requests.post(search_url, data=json.dumps(query)) if r.status_code == 200: result = r.json() #pprint(result) total = result['hits']['total'] if total == 0: raise RuntimeError("Failed to find S1_AUX_CAL_ACTIVE at %s." % search_url) return result['hits']['hits'][0]['_source']['metadata']['active_ids'] else: print("Failed to query %s:\n%s" % (es_url, r.text), file=sys.stderr) print("query: %s" % json.dumps(query, indent=2), file=sys.stderr) print("returned: %s" % r.text, file=sys.stderr) r.raise_for_status() def get_cal_url(id, es_url): """Query for the active calibration url.""" query = { "query":{ "bool":{ "must":[ {"term":{"_id": id}}, ] } }, "fields": ["urls", "metadata.archive_filename"] } es_index = "grq_*_s1-aux_cal" if es_url.endswith('/'): search_url = '%s%s/_search' % (es_url, es_index) else: search_url = '%s/%s/_search' % (es_url, es_index) r = requests.post(search_url, data=json.dumps(query)) if r.status_code == 200: result = r.json() pprint(result) total = result['hits']['total'] if total == 0: raise RuntimeError("Failed to find %s at %s." % (id, search_url)) urls = result['hits']['hits'][0]['fields']['urls'] archive_fname = result['hits']['hits'][0]['fields']['metadata.archive_filename'][0] url = [x for x in urls if x.startswith('http')][0] #print(urls) #print(url) #print(archive_fname) return os.path.join(url, archive_fname) else: print("Failed to query %s:\n%s" % (es_url, r.text), file=sys.stderr) print("query: %s" % json.dumps(query, indent=2), file=sys.stderr) print("returned: %s" % r.text, file=sys.stderr) r.raise_for_status() def fetch(outdir, dry_run): # get endpoint configurations uu = UrlUtils() es_url = uu.rest_url # get active calibration ids active_ids = get_active_ids(es_url) print(active_ids) # get urls for active calibration files cal_urls = [get_cal_url(i, es_url) for i in active_ids] print(cal_urls) if len(cal_urls) == 0: print('Failed to find calibration auxiliary files') if dry_run: print('\n'.join(cal_urls)) else: if not os.path.isdir(outdir): os.makedirs(outdir) for cal_url in cal_urls: try: cal_file = download_file(cal_url, outdir) except: print('Failed to download URL: ', cal_url) raise try: cal_dir = untar_file(cal_file, outdir) except: print('Failed to untar: ', cal_file) raise os.unlink(cal_file) if __name__ == '__main__': inps = cmdLineParse() fetch(inps.outdir, inps.dry_run)
29.491124
105
0.573234
649
4,984
4.229584
0.268105
0.023679
0.028415
0.016029
0.358106
0.314026
0.283424
0.259381
0.259381
0.259381
0
0.007515
0.279093
4,984
168
106
29.666667
0.756471
0.06561
0
0.353448
0
0
0.178058
0.01589
0
0
0
0
0
1
0.051724
false
0
0.034483
0
0.12069
0.12931
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
71b74d81702689c7914ede59827af8b7196bc18b
2,590
py
Python
www/conservancy/urls.py
stain/conservancy-website
9e41ddff766fe517a99198d60701193e8b68415e
[ "0BSD" ]
null
null
null
www/conservancy/urls.py
stain/conservancy-website
9e41ddff766fe517a99198d60701193e8b68415e
[ "0BSD" ]
null
null
null
www/conservancy/urls.py
stain/conservancy-website
9e41ddff766fe517a99198d60701193e8b68415e
[ "0BSD" ]
null
null
null
# Copyright 2005-2008, James Garrison # Copyright 2010, 2012 Bradley M. Kuhn # This software's license gives you freedom; you can copy, convey, # propagate, redistribute, modify and/or redistribute modified versions of # this program under the terms of the GNU Affero General Public License # (AGPL) as published by the Free Software Foundation (FSF), either # version 3 of the License, or (at your option) any later version of the # AGPL published by the FSF. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero # General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program in a file in the toplevel directory called # "AGPLv3". If not, see <http://www.gnu.org/licenses/>. from django.conf.urls import url, include from django.contrib import admin, admindocs from conservancy import feeds, frontpage, sponsors import conservancy.apps.fundgoal.views as fundgoal_views import conservancy.static.views as static_views admin.autodiscover() urlpatterns = [ url(r'^$', frontpage.view), url(r'^sponsors$', frontpage.view), url(r'^sponsors/$', sponsors.view), url(r'^sponsors/index.html$', sponsors.view), url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', admin.site.urls), url(r'^feeds/blog/?$', feeds.BlogFeed()), url(r'^feeds/news/?$', feeds.PressReleaseFeed()), url(r'^feeds/omnibus/?$', feeds.OmnibusFeed()), url(r'^feeds/?$', feeds.view), url(r'^news(/|$)', include('conservancy.apps.news.urls')), url(r'^blog(/|$)', include('conservancy.apps.blog.urls')), # formerly static templated things... (dirs with templates) url(r'^error/(40[134]|500)(?:/index\.html|/|)$', static_views.handler), url(r'^error', static_views.index), url(r'^about', static_views.index), url(r'^donate', static_views.index), url(r'^copyleft-compliance', static_views.index, {'fundraiser_sought' : 'vmware-match-0'}), url(r'^projects', static_views.index), url(r'^npoacct', static_views.index, {'fundraiser_sought' : 'npoacct'}), url(r'^contractpatch', include('conservancy.apps.contractpatch.urls')), url(r'^overview', static_views.index), url(r'^privacy-policy', static_views.index), url(r'^supporter', include('conservancy.apps.supporter.urls')), url(r'^fundraiser_data', fundgoal_views.view), ]
44.655172
75
0.699614
356
2,590
5.047753
0.418539
0.053422
0.07123
0.063439
0.185865
0.055648
0.037841
0
0
0
0
0.012318
0.153668
2,590
57
76
45.438596
0.807482
0.362162
0
0
0
0
0.30496
0.127373
0
0
0
0
0
1
0
false
0
0.147059
0
0.147059
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
71b901299fb22334462ebfb480d8b6d820375ea4
1,430
py
Python
graphene_spike_tests/acceptances/test_query.py
FabienArcellier/spike-graphene-flask
bc7bce571a21826c3da852eb1c2e1904bbab99b4
[ "MIT" ]
1
2021-03-18T00:19:53.000Z
2021-03-18T00:19:53.000Z
graphene_spike_tests/acceptances/test_query.py
FabienArcellier/spike-graphene-flask
bc7bce571a21826c3da852eb1c2e1904bbab99b4
[ "MIT" ]
null
null
null
graphene_spike_tests/acceptances/test_query.py
FabienArcellier/spike-graphene-flask
bc7bce571a21826c3da852eb1c2e1904bbab99b4
[ "MIT" ]
null
null
null
import unittest from unittest.mock import Mock from graphene import Schema from graphene.test import Client from graphene_spike.query import Query class MainTest(unittest.TestCase): def setUp(self): self.schema = Schema(query=Query) self.client = client = Client(self.schema) def test_hello_should_work_without_argument(self): # Assign query_string = '{ hello }' # Acts executed = self.client.execute(query_string) # Assert self.assertEqual(executed['data'], {"hello": "Hello stranger, you have 18 !"}) def test_hello_should_write_the_giving_name(self): # Assign query_string = '{ hello(name: "Fabien") }' # Acts executed = self.client.execute(query_string) # Assert self.assertEqual(executed['data'], {"hello": "Hello Fabien, you have 18 !"}) def test_hello_should_write_the_giving_age(self): # Assign query_string = '{ hello(age: 24) }' # Acts executed = self.client.execute(query_string) # Assert self.assertEqual(executed['data'], {"hello": "Hello stranger, you have 24 !"}) def test_goodbye_should_giving_a_response(self): # Assign query_string = '{ goodbye }' # Acts executed = self.client.execute(query_string) # Assert self.assertEqual(executed['data'], {"goodbye": "See ya!"})
26.481481
86
0.630769
163
1,430
5.343558
0.276074
0.101033
0.068886
0.096441
0.579793
0.490241
0.490241
0.490241
0.490241
0.490241
0
0.007533
0.257343
1,430
53
87
26.981132
0.812618
0.052448
0
0.16
0
0
0.143815
0
0
0
0
0
0.16
1
0.2
false
0
0.2
0
0.44
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
71b9373dfb805ca37a8bda9472585bd77a94fc2f
10,028
py
Python
clikan.py
davidventasmarin/clikan
401fe4053a14873872bb246739d55c55f8f6dcfa
[ "MIT" ]
null
null
null
clikan.py
davidventasmarin/clikan
401fe4053a14873872bb246739d55c55f8f6dcfa
[ "MIT" ]
null
null
null
clikan.py
davidventasmarin/clikan
401fe4053a14873872bb246739d55c55f8f6dcfa
[ "MIT" ]
null
null
null
from rich import print from rich.console import Console from rich.table import Table import click from click_default_group import DefaultGroup import yaml import os ##from terminaltables import SingleTable import sys from textwrap import wrap import collections import datetime import configparser import pkg_resources # part of setuptools VERSION = pkg_resources.require("clikan")[0].version class Config(object): """The config in this example only holds aliases.""" def __init__(self): self.path = os.getcwd() self.aliases = {} def read_config(self, filename): parser = configparser.RawConfigParser() parser.read([filename]) try: self.aliases.update(parser.items('aliases')) except configparser.NoSectionError: pass pass_config = click.make_pass_decorator(Config, ensure=True) class AliasedGroup(DefaultGroup): """This subclass of a group supports looking up aliases in a config file and with a bit of magic. """ def get_command(self, ctx, cmd_name): # Step one: bulitin commands as normal rv = click.Group.get_command(self, ctx, cmd_name) if rv is not None: return rv # Step two: find the config object and ensure it's there. This # will create the config object is missing. cfg = ctx.ensure_object(Config) # Step three: lookup an explicit command aliase in the config if cmd_name in cfg.aliases: actual_cmd = cfg.aliases[cmd_name] return click.Group.get_command(self, ctx, actual_cmd) # Alternative option: if we did not find an explicit alias we # allow automatic abbreviation of the command. "status" for # instance will match "st". We only allow that however if # there is only one command. matches = [x for x in self.list_commands(ctx) if x.lower().startswith(cmd_name.lower())] if not matches: return None elif len(matches) == 1: return click.Group.get_command(self, ctx, matches[0]) ctx.fail('Too many matches: %s' % ', '.join(sorted(matches))) def read_config(ctx, param, value): """Callback that is used whenever --config is passed. We use this to always load the correct config. This means that the config is loaded even if the group itself never executes so our aliases stay always available. """ cfg = ctx.ensure_object(Config) if value is None: value = os.path.join(os.path.dirname(__file__), 'aliases.ini') cfg.read_config(value) return value @click.version_option(VERSION) @click.command(cls=AliasedGroup, default='show', default_if_no_args=True) def clikan(): """clikan: CLI personal kanban """ @clikan.command() def configure(): """Place default config file in CLIKAN_HOME or HOME""" home = get_clikan_home() data_path = os.path.join(home, ".clikan.dat") config_path = os.path.join(home, ".clikan.yaml") if (os.path.exists(config_path) and not click.confirm('Config file exists. Do you want to overwrite?')): return with open(config_path, 'w') as outfile: conf = {'clikan_data': data_path} yaml.dump(conf, outfile, default_flow_style=False) click.echo("Creating %s" % config_path) @clikan.command() @click.argument('task') def add(task): """Add a task in todo""" if len(task) > 40: click.echo('Task must be shorter than 40 chars. Brevity counts.') else: config = read_config_yaml() dd = read_data(config) todos, inprogs, dones = split_items(config, dd) if ('limits' in config and 'todo' in config['limits'] and int(config['limits']['todo']) <= len(todos)): click.echo('No new todos, limit reached already.') else: od = collections.OrderedDict(sorted(dd['data'].items())) new_id = 1 if bool(od): new_id = next(reversed(od)) + 1 entry = ['todo', task, timestamp(), timestamp()] dd['data'].update({new_id: entry}) click.echo("Creating new task w/ id: %d -> %s" % (new_id, task)) write_data(config, dd) @clikan.command() @click.argument('id') def delete(id): """Delete task""" config = read_config_yaml() dd = read_data(config) item = dd['data'].get(int(id)) if item is None: click.echo('No existing task with that id.') else: item[0] = 'deleted' item[2] = timestamp() dd['deleted'].update({int(id): item}) dd['data'].pop(int(id)) write_data(config, dd) click.echo('Removed task %d.' % int(id)) @clikan.command() @click.argument('id') def promote(id): """Promote task""" config = read_config_yaml() dd = read_data(config) todos, inprogs, dones = split_items(config, dd) item = dd['data'].get(int(id)) if item[0] == 'todo': if ('limits' in config and 'wip' in config['limits'] and int(config['limits']['wip']) <= len(inprogs)): click.echo('No new tasks, limit reached already.') else: click.echo('Promoting task %s to in-progress.' % id) dd['data'][int(id)] = ['inprogress', item[1], timestamp(), item[3]] write_data(config, dd) elif item[0] == 'inprogress': click.echo('Promoting task %s to done.' % id) dd['data'][int(id)] = ['done', item[1], timestamp(), item[3]] write_data(config, dd) else: click.echo('Already done, can not promote %s' % id) @clikan.command() @click.argument('id') def regress(id): """Regress task""" config = read_config_yaml() dd = read_data(config) item = dd['data'].get(int(id)) if item[0] == 'done': click.echo('Regressing task %s to in-progress.' % id) dd['data'][int(id)] = ['inprogress', item[1], timestamp(), item[3]] write_data(config, dd) elif item[0] == 'inprogress': click.echo('Regressing task %s to todo.' % id) dd['data'][int(id)] = ['todo', item[1], timestamp(), item[3]] write_data(config, dd) else: click.echo('Already in todo, can not regress %s' % id) @clikan.command() def show(): console = Console() """Show tasks in clikan""" config = read_config_yaml() dd = read_data(config) todos, inprogs, dones = split_items(config, dd) if 'limits' in config and 'done' in config['limits']: dones = dones[0:int(config['limits']['done'])] else: dones = dones[0:10] todos = '\n'.join([str(x) for x in todos]) inprogs = '\n'.join([str(x) for x in inprogs]) dones = '\n'.join([str(x) for x in dones]) # td = [ # ['todo', 'in-progress', '[bold magenta]done[/bold magenta]'], # ['', '', ''], # ] #table = SingleTable(td, 'clikan v.{}'.format(VERSION)) # table.inner_heading_row_border = False # table.inner_row_border = True # table.justify_columns = {0: 'center', 1: 'center', 2: 'center'} table = Table(show_header=True, show_footer=True) table.add_column("[bold yellow]todo[/bold yellow]", no_wrap=True, footer="clikan") table.add_column('[bold green]in-progress[/bold green]', no_wrap=True) table.add_column('[bold magenta]done[/bold magenta]', no_wrap=True, footer="v.{}".format(VERSION)) # def wrap_lines(lines, column_index): # max_width = table.column_max_width(column_index) # packed = [line for line in lines if line.strip() != ''] # wrapped = [wrap(line, max_width, break_long_words=False, # replace_whitespace=False) for line in packed] # return '\n'.join(['\n'.join(w) for w in wrapped]) # for index, section in enumerate((todos, inprogs, dones)): # table.table_data[1][index] = wrap_lines(section.splitlines(), index) table.add_row(todos, inprogs, dones) console.print(table) #print(table.table) def read_data(config): """Read the existing data from the config datasource""" try: with open(config["clikan_data"], 'r') as stream: try: return yaml.load(stream, Loader=yaml.FullLoader) except yaml.YAMLError as exc: print("Ensure %s exists, as you specified it " "as the clikan data file." % config['clikan_data']) print(exc) except IOError: click.echo("No data, initializing data file.") write_data(config, {"data": {}, "deleted": {}}) with open(config["clikan_data"], 'r') as stream: return yaml.load(stream, Loader=yaml.FullLoader) def write_data(config, data): """Write the data to the config datasource""" with open(config["clikan_data"], 'w') as outfile: yaml.dump(data, outfile, default_flow_style=False) def get_clikan_home(): home = os.environ.get('CLIKAN_HOME') if not home: home = os.path.expanduser('~') return home def read_config_yaml(): """Read the app config from ~/.clikan.yaml""" try: home = get_clikan_home() with open(home + "/.clikan.yaml", 'r') as stream: try: return yaml.load(stream, Loader=yaml.FullLoader) except yaml.YAMLError: print("Ensure %s/.clikan.yaml is valid, expected YAML." % home) sys.exit() except IOError: print("Ensure %s/.clikan.yaml exists and is valid." % home) sys.exit() def split_items(config, dd): todos = [] inprogs = [] dones = [] for key, value in dd['data'].items(): if value[0] == 'todo': todos.append("[%d] %s" % (key, value[1])) elif value[0] == 'inprogress': inprogs.append("[%d] %s" % (key, value[1])) else: dones.insert(0, "[%d] %s" % (key, value[1])) return todos, inprogs, dones def timestamp(): return '{:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now())
33.315615
102
0.603311
1,331
10,028
4.455297
0.220135
0.021248
0.020236
0.017201
0.298482
0.244519
0.203879
0.156492
0.14688
0.141821
0
0.004947
0.254188
10,028
300
103
33.426667
0.78794
0.183785
0
0.300493
0
0
0.145805
0.002859
0
0
0
0.003333
0
1
0.083744
false
0.009852
0.064039
0.004926
0.216749
0.029557
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
71b9f7585fb3ca8d7750b533bdb679556becb780
853
py
Python
trial/src/sender.py
siddharthumakarthikeyan/Cable-Driven-Parallel-Robots-CDPR-Modelling
4e8d991d55ae7da91b3c90773c679f3369a4dafa
[ "MIT" ]
9
2021-06-01T12:19:58.000Z
2022-02-28T12:30:09.000Z
trial/src/sender.py
siddharthumakarthikeyan/Cable-Driven-Parallel-Robots-CDPR-Modelling
4e8d991d55ae7da91b3c90773c679f3369a4dafa
[ "MIT" ]
1
2021-09-27T12:24:50.000Z
2021-09-27T12:24:50.000Z
trial/src/sender.py
siddharthumakarthikeyan/Cable-Driven-Parallel-Robots-CDPR-Modelling
4e8d991d55ae7da91b3c90773c679f3369a4dafa
[ "MIT" ]
1
2021-08-02T00:48:11.000Z
2021-08-02T00:48:11.000Z
#!/usr/bin/env python # license removed for brevity import rospy from std_msgs.msg import String from gazebo_msgs.msg import LinkState def talker(): pub = rospy.Publisher('/gazebo/set_link_state', LinkState, queue_size=10) ppp = LinkState() rospy.init_node('talker', anonymous=True) rate = rospy.Rate(100) # 10hz i = 1 while not rospy.is_shutdown(): ppp.link_name = "platform" ppp.pose.position.x = 0.1 ppp.pose.position.y = 0.1 ppp.pose.position.z = 1 ppp.pose.orientation.x = 0 ppp.pose.orientation.y = 0 ppp.pose.orientation.z = 0 ppp.pose.orientation.w = 0 i = i+1 rospy.loginfo(ppp) pub.publish(ppp) rate.sleep() if __name__ == '__main__': try: talker() except rospy.ROSInterruptException: pass
24.371429
77
0.614302
116
853
4.37931
0.517241
0.096457
0.141732
0.112205
0.066929
0
0
0
0
0
0
0.028986
0.271981
853
34
78
25.088235
0.78905
0.062134
0
0
0
0
0.055207
0.027604
0
0
0
0
0
1
0.037037
false
0.037037
0.111111
0
0.148148
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
71bb038e552d16449011833ef1582532136fc5b7
1,073
py
Python
discriminator_dataset.py
kimmokal/CC-Art-Critics
af83762a5f22043f279c167cbd58e16737e3ec87
[ "MIT" ]
null
null
null
discriminator_dataset.py
kimmokal/CC-Art-Critics
af83762a5f22043f279c167cbd58e16737e3ec87
[ "MIT" ]
null
null
null
discriminator_dataset.py
kimmokal/CC-Art-Critics
af83762a5f22043f279c167cbd58e16737e3ec87
[ "MIT" ]
null
null
null
import torch from os import listdir, path from PIL import Image import torchvision class DiscriminatorDataset(torch.utils.data.Dataset): def __init__(self): super(DiscriminatorDataset, self).__init__() currentDir = path.dirname(__file__) abstractDir = path.join(currentDir, 'image_data/abstract') realisticDir = path.join(currentDir, 'image_data/realistic') abstractFiles = [path.join(abstractDir, f) for f in listdir( abstractDir) if path.isfile(path.join(abstractDir, f))] realisticFiles = [path.join(realisticDir, f) for f in listdir( realisticDir) if path.isfile(path.join(realisticDir, f))] self.abstractFilesLen = len(abstractFiles) self.allFiles = abstractFiles + realisticFiles def __len__(self): return len(self.allFiles) def __getitem__(self, index): filename = self.allFiles[index] pilImage = Image.open(filename).convert("RGB") return (torchvision.transforms.ToTensor()(pilImage), 1 if index < self.abstractFilesLen else 0)
38.321429
103
0.692451
119
1,073
6.058824
0.411765
0.066574
0.049931
0.0638
0.169209
0
0
0
0
0
0
0.002347
0.205965
1,073
27
104
39.740741
0.843897
0
0
0
0
0
0.039143
0
0
0
0
0
0
1
0.136364
false
0
0.181818
0.045455
0.454545
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
71bcf0be9208fd0fbb5c709b03c8fca5ba790724
951
py
Python
emailmeld/sender.py
ionata/django-emailmeld
28326933d22957f8737ab8a9564daa9cbfca6d06
[ "BSD-2-Clause" ]
null
null
null
emailmeld/sender.py
ionata/django-emailmeld
28326933d22957f8737ab8a9564daa9cbfca6d06
[ "BSD-2-Clause" ]
1
2017-11-21T22:11:04.000Z
2017-11-22T00:37:49.000Z
emailmeld/sender.py
ionata/django-emailmeld
28326933d22957f8737ab8a9564daa9cbfca6d06
[ "BSD-2-Clause" ]
null
null
null
from django.core.mail.message import EmailMessage, EmailMultiAlternatives from django.utils.translation import ugettext_lazy as _ from django.template.loader import render_to_string from django.utils.safestring import mark_safe def send_mail_task(subject, message, from_email, recipient_list): message = EmailMessage("Discover Special Value - {0}".format(subject), message, from_email, recipient_list) message.send() def send_html_mail_task(subject, text_message, html_message, from_email, recipient_list, template='email/email_base.html'): if template is not None: html_message = render_to_string(template, {'content': mark_safe(html_message)}) # render html into an email template message = EmailMultiAlternatives("Discover Special Value - {0}".format(subject), html_message, from_email, recipient_list) message.content_subtype = "html" message.attach_alternative(text_message, "text/plain") message.send()
47.55
126
0.785489
124
951
5.782258
0.379032
0.076709
0.089261
0.13947
0.306834
0.306834
0.119944
0
0
0
0
0.002398
0.123028
951
19
127
50.052632
0.857314
0.035752
0
0.142857
0
0
0.107104
0.022951
0
0
0
0
0
1
0.142857
false
0
0.285714
0
0.428571
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
71be4424294b2ee2dc156eab695f7198203426e0
1,506
py
Python
tests/test_hap_server.py
sander-vd/HAP-python
991761ceadfd7796d454d61c87be7f5d4b75d432
[ "Apache-2.0" ]
3
2019-12-07T22:42:38.000Z
2022-01-20T08:44:46.000Z
tests/test_hap_server.py
sander-vd/HAP-python
991761ceadfd7796d454d61c87be7f5d4b75d432
[ "Apache-2.0" ]
null
null
null
tests/test_hap_server.py
sander-vd/HAP-python
991761ceadfd7796d454d61c87be7f5d4b75d432
[ "Apache-2.0" ]
1
2021-05-15T22:34:52.000Z
2021-05-15T22:34:52.000Z
"""Tests for the HAPServer.""" from socket import timeout from unittest.mock import Mock, MagicMock, patch import pytest from pyhap import hap_server @patch('pyhap.hap_server.HAPServer.server_bind', new=MagicMock()) @patch('pyhap.hap_server.HAPServer.server_activate', new=MagicMock()) def test_finish_request_pops_socket(): """Test that ``finish_request`` always clears the connection after a request.""" amock = Mock() client_addr = ('192.168.1.1', 55555) server_addr = ('', 51826) # Positive case: The request is handled server = hap_server.HAPServer(server_addr, amock, handler_type=lambda *args: MagicMock()) server.connections[client_addr] = amock server.finish_request(amock, client_addr) assert len(server.connections) == 0 # Negative case: The request fails with a timeout def raises(*args): raise timeout() server = hap_server.HAPServer(server_addr, amock, handler_type=raises) server.connections[client_addr] = amock server.finish_request(amock, client_addr) assert len(server.connections) == 0 # Negative case: The request raises some other exception server = hap_server.HAPServer(server_addr, amock, handler_type=lambda *args: 1 / 0) server.connections[client_addr] = amock with pytest.raises(Exception): server.finish_request(amock, client_addr) assert len(server.connections) == 0
32.73913
84
0.677955
183
1,506
5.415301
0.31694
0.070636
0.090817
0.12109
0.566095
0.533804
0.465187
0.465187
0.465187
0.414733
0
0.019658
0.223108
1,506
45
85
33.466667
0.82735
0.160027
0
0.428571
0
0
0.072684
0.063898
0
0
0
0
0.107143
1
0.071429
false
0
0.142857
0
0.214286
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
71bf1e11839857da419f894d58ec4b485c55ada9
1,604
py
Python
app/views/main.py
charlesashby/marketvault-front-end
758cf8ba1d8486f45eac093ded78a15fc82df3dc
[ "MIT" ]
null
null
null
app/views/main.py
charlesashby/marketvault-front-end
758cf8ba1d8486f45eac093ded78a15fc82df3dc
[ "MIT" ]
null
null
null
app/views/main.py
charlesashby/marketvault-front-end
758cf8ba1d8486f45eac093ded78a15fc82df3dc
[ "MIT" ]
null
null
null
from flask import render_template, Blueprint, request from app.utils.search import MySQLClient from app.utils.preprocessor import TextPreprocessor mainbp = Blueprint("main", __name__) @mainbp.route("/search", methods=["GET"]) @mainbp.route("/", methods=["GET"]) def home(): stores_by_page = 10 topic = request.args.get("topic") category = request.args.get("category") daily_visitors = request.args.get("dailyvisitors") alexa_rank = request.args.get("alexarank") page = request.args.get("page") or 0 if all([topic is None, category is None, daily_visitors is None, alexa_rank is None]): stores = MySQLClient.random_stores(page * stores_by_page, stores_by_page) else: stores = MySQLClient.search_stores(category, daily_visitors, alexa_rank, topic, page * stores_by_page, stores_by_page) stores = [ { "url": store.url, "description": TextPreprocessor.clean_str(store.description), "title": TextPreprocessor.clean_str(store.title), "alexa_rank": store.alexa_rank, "category": store.category, "average_product_price": store.average_product_price, "daily_visitors": store.daily_visitors } for store in stores ] return render_template("search/index.html", stores=stores) @mainbp.route("/search/topics", methods=["GET"]) def search_topics(): substring = request.args.get("q") return [ { "id": topic.id, "text": topic.text } for topic in MySQLClient.search_topic_by_substring(substring) ]
31.45098
126
0.663342
190
1,604
5.4
0.321053
0.064327
0.081871
0.062378
0.060429
0.054581
0.054581
0
0
0
0
0.002383
0.215087
1,604
50
127
32.08
0.81255
0
0
0
0
0
0.106117
0.013109
0
0
0
0
0
1
0.052632
false
0
0.078947
0
0.184211
0.052632
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
71bf83bddad54a592ea34fa0a46b33394f925a8d
31,770
py
Python
bag_testbenches/ckt_dsn/analog/amplifier/opamp_two_stage.py
tinapiao/Software-IC-Automation
74b23cd94aa6e4658b110e93b5deb635e014f3a6
[ "BSD-3-Clause" ]
null
null
null
bag_testbenches/ckt_dsn/analog/amplifier/opamp_two_stage.py
tinapiao/Software-IC-Automation
74b23cd94aa6e4658b110e93b5deb635e014f3a6
[ "BSD-3-Clause" ]
null
null
null
bag_testbenches/ckt_dsn/analog/amplifier/opamp_two_stage.py
tinapiao/Software-IC-Automation
74b23cd94aa6e4658b110e93b5deb635e014f3a6
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- """This module contains design algorithm for a traditional two stage operational amplifier.""" from typing import TYPE_CHECKING, List, Optional, Dict, Any, Tuple, Sequence from copy import deepcopy import numpy as np import scipy.optimize as sciopt from bag.math import gcd from bag.data.lti import LTICircuit, get_stability_margins, get_w_crossings, get_w_3db from bag.util.search import FloatBinaryIterator, BinaryIterator, minimize_cost_golden from bag.simulation.core import MeasurementManager from verification.mos.query import MOSDBDiscrete from .components import LoadDiodePFB, InputGm if TYPE_CHECKING: from verification.ac.core import ACTB class TailStage1(object): """Tail transistor of the first stage op amp. Due to layout restrictions, the tail transistor needs to have the same number of fingers and stack number as the input transistor. This method finds the optimal width/intent. """ def __init__(self, mos_db): # type: (MOSDBDiscrete) -> None self._db = mos_db self._intent_list = mos_db.get_dsn_param_values('intent') self._valid_widths = mos_db.width_list self._best_op = None def design(self, itarg_list, # type: List[float] vd_list, # type: List[float] vout_amp_list, # type: List[float] vb, # type: float l, # type: float seg, # type: int stack, # type: int ): # type: (...) -> None vgs_idx = self._db.get_fun_arg_index('vgs') self._best_op = best_score = None for intent in self._intent_list: for w in self._valid_widths: self._db.set_dsn_params(l=l, w=w, intent=intent, stack=stack) ib = self._db.get_function_list('ibias') gds = self._db.get_function_list('gds') vgs_min, vgs_max = ib[0].get_input_range(vgs_idx) vg_min = vgs_min + vb vg_max = vgs_max + vb # find vgs for each corner vgs_list, gds1_list, gds2_list = self._solve_vgs(itarg_list, vout_amp_list, vd_list, ib, gds, seg, vb, vg_min, vg_max) if vgs_list is not None: cur_score = max(gds2_list) if self._best_op is None or cur_score < best_score: best_score = cur_score self._best_op = (w, intent, seg, stack, vb, vgs_list, vout_amp_list, gds1_list, gds2_list) def _solve_vgs(self, itarg_list, vout_list, vd_list, ib_list, gds_list, seg, vb, vg_min, vg_max): vgs_list, gds1_list, gds2_list = [], [], [] for itarg, vout, vd, ibf, gdsf in zip(itarg_list, vout_list, vd_list, ib_list, gds_list): def zero_fun(vg): farg = self._db.get_fun_arg(vbs=vb - vd, vds=vd - vb, vgs=vg - vb) return seg * ibf(farg) - itarg v1, v2 = zero_fun(vg_min), zero_fun(vg_max) if v1 < 0 and v2 < 0 or v1 > 0 and v2 > 0: # no solution return None, None, None vg_sol = sciopt.brentq(zero_fun, vg_min, vg_max) # type: float vgs_opt = vg_sol - vb arg1 = self._db.get_fun_arg(vbs=vb - vd, vds=vd - vb, vgs=vgs_opt) arg2 = self._db.get_fun_arg(vbs=vb - vd, vds=vout - vb, vgs=vgs_opt) vgs_list.append(vgs_opt) gds1_list.append(seg * gdsf(arg1)) gds2_list.append(seg * gdsf(arg2)) return vgs_list, gds1_list, gds2_list def get_dsn_info(self): # type: () -> Optional[Dict[str, Any]] if self._best_op is None: return None w, intent, seg, stack, vb, vgs_list, vout_list, gds1_list, gds2_list = self._best_op self._db.set_dsn_params(w=w, intent=intent, stack=stack) cdd = self._db.get_function_list('cdd') cdd2_list = [] for vgs, vout, cddf in zip(vgs_list, vout_list, cdd): arg = self._db.get_fun_arg(vbs=0, vds=vout - vb, vgs=vgs) cur_cdd = cddf(arg) # type: float cdd2_list.append(seg * cur_cdd) return dict( w=w, intent=intent, vgs=vgs_list, gds1=gds1_list, gds2=gds2_list, cdd2=cdd2_list, ) class StageOneCurrentError(Exception): pass class OpAmpTwoStage(object): """A two stage fully differential operational amplifier. The first stage is a differential amplifier with diode + positive feedback load, the second stage is a psuedo-differential common source amplifier. This topology has the following advantages: 1. large output swing. 2. Common mode feedback is only required for the second stage. """ def __init__(self, nch_db, pch_db): # type: (MOSDBDiscrete, MOSDBDiscrete) -> None self._nch_db = nch_db self._pch_db = pch_db self._amp_info = None def design(self, i1_unit, # type: List[float] i1_min_size, # type: int vg_list, # type: List[float] vout_list, # type: List[float] cpar1, # type: float cload, # type: float f_unit, # type: float phase_margin, # type: float res_var, # type: float l, # type: float vstar_gm_min, # type: float ft_load_scale, # type: float vds_tail_min, # type: float seg_gm_min, # type: int vdd, # type: float pmos_input=True, # type: bool max_ref_ratio=20, # type: int load_stack_list=None, # type: Optional[List[int]] ): # type: (...) -> None # binary search for minimum stage 1 current, i1_size_iter = BinaryIterator(i1_min_size, None) i1_size_opt, opt_info = None, None while i1_size_iter.has_next(): i1_size = i1_size_iter.get_next() print('trying i1_size = %d' % i1_size) try: self._design_with_itarg(i1_size, i1_unit, vg_list, vout_list, cpar1, cload, f_unit, phase_margin, res_var, l, vstar_gm_min, ft_load_scale, vds_tail_min, seg_gm_min, vdd, pmos_input, max_ref_ratio, load_stack_list) success = True except StageOneCurrentError as err: print(err) success = False if success: print('success') opt_info = self._amp_info i1_size_opt = i1_size i1_size_iter.down() else: i1_size_iter.up() # linear search to find optimal scale2 scale2_int_max = int(opt_info['scale2']) if scale2_int_max == opt_info['scale2']: scale2_int_max -= 1 last_i1_size = i1_size_opt print('i1_size = %d, scale2 = %.4g' % (i1_size_opt, opt_info['scale2'])) for scale2_test in range(scale2_int_max, 0, -1): i1_size_test = int(np.floor(i1_size_opt * (1 + opt_info['scale2']) / (1 + scale2_test))) if i1_size_test <= last_i1_size or scale2_test == opt_info['scale2']: continue print('testing i1_size = %d, scale2 = %.4g' % (i1_size_test, scale2_test)) try: self._design_with_itarg(i1_size_test, i1_unit, vg_list, vout_list, cpar1, cload, f_unit, phase_margin, res_var, l, vstar_gm_min, ft_load_scale, vds_tail_min, seg_gm_min, vdd, pmos_input, max_ref_ratio, load_stack_list) except StageOneCurrentError as err: print(err) continue if self._amp_info['scale2'] <= scale2_test: # found new minimum. close in to find optimal i1 size opt_info = self._amp_info i1_size_opt = i1_size_test print('update: i1_size = %d, scale2 = %.4g' % (i1_size_opt, opt_info['scale2'])) i1_size_iter = BinaryIterator(last_i1_size + 1, i1_size_test) while i1_size_iter.has_next(): i1_size_cur_opt = i1_size_iter.get_next() print('testing i1_size = %d' % i1_size_cur_opt) try: self._design_with_itarg(i1_size_cur_opt, i1_unit, vg_list, vout_list, cpar1, cload, f_unit, phase_margin, res_var, l, vstar_gm_min, ft_load_scale, vds_tail_min, seg_gm_min, vdd, pmos_input, max_ref_ratio, load_stack_list) if self._amp_info['scale2'] <= opt_info['scale2']: opt_info = self._amp_info i1_size_opt = i1_size_cur_opt print('update: i1_size = %d, ' 'scale2 = %.4g' % (i1_size_opt, opt_info['scale2'])) i1_size_iter.down() else: i1_size_iter.up() except StageOneCurrentError as err: print(err) i1_size_iter.up() last_i1_size = i1_size_test self._amp_info = opt_info def _design_with_itarg(self, i1_size, # type: int i1_unit, # type: List[float] vg_list, # type: List[float] vout_list, # type: List[float] cpar1, # type: float cload, # type: float f_unit, # type: float phase_margin, # type: float res_var, # type: float l, # type: float vstar_gm_min, # type: float ft_load_scale, # type: float vds_tail_min, # type: float seg_gm_min, # type: int vdd, # type: float pmos_input, # type: bool max_ref_ratio, # type: int load_stack_list, # type: Optional[List[int]] ): # type: (...) -> None itarg_list = [i1 * i1_size for i1 in i1_unit] if pmos_input: load_db = self._nch_db gm_db = self._pch_db vds2_list = vout_list vb_gm = vdd vb_load = 0 else: load_db = self._pch_db gm_db = self._nch_db vds2_list = [vo - vdd for vo in vout_list] vb_gm = 0 vb_load = vdd load = LoadDiodePFB(load_db) gm = InputGm(gm_db) tail1 = TailStage1(gm_db) # design load print('designing load') load.design(itarg_list, vds2_list, ft_load_scale * f_unit, stack_list=load_stack_list) load_info = load.get_dsn_info() vgs_load_list = load_info['vgs'] gds_load_list = load_info['gds1'] gm2_list = load_info['gm2'] stack_diode = load_info['stack_diode'] stack_ngm = load_info['stack_ngm'] seg_diode = load_info['seg_diode'] seg_ngm = load_info['seg_ngm'] if pmos_input: vmid_list = vgs_load_list else: vmid_list = [vdd - vgs for vgs in vgs_load_list] # design input gm print('designing input gm') gm.design(itarg_list, vg_list, vmid_list, gds_load_list, vb_gm, vstar_gm_min, vds_tail_min, seg_min=seg_gm_min, stack_list=[stack_ngm]) gm_info = gm.get_dsn_info() gm1_list = gm_info['gm'] gds_in_list = gm_info['gds'] vtail_list = gm_info['vs'] seg_gm = gm_info['seg'] stack_gm = gm_info['stack'] gds1_list = [gds_in + gds_load for gds_in, gds_load in zip(gds_in_list, gds_load_list)] gain1_list = [gm1 / gds1 for gm1, gds1 in zip(gm1_list, gds1_list)] # design stage 1 tail print('designing tail') tail1.design(itarg_list, vtail_list, vout_list, vb_gm, l, seg_gm, stack_gm) tail1_info = tail1.get_dsn_info() vbias_list = [vgs_tail + vb_gm for vgs_tail in tail1_info['vgs']] # design stage 2 gm w_dict = {'load': load_info['w'], 'in': gm_info['w'], 'tail': tail1_info['w']} th_dict = {'load': load_info['intent'], 'in': gm_info['intent'], 'tail': tail1_info['intent']} stack_dict = {'tail': stack_gm, 'in': stack_gm, 'diode': stack_diode, 'ngm': stack_ngm} seg_dict = {'tail1': seg_gm, 'in': seg_gm, 'diode1': seg_diode, 'ngm1': seg_ngm, } print('designing stage 2') stage2_results = self._design_stage2(gm_db, load_db, vtail_list, vg_list, vmid_list, vout_list, vbias_list, vb_gm, vb_load, cload, cpar1, w_dict, th_dict, stack_dict, seg_dict, gm2_list, res_var, phase_margin, f_unit, max_ref_ratio) scale2 = seg_dict['diode2'] / seg_dict['diode1'] scaler = seg_dict['ref'] / seg_dict['tail1'] itot_list = [(2 * (1 + scale2) + scaler) * itarg for itarg in itarg_list] layout_info = dict( w_dict=w_dict, th_dict=th_dict, stack_dict=stack_dict, seg_dict=seg_dict, ) self._amp_info = dict( i1_size=i1_size, scale2=scale2, scaler=scaler, vtail=vtail_list, vmid=vmid_list, vbias=vbias_list, itot=itot_list, vstar=gm_info['vstar'], cin=gm_info['cgg'], gm1=gm1_list, gds1=gds1_list, gain1=gain1_list, rfb=stage2_results['rz'], cfb=stage2_results['cf'], gain_tot=stage2_results['gain'], f_3db=stage2_results['f_3db'], f_unit=stage2_results['f_unity'], phase_margin=stage2_results['phase_margin'], layout_info=layout_info, ) print('done') def get_dsn_info(self): # type: () -> Optional[Dict[str, Any]] return self._amp_info def get_specs_verification(self, top_specs): # type: (Dict[str, Any]) -> Dict[str, Any] top_specs = deepcopy(top_specs) dsn_specs = top_specs['dsn_specs'] ibias = dsn_specs['i1_unit'][0] * self._amp_info['i1_size'] * self._amp_info['scaler'] vdd = dsn_specs['vdd'] vindc = dsn_specs['vg_list'][0] voutdc = dsn_specs['vout_list'][0] f_unit = dsn_specs['f_unit'] gain_max = max(self._amp_info['gain_tot']) f_bw_log = int(np.floor(np.log10(f_unit / gain_max))) f_unit_log = int(np.ceil(np.log10(f_unit))) top_specs['layout_params'].update(self._amp_info['layout_info']) meas = top_specs['measurements'][0] meas['cfb'] = self._amp_info['cfb'] meas['rfb'] = self._amp_info['rfb'] ac_tb = meas['testbenches']['ac'] ac_tb['fstart'] = 10 ** (f_bw_log - 1) ac_tb['fstop'] = 10 ** (f_unit_log + 1) ac_sim_vars = ac_tb['sim_vars'] ac_sim_vars['vdd'] = vdd ac_sim_vars['cload'] = dsn_specs['cload'] ac_sim_vars['vincm'] = vindc ac_sim_vars['voutcm'] = voutdc ac_sim_vars['ibias'] = ibias ac_sim_vars['vdd'] = vdd ac_sim_vars['vinac'] = 1.0 ac_sim_vars['vindc'] = 0.0 """ top_specs['tb_dc']['tb_params']['vimax'] = vdd top_specs['tb_dc']['tb_params']['vimin'] = -vdd top_specs['tb_dc']['tb_params']['vindc'] = vindc top_specs['tb_dc']['tb_params']['voutcm'] = voutdc top_specs['tb_dc']['tb_params']['ibias'] = ibias top_specs['tb_dc']['tb_params']['vdd'] = vdd top_specs['tb_dc']['tb_params']['voutref'] = voutdc top_specs['tb_dc']['tb_params']['vout_start'] = -vdd + 0.15 top_specs['tb_dc']['tb_params']['vout_stop'] = vdd - 0.15 """ return top_specs def _design_stage2(self, gm_db, load_db, vtail_list, vg_list, vmid_list, vout_list, vbias_list, vb_gm, vb_load, cload, cpar1, w_dict, th_dict, stack_dict, seg_dict, gm2_list, res_var, phase_margin, f_unit, max_ref_ratio): seg_tail1 = seg_dict['tail1'] seg_diode1 = seg_dict['diode1'] seg_ngm1 = seg_dict['ngm1'] # step 1: find stage 2 unit size seg_gcd = gcd(gcd(seg_tail1, seg_diode1), seg_ngm1) if seg_gcd % 2 != 0: raise ValueError('All segment numbers must be even.') # divide seg_gcd by 2 to make sure all generated segment numbers are even seg_gcd //= 2 # make sure we have enough tail fingers for common mode feedback min_size = 2 if seg_tail1 // seg_gcd == 2 else 1 def ac_results_fun(cur_size): seg_dict['tail2'] = seg_tail1 // seg_gcd * cur_size seg_dict['diode2'] = seg_diode1 // seg_gcd * cur_size seg_dict['ngm2'] = seg_ngm1 // seg_gcd * cur_size cur_scale2 = cur_size / seg_gcd cur_gm2_list = [gm2 * cur_scale2 for gm2 in gm2_list] ac_results = self._find_rz_cf(gm_db, load_db, vtail_list, vg_list, vmid_list, vout_list, vbias_list, vb_gm, vb_load, cload, cpar1, w_dict, th_dict, stack_dict, seg_dict, cur_gm2_list, res_var, phase_margin) return ac_results def funity_fun(cur_size): ac_results_tmp = ac_results_fun(cur_size) fu_list = ac_results_tmp[0] if fu_list is None: return -1 # noinspection PyTypeChecker ans = min(fu_list) return ans # find min_size such that amplifier is stable min_bin_iter = BinaryIterator(min_size, None) while min_bin_iter.has_next(): test_size = min_bin_iter.get_next() test_fu = funity_fun(test_size) if test_fu >= 0: min_bin_iter.save() min_bin_iter.down() else: min_bin_iter.up() min_result = minimize_cost_golden(funity_fun, f_unit, offset=min_bin_iter.get_last_save()) if min_result.x is None: msg = 'Insufficient stage 1 current. funity_max=%.4g' raise StageOneCurrentError(msg % min_result.vmax) funity_list, rz_nom, cf_min, gain_list, f3db_list, pm_list = ac_results_fun(min_result.x) seg_tail2_tot = seg_dict['tail2'] seg_tail2 = (seg_tail2_tot // 4) * 2 seg_tailcm = seg_tail2_tot - seg_tail2 seg_tail_tot = 2 * (seg_dict['tail1'] + seg_tail2) seg_dict['tail2'] = seg_tail2 seg_dict['tailcm'] = seg_tailcm seg_dict['ref'] = max(2, -((-seg_tail_tot // max_ref_ratio) // 2) * 2) return dict( rz=rz_nom, cf=cf_min, gain=gain_list, f_3db=f3db_list, f_unity=funity_list, phase_margin=pm_list, ) @classmethod def _get_stage2_ss(cls, gm2_list, gds2_list, c2_list, cg2_list, cload, seg_gcd, cur_size): cur_gm2_list, cur_gds2_list, cur_c2_list, cur_cg2_list = [], [], [], [] for gm2, gds2, c2, cg2 in zip(gm2_list, gds2_list, c2_list, cg2_list): cur_gm2_list.append(gm2 * cur_size / seg_gcd) cur_gds2_list.append(gds2 * cur_size / seg_gcd) cur_c2_list.append(cload + c2 * cur_size / seg_gcd) cur_cg2_list.append(cg2 * cur_size / seg_gcd) return cur_gm2_list, cur_gds2_list, cur_c2_list, cur_cg2_list def _find_rz_cf(self, gm_db, load_db, vtail_list, vg_list, vmid_list, vout_list, vbias_list, vb_gm, vb_load, cload, cpar1, w_dict, th_dict, stack_dict, seg_dict, gm2_list, res_var, phase_margin, cap_tol=1e-15, cap_step=10e-15, cap_min=1e-15, cap_max=1e-9): """Find minimum miller cap that stabilizes the system. NOTE: This function assume phase of system for any miller cap value will not loop around 360, otherwise it may get the phase margin wrong. This assumption should be valid for this op amp. """ gz_worst = float(min(gm2_list)) gz_nom = gz_worst * (1 - res_var) # find maximum Cf needed to stabilize all corners cf_min = cap_min for env_idx, (vtail, vg, vmid, vout, vbias) in \ enumerate(zip(vtail_list, vg_list, vmid_list, vout_list, vbias_list)): cir = self._make_circuit(env_idx, gm_db, load_db, vtail, vg, vmid, vout, vbias, vb_gm, vb_load, cload, cpar1, w_dict, th_dict, stack_dict, seg_dict, gz_worst) bin_iter = FloatBinaryIterator(cf_min, None, cap_tol, search_step=cap_step) while bin_iter.has_next(): cur_cf = bin_iter.get_next() cir.add_cap(cur_cf, 'outp', 'xp') cir.add_cap(cur_cf, 'outn', 'xn') num, den = cir.get_num_den('in', 'out') cur_pm, _ = get_stability_margins(num, den) if cur_pm < phase_margin: if cur_cf > cap_max: # no way to make amplifier stable, just return return None, None, None, None, None, None bin_iter.up() else: bin_iter.save() bin_iter.down() cir.add_cap(-cur_cf, 'outp', 'xp') cir.add_cap(-cur_cf, 'outn', 'xn') # bin_iter is guaranteed to save at least one value, so don't need to worry about # cf_min being None cf_min = bin_iter.get_last_save() # find gain, unity gain bandwidth, and phase margin across corners gain_list, f3db_list, funity_list, pm_list = [], [], [], [] for env_idx, (vtail, vg, vmid, vout, vbias) in \ enumerate(zip(vtail_list, vg_list, vmid_list, vout_list, vbias_list)): cir = self._make_circuit(env_idx, gm_db, load_db, vtail, vg, vmid, vout, vbias, vb_gm, vb_load, cload, cpar1, w_dict, th_dict, stack_dict, seg_dict, gz_nom) cir.add_cap(cf_min, 'outp', 'xp') cir.add_cap(cf_min, 'outn', 'xn') num, den = cir.get_num_den('in', 'out') pn = np.poly1d(num) pd = np.poly1d(den) gain_list.append(abs(pn(0) / pd(0))) f3db_list.append(get_w_3db(num, den) / 2 / np.pi) funity_list.append(get_w_crossings(num, den)[0] / 2 / np.pi) pm_list.append(get_stability_margins(num, den)[0]) return funity_list, 1 / gz_nom, cf_min, gain_list, f3db_list, pm_list @classmethod def _make_circuit(cls, env_idx, gm_db, load_db, vtail, vg, vmid, vout, vbias, vb_gm, vb_load, cload, cpar1, w_dict, th_dict, stack_dict, seg_dict, gz, neg_cap=False, no_fb=False): cur_env = gm_db.env_list[env_idx] gm_db.set_dsn_params(w=w_dict['tail'], intent=th_dict['tail'], stack=stack_dict['tail']) tail1_params = gm_db.query(env=cur_env, vbs=0, vds=vtail - vb_gm, vgs=vbias - vb_gm) tail2_params = gm_db.query(env=cur_env, vbs=0, vds=vout - vb_gm, vgs=vbias - vb_gm) gm_db.set_dsn_params(w=w_dict['in'], intent=th_dict['in'], stack=stack_dict['in']) gm1_params = gm_db.query(env=cur_env, vbs=vb_gm - vtail, vds=vmid - vtail, vgs=vg - vtail) load_db.set_dsn_params(w=w_dict['load'], intent=th_dict['load'], stack=stack_dict['diode']) diode1_params = load_db.query(env=cur_env, vbs=0, vds=vmid - vb_load, vgs=vmid - vb_load) diode2_params = load_db.query(env=cur_env, vbs=0, vds=vout - vb_load, vgs=vmid - vb_load) load_db.set_dsn_params(stack=stack_dict['ngm']) ngm1_params = load_db.query(env=cur_env, vbs=0, vds=vmid - vb_load, vgs=vmid - vb_load) ngm2_params = load_db.query(env=cur_env, vbs=0, vds=vout - vb_load, vgs=vmid - vb_load) cir = LTICircuit() # stage 1 cir.add_transistor(tail1_params, 'tail', 'gnd', 'gnd', 'gnd', fg=seg_dict['tail1'], neg_cap=neg_cap) cir.add_transistor(gm1_params, 'midp', 'inn', 'tail', 'gnd', fg=seg_dict['in'], neg_cap=neg_cap) cir.add_transistor(gm1_params, 'midn', 'inp', 'tail', 'gnd', fg=seg_dict['in'], neg_cap=neg_cap) cir.add_transistor(diode1_params, 'midp', 'midp', 'gnd', 'gnd', fg=seg_dict['diode1'], neg_cap=neg_cap) cir.add_transistor(diode1_params, 'midn', 'midn', 'gnd', 'gnd', fg=seg_dict['diode1'], neg_cap=neg_cap) cir.add_transistor(ngm1_params, 'midn', 'midp', 'gnd', 'gnd', fg=seg_dict['ngm1'], neg_cap=neg_cap) cir.add_transistor(ngm1_params, 'midp', 'midn', 'gnd', 'gnd', fg=seg_dict['ngm1'], neg_cap=neg_cap) # stage 2 cir.add_transistor(tail2_params, 'outp', 'gnd', 'gnd', 'gnd', fg=seg_dict['tail2'], neg_cap=neg_cap) cir.add_transistor(tail2_params, 'outn', 'gnd', 'gnd', 'gnd', fg=seg_dict['tail2'], neg_cap=neg_cap) cir.add_transistor(diode2_params, 'outp', 'midn', 'gnd', 'gnd', fg=seg_dict['diode2'], neg_cap=neg_cap) cir.add_transistor(diode2_params, 'outn', 'midp', 'gnd', 'gnd', fg=seg_dict['diode2'], neg_cap=neg_cap) cir.add_transistor(ngm2_params, 'outp', 'midn', 'gnd', 'gnd', fg=seg_dict['ngm2'], neg_cap=neg_cap) cir.add_transistor(ngm2_params, 'outn', 'midp', 'gnd', 'gnd', fg=seg_dict['ngm2'], neg_cap=neg_cap) # parasitic cap cir.add_cap(cpar1, 'midp', 'gnd') cir.add_cap(cpar1, 'midn', 'gnd') # load cap cir.add_cap(cload, 'outp', 'gnd') cir.add_cap(cload, 'outn', 'gnd') # feedback resistors if not no_fb: cir.add_conductance(gz, 'xp', 'midn') cir.add_conductance(gz, 'xn', 'midp') # diff-to-single conversion cir.add_vcvs(0.5, 'inp', 'gnd', 'in', 'gnd') cir.add_vcvs(-0.5, 'inn', 'gnd', 'in', 'gnd') cir.add_vcvs(1, 'out', 'gnd', 'outp', 'outn') return cir class OpAmpTwoStageChar(MeasurementManager): def __init__(self, data_dir, # type: str meas_name, # type: str impl_lib, # type: str specs, # type: Dict[str, Any] wrapper_lookup, # type: Dict[str, str] sim_view_list, # type: Sequence[Tuple[str, str]] env_list, # type: Sequence[str] ): MeasurementManager.__init__(self, data_dir, meas_name, impl_lib, specs, wrapper_lookup, sim_view_list, env_list) def get_initial_state(self): # type: () -> str """Returns the initial FSM state.""" return 'ac0' def get_testbench_info(self, state, prev_output): rfb0 = self.specs['rfb'] cfb0 = self.specs['cfb'] find_cfb = self.specs.get('find_cfb', True) res_var = self.specs['res_var'] cmin_scale = self.specs['cmin_scale'] cmax_scale = self.specs['cmax_scale'] num_pts = self.specs['num_pts'] tmp = super(OpAmpTwoStageChar, self).get_testbench_info('ac', prev_output) tb_name, tb_type, tb_specs, tb_params = tmp if state == 'ac0' and find_cfb: cfb_list = np.linspace(cfb0 * cmin_scale, cfb0 * cmax_scale, num_pts).tolist() tb_specs['sim_vars']['rfb'] = rfb0 * (1 - res_var) tb_specs['sim_vars']['cfb'] = cfb_list else: if find_cfb: cfb = self.get_state_output('ac0')['cfb'] else: cfb = cfb0 tb_specs['sim_vars']['rfb'] = rfb0 tb_specs['sim_vars']['cfb'] = cfb return tb_name, tb_type, tb_specs, tb_params def process_output(self, state, data, tb_manager): # type: (str, Dict[str, Any], ACTB) -> Tuple[bool, str, Dict[str, Any]] phase_margin = self.specs['phase_margin'] find_cfb = self.specs.get('find_cfb', True) output_list = ['vout'] results = tb_manager.get_ugb_and_pm(data, output_list) if state == 'ac0' and find_cfb: done = False next_state = 'ac1' cfb = self._find_min_cfb(phase_margin, results) output = dict(cfb=cfb) else: done = True next_state = '' if find_cfb: cfb = self.get_state_output('ac0')['cfb'] else: cfb = self.specs['cfb'] gain_results = tb_manager.get_gain_and_w3db(data, output_list, output_dict=results) corner_list = results['corner'].tolist() gain_list = gain_results['gain_vout'].tolist() bw_list = gain_results['w3db_vout'].tolist() funity_list = results['funity_vout'].tolist() pm_list = results['pm_vout'].tolist() output = dict(cfb=cfb, corners=corner_list, gain=gain_list, bw=bw_list, funity=funity_list, pm=pm_list) return done, next_state, output @classmethod def _find_min_cfb(cls, phase_margin, results): axis_names = ['corner', 'cfb'] corner_list = results['corner'] corner_sort_arg = np.argsort(corner_list) # type: Sequence[int] # rearrange array axis sweep_vars = results['sweep_params']['pm_vout'] order = [sweep_vars.index(name) for name in axis_names] pm_data = np.transpose(results['pm_vout'], axes=order) # determine minimum cfb cfb_vec = results['cfb'] cfb_idx_min = 0 for corner_idx in corner_sort_arg: bin_iter = BinaryIterator(cfb_idx_min, cfb_vec.size) while bin_iter.has_next(): cur_cfb_idx = bin_iter.get_next() pm = pm_data[corner_idx, cur_cfb_idx] if pm >= phase_margin: bin_iter.save() bin_iter.down() else: bin_iter.up() cfb_idx_min = bin_iter.get_last_save() if cfb_idx_min is None: # No solution; cannot make amplifier stable break if cfb_idx_min is None: raise ValueError('Cannot determine cfb.') else: cfb = cfb_vec[cfb_idx_min] return cfb.item()
42.53012
100
0.549292
4,193
31,770
3.833055
0.110422
0.019039
0.0112
0.009706
0.393168
0.337295
0.274204
0.254293
0.227352
0.208624
0
0.019908
0.343846
31,770
746
101
42.587131
0.751079
0.091911
0
0.22807
0
0
0.052781
0
0
0
0
0
0
1
0.036842
false
0.001754
0.019298
0.001754
0.096491
0.026316
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
71c07edf7c5c3864d451ebab890ced63f246e9c3
3,303
py
Python
alipay/aop/api/domain/AlipayMerchantAuthDeleteModel.py
antopen/alipay-sdk-python-all
8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c
[ "Apache-2.0" ]
null
null
null
alipay/aop/api/domain/AlipayMerchantAuthDeleteModel.py
antopen/alipay-sdk-python-all
8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c
[ "Apache-2.0" ]
null
null
null
alipay/aop/api/domain/AlipayMerchantAuthDeleteModel.py
antopen/alipay-sdk-python-all
8e51c54409b9452f8d46c7bb10eea7c8f7e8d30c
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayMerchantAuthDeleteModel(object): def __init__(self): self._channel_code = None self._operator_id = None self._role = None self._scene_code = None self._user_id_list = None @property def channel_code(self): return self._channel_code @channel_code.setter def channel_code(self, value): self._channel_code = value @property def operator_id(self): return self._operator_id @operator_id.setter def operator_id(self, value): self._operator_id = value @property def role(self): return self._role @role.setter def role(self, value): self._role = value @property def scene_code(self): return self._scene_code @scene_code.setter def scene_code(self, value): self._scene_code = value @property def user_id_list(self): return self._user_id_list @user_id_list.setter def user_id_list(self, value): if isinstance(value, list): self._user_id_list = list() for i in value: self._user_id_list.append(i) def to_alipay_dict(self): params = dict() if self.channel_code: if hasattr(self.channel_code, 'to_alipay_dict'): params['channel_code'] = self.channel_code.to_alipay_dict() else: params['channel_code'] = self.channel_code if self.operator_id: if hasattr(self.operator_id, 'to_alipay_dict'): params['operator_id'] = self.operator_id.to_alipay_dict() else: params['operator_id'] = self.operator_id if self.role: if hasattr(self.role, 'to_alipay_dict'): params['role'] = self.role.to_alipay_dict() else: params['role'] = self.role if self.scene_code: if hasattr(self.scene_code, 'to_alipay_dict'): params['scene_code'] = self.scene_code.to_alipay_dict() else: params['scene_code'] = self.scene_code if self.user_id_list: if isinstance(self.user_id_list, list): for i in range(0, len(self.user_id_list)): element = self.user_id_list[i] if hasattr(element, 'to_alipay_dict'): self.user_id_list[i] = element.to_alipay_dict() if hasattr(self.user_id_list, 'to_alipay_dict'): params['user_id_list'] = self.user_id_list.to_alipay_dict() else: params['user_id_list'] = self.user_id_list return params @staticmethod def from_alipay_dict(d): if not d: return None o = AlipayMerchantAuthDeleteModel() if 'channel_code' in d: o.channel_code = d['channel_code'] if 'operator_id' in d: o.operator_id = d['operator_id'] if 'role' in d: o.role = d['role'] if 'scene_code' in d: o.scene_code = d['scene_code'] if 'user_id_list' in d: o.user_id_list = d['user_id_list'] return o
30.302752
75
0.578868
418
3,303
4.255981
0.126794
0.067454
0.112423
0.094435
0.322653
0.251827
0.082069
0.060708
0
0
0
0.000894
0.32304
3,303
108
76
30.583333
0.794723
0.012716
0
0.10989
0
0
0.085969
0
0
0
0
0
0
1
0.142857
false
0
0.021978
0.054945
0.263736
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
71c15aae1f82d17826550ce3299615cff978924d
2,206
py
Python
src/nba_analysis/pipelines/data_processing/pipeline.py
stanton119/nba-analysis
79343150edaaa97472939c47b3ce521e038871b0
[ "MIT" ]
null
null
null
src/nba_analysis/pipelines/data_processing/pipeline.py
stanton119/nba-analysis
79343150edaaa97472939c47b3ce521e038871b0
[ "MIT" ]
null
null
null
src/nba_analysis/pipelines/data_processing/pipeline.py
stanton119/nba-analysis
79343150edaaa97472939c47b3ce521e038871b0
[ "MIT" ]
1
2021-12-16T01:04:09.000Z
2021-12-16T01:04:09.000Z
""" Two pipelines: * full history * update latest season * Only updates latest season year """ from functools import partial import itertools from kedro.pipeline import Pipeline, node from nba_analysis.pipelines.data_processing import basketball_reference from . import nodes def create_pipeline(**kwargs): season_range = range(2018, 2021) download_nodes = [ node( func=partial(nodes.download_season_data, season=season), inputs=[], outputs=f"season_data_{season}", name=f"download_season_data_{season}_node", ) for season in season_range ] # month_range = ['october','november','december','january','february','march','april','may','june','july','august','september'] # download_game_log_nodes = [ # node( # func=partial(nodes.download_game_log_data, season=season, month=month), # inputs=[], # outputs=f"game_log_data_{season}_{month}", # name=f"download_game_log_data_{season}_{month}_node", # ) # for season, month in itertools.product(season_range,month_range) # ] download_game_log_nodes = [ node( func=partial( basketball_reference.get_full_season_game_log, season=season ), inputs=[], outputs=f"game_log_data_{season}", name=f"download_game_log_data_{season}_node", ) for season in season_range ] process_game_log_nodes = [ node( func=basketball_reference.process_df_game_log, inputs=f"game_log_data_{season}", outputs=f"game_log_data_{season}_int", name=f"process_game_log_data_{season}_node", ) for season in season_range ] return Pipeline( [ *download_nodes, node( func=nodes.process_season_data, inputs=[f"season_data_{season}" for season in season_range], outputs="cleaned_season_data", name="process_season_data_node", ), *download_game_log_nodes, *process_game_log_nodes, ] )
30.219178
131
0.602901
242
2,206
5.132231
0.252066
0.084541
0.070853
0.109501
0.415459
0.296296
0.23913
0.098229
0.069243
0.069243
0
0.005145
0.295104
2,206
72
132
30.638889
0.793569
0.2466
0
0.22449
0
0
0.156839
0.120973
0
0
0
0
0
1
0.020408
false
0
0.102041
0
0.142857
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
71c7397a9aa9b39fdf9e024d5ca5dfdc737b974f
1,820
py
Python
0673.GCBA-HOTEL_STAFF.py
alphacastio/connectors-gcba
d1b97fb851463694ea844b3b81402c3ea747863b
[ "MIT" ]
1
2021-11-19T21:37:01.000Z
2021-11-19T21:37:01.000Z
0673.GCBA-HOTEL_STAFF.py
alphacastio/connectors-gcba
d1b97fb851463694ea844b3b81402c3ea747863b
[ "MIT" ]
null
null
null
0673.GCBA-HOTEL_STAFF.py
alphacastio/connectors-gcba
d1b97fb851463694ea844b3b81402c3ea747863b
[ "MIT" ]
null
null
null
#!/usr/bin/env python # coding: utf-8 # In[9]: import requests import pandas as pd from lxml import etree from bs4 import BeautifulSoup import datetime import io import numpy as np from alphacast import Alphacast from dotenv import dotenv_values API_KEY = dotenv_values(".env").get("API_KEY") alphacast = Alphacast(API_KEY) # In[10]: url1 = "https://www.estadisticaciudad.gob.ar/eyc/wp-content/uploads/2020/11/Eoh_PnoA_0811.xlsx" df1 = pd.read_excel(url1) df1[:2] = df1[:2].ffill(1) df1.columns = "Personal No Asalariado - " + df1.iloc[1] + " - " + df1.iloc[2] df1 = df1.drop(df1.columns[[1]], axis = 1) df1 = df1.drop(index=1) df1 = df1.drop(index=0) df1 = df1.drop(index=2) df1 = df1.dropna(subset = [df1.columns[3]]) #df1 = df1.iloc[2: , 3:-2] #df1 = df1[~df1.iloc[:, 0].astype(str).str.isdigit()] df1 = df1[df1.columns.dropna()] df1.index = pd.date_range(start='1/1/2008', periods=len(df1), freq = "QS") df1.index.name = "Date" #df1 = df1[df1.columns.drop(list(df1.filter(regex='Participación')))] df1 # In[11]: url2 = "https://www.estadisticaciudad.gob.ar/eyc/wp-content/uploads/2018/05/Eoh_PA_0811.xlsx" df2 = pd.read_excel(url2) df2[:2] = df2[:2].ffill(1) df2.columns = "Personal Asalariado - " + df2.iloc[1] + " - " + df2.iloc[2] df2 = df2.drop(df2.columns[[1]], axis = 1) df2 = df2.drop(index=1) df2 = df2.drop(index=0) df2 = df2.drop(index=2) df2 = df2.dropna(subset = [df2.columns[3]]) #df2 = df2.iloc[2: , 3:-2] #df2 = df2[~df2.iloc[:, 0].astype(str).str.isdigit()] df2 = df2[df2.columns.dropna()] df2.index = pd.date_range(start='1/1/2008', periods=len(df2), freq = "QS") df2.index.name = "Date" df3 = df1.merge(df2, right_index=True, left_index=True) alphacast.datasets.dataset(7432).upload_data_from_df(df3, deleteMissingFromDB = True, onConflictUpdateDB = True, uploadIndex=True)
27.575758
95
0.686813
303
1,820
4.066007
0.326733
0.058442
0.032468
0.036526
0.230519
0.178571
0.13961
0.13961
0.13961
0.060065
0
0.089944
0.12033
1,820
65
96
28
0.679575
0.153297
0
0
0
0.051282
0.171354
0
0
0
0
0
0
1
0
false
0
0.230769
0
0.230769
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
71c798c6020de830cf23434ebeb38ea555cc0bd8
5,572
py
Python
simpleGmatch4py.py
aravi11/approxGed
6c0a2ed4fd1bcc86c22169e3c96fcf4de717bf8c
[ "MIT" ]
null
null
null
simpleGmatch4py.py
aravi11/approxGed
6c0a2ed4fd1bcc86c22169e3c96fcf4de717bf8c
[ "MIT" ]
null
null
null
simpleGmatch4py.py
aravi11/approxGed
6c0a2ed4fd1bcc86c22169e3c96fcf4de717bf8c
[ "MIT" ]
null
null
null
# import the GED using the munkres algorithm import gmatch4py as gm import networkx as nx import collections import csv import pickle from collections import OrderedDict import json import concurrent.futures as cf import time iter = 0 def getFinishedStatus(): iter +=1 print('*******\t' + str(iter)+ "\t*******") def getGraphDiff(files): dotFile_data_path = './DotFiles/' file1 = files.split(',')[0] file2 = files.split(',')[1] g1_name = file1.split('.')[0] # gets the name of first dotFile without its extension g2_name = file2.split('.')[0] # gets the name of second dotFile without its extension #print("\n Started pair: "+ str(g1_name) + ', ' + str(g2_name)) graph_1 = nx.drawing.nx_pydot.read_dot(str(dotFile_data_path) + str(file1)) graph_2 = nx.drawing.nx_pydot.read_dot(str(dotFile_data_path) + str(file2)) jsonData = getJsonData(graph_1, graph_2) dumpJson(jsonData, g1_name, g2_name) #print("\n >>>Finished pair: "+ str(g1_name) + ', ' + str(g2_name)) #getFinishedStatus() #print('Total time : '+str(totalTime)+ '\n') ''' def runParallelCode(pairList): with cf.ProcessPoolExecutor(max_workers =2) as executor: try: for future in cf.as_completed((executor.map(getGraphDiff, pairList, timeout=5000000)), timeout=5000000): print(str(type(future.result()))) if str(type(future.result())) == "<class 'NoneType'>": pass else: print(future.result(timeout=5000000)) except cf._base.TimeoutError: print("Time limit exceeded") pass ''' def runParallelCode(pairList): with cf.ProcessPoolExecutor(max_workers =2) as executor: try: result = executor.map(getGraphDiff, pairList, timeout=5000000) for r in result: if str(type(r)) == "<class 'NoneType'>": pass else: print(r) except cf._base.TimeoutError: print("Time limit exceeded") pass def getJsonData(graph_1,graph_2): g1_edgeList = [] g2_edgeList = [] # convert the node labels which are strings to sorted integers without affecting the node attributes. sortedIntGraph_1 = nx.relabel.convert_node_labels_to_integers(graph_1, first_label=0, ordering='sorted', label_attribute=None) sortedIntGraph_2 = nx.relabel.convert_node_labels_to_integers(graph_2, first_label=0, ordering='sorted', label_attribute=None) g1_edgeTuple = list(sortedIntGraph_1.edges(data=False)) g2_edgeTuple = list(sortedIntGraph_2.edges(data=False)) # get graph edge lists for i in g1_edgeTuple: g1_edgeList.append(list(i)) for i in g2_edgeTuple: g2_edgeList.append(list(i)) # get graph attributes in the ascending order as the node labels nodeLabelList_g1 = [] nodeLabelList_g2 = [] nodeList_g1 = list(sortedIntGraph_1.nodes(data=True)) nodeList_g2 = list(sortedIntGraph_2.nodes(data=True)) for i in range(len(nodeList_g1)): if nodeList_g1[i][0] == i: nodeLabelList_g1.insert(i, nodeList_g1[i][1].get('label').replace('"', '')) for i in range(len(nodeList_g2)): if nodeList_g2[i][0] == i: nodeLabelList_g2.insert(i, nodeList_g2[i][1].get('label').replace('"', '')) # get graph edit distance #ged = nx.graph_edit_distance(sortedIntGraph_1, sortedIntGraph_2, node_match=return_eq) Commented since its too time expensive #Gmatch4py code for calculating ged #abs_ged = gm.BP_2(1,1,1,1) ged=gm.GraphEditDistance(1,1,1,1) # all edit costs are equal to 1 #hed = gm.HED(1,1,1,1) result = ged.compare([sortedIntGraph_1, sortedIntGraph_2], None) # generate the json files jsonDict = {} jsonDict["graph_1"] = g1_edgeList jsonDict["graph_2"] = g2_edgeList jsonDict["labels_1"] = nodeLabelList_g1 jsonDict["labels_2"] = nodeLabelList_g2 jsonDict["ged"] = int(result[0][1]) #print(jsonDict) return jsonDict def return_eq(node1, node2): #function to compare the node labels return node1['label']==node2['label'] def dumpJson(jsonFile, g1, g2): #function to dump the Json files outPath = './outFiles/' with open(str(outPath)+ str(g1) + '::::'+ str(g2) + '.json', 'w') as fp: json.dump(jsonFile, fp) def main(): #main function from where the program starts dotFileList= [] #dotFile_data_path = './DotFiles/test' with open('./filenames.txt', 'r') as csvFile: reader = csv.reader(csvFile) for row in reader: dotName = str(row).replace('[', '').replace(']','').replace("'","").strip() dotFileList.append(dotName) print("Total number of graph files: " + str(len(dotFileList))) counter = 0 len_dotFileList = len(dotFileList) totalGraphJsons = len_dotFileList * len_dotFileList #total number of graph similarity json samples print("Total Graph Similarity json samples: " + str(int(totalGraphJsons))) pairList = [] #Code for generating graph Similarity json. Takes a non-symmetric pair of graphs from a list and returns their json data for dotFile_i in dotFileList: for dotFile_j in dotFileList: pairList.append(str(dotFile_i + ','+ str(dotFile_j))) print("<<<<<<<<<<<<<<<<<<<<<< " + str(len(pairList))) runParallelCode(pairList) if __name__ == '__main__': start_time = time.time() main() print("--- %s seconds ---" % (time.time() - start_time))
32.395349
130
0.644113
716
5,572
4.863128
0.26676
0.005169
0.005169
0.003446
0.246123
0.208214
0.158817
0.14618
0.097932
0.097932
0
0.02982
0.223618
5,572
171
131
32.584795
0.775081
0.203877
0
0.021505
0
0
0.076005
0.005707
0
0
0
0
0
1
0.075269
false
0.021505
0.096774
0.010753
0.193548
0.075269
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
71c80c035280e16e1aaf199b5f9834181e50b2ad
1,940
py
Python
src/blockdiag/utils/rst/nodes.py
Dridi/blockdiag
bbb16f8a731cdf79a675a63c1ff847e70fdc4a5b
[ "Apache-2.0" ]
null
null
null
src/blockdiag/utils/rst/nodes.py
Dridi/blockdiag
bbb16f8a731cdf79a675a63c1ff847e70fdc4a5b
[ "Apache-2.0" ]
null
null
null
src/blockdiag/utils/rst/nodes.py
Dridi/blockdiag
bbb16f8a731cdf79a675a63c1ff847e70fdc4a5b
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright 2011 Takeshi KOMIYA # # 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 os from hashlib import sha1 from docutils import nodes import blockdiag.parser import blockdiag.builder import blockdiag.drawer class blockdiag(nodes.General, nodes.Element): name = 'blockdiag' processor = blockdiag def to_diagram(self): try: tree = self.processor.parser.parse_string(self['code']) except: code = '%s { %s }' % (self.name, self['code']) tree = self.processor.parser.parse_string(code) self['code'] = code # replace if succeeded return self.processor.builder.ScreenNodeBuilder.build(tree) def to_drawer(self, image_format, filename, fontmap, **kwargs): diagram = self.to_diagram() return self.processor.drawer.DiagramDraw(image_format, diagram, filename, fontmap=fontmap, **kwargs) def get_path(self, **options): options.update(self['options']) hashseed = (self['code'] + str(options)).encode('utf-8') hashed = sha1(hashseed).hexdigest() filename = "%s-%s.%s" % (self.name, hashed, options['format'].lower()) outputdir = options.get('outputdir') if outputdir: filename = os.path.join(outputdir, filename) return filename
35.272727
78
0.640206
233
1,940
5.296137
0.493562
0.048622
0.02107
0.025932
0.055105
0.055105
0
0
0
0
0
0.00831
0.25567
1,940
54
79
35.925926
0.84626
0.31134
0
0
0
0
0.052273
0
0
0
0
0
0
1
0.096774
false
0
0.193548
0
0.483871
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
71c81073e9fc83a90c2d12dc9cb29a2d00b1831d
1,355
py
Python
python-advanced/chp1/main.py
emiliachojak/bio-projects
d2e5290b48613ef6721e303b3490a98cf4cbf6c0
[ "MIT" ]
2
2019-12-11T20:55:46.000Z
2020-06-17T14:01:07.000Z
python-advanced/chp1/main.py
emiliachojak/bio-projects
d2e5290b48613ef6721e303b3490a98cf4cbf6c0
[ "MIT" ]
null
null
null
python-advanced/chp1/main.py
emiliachojak/bio-projects
d2e5290b48613ef6721e303b3490a98cf4cbf6c0
[ "MIT" ]
1
2019-12-11T20:58:45.000Z
2019-12-11T20:58:45.000Z
# -*- coding: utf-8 -*- """ Created on Thu Dec 19 20:00:00 2019 @author: Emilia Chojak @e-mail: emilia.chojak@gmail.com """ tax_dict = { 'Pan troglodytes' : 'Hominoidea', 'Pongo abelii' : 'Hominoidea', 'Hominoidea' : 'Simiiformes', 'Simiiformes' : 'Haplorrhini', 'Tarsius tarsier' : 'Tarsiiformes', 'Haplorrhini' : 'Primates', 'Tarsiiformes' : 'Haplorrhini', 'Loris tardigradus' : 'Lorisidae', 'Lorisidae' : 'Strepsirrhini', 'Strepsirrhini' : 'Primates', 'Allocebus trichotis' : 'Lemuriformes', 'Lemuriformes' : 'Strepsirrhini', 'Galago alleni' : 'Lorisiformes', 'Lorisiformes' : 'Strepsirrhini', 'Galago moholi' : 'Lorisiformes' } def find_ancestors(taxon): if taxon == 'Primates': return [taxon] parent = tax_dict[taxon] parent_ancestors = find_ancestors(parent) return [taxon] + parent_ancestors def find_ancestors_for_many(taxon_list): many_parents = [] for taxon in taxon_list: many_parents.append(find_ancestors(taxon)) return many_parents def last_common_ancestor(many_parents): for parent in many_parents[0]: is_ok = True for parent_list in many_parents: if parent not in parent_list: is_ok = False if is_ok == True: return parent print(last_common_ancestor(find_ancestors_for_many(["Galago alleni", "Galago moholi"])))
30.111111
88
0.677491
153
1,355
5.803922
0.424837
0.074324
0.036036
0.045045
0
0
0
0
0
0
0
0.012821
0.194096
1,355
45
88
30.111111
0.800366
0.084871
0
0.060606
0
0
0.318735
0
0
0
0
0
0
1
0.090909
false
0
0
0
0.212121
0.030303
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
71c859d9d13c7c86199e6c92e91a1441fbf8c1ae
334
py
Python
Python/csv/1.py
LeishenKOBE/good-good-study
ac6b859f53b8b95f0746f35c5278009a5cad40a8
[ "MIT" ]
null
null
null
Python/csv/1.py
LeishenKOBE/good-good-study
ac6b859f53b8b95f0746f35c5278009a5cad40a8
[ "MIT" ]
null
null
null
Python/csv/1.py
LeishenKOBE/good-good-study
ac6b859f53b8b95f0746f35c5278009a5cad40a8
[ "MIT" ]
null
null
null
import csv # with open('./1.csv', newline='', encoding='utf-8') as f: # reader = csv.reader(f) # for row in reader: # print(row) with open('./1.csv', 'a', encoding='utf-8') as f: writer = csv.writer(f) writer.writerow(['4', '猫砂', '25', '1022', '886']) writer.writerow(['5', '猫罐头', '18', '2234', '3121'])
27.833333
58
0.535928
50
334
3.58
0.58
0.089385
0.100559
0.134078
0.167598
0
0
0
0
0
0
0.09434
0.206587
334
11
59
30.363636
0.581132
0.374252
0
0
0
0
0.191176
0
0
0
0
0
0
1
0
false
0
0.2
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
71c9afc9f2fd7d8896cef3ef910e93c309b9fb9f
1,845
py
Python
python/data_structures/binheap.py
adriennekarnoski/data-structures
86ccf988ac02884749226236ad4ac37762873efa
[ "MIT" ]
1
2017-11-05T20:59:04.000Z
2017-11-05T20:59:04.000Z
python/data_structures/binheap.py
adriennekarnoski/data-structures
86ccf988ac02884749226236ad4ac37762873efa
[ "MIT" ]
5
2017-12-15T01:37:47.000Z
2018-02-20T22:51:29.000Z
python/data_structures/binheap.py
adriennekarnoski/data-structures
86ccf988ac02884749226236ad4ac37762873efa
[ "MIT" ]
null
null
null
"""Build a binary min heap object.""" from math import floor class BinaryHeap(object): """Create a Binary Heap object as a Min Heap.""" def __init__(self): """Initialize the heap list to be used by Binary Heap.""" self._heap_list = [] def push(self, val): """Add new value to heap list and run check heap method.""" self._heap_list.append(val) if len(self._heap_list) == 2: self._small_heap() self._check_heap() def _small_heap(self): heap = self._heap_list if heap[0] > heap[1]: heap[0], heap[1] = heap[1], heap[0] return heap def _check_heap(self): """Check all the children are less than their parents.""" heap = self._heap_list index = floor((len(heap) - 1) / 2) i = 0 while i < index: l = (2 * i) + 1 if heap[i] > heap[l]: heap[i], heap[l] = heap[l], heap[i] try: r = (2 * i) + 2 if heap[i] > heap[r]: heap[i], heap[r] = heap[r], heap[i] except IndexError: # pragma: no cover pass i += 1 return heap def pop(self): """Remove top value of heap and run check heap method.""" try: heap = self._heap_list index = len(heap) - 1 heap[0], heap[index] = heap[index], heap[0] self._heap_list.pop() if len(self._heap_list) == 2: self._small_heap() self._check_heap() return heap except IndexError: raise IndexError('Nothing available to pop') def _display(self): # pragma: no cover """Make it easier during testing.""" for item in self._heap_list: print(item)
30.245902
67
0.505149
241
1,845
3.721992
0.319502
0.098105
0.120401
0.071349
0.287625
0.098105
0.098105
0.098105
0.098105
0.098105
0
0.016507
0.376152
1,845
60
68
30.75
0.762815
0.189702
0
0.355556
0
0
0.016461
0
0
0
0
0
0
1
0.133333
false
0.022222
0.022222
0
0.244444
0.022222
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
71ca38941354160e243965319c30a6e676cdeb33
1,547
py
Python
vesper/archive_settings.py
RichardLitt/Vesper
5360844f42a06942e7684121c650b08cf8616285
[ "MIT" ]
29
2017-07-10T14:49:15.000Z
2022-02-02T23:14:38.000Z
vesper/archive_settings.py
Tubbz-alt/Vesper
76e5931ca0c7fbe070c53b1362ec246ec9007beb
[ "MIT" ]
167
2015-03-17T14:45:22.000Z
2022-03-30T21:00:05.000Z
vesper/archive_settings.py
Tubbz-alt/Vesper
76e5931ca0c7fbe070c53b1362ec246ec9007beb
[ "MIT" ]
4
2015-02-06T03:30:27.000Z
2020-12-27T08:38:52.000Z
""" Vesper archive settings. The Vesper server serves the Vesper archive that is in the directory in which the server starts. The archive settings are the composition of a set of default settings (hard-coded in this module) and settings (optionally) specified in the file "Archive Settings.yaml" in the archive directory. """ from pathlib import Path import os import sys from vesper.util.settings import Settings from vesper.util.settings_type import SettingsType import vesper.archive_paths as archive_paths _DEFAULT_SETTINGS = Settings.create_from_yaml(''' database: engine: SQLite ''') _SETTINGS_TYPE = SettingsType('Archive Settings', _DEFAULT_SETTINGS) _SETTINGS_FILE_NAME = 'Archive Settings.yaml' def _create_settings(): archive_dir_path = Path(os.getcwd()) settings = _load_settings_file(archive_dir_path) archive_paths.initialize(archive_dir_path, settings) return settings def _load_settings_file(archive_dir_path): file_path = archive_dir_path / _SETTINGS_FILE_NAME if not file_path.exists(): # settings file doex not exist return _SETTINGS_TYPE.defaults else: # settings file exists try: return _SETTINGS_TYPE.create_settings_from_yaml_file(file_path) except Exception as e: print(( 'Load failed for settings file "{}". Error message ' 'was: {}').format(file_path, str(e))) sys.exit(1) archive_settings = _create_settings()
24.555556
75
0.701357
195
1,547
5.302564
0.358974
0.081238
0.067698
0.042553
0.058027
0.058027
0
0
0
0
0
0.00084
0.230123
1,547
62
76
24.951613
0.867338
0.238526
0
0
0
0
0.106074
0
0
0
0
0
0
1
0.066667
false
0
0.2
0
0.366667
0.033333
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
71ca8311a73312ae9b4e292ad1989e57d088b408
9,841
py
Python
autotf/model/vgg16.py
DAIM-ML/autotf
3f82d858f49c27d5ecb624cee555fb8fd47bf067
[ "BSD-3-Clause" ]
8
2018-03-07T06:58:16.000Z
2019-01-30T07:49:44.000Z
autotf/model/vgg16.py
DAIM-ML/autotf
3f82d858f49c27d5ecb624cee555fb8fd47bf067
[ "BSD-3-Clause" ]
null
null
null
autotf/model/vgg16.py
DAIM-ML/autotf
3f82d858f49c27d5ecb624cee555fb8fd47bf067
[ "BSD-3-Clause" ]
1
2018-03-31T09:06:12.000Z
2018-03-31T09:06:12.000Z
#-*- coding=utf-8 -*- from __future__ import division, print_function, absolute_import from base_model import BaseModel from helper import * import tensorflow as tf import pickle import numpy as np import time class Vgg16(BaseModel): default_param = { "loss" : "square_loss", "metrics" : ["loss"], "optimizer" : "sgd", "learning_rate" : 1e-2, "batch_size" : 100, "num_epochs" : 25, "keep_prob":0.75 } def __init__(self,classnum): self.class_num = classnum self.model = None self.sess = tf.Session() self.scope = {} self.summary = [] def conv2d(self,layer_name,inputs, out_channels, kernel_size, strides=1, padding='SAME'): in_channels = inputs.get_shape()[-1] with tf.variable_scope(layer_name) as scope: self.scope[layer_name] = scope w = tf.get_variable(name='weights', trainable=True, shape=[kernel_size, kernel_size, in_channels, out_channels], initializer=tf.contrib.layers.xavier_initializer()) b = tf.get_variable(name='biases', trainable=True, shape=[out_channels], initializer=tf.constant_initializer(0.0)) inputs = tf.nn.conv2d(inputs, w, [1, strides, strides, 1], padding=padding, name='conv') inputs = tf.nn.bias_add(inputs, b, name='bias_add') inputs = tf.nn.relu(inputs, name='relu') return inputs def max_pool(self, layer_name, inputs, pool_size, strides, padding='SAME'): with tf.name_scope(layer_name): return tf.nn.max_pool(inputs, [1, pool_size, pool_size, 1], [1, strides, strides, 1], padding=padding, name=layer_name) def avg_pool(self, layer_name, inputs, pool_size, strides, padding='SAME'): with tf.name_scope(layer_name): return tf.nn.avg_pool(inputs, [1, pool_size, pool_size, 1], [1, strides, strides, 1], padding=padding, name=layer_name) def lrn(self, layer_name, inputs, depth_radius=5, alpha=0.0001, beta=0.75): with tf.name_scope(layer_name): return tf.nn.local_response_normalization(name='pool1_norm1', input=inputs, depth_radius=depth_radius, alpha=alpha, beta=beta) def concat(self, layer_name, inputs): with tf.name_scope(layer_name): one_by_one = inputs[0] three_by_three = inputs[1] five_by_five = inputs[2] pooling = inputs[3] return tf.concat([one_by_one, three_by_three, five_by_five, pooling], axis=3) def dropout(self, layer_name, inputs, keep_prob): # dropout_rate = 1 - keep_prob with tf.name_scope(layer_name): return tf.nn.dropout(name=layer_name, x=inputs, keep_prob=keep_prob) def bn(self, layer_name, inputs, epsilon=1e-3): with tf.name_scope(layer_name): batch_mean, batch_var = tf.nn.moments(inputs, [0]) inputs = tf.nn.batch_normalization(inputs, mean=batch_mean, variance=batch_var, offset=None, scale=None, variance_epsilon=epsilon) return inputs def fc(self, layer_name, inputs, out_nodes): shape = inputs.get_shape() if len(shape) == 4: # x is 4D tensor size = shape[1].value * shape[2].value * shape[3].value else: # x has already flattened size = shape[-1].value with tf.variable_scope(layer_name) as scope: self.scope[layer_name] = scope w = tf.get_variable('weights', shape=[size, out_nodes], initializer=tf.contrib.layers.xavier_initializer()) b = tf.get_variable('biases', shape=[out_nodes], initializer=tf.constant_initializer(0.0)) flat_x = tf.reshape(inputs, [-1, size]) inputs = tf.nn.bias_add(tf.matmul(flat_x, w), b) inputs = tf.nn.relu(inputs) return inputs def build_model(self): # 训练数据 self.inputs = tf.placeholder(tf.float32, shape=[None, 224, 224, 3]) # 训练标签数据 self.labels = tf.placeholder(tf.float32, shape=[None, self.class_num]) # dropout self.keep_prob = tf.placeholder(tf.float32) self.conv1_1 = self.conv2d("conv1_1",self.inputs,64,3) self.conv1_2 = self.conv2d("conv1_2",self.conv1_1, 64,3) self.pool1 = self.max_pool('pool1',self.conv1_2,pool_size=2,strides=2) #112*112*64 self.conv2_1 = self.conv2d("conv2_1",self.pool1, 128,3) self.conv2_2 = self.conv2d( "conv2_2",self.conv2_1, 128,3) self.pool2 = self.max_pool("pool2",self.conv2_2,pool_size=2,strides=2) #56*56*128 self.conv3_1 = self.conv2d("conv3_1",self.pool2, 256,3) self.conv3_2 = self.conv2d("conv3_2",self.conv3_1, 256,3) self.conv3_3 = self.conv2d("conv3_3",self.conv3_2, 256, 3) self.pool3 = self.max_pool("pool3",self.conv3_3,pool_size=2,strides=2) #28*28*256 self.conv4_1 = self.conv2d("conv4_1",self.pool3, 512, 3) self.conv4_2 = self.conv2d("conv4_2",self.conv4_1, 512, 3) self.conv4_3 = self.conv2d("conv4_3",self.conv4_2, 512, 3) self.pool4 = self.max_pool("pool4",self.conv4_3, pool_size=2,strides=2) #14*14*512 self.conv5_1 = self.conv2d("conv5_1",self.pool4, 512, 3) self.conv5_2 = self.conv2d("conv5_2",self.conv5_1, 512, 3) self.conv5_3 = self.conv2d("conv5_3",self.conv5_2, 512, 3) self.pool5 = self.max_pool( 'pool5',self.conv5_3,pool_size=2,strides=2) #7*7*512 self.fc6 = self.fc("fc6",self.pool5,4096) # 25088 = 7*7*512 self.relu6 = tf.nn.dropout(self.fc6, self.keep_prob) self.fc7 = self.fc("fc7",self.relu6,4096) self.relu7 = tf.nn.dropout(self.fc7, self.keep_prob) self.pred = self.fc("fc8",self.relu7, self.class_num) def set_parameter(self, param): for name in self.default_param: if name not in param: param[name] = self.default_param[name] self.build_model() # 定义交叉熵损失函数 self.keep_prob_value = param["keep_prob"] loss_fun = param["loss"] self.loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=self.pred, labels=self.labels)) optimizer = param["optimizer"] self.learning_rate = param["learning_rate"] self.optimizer = tf.train.RMSPropOptimizer(self.learning_rate).minimize(self.loss) self.correct_prediction = tf.equal(tf.argmax(self.pred, 1), tf.argmax(self.labels, 1)) self.accuracy = tf.reduce_mean(tf.cast(self.correct_prediction, tf.float32)) self.batch_size = param["batch_size"] self.num_epochs = param["num_epochs"] def get_batch(self, feed_data): X = feed_data["inputs"] Y = feed_data["labels"] totalbatch = int(len(X)/self.batch_size)+1 if (totalbatch * self.batch_size == len(X)): totalbatch = totalbatch - 1 for i in range(0,totalbatch): startindex = i*self.batch_size endindex = (i+1)*self.batch_size batch_xs = X[startindex:endindex] batch_ys = Y[startindex:endindex] yield { "batch_xs" : batch_xs, "batch_ys" : batch_ys } def train(self, feed_data): self.sess.run(tf.global_variables_initializer()) trainstep = 0 for epoch in range(self.num_epochs): avg_cost = 0.0 totalaccuracy = 0.0 for batch in self.get_batch(feed_data): feed_dict = { self.inputs : batch["batch_xs"], self.labels : batch["batch_ys"], self.keep_prob: self.keep_prob_value, } _, loss, acc = self.sess.run([self.optimizer, self.loss,self.accuracy], feed_dict=feed_dict) totalaccuracy += acc*len(batch["batch_xs"]) avg_cost += loss trainstep = trainstep + 1 totalaccuracy /= len(feed_data['inputs']) print("train_step"+"\t"+str(trainstep)+"\t"+"epoch:"+"\t"+str(epoch+1)+"\t"+"accuracy:"+"\t"+str(totalaccuracy)+"\t"+"loss:"+"\t"+str(avg_cost)) def model_load(self,path): saver = tf.train.Saver() saver.restore(self.sess, path) return def model_save(self,path): saver = tf.train.Saver() saver.save(self.sess, path) return def evaluate(self, feed_data): avg_loss = 0.0 totalaccuracy = 0.0 totallen = len(feed_data["inputs"]) for batch in self.get_batch(feed_data): feed_dict = { self.inputs: batch["batch_xs"], self.labels: batch["batch_ys"], self.keep_prob:self.keep_prob_value } loss, acc = self.sess.run([self.loss, self.accuracy], feed_dict=feed_dict) totalaccuracy += acc * len(batch["batch_xs"]) avg_loss += loss avg_loss /= totallen totalaccuracy /= len(feed_data['inputs']) res = {"accuracy":totalaccuracy,"loss":avg_loss} return res def predict(self, feed_data): res = [] for batch in self.get_batch(feed_data): feed_dict = { self.inputs: batch["batch_xs"] } pred = self.sess.run(self.pred, feed_dict=feed_dict) res.extend(pred.tolist()) return res
39.681452
156
0.580124
1,291
9,841
4.226956
0.173509
0.034634
0.025655
0.027854
0.314825
0.268279
0.219168
0.201942
0.201942
0.189481
0
0.045919
0.294076
9,841
247
157
39.842105
0.7396
0.018088
0
0.225131
0
0
0.050062
0
0
0
0
0
0
1
0.089005
false
0
0.036649
0
0.198953
0.010471
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
71cad3858a3b017c8adbe9bb0a7f32ee389c518f
3,226
py
Python
LEGEND/modules/_exec.py
RAJESHSAINI2113/LEGENDX
82c3c61062e804c3bf8b6e4ee31d1e603ab8bfd0
[ "MIT" ]
2
2021-03-01T03:50:22.000Z
2021-03-05T07:13:19.000Z
LEGEND/modules/_exec.py
RAJESHSAINI2113/LEGENDX
82c3c61062e804c3bf8b6e4ee31d1e603ab8bfd0
[ "MIT" ]
null
null
null
LEGEND/modules/_exec.py
RAJESHSAINI2113/LEGENDX
82c3c61062e804c3bf8b6e4ee31d1e603ab8bfd0
[ "MIT" ]
5
2021-03-01T08:40:31.000Z
2021-10-01T16:32:04.000Z
import subprocess from LEGEND import tbot as bot from LEGEND import tbot as borg from LEGEND.events import register from LEGEND import OWNER_ID, SUDO_USERS import asyncio import traceback import io import os import sys import time from telethon.tl import functions from telethon.tl import types from telethon.tl.types import * from telethon.errors import * @register(pattern="^/bash (.*)") async def msg(event): if event.sender_id == OWNER_ID: pass else: return PROCESS_RUN_TIME = 100 cmd = event.pattern_match.group(1) reply_to_id = event.message.id if event.reply_to_msg_id: reply_to_id = event.reply_to_msg_id time.time() + PROCESS_RUN_TIME process = await asyncio.create_subprocess_shell( cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE ) stdout, stderr = await process.communicate() e = stderr.decode() if not e: e = "No Error" o = stdout.decode() if not o: o = "**Tip**: \n`If you want to see the results of your code, I suggest printing them to stdout.`" else: _o = o.split("\n") o = "`\n".join(_o) await event.reply(f"**QUERY:**\n__Command:__\n`{cmd}` \n__PID:__\n`{process.pid}`\n\n**stderr:** \n`{e}`\n**Output:**\n{o}" ) @register(pattern="^/eval") async def _(event): if event.sender_id == OWNER_ID: pass elif event.sender_id in SUDO_USERS: pass else: return cmd = event.text.split(" ", maxsplit=1)[1] reply_to_id = event.message.id if event.reply_to_msg_id: reply_to_id = event.reply_to_msg_id old_stderr = sys.stderr old_stdout = sys.stdout redirected_output = sys.stdout = io.StringIO() redirected_error = sys.stderr = io.StringIO() stdout, stderr, exc = None, None, None try: await aexec(cmd, event) except Exception: exc = traceback.format_exc() stdout = redirected_output.getvalue() stderr = redirected_error.getvalue() sys.stdout = old_stdout sys.stderr = old_stderr evaluation = "" if exc: evaluation = exc elif stderr: evaluation = stderr elif stdout: evaluation = stdout else: evaluation = "Success" final_output = "**EVAL**: `{}` \n\n **OUTPUT**: \n`{}` \n".format(cmd, evaluation) MAX_MESSAGE_SIZE_LIMIT = 4095 if len(final_output) > MAX_MESSAGE_SIZE_LIMIT: with io.BytesIO(str.encode(final_output)) as out_file: out_file.name = "eval.text" await bot.send_file( event.chat_id, out_file, force_document=True, allow_cache=False, caption=cmd, reply_to=reply_to_id, ) else: await event.reply(final_output) async def aexec(code, smessatatus): message = event = smessatatus def p(_x): return print(slitu.yaml_format(_x)) reply = await event.get_reply_message() exec( "async def __aexec(message, reply, client, p): " + "\n event = smessatatus = message" + "".join(f"\n {l}" for l in code.split("\n")) ) return await locals()["__aexec"](message, reply, bot, p)
27.810345
127
0.623993
433
3,226
4.454965
0.30485
0.036288
0.023328
0.029031
0.12649
0.103681
0.103681
0.103681
0.07154
0.07154
0
0.0042
0.261934
3,226
115
128
28.052174
0.805964
0
0
0.176471
0
0.019608
0.116243
0.030998
0
0
0
0
0
1
0.009804
false
0.029412
0.147059
0.009804
0.196078
0.019608
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
71cd65bd2b7c6ec78dfa4527145f67145398f409
14,872
py
Python
src/python/pants/base/specs.py
mcguigan/pants
e085d45669b72d0c51ab8a54602306fc76e07256
[ "Apache-2.0" ]
null
null
null
src/python/pants/base/specs.py
mcguigan/pants
e085d45669b72d0c51ab8a54602306fc76e07256
[ "Apache-2.0" ]
null
null
null
src/python/pants/base/specs.py
mcguigan/pants
e085d45669b72d0c51ab8a54602306fc76e07256
[ "Apache-2.0" ]
null
null
null
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import os import re from abc import ABC, ABCMeta, abstractmethod from dataclasses import dataclass from typing import ( TYPE_CHECKING, Dict, Iterable, Iterator, List, Optional, Sequence, Tuple, Union, cast, ) from pants.engine.fs import PathGlobs from pants.engine.objects import Collection from pants.option.custom_types import GlobExpansionConjunction from pants.option.global_options import GlobMatchErrorBehavior from pants.util.collections import assert_single_element from pants.util.dirutil import fast_relpath_optional, recursive_dirname from pants.util.filtering import create_filters, wrap_filters from pants.util.memo import memoized_property from pants.util.meta import frozen_after_init if TYPE_CHECKING: from pants.engine.mapper import AddressFamily, AddressMapper class Spec(ABC): """A specification for what Pants should operate on.""" @abstractmethod def to_spec_string(self) -> str: """Return the normalized string representation of this spec.""" class AddressSpec(Spec, metaclass=ABCMeta): """Represents address selectors as passed from the command line. Supports `Single` target addresses as well as `Sibling` (:) and `Descendant` (::) selector forms. Note: In general, 'spec' should not be a user visible term, it is usually appropriate to substitute 'address' for a spec resolved to an address, or 'address selector' if you are referring to an unresolved spec string. """ class AddressFamilyResolutionError(Exception): pass @abstractmethod def matching_address_families( self, address_families_dict: Dict[str, "AddressFamily"], ) -> List["AddressFamily"]: """Given a dict of (namespace path) -> AddressFamily, return the values matching this address spec. :raises: :class:`AddressSpec.AddressFamilyResolutionError` if no address families matched this spec. """ @classmethod def address_families_for_dir( cls, address_families_dict: Dict[str, "AddressFamily"], spec_dir_path: str ) -> List["AddressFamily"]: """Implementation of `matching_address_families()` for address specs matching at most one directory.""" maybe_af = address_families_dict.get(spec_dir_path, None) if maybe_af is None: raise cls.AddressFamilyResolutionError( 'Path "{}" does not contain any BUILD files.' .format(spec_dir_path)) return [maybe_af] class AddressResolutionError(Exception): pass @abstractmethod def address_target_pairs_from_address_families(self, address_families: List["AddressFamily"]): """Given a list of AddressFamily, return (address, target) pairs matching this address spec. :raises: :class:`SingleAddress._SingleAddressResolutionError` for resolution errors with a :class:`SingleAddress` instance. :raises: :class:`AddressSpec.AddressResolutionError` if no targets could be found otherwise, if the address spec type requires a non-empty set of targets. :return: list of (Address, Target) pairs. """ @classmethod def all_address_target_pairs(cls, address_families): """Implementation of `address_target_pairs_from_address_families()` which does no filtering.""" addr_tgt_pairs = [] for af in address_families: addr_tgt_pairs.extend(af.addressables.items()) return addr_tgt_pairs @abstractmethod def make_glob_patterns(self, address_mapper: "AddressMapper") -> List[str]: """Generate glob patterns matching exactly all the BUILD files this address spec covers.""" @classmethod def globs_in_single_dir(cls, spec_dir_path: str, address_mapper: "AddressMapper") -> List[str]: """Implementation of `make_glob_patterns()` which only allows a single base directory.""" return [os.path.join(spec_dir_path, pat) for pat in address_mapper.build_patterns] @dataclass(frozen=True) class SingleAddress(AddressSpec): """An AddressSpec for a single address.""" directory: str name: str def __post_init__(self) -> None: if self.directory is None: raise ValueError(f'A SingleAddress must have a directory. Got: {self}') if self.name is None: raise ValueError(f'A SingleAddress must have a name. Got: {self}') def to_spec_string(self) -> str: return '{}:{}'.format(self.directory, self.name) def matching_address_families( self, address_families_dict: Dict[str, "AddressFamily"] ) -> List["AddressFamily"]: return self.address_families_for_dir(address_families_dict, self.directory) class _SingleAddressResolutionError(Exception): def __init__(self, single_address_family: "AddressFamily", name: str) -> None: super().__init__() self.single_address_family = single_address_family self.name = name def address_target_pairs_from_address_families(self, address_families: Sequence["AddressFamily"]): """Return the pair for the single target matching the single AddressFamily, or error. :raises: :class:`SingleAddress._SingleAddressResolutionError` if no targets could be found for a :class:`SingleAddress` instance. :return: list of (Address, Target) pairs with exactly one element. """ single_af = assert_single_element(address_families) addr_tgt_pairs = [ (addr, tgt) for addr, tgt in single_af.addressables.items() if addr.target_name == self.name ] if len(addr_tgt_pairs) == 0: raise self._SingleAddressResolutionError(single_af, self.name) # There will be at most one target with a given name in a single AddressFamily. assert(len(addr_tgt_pairs) == 1) return addr_tgt_pairs def make_glob_patterns(self, address_mapper: "AddressMapper") -> List[str]: return self.globs_in_single_dir(self.directory, address_mapper) @dataclass(frozen=True) class SiblingAddresses(AddressSpec): """An AddressSpec representing all addresses located directly within the given directory.""" directory: str def to_spec_string(self) -> str: return f'{self.directory}:' def matching_address_families( self, address_families_dict: Dict[str, "AddressFamily"], ) -> List["AddressFamily"]: return self.address_families_for_dir(address_families_dict, self.directory) def address_target_pairs_from_address_families(self, address_families: Sequence["AddressFamily"]): return self.all_address_target_pairs(address_families) def make_glob_patterns(self, address_mapper: "AddressMapper") -> List[str]: return self.globs_in_single_dir(self.directory, address_mapper) @dataclass(frozen=True) class DescendantAddresses(AddressSpec): """An AddressSpec representing all addresses located recursively under the given directory.""" directory: str def to_spec_string(self) -> str: return f'{self.directory}::' def matching_address_families( self, address_families_dict: Dict[str, "AddressFamily"], ) -> List["AddressFamily"]: return [ af for ns, af in address_families_dict.items() if fast_relpath_optional(ns, self.directory) is not None ] def address_target_pairs_from_address_families(self, address_families: Sequence["AddressFamily"]): addr_tgt_pairs = self.all_address_target_pairs(address_families) if len(addr_tgt_pairs) == 0: raise self.AddressResolutionError('AddressSpec {} does not match any targets.'.format(self)) return addr_tgt_pairs def make_glob_patterns(self, address_mapper: "AddressMapper") -> List[str]: return [os.path.join(self.directory, '**', pat) for pat in address_mapper.build_patterns] @dataclass(frozen=True) class AscendantAddresses(AddressSpec): """An AddressSpec representing all addresses located recursively _above_ the given directory.""" directory: str def to_spec_string(self) -> str: return f'{self.directory}^' def matching_address_families( self, address_families_dict: Dict[str, "AddressFamily"], ) -> List["AddressFamily"]: return [ af for ns, af in address_families_dict.items() if fast_relpath_optional(self.directory, ns) is not None ] def address_target_pairs_from_address_families(self, address_families): return self.all_address_target_pairs(address_families) def make_glob_patterns(self, address_mapper: "AddressMapper") -> List[str]: return [ os.path.join(f, pattern) for pattern in address_mapper.build_patterns for f in recursive_dirname(self.directory) ] _specificity = { SingleAddress: 0, SiblingAddresses: 1, AscendantAddresses: 2, DescendantAddresses: 3, type(None): 99 } def more_specific( address_spec1: Optional[AddressSpec], address_spec2: Optional[AddressSpec] ) -> AddressSpec: """Returns which of the two specs is more specific. This is useful when a target matches multiple specs, and we want to associate it with the "most specific" one, which will make the most intuitive sense to the user. """ # Note that if either of spec1 or spec2 is None, the other will be returned. if address_spec1 is None and address_spec2 is None: raise ValueError('internal error: both specs provided to more_specific() were None') return cast( AddressSpec, address_spec1 if _specificity[type(address_spec1)] < _specificity[type(address_spec2)] else address_spec2 ) @frozen_after_init @dataclass(unsafe_hash=True) class AddressSpecsMatcher: """Contains filters for the output of a AddressSpecs match. This class is separated out from `AddressSpecs` to allow for both stuctural equality of the `tags` and `exclude_patterns`, and for caching of their compiled forms using `@memoized_property` (which uses the hash of the class instance in its key, and results in a very large key when used with `AddressSpecs` directly). """ tags: Tuple[str, ...] exclude_patterns: Tuple[str, ...] def __init__( self, tags: Optional[Iterable[str]] = None, exclude_patterns: Optional[Iterable[str]] = None, ) -> None: self.tags = tuple(tags or []) self.exclude_patterns = tuple(exclude_patterns or []) @memoized_property def _exclude_compiled_regexps(self): return [re.compile(pattern) for pattern in set(self.exclude_patterns or [])] def _excluded_by_pattern(self, address): return any(p.search(address.spec) is not None for p in self._exclude_compiled_regexps) @memoized_property def _target_tag_matches(self): def filter_for_tag(tag): return lambda t: tag in [str(t_tag) for t_tag in t.kwargs().get("tags", [])] return wrap_filters(create_filters(self.tags, filter_for_tag)) def matches_target_address_pair(self, address, target): """ :param Address address: An Address to match :param HydratedTarget target: The Target for the address. :return: True if the given Address/HydratedTarget are included by this matcher. """ return self._target_tag_matches(target) and not self._excluded_by_pattern(address) @frozen_after_init @dataclass(unsafe_hash=True) class AddressSpecs: """A collection of `AddressSpec`s representing AddressSpec subclasses, and a AddressSpecsMatcher to filter results.""" dependencies: Tuple[AddressSpec, ...] matcher: AddressSpecsMatcher def __init__( self, dependencies: Iterable[AddressSpec], tags: Optional[Iterable[str]] = None, exclude_patterns: Optional[Iterable[str]] = None, ) -> None: self.dependencies = tuple(dependencies) self.matcher = AddressSpecsMatcher(tags=tags, exclude_patterns=exclude_patterns) def __iter__(self) -> Iterator[AddressSpec]: return iter(self.dependencies) class FilesystemSpec(Spec, metaclass=ABCMeta): pass @dataclass(frozen=True) class FilesystemLiteralSpec(FilesystemSpec): """A literal file name, e.g. `foo.py`.""" file: str def to_spec_string(self) -> str: return self.file @dataclass(frozen=True) class FilesystemGlobSpec(FilesystemSpec): """A spec with a glob or globs, e.g. `*.py` and `**/*.java`.""" glob: str def to_spec_string(self) -> str: return self.glob @dataclass(frozen=True) class FilesystemIgnoreSpec(FilesystemSpec): """A spec to ignore certain files or globs.""" glob: str def __post_init__(self) -> None: if self.glob.startswith("!"): raise ValueError(f"The `glob` for {self} should not start with `!`.") def to_spec_string(self) -> str: return f"!{self.glob}" class FilesystemSpecs(Collection[FilesystemSpec]): @memoized_property def includes(self) -> Tuple[Union[FilesystemLiteralSpec, FilesystemGlobSpec], ...]: return tuple( spec for spec in self.dependencies if isinstance(spec, (FilesystemGlobSpec, FilesystemLiteralSpec)) ) @memoized_property def ignores(self) -> Tuple[FilesystemIgnoreSpec, ...]: return tuple(spec for spec in self.dependencies if isinstance(spec, FilesystemIgnoreSpec)) @staticmethod def _generate_path_globs(specs: Iterable[FilesystemSpec]) -> PathGlobs: return PathGlobs( globs=(s.to_spec_string() for s in specs), # We error on unmatched globs for consistency with unmatched address specs. This also # ensures that scripts don't silently do the wrong thing. glob_match_error_behavior=GlobMatchErrorBehavior.error, # We validate that _every_ glob is valid. conjunction=GlobExpansionConjunction.all_match, description_of_origin="file arguments", ) def path_globs_for_spec( self, spec: Union[FilesystemLiteralSpec, FilesystemGlobSpec] ) -> PathGlobs: """Generate PathGlobs for the specific spec, automatically including the instance's FilesystemIgnoreSpecs. """ return self._generate_path_globs(specs=(spec, *self.ignores)) def to_path_globs(self) -> PathGlobs: """Generate a single PathGlobs for the instance.""" return self._generate_path_globs(specs=(*self.includes, *self.ignores)) class AmbiguousSpecs(Exception): pass @dataclass(frozen=True) class Specs: address_specs: AddressSpecs filesystem_specs: FilesystemSpecs def __post_init__(self) -> None: if self.address_specs.dependencies and self.filesystem_specs.dependencies: raise AmbiguousSpecs( "Both address specs and filesystem specs given. Please use only one type of spec.\n\n" f"Address specs: {', '.join(spec.to_spec_string() for spec in self.address_specs)}\n" f"Filesystem specs: {', '.join(spec.to_spec_string() for spec in self.filesystem_specs)}" ) @property def provided_specs(self) -> Union[AddressSpecs, FilesystemSpecs]: """Return whichever types of specs was provided by the user. It is guaranteed that there will only ever be AddressSpecs or FilesystemSpecs, but not both, through validation in the constructor.""" return ( self.filesystem_specs if self.filesystem_specs.dependencies else self.address_specs )
35.158392
109
0.739981
1,893
14,872
5.627575
0.184363
0.053506
0.021966
0.024406
0.334084
0.312963
0.283488
0.266967
0.236178
0.226509
0
0.002014
0.165344
14,872
422
110
35.241706
0.856199
0.2617
0
0.330798
0
0
0.086969
0.009415
0
0
0
0
0.011407
1
0.171103
false
0.015209
0.057034
0.091255
0.48289
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
71d0e460dfc97542581b94a812752a1bad4c2629
709
py
Python
Scripts/nominatintest.py
carlosdenner/business_atlas
8f95bbd07384baa6c5e51776690103e418b3875e
[ "MIT" ]
null
null
null
Scripts/nominatintest.py
carlosdenner/business_atlas
8f95bbd07384baa6c5e51776690103e418b3875e
[ "MIT" ]
4
2021-04-14T19:18:46.000Z
2021-11-02T16:11:36.000Z
Scripts/nominatintest.py
carlosdenner/business_atlas
8f95bbd07384baa6c5e51776690103e418b3875e
[ "MIT" ]
3
2021-09-01T03:05:21.000Z
2021-11-01T16:54:26.000Z
from geopy.geocoders import Nominatim from requests.models import LocationParseError geolocator = Nominatim(user_agent="geoapiExercises") Latitude = 25.594095 Longitude = 85.137566 def location(Latitude, Longitude): lat = str(Latitude) long = str(Longitude) print(lat + long) local = lat + "," + long print(local) if(len(local) > 3): location = geolocator.reverse(local) locStr = str(location) print(locStr) splitted = locStr.split(',') country = splitted[len(splitted) - 1] print(country) print("==============país==============") return country else: return "" location(Latitude, Longitude) # Display
22.870968
52
0.61354
72
709
6.027778
0.527778
0.073733
0.115207
0
0
0
0
0
0
0
0
0.03352
0.242595
709
30
53
23.633333
0.774674
0.009873
0
0
0
0
0.0701
0.04578
0
0
0
0
0
1
0.043478
false
0
0.086957
0
0.217391
0.217391
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
71d178c96b191f21134b0e3351ee139671d87fc0
4,710
py
Python
train/filelocks.py
mister-bailey/MagNET
4f75a6e2fe34eabf455d13338f318e3dc4bf0295
[ "Apache-2.0" ]
null
null
null
train/filelocks.py
mister-bailey/MagNET
4f75a6e2fe34eabf455d13338f318e3dc4bf0295
[ "Apache-2.0" ]
null
null
null
train/filelocks.py
mister-bailey/MagNET
4f75a6e2fe34eabf455d13338f318e3dc4bf0295
[ "Apache-2.0" ]
null
null
null
from filelock import FileLock, Timeout import os import time class ProcessFileLock(FileLock): """ FileLock that is unique per path in each process (for, eg., reentrance) """ locks = {} def __new__(cls, path, *args, **kwargs): if path in ProcessFileLock.locks: return ProcessFileLock.locks[path] else: lock = super().__new__(cls, path, *args, **kwargs) lock.__new_init__(path, *args, **kwargs) ProcessFileLock.locks[path] = lock return lock def __new_init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def __init__(self, *args, **kwargs): pass class ExplosiveFileLock(ProcessFileLock): def acquire(self, *args, **kwargs): r = super().acquire(*args, **kwargs) if self._lock_counter > 1: raise BlockingIOError(f"Process attempted to reacquire lock for {self._lock_file}") return r class HistoriesLock(FileLock): def __init__(self, dir, ensemble=None): super().__init__(os.path.join(dir, "histories.lock")) self.ensemble = ensemble def release(self, **kwargs): super().release() if self.ensemble and self._lock_counter == 0: self.ensemble.close_histories() class SamplesLock(FileLock): def __init__(self, dir, ensemble=None): super().__init__(os.path.join(dir, "samples.lock")) self.ensemble = ensemble def release(self, **kwargs): if self.ensemble and self._lock_counter == 1: self.ensemble._test_samples.close() self.ensemble._test_samples = None super().release() def __enter__(self): print("Acquiring samples lock... ", end='') super().__enter__() if self.ensemble._test_samples is None: from sample_hyperparameters import TrainableSampleGenerator self.ensemble._test_samples = TrainableSampleGenerator(self.ensemble.config.exploration.sample_file, configs=self.ensemble.config_files, stub=self.ensemble.stub) print("Done.") return self.ensemble._test_samples class ExistLock: """ Locks on the existence of the given file. No guarantees of atomicity! Unique per process, for reentry """ locks={} def __new__(cls, path, *args, **kwargs): if path in ExistLock.locks: lock = ExistLock.locks[path] #print(f"Reloading ExistLock('{path}')") #print(f" Lock counter = {lock._lock_counter}") return lock else: #print(f"Creating new ExistLock('{path}')") lock = super().__new__(cls) lock.__new_init__(path, *args, **kwargs) ExistLock.locks[path] = lock return lock def __new_init__(self, path, block=True, timeout=None, polling_interval=.05): self.path = path if not block: timeout == 0.0 else: self.timeout=timeout self.polling_interval=polling_interval self._lock_counter = 0 def acquire(self, block=None, timeout=None): """ Not atomic. Should probably happen within the context of an atomic lock. """ if block == False: timeout = 0.0 if timeout is None: timeout = self.timeout #print(f"Trying to acquire ExistLock('{self.path}')...") #print(f" Lock counter = {self._lock_counter}") start_time = time.time() while os.path.isfile(self.path): if self._lock_counter > 0: self._lock_counter += 1 #print(f"Acquired, lock counter = {self._lock_counter}") return True if timeout is None or time.time() - start_time < timeout: time.sleep(self.polling_interval) else: return False with open(self.path, 'w'): self._lock_counter = 1 #print(f"Acquired, lock counter = {self._lock_counter}") return True def release(self): self._lock_counter = min(0, self._lock_counter - 1) if self._lock_counter == 0 and os.path.isfile(self.path): os.remove(self.path) def __enter__(self): if self.acquire(): return self else: raise Timeout(f"Failed to acquire ExistLock for file {self.path}") def __exit__(self, type, value, traceback): self.release()
34.888889
174
0.56603
513
4,710
4.951267
0.222222
0.077953
0.076772
0.031496
0.301969
0.233071
0.213386
0.188189
0.153543
0.124409
0
0.005049
0.327176
4,710
134
175
35.149254
0.796466
0.125478
0
0.273684
0
0
0.041709
0
0
0
0
0
0
1
0.157895
false
0.010526
0.042105
0
0.378947
0.021053
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
71d4b733728e3fe154331308ec40f232a937aaa6
1,637
py
Python
todo/management/serializers/tasks.py
Sanguet/todo-challenge
8eabc02081e7ce6b33408558d4a4a39edee3944c
[ "MIT" ]
null
null
null
todo/management/serializers/tasks.py
Sanguet/todo-challenge
8eabc02081e7ce6b33408558d4a4a39edee3944c
[ "MIT" ]
null
null
null
todo/management/serializers/tasks.py
Sanguet/todo-challenge
8eabc02081e7ce6b33408558d4a4a39edee3944c
[ "MIT" ]
null
null
null
# Django REST Framework from rest_framework import serializers # Model from todo.management.models import Task # Utils from todo.utils.tasks import TaskMetrics from todo.utils.serializer_fields import CompleteNameUser class TaskModelSerializer(serializers.ModelSerializer): """Modelo serializer del circulo""" user = CompleteNameUser(many=False) class Meta: """Meta class""" model = Task fields = ( 'id', 'user', 'title', 'date_to_finish', 'is_finalize', 'description', 'created', 'priority', 'color' ) read_only_fields = ( 'id', 'user', 'created', ) def create(self, data): """Creacion de la tarea""" # Sacamos los datos que ya tenemos en el context user = self.context['request'].user data['is_finalize'] = False # Creamos la tarea task = Task.objects.create( user=user, **data ) # Puntos al perfil TaskMetrics(action='Create', user=user) return task def update(self, instance, data): """Actualizacion de la tarea""" # Extraemos el user del contexto y mandamos la funcion update user = self.context['request'].user new_is_finalize = data.get('is_finalize', instance.is_finalize) if new_is_finalize != instance.is_finalize: TaskMetrics(action='Update', user=user, is_finalize=new_is_finalize) # Actualizamos los datos normales super(TaskModelSerializer, self).update(instance, data) return instance
25.578125
80
0.607819
175
1,637
5.582857
0.451429
0.092119
0.039918
0.045036
0.110542
0
0
0
0
0
0
0
0.29383
1,637
63
81
25.984127
0.845156
0.180208
0
0.058824
0
0
0.097412
0
0
0
0
0
0
1
0.058824
false
0
0.117647
0
0.323529
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
71d5ac8fe8a1e3e087c79c30be252f654bc0722c
1,895
py
Python
outlier_detector.py
Sean-Ker/data_homework
5f289c692690724ee5973683c53e83299958b270
[ "Apache-2.0" ]
null
null
null
outlier_detector.py
Sean-Ker/data_homework
5f289c692690724ee5973683c53e83299958b270
[ "Apache-2.0" ]
null
null
null
outlier_detector.py
Sean-Ker/data_homework
5f289c692690724ee5973683c53e83299958b270
[ "Apache-2.0" ]
null
null
null
import numpy as np import pandas as pd from sklearn.decomposition import PCA ''' A function that detects outliers, where k is a tandard deviation threshold hyperparameter preferablly (2, 2.5, 3). The algo could handle multivariable data frames with any number of features d. For that manner, it first reduces the dimensionality to 2 using PCA, makes sure that the matrix is positive definite and calculates the Mahalanobis Distance with a threshold value. Returns a series of n rows back. ''' def outlier_detector(data, k=2.5): # Calculate Principal Component Analysis pca = PCA(n_components=data.shape[1], svd_solver='full') df = pd.DataFrame(pca.fit_transform( data), index=data.index, columns=data.columns) # Calculate covariance and its inverse matrices cov_matrix = np.cov(df.values, rowvar=False) inv_cov = np.linalg.inv(cov_matrix) mean = df.values.mean(axis=0) # Check matrices are positive definite: https://en.wikipedia.org/wiki/Definiteness_of_a_matrix assert is_pos_def(cov_matrix) and is_pos_def(inv_cov) # Calculate Mahalanobis Distance https://en.wikipedia.org/wiki/Mahalanobis_distance md = mahalanobis_dist(inv_cov, mean, df.values, verbose=False) threshold = np.mean(md) * k # res = pd.DataFrame(index=data.index,columns=data.columns) return data[md > threshold] # https://www.youtube.com/watch?v=spNpfmWZBmg&t=0s def mahalanobis_dist(inv_cov_matrix, mean_distr, data, verbose=False): diff = data - mean_distr md = [] for i in range(len(diff)): md.append(np.sqrt(diff[i].dot(inv_cov_matrix).dot(diff[i]))) return np.array(md) # Check that matrix is positive definite def is_pos_def(A): if np.allclose(A, A.T): try: np.linalg.cholesky(A) return True except np.linalg.LinAlgError: return False else: return False
35.754717
180
0.713456
286
1,895
4.629371
0.472028
0.02719
0.02719
0.036254
0.083082
0.048338
0
0
0
0
0
0.006519
0.190501
1,895
52
181
36.442308
0.856584
0.21372
0
0.068966
0
0
0.003752
0
0
0
0
0
0.034483
1
0.103448
false
0
0.103448
0
0.37931
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
71d79b9492d4549b986121f837ee137051811f29
1,631
py
Python
arc113/b.py
nishio/atcoder
8db36537b5d8580745d5f98312162506ad7d7ab4
[ "MIT" ]
1
2021-03-09T04:28:13.000Z
2021-03-09T04:28:13.000Z
arc113/b.py
nishio/atcoder
8db36537b5d8580745d5f98312162506ad7d7ab4
[ "MIT" ]
null
null
null
arc113/b.py
nishio/atcoder
8db36537b5d8580745d5f98312162506ad7d7ab4
[ "MIT" ]
null
null
null
# included from snippets/main.py def debug(*x, msg=""): import sys print(msg, *x, file=sys.stderr) def solve(SOLVE_PARAMS): pass def main(): A, B, C = map(int, input().split()) doubling = [B % 20] for i in range(32): doubling.append( (doubling[-1] ** 2) % 20 ) BC = 1 for i in range(32): if C % 2: BC *= doubling[i] BC %= 20 C //= 2 if BC == 0: BC = 20 ret = (A % 10) ** BC ret %= 10 print(ret) # tests T1 = """ 4 3 2 """ TEST_T1 = """ >>> as_input(T1) >>> main() 4 """ T2 = """ 1 2 3 """ TEST_T2 = """ >>> as_input(T2) >>> main() 1 """ T3 = """ 3141592 6535897 9323846 """ TEST_T3 = """ >>> as_input(T3) >>> main() 2 """ T4 = """ 2 10 1 """ TEST_T4 = """ >>> as_input(T4) >>> main() 4 """ T5 = """ 2 20 1 """ TEST_T5 = """ >>> as_input(T5) >>> main() 6 """ def _test(): import doctest doctest.testmod() g = globals() for k in sorted(g): if k.startswith("TEST_"): print(k) doctest.run_docstring_examples(g[k], g, name=k) def as_input(s): "use in test, use given string as input file" import io f = io.StringIO(s.strip()) g = globals() g["input"] = lambda: bytes(f.readline(), "ascii") g["read"] = lambda: bytes(f.read(), "ascii") if __name__ == "__main__": import sys input = sys.stdin.buffer.readline read = sys.stdin.buffer.read sys.setrecursionlimit(10 ** 6) if sys.argv[-1] == "-t": print("testing") _test() sys.exit() main() sys.exit() # end of snippets/main.py
14.963303
59
0.498467
232
1,631
3.396552
0.37069
0.062183
0.035533
0.027919
0.032995
0
0
0
0
0
0
0.071492
0.305334
1,631
108
60
15.101852
0.624007
0.064378
0
0.258427
0
0
0.18762
0
0
0
0
0
0
1
0.05618
false
0.011236
0.044944
0
0.101124
0.044944
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
71d7b6b5d8927503c0de7b2300ecece8268c9b0c
892
py
Python
pythonG/objects.py
ezan2000/Cssi_2018
2385e9f4557c1a2aa642e21d42dcc935e24c88c3
[ "Apache-2.0" ]
null
null
null
pythonG/objects.py
ezan2000/Cssi_2018
2385e9f4557c1a2aa642e21d42dcc935e24c88c3
[ "Apache-2.0" ]
null
null
null
pythonG/objects.py
ezan2000/Cssi_2018
2385e9f4557c1a2aa642e21d42dcc935e24c88c3
[ "Apache-2.0" ]
null
null
null
ezan = { 'name': 'ezan', 'age': 18, 'hair': 'brown', 'cool': True , } print(ezan) class Person(object): #use class to make object def __init__( self, name, age ,hair, color, hungry) : #initialize #first object inside of a class is self self.name = 'ezan' self.age = 18 self.hair = 'brown' self.cool = True def eat(self,food): print("EAT {f}".format(f = food)) self.hungry = food def play(self, game): print("Play {p}".format(p = game)) self.play = game def birth(self,person): kids = Person(name = " lail", age = 18, hair = 'black', color = 'blue', hungry = True) ezan = Person( name = "ezan", age = 18, hair = "black", cool = True, hungry = False) print(ezan.name) print('I am hungry') Austin = Person(name = 'austin', age = 18, hair = "Shrek", cool = False, hungry = True)
25.485714
94
0.56278
121
892
4.115702
0.355372
0.050201
0.072289
0.052209
0.068273
0
0
0
0
0
0
0.01548
0.275785
892
34
95
26.235294
0.755418
0.080717
0
0
0
0
0.113831
0
0
0
0
0
0
1
0.153846
false
0
0
0
0.192308
0.192308
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
71d7fc5500dfa419709498ae6eaa8bc5f3fa5a27
400
py
Python
62/main.py
pauvrepetit/leetcode
6ad093cf543addc4dfa52d72a8e3c0d05a23b771
[ "MIT" ]
null
null
null
62/main.py
pauvrepetit/leetcode
6ad093cf543addc4dfa52d72a8e3c0d05a23b771
[ "MIT" ]
null
null
null
62/main.py
pauvrepetit/leetcode
6ad093cf543addc4dfa52d72a8e3c0d05a23b771
[ "MIT" ]
null
null
null
# 62. 不同路径 # 组合数,杨辉三角 yanghui = [[0 for i in range(202)] for j in range(202)] def comb(n, k): if yanghui[n][k] == 0: yanghui[n][k] = (comb(n-1, k-1) + comb(n-1, k)) return yanghui[n][k] class Solution: def uniquePaths(self, m: int, n: int) -> int: for i in range(202): yanghui[i][0] = 1 yanghui[i][i] = 1 return comb(m+n-2, min(m, n)-1)
23.529412
55
0.51
73
400
2.794521
0.369863
0.039216
0.147059
0.107843
0.137255
0
0
0
0
0
0
0.074733
0.2975
400
17
56
23.529412
0.651246
0.0425
0
0
0
0
0
0
0
0
0
0
0
1
0.181818
false
0
0
0
0.454545
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