hexsha
stringlengths
40
40
size
int64
7
1.04M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
247
max_stars_repo_name
stringlengths
4
125
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
247
max_issues_repo_name
stringlengths
4
125
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
247
max_forks_repo_name
stringlengths
4
125
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.04M
avg_line_length
float64
1.77
618k
max_line_length
int64
1
1.02M
alphanum_fraction
float64
0
1
original_content
stringlengths
7
1.04M
filtered:remove_function_no_docstring
int64
-102
942k
filtered:remove_class_no_docstring
int64
-354
977k
filtered:remove_delete_markers
int64
0
60.1k
1ed1ad90bbb7f458daba222ac3b8b2de75201045
3,271
py
Python
plotta/__init__.py
gzuidhof/plotta-python
61ec22c11c24e599486aedbeabb4d13ca62c6918
[ "MIT" ]
null
null
null
plotta/__init__.py
gzuidhof/plotta-python
61ec22c11c24e599486aedbeabb4d13ca62c6918
[ "MIT" ]
null
null
null
plotta/__init__.py
gzuidhof/plotta-python
61ec22c11c24e599486aedbeabb4d13ca62c6918
[ "MIT" ]
null
null
null
import unirest import time import socket import uuid HOSTNAME = 'localhost' PORT = 3000 PLOTTA_ENABLED = True # API endpoint wrappers
31.757282
109
0.636197
import unirest import time import socket import uuid HOSTNAME = 'localhost' PORT = 3000 PLOTTA_ENABLED = True # API endpoint wrappers def job_new(job_id, name, node): payload = {'job_id': job_id, 'name': name, 'node': node} url = "http://{0}:{1}/api/job/new".format(HOSTNAME, PORT) return sync_request(url, payload) def job_stop(job_id): payload = {'job_id': job_id} url = "http://{0}:{1}/api/job/stop".format(HOSTNAME, PORT) async_request(url, payload) def stream_new(stream_id, job_id, name, x_name, y_name): payload = {'stream_id': stream_id, 'job_id': job_id, 'name': name, 'xName': x_name, 'yName': y_name} url = "http://{0}:{1}/api/stream/new".format(HOSTNAME, PORT) return sync_request(url, payload) def append(stream_id, job_id, x, y): payload = {'stream_id': stream_id, 'job_id': job_id, 'x': x, 'y': y} url = "http://{0}:{1}/api/stream/append".format(HOSTNAME, PORT) async_request(url, payload) def sync_request(url, payload): try: response = unirest.post(url, headers = {"Accept": "application/json"}, params = payload) check_success(response) return response except Exception, e: check_success(None) return None def async_request(url, payload): unirest.post(url, headers = {"Accept": "application/json"}, params = payload, callback = _empty_callback) def _empty_callback(_): pass def check_success(response): if response is None or response.code in [404, 502, 503, 504]: # Server offline, disable plotta print "Plotta server offline. Disabling Plotta." PLOTTA_ENABLED = False elif response.code in [400, 405, 406, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 501]: raise RuntimeError("Plotta user error ({0}). Message: {1}".format(response.code, response.body)) elif response.code in [500]: raise RuntimeError("Plotta server error ({0}). Message: ".format(response.code, response.body)) class Job(): def __init__(self, job_name, job_id = None, node_name = None): if job_id is None: job_id = int(round(time.time())) if node_name is None: node_name = socket.getfqdn() self.job_name = job_name self.job_id = job_id self.node_name = node_name def start(self): if PLOTTA_ENABLED: job_new(self.job_id, self.job_name, self.node_name) def stop(self): if PLOTTA_ENABLED: job_stop(self.job_id) def add_stream(self, name, stream_id=None, x_name="", y_name=""): if stream_id is None: #Generate a unique ID for this stream stream_id = uuid.uuid4() stream = Stream(stream_id, self.job_id, name, x_name, y_name) stream.start() return stream class Stream(): def __init__(self, stream_id, job_id, namw, x_name, y_name): self.stream_id = stream_id self.job_id = job_id self.name = name self.x_name = x_name self.y_name = y_name def start(self): if PLOTTA_ENABLED: stream_new(self.stream_id, self.job_id, self.name, self.x_name, self.y_name) def append(self, x, y): if PLOTTA_ENABLED: append(self.stream_id, self.job_id, x, y)
2,732
-15
418
257430f2566bf7abcdadbc27fbcfb4ceab9cd18c
1,051
py
Python
Train_and_Test_Notebooks/tests/IoU.py
parshwa1999/Map-Segmentation
0c45c887fb2363125771bccafc27a953ad05ce5a
[ "MIT" ]
5
2020-03-23T18:43:00.000Z
2021-12-14T09:52:12.000Z
Train_and_Test_Notebooks/tests/IoU.py
parshwa1999/Map-Segmentation
0c45c887fb2363125771bccafc27a953ad05ce5a
[ "MIT" ]
null
null
null
Train_and_Test_Notebooks/tests/IoU.py
parshwa1999/Map-Segmentation
0c45c887fb2363125771bccafc27a953ad05ce5a
[ "MIT" ]
1
2020-09-08T12:34:39.000Z
2020-09-08T12:34:39.000Z
import cv2 import numpy as np total = 0 for i in range(29): original = cv2.imread(str(i) + "GroundTruth.png", 0) predicted = cv2.imread(str(i) + "Prediction_Threshold.png", 0) #print(np.shape(original)) original = original.flatten() predicted = predicted.flatten() original = (original>127) predicted = (predicted>127) #print(np.unique(predicted)) #print(np.unique(original)) print(i) if np.sum(np.invert(original)) != 0: sum0 = np.sum((np.invert(predicted) * np.invert(original))*1) / np.sum(np.invert(original)) else: sum0 = 1 if np.sum(original) != 0: sum1 = np.sum((predicted * original)*1) / np.sum(original) else: sum1 = 1 print("SUM: " + str( np.sum(original))) #print("SUM: " + str( np.sum(np.invert(original)))) #print("MUL : " + str(np.sum(np.invert(original) * original))) IoU = ((sum0 + sum1) / 2) * 100 print("IoU: " + str(sum0) + " " + str(sum1) + " " + str(IoU)) total += IoU print(total/29)
25.634146
99
0.573739
import cv2 import numpy as np total = 0 for i in range(29): original = cv2.imread(str(i) + "GroundTruth.png", 0) predicted = cv2.imread(str(i) + "Prediction_Threshold.png", 0) #print(np.shape(original)) original = original.flatten() predicted = predicted.flatten() original = (original>127) predicted = (predicted>127) #print(np.unique(predicted)) #print(np.unique(original)) print(i) if np.sum(np.invert(original)) != 0: sum0 = np.sum((np.invert(predicted) * np.invert(original))*1) / np.sum(np.invert(original)) else: sum0 = 1 if np.sum(original) != 0: sum1 = np.sum((predicted * original)*1) / np.sum(original) else: sum1 = 1 print("SUM: " + str( np.sum(original))) #print("SUM: " + str( np.sum(np.invert(original)))) #print("MUL : " + str(np.sum(np.invert(original) * original))) IoU = ((sum0 + sum1) / 2) * 100 print("IoU: " + str(sum0) + " " + str(sum1) + " " + str(IoU)) total += IoU print(total/29)
0
0
0
294464d47e73dcdf833d00d706cd3d6297463a47
1,488
py
Python
Block.py
LiorArmon/Python-Hackathon
075056d8476c6144b2eaa826ff623cf828385c73
[ "Apache-2.0" ]
null
null
null
Block.py
LiorArmon/Python-Hackathon
075056d8476c6144b2eaa826ff623cf828385c73
[ "Apache-2.0" ]
null
null
null
Block.py
LiorArmon/Python-Hackathon
075056d8476c6144b2eaa826ff623cf828385c73
[ "Apache-2.0" ]
2
2018-06-26T08:40:17.000Z
2018-06-27T06:17:55.000Z
import psychopy.core import psychopy.event import psychopy.visual import pandas as pd import numpy as np import psychopy.gui import psychopy.sound import os import yaml import json from pathlib import Path import random from Trial import Trial
29.76
119
0.597446
import psychopy.core import psychopy.event import psychopy.visual import pandas as pd import numpy as np import psychopy.gui import psychopy.sound import os import yaml import json from pathlib import Path import random from Trial import Trial class Block: def __init__(self, stim_list, df, params, win, cue): self.df = df self.win = win self.stim_list = stim_list self.success_count = 0 self.failure_count = 0 self.params = params self.cue = cue def run_block(self): random.shuffle(self.stim_list) self.trials = [] for stim in self.stim_list: curr_trial = Trial(stim, self.params, self.win, self.success_count, self.failure_count, self.cue) curr_trial.run_trial() self.trials.append(curr_trial) def get_result(self): trials_data = pd.DataFrame(data=None, index=None, columns=['trial', 'RT', 'success', 'key']) for trial in self.trials: if trial.stimulus.show: trial_data = trial.get_trial_data() if trial_data[2] == 1: self.success_count += 1 else: self.failure_count += 1 new_row = {'trial': trial_data[0], 'RT': trial_data[1], 'success': trial_data[2], 'key': trial_data[3]} trials_data = trials_data.append(new_row, ignore_index = True) return trials_data
1,147
-9
107
e1d5805eabcda488c36ca76271466031cb90112e
17,757
py
Python
rak811/cli.py
hrnciar/pyrak811
e62be1c7524224105984531abc8b9bda02a61e26
[ "Apache-2.0" ]
45
2019-04-23T03:36:07.000Z
2022-03-23T06:05:46.000Z
rak811/cli.py
hrnciar/pyrak811
e62be1c7524224105984531abc8b9bda02a61e26
[ "Apache-2.0" ]
24
2019-05-21T17:18:31.000Z
2022-03-01T11:18:22.000Z
rak811/cli.py
hrnciar/pyrak811
e62be1c7524224105984531abc8b9bda02a61e26
[ "Apache-2.0" ]
25
2019-03-11T14:25:26.000Z
2022-03-04T15:05:28.000Z
"""RAK811 CLI interface. Provides a command line interface for the RAK811 module (Firmware V2.0). Copyright 2019, 2021 Philippe Vanhaesendonck 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. SPDX-License-Identifier: Apache-2.0 """ from json import dumps import logging import click from .rak811 import Mode, RecvEx, Reset from .rak811 import Rak811 from .rak811 import Rak811Error from .rak811 import Rak811EventError, Rak811ResponseError, Rak811TimeoutError # Valid configuration keys for LoRaWan LW_CONFIG_KEYS = ('dev_addr', 'dev_eui', 'app_eui', 'app_key', 'nwks_key', 'apps_key', 'tx_power', 'pwr_level', 'adr', 'dr', 'public_net', 'rx_delay1', 'ch_list', 'ch_mask', 'max_chs', 'rx2', 'join_cnt', 'nbtrans', 'retrans', 'class', 'duty') # Valid configuration keys for LoRaP2P P2P_CONFIG_KEYS = { 'freq': click.FloatRange(min=860.000, max=929.900, clamp=False), 'sf': click.IntRange(min=6, max=12, clamp=False), 'bw': click.IntRange(min=0, max=2, clamp=False), 'cr': click.IntRange(min=1, max=4, clamp=False), 'prlen': click.IntRange(min=8, max=65535, clamp=False), 'pwr': click.IntRange(min=5, max=20, clamp=False) } class KeyValueParamTypeLW(click.ParamType): """Basic KEY=VALUE pair parameter type for LoRaWan.""" name = 'key-value-lorawan' class KeyValueParamTypeP2P(click.ParamType): """Basic KEY=VALUE pair parameter type for LoRaP2P.""" name = 'key-value-p2p' def print_exception(e): """Print exception raised by the Rak811 library.""" if isinstance(e, Rak811ResponseError): click.echo('RAK811 response error {}: {}'.format(e.errno, e.strerror)) elif isinstance(e, Rak811EventError): click.echo('RAK811 event error {}: {}'.format(e.errno, e.strerror)) elif isinstance(e, Rak811TimeoutError): click.echo('RAK811 timeout: {}'.format(e)) else: click.echo('RAK811 unexpected exception {}'.format(e)) @click.group() @click.option( '-v', '--verbose', is_flag=True, help='Verbose mode' ) @click.option( '-d', '--debug', is_flag=True, help='Debug mode' ) @click.version_option() @click.pass_context def cli(ctx, verbose, debug): """Command line interface for the RAK811 module.""" ctx.ensure_object(dict) ctx.obj['VERBOSE'] = verbose logging.basicConfig(level=logging.DEBUG if debug else logging.INFO) @cli.command(name='hard-reset') @click.pass_context def hard_reset(ctx): """Hardware reset of the module. Hard reset should not be required in normal operation. It needs to be issued once after host boot, or module restart. """ lora = Rak811() lora.hard_reset() if ctx.obj['VERBOSE']: click.echo('Hard reset complete') lora.close() """System commands.""" @cli.command() @click.pass_context def version(ctx): """Get module version.""" lora = Rak811() click.echo(lora.version) lora.close() @cli.command() @click.pass_context def sleep(ctx): """Enter sleep mode.""" lora = Rak811() lora.sleep() if ctx.obj['VERBOSE']: click.echo('Sleeping') lora.close() @cli.command(name='wake-up') @click.pass_context def wake_up(ctx): """Wake up.""" lora = Rak811() lora.wake_up() if ctx.obj['VERBOSE']: click.echo('Alive!') lora.close() @cli.command() @click.argument( 'reset_type', required=True, type=click.Choice(['module', 'lora']) ) @click.pass_context def reset(ctx, reset_type): """Reset Module or LoRaWan stack.""" lora = Rak811() if reset_type == 'module': lora.reset(Reset.Module) else: lora.reset(Reset.LoRa) if ctx.obj['VERBOSE']: click.echo('{0} reset complete.'.format( 'Module' if reset_type == 'module' else 'LoRa')) lora.close() @cli.command() @click.pass_context def reload(ctx): """Set LoRaWan or LoRaP2P configurations to default.""" lora = Rak811() lora.reload() if ctx.obj['VERBOSE']: click.echo('Configuration reloaded.') lora.close() @cli.command() @click.argument( 'mode', required=False, type=click.Choice(['LoRaWan', 'LoRaP2P'], case_sensitive=False) ) @click.pass_context def mode(ctx, mode): """Get/Set mode to LoRaWan or LoRaP2P.""" lora = Rak811() if mode is None: click.echo('LoRaWan' if lora.mode == Mode.LoRaWan else 'LoRaP2P') else: mode = mode.lower() if mode == 'lorawan': lora.mode = Mode.LoRaWan else: lora.mode = Mode.LoRaP2P if ctx.obj['VERBOSE']: click.echo('Mode set to {0}.'.format( 'LoRaWan' if mode == 'lorawan' else 'LoRaP2P')) lora.close() @cli.command() @click.argument( 'recv_ex', required=False, type=click.Choice(['enable', 'disable']) ) @click.pass_context def recv_ex(ctx, recv_ex): """RSSI & SNR report on receive.""" lora = Rak811() if recv_ex is None: click.echo('Enabled' if lora.recv_ex == RecvEx.Enabled else 'Disabled') else: lora.recv_ex = ( RecvEx.Enabled if recv_ex == 'enable' else RecvEx.Disabled ) if ctx.obj['VERBOSE']: click.echo('RSSI & SNR report on receive {0}.'.format( 'Enabled' if recv_ex == 'enable' else 'Disabled')) lora.close() """LoRaWan commands.""" @cli.command() @click.argument( 'band', required=False, type=click.Choice( ['EU868', 'US915', 'AU915', 'KR920', 'AS923', 'IN865'], case_sensitive=False ) ) @click.pass_context def band(ctx, band): """Get/Set LoRaWan region.""" lora = Rak811() if band is None: click.echo(lora.band) else: band = band.upper() lora.band = band if ctx.obj['VERBOSE']: click.echo('LoRaWan region set to {0}.'.format(band)) lora.close() @cli.command() @click.argument( 'key_values', metavar='KEY=VALUE...', required=True, type=KeyValueParamTypeLW(), nargs=-1 ) @click.pass_context def set_config(ctx, key_values): """Set LoraWAN configuration. \b Arguments are specified as KEY=VALUE pairs, e.g.: set-config app_eui='APP_EUI' app_key='APP_KEY' """ lora = Rak811() kv_args = dict(key_values) try: lora.set_config(**kv_args) if ctx.obj['VERBOSE']: click.echo('LoRaWan parameters set') except Rak811Error as e: print_exception(e) lora.close() @cli.command() @click.argument( 'key', required=True, type=click.Choice(LW_CONFIG_KEYS) ) @click.pass_context def get_config(ctx, key): """Get LoraWan configuration.""" lora = Rak811() try: click.echo(lora.get_config(key)) except Rak811Error as e: print_exception(e) lora.close() @cli.command() @click.pass_context def join_otaa(ctx): """Join the configured network in OTAA mode.""" lora = Rak811() try: lora.join_otaa() if ctx.obj['VERBOSE']: click.echo('Joined in OTAA mode') except Rak811Error as e: print_exception(e) lora.close() @cli.command() @click.pass_context def join_abp(ctx): """Join the configured network in ABP mode.""" lora = Rak811() try: lora.join_abp() if ctx.obj['VERBOSE']: click.echo('Joined in ABP mode') except Rak811Error as e: print_exception(e) lora.close() @cli.command() @click.pass_context def signal(ctx): """Get (RSSI,SNR) from latest received packet.""" lora = Rak811() (rssi, snr) = lora.signal if ctx.obj['VERBOSE']: click.echo('RSSI: {0} - SNR: {1}'.format(rssi, snr)) else: click.echo('{} {}'.format(rssi, snr)) lora.close() @cli.command() @click.argument( 'dr', required=False, type=click.INT ) @click.pass_context def dr(ctx, dr): """Get/Set next send data rate.""" lora = Rak811() if dr is None: click.echo(lora.dr) else: try: lora.dr = dr if ctx.obj['VERBOSE']: click.echo('Data rate set to {0}.'.format(dr)) except Rak811Error as e: print_exception(e) lora.close() @cli.command() @click.pass_context def link_cnt(ctx): """Get up & downlink counters.""" lora = Rak811() (uplink, downlink) = lora.link_cnt if ctx.obj['VERBOSE']: click.echo('Uplink: {0} - Downlink: {1}'.format(uplink, downlink)) else: click.echo('{} {}'.format(uplink, downlink)) lora.close() @cli.command() @click.pass_context def abp_info(ctx): """Get ABP info. When using OTAA, returns the necessary info to re-join in ABP mode. The following tuple is returned: (NetworkID, DevAddr, Nwkskey, Appskey) """ lora = Rak811() (nwk_id, dev_addr, nwks_key, apps_key) = lora.abp_info if ctx.obj['VERBOSE']: click.echo('NwkId: {}'.format(nwk_id)) click.echo('DevAddr: {}'.format(dev_addr)) click.echo('Nwkskey: {}'.format(nwks_key)) click.echo('Appskey: {}'.format(apps_key)) else: click.echo('{} {} {} {}'.format(nwk_id, dev_addr, nwks_key, apps_key)) lora.close() @cli.command() @click.option( '-p', '--port', default=1, type=click.IntRange(1, 223), help='port number to use (1-223)' ) @click.option( '--confirm', is_flag=True, help='regular or confirmed send' ) @click.option( '--binary', is_flag=True, help='Data is binary (hex encoded)' ) @click.argument( 'data', required=True ) @click.option( '--json', is_flag=True, help='Output downlink in JSON format' ) @click.pass_context def send(ctx, port, confirm, binary, data, json): """Send LoRaWan message and check for downlink.""" if binary: try: data = bytes.fromhex(data) except ValueError: click.echo('Invalid binary data') return lora = Rak811() try: lora.send(data, confirm=confirm, port=port) except Rak811Error as e: print_exception(e) lora.close() return if ctx.obj['VERBOSE']: click.echo('Message sent.') if lora.nb_downlinks: downlink = lora.get_downlink() downlink['data'] = downlink['data'].hex() if json: click.echo(dumps(downlink, indent=4)) elif ctx.obj['VERBOSE']: click.echo('Downlink received:') click.echo('Port: {}'.format(downlink['port'])) if downlink['rssi']: click.echo('RSSI: {}'.format(downlink['rssi'])) click.echo('SNR: {}'.format(downlink['snr'])) click.echo('Data: {}'.format(downlink['data'])) else: click.echo(downlink['data']) elif ctx.obj['VERBOSE']: click.echo('No downlink available.') lora.close() @cli.command() @click.argument( 'key_values', metavar='KEY=VALUE...', required=False, type=KeyValueParamTypeP2P(), nargs=-1 ) @click.pass_context def rf_config(ctx, key_values): """Get/Set LoraP2P configuration. \b Without argument, returns: frequency, sf, bw, cr, prlen, pwr \b Otherwise set rf_config, Arguments are specified as KEY=VALUE pairs: freq: frequency in MHz (860.000-929.900) sf: strength factor (6-12) bw: bandwidth (0:125KHz, 1:250KHz, 2:500KHz) cr: coding rate (1:4/5, 2:4/6, 3:4/7, 4:4/8) prlen: preamble length default (8-65535) pwr: Tx power (5-20) E.g.: rf-config freq=860.100 sf=7 pwr=16 """ lora = Rak811() config = dict(key_values) if config == {}: # No parameters: returns rc_config config = lora.rf_config if ctx.obj['VERBOSE']: click.echo('Frequency: {}'.format(config['freq'])) click.echo('SF: {}'.format(config['sf'])) click.echo('BW: {}'.format(config['bw'])) click.echo('CR: {}'.format(config['cr'])) click.echo('PrLen: {}'.format(config['prlen'])) click.echo('Power: {}'.format(config['pwr'])) else: click.echo('{} {} {} {} {} {}'.format( config['freq'], config['sf'], config['bw'], config['cr'], config['prlen'], config['pwr'] )) else: # At least a parameter, set rc_config lora.rf_config = config if ctx.obj['VERBOSE']: click.echo('rf_config set: ' + ', '.join('{}={}'.format(k, v) for k, v in config.items())) lora.close() @cli.command() @click.option( '--cnt', default=1, type=click.IntRange(1, 65535), help='tx counts (1-65535)' ) @click.option( '--interval', default=60, type=click.IntRange(1, 3600), help=' tx interval (1-3600)' ) @click.option( '--binary', is_flag=True, help='Data is binary (hex encoded)' ) @click.argument( 'data', required=True ) @click.pass_context def txc(ctx, cnt, interval, binary, data): """Send LoRaP2P message.""" if binary: try: data = bytes.fromhex(data) except ValueError: click.echo('Invalid binary data') return lora = Rak811() try: lora.txc(data, cnt=cnt, interval=interval) except Rak811Error as e: print_exception(e) lora.close() return if ctx.obj['VERBOSE']: click.echo('Message sent.') lora.close() @cli.command() @click.pass_context def rxc(ctx): """Set module in LoraP2P receive mode.""" lora = Rak811() lora.rxc() if ctx.obj['VERBOSE']: click.echo('Module set in receive mode.') lora.close() @cli.command() @click.pass_context def tx_stop(ctx): """Stop LoraP2P TX.""" lora = Rak811() lora.tx_stop() if ctx.obj['VERBOSE']: click.echo('LoraP2P TX stopped.') lora.close() @cli.command() @click.pass_context def rx_stop(ctx): """Stop LoraP2P RX.""" lora = Rak811() lora.rx_stop() if ctx.obj['VERBOSE']: click.echo('LoraP2P RX stopped.') lora.close() @cli.command() @click.argument( 'timeout', required=False, default=60, type=click.INT ) @click.option( '--json', is_flag=True, help='Output message in JSON format' ) @click.pass_context def rx_get(ctx, timeout, json): """Get LoraP2P message.""" lora = Rak811() lora.rx_get(timeout) if lora.nb_downlinks: rx = lora.get_downlink() rx['data'] = rx['data'].hex() if json: click.echo(dumps(rx, indent=4)) elif ctx.obj['VERBOSE']: click.echo('Message received:') if rx['rssi']: click.echo('RSSI: {}'.format(rx['rssi'])) click.echo('SNR: {}'.format(rx['snr'])) click.echo('Data: {}'.format(rx['data'])) else: click.echo(rx['data']) elif ctx.obj['VERBOSE']: click.echo('No message available.') lora.close() @cli.command() @click.pass_context def radio_status(ctx): """Get radio statistics. Returns: TxSuccessCnt, TxErrCnt, RxSuccessCnt, RxTimeOutCnt, RxErrCnt, Rssi, Snr. """ lora = Rak811() ( tx_success_cnt, tx_err_cnt, rx_success_cnt, rx_timeout_cnt, rx_err_cnt, rssi, snr ) = lora.radio_status if ctx.obj['VERBOSE']: click.echo('TxSuccessCnt: {}'.format(tx_success_cnt)) click.echo('TxErrCnt: {}'.format(tx_err_cnt)) click.echo('RxSuccessCnt: {}'.format(rx_success_cnt)) click.echo('RxTimeOutCnt: {}'.format(rx_timeout_cnt)) click.echo('RxErrCnt: {}'.format(rx_err_cnt)) click.echo('RSSI: {}'.format(rssi)) click.echo('SNR: {}'.format(snr)) else: click.echo('{} {} {} {} {} {} {}'.format( tx_success_cnt, tx_err_cnt, rx_success_cnt, rx_timeout_cnt, rx_err_cnt, rssi, snr )) lora.close() @cli.command() @click.pass_context def clear_radio_status(ctx): """Clear radio statistics.""" lora = Rak811() lora.clear_radio_status() if ctx.obj['VERBOSE']: click.echo('Radio statistics cleared.') lora.close() if __name__ == '__main__': cli()
25.772134
79
0.587599
"""RAK811 CLI interface. Provides a command line interface for the RAK811 module (Firmware V2.0). Copyright 2019, 2021 Philippe Vanhaesendonck 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. SPDX-License-Identifier: Apache-2.0 """ from json import dumps import logging import click from .rak811 import Mode, RecvEx, Reset from .rak811 import Rak811 from .rak811 import Rak811Error from .rak811 import Rak811EventError, Rak811ResponseError, Rak811TimeoutError # Valid configuration keys for LoRaWan LW_CONFIG_KEYS = ('dev_addr', 'dev_eui', 'app_eui', 'app_key', 'nwks_key', 'apps_key', 'tx_power', 'pwr_level', 'adr', 'dr', 'public_net', 'rx_delay1', 'ch_list', 'ch_mask', 'max_chs', 'rx2', 'join_cnt', 'nbtrans', 'retrans', 'class', 'duty') # Valid configuration keys for LoRaP2P P2P_CONFIG_KEYS = { 'freq': click.FloatRange(min=860.000, max=929.900, clamp=False), 'sf': click.IntRange(min=6, max=12, clamp=False), 'bw': click.IntRange(min=0, max=2, clamp=False), 'cr': click.IntRange(min=1, max=4, clamp=False), 'prlen': click.IntRange(min=8, max=65535, clamp=False), 'pwr': click.IntRange(min=5, max=20, clamp=False) } class KeyValueParamTypeLW(click.ParamType): """Basic KEY=VALUE pair parameter type for LoRaWan.""" name = 'key-value-lorawan' def convert(self, value, param, ctx): try: (k, v) = value.split('=') k = k.lower() if k not in LW_CONFIG_KEYS: self.fail('{0} is not a valid config key'.format(k), param, ctx) return (k, v) except ValueError: self.fail('{0} is not a valid Key=Value parameter'.format(value), param, ctx) class KeyValueParamTypeP2P(click.ParamType): """Basic KEY=VALUE pair parameter type for LoRaP2P.""" name = 'key-value-p2p' def convert(self, value, param, ctx): try: (k, v) = value.split('=') k = k.lower() except ValueError: self.fail('{0} is not a valid Key=Value parameter'.format(value), param, ctx) if k not in P2P_CONFIG_KEYS: self.fail('{0} is not a valid config key'.format(k), param, ctx) v = P2P_CONFIG_KEYS[k].convert(v, param, ctx) return (k, v) def print_exception(e): """Print exception raised by the Rak811 library.""" if isinstance(e, Rak811ResponseError): click.echo('RAK811 response error {}: {}'.format(e.errno, e.strerror)) elif isinstance(e, Rak811EventError): click.echo('RAK811 event error {}: {}'.format(e.errno, e.strerror)) elif isinstance(e, Rak811TimeoutError): click.echo('RAK811 timeout: {}'.format(e)) else: click.echo('RAK811 unexpected exception {}'.format(e)) @click.group() @click.option( '-v', '--verbose', is_flag=True, help='Verbose mode' ) @click.option( '-d', '--debug', is_flag=True, help='Debug mode' ) @click.version_option() @click.pass_context def cli(ctx, verbose, debug): """Command line interface for the RAK811 module.""" ctx.ensure_object(dict) ctx.obj['VERBOSE'] = verbose logging.basicConfig(level=logging.DEBUG if debug else logging.INFO) @cli.command(name='hard-reset') @click.pass_context def hard_reset(ctx): """Hardware reset of the module. Hard reset should not be required in normal operation. It needs to be issued once after host boot, or module restart. """ lora = Rak811() lora.hard_reset() if ctx.obj['VERBOSE']: click.echo('Hard reset complete') lora.close() """System commands.""" @cli.command() @click.pass_context def version(ctx): """Get module version.""" lora = Rak811() click.echo(lora.version) lora.close() @cli.command() @click.pass_context def sleep(ctx): """Enter sleep mode.""" lora = Rak811() lora.sleep() if ctx.obj['VERBOSE']: click.echo('Sleeping') lora.close() @cli.command(name='wake-up') @click.pass_context def wake_up(ctx): """Wake up.""" lora = Rak811() lora.wake_up() if ctx.obj['VERBOSE']: click.echo('Alive!') lora.close() @cli.command() @click.argument( 'reset_type', required=True, type=click.Choice(['module', 'lora']) ) @click.pass_context def reset(ctx, reset_type): """Reset Module or LoRaWan stack.""" lora = Rak811() if reset_type == 'module': lora.reset(Reset.Module) else: lora.reset(Reset.LoRa) if ctx.obj['VERBOSE']: click.echo('{0} reset complete.'.format( 'Module' if reset_type == 'module' else 'LoRa')) lora.close() @cli.command() @click.pass_context def reload(ctx): """Set LoRaWan or LoRaP2P configurations to default.""" lora = Rak811() lora.reload() if ctx.obj['VERBOSE']: click.echo('Configuration reloaded.') lora.close() @cli.command() @click.argument( 'mode', required=False, type=click.Choice(['LoRaWan', 'LoRaP2P'], case_sensitive=False) ) @click.pass_context def mode(ctx, mode): """Get/Set mode to LoRaWan or LoRaP2P.""" lora = Rak811() if mode is None: click.echo('LoRaWan' if lora.mode == Mode.LoRaWan else 'LoRaP2P') else: mode = mode.lower() if mode == 'lorawan': lora.mode = Mode.LoRaWan else: lora.mode = Mode.LoRaP2P if ctx.obj['VERBOSE']: click.echo('Mode set to {0}.'.format( 'LoRaWan' if mode == 'lorawan' else 'LoRaP2P')) lora.close() @cli.command() @click.argument( 'recv_ex', required=False, type=click.Choice(['enable', 'disable']) ) @click.pass_context def recv_ex(ctx, recv_ex): """RSSI & SNR report on receive.""" lora = Rak811() if recv_ex is None: click.echo('Enabled' if lora.recv_ex == RecvEx.Enabled else 'Disabled') else: lora.recv_ex = ( RecvEx.Enabled if recv_ex == 'enable' else RecvEx.Disabled ) if ctx.obj['VERBOSE']: click.echo('RSSI & SNR report on receive {0}.'.format( 'Enabled' if recv_ex == 'enable' else 'Disabled')) lora.close() """LoRaWan commands.""" @cli.command() @click.argument( 'band', required=False, type=click.Choice( ['EU868', 'US915', 'AU915', 'KR920', 'AS923', 'IN865'], case_sensitive=False ) ) @click.pass_context def band(ctx, band): """Get/Set LoRaWan region.""" lora = Rak811() if band is None: click.echo(lora.band) else: band = band.upper() lora.band = band if ctx.obj['VERBOSE']: click.echo('LoRaWan region set to {0}.'.format(band)) lora.close() @cli.command() @click.argument( 'key_values', metavar='KEY=VALUE...', required=True, type=KeyValueParamTypeLW(), nargs=-1 ) @click.pass_context def set_config(ctx, key_values): """Set LoraWAN configuration. \b Arguments are specified as KEY=VALUE pairs, e.g.: set-config app_eui='APP_EUI' app_key='APP_KEY' """ lora = Rak811() kv_args = dict(key_values) try: lora.set_config(**kv_args) if ctx.obj['VERBOSE']: click.echo('LoRaWan parameters set') except Rak811Error as e: print_exception(e) lora.close() @cli.command() @click.argument( 'key', required=True, type=click.Choice(LW_CONFIG_KEYS) ) @click.pass_context def get_config(ctx, key): """Get LoraWan configuration.""" lora = Rak811() try: click.echo(lora.get_config(key)) except Rak811Error as e: print_exception(e) lora.close() @cli.command() @click.pass_context def join_otaa(ctx): """Join the configured network in OTAA mode.""" lora = Rak811() try: lora.join_otaa() if ctx.obj['VERBOSE']: click.echo('Joined in OTAA mode') except Rak811Error as e: print_exception(e) lora.close() @cli.command() @click.pass_context def join_abp(ctx): """Join the configured network in ABP mode.""" lora = Rak811() try: lora.join_abp() if ctx.obj['VERBOSE']: click.echo('Joined in ABP mode') except Rak811Error as e: print_exception(e) lora.close() @cli.command() @click.pass_context def signal(ctx): """Get (RSSI,SNR) from latest received packet.""" lora = Rak811() (rssi, snr) = lora.signal if ctx.obj['VERBOSE']: click.echo('RSSI: {0} - SNR: {1}'.format(rssi, snr)) else: click.echo('{} {}'.format(rssi, snr)) lora.close() @cli.command() @click.argument( 'dr', required=False, type=click.INT ) @click.pass_context def dr(ctx, dr): """Get/Set next send data rate.""" lora = Rak811() if dr is None: click.echo(lora.dr) else: try: lora.dr = dr if ctx.obj['VERBOSE']: click.echo('Data rate set to {0}.'.format(dr)) except Rak811Error as e: print_exception(e) lora.close() @cli.command() @click.pass_context def link_cnt(ctx): """Get up & downlink counters.""" lora = Rak811() (uplink, downlink) = lora.link_cnt if ctx.obj['VERBOSE']: click.echo('Uplink: {0} - Downlink: {1}'.format(uplink, downlink)) else: click.echo('{} {}'.format(uplink, downlink)) lora.close() @cli.command() @click.pass_context def abp_info(ctx): """Get ABP info. When using OTAA, returns the necessary info to re-join in ABP mode. The following tuple is returned: (NetworkID, DevAddr, Nwkskey, Appskey) """ lora = Rak811() (nwk_id, dev_addr, nwks_key, apps_key) = lora.abp_info if ctx.obj['VERBOSE']: click.echo('NwkId: {}'.format(nwk_id)) click.echo('DevAddr: {}'.format(dev_addr)) click.echo('Nwkskey: {}'.format(nwks_key)) click.echo('Appskey: {}'.format(apps_key)) else: click.echo('{} {} {} {}'.format(nwk_id, dev_addr, nwks_key, apps_key)) lora.close() @cli.command() @click.option( '-p', '--port', default=1, type=click.IntRange(1, 223), help='port number to use (1-223)' ) @click.option( '--confirm', is_flag=True, help='regular or confirmed send' ) @click.option( '--binary', is_flag=True, help='Data is binary (hex encoded)' ) @click.argument( 'data', required=True ) @click.option( '--json', is_flag=True, help='Output downlink in JSON format' ) @click.pass_context def send(ctx, port, confirm, binary, data, json): """Send LoRaWan message and check for downlink.""" if binary: try: data = bytes.fromhex(data) except ValueError: click.echo('Invalid binary data') return lora = Rak811() try: lora.send(data, confirm=confirm, port=port) except Rak811Error as e: print_exception(e) lora.close() return if ctx.obj['VERBOSE']: click.echo('Message sent.') if lora.nb_downlinks: downlink = lora.get_downlink() downlink['data'] = downlink['data'].hex() if json: click.echo(dumps(downlink, indent=4)) elif ctx.obj['VERBOSE']: click.echo('Downlink received:') click.echo('Port: {}'.format(downlink['port'])) if downlink['rssi']: click.echo('RSSI: {}'.format(downlink['rssi'])) click.echo('SNR: {}'.format(downlink['snr'])) click.echo('Data: {}'.format(downlink['data'])) else: click.echo(downlink['data']) elif ctx.obj['VERBOSE']: click.echo('No downlink available.') lora.close() @cli.command() @click.argument( 'key_values', metavar='KEY=VALUE...', required=False, type=KeyValueParamTypeP2P(), nargs=-1 ) @click.pass_context def rf_config(ctx, key_values): """Get/Set LoraP2P configuration. \b Without argument, returns: frequency, sf, bw, cr, prlen, pwr \b Otherwise set rf_config, Arguments are specified as KEY=VALUE pairs: freq: frequency in MHz (860.000-929.900) sf: strength factor (6-12) bw: bandwidth (0:125KHz, 1:250KHz, 2:500KHz) cr: coding rate (1:4/5, 2:4/6, 3:4/7, 4:4/8) prlen: preamble length default (8-65535) pwr: Tx power (5-20) E.g.: rf-config freq=860.100 sf=7 pwr=16 """ lora = Rak811() config = dict(key_values) if config == {}: # No parameters: returns rc_config config = lora.rf_config if ctx.obj['VERBOSE']: click.echo('Frequency: {}'.format(config['freq'])) click.echo('SF: {}'.format(config['sf'])) click.echo('BW: {}'.format(config['bw'])) click.echo('CR: {}'.format(config['cr'])) click.echo('PrLen: {}'.format(config['prlen'])) click.echo('Power: {}'.format(config['pwr'])) else: click.echo('{} {} {} {} {} {}'.format( config['freq'], config['sf'], config['bw'], config['cr'], config['prlen'], config['pwr'] )) else: # At least a parameter, set rc_config lora.rf_config = config if ctx.obj['VERBOSE']: click.echo('rf_config set: ' + ', '.join('{}={}'.format(k, v) for k, v in config.items())) lora.close() @cli.command() @click.option( '--cnt', default=1, type=click.IntRange(1, 65535), help='tx counts (1-65535)' ) @click.option( '--interval', default=60, type=click.IntRange(1, 3600), help=' tx interval (1-3600)' ) @click.option( '--binary', is_flag=True, help='Data is binary (hex encoded)' ) @click.argument( 'data', required=True ) @click.pass_context def txc(ctx, cnt, interval, binary, data): """Send LoRaP2P message.""" if binary: try: data = bytes.fromhex(data) except ValueError: click.echo('Invalid binary data') return lora = Rak811() try: lora.txc(data, cnt=cnt, interval=interval) except Rak811Error as e: print_exception(e) lora.close() return if ctx.obj['VERBOSE']: click.echo('Message sent.') lora.close() @cli.command() @click.pass_context def rxc(ctx): """Set module in LoraP2P receive mode.""" lora = Rak811() lora.rxc() if ctx.obj['VERBOSE']: click.echo('Module set in receive mode.') lora.close() @cli.command() @click.pass_context def tx_stop(ctx): """Stop LoraP2P TX.""" lora = Rak811() lora.tx_stop() if ctx.obj['VERBOSE']: click.echo('LoraP2P TX stopped.') lora.close() @cli.command() @click.pass_context def rx_stop(ctx): """Stop LoraP2P RX.""" lora = Rak811() lora.rx_stop() if ctx.obj['VERBOSE']: click.echo('LoraP2P RX stopped.') lora.close() @cli.command() @click.argument( 'timeout', required=False, default=60, type=click.INT ) @click.option( '--json', is_flag=True, help='Output message in JSON format' ) @click.pass_context def rx_get(ctx, timeout, json): """Get LoraP2P message.""" lora = Rak811() lora.rx_get(timeout) if lora.nb_downlinks: rx = lora.get_downlink() rx['data'] = rx['data'].hex() if json: click.echo(dumps(rx, indent=4)) elif ctx.obj['VERBOSE']: click.echo('Message received:') if rx['rssi']: click.echo('RSSI: {}'.format(rx['rssi'])) click.echo('SNR: {}'.format(rx['snr'])) click.echo('Data: {}'.format(rx['data'])) else: click.echo(rx['data']) elif ctx.obj['VERBOSE']: click.echo('No message available.') lora.close() @cli.command() @click.pass_context def radio_status(ctx): """Get radio statistics. Returns: TxSuccessCnt, TxErrCnt, RxSuccessCnt, RxTimeOutCnt, RxErrCnt, Rssi, Snr. """ lora = Rak811() ( tx_success_cnt, tx_err_cnt, rx_success_cnt, rx_timeout_cnt, rx_err_cnt, rssi, snr ) = lora.radio_status if ctx.obj['VERBOSE']: click.echo('TxSuccessCnt: {}'.format(tx_success_cnt)) click.echo('TxErrCnt: {}'.format(tx_err_cnt)) click.echo('RxSuccessCnt: {}'.format(rx_success_cnt)) click.echo('RxTimeOutCnt: {}'.format(rx_timeout_cnt)) click.echo('RxErrCnt: {}'.format(rx_err_cnt)) click.echo('RSSI: {}'.format(rssi)) click.echo('SNR: {}'.format(snr)) else: click.echo('{} {} {} {} {} {} {}'.format( tx_success_cnt, tx_err_cnt, rx_success_cnt, rx_timeout_cnt, rx_err_cnt, rssi, snr )) lora.close() @cli.command() @click.pass_context def clear_radio_status(ctx): """Clear radio statistics.""" lora = Rak811() lora.clear_radio_status() if ctx.obj['VERBOSE']: click.echo('Radio statistics cleared.') lora.close() if __name__ == '__main__': cli()
941
0
54
a54e466881c321eed881e10830f98325604d6d17
16,728
py
Python
code-postprocessing/cocopp/testbedsettings.py
asmaatamna/coco
4b1497a0e6d4de4a0dd75e03779d6c5349fa21ae
[ "BSD-3-Clause" ]
2
2021-02-15T17:09:24.000Z
2021-12-28T09:23:01.000Z
code-postprocessing/cocopp/testbedsettings.py
patsp/coco
4b1497a0e6d4de4a0dd75e03779d6c5349fa21ae
[ "BSD-3-Clause" ]
null
null
null
code-postprocessing/cocopp/testbedsettings.py
patsp/coco
4b1497a0e6d4de4a0dd75e03779d6c5349fa21ae
[ "BSD-3-Clause" ]
null
null
null
import os import numpy as np import warnings from . import genericsettings scenario_rlbased = 'rlbased' scenario_fixed = 'fixed' scenario_biobjfixed = 'biobjfixed' scenario_biobjrlbased = 'biobjrlbased' scenario_biobjextfixed = 'biobjextfixed' all_scenarios = [scenario_rlbased, scenario_fixed, scenario_biobjfixed, scenario_biobjrlbased, scenario_biobjextfixed] testbed_name_single = 'bbob' testbed_name_single_noisy = 'bbob-noisy' testbed_name_bi = 'bbob-biobj' testbed_name_bi_ext = 'bbob-biobj-ext' default_testbed_single = 'GECCOBBOBTestbed' default_testbed_single_noisy = 'GECCOBBOBNoisyTestbed' default_testbed_bi = 'GECCOBiObjBBOBTestbed' default_testbed_bi_ext = 'GECCOBiObjExtBBOBTestbed' current_testbed = None suite_to_testbed = { 'bbob' : default_testbed_single, 'bbob-noisy' : default_testbed_single_noisy, 'bbob-biobj' : default_testbed_bi, 'bbob-biobj-ext' : default_testbed_bi_ext } reference_values = {} def get_reference_values(algorithm): """ Returns the hash value of the hypervolume reference values for the specified algorithm (if available, i.e. if the algorithm has been run on the `bbob-biobj` testbed). If algorithm=None, all hash values are returned as a set (i.e. with no duplicates) if more than one hash is available or as a string if all hashes are the same. """ global reference_values if reference_values and algorithm in reference_values: return reference_values[algorithm] if reference_values and algorithm is None: return set(reference_values.values()) if len(set(reference_values.values())) > 1 else reference_values.values()[0] return None class Testbed(object): """this might become the future way to have settings related to testbeds TODO: how do we pass information from the benchmark to the post-processing? """ reference_algorithm_displayname = None def info(self, fun_number=None): """info on the testbed if ``fun_number is None`` or one-line info for function with number ``fun_number``. """ if fun_number is None: return self.__doc__ for line in open(os.path.join(os.path.abspath(os.path.split(__file__)[0]), self.info_filename)).readlines(): if line.split(): # ie if not empty try: # empty lines are ignored fun = int(line.split()[0]) if fun == fun_number: return 'F' + str(fun) + ' ' + ' '.join(line.split()[1:]) except ValueError: continue # ignore annotations class GECCOBBOBTestbed(Testbed): """Testbed used in the GECCO BBOB workshops 2009, 2010, 2012, 2013, 2015, and 2016. """ shortinfo_filename = 'bbob-benchmarkshortinfos.txt' pptable_target_runlengths = [0.5, 1.2, 3, 10, 50] # used in config for expensive setting pptable_targetsOfInterest = (10, 1, 1e-1, 1e-2, 1e-3, 1e-5, 1e-7) # for pptable and pptablemany settings = dict( info_filename = 'bbob-benchmarkinfos.txt', shortinfo_filename = shortinfo_filename, name = testbed_name_single, short_names = get_short_names(shortinfo_filename), hardesttargetlatex = '10^{-8}', # used for ppfigs, pptable, pptable2, and pptables ppfigs_ftarget = 1e-8, # to set target runlength in expensive setting, use genericsettings.target_runlength ppfig2_ftarget = 1e-8, ppfigdim_target_values = (10, 1, 1e-1, 1e-2, 1e-3, 1e-5, 1e-8), pprldistr_target_values = (10., 1e-1, 1e-4, 1e-8), pprldmany_target_values = 10 ** np.arange(2, -8.2, -0.2), pprldmany_target_range_latex = '$10^{[-8..2]}$', ppscatter_target_values = np.logspace(-8, 2, 21), # 21 was 46 rldValsOfInterest = (10, 1e-1, 1e-4, 1e-8), # possibly changed in config ppfvdistr_min_target = 1e-8, functions_with_legend = (1, 24, 101, 130), first_function_number = 1, last_function_number = 24, reference_values_hash_dimensions = [], pptable_ftarget = 1e-8, # value for determining the success ratio in all tables pptable_targetsOfInterest = pptable_targetsOfInterest, pptable2_targetsOfInterest = (1e+1, 1e-1, 1e-3, 1e-5, 1e-7), # used for pptable2 pptablemany_targetsOfInterest = pptable_targetsOfInterest, scenario = scenario_fixed, reference_algorithm_filename = 'refalgs/best2009-bbob.tar.gz', reference_algorithm_displayname = 'best 2009', # TODO: should be read in from data set in reference_algorithm_filename #.reference_algorithm_filename = 'data/RANDOMSEARCH' #.reference_algorithm_displayname = "RANDOMSEARCH" # TODO: should be read in from data set in reference_algorithm_filename # expensive optimization settings: pptable_target_runlengths = pptable_target_runlengths, pptable2_target_runlengths = pptable_target_runlengths, pptables_target_runlengths = pptable_target_runlengths, instancesOfInterest = None # None: consider all instances #.instancesOfInterest = {1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, # 10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 1, # 21: 1, 22: 1, 23: 1, 24: 1, 25: 1, 26: 1, 27: 1, 28: 1, 29: 1, 30: 1, # 31: 1, 32: 1, 33: 1, 34: 1, 35: 1, 36: 1, 37: 1, 38: 1, 39: 1, 40: 1, # 41: 1, 42: 1, 43: 1, 44: 1, 45: 1, 46: 1, 47: 1, 48: 1, 49: 1, 50: 1, # 51: 1, 52: 1, 53: 1, 54: 1, 55: 1, 56: 1, 57: 1, 58: 1, 59: 1, 60: 1} # consider only 2009-2016 instances #.instancesOfInterest = {1: 1, 2: 1} ) class GECCOBBOBNoisyTestbed(GECCOBBOBTestbed): """The noisy testbed used in the GECCO BBOB workshops 2009, 2010, 2012, 2013, 2015, and 2016. """ shortinfo_filename = 'bbob-noisy-benchmarkshortinfos.txt' settings = dict( info_filename = 'bbob-noisy-benchmarkinfos.txt', shortinfo_filename = shortinfo_filename, short_names = get_short_names(shortinfo_filename), name = testbed_name_single, # TODO: until we clean the code which uses this name, we need to use it also here. functions_with_legend = (101, 130), first_function_number = 101, last_function_number = 130, reference_algorithm_filename = 'refalgs/best2009-bbob-noisy.tar.gz', reference_algorithm_displayname = 'best 2009' # TODO: should be read in from data set in reference_algorithm_filename ) class GECCOBiObjBBOBTestbed(Testbed): """Testbed used in the BBOB workshops to display data sets run on the `bbob-biobj` test suite. """ shortinfo_filename = 'bbob-biobj-benchmarkshortinfos.txt' pptable_target_runlengths = [0.5, 1.2, 3, 10, 50] # used in config for expensive setting pptable_targetsOfInterest = (10, 1, 1e-1, 1e-2, 1e-3, 1e-5, 1e-7) # for pptable and pptablemany settings = dict( info_filename = 'bbob-biobj-benchmarkinfos.txt', shortinfo_filename = shortinfo_filename, name = testbed_name_bi, short_names = get_short_names(shortinfo_filename), hardesttargetlatex = '10^{-5}', # used for ppfigs, pptable, pptable2, and pptables ppfigs_ftarget = 1e-5, # to set target runlength in expensive setting, use genericsettings.target_runlength ppfig2_ftarget = 1e-5, ppfigdim_target_values = (1e-1, 1e-2, 1e-3, 1e-4, 1e-5), pprldistr_target_values = (1e-1, 1e-2, 1e-3, 1e-5), pprldmany_target_values = np.append(np.append(10 ** np.arange(0, -5.1, -0.1), [0]), -10 ** np.arange(-5, -3.9, 0.2)), pprldmany_target_range_latex = '$\{-10^{-4}, -10^{-4.2}, $ $-10^{-4.4}, -10^{-4.6}, -10^{-4.8}, -10^{-5}, 0, 10^{-5}, 10^{-4.9}, 10^{-4.8}, \dots, 10^{-0.1}, 10^0\}$', ppscatter_target_values = np.logspace(-5, 1, 21), # 21 was 51 rldValsOfInterest = (1e-1, 1e-2, 1e-3, 1e-4, 1e-5), ppfvdistr_min_target = 1e-5, functions_with_legend = (1, 30, 31, 55), first_function_number = 1, last_function_number = 55, reference_values_hash_dimensions = [2, 3, 5, 10, 20], pptable_ftarget = 1e-5, # value for determining the success ratio in all tables pptable_targetsOfInterest = (1, 1e-1, 1e-2, 1e-3, 1e-4, 1e-5), pptable2_targetsOfInterest = (1e-1, 1e-2, 1e-3, 1e-4, 1e-5), # used for pptable2 pptablemany_targetsOfInterest = (1, 1e-1, 1e-2, 1e-3), # used for pptables scenario = scenario_biobjfixed, reference_algorithm_filename = 'refalgs/best2016-bbob-biobj.tar.gz', # TODO produce correct best2016 algo and delete this line reference_algorithm_displayname = 'best 2016', # TODO: should be read in from data set in reference_algorithm_filename instancesOfInterest = {1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1}, # None, # None: consider all instances # expensive optimization settings: pptable_target_runlengths = [0.5, 1.2, 3, 10, 50], # [0.5, 2, 10, 50] # used in config for expensive setting pptable2_target_runlengths = [0.5, 1.2, 3, 10, 50], # [0.5, 2, 10, 50] # used in config for expensive setting pptables_target_runlengths = [2, 10, 50] # used in config for expensive setting ) class GECCOBiObjExtBBOBTestbed(GECCOBiObjBBOBTestbed): """Biobjective testbed to display data sets run on the `bbob-biobj-ext` test suite. """ shortinfo_filename = 'bbob-biobj-benchmarkshortinfos.txt' settings = dict( info_filename = 'bbob-biobj-benchmarkinfos.txt', shortinfo_filename = shortinfo_filename, name = testbed_name_bi_ext, short_names = get_short_names(shortinfo_filename), functions_with_legend = (1, 30, 31, 60, 61, 92), first_function_number = 1, last_function_number = 92, scenario = scenario_biobjextfixed, reference_algorithm_filename = '', # TODO produce correct best2017 algo and delete this line reference_algorithm_displayname = '', # TODO: should be read in from data set in reference_algorithm_filename instancesOfInterest = {1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1}, # None: consider all instances )
45.830137
175
0.663857
import os import numpy as np import warnings from . import genericsettings scenario_rlbased = 'rlbased' scenario_fixed = 'fixed' scenario_biobjfixed = 'biobjfixed' scenario_biobjrlbased = 'biobjrlbased' scenario_biobjextfixed = 'biobjextfixed' all_scenarios = [scenario_rlbased, scenario_fixed, scenario_biobjfixed, scenario_biobjrlbased, scenario_biobjextfixed] testbed_name_single = 'bbob' testbed_name_single_noisy = 'bbob-noisy' testbed_name_bi = 'bbob-biobj' testbed_name_bi_ext = 'bbob-biobj-ext' default_testbed_single = 'GECCOBBOBTestbed' default_testbed_single_noisy = 'GECCOBBOBNoisyTestbed' default_testbed_bi = 'GECCOBiObjBBOBTestbed' default_testbed_bi_ext = 'GECCOBiObjExtBBOBTestbed' current_testbed = None suite_to_testbed = { 'bbob' : default_testbed_single, 'bbob-noisy' : default_testbed_single_noisy, 'bbob-biobj' : default_testbed_bi, 'bbob-biobj-ext' : default_testbed_bi_ext } def load_current_testbed(testbed_name, target_values): global current_testbed if testbed_name in globals(): constructor = globals()[testbed_name] current_testbed = constructor(target_values) else: raise ValueError('Testbed class %s does not exist. Add it to testbedsettings.py to process this data.' % testbed_name) return current_testbed def get_testbed_from_suite(suite_name): if suite_name in suite_to_testbed: return suite_to_testbed[suite_name] else: raise ValueError('Mapping from suite name to testbed class for suite %s does not exist. ' 'Add it to suite_to_testbed dictionary in testbedsettings.py to process this data.' % suite_name) reference_values = {} def reset_reference_values(): global reference_values reference_values = {} def update_reference_values(algorithm, reference_value): global reference_values if reference_values and reference_values[reference_values.keys()[0]] != reference_value: warnings.warn(" Reference values for the algorithm '%s' are different from the algorithm '%s'" % (algorithm, reference_values.keys()[0])) reference_values[algorithm] = reference_value def copy_reference_values(old_algorithm_id, new_algorithm_id): global reference_values if reference_values and old_algorithm_id in reference_values and new_algorithm_id not in reference_values: reference_values[new_algorithm_id] = reference_values[old_algorithm_id] def get_reference_values(algorithm): """ Returns the hash value of the hypervolume reference values for the specified algorithm (if available, i.e. if the algorithm has been run on the `bbob-biobj` testbed). If algorithm=None, all hash values are returned as a set (i.e. with no duplicates) if more than one hash is available or as a string if all hashes are the same. """ global reference_values if reference_values and algorithm in reference_values: return reference_values[algorithm] if reference_values and algorithm is None: return set(reference_values.values()) if len(set(reference_values.values())) > 1 else reference_values.values()[0] return None def get_first_reference_values(): global reference_values if reference_values and len(reference_values) > 0: return reference_values[reference_values.keys()[0]] return None def get_short_names(file_name): try: info_list = open(os.path.join(os.path.dirname(__file__), file_name), 'r').read().split('\n') info_dict = {} for line in info_list: if len(line) == 0 or line.startswith('%') or line.isspace() : continue key_val = line.split(' ', 1) if len(key_val) > 1: info_dict[int(key_val[0])] = key_val[1] return info_dict except: warnings.warn('benchmark infos not found') print(os.path.join(os.path.dirname(__file__), file_name)) class Testbed(object): """this might become the future way to have settings related to testbeds TODO: how do we pass information from the benchmark to the post-processing? """ reference_algorithm_displayname = None def info(self, fun_number=None): """info on the testbed if ``fun_number is None`` or one-line info for function with number ``fun_number``. """ if fun_number is None: return self.__doc__ for line in open(os.path.join(os.path.abspath(os.path.split(__file__)[0]), self.info_filename)).readlines(): if line.split(): # ie if not empty try: # empty lines are ignored fun = int(line.split()[0]) if fun == fun_number: return 'F' + str(fun) + ' ' + ' '.join(line.split()[1:]) except ValueError: continue # ignore annotations class GECCOBBOBTestbed(Testbed): """Testbed used in the GECCO BBOB workshops 2009, 2010, 2012, 2013, 2015, and 2016. """ shortinfo_filename = 'bbob-benchmarkshortinfos.txt' pptable_target_runlengths = [0.5, 1.2, 3, 10, 50] # used in config for expensive setting pptable_targetsOfInterest = (10, 1, 1e-1, 1e-2, 1e-3, 1e-5, 1e-7) # for pptable and pptablemany settings = dict( info_filename = 'bbob-benchmarkinfos.txt', shortinfo_filename = shortinfo_filename, name = testbed_name_single, short_names = get_short_names(shortinfo_filename), hardesttargetlatex = '10^{-8}', # used for ppfigs, pptable, pptable2, and pptables ppfigs_ftarget = 1e-8, # to set target runlength in expensive setting, use genericsettings.target_runlength ppfig2_ftarget = 1e-8, ppfigdim_target_values = (10, 1, 1e-1, 1e-2, 1e-3, 1e-5, 1e-8), pprldistr_target_values = (10., 1e-1, 1e-4, 1e-8), pprldmany_target_values = 10 ** np.arange(2, -8.2, -0.2), pprldmany_target_range_latex = '$10^{[-8..2]}$', ppscatter_target_values = np.logspace(-8, 2, 21), # 21 was 46 rldValsOfInterest = (10, 1e-1, 1e-4, 1e-8), # possibly changed in config ppfvdistr_min_target = 1e-8, functions_with_legend = (1, 24, 101, 130), first_function_number = 1, last_function_number = 24, reference_values_hash_dimensions = [], pptable_ftarget = 1e-8, # value for determining the success ratio in all tables pptable_targetsOfInterest = pptable_targetsOfInterest, pptable2_targetsOfInterest = (1e+1, 1e-1, 1e-3, 1e-5, 1e-7), # used for pptable2 pptablemany_targetsOfInterest = pptable_targetsOfInterest, scenario = scenario_fixed, reference_algorithm_filename = 'refalgs/best2009-bbob.tar.gz', reference_algorithm_displayname = 'best 2009', # TODO: should be read in from data set in reference_algorithm_filename #.reference_algorithm_filename = 'data/RANDOMSEARCH' #.reference_algorithm_displayname = "RANDOMSEARCH" # TODO: should be read in from data set in reference_algorithm_filename # expensive optimization settings: pptable_target_runlengths = pptable_target_runlengths, pptable2_target_runlengths = pptable_target_runlengths, pptables_target_runlengths = pptable_target_runlengths, instancesOfInterest = None # None: consider all instances #.instancesOfInterest = {1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, # 10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 1, # 21: 1, 22: 1, 23: 1, 24: 1, 25: 1, 26: 1, 27: 1, 28: 1, 29: 1, 30: 1, # 31: 1, 32: 1, 33: 1, 34: 1, 35: 1, 36: 1, 37: 1, 38: 1, 39: 1, 40: 1, # 41: 1, 42: 1, 43: 1, 44: 1, 45: 1, 46: 1, 47: 1, 48: 1, 49: 1, 50: 1, # 51: 1, 52: 1, 53: 1, 54: 1, 55: 1, 56: 1, 57: 1, 58: 1, 59: 1, 60: 1} # consider only 2009-2016 instances #.instancesOfInterest = {1: 1, 2: 1} ) def __init__(self, targetValues): for key, val in GECCOBBOBTestbed.settings.items(): setattr(self, key, val) # set targets according to targetValues class (possibly all changed # in config: self.ppfigdim_target_values = targetValues(self.ppfigdim_target_values) self.pprldistr_target_values = targetValues(self.pprldistr_target_values) self.pprldmany_target_values = targetValues(self.pprldmany_target_values) self.ppscatter_target_values = targetValues(self.ppscatter_target_values) self.pptable_targetsOfInterest = targetValues(self.pptable_targetsOfInterest) self.pptable2_targetsOfInterest = targetValues(self.pptable2_targetsOfInterest) self.pptablemany_targetsOfInterest = targetValues(self.pptablemany_targetsOfInterest) if 11 < 3: # override settings if needed... #self.reference_algorithm_filename = 'best09-16-bbob.tar.gz' #self.reference_algorithm_displayname = 'best 2009--16' # TODO: should be read in from data set in reference_algorithm_filename #self.reference_algorithm_filename = 'data/RANDOMSEARCH' #self.reference_algorithm_displayname = "RANDOMSEARCH" # TODO: should be read in from data set in reference_algorithm_filename self.short_names = get_short_names(self.shortinfo_filename) self.instancesOfInterest = {1: 1, 2: 1, 3: 1, 4: 1, 5: 1} class GECCOBBOBNoisyTestbed(GECCOBBOBTestbed): """The noisy testbed used in the GECCO BBOB workshops 2009, 2010, 2012, 2013, 2015, and 2016. """ shortinfo_filename = 'bbob-noisy-benchmarkshortinfos.txt' settings = dict( info_filename = 'bbob-noisy-benchmarkinfos.txt', shortinfo_filename = shortinfo_filename, short_names = get_short_names(shortinfo_filename), name = testbed_name_single, # TODO: until we clean the code which uses this name, we need to use it also here. functions_with_legend = (101, 130), first_function_number = 101, last_function_number = 130, reference_algorithm_filename = 'refalgs/best2009-bbob-noisy.tar.gz', reference_algorithm_displayname = 'best 2009' # TODO: should be read in from data set in reference_algorithm_filename ) def __init__(self, target_values): super(GECCOBBOBNoisyTestbed, self).__init__(target_values) for key, val in GECCOBBOBNoisyTestbed.settings.items(): setattr(self, key, val) if 11 < 3: # override settings if needed... self.reference_algorithm_filename = 'best09-16-bbob-noisy.tar.gz' self.reference_algorithm_displayname = 'best 2009--16' # TODO: should be read in from data set in reference_algorithm_filename class GECCOBiObjBBOBTestbed(Testbed): """Testbed used in the BBOB workshops to display data sets run on the `bbob-biobj` test suite. """ shortinfo_filename = 'bbob-biobj-benchmarkshortinfos.txt' pptable_target_runlengths = [0.5, 1.2, 3, 10, 50] # used in config for expensive setting pptable_targetsOfInterest = (10, 1, 1e-1, 1e-2, 1e-3, 1e-5, 1e-7) # for pptable and pptablemany settings = dict( info_filename = 'bbob-biobj-benchmarkinfos.txt', shortinfo_filename = shortinfo_filename, name = testbed_name_bi, short_names = get_short_names(shortinfo_filename), hardesttargetlatex = '10^{-5}', # used for ppfigs, pptable, pptable2, and pptables ppfigs_ftarget = 1e-5, # to set target runlength in expensive setting, use genericsettings.target_runlength ppfig2_ftarget = 1e-5, ppfigdim_target_values = (1e-1, 1e-2, 1e-3, 1e-4, 1e-5), pprldistr_target_values = (1e-1, 1e-2, 1e-3, 1e-5), pprldmany_target_values = np.append(np.append(10 ** np.arange(0, -5.1, -0.1), [0]), -10 ** np.arange(-5, -3.9, 0.2)), pprldmany_target_range_latex = '$\{-10^{-4}, -10^{-4.2}, $ $-10^{-4.4}, -10^{-4.6}, -10^{-4.8}, -10^{-5}, 0, 10^{-5}, 10^{-4.9}, 10^{-4.8}, \dots, 10^{-0.1}, 10^0\}$', ppscatter_target_values = np.logspace(-5, 1, 21), # 21 was 51 rldValsOfInterest = (1e-1, 1e-2, 1e-3, 1e-4, 1e-5), ppfvdistr_min_target = 1e-5, functions_with_legend = (1, 30, 31, 55), first_function_number = 1, last_function_number = 55, reference_values_hash_dimensions = [2, 3, 5, 10, 20], pptable_ftarget = 1e-5, # value for determining the success ratio in all tables pptable_targetsOfInterest = (1, 1e-1, 1e-2, 1e-3, 1e-4, 1e-5), pptable2_targetsOfInterest = (1e-1, 1e-2, 1e-3, 1e-4, 1e-5), # used for pptable2 pptablemany_targetsOfInterest = (1, 1e-1, 1e-2, 1e-3), # used for pptables scenario = scenario_biobjfixed, reference_algorithm_filename = 'refalgs/best2016-bbob-biobj.tar.gz', # TODO produce correct best2016 algo and delete this line reference_algorithm_displayname = 'best 2016', # TODO: should be read in from data set in reference_algorithm_filename instancesOfInterest = {1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1}, # None, # None: consider all instances # expensive optimization settings: pptable_target_runlengths = [0.5, 1.2, 3, 10, 50], # [0.5, 2, 10, 50] # used in config for expensive setting pptable2_target_runlengths = [0.5, 1.2, 3, 10, 50], # [0.5, 2, 10, 50] # used in config for expensive setting pptables_target_runlengths = [2, 10, 50] # used in config for expensive setting ) def __init__(self, targetValues): for key, val in GECCOBiObjBBOBTestbed.settings.items(): setattr(self, key, val) # set targets according to targetValues class (possibly all changed # in config: self.ppfigdim_target_values = targetValues(self.ppfigdim_target_values) self.pprldistr_target_values = targetValues(self.pprldistr_target_values) self.pprldmany_target_values = targetValues(self.pprldmany_target_values) self.ppscatter_target_values = targetValues(self.ppscatter_target_values) self.pptable_targetsOfInterest = targetValues(self.pptable_targetsOfInterest) self.pptable2_targetsOfInterest = targetValues(self.pptable2_targetsOfInterest) self.pptablemany_targetsOfInterest = targetValues(self.pptablemany_targetsOfInterest) if 11 < 3: # override settings if needed... #self.reference_algorithm_filename = 'refalgs/best2016-bbob-biobj-NEW.tar.gz' #self.reference_algorithm_displayname = 'best 2016' # TODO: should be read in from data set in reference_algorithm_filename #self.short_names = get_short_names(self.shortinfo_filename) self.instancesOfInterest = {1: 1, 2: 1, 3: 1, 4: 1, 5: 1} class GECCOBiObjExtBBOBTestbed(GECCOBiObjBBOBTestbed): """Biobjective testbed to display data sets run on the `bbob-biobj-ext` test suite. """ shortinfo_filename = 'bbob-biobj-benchmarkshortinfos.txt' settings = dict( info_filename = 'bbob-biobj-benchmarkinfos.txt', shortinfo_filename = shortinfo_filename, name = testbed_name_bi_ext, short_names = get_short_names(shortinfo_filename), functions_with_legend = (1, 30, 31, 60, 61, 92), first_function_number = 1, last_function_number = 92, scenario = scenario_biobjextfixed, reference_algorithm_filename = '', # TODO produce correct best2017 algo and delete this line reference_algorithm_displayname = '', # TODO: should be read in from data set in reference_algorithm_filename instancesOfInterest = {1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1}, # None: consider all instances ) def __init__(self, targetValues): super(GECCOBiObjExtBBOBTestbed, self).__init__(targetValues) for key, val in GECCOBiObjExtBBOBTestbed.settings.items(): setattr(self, key, val) if 11 < 3: # override settings if needed... self.reference_algorithm_filename = 'refalgs/best2017-bbob-biobj-ext.tar.gz' self.reference_algorithm_displayname = 'best 2017' # TODO: should be read in from data set in reference_algorithm_filename self.short_names = get_short_names(self.shortinfo_filename) self.instancesOfInterest = {1: 1, 2: 1, 3: 1, 4: 1, 5: 1}
5,994
0
269
d05bdb90e6a92f83d84b67e331d6c3e5b11a35e9
11,679
py
Python
gdal2tile-mapslicer/mapslicer/pp/ppserver.py
13903596952/gdal2tiles
5bfb8373da4776cab57e0cc58e7422fcedbe2315
[ "Apache-2.0" ]
44
2015-03-20T23:12:34.000Z
2022-01-09T16:00:19.000Z
mapslicer/pp/ppserver.py
himaps/mapslicer
1c60a2d4d3c0296424b2421e09001fcf32075c6e
[ "BSD-3-Clause" ]
12
2015-02-16T20:41:25.000Z
2021-05-01T05:21:34.000Z
mapslicer/pp/ppserver.py
kalxas/maptiler
1c60a2d4d3c0296424b2421e09001fcf32075c6e
[ "BSD-3-Clause" ]
20
2015-02-16T20:25:50.000Z
2021-11-02T12:11:11.000Z
#!/usr/bin/env python # Parallel Python Software: http://www.parallelpython.com # Copyright (c) 2005-2009, Vitalii Vanovschi # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the author nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. """ Parallel Python Software, Network Server http://www.parallelpython.com - updates, documentation, examples and support forums """ import logging import getopt import sys import socket import thread import random import string import time import os import pptransport import ppauto from pp import Server copyright = "Copyright (c) 2005-2009 Vitalii Vanovschi. All rights reserved" version = "1.5.7" # compartibility with Python 2.6 try: import hashlib sha_new = hashlib.sha1 except ImportError: import sha sha_new = sha.new class _NetworkServer(Server): """Network Server Class """ def ncon_add(self, val): """Keeps track of the number of connections and time of the last one""" self.ncon_lock.acquire() self.ncon += val self.last_con_time = time.time() self.ncon_lock.release() def check_timeout(self): """Checks if timeout happened and shutdowns server if it did""" while True: if self.ncon == 0: idle_time = time.time() - self.last_con_time if idle_time < self.timeout: time.sleep(self.timeout - idle_time) else: logging.debug("exiting ppserver due to timeout (no client"\ " connections in last %i sec)", self.timeout) os._exit(0) else: time.sleep(self.timeout) def listen(self): """Initiates listenting to incoming connections""" try: ssocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # following allows ppserver to restart faster on the same port ssocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ssocket.bind((self.host, self.port)) ssocket.listen(5) except socket.error: logging.error("Cannot create socket with port " + str(self.port) + " (port is already in use)") try: while 1: #accept connections from outside (csocket, address) = ssocket.accept() #now do something with the clientsocket #in this case, we'll pretend this is a threaded server thread.start_new_thread(self.crun, (csocket, )) except: logging.debug("Closing server socket") ssocket.close() def crun(self, csocket): """Authenticates client and handles its jobs""" mysocket = pptransport.CSocketTransport(csocket) #send PP version mysocket.send(version) #generate a random string srandom = "".join([random.choice(string.ascii_letters) for i in xrange(16)]) mysocket.send(srandom) answer = sha_new(srandom+self.secret).hexdigest() cleintanswer = mysocket.receive() if answer != cleintanswer: logging.warning("Authentification failed, client host=%s, port=%i" % csocket.getpeername()) mysocket.send("FAILED") csocket.close() return else: mysocket.send("OK") ctype = mysocket.receive() logging.debug("Control message received: " + ctype) self.ncon_add(1) try: if ctype == "STAT": #reset time at each new connection self.get_stats()["local"].time = 0.0 mysocket.send(str(self.get_ncpus())) while 1: mysocket.receive() mysocket.send(str(self.get_stats()["local"].time)) elif ctype=="EXEC": while 1: sfunc = mysocket.creceive() sargs = mysocket.receive() fun = self.insert(sfunc, sargs) sresult = fun(True) mysocket.send(sresult) except: #print sys.excepthook(*sys.exc_info()) logging.debug("Closing client socket") csocket.close() self.ncon_add(-1) def broadcast(self): """Initiaates auto-discovery mechanism""" discover = ppauto.Discover(self) thread.start_new_thread(discover.run, ((self.host, self.port), (self.bcast, self.port)), ) def parse_config(file_loc): """ Parses a config file in a very forgiving way. """ # If we don't have configobj installed then let the user know and exit try: from configobj import ConfigObj except ImportError, ie: print >> sys.stderr, "ERROR: You must have configobj installed to use \ configuration files. You can still use command line switches." sys.exit(1) if not os.access(file_loc, os.F_OK): print >> sys.stderr, "ERROR: Can not access %s." % arg sys.exit(1) # Load the configuration file config = ConfigObj(file_loc) # try each config item and use the result if it exists. If it doesn't # then simply pass and move along try: args['secret'] = config['general'].get('secret') except: pass try: autodiscovery = config['network'].as_bool('autodiscovery') except: pass try: args['interface'] = config['network'].get('interface', default="0.0.0.0") except: pass try: args['broadcast'] = config['network'].get('broadcast') except: pass try: args['port'] = config['network'].as_int('port') except: pass try: args['loglevel'] = config['general'].as_bool('debug') except: pass try: args['ncpus'] = config['general'].as_int('workers') except: pass try: args['proto'] = config['general'].as_int('proto') except: pass try: args['restart'] = config['general'].as_bool('restart') except: pass try: args['timeout'] = config['network'].as_int('timeout') except: pass # Return a tuple of the args dict and autodiscovery variable return args, autodiscovery def print_usage(): """Prints help""" print "Parallel Python Network Server (pp-" + version + ")" print "Usage: ppserver.py [-hdar] [-n proto] [-c config_path]"\ " [-i interface] [-b broadcast] [-p port] [-w nworkers]"\ " [-s secret] [-t seconds]" print print "Options: " print "-h : this help message" print "-d : debug" print "-a : enable auto-discovery service" print "-r : restart worker process after each"\ " task completion" print "-n proto : protocol number for pickle module" print "-c path : path to config file" print "-i interface : interface to listen" print "-b broadcast : broadcast address for auto-discovery service" print "-p port : port to listen" print "-w nworkers : number of workers to start" print "-s secret : secret for authentication" print "-t seconds : timeout to exit if no connections with "\ "clients exist" print print "Due to the security concerns always use a non-trivial secret key." print "Secret key set by -s switch will override secret key assigned by" print "pp_secret variable in .pythonrc.py" print print "Please visit http://www.parallelpython.com for extended up-to-date" print "documentation, examples and support forums" if __name__ == "__main__": try: opts, args = getopt.getopt(sys.argv[1:], "hdarn:c:b:i:p:w:s:t:", ["help"]) except getopt.GetoptError: print_usage() sys.exit(1) args = {} autodiscovery = False for opt, arg in opts: if opt in ("-h", "--help"): print_usage() sys.exit() elif opt == "-c": args, autodiscovery = parse_config(arg) elif opt == "-d": args["loglevel"] = logging.DEBUG elif opt == "-i": args["interface"] = arg elif opt == "-s": args["secret"] = arg elif opt == "-p": args["port"] = int(arg) elif opt == "-w": args["ncpus"] = int(arg) elif opt == "-a": autodiscovery = True elif opt == "-r": args["restart"] = True elif opt == "-b": args["broadcast"] = arg elif opt == "-n": args["proto"] = int(arg) elif opt == "-t": args["timeout"] = int(arg) server = _NetworkServer(**args) if autodiscovery: server.broadcast() server.listen() #have to destroy it here explicitelly otherwise an exception #comes out in Python 2.4 del server # Parallel Python Software: http://www.parallelpython.com
34.553254
79
0.587379
#!/usr/bin/env python # Parallel Python Software: http://www.parallelpython.com # Copyright (c) 2005-2009, Vitalii Vanovschi # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the author nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. """ Parallel Python Software, Network Server http://www.parallelpython.com - updates, documentation, examples and support forums """ import logging import getopt import sys import socket import thread import random import string import time import os import pptransport import ppauto from pp import Server copyright = "Copyright (c) 2005-2009 Vitalii Vanovschi. All rights reserved" version = "1.5.7" # compartibility with Python 2.6 try: import hashlib sha_new = hashlib.sha1 except ImportError: import sha sha_new = sha.new class _NetworkServer(Server): """Network Server Class """ def __init__(self, ncpus="autodetect", interface="0.0.0.0", broadcast="255.255.255.255", port=None, secret=None, timeout=None, loglevel=logging.WARNING, restart=False, proto=0): Server.__init__(self, ncpus, secret=secret, loglevel=loglevel, restart=restart, proto=proto) self.host = interface self.bcast = broadcast if port is not None: self.port = port else: self.port = self.default_port self.timeout = timeout self.ncon = 0 self.last_con_time = time.time() self.ncon_lock = thread.allocate_lock() logging.debug("Strarting network server interface=%s port=%i" % (self.host, self.port)) if self.timeout is not None: logging.debug("ppserver will exit in %i seconds if no "\ "connections with clients exist" % (self.timeout)) thread.start_new_thread(self.check_timeout, ()) def ncon_add(self, val): """Keeps track of the number of connections and time of the last one""" self.ncon_lock.acquire() self.ncon += val self.last_con_time = time.time() self.ncon_lock.release() def check_timeout(self): """Checks if timeout happened and shutdowns server if it did""" while True: if self.ncon == 0: idle_time = time.time() - self.last_con_time if idle_time < self.timeout: time.sleep(self.timeout - idle_time) else: logging.debug("exiting ppserver due to timeout (no client"\ " connections in last %i sec)", self.timeout) os._exit(0) else: time.sleep(self.timeout) def listen(self): """Initiates listenting to incoming connections""" try: ssocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # following allows ppserver to restart faster on the same port ssocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ssocket.bind((self.host, self.port)) ssocket.listen(5) except socket.error: logging.error("Cannot create socket with port " + str(self.port) + " (port is already in use)") try: while 1: #accept connections from outside (csocket, address) = ssocket.accept() #now do something with the clientsocket #in this case, we'll pretend this is a threaded server thread.start_new_thread(self.crun, (csocket, )) except: logging.debug("Closing server socket") ssocket.close() def crun(self, csocket): """Authenticates client and handles its jobs""" mysocket = pptransport.CSocketTransport(csocket) #send PP version mysocket.send(version) #generate a random string srandom = "".join([random.choice(string.ascii_letters) for i in xrange(16)]) mysocket.send(srandom) answer = sha_new(srandom+self.secret).hexdigest() cleintanswer = mysocket.receive() if answer != cleintanswer: logging.warning("Authentification failed, client host=%s, port=%i" % csocket.getpeername()) mysocket.send("FAILED") csocket.close() return else: mysocket.send("OK") ctype = mysocket.receive() logging.debug("Control message received: " + ctype) self.ncon_add(1) try: if ctype == "STAT": #reset time at each new connection self.get_stats()["local"].time = 0.0 mysocket.send(str(self.get_ncpus())) while 1: mysocket.receive() mysocket.send(str(self.get_stats()["local"].time)) elif ctype=="EXEC": while 1: sfunc = mysocket.creceive() sargs = mysocket.receive() fun = self.insert(sfunc, sargs) sresult = fun(True) mysocket.send(sresult) except: #print sys.excepthook(*sys.exc_info()) logging.debug("Closing client socket") csocket.close() self.ncon_add(-1) def broadcast(self): """Initiaates auto-discovery mechanism""" discover = ppauto.Discover(self) thread.start_new_thread(discover.run, ((self.host, self.port), (self.bcast, self.port)), ) def parse_config(file_loc): """ Parses a config file in a very forgiving way. """ # If we don't have configobj installed then let the user know and exit try: from configobj import ConfigObj except ImportError, ie: print >> sys.stderr, "ERROR: You must have configobj installed to use \ configuration files. You can still use command line switches." sys.exit(1) if not os.access(file_loc, os.F_OK): print >> sys.stderr, "ERROR: Can not access %s." % arg sys.exit(1) # Load the configuration file config = ConfigObj(file_loc) # try each config item and use the result if it exists. If it doesn't # then simply pass and move along try: args['secret'] = config['general'].get('secret') except: pass try: autodiscovery = config['network'].as_bool('autodiscovery') except: pass try: args['interface'] = config['network'].get('interface', default="0.0.0.0") except: pass try: args['broadcast'] = config['network'].get('broadcast') except: pass try: args['port'] = config['network'].as_int('port') except: pass try: args['loglevel'] = config['general'].as_bool('debug') except: pass try: args['ncpus'] = config['general'].as_int('workers') except: pass try: args['proto'] = config['general'].as_int('proto') except: pass try: args['restart'] = config['general'].as_bool('restart') except: pass try: args['timeout'] = config['network'].as_int('timeout') except: pass # Return a tuple of the args dict and autodiscovery variable return args, autodiscovery def print_usage(): """Prints help""" print "Parallel Python Network Server (pp-" + version + ")" print "Usage: ppserver.py [-hdar] [-n proto] [-c config_path]"\ " [-i interface] [-b broadcast] [-p port] [-w nworkers]"\ " [-s secret] [-t seconds]" print print "Options: " print "-h : this help message" print "-d : debug" print "-a : enable auto-discovery service" print "-r : restart worker process after each"\ " task completion" print "-n proto : protocol number for pickle module" print "-c path : path to config file" print "-i interface : interface to listen" print "-b broadcast : broadcast address for auto-discovery service" print "-p port : port to listen" print "-w nworkers : number of workers to start" print "-s secret : secret for authentication" print "-t seconds : timeout to exit if no connections with "\ "clients exist" print print "Due to the security concerns always use a non-trivial secret key." print "Secret key set by -s switch will override secret key assigned by" print "pp_secret variable in .pythonrc.py" print print "Please visit http://www.parallelpython.com for extended up-to-date" print "documentation, examples and support forums" if __name__ == "__main__": try: opts, args = getopt.getopt(sys.argv[1:], "hdarn:c:b:i:p:w:s:t:", ["help"]) except getopt.GetoptError: print_usage() sys.exit(1) args = {} autodiscovery = False for opt, arg in opts: if opt in ("-h", "--help"): print_usage() sys.exit() elif opt == "-c": args, autodiscovery = parse_config(arg) elif opt == "-d": args["loglevel"] = logging.DEBUG elif opt == "-i": args["interface"] = arg elif opt == "-s": args["secret"] = arg elif opt == "-p": args["port"] = int(arg) elif opt == "-w": args["ncpus"] = int(arg) elif opt == "-a": autodiscovery = True elif opt == "-r": args["restart"] = True elif opt == "-b": args["broadcast"] = arg elif opt == "-n": args["proto"] = int(arg) elif opt == "-t": args["timeout"] = int(arg) server = _NetworkServer(**args) if autodiscovery: server.broadcast() server.listen() #have to destroy it here explicitelly otherwise an exception #comes out in Python 2.4 del server # Parallel Python Software: http://www.parallelpython.com
988
0
27
f2d2f5392bab021e4b228788a197e370981a420f
66
py
Python
data/__init__.py
gjghks/SAS
d7624f02eb9658e10a2e66380c4b25f006a95e51
[ "MIT" ]
1
2022-03-23T03:31:26.000Z
2022-03-23T03:31:26.000Z
data/__init__.py
gjghks/SAS
d7624f02eb9658e10a2e66380c4b25f006a95e51
[ "MIT" ]
null
null
null
data/__init__.py
gjghks/SAS
d7624f02eb9658e10a2e66380c4b25f006a95e51
[ "MIT" ]
null
null
null
from .config import * import torch import cv2 import numpy as np
11
21
0.772727
from .config import * import torch import cv2 import numpy as np
0
0
0
fc66478b7ed6885d2b1e726b852435e4ae36da7a
1,496
py
Python
speakers/views.py
cornend/church_site
8d61a4fa3fcbdc88b6cd95fb81d23994756a1128
[ "MIT" ]
null
null
null
speakers/views.py
cornend/church_site
8d61a4fa3fcbdc88b6cd95fb81d23994756a1128
[ "MIT" ]
44
2020-05-13T20:15:26.000Z
2022-03-04T02:58:58.000Z
speakers/views.py
cornend/church_site
8d61a4fa3fcbdc88b6cd95fb81d23994756a1128
[ "MIT" ]
4
2020-06-05T17:59:52.000Z
2021-02-06T19:09:43.000Z
from django.contrib.auth.mixins import PermissionRequiredMixin from django.urls import reverse_lazy from django.views.generic.edit import FormMixin from church_site.views import AdminListView, BaseCreateView, BaseUpdateView from .forms import SpeakerCreateForm from .models import Speaker
36.487805
75
0.772727
from django.contrib.auth.mixins import PermissionRequiredMixin from django.urls import reverse_lazy from django.views.generic.edit import FormMixin from church_site.views import AdminListView, BaseCreateView, BaseUpdateView from .forms import SpeakerCreateForm from .models import Speaker class SpeakersAdminListView(PermissionRequiredMixin, AdminListView): permission_required = 'speakers.view_speaker' model = Speaker template_name = 'speakers/speakers-admin-list.html' context_object_name = 'speakers' page_title = 'Speakers - Admin' current_page = 'manage' btn_add_href = reverse_lazy('speakers:speakers-admin-create') class SpeakersAdminCreateView(PermissionRequiredMixin, BaseCreateView): permission_required = 'speakers.add_speaker' model = Speaker template_name = 'admin-form-view.html' form_class = SpeakerCreateForm page_title = 'New Speaker - Admin' current_page = 'manage' btn_back_href = reverse_lazy('speakers:speakers-admin-list') success_url = reverse_lazy('speakers:speakers-admin-list') class SpeakerAdminUpdateView(PermissionRequiredMixin, BaseUpdateView): permission_required = 'speakers.change_speaker' model = Speaker template_name = 'admin-form-view.html' form_class = SpeakerCreateForm page_title = 'Update Speaker - Admin' current_page = 'manage' btn_back_href = reverse_lazy('speakers:speakers-admin-list') success_url = reverse_lazy('speakers:speakers-admin-list')
0
1,129
69
bf87e4023cb1c5cc6c8cb40d4677fb819d5cc6e4
470
py
Python
dist/py/relay.py
microsoft/jacdac
2c6548b7e55ac34141e5152c664ca268e873cf09
[ "CC-BY-4.0", "MIT" ]
31
2020-07-24T14:49:32.000Z
2022-03-20T12:20:56.000Z
dist/py/relay.py
microsoft/jacdac
2c6548b7e55ac34141e5152c664ca268e873cf09
[ "CC-BY-4.0", "MIT" ]
747
2020-07-31T22:05:45.000Z
2022-03-31T23:27:35.000Z
dist/py/relay.py
microsoft/jacdac
2c6548b7e55ac34141e5152c664ca268e873cf09
[ "CC-BY-4.0", "MIT" ]
17
2020-07-31T10:49:01.000Z
2022-03-15T03:21:43.000Z
# Autogenerated file for Relay # Add missing from ... import const _JD_SERVICE_CLASS_RELAY = const(0x183fe656) _JD_RELAY_VARIANT_ELECTROMECHANICAL = const(0x1) _JD_RELAY_VARIANT_SOLID_STATE = const(0x2) _JD_RELAY_VARIANT_REED = const(0x3) _JD_RELAY_REG_CLOSED = const(JD_REG_INTENSITY) _JD_RELAY_REG_VARIANT = const(JD_REG_VARIANT) _JD_RELAY_REG_MAX_SWITCHING_CURRENT = const(0x180) _JD_RELAY_EV_ACTIVE = const(JD_EV_ACTIVE) _JD_RELAY_EV_INACTIVE = const(JD_EV_INACTIVE)
42.727273
50
0.851064
# Autogenerated file for Relay # Add missing from ... import const _JD_SERVICE_CLASS_RELAY = const(0x183fe656) _JD_RELAY_VARIANT_ELECTROMECHANICAL = const(0x1) _JD_RELAY_VARIANT_SOLID_STATE = const(0x2) _JD_RELAY_VARIANT_REED = const(0x3) _JD_RELAY_REG_CLOSED = const(JD_REG_INTENSITY) _JD_RELAY_REG_VARIANT = const(JD_REG_VARIANT) _JD_RELAY_REG_MAX_SWITCHING_CURRENT = const(0x180) _JD_RELAY_EV_ACTIVE = const(JD_EV_ACTIVE) _JD_RELAY_EV_INACTIVE = const(JD_EV_INACTIVE)
0
0
0
9edf97789321d9901bac7d3458335d78de943376
3,806
py
Python
config.py
stummyhurt/auto-emby-accounts
f6ee172ffa704a4eb23b41bef25be2136b3cf5bc
[ "MIT" ]
4
2020-07-13T16:57:41.000Z
2020-12-05T16:18:57.000Z
config.py
seansusmilch/auto-emby-accounts
f6ee172ffa704a4eb23b41bef25be2136b3cf5bc
[ "MIT" ]
1
2020-05-14T03:01:30.000Z
2020-05-14T03:01:30.000Z
config.py
seansusmilch/auto-emby-accounts
f6ee172ffa704a4eb23b41bef25be2136b3cf5bc
[ "MIT" ]
2
2021-09-17T05:32:13.000Z
2022-02-14T13:46:40.000Z
# Different Logging Levels # 4: DEBUG # 3: INFO # 2: WARNING # 1: ERROR # 0: CRITICAL log_level = 3 # When set true, if the script finds a user that already exists, # the script will attempt to change the policy of that user, # and add the emby connect account to that user. overwrite = False # The url to your Emby server emby_base_url = 'http://localhost:8096' # Login info for an account on your Emby server that has admin privileges # Username emby_admin_uname = '' # Password emby_admin_passwd = '' # The script will avoid doing anything to these users AND admin_uname avoid_users = [ 'Python', 'Admin1122' ] # number of seconds before the first request will timeout. timeout = 2 # Determine whether or not to output in tsv format. Will be text if False tsv_out = True # If all thats provided is a connect username, this prefix will be put at # the start of the username on the server user_prefix = '!' # These are the user policy changes that will be made. Can be empty user_policy = { 'IsAdministrator': False, # True|False 'IsHidden': True, # True|False 'IsHiddenRemotely': True, # True|False 'IsDisabled': False, # True|False # 'MaxParentalRating': None, # int|None # 'BlockedTags': [], # string[] # 'EnableUserPreferenceAccess': True, # True|False # 'AccessSchedules': [], # [Configuration.AccessSchedule{...}] # 'BlockUnratedItems': [], # string[Movie, Trailer, Series, Music, Game, Book, LiveTvChannel, LiveTvProgram, ChannelContent, Other] 'EnableRemoteControlOfOtherUsers': False, # True|False 'EnableSharedDeviceControl': True, # True|False 'EnableRemoteAccess': True, # True|False 'EnableLiveTvManagement': False, # True|False 'EnableLiveTvAccess': False, # True|False 'EnableMediaPlayback': True, # True|False 'EnableAudioPlaybackTranscoding': True, # True|False 'EnableVideoPlaybackTranscoding': True, # True|False 'EnablePlaybackRemuxing': True, # True|False 'EnableContentDeletion': False, # True|False # 'EnableContentDeletionFromFolders': [], # string[] 'EnableContentDownloading': True, # True|False 'EnableSubtitleDownloading': False, # True|False 'EnableSubtitleManagement': False, # True|False 'EnableSyncTranscoding': False, # True|False 'EnableMediaConversion': False, # True|False # 'EnabledDevices': [], # string[] 'EnableAllDevices': True, # True|False # 'EnabledChannels': [], # string[] 'EnableAllChannels': True, # True|False # 'EnabledFolders': [], # string[] 'EnableAllFolders': True, # True|False # 'InvalidLoginAttemptCount': 10, # int 'EnablePublicSharing': False, # True|False # 'BlockedMediaFolders': [], # string[] # 'BlockedChannels': [], # string[] # 'RemoteClientBitrateLimit': 12, # int # 'AuthenticationProviderId': '', # string # 'ExcludedSubFolders': [], # string[] # 'DisablePremiumFeatures': False # True|False }
46.987654
159
0.53547
# Different Logging Levels # 4: DEBUG # 3: INFO # 2: WARNING # 1: ERROR # 0: CRITICAL log_level = 3 # When set true, if the script finds a user that already exists, # the script will attempt to change the policy of that user, # and add the emby connect account to that user. overwrite = False # The url to your Emby server emby_base_url = 'http://localhost:8096' # Login info for an account on your Emby server that has admin privileges # Username emby_admin_uname = '' # Password emby_admin_passwd = '' # The script will avoid doing anything to these users AND admin_uname avoid_users = [ 'Python', 'Admin1122' ] # number of seconds before the first request will timeout. timeout = 2 # Determine whether or not to output in tsv format. Will be text if False tsv_out = True # If all thats provided is a connect username, this prefix will be put at # the start of the username on the server user_prefix = '!' # These are the user policy changes that will be made. Can be empty user_policy = { 'IsAdministrator': False, # True|False 'IsHidden': True, # True|False 'IsHiddenRemotely': True, # True|False 'IsDisabled': False, # True|False # 'MaxParentalRating': None, # int|None # 'BlockedTags': [], # string[] # 'EnableUserPreferenceAccess': True, # True|False # 'AccessSchedules': [], # [Configuration.AccessSchedule{...}] # 'BlockUnratedItems': [], # string[Movie, Trailer, Series, Music, Game, Book, LiveTvChannel, LiveTvProgram, ChannelContent, Other] 'EnableRemoteControlOfOtherUsers': False, # True|False 'EnableSharedDeviceControl': True, # True|False 'EnableRemoteAccess': True, # True|False 'EnableLiveTvManagement': False, # True|False 'EnableLiveTvAccess': False, # True|False 'EnableMediaPlayback': True, # True|False 'EnableAudioPlaybackTranscoding': True, # True|False 'EnableVideoPlaybackTranscoding': True, # True|False 'EnablePlaybackRemuxing': True, # True|False 'EnableContentDeletion': False, # True|False # 'EnableContentDeletionFromFolders': [], # string[] 'EnableContentDownloading': True, # True|False 'EnableSubtitleDownloading': False, # True|False 'EnableSubtitleManagement': False, # True|False 'EnableSyncTranscoding': False, # True|False 'EnableMediaConversion': False, # True|False # 'EnabledDevices': [], # string[] 'EnableAllDevices': True, # True|False # 'EnabledChannels': [], # string[] 'EnableAllChannels': True, # True|False # 'EnabledFolders': [], # string[] 'EnableAllFolders': True, # True|False # 'InvalidLoginAttemptCount': 10, # int 'EnablePublicSharing': False, # True|False # 'BlockedMediaFolders': [], # string[] # 'BlockedChannels': [], # string[] # 'RemoteClientBitrateLimit': 12, # int # 'AuthenticationProviderId': '', # string # 'ExcludedSubFolders': [], # string[] # 'DisablePremiumFeatures': False # True|False }
0
0
0
6fcba304f8d15443f18e2e1f65d3e399bd0853b4
2,565
py
Python
benchmarks/code_cifar10/sdt.py
PSSF23/SPDT
2e369a3aa5735994c3c5efd485ed19a1e9f1e8ad
[ "MIT" ]
3
2020-10-02T18:36:17.000Z
2020-10-13T00:43:13.000Z
benchmarks/code_cifar10/sdt.py
PSSF23/SPDT
2e369a3aa5735994c3c5efd485ed19a1e9f1e8ad
[ "MIT" ]
8
2020-10-02T18:40:51.000Z
2021-10-01T17:40:54.000Z
benchmarks/code_cifar10/sdt.py
PSSF23/SPDT
2e369a3aa5735994c3c5efd485ed19a1e9f1e8ad
[ "MIT" ]
null
null
null
""" Author: Haoyin Xu """ import time import numpy as np import torchvision.datasets as datasets from numpy.random import permutation from sklearn.tree import DecisionTreeClassifier def write_result(filename, acc_ls): """Writes results to specified text file""" output = open(filename, "w") for acc in acc_ls: output.write(str(acc) + "\n") def prediction(classifier): """Generates predictions from model""" predictions = classifier.predict(X_test) p_t = 0 for i in range(X_test.shape[0]): if predictions[i] == y_test[i]: p_t += 1 return p_t / X_test.shape[0] def experiment_sdt(): """Runs experiments for Stream Decision Tree""" sdt_l = [] train_time_l = [] test_time_l = [] sdt = DecisionTreeClassifier() for i in range(500): X_t = X_r[i * 100 : (i + 1) * 100] y_t = y_r[i * 100 : (i + 1) * 100] # Train the model start_time = time.perf_counter() sdt.partial_fit(X_t, y_t, classes=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) end_time = time.perf_counter() train_time_l.append(end_time - start_time) # Test the model start_time = time.perf_counter() sdt_l.append(prediction(sdt)) end_time = time.perf_counter() test_time_l.append(end_time - start_time) # Reformat the train times for i in range(1, 500): train_time_l[i] += train_time_l[i - 1] return sdt_l, train_time_l, test_time_l # prepare CIFAR data # normalize scale = np.mean(np.arange(0, 256)) normalize = lambda x: (x - scale) / scale # train data cifar_trainset = datasets.CIFAR10(root="../", train=True, download=True, transform=None) X_train = normalize(cifar_trainset.data) y_train = np.array(cifar_trainset.targets) # test data cifar_testset = datasets.CIFAR10(root="../", train=False, download=True, transform=None) X_test = normalize(cifar_testset.data) y_test = np.array(cifar_testset.targets) X_train = X_train.reshape(-1, 32 * 32 * 3) X_test = X_test.reshape(-1, 32 * 32 * 3) # Perform experiments sdt_acc_l = [] sdt_train_t_l = [] sdt_test_t_l = [] for i in range(10): p = permutation(X_train.shape[0]) X_r = X_train[p] y_r = y_train[p] sdt_acc, sdt_train_t, sdt_test_t = experiment_sdt() sdt_acc_l.append(sdt_acc) sdt_train_t_l.append(sdt_train_t) sdt_test_t_l.append(sdt_test_t) write_result("../sdt/cifar10_acc.txt", sdt_acc_l) write_result("../sdt/cifar10_train_t.txt", sdt_train_t_l) write_result("../sdt/cifar10_test_t.txt", sdt_test_t_l)
26.443299
88
0.661988
""" Author: Haoyin Xu """ import time import numpy as np import torchvision.datasets as datasets from numpy.random import permutation from sklearn.tree import DecisionTreeClassifier def write_result(filename, acc_ls): """Writes results to specified text file""" output = open(filename, "w") for acc in acc_ls: output.write(str(acc) + "\n") def prediction(classifier): """Generates predictions from model""" predictions = classifier.predict(X_test) p_t = 0 for i in range(X_test.shape[0]): if predictions[i] == y_test[i]: p_t += 1 return p_t / X_test.shape[0] def experiment_sdt(): """Runs experiments for Stream Decision Tree""" sdt_l = [] train_time_l = [] test_time_l = [] sdt = DecisionTreeClassifier() for i in range(500): X_t = X_r[i * 100 : (i + 1) * 100] y_t = y_r[i * 100 : (i + 1) * 100] # Train the model start_time = time.perf_counter() sdt.partial_fit(X_t, y_t, classes=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) end_time = time.perf_counter() train_time_l.append(end_time - start_time) # Test the model start_time = time.perf_counter() sdt_l.append(prediction(sdt)) end_time = time.perf_counter() test_time_l.append(end_time - start_time) # Reformat the train times for i in range(1, 500): train_time_l[i] += train_time_l[i - 1] return sdt_l, train_time_l, test_time_l # prepare CIFAR data # normalize scale = np.mean(np.arange(0, 256)) normalize = lambda x: (x - scale) / scale # train data cifar_trainset = datasets.CIFAR10(root="../", train=True, download=True, transform=None) X_train = normalize(cifar_trainset.data) y_train = np.array(cifar_trainset.targets) # test data cifar_testset = datasets.CIFAR10(root="../", train=False, download=True, transform=None) X_test = normalize(cifar_testset.data) y_test = np.array(cifar_testset.targets) X_train = X_train.reshape(-1, 32 * 32 * 3) X_test = X_test.reshape(-1, 32 * 32 * 3) # Perform experiments sdt_acc_l = [] sdt_train_t_l = [] sdt_test_t_l = [] for i in range(10): p = permutation(X_train.shape[0]) X_r = X_train[p] y_r = y_train[p] sdt_acc, sdt_train_t, sdt_test_t = experiment_sdt() sdt_acc_l.append(sdt_acc) sdt_train_t_l.append(sdt_train_t) sdt_test_t_l.append(sdt_test_t) write_result("../sdt/cifar10_acc.txt", sdt_acc_l) write_result("../sdt/cifar10_train_t.txt", sdt_train_t_l) write_result("../sdt/cifar10_test_t.txt", sdt_test_t_l)
0
0
0
60bd8b8f9eae67891fa4c30429ba3e25b2bb87c3
3,503
py
Python
src/train_cnn.py
JiJingYu/Sensor-Specific-Hyperspectral-Image-Feature-Learning
de0ddec567fb8b47b37cffc6215c51533ac35a56
[ "Apache-2.0" ]
1
2017-08-14T03:21:00.000Z
2017-08-14T03:21:00.000Z
src/train_cnn.py
JiJingYu/Sensor-Specific-Hyperspectral-Image-Feature-Learning
de0ddec567fb8b47b37cffc6215c51533ac35a56
[ "Apache-2.0" ]
null
null
null
src/train_cnn.py
JiJingYu/Sensor-Specific-Hyperspectral-Image-Feature-Learning
de0ddec567fb8b47b37cffc6215c51533ac35a56
[ "Apache-2.0" ]
1
2021-02-16T00:04:52.000Z
2021-02-16T00:04:52.000Z
import os import sys import h5py import argparse import net.proto_file as proto_file import subprocess import numpy as np import scipy.io as sio import data_analysis.find_caffe as find_caffe import Config.ExpConfigInfo as Config caffe_root = find_caffe.caffe_root if __name__ == '__main__': parser = argparse.ArgumentParser(description="train bn net", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--spatial_info', type=str, default='5x5_mean_std', help="1x1_mean', '3x3_mean', '3x3_mean_std', '5x5_mean', '5x5_mean_std") parser.add_argument('--gpu', type=int, default=1, help='the number of gpu id, only one number is required') parser.add_argument('--dst_dir', type=str, default='bn_net_200', help='the destination dir for the experiments') parser.add_argument('--data_set', type=str, default='salina', help='indian_pines, salina') parser.add_argument('--max_iter', type=int, default=10000, help='how many iters') parser.add_argument('--train_nums', type=float, default=200, help='how many samples for training or how much percents for training, 200 or 0.1') args = parser.parse_args() train(args=args)
43.246914
118
0.640879
import os import sys import h5py import argparse import net.proto_file as proto_file import subprocess import numpy as np import scipy.io as sio import data_analysis.find_caffe as find_caffe import Config.ExpConfigInfo as Config caffe_root = find_caffe.caffe_root def train_aviris_10_times(label_unique, args): for i in range(5): exp_info = Config.ExpConfigInfo(name=args.data_set, label_unique=label_unique, new_dir_name=args.dst_dir, gpus=args.gpu, net_name='bn_net', exp_index=i, spatial_info=args.spatial_info, train_nums=args.train_nums) # set hyperparameters exp_info.set_data() exp_info.max_iter = args.max_iter exp_info.set_final_model() # train proto_file.set_prototxt(exp_info, exp_info.test_nums, exp_info.max_class) job_file = 'job_file_gpu_{}.sh'.format(exp_info.gpus) with open(job_file, 'w') as f: # f.write('cd {}\n'.format(caffe_root)) f.write(caffe_root + '/build/tools/caffe train \\\n') f.write('--solver="{}" \\\n'.format(exp_info.solver_file)) f.write('--gpu {} 2>&1 | tee {}\n'.format(exp_info.gpus, exp_info.log_file)) subprocess.check_call('bash {}'.format(job_file), shell=True) test_dict = Config.get_y_pred_from_model(model=exp_info, mode='test', score_layer_name='ip2') train_dict = Config.get_y_pred_from_model(model=exp_info, mode='train', score_layer_name='ip2') test_feature = Config.get_feature_from_model(model=exp_info, mode='test', score_layer_name='ip1') train_feature = Config.get_feature_from_model(model=exp_info, mode='train', score_layer_name='ip1') sio.savemat(exp_info.result_mat_file, {'train': train_dict, 'test': test_dict, 'train_feature': train_feature, 'test_feature': test_feature}) def train_indian_pines(args): label_unique = [2, 3, 5, 6, 8, 10, 11, 12, 14] train_aviris_10_times(label_unique, args=args) def train_salina(args): label_unique = range(1, 17) train_aviris_10_times(label_unique, args=args) def train(args): if args.data_set == 'indian_pines': train_indian_pines(args) elif args.data_set == 'salina': train_salina(args) else: raise NameError if __name__ == '__main__': parser = argparse.ArgumentParser(description="train bn net", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--spatial_info', type=str, default='5x5_mean_std', help="1x1_mean', '3x3_mean', '3x3_mean_std', '5x5_mean', '5x5_mean_std") parser.add_argument('--gpu', type=int, default=1, help='the number of gpu id, only one number is required') parser.add_argument('--dst_dir', type=str, default='bn_net_200', help='the destination dir for the experiments') parser.add_argument('--data_set', type=str, default='salina', help='indian_pines, salina') parser.add_argument('--max_iter', type=int, default=10000, help='how many iters') parser.add_argument('--train_nums', type=float, default=200, help='how many samples for training or how much percents for training, 200 or 0.1') args = parser.parse_args() train(args=args)
2,051
0
92
03d5517469cf562a344fb431f9038f8db0ca08af
3,360
py
Python
merge.py
arvin-chou/livechat
13da09d4007439dea2011dbaad5f3ee4a2ca72e8
[ "MIT" ]
null
null
null
merge.py
arvin-chou/livechat
13da09d4007439dea2011dbaad5f3ee4a2ca72e8
[ "MIT" ]
4
2021-09-08T21:31:38.000Z
2022-03-29T22:39:21.000Z
merge.py
arvin-chou/livechat
13da09d4007439dea2011dbaad5f3ee4a2ca72e8
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import io import json import os import glob import requests import urllib.parse import sys import time from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument("-p", "--path", help="log path", dest="p", default="app/static/line") parser.add_argument("-i", "--id", help="chrome extension id", dest="i", default="*") parser.add_argument("-u", "--url", help="server url", dest="u", default="http://localhost:8080") parser.add_argument("-l", "--login", help="login api", dest="l", default="/api/v1/security/login") parser.add_argument("-c", "--concat", help="concat api", dest="c", default="/api/1.0/contactmodelapi/add") parser.add_argument("--username", help="login username", dest="username", default="addline") parser.add_argument("--password", help="concat api", dest="password", default="ZAHVjB$WLM*@6fV46?B&$Y+ELW+fvd%q") args = parser.parse_args() #if len(files) is 0: # sys.exit("no file, 81") while True: monitor_log() time.sleep(1)
32.307692
124
0.56756
# -*- coding: utf-8 -*- import io import json import os import glob import requests import urllib.parse import sys import time from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument("-p", "--path", help="log path", dest="p", default="app/static/line") parser.add_argument("-i", "--id", help="chrome extension id", dest="i", default="*") parser.add_argument("-u", "--url", help="server url", dest="u", default="http://localhost:8080") parser.add_argument("-l", "--login", help="login api", dest="l", default="/api/v1/security/login") parser.add_argument("-c", "--concat", help="concat api", dest="c", default="/api/1.0/contactmodelapi/add") parser.add_argument("--username", help="login username", dest="username", default="addline") parser.add_argument("--password", help="concat api", dest="password", default="ZAHVjB$WLM*@6fV46?B&$Y+ELW+fvd%q") args = parser.parse_args() #if len(files) is 0: # sys.exit("no file, 81") def monitor_log(): outs = {} files = glob.glob1(args.p, "*" + args.i + "*.json") if len(files) is 0: print("no file, 81") return for f in files: fullpath = os.path.join(args.p, f) #log_oamhaiapniikdcfejkobaffhlkjncpoe_1559912975101.json #print("read ", fullpath) with open(fullpath, 'r', encoding='UTF-8') as file: json_str = file.read() json_dict = json.loads(json_str)['chat'] id = f.split("_")[1] if id not in outs: outs[id] = []; for e in outs[id]: new_index = next((index for (index, d) in enumerate(json_dict) if d.get("id", None) == e.get("id", None)), None) if new_index: e['chat'] = e['chat'] + json_dict[new_index]['chat'] del json_dict[new_index] #print("merge:", e['chat']) #print("merge:", e.get('id', None), z) #print(e, new_index) #print("unmerge:", json_dict) outs[id] = outs[id] + json_dict filename = "/tmp/1" TOKEN = "" if len(outs): headers = {'Content-type': 'application/json'} auth = {"username": args.username, "password": args.password, "provider": "db"} r = requests.post(urllib.parse.urljoin(args.u, args.l), json=auth, headers=headers) #print(r.status_code, r.json()) if r.status_code != 200: print(r.status_code, r.json()) return result = r.json() TOKEN = result['access_token'] for rid in outs: output = {'len': 0, 'chat': []} output['len'] = len(outs[rid]) output['chat'] = outs[rid] output['rid'] = rid headers = {'Content-type': 'application/json', 'Authorization': 'Bearer ' + TOKEN} r = requests.post(urllib.parse.urljoin(args.u, args.c), json=output, headers=headers) #print(r.status_code, r.json()) if r.status_code is 200: for f in files: fullpath = os.path.join(args.p, f) os.remove(fullpath) print(r.json()) else: print(r.status_code, r.json()) #with io.open(filename, 'w', encoding='UTF-8') as file: # file.write(json.dumps(output, ensure_ascii=False)) while True: monitor_log() time.sleep(1)
2,271
0
23
345a93ce42a9e0745a244e0f859478711fe136ec
2,310
py
Python
csgostash_scraper/modules/objects/_utils.py
Quentium-s-Forks/csgostash-scraper
cb75128215e208e49a29c54c142da1da6386f55a
[ "MIT" ]
6
2020-05-10T12:46:57.000Z
2022-03-25T17:14:54.000Z
csgostash_scraper/modules/objects/_utils.py
Quentium-s-Forks/csgostash-scraper
cb75128215e208e49a29c54c142da1da6386f55a
[ "MIT" ]
1
2021-03-21T16:52:05.000Z
2021-03-21T16:52:05.000Z
csgostash_scraper/modules/objects/_utils.py
Quentium-s-Forks/csgostash-scraper
cb75128215e208e49a29c54c142da1da6386f55a
[ "MIT" ]
4
2021-03-12T00:17:37.000Z
2021-07-16T15:27:37.000Z
# -*- coding: utf-8 -*- """ MIT License Copyright (c) 2020 supr3me Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ RarityColor = RarityColour
30
85
0.651082
# -*- coding: utf-8 -*- """ MIT License Copyright (c) 2020 supr3me Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ class RarityColour: colours = { 'Consumer Grade': '0xafafaf', 'Base Grade': '0xafafaf', 'Industrial Grade': '0x6496e1', 'Mil-Spec': '0x177cc7', 'High Grade': '0x177cc7', 'Restricted': '0x872de0', 'Remarkable': '0x872de0', 'Classified': '0xc917e0', 'Exotic': '0xc917e0', 'Covert': '0xe7191b', 'Extraordinary': '0xe7191b', 'Rare Special Item': '0xa47719', 'Contraband': '0x886a08' } def __init__(self, colour): self.colour = colour self.color = colour pass def __str__(self): return str(self.colour) @staticmethod def get(self): """Returns the colour dictionary""" return self.colours @classmethod def _from_string(cls, string: str): """Constructs a RarityColour object from a string This is used by the scraper to set colour based on the item rarity attribute """ for colour, v in cls.colours.items(): if string.split(' ')[0] in colour: return cls(v) RarityColor = RarityColour
109
1,020
25
8d9b430957d44a00d42d86da9d135e189d354a83
189
py
Python
15_euler.py
f0ti/euler
c939f80f6fe806297c60cc6763dc1dc5daa86328
[ "MIT" ]
1
2021-07-31T12:50:38.000Z
2021-07-31T12:50:38.000Z
15_euler.py
f0ti/euler
c939f80f6fe806297c60cc6763dc1dc5daa86328
[ "MIT" ]
null
null
null
15_euler.py
f0ti/euler
c939f80f6fe806297c60cc6763dc1dc5daa86328
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import math # Binomial coeff 4ever print(int(find_bin_coeff(40, 20)))
18.9
66
0.730159
#!/usr/bin/env python3 import math # Binomial coeff 4ever def find_bin_coeff(n, k): return math.factorial(n)/(math.factorial(k)*math.factorial(n-k)) print(int(find_bin_coeff(40, 20)))
71
0
23
4006594bb13d96bcc673addd0398f1af7ae36a69
12,700
py
Python
fizz_buzz.py
Danielli-Itai/TfFizzBuzz
b5962dcf1ad0f111041bb890df515abd6a2fce7a
[ "Unlicense" ]
null
null
null
fizz_buzz.py
Danielli-Itai/TfFizzBuzz
b5962dcf1ad0f111041bb890df515abd6a2fce7a
[ "Unlicense" ]
null
null
null
fizz_buzz.py
Danielli-Itai/TfFizzBuzz
b5962dcf1ad0f111041bb890df515abd6a2fce7a
[ "Unlicense" ]
null
null
null
# Fizz Buzz in Tensorflow! # Our goal is to produce fizzbuzz for the numbers 1 to 100. # So it would be unfair to include these in our training data. # Accordingly, the training data corresponds to the numbers 101 to (2 ** NUM_DIGITS - 1). # see http://joelgrus.com/2016/05/23/fizz-buzz-in-tensorflow/ from PyBaseGUI.Mplot import plot_confusion_matrix as plot import numpy #as np import tensorflow.compat.v1 as tf from sklearn import metrics from sympy import sieve from sympy.ntheory import factorint #************************************************************* # Maximum number to clasify PROGRESS_SHOW = False MAX_NUM = 2**10 #************************************************************* # Binary Encoding # Represent each input by an array of its binary digits. #************************************************************* # Primes Encoding # Represent each input by an array of its primary number multiplier as digits. #************************************************************* # Create the network model. # Generate random weights. # Our model is a standard 1-hidden-layer multi-layer-perceptron with ReLU activation. # The softmax (which turns arbitrary real-valued outputs into probabilities) gets applied in the cost function. #Create optimization function. #************************************************************* # Network data place holders # Our variables. The input has width in_digits, and the output has width out_digits. #************************************************************* # Network Training # Create Labled training data. # Fizz-Buzz data lables generation. # One-hot encode the desired network outputs: [number, "fizz", "buzz", "fizzbuzz"]) # Finally, we need a way to turn a prediction (and an original number) into a fizz buzz output fizz_buzz_names=["num", "fizz", "buzz", "fizzbuzz"]; # Mish-Buzz data lables generation. # One-hot encode the desired outputs: [number, "fizz", "buzz", "fizzbuzz", "mish", "mishfizz", "mishbuzz"] mish_buzz_names:list=["num", "mish", "fizz", "buzz", "mishfizz", "mishbuzz", "fizzbuzz"]; # Train the network using the labled data. #************************************************************* # Network testing. #************************************************************* # Performance report. #Report the network performance. #************************************************************* # Run the network learning algorithm. #************************************************************* # Running experiments # questions 1-4 #1. Take the FizzBuzz example and make it work: It works. #2. Add to the code a function that analyzes the results. # a. Print the accuracy of the classifier: See the report function and the batch accuracy reort. # b. Generate a confusion matrix: See the report function. #3. Run it once and put the results in a word file: the loop can be set to once or 10 times. NUM_HIDDEN = 100 # How many units in the hidden layer. NUM_IN_DIGITS = binary_digits(MAX_NUM) # Number of binary digits (Maximum number) TRAIN_SIZE = 8 print("Run bizz buzz 1 time with progress combinations of 2,3,6,10") for i in range (1): TensorFlowRun(NUM_HIDDEN, TRAIN_SIZE, binary_encode, fizz_buzz_encode, fizz_buzz_cls, fizz_buzz_name, MAX_NUM, NUM_IN_DIGITS, fizz_buzz_names, True); #4. Rerun the algorithm 10 times and see if there are differences in the accuracy: The alogrithem is executed 10 times. NUM_HIDDEN = 100 # How many units in the hidden layer. NUM_IN_DIGITS = binary_digits(MAX_NUM) # Number of binary digits (Maximum number) TRAIN_SIZE = 8 print("Run 8 times without progress report to compare results") for i in range (9): TensorFlowRun(NUM_HIDDEN, TRAIN_SIZE, binary_encode, fizz_buzz_encode, fizz_buzz_cls, fizz_buzz_name, MAX_NUM, NUM_IN_DIGITS, fizz_buzz_names, False); TensorFlowRun(NUM_HIDDEN, TRAIN_SIZE, binary_encode, fizz_buzz_encode, fizz_buzz_cls, fizz_buzz_name, MAX_NUM, NUM_IN_DIGITS, fizz_buzz_names, True); # questions 5-6 #5. Change the algorithm to also deal with the number 2 besides the numbers 3 # and 5 with all the relevant combinations (more classes2,3,5): we added the mish_buzz ancoding and class functions and class names. #6. Run it once and put the results in a word file. NUM_HIDDEN = 100 # How many units in the hidden layer. print("Add mish buzz combinations of 2,3,5,6,10,15") NUM_IN_DIGITS = binary_digits(MAX_NUM) # Number of binary digits (Maximum number) TRAIN_SIZE = 8 for i in range (1): TensorFlowRun(NUM_HIDDEN, TRAIN_SIZE, binary_encode, mish_buzz_encode, mish_buzz_cls, mish_buzz_name, MAX_NUM, NUM_IN_DIGITS, mish_buzz_names, True); # a question 7 #7. Try to improve the results by more training, change the network etc. NUM_HIDDEN = 5000 # How many units in the hidden layer. we increase from 100 to 5000 NUM_IN_DIGITS = primes_digits(MAX_NUM) # Number of binary digits (Maximum number) TRAIN_SIZE = 1 print("improve binary encode training and hidden layer") for i in range (1): TensorFlowRun(NUM_HIDDEN, TRAIN_SIZE, primes_encode, mish_buzz_encode, mish_buzz_cls, mish_buzz_name, MAX_NUM, NUM_IN_DIGITS, mish_buzz_names, True); # a question 8 for fizzbuzz #8. Change the representation from binary to prime based(encode the numbers as # prime number multiplayer). That means each number is coded by how many # time each prime appears in the product. For large primes you can put them all # in one bucket. # Example: 24 is coded as 2^3* 3^1 -? [3,1,0,0,0,0…] # Do you think the algorithms (first and second) will work better? Run them # and write the results and compare them. NUM_HIDDEN = 100 # How many units in the hidden layer. NUM_IN_DIGITS = primes_digits(MAX_NUM) # Number of binary digits (Maximum number) TRAIN_SIZE = 2 print("perform prim encoding with small hidden layer and small number of train") for i in range(0): TensorFlowRun(NUM_HIDDEN, TRAIN_SIZE, primes_encode, mish_buzz_encode, mish_buzz_cls, mish_buzz_name, MAX_NUM, NUM_IN_DIGITS, mish_buzz_names, True); input("Press Enter to continue...")
38.957055
153
0.669528
# Fizz Buzz in Tensorflow! # Our goal is to produce fizzbuzz for the numbers 1 to 100. # So it would be unfair to include these in our training data. # Accordingly, the training data corresponds to the numbers 101 to (2 ** NUM_DIGITS - 1). # see http://joelgrus.com/2016/05/23/fizz-buzz-in-tensorflow/ from PyBaseGUI.Mplot import plot_confusion_matrix as plot import numpy #as np import tensorflow.compat.v1 as tf from sklearn import metrics from sympy import sieve from sympy.ntheory import factorint #************************************************************* # Maximum number to clasify PROGRESS_SHOW = False MAX_NUM = 2**10 #************************************************************* # Binary Encoding # Represent each input by an array of its binary digits. def binary_digits(number:int)->int: count = 0 while (number > 0): number = number // 2 count = count + 1 return(count) def binary_encode(number:int, num_digits:int)->list: encode : list= numpy.array([number >> d & 1 for d in range(num_digits)]); return encode; #************************************************************* # Primes Encoding # Represent each input by an array of its primary number multiplier as digits. def primes_digits(number:int)->int: sieve.extend(number) return(len(sieve._list)) def prime_encode(number:int, num_digits:int)->list: sieve.extend(number) prime_nums = sieve._list prim_factored = factorint(int(number)) encode:list = list(range(num_digits)); for prime in prime_nums: if prime in prim_factored: encode[prime_nums.index(prime)]=prim_factored[prime] else: encode[prime_nums.index(prime)]=0 return encode; def primes_encode(numbers, num_digits:int)->list: encode: list=[] if(type(numbers)==int): encode = prime_encode(numbers, num_digits); else: for num in numbers: encode.append(prime_encode(num, num_digits)); encode = numpy.transpose(encode) return encode; #************************************************************* # Create the network model. # Generate random weights. def WeightsInit(in_digits:int, num_hidden:int, out_digits:int): # We'll want to randomly initialize weights. def init_weights(shape): return tf.Variable(tf.random_normal(shape, stddev=0.01)) # Initialize the weights. weights_h = init_weights([in_digits, num_hidden]) #Hidden layer weights. weights_o = init_weights([num_hidden, out_digits]) #Output layer weights. return(weights_h, weights_o) # Our model is a standard 1-hidden-layer multi-layer-perceptron with ReLU activation. # The softmax (which turns arbitrary real-valued outputs into probabilities) gets applied in the cost function. def model(X, weights_h, weights_o): h = tf.nn.relu(tf.matmul(X, weights_h)) return tf.matmul(h, weights_o) #Create optimization function. def Optimizer(X, Y, w_h, w_o): # Predict y given x using the model. py_x = model(X, w_h, w_o) # We'll train our model by minimizing a cost function. cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y)) train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost) # And we'll make predictions by choosing the largest output. predict_op = tf.argmax(py_x, 1) return(train_op, predict_op) #************************************************************* # Network data place holders # Our variables. The input has width in_digits, and the output has width out_digits. def PlaceHolders(in_digits:int, out_digits): X = tf.placeholder("float", [None, in_digits]) Y = tf.placeholder("float", [None, out_digits]) return(X,Y); #************************************************************* # Network Training # Create Labled training data. # Fizz-Buzz data lables generation. # One-hot encode the desired network outputs: [number, "fizz", "buzz", "fizzbuzz"]) def fizz_buzz_encode(i): if i % 15 == 0: return numpy.array([0, 0, 0, 1]) elif i % 5 == 0: return numpy.array([0, 0, 1, 0]) elif i % 3 == 0: return numpy.array([0, 1, 0, 0]) else: return numpy.array([1, 0, 0, 0]) # Finally, we need a way to turn a prediction (and an original number) into a fizz buzz output def fizz_buzz_cls(num): if num % 15 == 0: return 3 elif num % 5 == 0: return 2 elif num % 3 == 0: return 1 else: return 0 fizz_buzz_names=["num", "fizz", "buzz", "fizzbuzz"]; def fizz_buzz_name(i, prediction): return [str(i), "fizz", "buzz", "fizzbuzz"][prediction] # Mish-Buzz data lables generation. # One-hot encode the desired outputs: [number, "fizz", "buzz", "fizzbuzz", "mish", "mishfizz", "mishbuzz"] def mish_buzz_encode(i): if i % 15 == 0: return numpy.array([0, 0, 0, 0, 0, 0, 1]) elif i % 10 == 0: return numpy.array([0, 0, 0, 0, 0, 1, 0]) elif i % 6 == 0: return numpy.array([0, 0, 0, 0, 1, 0, 0]) elif i % 5 == 0: return numpy.array([0, 0, 0, 1, 0, 0, 0]) elif i % 3 == 0: return numpy.array([0, 0, 1, 0, 0, 0, 0]) elif i % 2 == 0: return numpy.array([0, 1, 0, 0, 0, 0, 0]) else: return numpy.array([1, 0, 0, 0, 0, 0, 0]) def mish_buzz_cls(num): if num % 15 == 0: return 6 elif num % 10 == 0: return 5 elif num % 6 == 0: return 4 elif num % 5 == 0: return 3 elif num % 3 == 0: return 2 elif num % 2 == 0: return 1 else: return 0 mish_buzz_names:list=["num", "mish", "fizz", "buzz", "mishfizz", "mishbuzz", "fizzbuzz"]; def mish_buzz_name(i, prediction): return [str(i), "mish", "fizz", "buzz", "mishfizz", "mishbuzz", "fizzbuzz"][prediction] def TrainData(test_start:int, max_in, in_digits, input_encoder, fizz_buzz_encode): trainX = numpy.array([input_encoder(i, in_digits) for i in range(test_start, max_in)]) trainY = numpy.array([fizz_buzz_encode(i) for i in range(test_start, max_in)]) return(trainX, trainY) # Train the network using the labled data. def TensorTrain(X, Y, test_size:int, batch_size:int, trainX:list, trainY:list, train_op, predict_op, sess:tf.Session): for epoch in range(test_size): # Shuffle the data before each training iteration. p = numpy.random.permutation(range(len(trainX))) trainX, trainY = trainX[p], trainY[p] # Train in batches of 128 inputs. for start in range(0, len(trainX), batch_size): end = start + batch_size sess.run(train_op, feed_dict={X: trainX[start:end], Y: trainY[start:end]}) # And print the current accuracy on the training data. if(PROGRESS_SHOW): print(epoch, numpy.mean(numpy.argmax(trainY, axis=1) == sess.run(predict_op, feed_dict={X: trainX, Y: trainY}))) return; #************************************************************* # Network testing. def TensorTest(sess:tf.Session, input_encoder, test_last:int, in_digits:int, X, predict_op): # And now for some fizz buzz numbers = numpy.arange(1, test_last + 1) teX = numpy.transpose(input_encoder(numbers, in_digits)) teY = sess.run(predict_op, feed_dict={X: teX}) return (numbers, teY) #************************************************************* # Performance report. #Report the network performance. def Report(numbers:list, predicted_vec:list, fizz_buzz_name, fizz_buzz_cls, class_names:list): # Calculate the expected vector. expected_vec = numpy.vectorize(fizz_buzz_cls)(numbers) #Print the output vector. output_vec = numpy.vectorize(fizz_buzz_name)(numbers, predicted_vec) print(output_vec) #Print accuracy mesure. accuracy = metrics.accuracy_score(expected_vec, predicted_vec) print('Accuracy : ' + str(accuracy)); #Print confusion matrix. conf_matrix = metrics.confusion_matrix(expected_vec, predicted_vec) print('Confusion matrix : ' + str(conf_matrix)) plot(actual_cls=expected_vec, predict_cls=predicted_vec, classes=class_names) return; #************************************************************* # Run the network learning algorithm. def TensorFlowRun(num_hidden:int, train_size:int, input_encoder, exp_output, exp_class, class_name, max_in:int, in_digits:int, class_names, report:bool): TEST_LAST = 100 BATCH_SIZE = 128 # Number of samples to test. TRAIN_SIZE = BATCH_SIZE * train_size out_digits: int = len(class_names); with tf.Session() as sess: w_h, w_o = WeightsInit(in_digits, num_hidden, out_digits); X, Y = PlaceHolders(in_digits, out_digits); train_op, predict_op = Optimizer(X, Y, w_h, w_o); tf.initialize_all_variables().run() trainX, trainY = TrainData(TEST_LAST + 1, max_in, in_digits, input_encoder, exp_output) TensorTrain(X, Y, TRAIN_SIZE, BATCH_SIZE, trainX, trainY, train_op, predict_op, sess) numbers, test_output = TensorTest(sess, input_encoder, TEST_LAST + 1, in_digits, X, predict_op) if(report): Report(numbers, test_output, class_name, exp_class, class_names) return; #************************************************************* # Running experiments # questions 1-4 #1. Take the FizzBuzz example and make it work: It works. #2. Add to the code a function that analyzes the results. # a. Print the accuracy of the classifier: See the report function and the batch accuracy reort. # b. Generate a confusion matrix: See the report function. #3. Run it once and put the results in a word file: the loop can be set to once or 10 times. NUM_HIDDEN = 100 # How many units in the hidden layer. NUM_IN_DIGITS = binary_digits(MAX_NUM) # Number of binary digits (Maximum number) TRAIN_SIZE = 8 print("Run bizz buzz 1 time with progress combinations of 2,3,6,10") for i in range (1): TensorFlowRun(NUM_HIDDEN, TRAIN_SIZE, binary_encode, fizz_buzz_encode, fizz_buzz_cls, fizz_buzz_name, MAX_NUM, NUM_IN_DIGITS, fizz_buzz_names, True); #4. Rerun the algorithm 10 times and see if there are differences in the accuracy: The alogrithem is executed 10 times. NUM_HIDDEN = 100 # How many units in the hidden layer. NUM_IN_DIGITS = binary_digits(MAX_NUM) # Number of binary digits (Maximum number) TRAIN_SIZE = 8 print("Run 8 times without progress report to compare results") for i in range (9): TensorFlowRun(NUM_HIDDEN, TRAIN_SIZE, binary_encode, fizz_buzz_encode, fizz_buzz_cls, fizz_buzz_name, MAX_NUM, NUM_IN_DIGITS, fizz_buzz_names, False); TensorFlowRun(NUM_HIDDEN, TRAIN_SIZE, binary_encode, fizz_buzz_encode, fizz_buzz_cls, fizz_buzz_name, MAX_NUM, NUM_IN_DIGITS, fizz_buzz_names, True); # questions 5-6 #5. Change the algorithm to also deal with the number 2 besides the numbers 3 # and 5 with all the relevant combinations (more classes2,3,5): we added the mish_buzz ancoding and class functions and class names. #6. Run it once and put the results in a word file. NUM_HIDDEN = 100 # How many units in the hidden layer. print("Add mish buzz combinations of 2,3,5,6,10,15") NUM_IN_DIGITS = binary_digits(MAX_NUM) # Number of binary digits (Maximum number) TRAIN_SIZE = 8 for i in range (1): TensorFlowRun(NUM_HIDDEN, TRAIN_SIZE, binary_encode, mish_buzz_encode, mish_buzz_cls, mish_buzz_name, MAX_NUM, NUM_IN_DIGITS, mish_buzz_names, True); # a question 7 #7. Try to improve the results by more training, change the network etc. NUM_HIDDEN = 5000 # How many units in the hidden layer. we increase from 100 to 5000 NUM_IN_DIGITS = primes_digits(MAX_NUM) # Number of binary digits (Maximum number) TRAIN_SIZE = 1 print("improve binary encode training and hidden layer") for i in range (1): TensorFlowRun(NUM_HIDDEN, TRAIN_SIZE, primes_encode, mish_buzz_encode, mish_buzz_cls, mish_buzz_name, MAX_NUM, NUM_IN_DIGITS, mish_buzz_names, True); # a question 8 for fizzbuzz #8. Change the representation from binary to prime based(encode the numbers as # prime number multiplayer). That means each number is coded by how many # time each prime appears in the product. For large primes you can put them all # in one bucket. # Example: 24 is coded as 2^3* 3^1 -? [3,1,0,0,0,0…] # Do you think the algorithms (first and second) will work better? Run them # and write the results and compare them. NUM_HIDDEN = 100 # How many units in the hidden layer. NUM_IN_DIGITS = primes_digits(MAX_NUM) # Number of binary digits (Maximum number) TRAIN_SIZE = 2 print("perform prim encoding with small hidden layer and small number of train") for i in range(0): TensorFlowRun(NUM_HIDDEN, TRAIN_SIZE, primes_encode, mish_buzz_encode, mish_buzz_cls, mish_buzz_name, MAX_NUM, NUM_IN_DIGITS, mish_buzz_names, True); input("Press Enter to continue...")
6,168
0
445
70ddf0689650d8dd4714c839a174e7639e9072f0
11,815
py
Python
lib/coginvasion/hood/TownLoader.py
theclashingfritz/Cog-Invasion-Online-Dump
2561abbacb3e2e288e06f3f04b935b5ed589c8f8
[ "Apache-2.0" ]
1
2020-03-12T16:44:10.000Z
2020-03-12T16:44:10.000Z
lib/coginvasion/hood/TownLoader.py
theclashingfritz/Cog-Invasion-Online-Dump
2561abbacb3e2e288e06f3f04b935b5ed589c8f8
[ "Apache-2.0" ]
null
null
null
lib/coginvasion/hood/TownLoader.py
theclashingfritz/Cog-Invasion-Online-Dump
2561abbacb3e2e288e06f3f04b935b5ed589c8f8
[ "Apache-2.0" ]
null
null
null
# uncompyle6 version 3.2.4 # Python bytecode 2.7 (62211) # Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)] # Embedded file name: lib.coginvasion.hood.TownLoader from panda3d.core import * from direct.directnotify.DirectNotifyGlobal import directNotify from direct.fsm.StateData import StateData from direct.fsm.State import State from direct.fsm.ClassicFSM import ClassicFSM from direct.interval.IntervalGlobal import * from QuietZoneState import QuietZoneState import LinkTunnel, ZoneUtil, ToonInterior from lib.coginvasion.cogoffice import CogOfficeInterior
41.167247
296
0.650529
# uncompyle6 version 3.2.4 # Python bytecode 2.7 (62211) # Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)] # Embedded file name: lib.coginvasion.hood.TownLoader from panda3d.core import * from direct.directnotify.DirectNotifyGlobal import directNotify from direct.fsm.StateData import StateData from direct.fsm.State import State from direct.fsm.ClassicFSM import ClassicFSM from direct.interval.IntervalGlobal import * from QuietZoneState import QuietZoneState import LinkTunnel, ZoneUtil, ToonInterior from lib.coginvasion.cogoffice import CogOfficeInterior class TownLoader(StateData): notify = directNotify.newCategory('TownLoader') def __init__(self, hood, parentFSMState, doneEvent): self.hood = hood self.parentFSMState = parentFSMState StateData.__init__(self, doneEvent) self.fsm = ClassicFSM('TownLoader', [State('start', self.enterStart, self.exitStart, ['quietZone', 'street']), State('street', self.enterStreet, self.exitStreet, ['quietZone']), State('toonInterior', self.enterToonInterior, self.exitToonInterior, ['quietZone']), State('suitInterior', self.enterSuitInterior, self.exitSuitInterior, ['quietZone']), State('quietZone', self.enterQuietZone, self.exitQuietZone, ['street', 'toonInterior', 'suitInterior']), State('final', self.enterFinal, self.exitFinal, ['start'])], 'start', 'final') self.branchZone = None self.canonicalBranchZone = None self.placeDoneEvent = 'placeDone' self.linkTunnels = [] self.place = None return def findAndMakeLinkTunnels(self, requestStatus): for tunnel in self.geom.findAllMatches('**/*linktunnel*'): dnaRootStr = tunnel.getName() zone = LinkTunnel.getZoneFromDNARootStr(dnaRootStr) zone = LinkTunnel.maybeFixZone(zone) tunnelClass = LinkTunnel.getRecommendedTunnelClassFromZone(zone) link = tunnelClass(tunnel, dnaRootStr) self.linkTunnels.append(link) def load(self, zoneId): StateData.load(self) self.zoneId = zoneId self.branchZone = ZoneUtil.getBranchZone(zoneId) self.canonicalBranchZone = ZoneUtil.getCanonicalBranchZone(zoneId) self.music = base.loadMusic(self.musicFile) self.interiorMusic = base.loadMusic(self.interiorMusicFile) def unload(self): self.parentFSMState.removeChild(self.fsm) del self.parentFSMState del self.fsm del self.streetClass self.landmarkBlocks.removeNode() del self.landmarkBlocks self.hood.dnaStore.resetSuitPoints() self.hood.dnaStore.resetBattleCells() del self.hood del self.nodeDict del self.zoneDict del self.fadeInDict del self.fadeOutDict del self.nodeList self.geom.removeNode() del self.geom del self.music del self.interiorMusic ModelPool.garbageCollect() TexturePool.garbageCollect() StateData.unload(self) def enter(self, requestStatus): StateData.enter(self) self.findAndMakeLinkTunnels(requestStatus) self.fsm.enterInitialState() self.setState(requestStatus['where'], requestStatus) def exit(self): self.fsm.requestFinalState() self.ignoreAll() ModelPool.garbageCollect() TexturePool.garbageCollect() StateData.exit(self) def setState(self, state, requestStatus): self.fsm.request(state, [requestStatus]) def enterStart(self): pass def exitStart(self): pass def enterStreet(self, requestStatus): self.acceptOnce(self.placeDoneEvent, self.streetDone) self.place = self.streetClass(self, self.fsm, self.placeDoneEvent) self.place.load() def exitStreet(self): self.ignore(self.placeDoneEvent) self.place.exit() self.place.unload() self.place = None base.cr.playGame.setPlace(self.place) return def streetDone(self): self.requestStatus = self.place.doneStatus status = self.place.doneStatus if status['loader'] == 'townLoader' and ZoneUtil.getBranchZone(status['zoneId']) == self.branchZone and status['shardId'] == None or status['how'] == 'doorOut' or status['where'] == 'suitInterior': self.fsm.request('quietZone', [status]) else: self.doneStatus = status messenger.send(self.doneEvent) return def enterToonInterior(self, requestStatus): self.acceptOnce(self.placeDoneEvent, self.handleToonInteriorDone) self.place = ToonInterior.ToonInterior(self, self.fsm, self.placeDoneEvent) self.place.load() def exitToonInterior(self): self.ignore(self.placeDoneEvent) self.place.exit() self.place.unload() self.place = None base.cr.playGame.setPlace(self.place) return def enterSuitInterior(self, requestStatus): self.acceptOnce(self.placeDoneEvent, self.handleSuitInteriorDone) self.place = CogOfficeInterior.CogOfficeInterior(self, self.fsm, self.placeDoneEvent) self.place.load() def exitSuitInterior(self): self.ignore(self.placeDoneEvent) self.place.exit() self.place.unload() self.place = None base.cr.playGame.setPlace(self.place) return def enterThePlace(self, requestStatus): base.cr.playGame.setPlace(self.place) if self.place is not None: self.place.enter(requestStatus) return def handleToonInteriorDone(self): status = self.place.doneStatus if status['loader'] == 'townLoader' and ZoneUtil.getBranchZone(status['zoneId']) == self.branchZone and status['shardId'] == None or status['how'] == 'doorOut': self.fsm.request('quietZone', [status]) else: self.doneStatus = status messenger.send(self.doneEvent) return def handleSuitInteriorDone(self): self.handleToonInteriorDone() def enterQuietZone(self, requestStatus): self.fsm.request(requestStatus['where'], [requestStatus], exitCurrent=0) self.quietZoneDoneEvent = uniqueName('quietZoneDone') self.acceptOnce(self.quietZoneDoneEvent, self.handleQuietZoneDone) self.quietZoneStateData = QuietZoneState(self.quietZoneDoneEvent) self.quietZoneStateData.load() self.quietZoneStateData.enter(requestStatus) def exitQuietZone(self): self.ignore(self.quietZoneDoneEvent) del self.quietZoneDoneEvent self.quietZoneStateData.exit() self.quietZoneStateData.unload() self.quietZoneStateData = None return def handleQuietZoneDone(self): status = self.quietZoneStateData.getRequestStatus() self.exitQuietZone() self.enterThePlace(status) def enterFinal(self): pass def exitFinal(self): pass def createHood(self, dnaFile, loadStorage=1): if loadStorage: loader.loadDNAFile(self.hood.dnaStore, 'phase_5/dna/storage_town.pdna') loader.loadDNAFile(self.hood.dnaStore, self.townStorageDNAFile) node = loader.loadDNAFile(self.hood.dnaStore, dnaFile) if node.getNumParents() == 1: self.geom = NodePath(node.getParent(0)) self.geom.reparentTo(hidden) else: self.geom = hidden.attachNewNode(node) self.makeDictionaries(self.hood.dnaStore) self.reparentLandmarkBlockNodes() self.renameFloorPolys(self.nodeList) gsg = base.win.getGsg() if gsg: self.geom.prepareScene(gsg) self.geom.flattenLight() self.geom.setName('town_top_level') def reparentLandmarkBlockNodes(self): bucket = self.landmarkBlocks = hidden.attachNewNode('landmarkBlocks') npc = self.geom.findAllMatches('**/sb*:*_landmark_*_DNARoot') for i in xrange(npc.getNumPaths()): nodePath = npc.getPath(i) nodePath.wrtReparentTo(bucket) npc = self.geom.findAllMatches('**/sb*:*animated_building*_DNARoot') for i in xrange(npc.getNumPaths()): nodePath = npc.getPath(i) nodePath.wrtReparentTo(bucket) def makeDictionaries(self, dnaStore): self.nodeDict = {} self.zoneDict = {} self.zoneVisDict = {} self.nodeList = [] self.fadeInDict = {} self.fadeOutDict = {} a1 = Vec4(1, 1, 1, 1) a0 = Vec4(1, 1, 1, 0) numVisGroups = dnaStore.getNumDNAVisGroupsAI() for i in xrange(numVisGroups): groupFullName = dnaStore.getDNAVisGroupName(i) visGroup = dnaStore.getDNAVisGroupAI(i) groupName = base.cr.hoodMgr.extractGroupName(groupFullName) zoneId = int(groupName) zoneId = ZoneUtil.getTrueZoneId(zoneId, self.zoneId) groupNode = self.geom.find('**/' + groupFullName) if groupNode.isEmpty(): continue else: if ':' in groupName: groupName = '%s%s' % (zoneId, groupName[groupName.index(':'):]) else: groupName = '%s' % zoneId groupNode.setName(groupName) groupNode.flattenMedium() self.nodeDict[zoneId] = [] self.nodeList.append(groupNode) self.zoneDict[zoneId] = groupNode visibles = [] for i in xrange(visGroup.getNumVisibles()): visibles.append(int(visGroup.get_visible(i))) visibles.append(ZoneUtil.getBranchZone(zoneId)) self.zoneVisDict[zoneId] = visibles fadeDuration = 0.5 self.fadeOutDict[groupNode] = Sequence(Func(groupNode.setTransparency, 1), LerpColorScaleInterval(groupNode, fadeDuration, a0, startColorScale=a1), Func(groupNode.clearColorScale), Func(groupNode.clearTransparency), Func(groupNode.stash), name='fadeZone-' + str(zoneId), autoPause=1) self.fadeInDict[groupNode] = Sequence(Func(groupNode.unstash), Func(groupNode.setTransparency, 1), LerpColorScaleInterval(groupNode, fadeDuration, a1, startColorScale=a0), Func(groupNode.clearColorScale), Func(groupNode.clearTransparency), name='fadeZone-' + str(zoneId), autoPause=1) for i in xrange(numVisGroups): groupFullName = dnaStore.getDNAVisGroupName(i) zoneId = int(base.cr.hoodMgr.extractGroupName(groupFullName)) zoneId = ZoneUtil.getTrueZoneId(zoneId, self.zoneId) for j in xrange(dnaStore.getNumVisiblesInDNAVisGroup(i)): visName = dnaStore.getVisibleName(i, j) groupName = base.cr.hoodMgr.extractGroupName(visName) nextZoneId = int(groupName) nextZoneId = ZoneUtil.getTrueZoneId(nextZoneId, self.zoneId) visNode = self.zoneDict[nextZoneId] self.nodeDict[zoneId].append(visNode) self.hood.dnaStore.resetPlaceNodes() self.hood.dnaStore.resetDNAGroups() self.hood.dnaStore.resetDNAVisGroups() self.hood.dnaStore.resetDNAVisGroupsAI() def renameFloorPolys(self, nodeList): for i in nodeList: collNodePaths = i.findAllMatches('**/+CollisionNode') numCollNodePaths = collNodePaths.getNumPaths() visGroupName = i.node().getName() for j in xrange(numCollNodePaths): collNodePath = collNodePaths.getPath(j) bitMask = collNodePath.node().getIntoCollideMask() if bitMask.getBit(1): collNodePath.node().setName(visGroupName)
10,363
815
23
43f11f15a49bd36c2028ac01e96f9ab77af58c94
3,221
py
Python
tests/workflow_tests/test_storage.py
acidburn0zzz/cloudify-manager
ee2224c52347f7461a95976179ab61aee74a49dd
[ "Apache-2.0" ]
1
2015-11-03T14:27:11.000Z
2015-11-03T14:27:11.000Z
tests/workflow_tests/test_storage.py
acidburn0zzz/cloudify-manager
ee2224c52347f7461a95976179ab61aee74a49dd
[ "Apache-2.0" ]
2
2021-03-20T05:33:19.000Z
2021-03-26T00:38:21.000Z
tests/workflow_tests/test_storage.py
acidburn0zzz/cloudify-manager
ee2224c52347f7461a95976179ab61aee74a49dd
[ "Apache-2.0" ]
1
2019-10-29T06:15:31.000Z
2019-10-29T06:15:31.000Z
######## # Copyright (c) 2013 GigaSpaces Technologies Ltd. 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 uuid from testenv import TestCase from testenv.utils import get_resource as resource from testenv.utils import deploy_application as deploy from testenv.utils import create_rest_client from cloudify_rest_client.exceptions import CloudifyClientError
42.381579
79
0.65104
######## # Copyright (c) 2013 GigaSpaces Technologies Ltd. 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 uuid from testenv import TestCase from testenv.utils import get_resource as resource from testenv.utils import deploy_application as deploy from testenv.utils import create_rest_client from cloudify_rest_client.exceptions import CloudifyClientError class TestStorage(TestCase): def test_update_node_bad_version(self): deploy(resource("dsl/basic.yaml")) client = create_rest_client() instance = client.node_instances.list()[0] instance = client.node_instances.get(instance.id) # need the version props = {'key': 'value'} result = client.node_instances.update(instance.id, state='started', runtime_properties=props, version=instance.version,) self.assertEquals(instance.version+1, result.version) self.assertEquals(instance.id, result.id) self.assertDictContainsSubset(props, result.runtime_properties) self.assertEquals('started', result.state) # making another call with a bad version self.assertRaises( CloudifyClientError, client.node_instances.update, instance.id, version=1) def test_deployment_inputs(self): blueprint_id = str(uuid.uuid4()) blueprint = self.client.blueprints.upload(resource("dsl/basic.yaml"), blueprint_id) inputs = blueprint.plan['inputs'] self.assertEqual(1, len(inputs)) self.assertTrue('install_agent' in inputs) self.assertFalse(inputs['install_agent']['default']) self.assertTrue( len(inputs['install_agent']['description']) > 0) deployment_id = str(uuid.uuid4()) deployment = self.client.deployments.create(blueprint.id, deployment_id) self.assertEqual(1, len(deployment.inputs)) self.assertTrue('install_agent' in deployment.inputs) self.assertFalse(deployment.inputs['install_agent']) def test_node_operation_different_inputs(self): """ Tests storing different nodes with different structured inputs for the same operation. """ blueprint_id = str(uuid.uuid4()) blueprint = self.client.blueprints.upload( resource("dsl/two_nodes_different_inputs.yaml"), blueprint_id) deployment_id = str(uuid.uuid4()) self.client.deployments.create(blueprint.id, deployment_id)
1,766
530
23
389e5efd7c99483e7fd901d833239fb54e7e8122
356
py
Python
tests/keras/legacy/conftest.py
raveendezoysa/American-Sign-Language-to-Text-Based-Translator
0e0d3bea9912c87c51f00728742dc67cd85b7e66
[ "MIT" ]
1
2019-10-03T09:54:57.000Z
2019-10-03T09:54:57.000Z
tests/keras/legacy/conftest.py
raveendezoysa/American-Sign-Language-to-Text-Based-Translator
0e0d3bea9912c87c51f00728742dc67cd85b7e66
[ "MIT" ]
null
null
null
tests/keras/legacy/conftest.py
raveendezoysa/American-Sign-Language-to-Text-Based-Translator
0e0d3bea9912c87c51f00728742dc67cd85b7e66
[ "MIT" ]
null
null
null
import warnings import pytest @pytest.fixture(autouse=True) def clear_session_after_test(): """This wrapper runs for all the tests in the legacy directory (recursively). """ with warnings.catch_warnings(): warnings.filterwarnings('ignore', message=r'(.+) Keras 2 ', category=UserWarning) yield
27.384615
81
0.643258
import warnings import pytest @pytest.fixture(autouse=True) def clear_session_after_test(): """This wrapper runs for all the tests in the legacy directory (recursively). """ with warnings.catch_warnings(): warnings.filterwarnings('ignore', message=r'(.+) Keras 2 ', category=UserWarning) yield
0
0
0
f9d3414f8f4fa8562edec0a0c9d4ef0efad6a5c4
1,092
py
Python
tests/test_utils.py
takeshiD/urdf2dh
76d9c4ce6d388ef4bd7325be60b704ea955dad7d
[ "MIT" ]
1
2021-11-03T06:59:50.000Z
2021-11-03T06:59:50.000Z
tests/test_utils.py
takeshiD/urdf2dh
76d9c4ce6d388ef4bd7325be60b704ea955dad7d
[ "MIT" ]
1
2021-10-19T12:40:15.000Z
2021-10-19T12:40:15.000Z
tests/test_utils.py
takeshiD/urdf2dh
76d9c4ce6d388ef4bd7325be60b704ea955dad7d
[ "MIT" ]
null
null
null
import pytest from tik.utils import _RotX, _RotY, _RotZ, Rot, Trans, homogeneous_transform import numpy as np ATOL = 1.e-8 @pytest.mark.parametrize(('theta', 'expected'), [ (0, np.eye(4)), (2*np.pi, np.eye(4)), ]) @pytest.mark.parametrize(('roll','pitch','yaw','expected'), [ (0, 0, 0, np.eye(4)), (2*np.pi,2*np.pi,2*np.pi, np.eye(4)), (np.pi,np.pi,np.pi,np.eye(4)) ]) @pytest.mark.parametrize(('x','y','z','expected'), [ (0, 0, 0, np.eye(4)), ]) @pytest.mark.parametrize('a,alpha,d,theta,expected', [ (0,0,0,0, np.eye(4)) ])
34.125
76
0.668498
import pytest from tik.utils import _RotX, _RotY, _RotZ, Rot, Trans, homogeneous_transform import numpy as np ATOL = 1.e-8 @pytest.mark.parametrize(('theta', 'expected'), [ (0, np.eye(4)), (2*np.pi, np.eye(4)), ]) def test_RotXYZ(theta, expected): assert np.allclose(_RotX(theta), expected, atol=ATOL) assert np.allclose(_RotY(theta), expected, atol=ATOL) assert np.allclose(_RotZ(theta), expected, atol=ATOL) @pytest.mark.parametrize(('roll','pitch','yaw','expected'), [ (0, 0, 0, np.eye(4)), (2*np.pi,2*np.pi,2*np.pi, np.eye(4)), (np.pi,np.pi,np.pi,np.eye(4)) ]) def test_Rot(roll, pitch, yaw, expected): assert np.allclose(Rot(roll,pitch,yaw), expected, atol=ATOL) @pytest.mark.parametrize(('x','y','z','expected'), [ (0, 0, 0, np.eye(4)), ]) def test_Trans(x,y,z,expected): assert np.allclose(Trans(x,y,z), expected, atol=ATOL) @pytest.mark.parametrize('a,alpha,d,theta,expected', [ (0,0,0,0, np.eye(4)) ]) def test_homogeneous_transform(a,alpha,d,theta,expected): assert np.allclose(homogeneous_transform(a,alpha,d,theta), expected)
448
0
88
cdc8d0d7da85ef3d2e6f802fc54b3d3064614620
2,165
py
Python
v2.5.7/otp/ai/passlib/ifc.py
TTOFFLINE-LEAK/ttoffline
bb0e91704a755d34983e94288d50288e46b68380
[ "MIT" ]
4
2019-07-01T15:46:43.000Z
2021-07-23T16:26:48.000Z
v2.5.7/otp/ai/passlib/ifc.py
TTOFFLINE-LEAK/ttoffline
bb0e91704a755d34983e94288d50288e46b68380
[ "MIT" ]
1
2019-06-29T03:40:05.000Z
2021-06-13T01:15:16.000Z
v2.5.7/otp/ai/passlib/ifc.py
TTOFFLINE-LEAK/ttoffline
bb0e91704a755d34983e94288d50288e46b68380
[ "MIT" ]
4
2019-07-28T21:18:46.000Z
2021-02-25T06:37:25.000Z
import logging log = logging.getLogger(__name__) import sys from otp.ai.passlib.utils.decor import deprecated_method __all__ = [ 'PasswordHash'] from abc import ABCMeta, abstractmethod, abstractproperty @recreate_with_metaclass(ABCMeta)
27.0625
78
0.685912
import logging log = logging.getLogger(__name__) import sys from otp.ai.passlib.utils.decor import deprecated_method __all__ = [ 'PasswordHash'] def recreate_with_metaclass(meta): def builder(cls): if meta is type(cls): return cls return meta(cls.__name__, cls.__bases__, cls.__dict__.copy()) return builder from abc import ABCMeta, abstractmethod, abstractproperty @recreate_with_metaclass(ABCMeta) class PasswordHash(object): is_disabled = False truncate_size = None truncate_error = True truncate_verify_reject = True @classmethod @abstractmethod def hash(cls, secret, **setting_and_context_kwds): raise NotImplementedError('must be implemented by subclass') @deprecated_method(deprecated='1.7', removed='2.0', replacement='.hash()') @classmethod def encrypt(cls, *args, **kwds): return cls.hash(*args, **kwds) @classmethod @abstractmethod def verify(cls, secret, hash, **context_kwds): raise NotImplementedError('must be implemented by subclass') @classmethod @abstractmethod def using(cls, relaxed=False, **kwds): raise NotImplementedError('must be implemented by subclass') @classmethod def needs_update(cls, hash, secret=None): return False @classmethod @abstractmethod def identify(cls, hash): raise NotImplementedError('must be implemented by subclass') @deprecated_method(deprecated='1.7', removed='2.0') @classmethod def genconfig(cls, **setting_kwds): if cls.context_kwds: raise NotImplementedError('must be implemented by subclass') return cls.using(**setting_kwds).hash('') @deprecated_method(deprecated='1.7', removed='2.0') @classmethod def genhash(cls, secret, config, **context): raise NotImplementedError('must be implemented by subclass') deprecated = False class DisabledHash(PasswordHash): is_disabled = True @classmethod def disable(cls, hash=None): return cls.hash('') @classmethod def enable(cls, hash): raise ValueError('cannot restore original hash')
971
885
68
10ed78e18b80f9e2fa0a506db866dc06d61ab8c5
37
py
Python
nodetasks/__init__.py
michalStarski/node-tasks
9f9ec0d3a2488babd7c32cb04e47e120ca88d119
[ "MIT" ]
3
2020-10-29T21:13:51.000Z
2020-11-05T08:53:48.000Z
nodetasks/__init__.py
michalStarski/node-tasks
9f9ec0d3a2488babd7c32cb04e47e120ca88d119
[ "MIT" ]
null
null
null
nodetasks/__init__.py
michalStarski/node-tasks
9f9ec0d3a2488babd7c32cb04e47e120ca88d119
[ "MIT" ]
null
null
null
from nodetasks.nodetasks import main
18.5
36
0.864865
from nodetasks.nodetasks import main
0
0
0
90c7e36f7d5ca62d1e26ad3ae288e6ece67a2e02
592
py
Python
tests/saversion.py
edupo/py-mongosql
27d2d125e862106077addec0376b07b13894439d
[ "MIT" ]
36
2015-02-25T20:30:34.000Z
2022-02-13T08:38:24.000Z
tests/saversion.py
edupo/py-mongosql
27d2d125e862106077addec0376b07b13894439d
[ "MIT" ]
8
2017-06-14T03:21:42.000Z
2022-02-09T11:56:00.000Z
tests/saversion.py
edupo/py-mongosql
27d2d125e862106077addec0376b07b13894439d
[ "MIT" ]
10
2015-10-21T09:22:37.000Z
2022-02-09T11:33:32.000Z
from distutils.version import LooseVersion from mongosql import SA_VERSION, SA_12, SA_13 def SA_VERSION_IN(min_version, max_version): """ Check that SqlAlchemy version lies within a range This is slow; only use in unit-tests! """ return LooseVersion(min_version) <= LooseVersion(SA_VERSION) <= LooseVersion(max_version) def SA_SINCE(version): """ Check SqlAlchemy >= version """ return LooseVersion(SA_VERSION) >= LooseVersion(version) def SA_UNTIL(version): """ Check SqlAlchemy <= version """ return LooseVersion(SA_VERSION) <= LooseVersion(version)
26.909091
93
0.72973
from distutils.version import LooseVersion from mongosql import SA_VERSION, SA_12, SA_13 def SA_VERSION_IN(min_version, max_version): """ Check that SqlAlchemy version lies within a range This is slow; only use in unit-tests! """ return LooseVersion(min_version) <= LooseVersion(SA_VERSION) <= LooseVersion(max_version) def SA_SINCE(version): """ Check SqlAlchemy >= version """ return LooseVersion(SA_VERSION) >= LooseVersion(version) def SA_UNTIL(version): """ Check SqlAlchemy <= version """ return LooseVersion(SA_VERSION) <= LooseVersion(version)
0
0
0
78a25d57287b85842e5ab7905e861a14d92d55e6
1,347
py
Python
cn/opencv/color/color_three.py
Jasonandy/Python-X
2f02b9a17bd5495dd1f8746b191f11ec2d7bccbe
[ "Apache-2.0" ]
null
null
null
cn/opencv/color/color_three.py
Jasonandy/Python-X
2f02b9a17bd5495dd1f8746b191f11ec2d7bccbe
[ "Apache-2.0" ]
null
null
null
cn/opencv/color/color_three.py
Jasonandy/Python-X
2f02b9a17bd5495dd1f8746b191f11ec2d7bccbe
[ "Apache-2.0" ]
2
2019-06-18T05:53:26.000Z
2019-06-19T03:26:02.000Z
import numpy as np import cv2 red_lower = np.array([0,43,46]) red_upper = np.array([10,255,255]) blue_lower = np.array([100,43,46]) blue_upper = np.array([124,255,255]) cap = cv2.VideoCapture(0) cap.set(3,320) cap.set(4,240) while 1: ret,frame = cap.read() frame = cv2.GaussianBlur(frame,(5,5),0) hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV) mask = ChestRed() ChestBule() res = cv2.bitwise_and(frame,frame,mask=mask) cnts = cv2.findContours(mask.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2] if 20<len(cnts)<30: print("Red!") cv2.imshow("frame",frame) cv2.imshow("mask",mask) cv2.imshow("res",res) if cv2.waitKey(5) == ord('q'): break cap.release() cv2.destroyAllWindows()
30.613636
88
0.651076
import numpy as np import cv2 red_lower = np.array([0,43,46]) red_upper = np.array([10,255,255]) blue_lower = np.array([100,43,46]) blue_upper = np.array([124,255,255]) cap = cv2.VideoCapture(0) cap.set(3,320) cap.set(4,240) def ChestRed(): hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv, red_lower, red_upper) mask = cv2.erode(mask, None, iterations=2) mask = cv2.GaussianBlur(mask, (3, 3), 0) return mask def ChestBule(): ret, frame = cap.read() frame = cv2.GaussianBlur(frame, (5, 5), 0) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) mask = cv2.inRange(hsv, blue_lower, blue_upper) mask = cv2.GaussianBlur(mask, (3, 3), 0) cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2] if 25 < len(cnts) < 29: print("Blue!") while 1: ret,frame = cap.read() frame = cv2.GaussianBlur(frame,(5,5),0) hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV) mask = ChestRed() ChestBule() res = cv2.bitwise_and(frame,frame,mask=mask) cnts = cv2.findContours(mask.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2] if 20<len(cnts)<30: print("Red!") cv2.imshow("frame",frame) cv2.imshow("mask",mask) cv2.imshow("res",res) if cv2.waitKey(5) == ord('q'): break cap.release() cv2.destroyAllWindows()
557
0
44
cd43012772e2d2ca2aed819c9c52c439b40a78aa
4,595
py
Python
snapflow/testing/utils.py
icedevml/snapflow
329dae3f8eaa70d3a26d38a505faeb45d8eecb57
[ "BSD-3-Clause" ]
null
null
null
snapflow/testing/utils.py
icedevml/snapflow
329dae3f8eaa70d3a26d38a505faeb45d8eecb57
[ "BSD-3-Clause" ]
null
null
null
snapflow/testing/utils.py
icedevml/snapflow
329dae3f8eaa70d3a26d38a505faeb45d8eecb57
[ "BSD-3-Clause" ]
null
null
null
from __future__ import annotations import tempfile from contextlib import contextmanager from dataclasses import dataclass from typing import Any, Dict, Iterator, List, Optional from commonmodel.base import Schema, SchemaLike from dcp.data_format.handler import get_handler_for_name, infer_schema_for_name from dcp.data_format.formats.memory.records import PythonRecordsHandler from dcp.storage.base import Storage from dcp.storage.database.utils import get_tmp_sqlite_db_url from dcp.utils.common import rand_str from dcp.utils.data import read_csv, read_json, read_raw_string_csv from pandas import DataFrame from snapflow import DataBlock, Environment, Graph, _Snap from snapflow.core.module import SnapflowModule from snapflow.core.node import DataBlockLog, Node, SnapLog from sqlalchemy.orm import Session from sqlalchemy.sql.expression import select @dataclass @contextmanager
34.548872
82
0.661371
from __future__ import annotations import tempfile from contextlib import contextmanager from dataclasses import dataclass from typing import Any, Dict, Iterator, List, Optional from commonmodel.base import Schema, SchemaLike from dcp.data_format.handler import get_handler_for_name, infer_schema_for_name from dcp.data_format.formats.memory.records import PythonRecordsHandler from dcp.storage.base import Storage from dcp.storage.database.utils import get_tmp_sqlite_db_url from dcp.utils.common import rand_str from dcp.utils.data import read_csv, read_json, read_raw_string_csv from pandas import DataFrame from snapflow import DataBlock, Environment, Graph, _Snap from snapflow.core.module import SnapflowModule from snapflow.core.node import DataBlockLog, Node, SnapLog from sqlalchemy.orm import Session from sqlalchemy.sql.expression import select def display_snap_log(env: Environment): for dbl in env.md_api.execute( select(DataBlockLog).order_by(DataBlockLog.created_at) ): print(f"{dbl.snap_log.snap_key:30} {dbl.data_block_id:4} {dbl.direction}") def str_as_dataframe( env: Environment, test_data: str, module: Optional[SnapflowModule] = None, nominal_schema: Optional[Schema] = None, ) -> DataFrame: # TODO: add conform_dataframe_to_schema option if test_data.endswith(".csv"): if module is None: raise with module.open_module_file(test_data) as f: raw_records = list(read_csv(f.readlines())) elif test_data.endswith(".json"): if module is None: raise with module.open_module_file(test_data) as f: raw_records = [read_json(line) for line in f] else: # Raw str csv raw_records = list(read_raw_string_csv(test_data)) tmp = "_test_obj_" + rand_str() env._local_python_storage.get_api().put(tmp, raw_records) if nominal_schema is None: auto_schema = infer_schema_for_name(tmp, env._local_python_storage) nominal_schema = auto_schema else: PythonRecordsHandler().cast_to_schema( tmp, env._local_python_storage, nominal_schema ) df = DataFrame.from_records(raw_records) return df @dataclass class DataInput: data: str schema: Optional[SchemaLike] = None module: Optional[SnapflowModule] = None def as_dataframe(self, env: Environment): schema = None if self.schema: schema = env.get_schema(self.schema) return str_as_dataframe( env, self.data, module=self.module, nominal_schema=schema ) def get_schema_key(self) -> Optional[str]: if not self.schema: return None if isinstance(self.schema, str): return self.schema return self.schema.key @contextmanager def produce_snap_output_for_static_input( snap: _Snap, params: Dict[str, Any] = None, input: Any = None, inputs: Any = None, env: Optional[Environment] = None, module: Optional[SnapflowModule] = None, target_storage: Optional[Storage] = None, upstream: Any = None, # TODO: DEPRECATED ) -> Iterator[List[DataBlock]]: inputs = input or inputs or upstream if env is None: db = get_tmp_sqlite_db_url() env = Environment(metadata_storage=db) if target_storage: target_storage = env.add_storage(target_storage) with env.md_api.begin(): g = Graph(env) input_datas = inputs input_nodes: Dict[str, Node] = {} pi = snap.get_interface() if not isinstance(inputs, dict): assert len(pi.get_non_recursive_inputs()) == 1 input_datas = {pi.get_non_recursive_inputs()[0].name: inputs} for inpt in pi.inputs: if inpt.from_self: continue assert inpt.name is not None input_data = input_datas[inpt.name] if isinstance(input_data, str): input_data = DataInput(data=input_data) n = g.create_node( key=f"_input_{inpt.name}", snap="core.import_dataframe", params={ "dataframe": input_data.as_dataframe(env), "schema": input_data.get_schema_key(), }, ) input_nodes[inpt.name] = n test_node = g.create_node( key=f"{snap.name}", snap=snap, params=params, inputs=input_nodes ) blocks = env.produce( test_node, to_exhaustion=False, target_storage=target_storage ) yield blocks
3,467
147
90
d1be535622b9fc051067542af0f42d2347da64bf
110
py
Python
tests.py
mraarif/sample-checks-repo
cf26ec73fabf4231d74e0bcb85d80f26eeb2407c
[ "MIT" ]
null
null
null
tests.py
mraarif/sample-checks-repo
cf26ec73fabf4231d74e0bcb85d80f26eeb2407c
[ "MIT" ]
null
null
null
tests.py
mraarif/sample-checks-repo
cf26ec73fabf4231d74e0bcb85d80f26eeb2407c
[ "MIT" ]
null
null
null
import pytest
15.714286
52
0.7
import pytest def test_divide_by_zero(): with pytest.raises(ZeroDivisionError) as e_info: 1 / 0
72
0
23
4e8e763886d62307b0f52e2c95d2165e30ba591c
26,851
py
Python
pysnmp-with-texts/CISCO-SME-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
8
2019-05-09T17:04:00.000Z
2021-06-09T06:50:51.000Z
pysnmp-with-texts/CISCO-SME-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
4
2019-05-31T16:42:59.000Z
2020-01-31T21:57:17.000Z
pysnmp-with-texts/CISCO-SME-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
10
2019-04-30T05:51:36.000Z
2022-02-16T03:33:41.000Z
# # PySNMP MIB module CISCO-SME-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-SME-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:12:18 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ValueSizeConstraint") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") FcNameId, = mibBuilder.importSymbols("CISCO-ST-TC", "FcNameId") ifDescr, InterfaceIndex = mibBuilder.importSymbols("IF-MIB", "ifDescr", "InterfaceIndex") InetAddressType, InetAddress = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressType", "InetAddress") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup") TimeTicks, ModuleIdentity, Bits, Integer32, Unsigned32, ObjectIdentity, Counter32, Counter64, IpAddress, MibIdentifier, iso, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "ModuleIdentity", "Bits", "Integer32", "Unsigned32", "ObjectIdentity", "Counter32", "Counter64", "IpAddress", "MibIdentifier", "iso", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType") StorageType, RowStatus, DisplayString, TruthValue, TextualConvention, TimeStamp = mibBuilder.importSymbols("SNMPv2-TC", "StorageType", "RowStatus", "DisplayString", "TruthValue", "TextualConvention", "TimeStamp") ciscoSmeMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 632)) ciscoSmeMIB.setRevisions(('2008-03-28 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: ciscoSmeMIB.setRevisionsDescriptions(('Initial version',)) if mibBuilder.loadTexts: ciscoSmeMIB.setLastUpdated('200803280000Z') if mibBuilder.loadTexts: ciscoSmeMIB.setOrganization('Cisco Systems Inc. ') if mibBuilder.loadTexts: ciscoSmeMIB.setContactInfo(' Cisco Systems Customer Service Postal: 170 W Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553 -NETS E-mail: cs-san@cisco.com') if mibBuilder.loadTexts: ciscoSmeMIB.setDescription('MIB module to manage Storage Media Encryption (SME) service. SME is an encryption service provided by an encryption node residing on a linecard in a storage device. It receives clear-text data from host, encrypts it, then sends it to be written to tape or disk. It does the reverse in the opposite direction so the service is completely transparent to the host. The purpose of this service is to enhance data security in case the tape or disk is lost or stolen. As with any important service, user requires that it provides some level of fault tolerant in a graceful manner. SME provides this by allowing encryption nodes to be grouped into cluster. Nodes in the same cluster immediately pick up the work of a failed node so user does not see service disruption.') ciscoSmeMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 632, 0)) ciscoSmeMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 632, 1)) ciscoSmeMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 632, 2)) cSmeConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1)) cSmeClusterTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 1), ) if mibBuilder.loadTexts: cSmeClusterTable.setStatus('current') if mibBuilder.loadTexts: cSmeClusterTable.setDescription('This table lists all the SME clusters that are configured on this device. As with any important service, user requires that it provides some level of fault tolerant in a graceful manner. SME provides this by allowing encryption nodes to be grouped into cluster. Nodes in the same cluster immediately pick up the work of a failed node so user does not see service disruption.') cSmeClusterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-SME-MIB", "cSmeClusterId")) if mibBuilder.loadTexts: cSmeClusterEntry.setStatus('current') if mibBuilder.loadTexts: cSmeClusterEntry.setDescription('A conceptual row in the cSmeClusterTable. Each row represents a SME cluster in the system and provides the runtime and configuration information of a cluster.') cSmeClusterId = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 1, 1, 1), CiscoSmeClusterIndex()) if mibBuilder.loadTexts: cSmeClusterId.setStatus('current') if mibBuilder.loadTexts: cSmeClusterId.setDescription('Globally unique index that identifies a SME cluster. This index must be generated in such a way that the same value is never reused even after cluster has been deleted.') cSmeClusterName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 1, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeClusterName.setStatus('current') if mibBuilder.loadTexts: cSmeClusterName.setDescription('The name of the SME cluster.') cSmeClusterState = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 1, 1, 3), CiscoSmeClusterStatus()).setMaxAccess("readonly") if mibBuilder.loadTexts: cSmeClusterState.setStatus('current') if mibBuilder.loadTexts: cSmeClusterState.setDescription('The operational state of the SME cluster.') cSmeClusterMasterInetAddrType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 1, 1, 4), InetAddressType()).setMaxAccess("readonly") if mibBuilder.loadTexts: cSmeClusterMasterInetAddrType.setStatus('current') if mibBuilder.loadTexts: cSmeClusterMasterInetAddrType.setDescription('The type of Internet address of the SME cluster master. The Internet address of SME cluster master is specified by the value of the corresponding instance of cSmeClusterMasterInetAddr.') cSmeClusterMasterInetAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 1, 1, 5), InetAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: cSmeClusterMasterInetAddr.setStatus('current') if mibBuilder.loadTexts: cSmeClusterMasterInetAddr.setDescription('The Internet address of the SME cluster master device. The type of this Internet address is determined by the value of the corresponding instance of cSmeClusterMasterInetAddrType.') cSmeClusterStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 1, 1, 6), StorageType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeClusterStorageType.setStatus('current') if mibBuilder.loadTexts: cSmeClusterStorageType.setDescription('This object specifies the storage type for this conceptual row.') cSmeClusterRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 1, 1, 7), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeClusterRowStatus.setStatus('current') if mibBuilder.loadTexts: cSmeClusterRowStatus.setDescription('The status of this conceptual row. There is no restriction on the value of other columns before a newly created row can be made active.') cSmeClusterMembersTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 2), ) if mibBuilder.loadTexts: cSmeClusterMembersTable.setStatus('current') if mibBuilder.loadTexts: cSmeClusterMembersTable.setDescription('This table lists the information of devices, local or remote, which are members of SME clusters configured on a device.') cSmeClusterMembersEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 2, 1), ).setIndexNames((0, "CISCO-SME-MIB", "cSmeClusterId"), (0, "CISCO-SME-MIB", "cSmeMemberInetAddrType"), (0, "CISCO-SME-MIB", "cSmeMemberInetAddr")) if mibBuilder.loadTexts: cSmeClusterMembersEntry.setStatus('current') if mibBuilder.loadTexts: cSmeClusterMembersEntry.setDescription('A conceptual row in the cSmeClusterMembersTable. Each row represents a member device within a specified SME Cluster.') cSmeMemberInetAddrType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 2, 1, 1), InetAddressType()) if mibBuilder.loadTexts: cSmeMemberInetAddrType.setStatus('current') if mibBuilder.loadTexts: cSmeMemberInetAddrType.setDescription('The type of Internet address of a cluster member within a specified SME cluster. The Internet address of this device is specified by the value of the corresponding instance of cSmeMemberInetAddr.') cSmeMemberInetAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 2, 1, 2), InetAddress().subtype(subtypeSpec=ValueSizeConstraint(0, 32))) if mibBuilder.loadTexts: cSmeMemberInetAddr.setStatus('current') if mibBuilder.loadTexts: cSmeMemberInetAddr.setDescription('The Internet address of the cluster member device within a specified SME cluster. The type of this Internet address is determined by the value of the corresponding instance of cSmeMemberInetAddrType.') cSmeFabric = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 2, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeFabric.setStatus('current') if mibBuilder.loadTexts: cSmeFabric.setDescription('Refers to the name of physical fibre channel fabric in the SAN. A typical SAN deployment consists of a dual fabric topology which corresponds to two physical fabrics. In such a deployment, a VSAN and a cluster is configured in both fabrics to allow multi-pathing and redundancy. The user specifies the physical fabric to which a device belongs to when the cluster is configured.') cSmeIsMemberLocal = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 2, 1, 4), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: cSmeIsMemberLocal.setStatus('current') if mibBuilder.loadTexts: cSmeIsMemberLocal.setDescription("Identifies if the device is a local or remote member of this cluster. 'true' means this device is a local device. 'false' means this device is a remote device.") cSmeMemberIsMaster = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 2, 1, 5), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: cSmeMemberIsMaster.setStatus('current') if mibBuilder.loadTexts: cSmeMemberIsMaster.setDescription("Indicates if this device is currently the master of the SME cluster. The value 'true' means this device is the master. The value 'false' means this device is not the master. Devices in a cluster select one of the cluster member to be a master. The master is responsible for handling cluster membership.") cSmeClusterMemberStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 2, 1, 6), StorageType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeClusterMemberStorageType.setStatus('current') if mibBuilder.loadTexts: cSmeClusterMemberStorageType.setDescription('This object specifies the storage type for this conceptual row.') cSmeClusterMemberRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 2, 1, 7), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeClusterMemberRowStatus.setStatus('current') if mibBuilder.loadTexts: cSmeClusterMemberRowStatus.setDescription('The status of this conceptual row. There is no restriction on the value of other columns before a newly created row can be made active. When a cluster is deleted, all entries in this table should be purged automatically.') cSmeClusterMemberIfTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 3), ) if mibBuilder.loadTexts: cSmeClusterMemberIfTable.setStatus('current') if mibBuilder.loadTexts: cSmeClusterMemberIfTable.setDescription('This table lists the information of SME interfaces on all devices, local or remote, which are members of SME clusters configured on a device.') cSmeClusterMemberIfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 3, 1), ).setIndexNames((0, "CISCO-SME-MIB", "cSmeClusterId"), (0, "CISCO-SME-MIB", "cSmeMemberInetAddrType"), (0, "CISCO-SME-MIB", "cSmeMemberInetAddr"), (0, "CISCO-SME-MIB", "cSmeClusterInterfaceIndex")) if mibBuilder.loadTexts: cSmeClusterMemberIfEntry.setStatus('current') if mibBuilder.loadTexts: cSmeClusterMemberIfEntry.setDescription('A conceptual row in the cSmeClusterMemberIfTable. Each row represents a participating interface on local/remote device member within the specified SME cluster.') cSmeClusterInterfaceIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 3, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: cSmeClusterInterfaceIndex.setStatus('current') if mibBuilder.loadTexts: cSmeClusterInterfaceIndex.setDescription('A unique Interface index for a SME interface on a device in this cluster. This is the same as ifIndex of the ifTable of RFC1213.') cSmeClusterInterfaceState = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 3, 1, 2), CiscoSmeInterfaceStatus()).setMaxAccess("readonly") if mibBuilder.loadTexts: cSmeClusterInterfaceState.setStatus('current') if mibBuilder.loadTexts: cSmeClusterInterfaceState.setDescription('The operational state of this SME interface.') cSmeInterfaceTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 4), ) if mibBuilder.loadTexts: cSmeInterfaceTable.setStatus('current') if mibBuilder.loadTexts: cSmeInterfaceTable.setDescription('This table lists all SME interfaces on the local device and its corresponding information.') cSmeInterfaceEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 4, 1), ).setIndexNames((0, "CISCO-SME-MIB", "cSmeInterfaceIndex")) if mibBuilder.loadTexts: cSmeInterfaceEntry.setStatus('current') if mibBuilder.loadTexts: cSmeInterfaceEntry.setDescription('A conceptual row in the cSmeInterfaceTable. Each row represents a particular SME interface on a local device.') cSmeInterfaceIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 4, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: cSmeInterfaceIndex.setStatus('current') if mibBuilder.loadTexts: cSmeInterfaceIndex.setDescription('A unique Interface index for a SME interface on this device. This is the same as ifIndex of the ifTable of RFC1213.') cSmeInterfaceState = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 4, 1, 2), CiscoSmeInterfaceStatus()).setMaxAccess("readonly") if mibBuilder.loadTexts: cSmeInterfaceState.setStatus('current') if mibBuilder.loadTexts: cSmeInterfaceState.setDescription('Operational state of this SME interface.') cSmeInterfaceClusterId = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 4, 1, 3), CiscoSmeClusterIndex()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeInterfaceClusterId.setStatus('current') if mibBuilder.loadTexts: cSmeInterfaceClusterId.setDescription('Identifies the cluster to which this SME interface belongs.') cSmeInterfaceStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 4, 1, 4), StorageType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeInterfaceStorageType.setStatus('current') if mibBuilder.loadTexts: cSmeInterfaceStorageType.setDescription('This object specifies the storage type for this conceptual row.') cSmeInterfaceRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 4, 1, 5), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeInterfaceRowStatus.setStatus('current') if mibBuilder.loadTexts: cSmeInterfaceRowStatus.setDescription('The status of this conceptual row. There is no restriction on the value of other columns before a newly created row can be made active. For example, cSmeInterfaceClusterId column can be set independently later.') cSmeHostPortTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 5), ) if mibBuilder.loadTexts: cSmeHostPortTable.setStatus('current') if mibBuilder.loadTexts: cSmeHostPortTable.setDescription('This table lists the hosts that are configured for SME. In the case of application servers, the disks that are accessed by the hosts may be encrypted. In the case of backup/restore master/media servers, the tapes accessed by the hosts may be encrypted.') cSmeHostPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 5, 1), ).setIndexNames((0, "CISCO-SME-MIB", "cSmeHostPortName")) if mibBuilder.loadTexts: cSmeHostPortEntry.setStatus('current') if mibBuilder.loadTexts: cSmeHostPortEntry.setDescription('A conceptual row in the cSmeHostPortTable. Each row represents a particular host configured for SME service in a particular cluster.') cSmeHostPortName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 5, 1, 1), FcNameId()) if mibBuilder.loadTexts: cSmeHostPortName.setStatus('current') if mibBuilder.loadTexts: cSmeHostPortName.setDescription('Fibre-channel Port name (P_WWN) of the Host Nx_Port.') cSmeHostPortClusterId = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 5, 1, 2), CiscoSmeClusterIndex()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeHostPortClusterId.setStatus('current') if mibBuilder.loadTexts: cSmeHostPortClusterId.setDescription('Identifies the cluster to which this host port belongs.') cSmeHostPortStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 5, 1, 3), StorageType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeHostPortStorageType.setStatus('current') if mibBuilder.loadTexts: cSmeHostPortStorageType.setDescription('This object specifies the storage type for this conceptual row.') cSmeHostPortRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 5, 1, 4), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeHostPortRowStatus.setStatus('current') if mibBuilder.loadTexts: cSmeHostPortRowStatus.setDescription('The status of this conceptual row. There is no restriction on the value of other columns before a newly created row can be made active.') cSmeConfigTableLastChanged = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 6), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: cSmeConfigTableLastChanged.setStatus('current') if mibBuilder.loadTexts: cSmeConfigTableLastChanged.setDescription('The value of sysUpTime when a change to any SME MIB table other than the cSmeHostPortTable last occurred.') cSmeHostPortTableLastChanged = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 7), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: cSmeHostPortTableLastChanged.setStatus('current') if mibBuilder.loadTexts: cSmeHostPortTableLastChanged.setDescription('The value of sysUpTime when a change to cSmeHostPortTable last occurred.') cSmeNotifyEnable = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 8), TruthValue().clone('true')).setMaxAccess("readwrite") if mibBuilder.loadTexts: cSmeNotifyEnable.setStatus('current') if mibBuilder.loadTexts: cSmeNotifyEnable.setDescription("This object specifies if the SME notifications should be generated or not. If the value of this object is 'true', then the notifications are generated. If the value of this object is 'false, then the notifications are not generated.") ciscoSmeInterfaceCreate = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 632, 0, 1)).setObjects(("IF-MIB", "ifDescr")) if mibBuilder.loadTexts: ciscoSmeInterfaceCreate.setStatus('current') if mibBuilder.loadTexts: ciscoSmeInterfaceCreate.setDescription('This notification is generated when a SME interface associated with a local device is created.') ciscoSmeInterfaceDelete = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 632, 0, 2)).setObjects(("IF-MIB", "ifDescr")) if mibBuilder.loadTexts: ciscoSmeInterfaceDelete.setStatus('current') if mibBuilder.loadTexts: ciscoSmeInterfaceDelete.setDescription('This notification is generated when a SME interface associated with a local device is deleted.') ciscoSmeClusterNewMaster = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 632, 0, 3)).setObjects(("CISCO-SME-MIB", "cSmeClusterName"), ("CISCO-SME-MIB", "cSmeClusterMasterInetAddrType"), ("CISCO-SME-MIB", "cSmeClusterMasterInetAddr")) if mibBuilder.loadTexts: ciscoSmeClusterNewMaster.setStatus('current') if mibBuilder.loadTexts: ciscoSmeClusterNewMaster.setDescription('This notification is generated when the sending device who is participating in a SME cluster has transitioned to be the master of the cluster.') ciscoSmeMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 632, 2, 1)) ciscoSmeMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 632, 2, 2)) ciscoSmeMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 632, 2, 1, 1)).setObjects(("CISCO-SME-MIB", "ciscoSmeConfigGroup"), ("CISCO-SME-MIB", "ciscoSmeNotifControlGroup"), ("CISCO-SME-MIB", "ciscoSmeNotifsGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoSmeMIBCompliance = ciscoSmeMIBCompliance.setStatus('current') if mibBuilder.loadTexts: ciscoSmeMIBCompliance.setDescription('The compliance statement for entities that implement SME.') ciscoSmeConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 632, 2, 2, 1)).setObjects(("CISCO-SME-MIB", "cSmeClusterState"), ("CISCO-SME-MIB", "cSmeClusterMasterInetAddrType"), ("CISCO-SME-MIB", "cSmeClusterMasterInetAddr"), ("CISCO-SME-MIB", "cSmeIsMemberLocal"), ("CISCO-SME-MIB", "cSmeClusterInterfaceState"), ("CISCO-SME-MIB", "cSmeInterfaceState"), ("CISCO-SME-MIB", "cSmeInterfaceClusterId"), ("CISCO-SME-MIB", "cSmeHostPortClusterId"), ("CISCO-SME-MIB", "cSmeConfigTableLastChanged"), ("CISCO-SME-MIB", "cSmeHostPortTableLastChanged"), ("CISCO-SME-MIB", "cSmeFabric"), ("CISCO-SME-MIB", "cSmeClusterName"), ("CISCO-SME-MIB", "cSmeInterfaceRowStatus"), ("CISCO-SME-MIB", "cSmeClusterRowStatus"), ("CISCO-SME-MIB", "cSmeMemberIsMaster"), ("CISCO-SME-MIB", "cSmeClusterMemberRowStatus"), ("CISCO-SME-MIB", "cSmeClusterStorageType"), ("CISCO-SME-MIB", "cSmeClusterMemberStorageType"), ("CISCO-SME-MIB", "cSmeInterfaceStorageType"), ("CISCO-SME-MIB", "cSmeHostPortStorageType"), ("CISCO-SME-MIB", "cSmeHostPortRowStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoSmeConfigGroup = ciscoSmeConfigGroup.setStatus('current') if mibBuilder.loadTexts: ciscoSmeConfigGroup.setDescription('A collection of objects for SME configuration.') ciscoSmeNotifControlGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 632, 2, 2, 2)).setObjects(("CISCO-SME-MIB", "cSmeNotifyEnable")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoSmeNotifControlGroup = ciscoSmeNotifControlGroup.setStatus('current') if mibBuilder.loadTexts: ciscoSmeNotifControlGroup.setDescription('A collection of objects for controlling SME notification.') ciscoSmeNotifsGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 9, 9, 632, 2, 2, 3)).setObjects(("CISCO-SME-MIB", "ciscoSmeInterfaceCreate"), ("CISCO-SME-MIB", "ciscoSmeInterfaceDelete"), ("CISCO-SME-MIB", "ciscoSmeClusterNewMaster")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoSmeNotifsGroup = ciscoSmeNotifsGroup.setStatus('current') if mibBuilder.loadTexts: ciscoSmeNotifsGroup.setDescription('A collection of objects for notification of SME events.') mibBuilder.exportSymbols("CISCO-SME-MIB", cSmeClusterMemberStorageType=cSmeClusterMemberStorageType, cSmeClusterTable=cSmeClusterTable, cSmeHostPortStorageType=cSmeHostPortStorageType, PYSNMP_MODULE_ID=ciscoSmeMIB, ciscoSmeNotifsGroup=ciscoSmeNotifsGroup, ciscoSmeConfigGroup=ciscoSmeConfigGroup, cSmeClusterStorageType=cSmeClusterStorageType, ciscoSmeInterfaceCreate=ciscoSmeInterfaceCreate, cSmeClusterEntry=cSmeClusterEntry, cSmeHostPortTable=cSmeHostPortTable, cSmeClusterMembersEntry=cSmeClusterMembersEntry, cSmeIsMemberLocal=cSmeIsMemberLocal, cSmeHostPortName=cSmeHostPortName, cSmeConfigTableLastChanged=cSmeConfigTableLastChanged, cSmeInterfaceIndex=cSmeInterfaceIndex, cSmeClusterInterfaceIndex=cSmeClusterInterfaceIndex, cSmeClusterMemberRowStatus=cSmeClusterMemberRowStatus, ciscoSmeClusterNewMaster=ciscoSmeClusterNewMaster, ciscoSmeMIB=ciscoSmeMIB, cSmeClusterInterfaceState=cSmeClusterInterfaceState, cSmeMemberIsMaster=cSmeMemberIsMaster, ciscoSmeInterfaceDelete=ciscoSmeInterfaceDelete, ciscoSmeMIBGroups=ciscoSmeMIBGroups, cSmeClusterMemberIfEntry=cSmeClusterMemberIfEntry, cSmeClusterMasterInetAddr=cSmeClusterMasterInetAddr, CiscoSmeClusterStatus=CiscoSmeClusterStatus, cSmeMemberInetAddrType=cSmeMemberInetAddrType, ciscoSmeNotifControlGroup=ciscoSmeNotifControlGroup, cSmeClusterMasterInetAddrType=cSmeClusterMasterInetAddrType, cSmeClusterName=cSmeClusterName, cSmeHostPortEntry=cSmeHostPortEntry, ciscoSmeMIBCompliance=ciscoSmeMIBCompliance, cSmeConfig=cSmeConfig, cSmeClusterId=cSmeClusterId, CiscoSmeInterfaceStatus=CiscoSmeInterfaceStatus, cSmeFabric=cSmeFabric, ciscoSmeMIBNotifs=ciscoSmeMIBNotifs, CiscoSmeClusterIndex=CiscoSmeClusterIndex, cSmeInterfaceState=cSmeInterfaceState, cSmeInterfaceStorageType=cSmeInterfaceStorageType, cSmeInterfaceTable=cSmeInterfaceTable, cSmeNotifyEnable=cSmeNotifyEnable, cSmeMemberInetAddr=cSmeMemberInetAddr, cSmeClusterMemberIfTable=cSmeClusterMemberIfTable, cSmeInterfaceEntry=cSmeInterfaceEntry, cSmeClusterMembersTable=cSmeClusterMembersTable, cSmeHostPortRowStatus=cSmeHostPortRowStatus, cSmeInterfaceRowStatus=cSmeInterfaceRowStatus, cSmeInterfaceClusterId=cSmeInterfaceClusterId, cSmeHostPortClusterId=cSmeHostPortClusterId, ciscoSmeMIBConform=ciscoSmeMIBConform, ciscoSmeMIBObjects=ciscoSmeMIBObjects, cSmeHostPortTableLastChanged=cSmeHostPortTableLastChanged, ciscoSmeMIBCompliances=ciscoSmeMIBCompliances, cSmeClusterState=cSmeClusterState, cSmeClusterRowStatus=cSmeClusterRowStatus)
139.124352
2,458
0.783732
# # PySNMP MIB module CISCO-SME-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-SME-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:12:18 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ValueSizeConstraint") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") FcNameId, = mibBuilder.importSymbols("CISCO-ST-TC", "FcNameId") ifDescr, InterfaceIndex = mibBuilder.importSymbols("IF-MIB", "ifDescr", "InterfaceIndex") InetAddressType, InetAddress = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressType", "InetAddress") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup") TimeTicks, ModuleIdentity, Bits, Integer32, Unsigned32, ObjectIdentity, Counter32, Counter64, IpAddress, MibIdentifier, iso, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "ModuleIdentity", "Bits", "Integer32", "Unsigned32", "ObjectIdentity", "Counter32", "Counter64", "IpAddress", "MibIdentifier", "iso", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType") StorageType, RowStatus, DisplayString, TruthValue, TextualConvention, TimeStamp = mibBuilder.importSymbols("SNMPv2-TC", "StorageType", "RowStatus", "DisplayString", "TruthValue", "TextualConvention", "TimeStamp") ciscoSmeMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 632)) ciscoSmeMIB.setRevisions(('2008-03-28 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: ciscoSmeMIB.setRevisionsDescriptions(('Initial version',)) if mibBuilder.loadTexts: ciscoSmeMIB.setLastUpdated('200803280000Z') if mibBuilder.loadTexts: ciscoSmeMIB.setOrganization('Cisco Systems Inc. ') if mibBuilder.loadTexts: ciscoSmeMIB.setContactInfo(' Cisco Systems Customer Service Postal: 170 W Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553 -NETS E-mail: cs-san@cisco.com') if mibBuilder.loadTexts: ciscoSmeMIB.setDescription('MIB module to manage Storage Media Encryption (SME) service. SME is an encryption service provided by an encryption node residing on a linecard in a storage device. It receives clear-text data from host, encrypts it, then sends it to be written to tape or disk. It does the reverse in the opposite direction so the service is completely transparent to the host. The purpose of this service is to enhance data security in case the tape or disk is lost or stolen. As with any important service, user requires that it provides some level of fault tolerant in a graceful manner. SME provides this by allowing encryption nodes to be grouped into cluster. Nodes in the same cluster immediately pick up the work of a failed node so user does not see service disruption.') ciscoSmeMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 632, 0)) ciscoSmeMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 632, 1)) ciscoSmeMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 632, 2)) cSmeConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1)) class CiscoSmeInterfaceStatus(TextualConvention, Integer32): description = "Operational state of the SME interface. 'unknown(1)' -- interface is in an unknown state 'initializing(2)' -- interface is being initialized 'offline(3)' -- interface is not active 'online(4)' -- interface is online and can be used" status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4)) namedValues = NamedValues(("unknown", 1), ("initializing", 2), ("offline", 3), ("online", 4)) class CiscoSmeClusterStatus(TextualConvention, Integer32): description = "Operational state of the SME cluster 'unknown(1)' -- cluster is in an unknown state 'inactive(2)' -- cluster is not active 'degraded(3)' -- cluster has lost some of its members 'recovery(4)' -- cluster is recovering from membership lost 'active(5)' -- cluster is active" status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5)) namedValues = NamedValues(("unknown", 1), ("inactive", 2), ("degraded", 3), ("recovery", 4), ("active", 5)) class CiscoSmeClusterIndex(TextualConvention, OctetString): description = 'This denotes the globally unique index for a SME cluster. The value of the CiscoSmeClusterIndex is a thirty-two-octet unsigned integer value encoded in a network-byte order.' status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(32, 32) fixedLength = 32 cSmeClusterTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 1), ) if mibBuilder.loadTexts: cSmeClusterTable.setStatus('current') if mibBuilder.loadTexts: cSmeClusterTable.setDescription('This table lists all the SME clusters that are configured on this device. As with any important service, user requires that it provides some level of fault tolerant in a graceful manner. SME provides this by allowing encryption nodes to be grouped into cluster. Nodes in the same cluster immediately pick up the work of a failed node so user does not see service disruption.') cSmeClusterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-SME-MIB", "cSmeClusterId")) if mibBuilder.loadTexts: cSmeClusterEntry.setStatus('current') if mibBuilder.loadTexts: cSmeClusterEntry.setDescription('A conceptual row in the cSmeClusterTable. Each row represents a SME cluster in the system and provides the runtime and configuration information of a cluster.') cSmeClusterId = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 1, 1, 1), CiscoSmeClusterIndex()) if mibBuilder.loadTexts: cSmeClusterId.setStatus('current') if mibBuilder.loadTexts: cSmeClusterId.setDescription('Globally unique index that identifies a SME cluster. This index must be generated in such a way that the same value is never reused even after cluster has been deleted.') cSmeClusterName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 1, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeClusterName.setStatus('current') if mibBuilder.loadTexts: cSmeClusterName.setDescription('The name of the SME cluster.') cSmeClusterState = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 1, 1, 3), CiscoSmeClusterStatus()).setMaxAccess("readonly") if mibBuilder.loadTexts: cSmeClusterState.setStatus('current') if mibBuilder.loadTexts: cSmeClusterState.setDescription('The operational state of the SME cluster.') cSmeClusterMasterInetAddrType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 1, 1, 4), InetAddressType()).setMaxAccess("readonly") if mibBuilder.loadTexts: cSmeClusterMasterInetAddrType.setStatus('current') if mibBuilder.loadTexts: cSmeClusterMasterInetAddrType.setDescription('The type of Internet address of the SME cluster master. The Internet address of SME cluster master is specified by the value of the corresponding instance of cSmeClusterMasterInetAddr.') cSmeClusterMasterInetAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 1, 1, 5), InetAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: cSmeClusterMasterInetAddr.setStatus('current') if mibBuilder.loadTexts: cSmeClusterMasterInetAddr.setDescription('The Internet address of the SME cluster master device. The type of this Internet address is determined by the value of the corresponding instance of cSmeClusterMasterInetAddrType.') cSmeClusterStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 1, 1, 6), StorageType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeClusterStorageType.setStatus('current') if mibBuilder.loadTexts: cSmeClusterStorageType.setDescription('This object specifies the storage type for this conceptual row.') cSmeClusterRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 1, 1, 7), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeClusterRowStatus.setStatus('current') if mibBuilder.loadTexts: cSmeClusterRowStatus.setDescription('The status of this conceptual row. There is no restriction on the value of other columns before a newly created row can be made active.') cSmeClusterMembersTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 2), ) if mibBuilder.loadTexts: cSmeClusterMembersTable.setStatus('current') if mibBuilder.loadTexts: cSmeClusterMembersTable.setDescription('This table lists the information of devices, local or remote, which are members of SME clusters configured on a device.') cSmeClusterMembersEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 2, 1), ).setIndexNames((0, "CISCO-SME-MIB", "cSmeClusterId"), (0, "CISCO-SME-MIB", "cSmeMemberInetAddrType"), (0, "CISCO-SME-MIB", "cSmeMemberInetAddr")) if mibBuilder.loadTexts: cSmeClusterMembersEntry.setStatus('current') if mibBuilder.loadTexts: cSmeClusterMembersEntry.setDescription('A conceptual row in the cSmeClusterMembersTable. Each row represents a member device within a specified SME Cluster.') cSmeMemberInetAddrType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 2, 1, 1), InetAddressType()) if mibBuilder.loadTexts: cSmeMemberInetAddrType.setStatus('current') if mibBuilder.loadTexts: cSmeMemberInetAddrType.setDescription('The type of Internet address of a cluster member within a specified SME cluster. The Internet address of this device is specified by the value of the corresponding instance of cSmeMemberInetAddr.') cSmeMemberInetAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 2, 1, 2), InetAddress().subtype(subtypeSpec=ValueSizeConstraint(0, 32))) if mibBuilder.loadTexts: cSmeMemberInetAddr.setStatus('current') if mibBuilder.loadTexts: cSmeMemberInetAddr.setDescription('The Internet address of the cluster member device within a specified SME cluster. The type of this Internet address is determined by the value of the corresponding instance of cSmeMemberInetAddrType.') cSmeFabric = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 2, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeFabric.setStatus('current') if mibBuilder.loadTexts: cSmeFabric.setDescription('Refers to the name of physical fibre channel fabric in the SAN. A typical SAN deployment consists of a dual fabric topology which corresponds to two physical fabrics. In such a deployment, a VSAN and a cluster is configured in both fabrics to allow multi-pathing and redundancy. The user specifies the physical fabric to which a device belongs to when the cluster is configured.') cSmeIsMemberLocal = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 2, 1, 4), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: cSmeIsMemberLocal.setStatus('current') if mibBuilder.loadTexts: cSmeIsMemberLocal.setDescription("Identifies if the device is a local or remote member of this cluster. 'true' means this device is a local device. 'false' means this device is a remote device.") cSmeMemberIsMaster = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 2, 1, 5), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: cSmeMemberIsMaster.setStatus('current') if mibBuilder.loadTexts: cSmeMemberIsMaster.setDescription("Indicates if this device is currently the master of the SME cluster. The value 'true' means this device is the master. The value 'false' means this device is not the master. Devices in a cluster select one of the cluster member to be a master. The master is responsible for handling cluster membership.") cSmeClusterMemberStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 2, 1, 6), StorageType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeClusterMemberStorageType.setStatus('current') if mibBuilder.loadTexts: cSmeClusterMemberStorageType.setDescription('This object specifies the storage type for this conceptual row.') cSmeClusterMemberRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 2, 1, 7), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeClusterMemberRowStatus.setStatus('current') if mibBuilder.loadTexts: cSmeClusterMemberRowStatus.setDescription('The status of this conceptual row. There is no restriction on the value of other columns before a newly created row can be made active. When a cluster is deleted, all entries in this table should be purged automatically.') cSmeClusterMemberIfTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 3), ) if mibBuilder.loadTexts: cSmeClusterMemberIfTable.setStatus('current') if mibBuilder.loadTexts: cSmeClusterMemberIfTable.setDescription('This table lists the information of SME interfaces on all devices, local or remote, which are members of SME clusters configured on a device.') cSmeClusterMemberIfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 3, 1), ).setIndexNames((0, "CISCO-SME-MIB", "cSmeClusterId"), (0, "CISCO-SME-MIB", "cSmeMemberInetAddrType"), (0, "CISCO-SME-MIB", "cSmeMemberInetAddr"), (0, "CISCO-SME-MIB", "cSmeClusterInterfaceIndex")) if mibBuilder.loadTexts: cSmeClusterMemberIfEntry.setStatus('current') if mibBuilder.loadTexts: cSmeClusterMemberIfEntry.setDescription('A conceptual row in the cSmeClusterMemberIfTable. Each row represents a participating interface on local/remote device member within the specified SME cluster.') cSmeClusterInterfaceIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 3, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: cSmeClusterInterfaceIndex.setStatus('current') if mibBuilder.loadTexts: cSmeClusterInterfaceIndex.setDescription('A unique Interface index for a SME interface on a device in this cluster. This is the same as ifIndex of the ifTable of RFC1213.') cSmeClusterInterfaceState = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 3, 1, 2), CiscoSmeInterfaceStatus()).setMaxAccess("readonly") if mibBuilder.loadTexts: cSmeClusterInterfaceState.setStatus('current') if mibBuilder.loadTexts: cSmeClusterInterfaceState.setDescription('The operational state of this SME interface.') cSmeInterfaceTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 4), ) if mibBuilder.loadTexts: cSmeInterfaceTable.setStatus('current') if mibBuilder.loadTexts: cSmeInterfaceTable.setDescription('This table lists all SME interfaces on the local device and its corresponding information.') cSmeInterfaceEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 4, 1), ).setIndexNames((0, "CISCO-SME-MIB", "cSmeInterfaceIndex")) if mibBuilder.loadTexts: cSmeInterfaceEntry.setStatus('current') if mibBuilder.loadTexts: cSmeInterfaceEntry.setDescription('A conceptual row in the cSmeInterfaceTable. Each row represents a particular SME interface on a local device.') cSmeInterfaceIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 4, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: cSmeInterfaceIndex.setStatus('current') if mibBuilder.loadTexts: cSmeInterfaceIndex.setDescription('A unique Interface index for a SME interface on this device. This is the same as ifIndex of the ifTable of RFC1213.') cSmeInterfaceState = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 4, 1, 2), CiscoSmeInterfaceStatus()).setMaxAccess("readonly") if mibBuilder.loadTexts: cSmeInterfaceState.setStatus('current') if mibBuilder.loadTexts: cSmeInterfaceState.setDescription('Operational state of this SME interface.') cSmeInterfaceClusterId = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 4, 1, 3), CiscoSmeClusterIndex()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeInterfaceClusterId.setStatus('current') if mibBuilder.loadTexts: cSmeInterfaceClusterId.setDescription('Identifies the cluster to which this SME interface belongs.') cSmeInterfaceStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 4, 1, 4), StorageType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeInterfaceStorageType.setStatus('current') if mibBuilder.loadTexts: cSmeInterfaceStorageType.setDescription('This object specifies the storage type for this conceptual row.') cSmeInterfaceRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 4, 1, 5), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeInterfaceRowStatus.setStatus('current') if mibBuilder.loadTexts: cSmeInterfaceRowStatus.setDescription('The status of this conceptual row. There is no restriction on the value of other columns before a newly created row can be made active. For example, cSmeInterfaceClusterId column can be set independently later.') cSmeHostPortTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 5), ) if mibBuilder.loadTexts: cSmeHostPortTable.setStatus('current') if mibBuilder.loadTexts: cSmeHostPortTable.setDescription('This table lists the hosts that are configured for SME. In the case of application servers, the disks that are accessed by the hosts may be encrypted. In the case of backup/restore master/media servers, the tapes accessed by the hosts may be encrypted.') cSmeHostPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 5, 1), ).setIndexNames((0, "CISCO-SME-MIB", "cSmeHostPortName")) if mibBuilder.loadTexts: cSmeHostPortEntry.setStatus('current') if mibBuilder.loadTexts: cSmeHostPortEntry.setDescription('A conceptual row in the cSmeHostPortTable. Each row represents a particular host configured for SME service in a particular cluster.') cSmeHostPortName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 5, 1, 1), FcNameId()) if mibBuilder.loadTexts: cSmeHostPortName.setStatus('current') if mibBuilder.loadTexts: cSmeHostPortName.setDescription('Fibre-channel Port name (P_WWN) of the Host Nx_Port.') cSmeHostPortClusterId = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 5, 1, 2), CiscoSmeClusterIndex()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeHostPortClusterId.setStatus('current') if mibBuilder.loadTexts: cSmeHostPortClusterId.setDescription('Identifies the cluster to which this host port belongs.') cSmeHostPortStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 5, 1, 3), StorageType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeHostPortStorageType.setStatus('current') if mibBuilder.loadTexts: cSmeHostPortStorageType.setDescription('This object specifies the storage type for this conceptual row.') cSmeHostPortRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 5, 1, 4), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cSmeHostPortRowStatus.setStatus('current') if mibBuilder.loadTexts: cSmeHostPortRowStatus.setDescription('The status of this conceptual row. There is no restriction on the value of other columns before a newly created row can be made active.') cSmeConfigTableLastChanged = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 6), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: cSmeConfigTableLastChanged.setStatus('current') if mibBuilder.loadTexts: cSmeConfigTableLastChanged.setDescription('The value of sysUpTime when a change to any SME MIB table other than the cSmeHostPortTable last occurred.') cSmeHostPortTableLastChanged = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 7), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: cSmeHostPortTableLastChanged.setStatus('current') if mibBuilder.loadTexts: cSmeHostPortTableLastChanged.setDescription('The value of sysUpTime when a change to cSmeHostPortTable last occurred.') cSmeNotifyEnable = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 632, 1, 1, 8), TruthValue().clone('true')).setMaxAccess("readwrite") if mibBuilder.loadTexts: cSmeNotifyEnable.setStatus('current') if mibBuilder.loadTexts: cSmeNotifyEnable.setDescription("This object specifies if the SME notifications should be generated or not. If the value of this object is 'true', then the notifications are generated. If the value of this object is 'false, then the notifications are not generated.") ciscoSmeInterfaceCreate = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 632, 0, 1)).setObjects(("IF-MIB", "ifDescr")) if mibBuilder.loadTexts: ciscoSmeInterfaceCreate.setStatus('current') if mibBuilder.loadTexts: ciscoSmeInterfaceCreate.setDescription('This notification is generated when a SME interface associated with a local device is created.') ciscoSmeInterfaceDelete = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 632, 0, 2)).setObjects(("IF-MIB", "ifDescr")) if mibBuilder.loadTexts: ciscoSmeInterfaceDelete.setStatus('current') if mibBuilder.loadTexts: ciscoSmeInterfaceDelete.setDescription('This notification is generated when a SME interface associated with a local device is deleted.') ciscoSmeClusterNewMaster = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 632, 0, 3)).setObjects(("CISCO-SME-MIB", "cSmeClusterName"), ("CISCO-SME-MIB", "cSmeClusterMasterInetAddrType"), ("CISCO-SME-MIB", "cSmeClusterMasterInetAddr")) if mibBuilder.loadTexts: ciscoSmeClusterNewMaster.setStatus('current') if mibBuilder.loadTexts: ciscoSmeClusterNewMaster.setDescription('This notification is generated when the sending device who is participating in a SME cluster has transitioned to be the master of the cluster.') ciscoSmeMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 632, 2, 1)) ciscoSmeMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 632, 2, 2)) ciscoSmeMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 632, 2, 1, 1)).setObjects(("CISCO-SME-MIB", "ciscoSmeConfigGroup"), ("CISCO-SME-MIB", "ciscoSmeNotifControlGroup"), ("CISCO-SME-MIB", "ciscoSmeNotifsGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoSmeMIBCompliance = ciscoSmeMIBCompliance.setStatus('current') if mibBuilder.loadTexts: ciscoSmeMIBCompliance.setDescription('The compliance statement for entities that implement SME.') ciscoSmeConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 632, 2, 2, 1)).setObjects(("CISCO-SME-MIB", "cSmeClusterState"), ("CISCO-SME-MIB", "cSmeClusterMasterInetAddrType"), ("CISCO-SME-MIB", "cSmeClusterMasterInetAddr"), ("CISCO-SME-MIB", "cSmeIsMemberLocal"), ("CISCO-SME-MIB", "cSmeClusterInterfaceState"), ("CISCO-SME-MIB", "cSmeInterfaceState"), ("CISCO-SME-MIB", "cSmeInterfaceClusterId"), ("CISCO-SME-MIB", "cSmeHostPortClusterId"), ("CISCO-SME-MIB", "cSmeConfigTableLastChanged"), ("CISCO-SME-MIB", "cSmeHostPortTableLastChanged"), ("CISCO-SME-MIB", "cSmeFabric"), ("CISCO-SME-MIB", "cSmeClusterName"), ("CISCO-SME-MIB", "cSmeInterfaceRowStatus"), ("CISCO-SME-MIB", "cSmeClusterRowStatus"), ("CISCO-SME-MIB", "cSmeMemberIsMaster"), ("CISCO-SME-MIB", "cSmeClusterMemberRowStatus"), ("CISCO-SME-MIB", "cSmeClusterStorageType"), ("CISCO-SME-MIB", "cSmeClusterMemberStorageType"), ("CISCO-SME-MIB", "cSmeInterfaceStorageType"), ("CISCO-SME-MIB", "cSmeHostPortStorageType"), ("CISCO-SME-MIB", "cSmeHostPortRowStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoSmeConfigGroup = ciscoSmeConfigGroup.setStatus('current') if mibBuilder.loadTexts: ciscoSmeConfigGroup.setDescription('A collection of objects for SME configuration.') ciscoSmeNotifControlGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 632, 2, 2, 2)).setObjects(("CISCO-SME-MIB", "cSmeNotifyEnable")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoSmeNotifControlGroup = ciscoSmeNotifControlGroup.setStatus('current') if mibBuilder.loadTexts: ciscoSmeNotifControlGroup.setDescription('A collection of objects for controlling SME notification.') ciscoSmeNotifsGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 9, 9, 632, 2, 2, 3)).setObjects(("CISCO-SME-MIB", "ciscoSmeInterfaceCreate"), ("CISCO-SME-MIB", "ciscoSmeInterfaceDelete"), ("CISCO-SME-MIB", "ciscoSmeClusterNewMaster")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoSmeNotifsGroup = ciscoSmeNotifsGroup.setStatus('current') if mibBuilder.loadTexts: ciscoSmeNotifsGroup.setDescription('A collection of objects for notification of SME events.') mibBuilder.exportSymbols("CISCO-SME-MIB", cSmeClusterMemberStorageType=cSmeClusterMemberStorageType, cSmeClusterTable=cSmeClusterTable, cSmeHostPortStorageType=cSmeHostPortStorageType, PYSNMP_MODULE_ID=ciscoSmeMIB, ciscoSmeNotifsGroup=ciscoSmeNotifsGroup, ciscoSmeConfigGroup=ciscoSmeConfigGroup, cSmeClusterStorageType=cSmeClusterStorageType, ciscoSmeInterfaceCreate=ciscoSmeInterfaceCreate, cSmeClusterEntry=cSmeClusterEntry, cSmeHostPortTable=cSmeHostPortTable, cSmeClusterMembersEntry=cSmeClusterMembersEntry, cSmeIsMemberLocal=cSmeIsMemberLocal, cSmeHostPortName=cSmeHostPortName, cSmeConfigTableLastChanged=cSmeConfigTableLastChanged, cSmeInterfaceIndex=cSmeInterfaceIndex, cSmeClusterInterfaceIndex=cSmeClusterInterfaceIndex, cSmeClusterMemberRowStatus=cSmeClusterMemberRowStatus, ciscoSmeClusterNewMaster=ciscoSmeClusterNewMaster, ciscoSmeMIB=ciscoSmeMIB, cSmeClusterInterfaceState=cSmeClusterInterfaceState, cSmeMemberIsMaster=cSmeMemberIsMaster, ciscoSmeInterfaceDelete=ciscoSmeInterfaceDelete, ciscoSmeMIBGroups=ciscoSmeMIBGroups, cSmeClusterMemberIfEntry=cSmeClusterMemberIfEntry, cSmeClusterMasterInetAddr=cSmeClusterMasterInetAddr, CiscoSmeClusterStatus=CiscoSmeClusterStatus, cSmeMemberInetAddrType=cSmeMemberInetAddrType, ciscoSmeNotifControlGroup=ciscoSmeNotifControlGroup, cSmeClusterMasterInetAddrType=cSmeClusterMasterInetAddrType, cSmeClusterName=cSmeClusterName, cSmeHostPortEntry=cSmeHostPortEntry, ciscoSmeMIBCompliance=ciscoSmeMIBCompliance, cSmeConfig=cSmeConfig, cSmeClusterId=cSmeClusterId, CiscoSmeInterfaceStatus=CiscoSmeInterfaceStatus, cSmeFabric=cSmeFabric, ciscoSmeMIBNotifs=ciscoSmeMIBNotifs, CiscoSmeClusterIndex=CiscoSmeClusterIndex, cSmeInterfaceState=cSmeInterfaceState, cSmeInterfaceStorageType=cSmeInterfaceStorageType, cSmeInterfaceTable=cSmeInterfaceTable, cSmeNotifyEnable=cSmeNotifyEnable, cSmeMemberInetAddr=cSmeMemberInetAddr, cSmeClusterMemberIfTable=cSmeClusterMemberIfTable, cSmeInterfaceEntry=cSmeInterfaceEntry, cSmeClusterMembersTable=cSmeClusterMembersTable, cSmeHostPortRowStatus=cSmeHostPortRowStatus, cSmeInterfaceRowStatus=cSmeInterfaceRowStatus, cSmeInterfaceClusterId=cSmeInterfaceClusterId, cSmeHostPortClusterId=cSmeHostPortClusterId, ciscoSmeMIBConform=ciscoSmeMIBConform, ciscoSmeMIBObjects=ciscoSmeMIBObjects, cSmeHostPortTableLastChanged=cSmeHostPortTableLastChanged, ciscoSmeMIBCompliances=ciscoSmeMIBCompliances, cSmeClusterState=cSmeClusterState, cSmeClusterRowStatus=cSmeClusterRowStatus)
0
1,413
68
2bd219b3e013b14aa017a9137cadf5e8dcaa45fe
2,035
py
Python
racketinterpreter/predefined/_symbol.py
ZibingZhang/racket-interpreter
20402401ddcbfead0cc028fe214834ef7720b9db
[ "MIT" ]
2
2020-06-09T01:43:15.000Z
2020-06-25T23:25:45.000Z
racketinterpreter/predefined/_symbol.py
ZibingZhang/racket-interpreter
20402401ddcbfead0cc028fe214834ef7720b9db
[ "MIT" ]
1
2021-02-02T23:46:55.000Z
2021-02-02T23:46:55.000Z
racketinterpreter/predefined/_symbol.py
ZibingZhang/racket-interpreter
20402401ddcbfead0cc028fe214834ef7720b9db
[ "MIT" ]
null
null
null
from __future__ import annotations import typing as tp from racketinterpreter.classes import data as d from racketinterpreter.classes import errors as err from racketinterpreter.predefined._base import BuiltInProc if tp.TYPE_CHECKING: from racketinterpreter.classes import ast from racketinterpreter.processes import Interpreter
29.071429
91
0.649631
from __future__ import annotations import typing as tp from racketinterpreter.classes import data as d from racketinterpreter.classes import errors as err from racketinterpreter.predefined._base import BuiltInProc if tp.TYPE_CHECKING: from racketinterpreter.classes import ast from racketinterpreter.processes import Interpreter class SymbolToString(BuiltInProc): @staticmethod def _interpret(interpreter: Interpreter, actual_params: tp.List[ast.AST]) -> d.String: param_value = interpreter.visit(actual_params[0]) param_type = type(param_value) if not issubclass(param_type, d.Symbol): raise err.ArgumentTypeError( expected=d.Boolean, given=param_value ) result = d.String(str(param_value)[1:]) return result class SymbolSymEqualHuh(BuiltInProc): UPPER = None @staticmethod def _interpret(interpreter: Interpreter, actual_params: tp.List[ast.AST]) -> d.Boolean: evaluated_params = [] for idx, param in enumerate(actual_params): param_value = interpreter.visit(param) param_type = type(param_value) if not issubclass(param_type, d.Symbol): raise err.ArgumentTypeError( idx=idx, expected=d.Symbol, given=param_value ) evaluated_params.append(param_value) first_param_value = evaluated_params[0] result = d.Boolean(True) for param_value in evaluated_params: if param_value != first_param_value: result = d.Boolean(False) break return result class SymbolHuh(BuiltInProc): @staticmethod def _interpret(interpreter: Interpreter, actual_params: tp.List[ast.AST]) -> d.Boolean: param_value = interpreter.visit(actual_params[0]) param_type = type(param_value) result = d.Boolean(issubclass(param_type, d.Symbol)) return result
1,435
190
69
0beb3064917d4ce5e383fda2668249da2e12bccb
1,836
py
Python
tests/api/endpoints/test_shared_folders.py
Xandersoft/seahub
f75f238b3e0a907e8a8003f419e367fa36e992e7
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
tests/api/endpoints/test_shared_folders.py
Xandersoft/seahub
f75f238b3e0a907e8a8003f419e367fa36e992e7
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
tests/api/endpoints/test_shared_folders.py
Xandersoft/seahub
f75f238b3e0a907e8a8003f419e367fa36e992e7
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
import os import json from django.core.urlresolvers import reverse from seaserv import seafile_api from seahub.test_utils import BaseTestCase
30.098361
59
0.646514
import os import json from django.core.urlresolvers import reverse from seaserv import seafile_api from seahub.test_utils import BaseTestCase class SharedFoldersTest(BaseTestCase): def create_virtual_repo(self): name = os.path.basename(self.folder.rstrip('/')) sub_repo_id = seafile_api.create_virtual_repo( self.repo.id, self.folder, name, name, self.user.username) return sub_repo_id def share_repo_to_user(self, repo_id): seafile_api.share_repo( repo_id, self.user.username, self.admin.username, 'rw') def share_repo_to_group(self, repo_id): seafile_api.set_group_repo( repo_id, self.group.id, self.user.username, 'rw') def setUp(self): self.repo_id = self.repo.id self.group_id = self.group.id self.user_name = self.user.username self.admin_user = self.admin.username self.url = reverse('api-v2.1-shared-folders') sub_repo_id = self.create_virtual_repo() self.share_repo_to_user(sub_repo_id) self.share_repo_to_group(sub_repo_id) def tearDown(self): self.remove_repo() def test_can_get(self): self.login_as(self.user) resp = self.client.get(self.url) self.assertEqual(200, resp.status_code) json_resp = json.loads(resp.content) assert json_resp[0]['share_type'] == 'personal' assert json_resp[1]['share_type'] == 'group' def test_get_with_invalid_repo_permission(self): # login with admin, then get user's share repo info self.login_as(self.admin) resp = self.client.get(self.url) self.assertEqual(200, resp.status_code) json_resp = json.loads(resp.content) assert len(json_resp) == 0
1,462
17
212
51eea1c1e038fc63b707ac70d1a882e36370b93e
1,155
py
Python
src/solution_794b24be.py
MoizSM/ARC
f04b696f32a02db682271187f16ab8b1ffa1cfeb
[ "Apache-2.0" ]
null
null
null
src/solution_794b24be.py
MoizSM/ARC
f04b696f32a02db682271187f16ab8b1ffa1cfeb
[ "Apache-2.0" ]
null
null
null
src/solution_794b24be.py
MoizSM/ARC
f04b696f32a02db682271187f16ab8b1ffa1cfeb
[ "Apache-2.0" ]
null
null
null
import sys import json import numpy as np solve()
36.09375
132
0.499567
import sys import json import numpy as np def solve(): #Function that contains the logic to solve the task with open(sys.argv[1] , 'r') as f: data = json.load(f) #Parsing the JSON file. var = ['train' , 'test'] #Running for all the training and testing inputs for z in var: for n in range(len(data[z])): grid = np.asarray(data[z][n]['input']) count = 0 #Count will contain the number of blue elements for x in np.nditer(grid): if x!=0 : count = count + 1 #Iterating for every blue element. for i in range(len(grid)): for x in range(len(grid[i])): #For loop for assigning the red (2) color elements. if ( i == 0 and x < count ): grid[i][x] = 2 else: grid[i][x] = 0 if (count > 3): grid[1][1]= 2 # When elements are more than 3 then we place the next element in second row and second column print(grid , '\n') #Printing the ouput grid solve()
1,073
0
23
a351715bd030ece07ed0ad9c9e6f3fe8b928150c
878
py
Python
ampa/cole/migrations/0008_alumne_to_many.py
jordiprats/django-ampa
b8e9d6076c32caa8bdc11094362ddccb12d95f8c
[ "Apache-2.0" ]
null
null
null
ampa/cole/migrations/0008_alumne_to_many.py
jordiprats/django-ampa
b8e9d6076c32caa8bdc11094362ddccb12d95f8c
[ "Apache-2.0" ]
null
null
null
ampa/cole/migrations/0008_alumne_to_many.py
jordiprats/django-ampa
b8e9d6076c32caa8bdc11094362ddccb12d95f8c
[ "Apache-2.0" ]
null
null
null
# Generated by Django 3.0.5 on 2020-11-28 14:53 from django.db import migrations, models import django.db.models.deletion
29.266667
127
0.634396
# Generated by Django 3.0.5 on 2020-11-28 14:53 from django.db import migrations, models import django.db.models.deletion def forward(apps, schema_editor): Alumne = apps.get_model("cole", "Alumne") for alumne in Alumne.objects.all(): alumne.classes.add(alumne.classe) class Migration(migrations.Migration): dependencies = [ ('cole', '0007_auto_20201128_1421'), ] operations = [ migrations.AddField( model_name='alumne', name='classes', field=models.ManyToManyField(related_name='alumnes', to='cole.Classe'), ), migrations.AlterField( model_name='alumne', name='classe', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='old_alumnes', to='cole.Classe'), ), migrations.RunPython(forward) ]
140
569
46
675972611121cc8492248031549e729032aa875e
1,230
py
Python
tests/test_nullable.py
leafant/jsonmodels
12dae38b9fa1d9960cf3bd4e63299bbdd31f8648
[ "BSD-3-Clause" ]
null
null
null
tests/test_nullable.py
leafant/jsonmodels
12dae38b9fa1d9960cf3bd4e63299bbdd31f8648
[ "BSD-3-Clause" ]
null
null
null
tests/test_nullable.py
leafant/jsonmodels
12dae38b9fa1d9960cf3bd4e63299bbdd31f8648
[ "BSD-3-Clause" ]
null
null
null
from jsonmodels_qdyk.fields import StringField, ListField, EmbeddedField from jsonmodels_qdyk.models import Base
24.117647
72
0.565041
from jsonmodels_qdyk.fields import StringField, ListField, EmbeddedField from jsonmodels_qdyk.models import Base class Nullable(Base): field = StringField(nullable=True) class NullableListField(Base): field = ListField([str], nullable=True) class NullableEmbedded(Base): field = EmbeddedField(Nullable, nullable=True) def test_nullable_simple_field(): result = Nullable.to_json_schema() assert result['properties']['field']['type'] == ['string', 'null'] def test_nullable_list_field(): result = NullableListField.to_json_schema() items = result['properties']['field']['items'] assert items.get('oneOf') assert items['oneOf'] == [{'type': 'string'}, {'type': 'null'}] def test_nullable_embedded_field(): result = NullableEmbedded.to_json_schema() expected = [ { 'type': 'object', 'additionalProperties': False, 'properties': { 'field': { 'type': [ 'string', 'null' ] } } }, { 'type': 'null' } ] assert result['properties']['field']['oneOf'] == expected
822
151
138
bf4380d0dc7511bd18cb8a9b7d036c28f6afddd5
1,216
py
Python
model/dataset/dataset.py
qiaofengsheng/Pytorch-Image-Classifier-Collection
b95a07451c6c169639af9a4f6f5e074055570828
[ "MulanPSL-1.0" ]
3
2022-01-29T07:25:40.000Z
2022-03-06T15:20:39.000Z
model/dataset/dataset.py
qiaofengsheng/Pytorch-Image-Classifier-Collection
b95a07451c6c169639af9a4f6f5e074055570828
[ "MulanPSL-1.0" ]
null
null
null
model/dataset/dataset.py
qiaofengsheng/Pytorch-Image-Classifier-Collection
b95a07451c6c169639af9a4f6f5e074055570828
[ "MulanPSL-1.0" ]
1
2022-03-06T18:01:19.000Z
2022-03-06T18:01:19.000Z
''' _*_coding:utf-8 _*_ @Time :2022/1/28 19:00 @Author : qiaofengsheng @File :dataset.py @Software :PyCharm ''' import os from PIL import Image from torch.utils.data import * from model.utils import utils from torchvision import transforms
29.658537
73
0.625822
''' _*_coding:utf-8 _*_ @Time :2022/1/28 19:00 @Author : qiaofengsheng @File :dataset.py @Software :PyCharm ''' import os from PIL import Image from torch.utils.data import * from model.utils import utils from torchvision import transforms class ClassDataset(Dataset): def __init__(self, data_dir, config): self.config = config self.transform = transforms.Compose([ transforms.RandomRotation(60), transforms.ToTensor() ]) self.dataset = [] class_dirs = os.listdir(data_dir) for class_dir in class_dirs: image_names = os.listdir(os.path.join(data_dir, class_dir)) for image_name in image_names: self.dataset.append( [os.path.join(data_dir, class_dir, image_name), int(config['class_names'].index(class_dir))]) def __len__(self): return len(self.dataset) def __getitem__(self, index): data = self.dataset[index] image_path, image_label = data image = Image.open(image_path) image = utils.keep_shape_resize(image, self.config['image_size']) return self.transform(image), image_label
846
7
103
6a180c5cf411a93f02d065b8ae966d15b9e68f1e
1,017
py
Python
shp2json.py
DSAdv/Sentinel3-LST-data
921e05a34b0f77ed03b4c9e310845db0f0a8c353
[ "Apache-2.0" ]
null
null
null
shp2json.py
DSAdv/Sentinel3-LST-data
921e05a34b0f77ed03b4c9e310845db0f0a8c353
[ "Apache-2.0" ]
null
null
null
shp2json.py
DSAdv/Sentinel3-LST-data
921e05a34b0f77ed03b4c9e310845db0f0a8c353
[ "Apache-2.0" ]
1
2019-03-21T09:15:56.000Z
2019-03-21T09:15:56.000Z
import glob import shapefile
23.651163
75
0.675516
import glob import shapefile def to_geojson(path_to_shp: str): filename = find_shapefile(path_to_shp) reader = shapefile.Reader(filename, encoding='latin-1') buffer = create_buffer(reader) return { 'type': 'FeatureCollection', 'features': buffer, } def find_shapefile(path_to_shp: str) -> str: pattern = '{}/*.shp'.format(path_to_shp) files = glob.glob(pattern) return files[0] def create_buffer(reader: shapefile.Reader) -> list: fields = reader.fields[1:] field_names = [field[0] for field in fields] buffer = [] for shape_record in reader.shapeRecords(): buffer.append(create_feature(shape_record, field_names)) return buffer def create_feature(shape_record: shapefile.ShapeRecord, field_names: list): properties = dict(zip(field_names, shape_record.record)) geometry = shape_record.shape.__geo_interface__ return { 'type': 'Feature', 'geometry': geometry, 'properties': properties, }
892
0
92
3aa72ac8757e08fce59031b12faa36a550dc500e
1,388
py
Python
compute_nads.py
gortizji/linearized-networks
3c271fb0a6c6bdffa9c1aabd8497f8803b725731
[ "MIT" ]
6
2021-11-15T07:09:21.000Z
2022-01-26T10:12:07.000Z
compute_nads.py
gortizji/linearized-networks
3c271fb0a6c6bdffa9c1aabd8497f8803b725731
[ "MIT" ]
1
2021-12-21T19:54:12.000Z
2022-03-31T10:54:41.000Z
compute_nads.py
gortizji/linearized-networks
3c271fb0a6c6bdffa9c1aabd8497f8803b725731
[ "MIT" ]
1
2021-12-21T03:33:20.000Z
2021-12-21T03:33:20.000Z
import os import hydra import jax import jax.numpy as jnp from flax.serialization import to_state_dict from omegaconf import DictConfig, OmegaConf from models.jax import get_model from neural_kernels.nads import mixed_derivative_nad_decomposition from utils.misc import get_apply_fn @hydra.main(config_path="config/compute_nads", config_name="config") if __name__ == "__main__": main()
28.326531
90
0.729107
import os import hydra import jax import jax.numpy as jnp from flax.serialization import to_state_dict from omegaconf import DictConfig, OmegaConf from models.jax import get_model from neural_kernels.nads import mixed_derivative_nad_decomposition from utils.misc import get_apply_fn @hydra.main(config_path="config/compute_nads", config_name="config") def main(cfg: DictConfig) -> None: print(OmegaConf.to_yaml(cfg)) # Load model model_key = jax.random.PRNGKey(cfg.seed) model = get_model(**cfg.model) init_variables = model.init(model_key, jnp.zeros(cfg.nads.shape, jnp.float32)) apply_fn = get_apply_fn(model, expose_bn=False, variables=init_variables, train=False) _, init_params = init_variables.pop("params") print("Computing NADs...") # Compute NADs eigvals, nads = mixed_derivative_nad_decomposition(apply_fn, init_params, **cfg.nads) print("Done!") print("Saving results...") # Save results init_variables_state_dict = to_state_dict(init_variables) save_path = f"{hydra.utils.get_original_cwd()}/artifacts/nads/{cfg.model.model_name}" os.makedirs(save_path, exist_ok=True) jnp.save(f"{save_path}/nads.npy", nads) jnp.save(f"{save_path}/eigvals.npy", eigvals) jnp.save( f"{save_path}/init_variables.npy", init_variables_state_dict, ) if __name__ == "__main__": main()
970
0
22
266c07ac3778a39595008765fdd1e0e74d3100ef
329
py
Python
tests/test_rep_intensity.py
JoFrhwld/python-acoustic-similarity
50f71835532010b2fedf14b0ca3a52d88a9ab380
[ "MIT" ]
5
2018-01-15T22:06:20.000Z
2022-02-21T07:02:40.000Z
tests/test_rep_intensity.py
JoFrhwld/python-acoustic-similarity
50f71835532010b2fedf14b0ca3a52d88a9ab380
[ "MIT" ]
null
null
null
tests/test_rep_intensity.py
JoFrhwld/python-acoustic-similarity
50f71835532010b2fedf14b0ca3a52d88a9ab380
[ "MIT" ]
2
2019-11-28T17:06:27.000Z
2019-12-05T22:57:28.000Z
import pytest from acousticsim.representations.intensity import Intensity from numpy.testing import assert_array_almost_equal @pytest.mark.xfail
19.352941
59
0.738602
import pytest from acousticsim.representations.intensity import Intensity from numpy.testing import assert_array_almost_equal @pytest.mark.xfail def test_intensity(base_filenames): for f in base_filenames: wavpath = f+'.wav' intensity = Intensity(wavpath, time_step = 0.01) intensity.process()
155
0
22
96a037cf665d372ee897e3e0fead1ed297bca97f
2,678
py
Python
youtube_video_scraper.py
minimaxir/youtube-video-scraper
a5332f070f4dd27ef54d86b4aef718b9073692aa
[ "MIT" ]
19
2021-05-20T18:47:34.000Z
2022-01-10T11:52:03.000Z
youtube_video_scraper.py
minimaxir/youtube-video-scraper
a5332f070f4dd27ef54d86b4aef718b9073692aa
[ "MIT" ]
null
null
null
youtube_video_scraper.py
minimaxir/youtube-video-scraper
a5332f070f4dd27ef54d86b4aef718b9073692aa
[ "MIT" ]
2
2021-10-09T18:44:55.000Z
2022-01-31T17:56:48.000Z
import yaml import csv import os from tqdm import tqdm import requests import time with open("config.yml", "r", encoding="utf-8") as f: config = yaml.safe_load(f) API_KEY = config["API_KEY"] CHANNELS_API_URL = "https://www.googleapis.com/youtube/v3/channels" PLAYLIST_API_URL = "https://www.googleapis.com/youtube/v3/playlistItems" OUTPUT_FOLDER = config["output_folder"] OUTPUT_FIELDS = ["video_id", "title", "video_published_at"] channel_ids = config["channel_ids"] channels_params = { "key": API_KEY, "part": "contentDetails", } playlist_params = { "key": API_KEY, "part": "snippet", "maxResults": 50, } for channel_id in channel_ids: channels_params.update({"id": channel_id}) r = requests.get( CHANNELS_API_URL, params=channels_params, ).json() # the uploads_id indicates the playlist where a channel's uploads are located uploads_id = r["items"][0]["contentDetails"]["relatedPlaylists"]["uploads"] playlist_params.update({"playlistId": uploads_id}) r = requests.get( PLAYLIST_API_URL, params=playlist_params, ).json() if "items" in r: channel_name = r["items"][0]["snippet"]["channelTitle"] pageToken = r.get("nextPageToken") print(f"Scraping {channel_name}'s videos:") pbar = tqdm(total=r["pageInfo"]["totalResults"]) with open( os.path.join(OUTPUT_FOLDER, f"{channel_name}.csv".replace(os.sep, "_")), "w", encoding="utf-8", ) as f: w = csv.DictWriter(f, fieldnames=OUTPUT_FIELDS) w.writeheader() # process first page we already queried for video in r["items"]: w.writerow(process_video(video["snippet"])) pbar.update(len(r["items"])) # process the rest while pageToken: playlist_params.update({"pageToken": pageToken}) r = requests.get( PLAYLIST_API_URL, params=playlist_params, ).json() for video in r["items"]: w.writerow(process_video(video["snippet"])) pbar.update(len(r["items"])) pageToken = r.get("nextPageToken") time.sleep(0.1) pbar.close() # reset pageToken for new channel playlist_params.update({"pageToken": None})
30.431818
84
0.605302
import yaml import csv import os from tqdm import tqdm import requests import time def process_video(video_snippet): temp_dict = {} temp_dict["video_id"] = video_snippet["resourceId"]["videoId"] temp_dict["title"] = video_snippet["title"] temp_dict["video_published_at"] = video_snippet["publishedAt"] return temp_dict with open("config.yml", "r", encoding="utf-8") as f: config = yaml.safe_load(f) API_KEY = config["API_KEY"] CHANNELS_API_URL = "https://www.googleapis.com/youtube/v3/channels" PLAYLIST_API_URL = "https://www.googleapis.com/youtube/v3/playlistItems" OUTPUT_FOLDER = config["output_folder"] OUTPUT_FIELDS = ["video_id", "title", "video_published_at"] channel_ids = config["channel_ids"] channels_params = { "key": API_KEY, "part": "contentDetails", } playlist_params = { "key": API_KEY, "part": "snippet", "maxResults": 50, } for channel_id in channel_ids: channels_params.update({"id": channel_id}) r = requests.get( CHANNELS_API_URL, params=channels_params, ).json() # the uploads_id indicates the playlist where a channel's uploads are located uploads_id = r["items"][0]["contentDetails"]["relatedPlaylists"]["uploads"] playlist_params.update({"playlistId": uploads_id}) r = requests.get( PLAYLIST_API_URL, params=playlist_params, ).json() if "items" in r: channel_name = r["items"][0]["snippet"]["channelTitle"] pageToken = r.get("nextPageToken") print(f"Scraping {channel_name}'s videos:") pbar = tqdm(total=r["pageInfo"]["totalResults"]) with open( os.path.join(OUTPUT_FOLDER, f"{channel_name}.csv".replace(os.sep, "_")), "w", encoding="utf-8", ) as f: w = csv.DictWriter(f, fieldnames=OUTPUT_FIELDS) w.writeheader() # process first page we already queried for video in r["items"]: w.writerow(process_video(video["snippet"])) pbar.update(len(r["items"])) # process the rest while pageToken: playlist_params.update({"pageToken": pageToken}) r = requests.get( PLAYLIST_API_URL, params=playlist_params, ).json() for video in r["items"]: w.writerow(process_video(video["snippet"])) pbar.update(len(r["items"])) pageToken = r.get("nextPageToken") time.sleep(0.1) pbar.close() # reset pageToken for new channel playlist_params.update({"pageToken": None})
234
0
23
55b870505b10ac77428895ab5e3f4926336db9c8
8,089
py
Python
python/hyperon/__init__.py
trueagi-io/hyperon-experimental
50c2f136fb992880a2ecb104e279bbf9b31c53f1
[ "MIT" ]
6
2021-09-23T13:45:52.000Z
2022-03-16T16:01:18.000Z
python/hyperon/__init__.py
trueagi-io/hyperon-experimental
50c2f136fb992880a2ecb104e279bbf9b31c53f1
[ "MIT" ]
1
2022-03-25T10:46:20.000Z
2022-03-25T10:59:49.000Z
python/hyperon/__init__.py
trueagi-io/hyperon-experimental
50c2f136fb992880a2ecb104e279bbf9b31c53f1
[ "MIT" ]
1
2021-09-22T10:42:58.000Z
2021-09-22T10:42:58.000Z
import hyperonpy as hp from hyperonpy import AtomKind, init_logger
28.283217
93
0.657436
import hyperonpy as hp from hyperonpy import AtomKind, init_logger class Atom: def __init__(self, catom): self.catom = catom def __del__(self): #import sys; sys.stderr.write("Atom._del_(" + str(self) + ")\n"); sys.stderr.flush() hp.atom_free(self.catom) def __eq__(self, other): return (isinstance(other, Atom) and hp.atom_eq(self.catom, other.catom)) def __repr__(self): return hp.atom_to_str(self.catom) def get_type(self): return hp.atom_get_type(self.catom) @staticmethod def _from_catom(catom): type = hp.atom_get_type(catom) if type == AtomKind.SYMBOL: return SymbolAtom(catom) elif type == AtomKind.VARIABLE: return VariableAtom(catom) elif type == AtomKind.EXPR: return ExpressionAtom(catom) elif type == AtomKind.GROUNDED: return GroundedAtom(catom) else: raise Exception("Unexpected type of the atom: " + str(type)) class SymbolAtom(Atom): def __init__(self, catom): super().__init__(catom) def get_name(self): return hp.atom_get_name(self.catom) def S(name): return SymbolAtom(hp.atom_sym(name)) class VariableAtom(Atom): def __init__(self, catom): super().__init__(catom) def get_name(self): return hp.atom_get_name(self.catom) def V(name): return VariableAtom(hp.atom_var(name)) class ExpressionAtom(Atom): def __init__(self, catom): super().__init__(catom) def get_children(self): return [Atom._from_catom(catom) for catom in hp.atom_get_children(self.catom)] def E(*args): return ExpressionAtom(hp.atom_expr([atom.catom for atom in args])) class GroundedAtom(Atom): UNDEFINED_TYPE = S("Undefined") def __init__(self, catom): super().__init__(catom) def get_object(self): return hp.atom_get_object(self.catom) def get_grounded_type(self): return Atom._from_catom(hp.atom_get_grounded_type(self.catom)) def G(object, type=GroundedAtom.UNDEFINED_TYPE): return GroundedAtom(hp.atom_gnd(object, type.catom)) def call_execute_on_grounded_atom(gnd, typ, args): # ... if hp.atom_to_str(typ) == GroundedAtom.UNDEFINED_TYPE res_typ = GroundedAtom.UNDEFINED_TYPE if hp.atom_get_type(typ) != AtomKind.EXPR \ else Atom._from_catom(hp.atom_get_children(typ)[-1]) args = [Atom._from_catom(catom) for catom in args] return gnd.execute(*args, res_typ=res_typ) class ConstGroundedObject: def copy(self): return self class ValueObject(ConstGroundedObject): def __init__(self, value): self.value = value def __eq__(self, other): # TODO: ?typecheck if isinstance(other, ValueObject): return self.value == other.value return False def __repr__(self): return str(self.value) class OperationObject(ConstGroundedObject): def __init__(self, name, op, unwrap=True): self.name = name self.op = op self.unwrap = unwrap def execute(self, *args, res_typ=GroundedAtom.UNDEFINED_TYPE): # type-check? if self.unwrap: args = [arg.get_object().value for arg in args] return [G(ValueObject(self.op(*args)), res_typ)] else: return self.op(*args) def __eq__(self, other): # TODO: instance return isinstance(other, OperationObject) and self.name == other.name def __repr__(self): return self.name def OperationAtom(name, op, type_names=None, unwrap=True): # TODO: nested arrows if type_names is not None: typ = E(S("->"), *[S(n) for n in type_names]) else: typ = S("Undefined") return G(OperationObject(name, op, unwrap), typ) def ValueAtom(value, type_name='Undefined'): return G(ValueObject(value), S(type_name)) class GroundingSpace: def __init__(self, repr_name=None): self.cspace = hp.grounding_space_new() # This name is used only for __repr__ now self.repr_name = repr_name def __del__(self): hp.grounding_space_free(self.cspace) def __eq__(self, other): return (isinstance(other, GroundingSpace) and hp.grounding_space_eq(self.cspace, other.cspace)) def __repr__(self): return super().__repr__() if self.repr_name is None else self.repr_name def add_atom(self, atom): hp.grounding_space_add(self.cspace, atom.catom) def remove_atom(self, atom): return hp.grounding_space_remove(self.cspace, atom.catom) def replace_atom(self, atom, replacement): return hp.grounding_space_replace(self.cspace, atom.catom, replacement.catom) def get_atoms(self): return [Atom._from_catom(hp.grounding_space_get(self.cspace, i)) for i in range(0, hp.grounding_space_len(self.cspace))] def query(self, pattern): result = hp.grounding_space_query(self.cspace, pattern.catom) return [{k: Atom._from_catom(v) for k, v in bindings.items()} for bindings in result] def subst(self, pattern, templ): return [Atom._from_catom(catom) for catom in hp.grounding_space_subst(self.cspace, pattern.catom, templ.catom)] class Tokenizer: def __init__(self): self.ctokenizer = hp.tokenizer_new() def __del__(self): hp.tokenizer_free(self.ctokenizer) def register_token(self, regex, constr): hp.tokenizer_register_token(self.ctokenizer, regex, constr) class SExprParser: def __init__(self, text): self.cparser = hp.CSExprParser(text) def parse(self, tokenizer): catom = self.cparser.parse(tokenizer.ctokenizer) return Atom._from_catom(catom) if catom is not None else None class SExprSpace: def __init__(self): self.cspace = hp.sexpr_space_new() def __del__(self): hp.sexpr_space_free(self.cspace) def register_token(self, regex, constr): hp.sexpr_space_register_token(self.cspace, regex, constr) def add_string(self, text): hp.sexpr_space_add_str(self.cspace, text) def add_to(self, gspace): hp.sexpr_space_into_grounding_space(self.cspace, gspace.cspace) class Interpreter: def __init__(self, gnd_space, expr): self.step_result = hp.interpret_init(gnd_space.cspace, expr.catom) def has_next(self): return hp.step_has_next(self.step_result) def next(self): if not self.has_next(): raise StopIteration() self.step_result = hp.interpret_step(self.step_result) def get_result(self): if self.has_next(): raise RuntimeError("Plan execution is not finished") return hp.step_get_result(self.step_result) def get_step_result(self): return self.step_result def interpret(gnd_space, expr): interpreter = Interpreter(gnd_space, expr) while interpreter.has_next(): interpreter.next() return [Atom._from_catom(catom) for catom in interpreter.get_result()] class AtomType: _UNDEFINED = None @staticmethod def undefined(): if AtomType._UNDEFINED is None: AtomType._UNDEFINED = AtomType(hp.CAtomType.UNDEFINED) return AtomType._UNDEFINED @staticmethod def specific(atom): return AtomType(hp.atom_type_specific(atom.catom)) def __init__(self, ctype): self.ctype = ctype def __del__(self): hp.atom_type_free(self.ctype) # def __eq__(self, other): # return (isinstance(other, AtomType) and # hp.atom_type_eq(self.ctype, other.ctype)) # def __repr__(self): # return hp.atom_type_to_str(self.ctype) # def get_type(self): # return hp.atom_type_get_type(self.ctype) def check_type(gnd_space, atom, type): return hp.check_type(gnd_space.cspace, atom.catom, type.ctype) def validate_atom(gnd_space, expr): return hp.validate_atom(gnd_space.cspace, expr.catom)
5,624
791
1,605
a7ae004d197716589d3b70fcaee6b224af5dd3b6
231
py
Python
workSpace/esp32neopixeltest.py
khutson/macequilt
a4a090ddf296fcea763825fda4243bc84b4d5f0d
[ "MIT" ]
null
null
null
workSpace/esp32neopixeltest.py
khutson/macequilt
a4a090ddf296fcea763825fda4243bc84b4d5f0d
[ "MIT" ]
null
null
null
workSpace/esp32neopixeltest.py
khutson/macequilt
a4a090ddf296fcea763825fda4243bc84b4d5f0d
[ "MIT" ]
null
null
null
from neopixel import NeoPixel import machine import time np = NeoPixel(machine.Pin(4),1) for r in range(255): for g in range(255): for b in range(255): np[0]=((r,g,b)) np.write() time.sleep_ms(10)
15.4
31
0.606061
from neopixel import NeoPixel import machine import time np = NeoPixel(machine.Pin(4),1) for r in range(255): for g in range(255): for b in range(255): np[0]=((r,g,b)) np.write() time.sleep_ms(10)
0
0
0
d895d2119c18fb0dbae41dc21f1ac8211c55d97f
3,016
py
Python
wbia_pie_v2/models/efficientnet.py
dylanirion/wbia-plugin-pie-v2
8ae37c2ad218e5e888bb1aea039f1b04a3fe9d8d
[ "Apache-2.0" ]
null
null
null
wbia_pie_v2/models/efficientnet.py
dylanirion/wbia-plugin-pie-v2
8ae37c2ad218e5e888bb1aea039f1b04a3fe9d8d
[ "Apache-2.0" ]
null
null
null
wbia_pie_v2/models/efficientnet.py
dylanirion/wbia-plugin-pie-v2
8ae37c2ad218e5e888bb1aea039f1b04a3fe9d8d
[ "Apache-2.0" ]
1
2021-04-05T23:46:11.000Z
2021-04-05T23:46:11.000Z
# -*- coding: utf-8 -*- # Written by Olga Moskvyak (olga.moskvyak@hdr.qut.edu.au) import logging import torch.nn as nn from torchvision import models as torchmodels # NOQA from efficientnet_pytorch import EfficientNet logger = logging.getLogger(__name__) NAME_EMBEDDING_SIZE = { 'efficientnet-b0': 1280, 'efficientnet-b1': 1280, 'efficientnet-b2': 1408, 'efficientnet-b3': 1536, 'efficientnet-b4': 1792, 'efficientnet-b5': 2048, 'efficientnet-b6': 2304, 'efficientnet-b7': 2560, } class EfficientNetReid(nn.Module): """Re-id model with EfficientNet as a convolutional feature extractor. Input: core_name (string): name of core model, class from torchvision.models """ def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None): """Constructs fully connected layer Args: fc_dims (list or tuple): dimensions of fc layers, if None, no fc layers are constructed input_dim (int): input dimension dropout_p (float): dropout probability, if None, dropout is unused """ if fc_dims is None: self.feature_dim = input_dim return None assert isinstance( fc_dims, (list, tuple) ), 'fc_dims must be either list or tuple, but got {}'.format(type(fc_dims)) layers = [] for dim in fc_dims: layers.append(nn.Linear(input_dim, dim)) layers.append(nn.BatchNorm1d(dim)) layers.append(nn.ReLU(inplace=True)) if dropout_p is not None: layers.append(nn.Dropout(p=dropout_p)) input_dim = dim self.feature_dim = fc_dims[-1] return nn.Sequential(*layers)
28.72381
99
0.618037
# -*- coding: utf-8 -*- # Written by Olga Moskvyak (olga.moskvyak@hdr.qut.edu.au) import logging import torch.nn as nn from torchvision import models as torchmodels # NOQA from efficientnet_pytorch import EfficientNet logger = logging.getLogger(__name__) NAME_EMBEDDING_SIZE = { 'efficientnet-b0': 1280, 'efficientnet-b1': 1280, 'efficientnet-b2': 1408, 'efficientnet-b3': 1536, 'efficientnet-b4': 1792, 'efficientnet-b5': 2048, 'efficientnet-b6': 2304, 'efficientnet-b7': 2560, } class EfficientNetReid(nn.Module): """Re-id model with EfficientNet as a convolutional feature extractor. Input: core_name (string): name of core model, class from torchvision.models """ def __init__(self, core_name, num_classes, fc_dims, dropout_p, loss): super(EfficientNetReid, self).__init__() self.loss = loss self.core_model = EfficientNet.from_pretrained(core_name) self.global_avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = self._construct_fc_layer( fc_dims, NAME_EMBEDDING_SIZE[core_name], dropout_p ) self.classifier = nn.Linear(self.feature_dim, num_classes) def _construct_fc_layer(self, fc_dims, input_dim, dropout_p=None): """Constructs fully connected layer Args: fc_dims (list or tuple): dimensions of fc layers, if None, no fc layers are constructed input_dim (int): input dimension dropout_p (float): dropout probability, if None, dropout is unused """ if fc_dims is None: self.feature_dim = input_dim return None assert isinstance( fc_dims, (list, tuple) ), 'fc_dims must be either list or tuple, but got {}'.format(type(fc_dims)) layers = [] for dim in fc_dims: layers.append(nn.Linear(input_dim, dim)) layers.append(nn.BatchNorm1d(dim)) layers.append(nn.ReLU(inplace=True)) if dropout_p is not None: layers.append(nn.Dropout(p=dropout_p)) input_dim = dim self.feature_dim = fc_dims[-1] return nn.Sequential(*layers) def featuremaps(self, x): return self.core_model.extract_features(x) def forward(self, x): f = self.featuremaps(x) v = self.global_avgpool(f) v = v.view(v.size(0), -1) if self.fc is not None: v = self.fc(v) if not self.training: return v y = self.classifier(v) if 'softmax' in self.loss: return y elif 'triplet' in self.loss: return y, v else: raise KeyError('Unsupported loss: {}'.format(self.loss)) def efficientnet_b4(num_classes, loss='softmax', pretrained=True, **kwargs): model = EfficientNetReid( core_name='efficientnet-b4', num_classes=num_classes, loss=loss, fc_dims=[512], dropout_p=None, ) return model
1,179
0
104
fa72870226cae55f6adc9d6ec167b5fc30470890
761
py
Python
algorithm/raw_sum.py
hibikisan2018/learn_python
b0f9c82e1823782a59019882cae3523fbf533aa0
[ "BSD-2-Clause" ]
1
2019-05-04T05:23:46.000Z
2019-05-04T05:23:46.000Z
algorithm/raw_sum.py
hibikisan2018/learn_python
b0f9c82e1823782a59019882cae3523fbf533aa0
[ "BSD-2-Clause" ]
null
null
null
algorithm/raw_sum.py
hibikisan2018/learn_python
b0f9c82e1823782a59019882cae3523fbf533aa0
[ "BSD-2-Clause" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Refer to "https://hibiki-press.tech/algorithm/sum_2darray/698" @author: hibikisan """ import random if __name__ == '__main__': dim = (5, 3) # the dimension of original data array data = [] for i in range(dim[0]): data.append([random.randint(0, 10) for n in range(dim[1])]) #print(data) print('----Original data----') for l in data: print(l) sum_data = raw_sum(data) #print(sum_data) print('----Adding the colomn of sum of each raw----') for l in sum_data: print(l)
21.742857
67
0.546649
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Refer to "https://hibiki-press.tech/algorithm/sum_2darray/698" @author: hibikisan """ import random def raw_sum(data): for i in data: sum_ = 0 for j in range(len(i)): sum_ += i[j] i.append(sum_) return data if __name__ == '__main__': dim = (5, 3) # the dimension of original data array data = [] for i in range(dim[0]): data.append([random.randint(0, 10) for n in range(dim[1])]) #print(data) print('----Original data----') for l in data: print(l) sum_data = raw_sum(data) #print(sum_data) print('----Adding the colomn of sum of each raw----') for l in sum_data: print(l)
134
0
23
720b3fa099cbb9647fd56a21b9f9b7329207da00
4,499
py
Python
kmerexpr/plotting.py
bob-carpenter/kmers
769217d2b1af9e118f79ad211940efcc8e2672d1
[ "BSD-3-Clause" ]
1
2021-12-07T14:16:40.000Z
2021-12-07T14:16:40.000Z
kmerexpr/plotting.py
bob-carpenter/kmers
769217d2b1af9e118f79ad211940efcc8e2672d1
[ "BSD-3-Clause" ]
null
null
null
kmerexpr/plotting.py
bob-carpenter/kmers
769217d2b1af9e118f79ad211940efcc8e2672d1
[ "BSD-3-Clause" ]
null
null
null
import matplotlib.pyplot as plt import os import numpy as np
42.046729
128
0.608802
import matplotlib.pyplot as plt import os import numpy as np def plot_scatter(title,xaxis,yaxis, horizontal = False): plt.scatter(xaxis,yaxis , s=0.7, alpha=0.4 ) #theta_opt if horizontal: title = title + "-psi-minus-scatter" plt.plot([0,np.max(xaxis)], [0,0], '--') plt.ylabel(r"$ \psi^{opt} - \psi^{*}$", fontsize=25) else : max_scal = np.max([np.max(xaxis), np.max(yaxis)]) title = title + "-psi-scatter" plt.plot([0,max_scal], [0,max_scal], '--') plt.ylabel(r"$ \psi^{*}$", fontsize=25) plt.xlabel(r"$ \psi^{opt}$", fontsize=25) plt.title(title, fontsize=25) save_path="./figures" plt.savefig(os.path.join(save_path, title + ".pdf"), bbox_inches="tight", pad_inches=0.01) print("Saved plot ", os.path.join(save_path, title + ".pdf")) plt.close() def plot_general(result_dict, title, save_path, threshold=False, yaxislabel=r"$ f(x^k)/f(x^0)$", xaxislabel="Effective Passes", xticks=None, logplot=True, fontsize=30, miny = 10000 ): plt.rc("text", usetex=True) plt.rc("font", family="sans-serif") plt.figure(figsize=(9, 8), dpi=1200) palette = ["#377eb8","#ff7f00","#984ea3","#4daf4a","#e41a1c","brown","green","red",] markers = ["^-",">-","d-","<-","s-","+-","*-","o-","1-","2-","3-","4-","8-",] for algo_name, marker, color in zip(result_dict.keys(), markers, palette): print("plotting: ", algo_name) result = result_dict[algo_name] # result is a 2-d list with different length len_cut = len(min(result, key=len))# cut it with min_len and convert it to numpy array for plot result = np.array(list(map(lambda arr: arr[:len_cut], result))) # plot val_avg = np.mean(result, axis=0) if threshold: len_cut = ( np.argmax(val_avg <= threshold) + 1 if np.sum(val_avg <= threshold) > 0 else len(val_avg) ) val_avg = val_avg[:len_cut] newlength = len(val_avg) val_min = np.min(result, axis=0)[:newlength] val_max = np.max(result, axis=0)[:newlength] # std_result = np.std(result, axis=0)[:newlength] # val_min = np.add(val_avg, -std_result) # val_max = np.add(val_avg, std_result) if xticks is None: xticks_p = np.arange(newlength) else: xticks_p = xticks[:newlength] markevery = 1 if newlength > 20: markevery = int(np.floor(newlength / 15)) if (np.min(val_avg) <= 0 or logplot ==False): # this to detect negative values and prevent an error to be thrown plt.plot(xticks_p, val_avg, marker, markevery=markevery, markersize=12, label=algo_name, lw=3, color=color) else: plt.semilogy(xticks_p, val_avg, marker, markevery=markevery, markersize=12, label=algo_name, lw=3, color=color) plt.fill_between(xticks_p, val_min, val_max, alpha=0.2, color=color) newmincand = np.min(val_min) if miny > newmincand: miny = newmincand plt.ylim(bottom=miny) # (1- (miny/np.abs(miny))*0.1) plt.tick_params(labelsize=20) plt.legend(fontsize=fontsize) plt.xlabel(xaxislabel, fontsize=25) plt.ylabel(yaxislabel, fontsize=25) plt.title(title, fontsize=25) if not os.path.exists(save_path): os.makedirs(save_path) plt.savefig( os.path.join(save_path, title + ".pdf"), bbox_inches="tight", pad_inches=0.01 ) print("Saved plot ", os.path.join(save_path, title + ".pdf")) def plot_iter(result_dict, problem, title, save_path, threshold=False, tol=False, yaxislabel=r"$ f(x^k)/f(x^0)$", fontsize=30): plot_general( result_dict=result_dict, problem=problem, title=title, save_path=save_path, threshold=threshold, tol=tol, yaxislabel=yaxislabel, fontsize=fontsize, ) def plot_error_vs_iterations(dict_results, theta_true, title, model_type): errors_list = [] errors =[] for x in dict_results['xs']: errors.append(np.linalg.norm(x - theta_true, ord =1)) errors_list.append(errors) dict_plot = {} # dict_plot[model_type+"-sampled"] = errors_sam_list dict_plot[model_type] = errors_list plot_general(dict_plot, title=title , save_path="./figures", yaxislabel=r"$\|\theta -\theta^{*} \|$", xticks= dict_results['iteration_counts'], xaxislabel="iterations") plt.close()
4,345
0
92
a7f57df51d5609d8d6a099be39d77ff18d29c83c
20,228
py
Python
src/moca_modules/moca_log.py
el-ideal-ideas/MocaUsersAPI
8acc17d14ad1e3c57142b24a812a1806c44180a5
[ "MIT" ]
6
2020-04-12T08:43:27.000Z
2020-06-03T07:03:19.000Z
src/moca_modules/moca_log.py
el-ideal-ideas/MocaUsersAPI
8acc17d14ad1e3c57142b24a812a1806c44180a5
[ "MIT" ]
null
null
null
src/moca_modules/moca_log.py
el-ideal-ideas/MocaUsersAPI
8acc17d14ad1e3c57142b24a812a1806c44180a5
[ "MIT" ]
1
2020-06-26T18:12:47.000Z
2020-06-26T18:12:47.000Z
# Ω* #             ■          ■■■■■   #             ■         ■■   ■■  #             ■        ■■     ■  #             ■        ■■        #   ■■■■■     ■        ■■■       #  ■■   ■■    ■         ■■■      # ■■     ■■   ■          ■■■■    # ■■     ■■   ■            ■■■■  # ■■■■■■■■■   ■              ■■■ # ■■          ■               ■■ # ■■          ■               ■■ # ■■     ■    ■        ■■     ■■ #  ■■   ■■    ■   ■■■  ■■■   ■■  #   ■■■■■     ■   ■■■    ■■■■■ """ Copyright (c) 2020.5.28 [el.ideal-ideas] This software is released under the MIT License. see LICENSE.txt or following URL. https://www.el-ideal-ideas.com/MocaSystem/LICENSE/ """ # -- Imports -------------------------------------------------------------------------- from typing import * from pathlib import Path from sys import stdout from traceback import format_exc from datetime import datetime, date from .moca_variables import NEW_LINE, tz from .moca_utils import location from .moca_base_class import MocaClassCache, MocaNamedInstance from multiprocessing import current_process from threading import get_ident from aiofiles import open as aio_open from asyncio import get_event_loop # -------------------------------------------------------------------------- Imports -- # -- Variables -------------------------------------------------------------------------- # -------------------------------------------------------------------------- Variables -- # -- LogLevel -------------------------------------------------------------------------- class LogLevel(object): """The logging level for Moca Log Class.""" DEBUG = 0 INFO = 1 WARNING = 2 ERROR = 3 CRITICAL = 4 @classmethod @classmethod # -------------------------------------------------------------------------- LogLevel -- # -- Moca File Log -------------------------------------------------------------------------- class MocaFileLog(MocaClassCache, MocaNamedInstance): """ Write logs to the log file. Attributes ---------- self._filename: Path The file path of the log file. self._exc_filename: Path the file path to save exceptions. self._rotate: bool rotate the log file or not. self._file the file object to write logs. self._exc_file the file object to write exceptions. self._level: int current logging level. self._pid: Optional[int] the process id. self._last_modified: date the last modification date. """ LogLevel = LogLevel def __init__(self, filename: Union[str, Path], exc_filename: Union[str, Path], log_rotate: bool = True): """ :param filename: the file path of the log file. :param exc_filename: the file path to save exceptions. :param log_rotate: rotate the log file automatically. """ MocaClassCache.__init__(self) MocaNamedInstance.__init__(self) # set log rotation flag self._rotate: bool = log_rotate # set file path self._filename: Path = Path(filename) self._exc_filename: Path = Path(exc_filename) # set file object self._file = open(str(self._filename), mode='a', encoding='utf-8') self._exc_file = open(str(self._exc_filename), mode='a', encoding='utf-8') # set log level self._level: int = LogLevel.INFO # set process id self._pid: Optional[int] = current_process().pid # set last modified time self._last_modified: date = datetime.now(tz=tz).date() @property @property @property @property @property @property def start_log_rotate(self) -> None: """Start the auto-rotation""" self._rotate = True def stop_log_rotate(self) -> None: """Stop the auto-rotation""" self._rotate = False def set_log_level(self, level: int) -> None: """Set the log level.""" self._level = level self.save(f"MocaFileLog: Logging level changed to {LogLevel.int_to_str(level)}!", LogLevel.INFO) def save(self, message: str, level: int) -> None: """ Save a log message to the log file. :param message: the log message. :param level: the log level. :return: None Log Format ---------- [loglevel](time)<filename|caller|line number|process id|thread id>message """ if level >= self._level: filename, caller, line = location() current_time = datetime.now(tz=tz) current_date = current_time.date() if self._rotate and (current_date != self._last_modified): self.rotate_log_file() self._last_modified = current_date msg = f"[{LogLevel.int_to_str(level)}]({str(current_time)})" \ f"<{filename}|{caller}|{line}|{self._pid or 0}|{get_ident()}>" \ f"{message}" print(msg, end=NEW_LINE, file=self._file, flush=True) error = format_exc() if not error.startswith('NoneType'): print(error, end='', file=self._exc_file, flush=True) def save_exception(self) -> None: """Save the exception traceback information.""" print(format_exc(), end='', file=self._exc_file, flush=True) def start_dev_mode(self) -> None: """Show all logs on the console.""" file = self._file exc_file = self._exc_file self._file = stdout self._exc_file = stdout file.close() exc_file.close() self.save_cache('log_level', self._level) self._level = LogLevel.DEBUG self.save("MocaFileLog: Development mode started!", LogLevel.INFO) def stop_dev_mode(self) -> None: """Stop development mode.""" self.save("MocaFileLog: Development mode stopped!", LogLevel.INFO) self._level = self.get_cache('log_level') self._file = open(str(self._filename), mode='a', encoding='utf-8') self._exc_file = open(str(self._exc_filename), mode='a', encoding='utf-8') def get_all_logs(self) -> str: """Return today's logs'""" with open(str(self._filename), mode='r', encoding='utf-8') as log_file: return log_file.read() def get_all_logs_as_list(self) -> List[str]: """Return a list of today's logs.""" return self.get_all_logs().splitlines() def get_all_exceptions(self) -> str: """Return today's exceptions'""" with open(str(self._exc_filename), mode='r', encoding='utf-8') as exc_file: return exc_file.read() def clear_logs(self) -> None: """Clear today's logs""" self._file.close() self._exc_file.close() self._filename.unlink() self._exc_filename.unlink() self._file = open(str(self._filename), mode='a', encoding='utf-8') self._exc_file = open(str(self._exc_filename), mode='a', encoding='utf-8') self.save("MocaFileLog: Cleared logs!", LogLevel.INFO) def rotate_log_file(self) -> None: """Rotate the log file.""" self._file.close() self._exc_file.close() time = str(datetime.now(tz=tz).date()) new_filename = self._filename.parent.joinpath( f"{'.'.join(self._filename.name.split('.')[:-1])}-{time}.{self._filename.name.split('.')[-1]}" ) new_exc_filename = self._exc_filename.parent.joinpath( f"{'.'.join(self._exc_filename.name.split('.')[:-1])}-{time}.{self._exc_filename.name.split('.')[-1]}" ) if new_filename.is_file(): new_filename.unlink() if new_exc_filename.is_file(): new_exc_filename.unlink() self._filename.rename(str(new_filename)) self._exc_filename.rename(str(new_exc_filename)) self._file = open(str(self._filename), mode='a', encoding='utf-8') self._exc_file = open(str(self._exc_filename), mode='a', encoding='utf-8') def get_old_logs(self, year: int, month: int, day: int) -> Optional[str]: """Return the old logs as list. If can't found the file, return None.""" old_filename, _ = self._old_filename(year, month, day) if old_filename.is_file(): with open(str(old_filename), mode='r', encoding='utf-8') as log_file: return log_file.read() else: return None def get_old_logs_as_list(self, year: int, month: int, day: int) -> Optional[List[str]]: """Return the old logs. If can't found the file, return None.""" old_logs = self.get_old_logs(year, month, day) if old_logs is None: return None else: return old_logs.splitlines() def get_old_exceptions(self, year: int, month: int, day: int) -> Optional[str]: """Return the old exceptions, If can't found the file, return None.""" _, old_filename = self._old_filename(year, month, day) if old_filename.is_file(): with open(str(old_filename), mode='r', encoding='utf-8') as log_file: return log_file.read() else: return None def _old_filename(self, year: int, month: int, day: int) -> Tuple[Path, Path]: """Return the old filename.""" time = str(datetime(year, month, day).date()) exc_old_filename = self._exc_filename.parent.joinpath( f"{'.'.join(self._exc_filename.name.split('.')[:-1])}-{time}.{self._exc_filename.name.split('.')[-1]}" ) old_filename = self._filename.parent.joinpath( f"{'.'.join(self._filename.name.split('.')[:-1])}-{time}.{self._filename.name.split('.')[-1]}" ) return old_filename, exc_old_filename # -------------------------------------------------------------------------- Moca File Log -- # -- Moca Asynchronous File Log -------------------------------------------------------------------------- class MocaAsyncFileLog(MocaClassCache, MocaNamedInstance): """ Write logs to the log file asynchronously. Attributes ---------- self._filename: Path The file path of the log file. self._exc_filename: Path the file path to save exceptions. self._rotate: bool rotate the log file or not. self._file the file object to write logs. self._exc_file the file object to write exceptions. self._level: int current logging level. self._pid: Optional[int] the process id. self._last_modified: date the last modification date. self._dev_flag: bool the development flag. """ LogLevel = LogLevel def __init__(self, filename: Union[str, Path], exc_filename: Union[str, Path], log_rotate: bool = True): """ :param filename: the file path of the log file. :param exc_filename: the file path to save exceptions. :param log_rotate: rotate the log file automatically. """ MocaClassCache.__init__(self) MocaNamedInstance.__init__(self) # set log rotation flag self._rotate: bool = log_rotate # set file path self._filename: Path = Path(filename) self._exc_filename: Path = Path(exc_filename) # set log level self._level: int = LogLevel.INFO # set process id self._pid: Optional[int] = current_process().pid # set last modified time self._last_modified: date = datetime.now(tz=tz).date() # set development flag self._dev_flag: bool = False # set file object self._file = None self._exc_file = None @property @property @property @property @property @property def start_log_rotate(self) -> None: """Start the auto-rotation""" self._rotate = True def stop_log_rotate(self) -> None: """Stop the auto-rotation""" self._rotate = False async def set_log_level(self, level: int) -> None: """Set the log level.""" self._level = level await self.save(f"MocaAsyncFileLog: Logging level changed to {LogLevel.int_to_str(level)}!", LogLevel.INFO) async def save(self, message: str, level: int) -> None: """ Save a log message to the log file. :param message: the log message. :param level: the log level. :return: None Log Format ---------- [loglevel](time)<filename|caller|line number|process id|thread id>message """ if level >= self._level: filename, caller, line = location() current_time = datetime.now(tz=tz) current_date = current_time.date() if self._rotate and (current_date != self._last_modified): await self.rotate_log_file() self._last_modified = current_date msg = f"[{LogLevel.int_to_str(level)}]({str(current_time)})" \ f"<{filename}|{caller}|{line}|{self._pid or 0}|{get_ident()}>" \ f"{message}" if self._dev_flag: print(msg, end=NEW_LINE) else: await self._file.write(msg) await self._file.write(NEW_LINE) await self._file.flush() error = format_exc() if not error.startswith('NoneType'): if self._dev_flag: print(error, end='') else: await self._exc_file.write(error) await self._exc_file.flush() async def save_exception(self) -> None: """Save the exception traceback information.""" if self._dev_flag: print(format_exc(), end='') else: await self._exc_file.write(format_exc()) await self._exc_file.flush() async def start_dev_mode(self) -> None: """Show all logs on the console.""" self.save_cache('log_level', self._level) self._level = LogLevel.DEBUG self._dev_flag = True await self.save("MocaAsyncFileLog: Development mode started!", LogLevel.INFO) async def stop_dev_mode(self) -> None: """Stop development mode.""" self._dev_flag = False await self.save("MocaAsyncFileLog: Development mode stopped!", LogLevel.INFO) self._level = self.get_cache('log_level') async def get_all_logs(self) -> str: """Return today's logs'""" async with aio_open(str(self._filename), mode='r', encoding='utf-8') as log_file: return await log_file.read() async def get_all_logs_as_list(self) -> List[str]: """Return a list of today's logs.""" logs = await self.get_all_logs() return logs.splitlines() async def get_all_exceptions(self) -> str: """Return today's exceptions'""" async with aio_open(str(self._exc_filename), mode='r', encoding='utf-8') as exc_file: return await exc_file.read() async def clear_logs(self) -> None: """Clear today's logs""" await self._file.close() await self._exc_file.close() self._filename.unlink() self._exc_filename.unlink() await self._init() await self.save("MocaAsyncFileLog: Cleared logs!", LogLevel.INFO) async def rotate_log_file(self) -> None: """Rotate the log file.""" await self._file.close() await self._exc_file.close() time = str(datetime.now(tz=tz).date()) new_filename = self._filename.parent.joinpath( f"{'.'.join(self._filename.name.split('.')[:-1])}-{time}.{self._filename.name.split('.')[-1]}" ) new_exc_filename = self._exc_filename.parent.joinpath( f"{'.'.join(self._exc_filename.name.split('.')[:-1])}-{time}.{self._exc_filename.name.split('.')[-1]}" ) if new_filename.is_file(): new_filename.unlink() if new_exc_filename.is_file(): new_exc_filename.unlink() self._filename.rename(str(new_filename)) self._exc_filename.rename(str(new_exc_filename)) await self._init() async def get_old_logs(self, year: int, month: int, day: int) -> Optional[str]: """Return the old logs as list. If can't found the file, return None.""" old_filename, _ = self._old_filename(year, month, day) if old_filename.is_file(): async with aio_open(str(old_filename), mode='r', encoding='utf-8') as log_file: return await log_file.read() else: return None async def get_old_logs_as_list(self, year: int, month: int, day: int) -> Optional[List[str]]: """Return the old logs. If can't found the file, return None.""" old_logs = await self.get_old_logs(year, month, day) if old_logs is None: return None else: return old_logs.splitlines() async def get_old_exceptions(self, year: int, month: int, day: int) -> Optional[str]: """Return the old exceptions, If can't found the file, return None.""" _, old_filename = self._old_filename(year, month, day) if old_filename.is_file(): async with aio_open(str(old_filename), mode='r', encoding='utf-8') as log_file: return await log_file.read() else: return None def _old_filename(self, year: int, month: int, day: int) -> Tuple[Path, Path]: """Return the old filename.""" time = str(datetime(year, month, day).date()) exc_old_filename = self._exc_filename.parent.joinpath( f"{'.'.join(self._exc_filename.name.split('.')[:-1])}-{time}.{self._exc_filename.name.split('.')[-1]}" ) old_filename = self._filename.parent.joinpath( f"{'.'.join(self._filename.name.split('.')[:-1])}-{time}.{self._filename.name.split('.')[-1]}" ) return old_filename, exc_old_filename # -------------------------------------------------------------------------- Moca Asynchronous File Log --
36.121429
115
0.562636
# Ω* #             ■          ■■■■■   #             ■         ■■   ■■  #             ■        ■■     ■  #             ■        ■■        #   ■■■■■     ■        ■■■       #  ■■   ■■    ■         ■■■      # ■■     ■■   ■          ■■■■    # ■■     ■■   ■            ■■■■  # ■■■■■■■■■   ■              ■■■ # ■■          ■               ■■ # ■■          ■               ■■ # ■■     ■    ■        ■■     ■■ #  ■■   ■■    ■   ■■■  ■■■   ■■  #   ■■■■■     ■   ■■■    ■■■■■ """ Copyright (c) 2020.5.28 [el.ideal-ideas] This software is released under the MIT License. see LICENSE.txt or following URL. https://www.el-ideal-ideas.com/MocaSystem/LICENSE/ """ # -- Imports -------------------------------------------------------------------------- from typing import * from pathlib import Path from sys import stdout from traceback import format_exc from datetime import datetime, date from .moca_variables import NEW_LINE, tz from .moca_utils import location from .moca_base_class import MocaClassCache, MocaNamedInstance from multiprocessing import current_process from threading import get_ident from aiofiles import open as aio_open from asyncio import get_event_loop # -------------------------------------------------------------------------- Imports -- # -- Variables -------------------------------------------------------------------------- # -------------------------------------------------------------------------- Variables -- # -- LogLevel -------------------------------------------------------------------------- class LogLevel(object): """The logging level for Moca Log Class.""" DEBUG = 0 INFO = 1 WARNING = 2 ERROR = 3 CRITICAL = 4 @classmethod def int_to_str(cls, integer: int) -> str: if integer == 0: return 'DEBUG' elif integer == 1: return 'INFO' elif integer == 2: return 'WARNING' elif integer == 3: return 'ERROR' elif integer == 4: return 'CRITICAL' else: raise ValueError('Invalid integer value, only 0, 1, 2, 3, 4') @classmethod def str_to_int(cls, string: str) -> int: if string == 'DEBUG': return 0 elif string == 'INFO': return 1 elif string == 'WARNING': return 2 elif string == 'ERROR': return 3 elif string == 'CRITICAL': return 4 else: raise ValueError('Invalid string value, only DEBUG, INFO, WARNING, ERROR, CRITICAL') # -------------------------------------------------------------------------- LogLevel -- # -- Moca File Log -------------------------------------------------------------------------- class MocaFileLog(MocaClassCache, MocaNamedInstance): """ Write logs to the log file. Attributes ---------- self._filename: Path The file path of the log file. self._exc_filename: Path the file path to save exceptions. self._rotate: bool rotate the log file or not. self._file the file object to write logs. self._exc_file the file object to write exceptions. self._level: int current logging level. self._pid: Optional[int] the process id. self._last_modified: date the last modification date. """ LogLevel = LogLevel def __init__(self, filename: Union[str, Path], exc_filename: Union[str, Path], log_rotate: bool = True): """ :param filename: the file path of the log file. :param exc_filename: the file path to save exceptions. :param log_rotate: rotate the log file automatically. """ MocaClassCache.__init__(self) MocaNamedInstance.__init__(self) # set log rotation flag self._rotate: bool = log_rotate # set file path self._filename: Path = Path(filename) self._exc_filename: Path = Path(exc_filename) # set file object self._file = open(str(self._filename), mode='a', encoding='utf-8') self._exc_file = open(str(self._exc_filename), mode='a', encoding='utf-8') # set log level self._level: int = LogLevel.INFO # set process id self._pid: Optional[int] = current_process().pid # set last modified time self._last_modified: date = datetime.now(tz=tz).date() def __del__(self): self._file.close() self._exc_file.close() def __str__(self) -> str: return f"MocaFileLog: {self._filename}" @property def filename(self) -> Path: return self._filename @property def exc_filename(self) -> Path: return self._exc_filename @property def log_rotate(self) -> bool: return self._rotate @property def file(self): return self._file @property def exc_file(self): return self._exc_file @property def level(self) -> int: return self._level def start_log_rotate(self) -> None: """Start the auto-rotation""" self._rotate = True def stop_log_rotate(self) -> None: """Stop the auto-rotation""" self._rotate = False def set_log_level(self, level: int) -> None: """Set the log level.""" self._level = level self.save(f"MocaFileLog: Logging level changed to {LogLevel.int_to_str(level)}!", LogLevel.INFO) def save(self, message: str, level: int) -> None: """ Save a log message to the log file. :param message: the log message. :param level: the log level. :return: None Log Format ---------- [loglevel](time)<filename|caller|line number|process id|thread id>message """ if level >= self._level: filename, caller, line = location() current_time = datetime.now(tz=tz) current_date = current_time.date() if self._rotate and (current_date != self._last_modified): self.rotate_log_file() self._last_modified = current_date msg = f"[{LogLevel.int_to_str(level)}]({str(current_time)})" \ f"<{filename}|{caller}|{line}|{self._pid or 0}|{get_ident()}>" \ f"{message}" print(msg, end=NEW_LINE, file=self._file, flush=True) error = format_exc() if not error.startswith('NoneType'): print(error, end='', file=self._exc_file, flush=True) def save_exception(self) -> None: """Save the exception traceback information.""" print(format_exc(), end='', file=self._exc_file, flush=True) def start_dev_mode(self) -> None: """Show all logs on the console.""" file = self._file exc_file = self._exc_file self._file = stdout self._exc_file = stdout file.close() exc_file.close() self.save_cache('log_level', self._level) self._level = LogLevel.DEBUG self.save("MocaFileLog: Development mode started!", LogLevel.INFO) def stop_dev_mode(self) -> None: """Stop development mode.""" self.save("MocaFileLog: Development mode stopped!", LogLevel.INFO) self._level = self.get_cache('log_level') self._file = open(str(self._filename), mode='a', encoding='utf-8') self._exc_file = open(str(self._exc_filename), mode='a', encoding='utf-8') def get_all_logs(self) -> str: """Return today's logs'""" with open(str(self._filename), mode='r', encoding='utf-8') as log_file: return log_file.read() def get_all_logs_as_list(self) -> List[str]: """Return a list of today's logs.""" return self.get_all_logs().splitlines() def get_all_exceptions(self) -> str: """Return today's exceptions'""" with open(str(self._exc_filename), mode='r', encoding='utf-8') as exc_file: return exc_file.read() def clear_logs(self) -> None: """Clear today's logs""" self._file.close() self._exc_file.close() self._filename.unlink() self._exc_filename.unlink() self._file = open(str(self._filename), mode='a', encoding='utf-8') self._exc_file = open(str(self._exc_filename), mode='a', encoding='utf-8') self.save("MocaFileLog: Cleared logs!", LogLevel.INFO) def rotate_log_file(self) -> None: """Rotate the log file.""" self._file.close() self._exc_file.close() time = str(datetime.now(tz=tz).date()) new_filename = self._filename.parent.joinpath( f"{'.'.join(self._filename.name.split('.')[:-1])}-{time}.{self._filename.name.split('.')[-1]}" ) new_exc_filename = self._exc_filename.parent.joinpath( f"{'.'.join(self._exc_filename.name.split('.')[:-1])}-{time}.{self._exc_filename.name.split('.')[-1]}" ) if new_filename.is_file(): new_filename.unlink() if new_exc_filename.is_file(): new_exc_filename.unlink() self._filename.rename(str(new_filename)) self._exc_filename.rename(str(new_exc_filename)) self._file = open(str(self._filename), mode='a', encoding='utf-8') self._exc_file = open(str(self._exc_filename), mode='a', encoding='utf-8') def get_old_logs(self, year: int, month: int, day: int) -> Optional[str]: """Return the old logs as list. If can't found the file, return None.""" old_filename, _ = self._old_filename(year, month, day) if old_filename.is_file(): with open(str(old_filename), mode='r', encoding='utf-8') as log_file: return log_file.read() else: return None def get_old_logs_as_list(self, year: int, month: int, day: int) -> Optional[List[str]]: """Return the old logs. If can't found the file, return None.""" old_logs = self.get_old_logs(year, month, day) if old_logs is None: return None else: return old_logs.splitlines() def get_old_exceptions(self, year: int, month: int, day: int) -> Optional[str]: """Return the old exceptions, If can't found the file, return None.""" _, old_filename = self._old_filename(year, month, day) if old_filename.is_file(): with open(str(old_filename), mode='r', encoding='utf-8') as log_file: return log_file.read() else: return None def _old_filename(self, year: int, month: int, day: int) -> Tuple[Path, Path]: """Return the old filename.""" time = str(datetime(year, month, day).date()) exc_old_filename = self._exc_filename.parent.joinpath( f"{'.'.join(self._exc_filename.name.split('.')[:-1])}-{time}.{self._exc_filename.name.split('.')[-1]}" ) old_filename = self._filename.parent.joinpath( f"{'.'.join(self._filename.name.split('.')[:-1])}-{time}.{self._filename.name.split('.')[-1]}" ) return old_filename, exc_old_filename # -------------------------------------------------------------------------- Moca File Log -- # -- Moca Asynchronous File Log -------------------------------------------------------------------------- class MocaAsyncFileLog(MocaClassCache, MocaNamedInstance): """ Write logs to the log file asynchronously. Attributes ---------- self._filename: Path The file path of the log file. self._exc_filename: Path the file path to save exceptions. self._rotate: bool rotate the log file or not. self._file the file object to write logs. self._exc_file the file object to write exceptions. self._level: int current logging level. self._pid: Optional[int] the process id. self._last_modified: date the last modification date. self._dev_flag: bool the development flag. """ LogLevel = LogLevel def __init__(self, filename: Union[str, Path], exc_filename: Union[str, Path], log_rotate: bool = True): """ :param filename: the file path of the log file. :param exc_filename: the file path to save exceptions. :param log_rotate: rotate the log file automatically. """ MocaClassCache.__init__(self) MocaNamedInstance.__init__(self) # set log rotation flag self._rotate: bool = log_rotate # set file path self._filename: Path = Path(filename) self._exc_filename: Path = Path(exc_filename) # set log level self._level: int = LogLevel.INFO # set process id self._pid: Optional[int] = current_process().pid # set last modified time self._last_modified: date = datetime.now(tz=tz).date() # set development flag self._dev_flag: bool = False # set file object self._file = None self._exc_file = None async def init(self): self._file = await aio_open(str(self._filename), mode='a', encoding='utf-8') self._exc_file = await aio_open(str(self._exc_filename), mode='a', encoding='utf-8') def __del__(self): get_event_loop().run_until_complete(self._del()) async def _del(self): await self._file.close() await self._exc_file.close() def __str__(self) -> str: return f"MocaAsyncFileLog: {self._filename}" @property def filename(self) -> Path: return self._filename @property def exc_filename(self) -> Path: return self._exc_filename @property def log_rotate(self) -> bool: return self._rotate @property def file(self): return self._file @property def exc_file(self): return self._exc_file @property def level(self) -> int: return self._level def start_log_rotate(self) -> None: """Start the auto-rotation""" self._rotate = True def stop_log_rotate(self) -> None: """Stop the auto-rotation""" self._rotate = False async def set_log_level(self, level: int) -> None: """Set the log level.""" self._level = level await self.save(f"MocaAsyncFileLog: Logging level changed to {LogLevel.int_to_str(level)}!", LogLevel.INFO) async def save(self, message: str, level: int) -> None: """ Save a log message to the log file. :param message: the log message. :param level: the log level. :return: None Log Format ---------- [loglevel](time)<filename|caller|line number|process id|thread id>message """ if level >= self._level: filename, caller, line = location() current_time = datetime.now(tz=tz) current_date = current_time.date() if self._rotate and (current_date != self._last_modified): await self.rotate_log_file() self._last_modified = current_date msg = f"[{LogLevel.int_to_str(level)}]({str(current_time)})" \ f"<{filename}|{caller}|{line}|{self._pid or 0}|{get_ident()}>" \ f"{message}" if self._dev_flag: print(msg, end=NEW_LINE) else: await self._file.write(msg) await self._file.write(NEW_LINE) await self._file.flush() error = format_exc() if not error.startswith('NoneType'): if self._dev_flag: print(error, end='') else: await self._exc_file.write(error) await self._exc_file.flush() async def save_exception(self) -> None: """Save the exception traceback information.""" if self._dev_flag: print(format_exc(), end='') else: await self._exc_file.write(format_exc()) await self._exc_file.flush() async def start_dev_mode(self) -> None: """Show all logs on the console.""" self.save_cache('log_level', self._level) self._level = LogLevel.DEBUG self._dev_flag = True await self.save("MocaAsyncFileLog: Development mode started!", LogLevel.INFO) async def stop_dev_mode(self) -> None: """Stop development mode.""" self._dev_flag = False await self.save("MocaAsyncFileLog: Development mode stopped!", LogLevel.INFO) self._level = self.get_cache('log_level') async def get_all_logs(self) -> str: """Return today's logs'""" async with aio_open(str(self._filename), mode='r', encoding='utf-8') as log_file: return await log_file.read() async def get_all_logs_as_list(self) -> List[str]: """Return a list of today's logs.""" logs = await self.get_all_logs() return logs.splitlines() async def get_all_exceptions(self) -> str: """Return today's exceptions'""" async with aio_open(str(self._exc_filename), mode='r', encoding='utf-8') as exc_file: return await exc_file.read() async def clear_logs(self) -> None: """Clear today's logs""" await self._file.close() await self._exc_file.close() self._filename.unlink() self._exc_filename.unlink() await self._init() await self.save("MocaAsyncFileLog: Cleared logs!", LogLevel.INFO) async def rotate_log_file(self) -> None: """Rotate the log file.""" await self._file.close() await self._exc_file.close() time = str(datetime.now(tz=tz).date()) new_filename = self._filename.parent.joinpath( f"{'.'.join(self._filename.name.split('.')[:-1])}-{time}.{self._filename.name.split('.')[-1]}" ) new_exc_filename = self._exc_filename.parent.joinpath( f"{'.'.join(self._exc_filename.name.split('.')[:-1])}-{time}.{self._exc_filename.name.split('.')[-1]}" ) if new_filename.is_file(): new_filename.unlink() if new_exc_filename.is_file(): new_exc_filename.unlink() self._filename.rename(str(new_filename)) self._exc_filename.rename(str(new_exc_filename)) await self._init() async def get_old_logs(self, year: int, month: int, day: int) -> Optional[str]: """Return the old logs as list. If can't found the file, return None.""" old_filename, _ = self._old_filename(year, month, day) if old_filename.is_file(): async with aio_open(str(old_filename), mode='r', encoding='utf-8') as log_file: return await log_file.read() else: return None async def get_old_logs_as_list(self, year: int, month: int, day: int) -> Optional[List[str]]: """Return the old logs. If can't found the file, return None.""" old_logs = await self.get_old_logs(year, month, day) if old_logs is None: return None else: return old_logs.splitlines() async def get_old_exceptions(self, year: int, month: int, day: int) -> Optional[str]: """Return the old exceptions, If can't found the file, return None.""" _, old_filename = self._old_filename(year, month, day) if old_filename.is_file(): async with aio_open(str(old_filename), mode='r', encoding='utf-8') as log_file: return await log_file.read() else: return None def _old_filename(self, year: int, month: int, day: int) -> Tuple[Path, Path]: """Return the old filename.""" time = str(datetime(year, month, day).date()) exc_old_filename = self._exc_filename.parent.joinpath( f"{'.'.join(self._exc_filename.name.split('.')[:-1])}-{time}.{self._exc_filename.name.split('.')[-1]}" ) old_filename = self._filename.parent.joinpath( f"{'.'.join(self._filename.name.split('.')[:-1])}-{time}.{self._filename.name.split('.')[-1]}" ) return old_filename, exc_old_filename # -------------------------------------------------------------------------- Moca Asynchronous File Log --
1,629
0
526
4b507bf64e3654ff7c0698713e9656acd7b4e1f7
334
py
Python
code_test.py
twhughes/Finite-Difference-Frequency-Domain
e97739a40860305259ee7f53a052174a2697df0d
[ "MIT" ]
1
2019-11-10T05:17:39.000Z
2019-11-10T05:17:39.000Z
code_test.py
twhughes/Finite-Difference-Frequency-Domain
e97739a40860305259ee7f53a052174a2697df0d
[ "MIT" ]
null
null
null
code_test.py
twhughes/Finite-Difference-Frequency-Domain
e97739a40860305259ee7f53a052174a2697df0d
[ "MIT" ]
null
null
null
from NN import NN import numpy as np import matplotlib.pylab as plt layer_sizes = [2,4,1] activations = ['relu','sigmoid'] N = NN(layer_sizes,activations) #print(N.biases[4].shape) input = np.array([[1,2,3],[3,5,4]]) N.forward_prop(input) N.back_prop(np.array([[1,2,3]])) N.derivative_check(m=6,verbose=False) N.update_weights()
18.555556
37
0.706587
from NN import NN import numpy as np import matplotlib.pylab as plt layer_sizes = [2,4,1] activations = ['relu','sigmoid'] N = NN(layer_sizes,activations) #print(N.biases[4].shape) input = np.array([[1,2,3],[3,5,4]]) N.forward_prop(input) N.back_prop(np.array([[1,2,3]])) N.derivative_check(m=6,verbose=False) N.update_weights()
0
0
0
5c9099258ebfac3b326d362040bc65799a6dc51a
447
py
Python
src/classes/structures/__init__.py
ogoes/compiler-improvement
dbed16b88ed43630480daf6fffda69805d9cb807
[ "MIT" ]
null
null
null
src/classes/structures/__init__.py
ogoes/compiler-improvement
dbed16b88ed43630480daf6fffda69805d9cb807
[ "MIT" ]
null
null
null
src/classes/structures/__init__.py
ogoes/compiler-improvement
dbed16b88ed43630480daf6fffda69805d9cb807
[ "MIT" ]
null
null
null
from classes.structures.Atribuicao import Atribuicao from classes.structures.Cabecalho import Cabecalho from classes.structures.Escreva import Escreva from classes.structures.Indice import Indice from classes.structures.InicializacaoDeVariaveis import InicializacaoDeVariaveis from classes.structures.Leia import Leia from classes.structures.Repita import Repita from classes.structures.Retorna import Retorna from classes.structures.Se import Se
44.7
80
0.879195
from classes.structures.Atribuicao import Atribuicao from classes.structures.Cabecalho import Cabecalho from classes.structures.Escreva import Escreva from classes.structures.Indice import Indice from classes.structures.InicializacaoDeVariaveis import InicializacaoDeVariaveis from classes.structures.Leia import Leia from classes.structures.Repita import Repita from classes.structures.Retorna import Retorna from classes.structures.Se import Se
0
0
0
e369600bb8c77456462727ac300a097d3fd556bc
25,316
py
Python
atlas/lib/idds/atlas/workflow/atlaspandawork.py
wguanicedew/iDDS
ff3e8eadda3c7a7f8c87f0e68e06dbe02b7278e5
[ "Apache-2.0" ]
null
null
null
atlas/lib/idds/atlas/workflow/atlaspandawork.py
wguanicedew/iDDS
ff3e8eadda3c7a7f8c87f0e68e06dbe02b7278e5
[ "Apache-2.0" ]
null
null
null
atlas/lib/idds/atlas/workflow/atlaspandawork.py
wguanicedew/iDDS
ff3e8eadda3c7a7f8c87f0e68e06dbe02b7278e5
[ "Apache-2.0" ]
1
2020-05-27T13:04:38.000Z
2020-05-27T13:04:38.000Z
#!/usr/bin/env python # # 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.0OA # # Authors: # - Wen Guan, <wen.guan@cern.ch>, 2020 - 2021 try: import ConfigParser except ImportError: import configparser as ConfigParser # try: # from urllib import quote # except ImportError: # from urllib.parse import quote import copy import os import re import traceback from idds.common import exceptions from idds.common.constants import (TransformType, CollectionType, CollectionStatus, ProcessingStatus, WorkStatus, ContentStatus) from idds.workflow.work import Work, Processing from idds.workflow.workflow import Condition
49.252918
1,843
0.60918
#!/usr/bin/env python # # 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.0OA # # Authors: # - Wen Guan, <wen.guan@cern.ch>, 2020 - 2021 try: import ConfigParser except ImportError: import configparser as ConfigParser # try: # from urllib import quote # except ImportError: # from urllib.parse import quote import copy import os import re import traceback from idds.common import exceptions from idds.common.constants import (TransformType, CollectionType, CollectionStatus, ProcessingStatus, WorkStatus, ContentStatus) from idds.workflow.work import Work, Processing from idds.workflow.workflow import Condition class PandaCondition(Condition): def __init__(self, cond=None, current_work=None, true_work=None, false_work=None): super(PandaCondition, self).__init__(cond=cond, current_work=current_work, true_work=true_work, false_work=false_work) class ATLASPandaWork(Work): def __init__(self, executable=None, arguments=None, parameters=None, setup=None, work_tag='activelearning', exec_type='panda', sandbox=None, work_id=None, primary_input_collection=None, other_input_collections=None, output_collections=None, log_collections=None, logger=None, dependency_map=None, task_name="", panda_task_paramsmap=None): """ Init a work/task/transformation. :param setup: A string to setup the executable enviroment, it can be None. :param executable: The executable. :param arguments: The arguments. :param parameters: A dict with arguments needed to be replaced. :param work_type: The work type like data carousel, hyperparameteroptimization and so on. :param exec_type: The exec type like 'local', 'remote'(with remote_package set), 'docker' and so on. :param sandbox: The sandbox. :param work_id: The work/task id. :param primary_input_collection: The primary input collection. :param other_input_collections: List of the input collections. :param output_collections: List of the output collections. # :param workflow: The workflow the current work belongs to. """ # self.cmd_to_arguments = cmd_to_arguments self.panda_task_paramsmap = panda_task_paramsmap self.output_dataset_name = None super(ATLASPandaWork, self).__init__(executable=executable, arguments=arguments, parameters=parameters, setup=setup, work_type=TransformType.Processing, work_tag=work_tag, exec_type=exec_type, sandbox=sandbox, work_id=work_id, primary_input_collection=primary_input_collection, other_input_collections=other_input_collections, output_collections=output_collections, log_collections=log_collections, logger=logger) self.panda_url = None self.panda_url_ssl = None self.panda_monitor = None self.load_panda_urls() # from pandatools import Client # Client.getTaskParamsMap(23752996) # (0, '{"buildSpec": {"jobParameters": "-i ${IN} -o ${OUT} --sourceURL ${SURL} -r . ", "archiveName": "sources.0ca6a2fb-4ad0-42d0-979d-aa7c284f1ff7.tar.gz", "prodSourceLabel": "panda"}, "sourceURL": "https://aipanda048.cern.ch:25443", "cliParams": "prun --exec \\"python simplescript.py 0.5 0.5 200 output.json\\" --outDS user.wguan.altest1234 --outputs output.json --nJobs=10", "site": null, "vo": "atlas", "respectSplitRule": true, "osInfo": "Linux-3.10.0-1127.19.1.el7.x86_64-x86_64-with-centos-7.9.2009-Core", "log": {"type": "template", "param_type": "log", "container": "user.wguan.altest1234.log/", "value": "user.wguan.altest1234.log.$JEDITASKID.${SN}.log.tgz", "dataset": "user.wguan.altest1234.log/"}, "transUses": "", "excludedSite": [], "nMaxFilesPerJob": 200, "uniqueTaskName": true, "noInput": true, "taskName": "user.wguan.altest1234/", "transHome": null, "includedSite": null, "nEvents": 10, "nEventsPerJob": 1, "jobParameters": [{"type": "constant", "value": "-j \\"\\" --sourceURL ${SURL}"}, {"type": "constant", "value": "-r ."}, {"padding": false, "type": "constant", "value": "-p \\""}, {"padding": false, "type": "constant", "value": "python%20simplescript.py%200.5%200.5%20200%20output.json"}, {"type": "constant", "value": "\\""}, {"type": "constant", "value": "-l ${LIB}"}, {"container": "user.wguan.altest1234_output.json/", "value": "user.wguan.$JEDITASKID._${SN/P}.output.json", "dataset": "user.wguan.altest1234_output.json/", "param_type": "output", "hidden": true, "type": "template"}, {"type": "constant", "value": "-o \\"{\'output.json\': \'user.wguan.$JEDITASKID._${SN/P}.output.json\'}\\""}], "prodSourceLabel": "user", "processingType": "panda-client-1.4.47-jedi-run", "architecture": "@centos7", "userName": "Wen Guan", "taskType": "anal", "taskPriority": 1000, "countryGroup": "us"}') # noqa E501 self.panda_task_id = None self.init_panda_task_info() def initialize_work(self): if not self.is_initialized(): self.init_new_panda_task_info() super(ATLASPandaWork, self).initialize_work() def get_scope_name(self, dataset): if dataset.startswith("user"): scope = "user." + dataset.split('.')[1] elif dataset.startswith("group"): scope = "group." + dataset.split('.')[1] else: scope = dataset.split('.')[0] return scope def get_output_dataset_name_from_task_paramsmap(self): if self.panda_task_paramsmap: cliParams = self.panda_task_paramsmap['cliParams'] output_dataset_name = cliParams.split("--outDS")[1].strip().split(" ")[0] return output_dataset_name return None def init_panda_task_info(self): if self.panda_task_paramsmap: self.output_dataset_name = self.get_output_dataset_name_from_task_paramsmap() self.sandbox = os.path.join(self.panda_task_paramsmap['sourceURL'], 'cache/' + self.panda_task_paramsmap['buildSpec']['archiveName']) for p in self.panda_task_paramsmap["jobParameters"]: if 'param_type' in p and p['param_type'] == 'output': output_dataset = p['dataset'] output_dataset = output_dataset.replace("/", "") scope = self.get_scope_name(output_dataset) primary_input_collection = {'scope': scope, 'name': output_dataset} output_collection = {'scope': scope, 'name': output_dataset} self.set_primary_input_collection(primary_input_collection) self.add_output_collections([output_collection]) if 'log' in p: log_dataset = p['dataset'] log_dataset = log_dataset.replace("/", "") scope = self.get_scope_name(log_dataset) log_collection = {'scope': scope, 'name': log_dataset} self.add_log_collections([log_collection]) def init_new_panda_task_info(self): if not self.panda_task_paramsmap: return # generate new dataset name # self.padding = self.sequence_in_workflow new_dataset_name = self.output_dataset_name + "_" + str(self.sequence_id) for coll_id in self.collections: coll = self.collections[coll_id] coll['name'] = coll['name'].replace(self.output_dataset_name, new_dataset_name) self.panda_task_paramsmap['cliParams'] = \ self.panda_task_paramsmap['cliParams'].replace(self.output_dataset_name, new_dataset_name) self.panda_task_paramsmap['taskName'] = \ self.panda_task_paramsmap['taskName'].replace(self.output_dataset_name, new_dataset_name) jobParameters = self.panda_task_paramsmap['jobParameters'] for p in jobParameters: if 'container' in p: p['container'] = p['container'].replace(self.output_dataset_name, new_dataset_name) if 'dataset' in p: p['dataset'] = p['dataset'].replace(self.output_dataset_name, new_dataset_name) log = self.panda_task_paramsmap['log'] if 'value' in log: log['value'] = log['value'].replace(self.output_dataset_name, new_dataset_name) if 'container' in log: log['container'] = log['container'].replace(self.output_dataset_name, new_dataset_name) if 'dataset' in log: log['dataset'] = log['dataset'].replace(self.output_dataset_name, new_dataset_name) self.parse_arguments() def parse_arguments(self): try: # arguments = self.get_arguments() # parameters = self.get_parameters() new_parameters = self.get_parameters() if new_parameters: self.panda_task_paramsmap['cliParams'] = self.panda_task_paramsmap['cliParams'].format(**new_parameters) # todo # jobParameters = self.panda_task_paramsmap['jobParameters'] # for p in jobParameters: # if 'value' in p: # p['value'] = p['value'].replace(quote(arguments), quote(new_arguments)) # return new_arguments except Exception as ex: self.add_errors(str(ex)) def generate_work_from_template(self): new_work = super(ATLASPandaWork, self).generate_work_from_template() # new_work.unset_initialized() # new_work.panda_task_id = None return new_work def set_parameters(self, parameters): self.parameters = parameters # trigger to submit new tasks self.unset_initialized() self.panda_task_id = None def my_condition(self): if self.is_finished(): return True return False def load_panda_config(self): panda_config = ConfigParser.SafeConfigParser() if os.environ.get('IDDS_PANDA_CONFIG', None): configfile = os.environ['IDDS_PANDA_CONFIG'] if panda_config.read(configfile) == [configfile]: return panda_config configfiles = ['%s/etc/panda/panda.cfg' % os.environ.get('IDDS_HOME', ''), '/etc/panda/panda.cfg', '/opt/idds/etc/panda/panda.cfg', '%s/etc/panda/panda.cfg' % os.environ.get('VIRTUAL_ENV', '')] for configfile in configfiles: if panda_config.read(configfile) == [configfile]: return panda_config return panda_config def load_panda_urls(self): panda_config = self.load_panda_config() self.logger.debug("panda config: %s" % panda_config) self.panda_url = None self.panda_url_ssl = None self.panda_monitor = None if panda_config.has_section('panda'): if panda_config.has_option('panda', 'panda_monitor_url'): self.panda_monitor = panda_config.get('panda', 'panda_monitor_url') os.environ['PANDA_MONITOR_URL'] = self.panda_monitor self.logger.debug("Panda monitor url: %s" % str(self.panda_monitor)) if panda_config.has_option('panda', 'panda_url'): self.panda_url = panda_config.get('panda', 'panda_url') os.environ['PANDA_URL'] = self.panda_url self.logger.debug("Panda url: %s" % str(self.panda_url)) if panda_config.has_option('panda', 'panda_url_ssl'): self.panda_url_ssl = panda_config.get('panda', 'panda_url_ssl') os.environ['PANDA_URL_SSL'] = self.panda_url_ssl self.logger.debug("Panda url ssl: %s" % str(self.panda_url_ssl)) if not self.panda_monitor and 'PANDA_MONITOR_URL' in os.environ and os.environ['PANDA_MONITOR_URL']: self.panda_monitor = os.environ['PANDA_MONITOR_URL'] self.logger.debug("Panda monitor url: %s" % str(self.panda_monitor)) if not self.panda_url and 'PANDA_URL' in os.environ and os.environ['PANDA_URL']: self.panda_url = os.environ['PANDA_URL'] self.logger.debug("Panda url: %s" % str(self.panda_url)) if not self.panda_url_ssl and 'PANDA_URL_SSL' in os.environ and os.environ['PANDA_URL_SSL']: self.panda_url_ssl = os.environ['PANDA_URL_SSL'] self.logger.debug("Panda url ssl: %s" % str(self.panda_url_ssl)) def poll_external_collection(self, coll): try: # if 'coll_metadata' in coll and 'is_open' in coll['coll_metadata'] and not coll['coll_metadata']['is_open']: if coll.status in [CollectionStatus.Closed]: return coll else: # client = self.get_rucio_client() # did_meta = client.get_metadata(scope=coll['scope'], name=coll['name']) coll.coll_metadata['bytes'] = 0 coll.coll_metadata['total_files'] = 0 coll.coll_metadata['availability'] = True coll.coll_metadata['events'] = 0 coll.coll_metadata['is_open'] = False coll.coll_metadata['run_number'] = None coll.coll_metadata['did_type'] = 'DATASET' coll.coll_metadata['list_all_files'] = False if 'is_open' in coll.coll_metadata and not coll.coll_metadata['is_open']: coll_status = CollectionStatus.Closed else: coll_status = CollectionStatus.Open coll.status = coll_status if 'did_type' in coll.coll_metadata: if coll.coll_metadata['did_type'] == 'DATASET': coll_type = CollectionType.Dataset elif coll.coll_metadata['did_type'] == 'CONTAINER': coll_type = CollectionType.Container else: coll_type = CollectionType.File else: coll_type = CollectionType.Dataset coll.coll_metadata['coll_type'] = coll_type return coll except Exception as ex: self.logger.error(ex) self.logger.error(traceback.format_exc()) raise exceptions.IDDSException('%s: %s' % (str(ex), traceback.format_exc())) def get_input_collections(self): """ *** Function called by Transformer agent. """ colls = [self.primary_input_collection] + self.other_input_collections for coll_int_id in colls: coll = self.collections[coll_int_id] coll = self.poll_external_collection(coll) self.collections[coll_int_id] = coll return super(ATLASPandaWork, self).get_input_collections() def get_input_contents(self): """ Get all input contents from DDM. """ try: ret_files = [] return ret_files except Exception as ex: self.logger.error(ex) self.logger.error(traceback.format_exc()) raise exceptions.IDDSException('%s: %s' % (str(ex), traceback.format_exc())) def get_mapped_inputs(self, mapped_input_output_maps): ret = [] for map_id in mapped_input_output_maps: inputs = mapped_input_output_maps[map_id]['inputs'] # if 'primary' is not set, the first one is the primary input. primary_input = inputs[0] for ip in inputs: if 'primary' in ip['content_metadata'] and ip['content_metadata']['primary']: primary_input = ip ret.append(primary_input) return ret def get_new_input_output_maps(self, mapped_input_output_maps={}): """ New inputs which are not yet mapped to outputs. :param mapped_input_output_maps: Inputs that are already mapped. """ inputs = self.get_input_contents() mapped_inputs = self.get_mapped_inputs(mapped_input_output_maps) mapped_inputs_scope_name = [ip['scope'] + ":" + ip['name'] for ip in mapped_inputs] new_inputs = [] new_input_output_maps = {} for ip in inputs: ip_scope_name = ip['scope'] + ":" + ip['name'] if ip_scope_name not in mapped_inputs_scope_name: new_inputs.append(ip) # to avoid cheking new inputs if there are no new inputs anymore if (not new_inputs and 'status' in self.collections[self.primary_input_collection] and self.collections[self.primary_input_collection]['status'] in [CollectionStatus.Closed]): # noqa: W503 self.set_has_new_inputs(False) else: mapped_keys = mapped_input_output_maps.keys() if mapped_keys: next_key = max(mapped_keys) + 1 else: next_key = 1 for ip in new_inputs: out_ip = copy.deepcopy(ip) ip['status'] = ContentStatus.Available ip['substatus'] = ContentStatus.Available out_ip['coll_id'] = self.collections[self.output_collections[0]]['coll_id'] new_input_output_maps[next_key] = {'inputs': [ip], 'outputs': [out_ip], 'inputs_dependency': [], 'logs': []} next_key += 1 return new_input_output_maps def get_processing(self, input_output_maps, without_creating=False): """ *** Function called by Transformer agent. If there is already an active processing for this work, will do nothing. If there is no active processings, create_processing will be called. """ if self.active_processings: return self.processings[self.active_processings[0]] else: if not without_creating: return self.create_processing(input_output_maps) return None def create_processing(self, input_output_maps=[]): """ *** Function called by Transformer agent. :param input_output_maps: new maps from inputs to outputs. """ processing_metadata = {'panda_task_id': self.panda_task_id} proc = Processing(processing_metadata=processing_metadata) proc.workload_id = self.panda_task_id self.add_processing_to_processings(proc) self.active_processings.append(proc.internal_id) return proc def submit_panda_task(self, processing): try: from pandatools import Client status, tmpOut = Client.insertTaskParams(self.panda_task_paramsmap, False, True) if status == 0: tmp_status, tmp_output = tmpOut m = re.search("jediTaskID=(\d+)", tmp_output) # noqa W605 task_id = int(m.group(1)) processing.workload_id = task_id else: self.add_errors(tmpOut) raise Exception(tmpOut) except Exception as ex: self.logger.error(ex) self.logger.error(traceback.format_exc()) raise exceptions.IDDSException('%s: %s' % (str(ex), traceback.format_exc())) def submit_processing(self, processing): """ *** Function called by Carrier agent. """ if 'panda_task_id' in processing['processing_metadata'] and processing['processing_metadata']['panda_task_id']: pass else: self.set_user_proxy() self.submit_panda_task(processing) self.unset_user_proxy() def poll_panda_task(self, processing): if 'panda_task_id' in processing['processing_metadata']: from pandatools import Client status, task_status = Client.getTaskStatus(processing.workload_id) if status == 0: return task_status else: return 'failed' return None def kill_processing(self, processing): try: if processing: from pandatools import Client task_id = processing.workload_id Client.killTask(task_id) except Exception as ex: msg = "Failed to check the processing (%s) status: %s" % (str(processing['processing_id']), str(ex)) raise exceptions.IDDSException(msg) def reactivate_processing(self, processing): try: if processing: from pandatools import Client task_id = processing.workload_id Client.retryTask(task_id) # Client.reactivateTask(task_id) # Client.resumeTask(task_id) except Exception as ex: msg = "Failed to check the processing (%s) status: %s" % (str(processing['processing_id']), str(ex)) raise exceptions.IDDSException(msg) def poll_processing_updates(self, processing, input_output_maps): """ *** Function called by Carrier agent. """ updated_contents = [] update_processing = {} reset_expired_at = False if processing: if self.tocancel: self.logger.info("Cancelling processing (processing id: %s, jediTaskId: %s)" % (processing['processing_id'], processing['processing_metadata']['task_id'])) self.kill_processing(processing) self.tocancel = False elif self.tosuspend: self.logger.info("Suspending processing (processing id: %s, jediTaskId: %s)" % (processing['processing_id'], processing['processing_metadata']['task_id'])) self.kill_processing(processing) self.tosuspend = False elif self.toresume: self.logger.info("Resuming processing (processing id: %s, jediTaskId: %s)" % (processing['processing_id'], processing['processing_metadata']['task_id'])) self.reactivate_processing(processing) self.toresume = False reset_expired_at = True elif self.toexpire: self.logger.info("Expiring processing (processing id: %s, jediTaskId: %s)" % (processing['processing_id'], processing['processing_metadata']['task_id'])) self.kill_processing(processing) task_status = self.poll_panda_task(processing) if task_status: if task_status in ['registered', 'defined']: processing_status = ProcessingStatus.Submitted elif task_status in ['assigning', 'ready', 'pending', 'scouting', 'scouted', 'running', 'prepared']: processing_status = ProcessingStatus.Running elif task_status in ['done']: # finished, finishing, waiting it to be done processing_status = ProcessingStatus.Finished elif task_status in ['failed', 'aborted', 'broken', 'exhausted']: processing_status = ProcessingStatus.Failed else: # finished, finishing, aborting, topreprocess, preprocessing, tobroken # toretry, toincexec, rerefine, paused, throttled, passed processing_status = ProcessingStatus.Running update_processing = {'processing_id': processing['processing_id'], 'parameters': {'status': processing_status}} if reset_expired_at: update_processing['parameters']['expired_at'] = None processing['expired_at'] = None if (processing_status in [ProcessingStatus.SubFinished, ProcessingStatus.Finished, ProcessingStatus.Failed] or processing['status'] in [ProcessingStatus.Resuming]): # noqa W503 update_processing['parameters']['status'] = ProcessingStatus.Resuming return update_processing, updated_contents def syn_work_status(self, registered_input_output_maps, all_updates_flushed=True, output_statistics={}): # self.syn_collection_status() if self.is_processings_terminated() and not self.has_new_inputs(): if not self.is_all_outputs_flushed(registered_input_output_maps): self.logger.warn("The processing is terminated. but not all outputs are flushed. Wait to flush the outputs then finish the transform") return if self.is_processings_finished(): self.status = WorkStatus.Finished elif self.is_processings_failed(): self.status = WorkStatus.Failed elif self.is_processings_subfinished(): self.status = WorkStatus.SubFinished
12,409
11,997
72
bfe5be08375a6dd3c112ad918030bbe369fe8e25
8,340
py
Python
file_parser.py
bcbogdan/lisa-parser
08b636ef1d5ebafc076da11c84e92765cbc381bf
[ "Apache-2.0" ]
null
null
null
file_parser.py
bcbogdan/lisa-parser
08b636ef1d5ebafc076da11c84e92765cbc381bf
[ "Apache-2.0" ]
null
null
null
file_parser.py
bcbogdan/lisa-parser
08b636ef1d5ebafc076da11c84e92765cbc381bf
[ "Apache-2.0" ]
null
null
null
""" Linux on Hyper-V and Azure Test Code, ver. 1.0.0 Copyright (c) Microsoft Corporation 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. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. """ from __future__ import print_function import logging import re import sys import csv import fileinput try: import xml.etree.cElementTree as ElementTree except ImportError: import xml.etree.ElementTree as ElementTree logger = logging.getLogger(__name__) class ParseXML(object): """Class used to parse a specific xml test suite file """ def get_tests(self): """Iterates through the xml file looking for <test> sections and initializes a dict for every test case returning them in the end Dict structure: { 'testName' : {} } """ tests_dict = dict() for test in self.root.iter('suiteTest'): tests_dict[test.text.lower()] = dict() for test_case in self.root.iter('test'): # Check if testCase was not commented out if test_case.find('testName').text.lower() == \ test.text.lower(): logger.debug('Getting test details for - %s', test.text) tests_dict[test.text.lower()] = \ self.get_test_details(test_case) return tests_dict @staticmethod def get_test_details(test_root): """Gets and an XML object and iterates through it parsing the test details into a dictionary Dict structure: { 'testProperty' : [ value(s) ] } """ test_dict = dict() for test_property in test_root.getchildren(): if test_property.tag == 'testName': continue elif not test_property.getchildren(): test_dict[test_property.tag.lower()] = \ test_property.text.strip().split() else: test_dict[test_property.tag.lower()] = list() for item in test_property.getchildren(): if test_property.tag.lower() == 'testparams': parameter = item.text.split('=') test_dict[test_property.tag.lower()].append( (parameter[0], parameter[1]) ) else: test_dict[test_property.tag.lower()].append(item.text) return test_dict def get_vms(self): """Method searches for the 'vm' sections in the XML file saving a dict for each vm found. Dict structure: { vm_name: { vm_details } } """ vm_dict = dict() for machine in self.root.iter('vm'): vm_dict[machine.find('vmName').text.lower()] = { 'hvServer': machine.find('hvServer').text.lower(), 'os': machine.find('os').text.lower() } return vm_dict # TODO(bogdancarpusor): Narrow exception field @staticmethod def parse_from_string(xml_string): """Static method that parses xml content from a string The method is used to parse the output of the PS command that is sent to the vm in order to get more details It returns a dict with the following structure: { vm_property: value } """ try: logger.debug('Converting XML string from KVP Command') root = ElementTree.fromstring(xml_string.strip()) prop_name = '' prop_value = '' for child in root: if child.attrib['NAME'] == 'Name': prop_name = child[0].text elif child.attrib['NAME'] == 'Data': prop_value = child[0].text return prop_name, prop_value except RuntimeError: logger.error('Failed to parse XML string,', exc_info=True) logger.info('Terminating execution') sys.exit(0) def parse_ica_log(log_path): """ Parser for the generated log file after a lisa run - ica.log The method iterates until the start of the test outcome section. After that it searches, using regex, for predefined fields and saves them in a dict structure. :param log_path: :return: """ logger.debug( 'Iterating through %s file until the test results part', log_path ) parsed_ica = dict() parsed_ica['vms'] = dict() parsed_ica['tests'] = dict() with open(log_path, 'r') as log_file: for line in log_file: if line.strip() == 'Test Results Summary': break # Get timestamp parsed_ica['timestamp'] = re.search('([0-9/]+) ([0-9:]+)', log_file.next()).group(0) vm_name = "" for line in log_file: line = line.strip().lower() if re.search("^vm:", line) and len(line.split()) == 2: vm_name = line.split()[1] parsed_ica['vms'][vm_name] = dict() # Check if there are any details about the VM try: parsed_ica['vms'][vm_name]['TestLocation'] = 'Hyper-V' except KeyError: parsed_ica['vms'][vm_name] = dict() parsed_ica['vms'][vm_name]['TestLocation'] = 'Azure' elif re.search('^test', line) and \ re.search('(success$|failed$|aborted$)', line): test = line.split() try: parsed_ica['tests'][test[1].lower()] = (vm_name, test[3]) except KeyError: logging.debug('Test %s was not listed in Test Suites ' 'section.It will be ignored from the final' 'results', test) elif re.search('^os', line): parsed_ica['vms'][vm_name]['hostOS'] = line.split(':')[1].strip() elif re.search('^server', line): parsed_ica['vms'][vm_name]['hvServer'] = line.split(':')[1].strip() elif re.search('^logs can be found at', line): parsed_ica['logPath'] = line.split()[-1] elif re.search('^lis version', line): parsed_ica['lisVersion'] = line.split(':')[1].strip() return parsed_ica def parse_from_csv(csv_path): """ Strip and read csv file into a dict data type. :param csv_path: csv file path :return: <list of dict> e.g. [{'t_col1': 'val1', 't_col2': 'val2', ... }, ...] None - on error """ # python [2.7.10, 3.0) does not support context manager for fileinput # strip csv of empty spaces or tabs f = fileinput.input(csv_path, inplace=True) for line in f: # redirect std to file write print(' '.join(line.split())) f.close() list_csv_dict = [] with open(csv_path, 'rb') as f: try: csv_dialect = csv.Sniffer().sniff(f.read(), delimiters=";, ") except Exception as e: logger.error('Error reading csv file {}: {}'.format(csv_path, e)) return None f.seek(0) reader = csv.DictReader(f, dialect=csv_dialect) for csv_dict in reader: list_csv_dict.append(csv_dict) return list_csv_dict
34.320988
83
0.556715
""" Linux on Hyper-V and Azure Test Code, ver. 1.0.0 Copyright (c) Microsoft Corporation 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. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. """ from __future__ import print_function import logging import re import sys import csv import fileinput try: import xml.etree.cElementTree as ElementTree except ImportError: import xml.etree.ElementTree as ElementTree logger = logging.getLogger(__name__) class ParseXML(object): """Class used to parse a specific xml test suite file """ def __init__(self, file_path): self.tree = ElementTree.ElementTree(file=file_path) self.root = self.tree.getroot() def get_tests_suite(self): return self.root.find('testSuites').getchildren()[0]\ .find('suiteName').text def get_tests(self): """Iterates through the xml file looking for <test> sections and initializes a dict for every test case returning them in the end Dict structure: { 'testName' : {} } """ tests_dict = dict() for test in self.root.iter('suiteTest'): tests_dict[test.text.lower()] = dict() for test_case in self.root.iter('test'): # Check if testCase was not commented out if test_case.find('testName').text.lower() == \ test.text.lower(): logger.debug('Getting test details for - %s', test.text) tests_dict[test.text.lower()] = \ self.get_test_details(test_case) return tests_dict @staticmethod def get_test_details(test_root): """Gets and an XML object and iterates through it parsing the test details into a dictionary Dict structure: { 'testProperty' : [ value(s) ] } """ test_dict = dict() for test_property in test_root.getchildren(): if test_property.tag == 'testName': continue elif not test_property.getchildren(): test_dict[test_property.tag.lower()] = \ test_property.text.strip().split() else: test_dict[test_property.tag.lower()] = list() for item in test_property.getchildren(): if test_property.tag.lower() == 'testparams': parameter = item.text.split('=') test_dict[test_property.tag.lower()].append( (parameter[0], parameter[1]) ) else: test_dict[test_property.tag.lower()].append(item.text) return test_dict def get_vms(self): """Method searches for the 'vm' sections in the XML file saving a dict for each vm found. Dict structure: { vm_name: { vm_details } } """ vm_dict = dict() for machine in self.root.iter('vm'): vm_dict[machine.find('vmName').text.lower()] = { 'hvServer': machine.find('hvServer').text.lower(), 'os': machine.find('os').text.lower() } return vm_dict # TODO(bogdancarpusor): Narrow exception field @staticmethod def parse_from_string(xml_string): """Static method that parses xml content from a string The method is used to parse the output of the PS command that is sent to the vm in order to get more details It returns a dict with the following structure: { vm_property: value } """ try: logger.debug('Converting XML string from KVP Command') root = ElementTree.fromstring(xml_string.strip()) prop_name = '' prop_value = '' for child in root: if child.attrib['NAME'] == 'Name': prop_name = child[0].text elif child.attrib['NAME'] == 'Data': prop_value = child[0].text return prop_name, prop_value except RuntimeError: logger.error('Failed to parse XML string,', exc_info=True) logger.info('Terminating execution') sys.exit(0) def parse_ica_log(log_path): """ Parser for the generated log file after a lisa run - ica.log The method iterates until the start of the test outcome section. After that it searches, using regex, for predefined fields and saves them in a dict structure. :param log_path: :return: """ logger.debug( 'Iterating through %s file until the test results part', log_path ) parsed_ica = dict() parsed_ica['vms'] = dict() parsed_ica['tests'] = dict() with open(log_path, 'r') as log_file: for line in log_file: if line.strip() == 'Test Results Summary': break # Get timestamp parsed_ica['timestamp'] = re.search('([0-9/]+) ([0-9:]+)', log_file.next()).group(0) vm_name = "" for line in log_file: line = line.strip().lower() if re.search("^vm:", line) and len(line.split()) == 2: vm_name = line.split()[1] parsed_ica['vms'][vm_name] = dict() # Check if there are any details about the VM try: parsed_ica['vms'][vm_name]['TestLocation'] = 'Hyper-V' except KeyError: parsed_ica['vms'][vm_name] = dict() parsed_ica['vms'][vm_name]['TestLocation'] = 'Azure' elif re.search('^test', line) and \ re.search('(success$|failed$|aborted$)', line): test = line.split() try: parsed_ica['tests'][test[1].lower()] = (vm_name, test[3]) except KeyError: logging.debug('Test %s was not listed in Test Suites ' 'section.It will be ignored from the final' 'results', test) elif re.search('^os', line): parsed_ica['vms'][vm_name]['hostOS'] = line.split(':')[1].strip() elif re.search('^server', line): parsed_ica['vms'][vm_name]['hvServer'] = line.split(':')[1].strip() elif re.search('^logs can be found at', line): parsed_ica['logPath'] = line.split()[-1] elif re.search('^lis version', line): parsed_ica['lisVersion'] = line.split(':')[1].strip() return parsed_ica def parse_from_csv(csv_path): """ Strip and read csv file into a dict data type. :param csv_path: csv file path :return: <list of dict> e.g. [{'t_col1': 'val1', 't_col2': 'val2', ... }, ...] None - on error """ # python [2.7.10, 3.0) does not support context manager for fileinput # strip csv of empty spaces or tabs f = fileinput.input(csv_path, inplace=True) for line in f: # redirect std to file write print(' '.join(line.split())) f.close() list_csv_dict = [] with open(csv_path, 'rb') as f: try: csv_dialect = csv.Sniffer().sniff(f.read(), delimiters=";, ") except Exception as e: logger.error('Error reading csv file {}: {}'.format(csv_path, e)) return None f.seek(0) reader = csv.DictReader(f, dialect=csv_dialect) for csv_dict in reader: list_csv_dict.append(csv_dict) return list_csv_dict
212
0
53
b06c6d5d0112f1268854aa1a8670da026490b05f
12,363
py
Python
adaptive/interface/adaptive/ttypes.py
scwolof/adaptive
9f7475400aa0469778cb60d5ce9c95d9ca359174
[ "MIT" ]
null
null
null
adaptive/interface/adaptive/ttypes.py
scwolof/adaptive
9f7475400aa0469778cb60d5ce9c95d9ca359174
[ "MIT" ]
null
null
null
adaptive/interface/adaptive/ttypes.py
scwolof/adaptive
9f7475400aa0469778cb60d5ce9c95d9ca359174
[ "MIT" ]
null
null
null
# # Autogenerated by Thrift Compiler (0.11.0) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # # options string: py # from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException from thrift.protocol.TProtocol import TProtocolException from thrift.TRecursive import fix_spec import sys import adaptive.interface.constants.datatypes.ttypes import adaptive.interface.constants.exceptions.ttypes import adaptive.interface.ad_event.ttypes import adaptive.interface.ad_data.ttypes import adaptive.interface.biz_data.ttypes import adaptive.interface.user_data.ttypes from thrift.transport import TTransport all_structs = [] class UserAdRequest(object): """ Attributes: - uid - sysinfo """ class UserAdResponse(object): """ Attributes: - timestamp - adReqId - adids """ class BizAdRequest(object): """ Attributes: - bizid - ad_info - daily_budget - lifetime_days """ class BizAdResponse(object): """ Attributes: - timestamp - adid """ all_structs.append(UserAdRequest) UserAdRequest.thrift_spec = ( None, # 0 (1, TType.I32, 'uid', None, None, ), # 1 (2, TType.STRUCT, 'sysinfo', [adaptive.interface.user_data.ttypes.SystemInformation, None], None, ), # 2 ) all_structs.append(UserAdResponse) UserAdResponse.thrift_spec = ( None, # 0 (1, TType.I32, 'timestamp', None, None, ), # 1 (2, TType.I32, 'adReqId', None, None, ), # 2 (3, TType.MAP, 'adids', (TType.I32, None, TType.I32, None, False), None, ), # 3 ) all_structs.append(BizAdRequest) BizAdRequest.thrift_spec = ( None, # 0 (1, TType.I32, 'bizid', None, None, ), # 1 (2, TType.STRUCT, 'ad_info', [adaptive.interface.ad_data.ttypes.AdCreation, None], None, ), # 2 (3, TType.DOUBLE, 'daily_budget', None, None, ), # 3 (4, TType.I32, 'lifetime_days', None, None, ), # 4 ) all_structs.append(BizAdResponse) BizAdResponse.thrift_spec = ( None, # 0 (1, TType.I32, 'timestamp', None, None, ), # 1 (2, TType.I32, 'adid', None, None, ), # 2 ) fix_spec(all_structs) del all_structs
33.871233
134
0.568632
# # Autogenerated by Thrift Compiler (0.11.0) # # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING # # options string: py # from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException from thrift.protocol.TProtocol import TProtocolException from thrift.TRecursive import fix_spec import sys import adaptive.interface.constants.datatypes.ttypes import adaptive.interface.constants.exceptions.ttypes import adaptive.interface.ad_event.ttypes import adaptive.interface.ad_data.ttypes import adaptive.interface.biz_data.ttypes import adaptive.interface.user_data.ttypes from thrift.transport import TTransport all_structs = [] class UserAdRequest(object): """ Attributes: - uid - sysinfo """ def __init__(self, uid=None, sysinfo=None,): self.uid = uid self.sysinfo = sysinfo def read(self, iprot): if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.I32: self.uid = iprot.readI32() else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.sysinfo = adaptive.interface.user_data.ttypes.SystemInformation() self.sysinfo.read(iprot) else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot._fast_encode is not None and self.thrift_spec is not None: oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) return oprot.writeStructBegin('UserAdRequest') if self.uid is not None: oprot.writeFieldBegin('uid', TType.I32, 1) oprot.writeI32(self.uid) oprot.writeFieldEnd() if self.sysinfo is not None: oprot.writeFieldBegin('sysinfo', TType.STRUCT, 2) self.sysinfo.write(oprot) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class UserAdResponse(object): """ Attributes: - timestamp - adReqId - adids """ def __init__(self, timestamp=None, adReqId=None, adids=None,): self.timestamp = timestamp self.adReqId = adReqId self.adids = adids def read(self, iprot): if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.I32: self.timestamp = iprot.readI32() else: iprot.skip(ftype) elif fid == 2: if ftype == TType.I32: self.adReqId = iprot.readI32() else: iprot.skip(ftype) elif fid == 3: if ftype == TType.MAP: self.adids = {} (_ktype1, _vtype2, _size0) = iprot.readMapBegin() for _i4 in range(_size0): _key5 = iprot.readI32() _val6 = iprot.readI32() self.adids[_key5] = _val6 iprot.readMapEnd() else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot._fast_encode is not None and self.thrift_spec is not None: oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) return oprot.writeStructBegin('UserAdResponse') if self.timestamp is not None: oprot.writeFieldBegin('timestamp', TType.I32, 1) oprot.writeI32(self.timestamp) oprot.writeFieldEnd() if self.adReqId is not None: oprot.writeFieldBegin('adReqId', TType.I32, 2) oprot.writeI32(self.adReqId) oprot.writeFieldEnd() if self.adids is not None: oprot.writeFieldBegin('adids', TType.MAP, 3) oprot.writeMapBegin(TType.I32, TType.I32, len(self.adids)) for kiter7, viter8 in self.adids.items(): oprot.writeI32(kiter7) oprot.writeI32(viter8) oprot.writeMapEnd() oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class BizAdRequest(object): """ Attributes: - bizid - ad_info - daily_budget - lifetime_days """ def __init__(self, bizid=None, ad_info=None, daily_budget=None, lifetime_days=None,): self.bizid = bizid self.ad_info = ad_info self.daily_budget = daily_budget self.lifetime_days = lifetime_days def read(self, iprot): if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.I32: self.bizid = iprot.readI32() else: iprot.skip(ftype) elif fid == 2: if ftype == TType.STRUCT: self.ad_info = adaptive.interface.ad_data.ttypes.AdCreation() self.ad_info.read(iprot) else: iprot.skip(ftype) elif fid == 3: if ftype == TType.DOUBLE: self.daily_budget = iprot.readDouble() else: iprot.skip(ftype) elif fid == 4: if ftype == TType.I32: self.lifetime_days = iprot.readI32() else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot._fast_encode is not None and self.thrift_spec is not None: oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) return oprot.writeStructBegin('BizAdRequest') if self.bizid is not None: oprot.writeFieldBegin('bizid', TType.I32, 1) oprot.writeI32(self.bizid) oprot.writeFieldEnd() if self.ad_info is not None: oprot.writeFieldBegin('ad_info', TType.STRUCT, 2) self.ad_info.write(oprot) oprot.writeFieldEnd() if self.daily_budget is not None: oprot.writeFieldBegin('daily_budget', TType.DOUBLE, 3) oprot.writeDouble(self.daily_budget) oprot.writeFieldEnd() if self.lifetime_days is not None: oprot.writeFieldBegin('lifetime_days', TType.I32, 4) oprot.writeI32(self.lifetime_days) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) class BizAdResponse(object): """ Attributes: - timestamp - adid """ def __init__(self, timestamp=None, adid=None,): self.timestamp = timestamp self.adid = adid def read(self, iprot): if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) return iprot.readStructBegin() while True: (fname, ftype, fid) = iprot.readFieldBegin() if ftype == TType.STOP: break if fid == 1: if ftype == TType.I32: self.timestamp = iprot.readI32() else: iprot.skip(ftype) elif fid == 2: if ftype == TType.I32: self.adid = iprot.readI32() else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot._fast_encode is not None and self.thrift_spec is not None: oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) return oprot.writeStructBegin('BizAdResponse') if self.timestamp is not None: oprot.writeFieldBegin('timestamp', TType.I32, 1) oprot.writeI32(self.timestamp) oprot.writeFieldEnd() if self.adid is not None: oprot.writeFieldBegin('adid', TType.I32, 2) oprot.writeI32(self.adid) oprot.writeFieldEnd() oprot.writeFieldStop() oprot.writeStructEnd() def validate(self): return def __repr__(self): L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ def __ne__(self, other): return not (self == other) all_structs.append(UserAdRequest) UserAdRequest.thrift_spec = ( None, # 0 (1, TType.I32, 'uid', None, None, ), # 1 (2, TType.STRUCT, 'sysinfo', [adaptive.interface.user_data.ttypes.SystemInformation, None], None, ), # 2 ) all_structs.append(UserAdResponse) UserAdResponse.thrift_spec = ( None, # 0 (1, TType.I32, 'timestamp', None, None, ), # 1 (2, TType.I32, 'adReqId', None, None, ), # 2 (3, TType.MAP, 'adids', (TType.I32, None, TType.I32, None, False), None, ), # 3 ) all_structs.append(BizAdRequest) BizAdRequest.thrift_spec = ( None, # 0 (1, TType.I32, 'bizid', None, None, ), # 1 (2, TType.STRUCT, 'ad_info', [adaptive.interface.ad_data.ttypes.AdCreation, None], None, ), # 2 (3, TType.DOUBLE, 'daily_budget', None, None, ), # 3 (4, TType.I32, 'lifetime_days', None, None, ), # 4 ) all_structs.append(BizAdResponse) BizAdResponse.thrift_spec = ( None, # 0 (1, TType.I32, 'timestamp', None, None, ), # 1 (2, TType.I32, 'adid', None, None, ), # 2 ) fix_spec(all_structs) del all_structs
9,438
0
756
d52704885e710e3feeb3ec02460d3b66440f0656
3,416
py
Python
dataset-tf.py
harrywang/chinese-calligraphy-dataset
92c9cf3cba044f00812639fdd7d8b5b1e98d6b2a
[ "Apache-2.0" ]
10
2020-12-14T05:08:03.000Z
2022-03-24T13:55:10.000Z
dataset-tf.py
harrywang/chinese-calligraphy-dataset
92c9cf3cba044f00812639fdd7d8b5b1e98d6b2a
[ "Apache-2.0" ]
null
null
null
dataset-tf.py
harrywang/chinese-calligraphy-dataset
92c9cf3cba044f00812639fdd7d8b5b1e98d6b2a
[ "Apache-2.0" ]
3
2020-10-05T12:54:59.000Z
2022-03-22T03:58:01.000Z
import tensorflow as tf import os import pathlib import numpy as np if __name__ == '__main__': import matplotlib.pyplot as plt batch_size = 8 sample_batch_num = 4 dataset = CalligraphyDataset(data_dir='./data/chinese-calligraphy-dataset/', character_csv='./data/label_character.csv', batch_size=8, repeat=False, shuffle=False) plt.figure() plt.rcParams['font.sans-serif']=['SimHei'] for i_batch, (images, labels) in enumerate(dataset.dataset): if i_batch >= sample_batch_num: break labels = np.array([dataset.characters[item.numpy().decode('utf-8')] for item in labels]) images = images.numpy() print(i_batch, images.shape, labels.shape) for i in range(images.shape[0]): ax = plt.subplot(sample_batch_num, batch_size, i_batch * batch_size + i + 1) ax.axis('off') ax.set_title(list(dataset.characters.keys())[labels[i]]) plt.imshow(images[i]) plt.show()
34.16
113
0.604508
import tensorflow as tf import os import pathlib import numpy as np class CalligraphyDataset: def _process_path(self, file_path): # read images from file # and then convert RGB to grayscale # for the images only have black and white img = tf.io.read_file(file_path) img = tf.image.decode_jpeg(img, channels=3) img = tf.image.rgb_to_grayscale(img) # convert black pixels to white and white piexels to black # # in the original calligraphy, the character is black # but we want pixels of character to contain information img = tf.cast(img, dtype=tf.int32) img = tf.math.abs(img - 255) img = tf.cast(img, dtype=tf.uint8) # finally we resize the images but keep the ratio # # the target size (140, 140) is from EDA (see eda.ipynb) # the biggest height or width of all the images is 140 img = tf.image.resize_with_pad( img, target_height=140, target_width=140) # we get the images corresponding labels from the file path # the path is like '../丁/xxx.jpg character = tf.strings.split(file_path, os.sep)[-2] return img, character def __init__(self, data_dir, character_csv, batch_size=1, repeat=True, shuffle=True, shuffle_buffer_size=32): data_dir = pathlib.Path(data_dir) list_ds = tf.data.Dataset.list_files(str(data_dir/'*/*.jpg')) self.length = len(list_ds) self.class_num = len(os.listdir(data_dir)) print('Found %d images in %d classes.' % (self.length, self.class_num)) labeled_ds = list_ds.map(self._process_path) dataset = labeled_ds if shuffle: dataset = dataset.shuffle( buffer_size=shuffle_buffer_size, reshuffle_each_iteration=True) if repeat: dataset = dataset.repeat() dataset = dataset.batch(batch_size=batch_size) # self.dataset = dataset.as_numpy_iterator() self.dataset = dataset # read embedding file from character_csv self.characters = {} with open(character_csv, 'r', encoding='utf-8') as f: for line in f.readlines(): self.characters[line.split(',')[0]] = int(line.split(',')[1]) def __len__(self): return self.length if __name__ == '__main__': import matplotlib.pyplot as plt batch_size = 8 sample_batch_num = 4 dataset = CalligraphyDataset(data_dir='./data/chinese-calligraphy-dataset/', character_csv='./data/label_character.csv', batch_size=8, repeat=False, shuffle=False) plt.figure() plt.rcParams['font.sans-serif']=['SimHei'] for i_batch, (images, labels) in enumerate(dataset.dataset): if i_batch >= sample_batch_num: break labels = np.array([dataset.characters[item.numpy().decode('utf-8')] for item in labels]) images = images.numpy() print(i_batch, images.shape, labels.shape) for i in range(images.shape[0]): ax = plt.subplot(sample_batch_num, batch_size, i_batch * batch_size + i + 1) ax.axis('off') ax.set_title(list(dataset.characters.keys())[labels[i]]) plt.imshow(images[i]) plt.show()
2,177
4
103
d8862b356539452c39a1b4172bc9c903c6711dfb
1,675
py
Python
interactive.py
ilSommo/rate-severity-of-toxic-comments
c0c28475c4d83eeeea72012df6911fc10ba0edbf
[ "MIT" ]
1
2022-02-25T18:37:02.000Z
2022-02-25T18:37:02.000Z
interactive.py
ilSommo/rate-severity-of-toxic-comments
c0c28475c4d83eeeea72012df6911fc10ba0edbf
[ "MIT" ]
null
null
null
interactive.py
ilSommo/rate-severity-of-toxic-comments
c0c28475c4d83eeeea72012df6911fc10ba0edbf
[ "MIT" ]
null
null
null
__version__ = '1.0.0-rc.1' __author__ = 'Lorenzo Menghini, Martino Pulici, Alessandro Stockman, Luca Zucchini' import argparse import pandas as pd import torch from rate_severity_of_toxic_comments.model import create_model from rate_severity_of_toxic_comments.utilities import parse_config, process_config DEFAULT_CONFIG_FILE_PATH = 'config/default.json' LOCAL_CONFIG_FILE_PATH = 'config/local.json' BEST_MODELS_FILE_PATH = 'config/best_models.json' if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--model_file') args = parser.parse_args() CONFIG = parse_config(DEFAULT_CONFIG_FILE_PATH, LOCAL_CONFIG_FILE_PATH) support_bag = process_config(pd.DataFrame(), CONFIG) run_mode = CONFIG['options']['run_mode'] device = torch.device('cuda' if torch.cuda.is_available() and CONFIG['options']['use_gpu'] else 'cpu') model = create_model( run_mode, CONFIG['training'], CONFIG[run_mode], support_bag) model.load_state_dict(torch.load(args.model_file)) model.to(device) query = True while query: query = input('Type comment:') inputs = support_bag['tokenizer']( query, truncation=True, add_special_tokens=True, max_length=128, padding='max_length' ) ids = inputs['input_ids'] mask = inputs['attention_mask'] score = model( ids.unsqueeze( dim=0).to(device), mask.unsqueeze( dim=0).to(device), torch.tensor( [0]).to(device)) print('Score:', score.item())
27.916667
83
0.644776
__version__ = '1.0.0-rc.1' __author__ = 'Lorenzo Menghini, Martino Pulici, Alessandro Stockman, Luca Zucchini' import argparse import pandas as pd import torch from rate_severity_of_toxic_comments.model import create_model from rate_severity_of_toxic_comments.utilities import parse_config, process_config DEFAULT_CONFIG_FILE_PATH = 'config/default.json' LOCAL_CONFIG_FILE_PATH = 'config/local.json' BEST_MODELS_FILE_PATH = 'config/best_models.json' if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--model_file') args = parser.parse_args() CONFIG = parse_config(DEFAULT_CONFIG_FILE_PATH, LOCAL_CONFIG_FILE_PATH) support_bag = process_config(pd.DataFrame(), CONFIG) run_mode = CONFIG['options']['run_mode'] device = torch.device('cuda' if torch.cuda.is_available() and CONFIG['options']['use_gpu'] else 'cpu') model = create_model( run_mode, CONFIG['training'], CONFIG[run_mode], support_bag) model.load_state_dict(torch.load(args.model_file)) model.to(device) query = True while query: query = input('Type comment:') inputs = support_bag['tokenizer']( query, truncation=True, add_special_tokens=True, max_length=128, padding='max_length' ) ids = inputs['input_ids'] mask = inputs['attention_mask'] score = model( ids.unsqueeze( dim=0).to(device), mask.unsqueeze( dim=0).to(device), torch.tensor( [0]).to(device)) print('Score:', score.item())
0
0
0
87e8c794bd6b41de02e02249cde7d720c0a22080
3,945
py
Python
cre.py
flowirtz/common-requirement-enumeration
c89b7bad18e7a62e247e7250100ef834fbfe1456
[ "CC0-1.0" ]
null
null
null
cre.py
flowirtz/common-requirement-enumeration
c89b7bad18e7a62e247e7250100ef834fbfe1456
[ "CC0-1.0" ]
null
null
null
cre.py
flowirtz/common-requirement-enumeration
c89b7bad18e7a62e247e7250100ef834fbfe1456
[ "CC0-1.0" ]
null
null
null
import argparse import os import sys import unittest from typing import List import click # type: ignore import coverage # type: ignore from flask_migrate import Migrate # type: ignore from application import create_app, sqla # type: ignore from application.cmd import cre_main # Hacky solutions to make this both a command line application with argparse and a flask application app = create_app(mode=os.getenv("FLASK_CONFIG") or "default") migrate = Migrate(app, sqla, render_as_batch=True) # flask <x> commands @app.cli.command() # type: ignore @click.option( "--cover/--no-cover", default=False, help="Run tests under code coverage." ) # type: ignore @click.argument("test_names", nargs=-1) # type: ignore # python cre.py --<x> commands if __name__ == "__main__": # if we're called directly main()
31.814516
127
0.65019
import argparse import os import sys import unittest from typing import List import click # type: ignore import coverage # type: ignore from flask_migrate import Migrate # type: ignore from application import create_app, sqla # type: ignore from application.cmd import cre_main # Hacky solutions to make this both a command line application with argparse and a flask application app = create_app(mode=os.getenv("FLASK_CONFIG") or "default") migrate = Migrate(app, sqla, render_as_batch=True) # flask <x> commands @app.cli.command() # type: ignore @click.option( "--cover/--no-cover", default=False, help="Run tests under code coverage." ) # type: ignore @click.argument("test_names", nargs=-1) # type: ignore def test(cover: coverage.Coverage, test_names: List[str]) -> None: COV = None if cover or os.environ.get("FLASK_COVERAGE"): COV = coverage.coverage( branch=True, include="application/*", check_preimported=True, config_file="application/tests/.coveragerc", ) COV.start() if test_names: tests = unittest.TestLoader().loadTestsFromNames(test_names) else: tests = unittest.TestLoader().discover("application/tests", pattern="*_test.py") unittest.TextTestRunner(verbosity=2).run(tests) if COV: COV.stop() COV.save() print("Coverage Summary:") COV.report() basedir = os.path.abspath(os.path.dirname(__file__)) covdir = os.path.join(basedir, "tmp/coverage") COV.html_report(directory=covdir) print("HTML version: file://%s/index.html" % covdir) COV.erase() # python cre.py --<x> commands def main() -> None: app_context = app.app_context() app_context.push() script_path = os.path.dirname(os.path.realpath(__file__)) parser = argparse.ArgumentParser( description="Add documents describing standards to a database" ) parser.add_argument( "--add", action="store_true", help="will treat the incoming spreadsheet as a reviewed cre and add to the database", ) parser.add_argument( "--review", action="store_true", help="will treat the incoming spreadsheet as a new mapping, will try to map the incoming connections to existing cre\ and will create a new spreadsheet with the result for review. Nothing will be added to the database at this point", ) parser.add_argument( "--email", help="used in conjuctions with --review, what email to share the resulting spreadsheet with", default="standards_cache.sqlite", ) parser.add_argument( "--from_spreadsheet", help="import from a spreadsheet to yaml and then database" ) parser.add_argument( "--print_graph", help="will show the graph of the relationships between standards", ) parser.add_argument( "--cache_file", help="where to read/store data", default=os.path.join(script_path, "standards_cache.sqlite"), ) parser.add_argument( "--cre_loc", default=os.path.join(os.path.dirname(os.path.realpath(__file__)), "./cres/"), help="define location of local cre files for review/add", ) parser.add_argument( "--owasp_proj_meta", default=os.path.join( os.path.dirname(os.path.realpath(__file__)), "./cres/owasp/projects.yaml" ), help="define location of owasp project metadata", ) parser.add_argument( "--osib_in", default=None, help="define location of local osib file for review/add", ) parser.add_argument( "--osib_out", default=None, help="define location of local directory to export database in OSIB format to", ) args = parser.parse_args() cre_main.run(args) if __name__ == "__main__": # if we're called directly main()
3,071
0
45
4721e0326315f8d91204ee9ea647d2bb2acb85af
4,419
py
Python
src/virtual_de1soc.py
weiernt/virtual-de1soc
e3405a18fbb9c07c98463a98aaacb8afe26716ea
[ "Python-2.0", "OLDAP-2.3", "OLDAP-2.8" ]
7
2020-05-05T05:52:49.000Z
2021-05-17T12:36:55.000Z
src/virtual_de1soc.py
weiernt/virtual-de1soc
e3405a18fbb9c07c98463a98aaacb8afe26716ea
[ "Python-2.0", "OLDAP-2.3", "OLDAP-2.8" ]
22
2020-05-27T08:34:57.000Z
2021-05-03T14:59:07.000Z
src/virtual_de1soc.py
weiernt/virtual-de1soc
e3405a18fbb9c07c98463a98aaacb8afe26716ea
[ "Python-2.0", "OLDAP-2.3", "OLDAP-2.8" ]
1
2021-05-04T01:04:40.000Z
2021-05-04T01:04:40.000Z
import fpga import modelsim import config_manager import ascii_ui import os import time import pathlib import keyboard screenIO = ascii_ui.ScreenIO() screenIO.renderMessage("Config loading...") configuration = initialise(screenIO) run_lib(screenIO, configuration) run_compile(screenIO, configuration) run_simulation(screenIO, configuration)
28.326923
104
0.719167
import fpga import modelsim import config_manager import ascii_ui import os import time import pathlib import keyboard def get_key_stroke(): keyevents = keyboard.stop_recording() keyboard.start_recording() keylist = [] for event in keyevents: if event.event_type == "down": if event.name not in keylist: keylist.append(event.name.lower()) return keylist def initialise(screenIO): configurationManager = config_manager.ConfigManager() configurationManager.load_config() screenIO.renderConfigMenu(configurationManager) configurationManager.set_types() return configurationManager.config def run_lib(screenIO, configuration): modelsim.VlibDriver(configuration["modelsim_path"], target_path = configuration["target_path"] ) screenIO.clear() screenIO.renderMessage("Vlib finished") modelsim.VmapDriver(configuration["modelsim_path"], target_path = configuration["target_path"] ) screenIO.renderMessage("Vmap finished") def run_compile(screenIO, configuration): vlog = modelsim.VlogDriver(configuration["modelsim_path"], target_path = configuration["target_path"] ) screenIO.renderMessage("Vlog finished") screenIO.renderMessage(vlog.outs) time.sleep(10) def run_simulation(screenIO, configuration): board = fpga.Board() screenIO.clear() screenIO.renderMessage("Vsim starting...") sim = modelsim.VsimController(board, configuration) screenIO.clear() screenIO.renderMessage("Vsim running") keyboard.start_recording() time_old = time.monotonic() count = 0 fps = 0 run = True pause_loop = False while(run): pause_loop = configuration["step_state"] if( configuration["step_state"] ): while pause_loop == True: keyevents = get_key_stroke() if len(keyevents) > 0: for value in keyevents: if value in configuration["SW_key"]: sw_index = configuration["SW_key"].index(value) board.SW.value[sw_index] = not(board.SW.value[sw_index]) if value in configuration["KEY_key"]: key_index = configuration["KEY_key"].index(value) board.KEY.value[key_index] = not(board.KEY.value[key_index]) if value in configuration["quit_key"]: run = False if value in configuration["forward_key"]: pause_loop = False if value in configuration["step_key"]: configuration["step_state"] = not(configuration["step_state"]) pause_loop = False if value in configuration["CLK_key"]: board.CLOCK_50.value[0] = not(board.CLOCK_50.value[0]) screenIO.renderBoard(board,fps) screenIO.renderMessage("STEP MODE!!!! Count: "+str(count)) time_new = time.monotonic() time_dealy = time_new-time_old time_lead = configuration["frame_time"] - time_dealy if (time_lead > 0): # print(time_lead) time.sleep(time_lead) time_new = time.monotonic() time_dealy = time_new-time_old fps = 1/(time_dealy) time_old = time_new sim.step() else: keyevents = get_key_stroke() if len(keyevents) > 0: for value in keyevents: if value in configuration["SW_key"]: sw_index = configuration["SW_key"].index(value) board.SW.value[sw_index] = not(board.SW.value[sw_index]) if value in configuration["KEY_key"]: key_index = configuration["KEY_key"].index(value) board.KEY.value[key_index] = not(board.KEY.value[key_index]) if value in configuration["quit_key"]: run = False if value in configuration["forward_key"]: pause_loop = False if value in configuration["step_key"]: configuration["step_state"] = not(configuration["step_state"]) board.CLOCK_50.value[0]=not(board.CLOCK_50.value[0]) sim.run(configuration["vsim_duration"]) screenIO.renderBoard(board,fps) if configuration["step_state"]: screenIO.renderMessage("STEP UPDATED! Count: "+str(count)) else: screenIO.renderMessage("Continuous mode") time_new = time.monotonic() time_dealy = time_new-time_old time_lead = configuration["frame_time"] - time_dealy if (time_lead > 0): # print(time_lead) time.sleep(time_lead) time_new = time.monotonic() time_dealy = time_new-time_old fps = 1/(time_dealy) time_old = time_new count += 1 sim.quitsim() screenIO = ascii_ui.ScreenIO() screenIO.renderMessage("Config loading...") configuration = initialise(screenIO) run_lib(screenIO, configuration) run_compile(screenIO, configuration) run_simulation(screenIO, configuration)
3,955
0
115
99d2314f7f503b983874f71b34cfeda2a9a10fd6
1,950
py
Python
dns_sprockets_lib/validators/rrsig_orphan.py
roeckelein/sprocket
8e7f9acf4d330d7b1005ba7a2ae8b644571f11fb
[ "Apache-2.0" ]
7
2015-09-11T04:08:12.000Z
2021-01-04T21:47:30.000Z
dns_sprockets_lib/validators/rrsig_orphan.py
roeckelein/sprocket
8e7f9acf4d330d7b1005ba7a2ae8b644571f11fb
[ "Apache-2.0" ]
null
null
null
dns_sprockets_lib/validators/rrsig_orphan.py
roeckelein/sprocket
8e7f9acf4d330d7b1005ba7a2ae8b644571f11fb
[ "Apache-2.0" ]
null
null
null
''' rrsig_orphan - Record test: RrsigOrphan .. Copyright (c) 2015 Neustar, Inc. All rights reserved. .. See COPYRIGHT.txt for full notice. See LICENSE.txt for terms and conditions. ''' import time import dns.rdtypes.ANY.RRSIG import dns.dnssec import dns_sprockets_lib.validators as validators class RrsigOrphan(validators.RecTest): # pylint: disable=too-few-public-methods ''' Checks for orphan RRSIGs. ''' TEST_DNSSECTYPE = True TEST_RRTYPE = 'RRSIG' TEST_OPTARGS = { 'now': (None, 'Time to use for validating RRSIG time windows, e.g. 20150101123000'), 'now_offset': (None, 'Number of seconds to offset the "now" value, e.g. -86400)')} # end of file
30
92
0.608718
''' rrsig_orphan - Record test: RrsigOrphan .. Copyright (c) 2015 Neustar, Inc. All rights reserved. .. See COPYRIGHT.txt for full notice. See LICENSE.txt for terms and conditions. ''' import time import dns.rdtypes.ANY.RRSIG import dns.dnssec import dns_sprockets_lib.validators as validators class RrsigOrphan(validators.RecTest): # pylint: disable=too-few-public-methods ''' Checks for orphan RRSIGs. ''' TEST_DNSSECTYPE = True TEST_RRTYPE = 'RRSIG' TEST_OPTARGS = { 'now': (None, 'Time to use for validating RRSIG time windows, e.g. 20150101123000'), 'now_offset': (None, 'Number of seconds to offset the "now" value, e.g. -86400)')} def __init__(self, args): self.now = None self.now_offset = None super(RrsigOrphan, self).__init__(args) self.posix_now = (self.now and dns.rdtypes.ANY.RRSIG.sigtime_to_posixtime(self.now) or int(time.time())) if self.now_offset: self.posix_now += int(self.now_offset) def run(self, context, suggested_tested, name, ttl, rdata): # pylint: disable=too-many-arguments result = None # Make sure there's a covered RRSet for the RRSIG rdata: rdataset = context.zone_obj.get_rdataset(name, rdata.type_covered) if not rdataset: result = 'No RRSet for name: %s type: %s' % ( name, dns.rdatatype.to_text(rdata.type_covered)) else: try: dns.dnssec.validate_rrsig( (name, rdataset), rdata, {context.zone_name: context.dnskey_rdataset}, now=self.posix_now) except dns.dnssec.UnsupportedAlgorithm as err: result = str(err) except dns.dnssec.ValidationFailure as err: result = str(err) return (suggested_tested, result) # end of file
1,191
0
54
5dda3f762efc780660deff671bbc1e43e11522fd
9,395
py
Python
django/seasight_forecasting/utils.py
rascundampelcuf/seasight-forecasting
d530f9c0be42d8a0f48830940c6b500bdfba3150
[ "CC-BY-4.0" ]
null
null
null
django/seasight_forecasting/utils.py
rascundampelcuf/seasight-forecasting
d530f9c0be42d8a0f48830940c6b500bdfba3150
[ "CC-BY-4.0" ]
9
2021-04-08T21:58:38.000Z
2022-02-10T14:35:42.000Z
django/seasight_forecasting/utils.py
rascundampelcuf/seasight-forecasting
d530f9c0be42d8a0f48830940c6b500bdfba3150
[ "CC-BY-4.0" ]
3
2020-08-16T18:56:32.000Z
2021-08-14T17:54:01.000Z
import itertools import os from seasight_forecasting import global_vars from threading import Thread from time import sleep, time
39.64135
224
0.579244
import itertools import os from seasight_forecasting import global_vars from threading import Thread from time import sleep, time def blankKML(id): string = "\"echo '<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?> \n" + \ "<kml xmlns=\\\"http://www.opengis.net/kml/2.2\\\"" + \ " xmlns:gx=\\\"http://www.google.com/kml/ext/2.2\\\"" + \ " xmlns:kml=\\\"http://www.opengis.net/kml/2.2\\\" " + \ " xmlns:atom=\\\"http://www.w3.org/2005/Atom\\\">\n" + \ " <Document id=\\\"slave_" + id + "\\\"> \n" + \ " </Document>\n" + \ " </kml>\n' > /var/www/html/kml/slave_" + id + ".kml\"" return string def sendKmlToLG(main, slave): command = "sshpass -p " + global_vars.lg_pass + " scp $HOME/" + global_vars.project_location \ + "Seasight-Forecasting/django/" + global_vars.kml_destination_path + main \ + " " + global_vars.lg_IP + ":/var/www/html/SF/" + global_vars.kml_destination_filename print(command) os.system(command) command = "sshpass -p {} scp $HOME/{}Seasight-Forecasting/django/seasight_forecasting/static/img/colorbar.png {}:/var/www/html/SF/colorbar.png".format(global_vars.lg_pass, global_vars.project_location, global_vars.lg_IP) print(command) os.system(command) command = "sshpass -p " + global_vars.lg_pass + " scp $HOME/" + global_vars.project_location \ + "Seasight-Forecasting/django/" + global_vars.kml_destination_path + slave + " " \ + global_vars.lg_IP + ":/var/www/html/kml/slave_" + str(global_vars.screen_for_colorbar) + ".kml" print(command) os.system(command) msg = "http:\/\/" + global_vars.lg_IP + ":81\/\SF\/" + global_vars.kml_destination_filename.replace("/", "\/") + "?id=" + str(int(time()*100)) command = "sshpass -p " + global_vars.lg_pass + " ssh " + global_vars.lg_IP \ + " \"sed -i \'1s/.*/" + msg + "/\' /var/www/html/kmls.txt\"" print(command) os.system(command) def sendKmlToLGCommon(filename): sendKmlToLG(filename, 'slave_{}.kml'.format(global_vars.screen_for_colorbar)) def sendKmlToLGHistoric(files): sendKmlToLG(files[0], files[1]) def threaded_function(): files = os.listdir(global_vars.kml_destination_path) files = [i for i in files if i.startswith('historic')] main = [] slave = [] for elem in files: if elem.endswith('slave_{}.kml'.format(global_vars.screen_for_colorbar)): slave.append(elem) else: main.append(elem) for elem in itertools.cycle(list(zip(main, slave))): sendKmlToLGHistoric(elem) sleep(global_vars.sleep_in_thread) if global_vars.thread == False: print("thread finished...exiting") break def startSendKMLThread(): global_vars.thread = True thread = Thread(target = threaded_function) thread.name = 'SendKML' thread.start() def stopSendKMLThread(): global_vars.thread = False stopOrbit() def sendFlyToToLG(lat, lon, altitude, heading, tilt, pRange, duration): flyTo = "flytoview=<LookAt>" \ + "<longitude>" + str(lon) + "</longitude>" \ + "<latitude>" + str(lat) + "</latitude>" \ + "<altitude>" + str(altitude) + "</altitude>" \ + "<heading>" + str(heading) + "</heading>" \ + "<tilt>" + str(tilt) + "</tilt>" \ + "<range>" + str(pRange) + "</range>" \ + "<altitudeMode>relativeToGround</altitudeMode>" \ + "<gx:altitudeMode>relativeToGround</gx:altitudeMode>" \ + "<gx:duration>" + str(duration) + "</gx:duration>" \ + "</LookAt>" command = "echo '" + flyTo + "' | sshpass -p " + global_vars.lg_pass + " ssh " + global_vars.lg_IP + " 'cat - > /tmp/query.txt'" print(command) os.system(command) def createRotation(lat, lon, alt, tilt, range1): xml = '<?xml version="1.0" encoding="UTF-8"?>' xml += '\n'+'<kml xmlns="http://www.opengis.net/kml/2.2"' xml += '\n'+'xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">' xml += '\n'+'<gx:Tour>' xml += '\n\t'+'<name>Orbit</name>' xml += '\n\t'+'<gx:Playlist>' for i in range(0,1440,10): xml += '\n\t\t'+'<gx:FlyTo>' xml += '\n\t\t\t'+'<gx:duration>1.2</gx:duration>' xml += '\n\t\t\t'+'<gx:flyToMode>smooth</gx:flyToMode>' xml += '\n\t\t\t'+'<LookAt>' xml += '\n\t\t\t\t'+'<longitude>'+str(lon)+'</longitude>' xml += '\n\t\t\t\t'+'<latitude>'+str(lat)+'</latitude>' xml += '\n\t\t\t\t'+'<altitude>'+str(alt)+'</altitude>' xml += '\n\t\t\t\t'+'<heading>'+str(i)+'</heading>' xml += '\n\t\t\t\t'+'<tilt>'+str(tilt)+'</tilt>' xml += '\n\t\t\t\t'+'<gx:fovy>35</gx:fovy>' xml += '\n\t\t\t\t'+'<range>'+str(range1)+'</range>' xml += '\n\t\t\t\t'+'<gx:altitudeMode>absolute</gx:altitudeMode>' xml += '\n\t\t\t'+'</LookAt>' xml += '\n\t\t'+'</gx:FlyTo>' xml += '\n\t'+'</gx:Playlist>' xml += '\n'+'</gx:Tour>' xml += '\n'+'</kml>' return xml def generateOrbitFile(content, path): with open(path, 'w') as file1: file1.write(content) def sendOrbitToLG(): command = "sshpass -p " + global_vars.lg_pass + " scp $HOME/" + global_vars.project_location \ + "Seasight-Forecasting/django/" + global_vars.kml_destination_path + "orbit.kml " + global_vars.lg_IP + ":/var/www/html/SF/orbit.kml" print(command) os.system(command) command = "sshpass -p " + global_vars.lg_pass + " ssh " + global_vars.lg_IP \ + " \"echo http://" + global_vars.lg_IP + ":81/SF/orbit.kml?id=" + str(int(time()*100)) \ + " >> /var/www/html/kmls.txt\"" print(command) os.system(command) def startOrbit(): command = "sshpass -p " + global_vars.lg_pass + " ssh " + global_vars.lg_IP + " \'echo \'playtour=Orbit\' > /tmp/query.txt\'" print(command) os.system(command) def stopOrbit(): command = "sshpass -p " + global_vars.lg_pass + " ssh " + global_vars.lg_IP + " \'echo \'exittour=true\' > /tmp/query.txt\'" print(command) os.system(command) def getCenterOfRegion(region): lon = region.centroid.coords.xy[0][0] lat = region.centroid.coords.xy[1][0] return lat, lon def doRotation(latitude, longitude, altitude, pRange): kml = createRotation(latitude, longitude, altitude, 5, pRange) generateOrbitFile(kml, global_vars.kml_destination_path + '/orbit.kml') sendOrbitToLG() sleep(1) startOrbit() def flyToRegion(region): center_lat, center_lon = getCenterOfRegion(region) sendFlyToToLG(center_lat, center_lon, 15000, 0, 0, 6000000, 2) sleep(4) doRotation(center_lat, center_lon, 15000, 6000000) def cleanVerbose(): fName = 'seasight_forecasting/static/scripts/verbose.txt' with open(fName, "w"): pass def writeVerbose(text): fName = 'seasight_forecasting/static/scripts/verbose.txt' with open(fName, "a+") as f: f.seek(0) data = f.read() if len(data) > 0 : f.write("<br>") f.write(text) def logprint(text): if global_vars.logs: print(text) def cleanMainKML(): command = "sshpass -p " + global_vars.lg_pass + " ssh " + global_vars.lg_IP \ + " \"echo '' > /var/www/html/kmls.txt\"" os.system(command) def cleanSecundaryKML(): for i in range(2,6): string = blankKML(str(i)) command = "sshpass -p " + global_vars.lg_pass + " ssh " + global_vars.lg_IP \ + " " + string os.system(command) def removeSFFolder(): command = "sshpass -p " + global_vars.lg_pass + " ssh " + global_vars.lg_IP \ + " rm -rf /var/www/html/SF" os.system(command) def cleanKMLFiles(): cleanVerbose() cleanMainKML() cleanSecundaryKML() def cleanAllKMLFiles(): cleanMainKML() cleanSecundaryKML() removeSFFolder() def setLogo(): kml = '<kml xmlns=\\\"http://www.opengis.net/kml/2.2\\\" xmlns:atom=\\\"http://www.w3.org/2005/Atom\\\" xmlns:gx=\\\"http://www.google.com/kml/ext/2.2\\\">' kml += '\n ' + '<Document>' kml += '\n ' + '<Folder>' kml += '\n ' + '<name>Logos</name>' kml += '\n ' + '<ScreenOverlay>' kml += '\n ' + '<name>Logo</name>' kml += '\n ' + '<Icon>' kml += '\n ' + '<href>http://lg1:81/SF/Logos.png</href>'.format(global_vars.server_IP) kml += '\n ' + '</Icon>' kml += '\n ' + '<overlayXY x=\\\"0\\\" y=\\\"1\\\" xunits=\\\"fraction\\\" yunits=\\\"fraction\\\"/>' kml += '\n ' + '<screenXY x=\\\"0.02\\\" y=\\\"0.98\\\" xunits=\\\"fraction\\\" yunits=\\\"fraction\\\"/>' kml += '\n ' + '<rotationXY x=\\\"0\\\" y=\\\"0\\\" xunits=\\\"fraction\\\" yunits=\\\"fraction\\\"/>' kml += '\n ' + '<size x=\\\"0.65\\\" y=\\\"0.2\\\" xunits=\\\"fraction\\\" yunits=\\\"fraction\\\"/>' kml += '\n ' + '</ScreenOverlay>' kml += '\n ' + '</Folder>' kml += '\n ' + '</Document>' kml += '\n' + '</kml>' logos_file_target = '/var/www/html/kml/slave_{}.kml'.format(global_vars.screen_for_logos) command = "sshpass -p {} ssh {} echo \"'{}' > {}\"".format(global_vars.lg_pass, global_vars.lg_IP, kml, logos_file_target) print(command) os.system(command) def resetView(): sendFlyToToLG(40.77, -3.6, 0, 0, 5, 10000000, 1.2) setLogo()
8,666
0
598
36536755edb2e6bd4a2e3ce5501ab142294d5898
5,100
py
Python
ModulemdTranslationHelpers/cli.py
sgallagher/ModulemdTranslationHelpers
a8fc0d786b4afa646ac3e017b719bdcce496522a
[ "MIT" ]
null
null
null
ModulemdTranslationHelpers/cli.py
sgallagher/ModulemdTranslationHelpers
a8fc0d786b4afa646ac3e017b719bdcce496522a
[ "MIT" ]
null
null
null
ModulemdTranslationHelpers/cli.py
sgallagher/ModulemdTranslationHelpers
a8fc0d786b4afa646ac3e017b719bdcce496522a
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # This file is part of ModulemdTranslationHelpers # Copyright (C) 2018 Stephen Gallagher # # Fedora-License-Identifier: MIT # SPDX-2.0-License-Identifier: MIT # SPDX-3.0-License-Identifier: MIT # # This program is free software. # For more information on the license, see COPYING. # For more information on free software, see # <https://www.gnu.org/philosophy/free-sw.en.html>. from __future__ import print_function import click import gi import os import os.path import xmlrpc.client from babel.messages import pofile gi.require_version('Modulemd', '1.0') from gi.repository import Modulemd from ModulemdTranslationHelpers import get_module_catalog_from_tags from ModulemdTranslationHelpers import get_modulemd_translations from ModulemdTranslationHelpers.Fedora import KOJI_URL from ModulemdTranslationHelpers.Fedora import get_fedora_rawhide_version from ModulemdTranslationHelpers.Fedora import get_tags_for_fedora_branch ############################################################################## # Common options for all commands # ############################################################################## @click.group() @click.option('--debug/--no-debug', default=False) @click.option('-k', '--koji-url', default=KOJI_URL, type=str, help="The URL of the Koji build system.", show_default=True, metavar="<URL>") @click.option('-b', '--branch', default="rawhide", type=str, help="The distribution release", metavar="<branch_name>") @click.pass_context def cli(ctx, debug, branch, koji_url): """Tools for managing modularity translations.""" ctx.obj = dict() ctx.obj['debug'] = debug ctx.obj['session'] = xmlrpc.client.ServerProxy(koji_url) ctx.obj['branch'] = branch if branch == "rawhide": ctx.obj['branch'] = get_fedora_rawhide_version(ctx.obj['session']) ############################################################################## # Subcommands # ############################################################################## ############################################################################## # `ModulemdTranslationHelpers extract` # ############################################################################## @cli.command() @click.option('-p', '--pot-file', default='fedora-modularity-translations.pot', type=click.File(mode='wb', atomic=True, lazy=True), show_default=True, metavar="<PATH>", help="Path to the portable object template (POT) file to hold " "the translatable strings.") @click.pass_context def extract(ctx, pot_file): """ Extract translatable strings from modules. Extract translations from all modules included in a particular version of Fedora or EPEL. """ catalog = get_module_catalog_from_tags( ctx.parent.obj['session'], get_tags_for_fedora_branch( ctx.parent.obj['branch']), debug=ctx.parent.obj['debug']) pofile.write_po(pot_file, catalog, sort_by_file=True) print("Wrote extracted strings for %s to %s" % (ctx.obj['branch'], pot_file.name)) ############################################################################## # `ModulemdTranslationHelpers generate_metadata` # ############################################################################## @cli.command() @click.option('-d', '--pofile-dir', default='.', help="Path to a directory containing portable object (.po) " "translation files", type=click.Path(exists=True, dir_okay=True, resolve_path=True, readable=True)) @click.option('-y', '--yaml-file', default='fedora-modularity-translations.yaml', type=click.File(mode='wb', atomic=True, lazy=True), show_default=True, metavar="<PATH>", help="Path to the YAML file to hold the translated strings in " "modulemd-translations format.") @click.pass_context def generate_metadata(ctx, pofile_dir, yaml_file): """ Generate modulemd-translations YAML. :return: 0 on successful creation of modulemd-translation, nonzero on failure. """ # Process all .po files in the provided directory translation_files = [f for f in os.listdir(pofile_dir) if os.path.isfile((os.path.join(pofile_dir, f))) and f.endswith(".po")] translations = get_modulemd_translations(translation_files, debug=ctx.parent.obj['debug']) yaml_file.write(Modulemd.dumps(sorted(translations)).encode('utf-8')) print("Wrote modulemd-translations YAML to %s" % yaml_file.name) if __name__ == "__main__": cli(obj={})
36.428571
78
0.546078
# -*- coding: utf-8 -*- # This file is part of ModulemdTranslationHelpers # Copyright (C) 2018 Stephen Gallagher # # Fedora-License-Identifier: MIT # SPDX-2.0-License-Identifier: MIT # SPDX-3.0-License-Identifier: MIT # # This program is free software. # For more information on the license, see COPYING. # For more information on free software, see # <https://www.gnu.org/philosophy/free-sw.en.html>. from __future__ import print_function import click import gi import os import os.path import xmlrpc.client from babel.messages import pofile gi.require_version('Modulemd', '1.0') from gi.repository import Modulemd from ModulemdTranslationHelpers import get_module_catalog_from_tags from ModulemdTranslationHelpers import get_modulemd_translations from ModulemdTranslationHelpers.Fedora import KOJI_URL from ModulemdTranslationHelpers.Fedora import get_fedora_rawhide_version from ModulemdTranslationHelpers.Fedora import get_tags_for_fedora_branch ############################################################################## # Common options for all commands # ############################################################################## @click.group() @click.option('--debug/--no-debug', default=False) @click.option('-k', '--koji-url', default=KOJI_URL, type=str, help="The URL of the Koji build system.", show_default=True, metavar="<URL>") @click.option('-b', '--branch', default="rawhide", type=str, help="The distribution release", metavar="<branch_name>") @click.pass_context def cli(ctx, debug, branch, koji_url): """Tools for managing modularity translations.""" ctx.obj = dict() ctx.obj['debug'] = debug ctx.obj['session'] = xmlrpc.client.ServerProxy(koji_url) ctx.obj['branch'] = branch if branch == "rawhide": ctx.obj['branch'] = get_fedora_rawhide_version(ctx.obj['session']) ############################################################################## # Subcommands # ############################################################################## ############################################################################## # `ModulemdTranslationHelpers extract` # ############################################################################## @cli.command() @click.option('-p', '--pot-file', default='fedora-modularity-translations.pot', type=click.File(mode='wb', atomic=True, lazy=True), show_default=True, metavar="<PATH>", help="Path to the portable object template (POT) file to hold " "the translatable strings.") @click.pass_context def extract(ctx, pot_file): """ Extract translatable strings from modules. Extract translations from all modules included in a particular version of Fedora or EPEL. """ catalog = get_module_catalog_from_tags( ctx.parent.obj['session'], get_tags_for_fedora_branch( ctx.parent.obj['branch']), debug=ctx.parent.obj['debug']) pofile.write_po(pot_file, catalog, sort_by_file=True) print("Wrote extracted strings for %s to %s" % (ctx.obj['branch'], pot_file.name)) ############################################################################## # `ModulemdTranslationHelpers generate_metadata` # ############################################################################## @cli.command() @click.option('-d', '--pofile-dir', default='.', help="Path to a directory containing portable object (.po) " "translation files", type=click.Path(exists=True, dir_okay=True, resolve_path=True, readable=True)) @click.option('-y', '--yaml-file', default='fedora-modularity-translations.yaml', type=click.File(mode='wb', atomic=True, lazy=True), show_default=True, metavar="<PATH>", help="Path to the YAML file to hold the translated strings in " "modulemd-translations format.") @click.pass_context def generate_metadata(ctx, pofile_dir, yaml_file): """ Generate modulemd-translations YAML. :return: 0 on successful creation of modulemd-translation, nonzero on failure. """ # Process all .po files in the provided directory translation_files = [f for f in os.listdir(pofile_dir) if os.path.isfile((os.path.join(pofile_dir, f))) and f.endswith(".po")] translations = get_modulemd_translations(translation_files, debug=ctx.parent.obj['debug']) yaml_file.write(Modulemd.dumps(sorted(translations)).encode('utf-8')) print("Wrote modulemd-translations YAML to %s" % yaml_file.name) if __name__ == "__main__": cli(obj={})
0
0
0
16891a91672520f3f4e34f0fed1c6dff57615f3a
444
py
Python
cert_tool/database.py
never00rei/cert_tool
07928bfdf59627b0f3cbc55d3cccc756c29dbec5
[ "MIT" ]
null
null
null
cert_tool/database.py
never00rei/cert_tool
07928bfdf59627b0f3cbc55d3cccc756c29dbec5
[ "MIT" ]
null
null
null
cert_tool/database.py
never00rei/cert_tool
07928bfdf59627b0f3cbc55d3cccc756c29dbec5
[ "MIT" ]
null
null
null
import datetime from sqlalchemy import Column, Integer, Text, Table, DateTime from sqlalchemy.orm import relationship, backref from sqlalchemy.ext.declarative import declarative_base base = declarative_base() certs = Table( "ssl_certificates", base.metadata, Column("cert_id", Integer, primary_key=True, nullable=False), Column("cert_hostname", Text, nullable=False), Column("cert_serial_number", Text, nullable=False) )
27.75
65
0.763514
import datetime from sqlalchemy import Column, Integer, Text, Table, DateTime from sqlalchemy.orm import relationship, backref from sqlalchemy.ext.declarative import declarative_base base = declarative_base() certs = Table( "ssl_certificates", base.metadata, Column("cert_id", Integer, primary_key=True, nullable=False), Column("cert_hostname", Text, nullable=False), Column("cert_serial_number", Text, nullable=False) )
0
0
0
57b96e2ecbc98aec697e4e1fb2cefa03fd7166db
8,552
py
Python
Autorigger/scripts/dataNodeManager.py
danOrzc/HeavyDutyVehicle
3954314a8ec8101003a8691aeced408c83981bc6
[ "MIT" ]
null
null
null
Autorigger/scripts/dataNodeManager.py
danOrzc/HeavyDutyVehicle
3954314a8ec8101003a8691aeced408c83981bc6
[ "MIT" ]
null
null
null
Autorigger/scripts/dataNodeManager.py
danOrzc/HeavyDutyVehicle
3954314a8ec8101003a8691aeced408c83981bc6
[ "MIT" ]
null
null
null
"""Rigging data storing. This script has functions that allows maya to save the rigging tool process results inside an empty network node that doesn't have transform info. It is in charge of creating the node and the attributes to store the data. It can also query the data or delete the attributes. We are using this module to save the names of the controllers across the rigging process and the groups that contain them. This way we can get the data later to parent them correctly to the mainController. This allows us to create multiple rigs of the same type (multiple wheels, treads, etc) and rig creation after parenting (add more wheels or arms) """ from maya import cmds class NodeData(): """A class used to represent a Node that saves rigging data to Maya It takes the name of the controllers and groups that drive the rigging processes and saves them into a Network node in Maya, which doesn't have transforms or any other kind of unnecesary data. Attributes ---------- mainController : str The name of the main nurbs curve that controls the rig mainControllerGroup : str The name of the group where the mainController is controllerAttributeName : str The name of the type of rig that is saved (i.e. wheelControllers, treadControllers, armControllers) controllerGroupAttributeName : str The name of the type of rig GROUP that is saved (i.e. wheelControllerGroups, treadControllerGroups, armControllerGroups) Methods ------- writeToNode() Takes the rigging info and stores it in a node """ def __init__(self): """Initialize default values""" self.mainController = "" self.mainControllerGroup ="" self.controllerAttributeName = "" self.controllerGroupAttributeName = "" def writeToNode(self): """Takes the rigging info and stores it in a node""" saveData(attributeName=self.controllerGroupAttributeName, value=self.mainControllerGroup) saveData(attributeName=self.controllerAttributeName, value=self.mainController) def createDataNode(nodeName): """Creates a new network node if it was not previously created Parameters ---------- nodeName : str The name of the rigging data node """ # Create node if it doesn't exist if not cmds.objExists(nodeName): cmds.createNode("network", name=nodeName) def createDataAttribute(nodeName, attributeName): """Creates new attribute on the node if it doesn't exist. It creates multi attributes, which are lists that can store multiple indices of data of the same type (i.e. multiple strings) Parameters ---------- nodeName : str The name of the rigging data node to create a new attribute into attributeName : str The name of the desired attribute to store the info """ # Create attribute if it doesn't exist on the node if not cmds.attributeQuery(attributeName, node=nodeName, exists=True): cmds.addAttr(nodeName, shortName=attributeName, dataType="string", multi=True) def saveData(nodeName="rigDataNode", attributeName="myAttr", value=""): """Save data in the specified attribute on the node. Parameters ---------- nodeName : str The name of the rigging data node to create a new attribute into attributeName : str The name of the desired attribute to store the info value : str The information to store (i.e. the namme of the controllers which will be used in other step) """ # Try to create a new node createDataNode(nodeName) # Trye to create an attribute on that node createDataAttribute(nodeName, attributeName) # Get the first element [0] of the attribute theAttr = cmds.getAttr("{}.{}[0]".format(nodeName, attributeName)) # Check if that element is valid (the attribute list has at least one attribute) if theAttr: # Get entire list of attributes attrList = getData(attributeName=attributeName) # If the value is already in the list (e.g. object was deleted and created new one with the same name) # exit the function if value in attrList: return # The index where we want to save the new value is the same as the length of the list # Because we want to store it in the end of the multi attribute elementIndex = len(attrList) # If the element is not valid (the list is empty), # we add our value to the index 0 else: elementIndex = 0 # Set the attribute value # Using format function to put variables inside {}'s # This way we build the attribute's name using the function's parameters # String is {nodeName}.{attributeName}{elementIndex} cmds.setAttr("{}.{}[{}]".format(nodeName, attributeName, elementIndex), value, type="string") """ theAttr = cmds.getAttr("{}.{}[*]".format(nodeName, attributeName)) size = cmds.getAttr("{}.{}".format(nodeName, attributeName),size=True) """ def getData(nodeName="rigDataNode", attributeName="myAttr"): """Get data from a specified attribute on the node. Parameters ---------- nodeName : str The name of the node where the attribute is located attributeName : str The name of the attribute to retrieve the info from """ # If the attribute doesn't exist, return an empty list if not cmds.attributeQuery(attributeName, node=nodeName, exists=True): return [] # Get the size of the attribute # This is because when the attribute has only one element, it returns it as a single string # but when it has multiple elements, it returns it as a list size = cmds.getAttr("{}.{}".format(nodeName, attributeName),size=True) # Get the attribute information theAttr = cmds.getAttr("{}.{}[*]".format(nodeName, attributeName)) # If the size is one element, save it to a list and return it if size == 1: return [theAttr] # Else, if the list has more than one element, return it as it is (already a list) elif size>1: return theAttr # If the attribute is empty, return empty list else: return [] def deleteValue(nodeName="rigDataNode", attributeName="myAttr", value=""): """Delete a specified value from the attribute list on the node. Parameters ---------- nodeName : str The name of the rigging data node to delete a value from attributeName : str The name of the attribute containing that value value : str The exact value to delete from the attribute """ # Exit the function if the node doesn't exist if not cmds.objExists(nodeName): return # Get the attribute list from the node dataList = getData(nodeName=nodeName, attributeName=attributeName) # If it is empty (or doesn't exist), exit the function if not dataList: return # Delete each element on the attribute using their indexes for index in xrange(len(dataList)): # removeMultiInstance removes an element by giving the name of the attribute and the index of the element cmds.removeMultiInstance("{}.{}[{}]".format(nodeName, attributeName, index)) # Create a new list containing only the elements that are not value # This is a list comprehension. It uses a for statement to iterate over a list # and at the same time compares the elements with the value given to see that they are not equal # then every element that succeeds the verification is added to the new list # [] are necessary to wrap the line to specify that we are saving a list newList = [element for element in dataList if not element == value] # Save each element on the new list to the node for element in newList: saveData(nodeName=nodeName, attributeName=attributeName, value=element) def deleteDataAttribute(nodeName="rigDataNode", attributeName="myAttr"): """Delete the entire attribute from the node. Parameters ---------- nodeName : str The name of the node that contains the attribute attributeName : str The name of the attribute that is going to be deleted """ # Exit the function if the node doesn't exist if not cmds.objExists(nodeName): return # Delete the attribute if it exists if cmds.attributeQuery(attributeName, node=nodeName, exists=True): cmds.deleteAttr(nodeName, attribute=attributeName)
37.182609
128
0.684986
"""Rigging data storing. This script has functions that allows maya to save the rigging tool process results inside an empty network node that doesn't have transform info. It is in charge of creating the node and the attributes to store the data. It can also query the data or delete the attributes. We are using this module to save the names of the controllers across the rigging process and the groups that contain them. This way we can get the data later to parent them correctly to the mainController. This allows us to create multiple rigs of the same type (multiple wheels, treads, etc) and rig creation after parenting (add more wheels or arms) """ from maya import cmds class NodeData(): """A class used to represent a Node that saves rigging data to Maya It takes the name of the controllers and groups that drive the rigging processes and saves them into a Network node in Maya, which doesn't have transforms or any other kind of unnecesary data. Attributes ---------- mainController : str The name of the main nurbs curve that controls the rig mainControllerGroup : str The name of the group where the mainController is controllerAttributeName : str The name of the type of rig that is saved (i.e. wheelControllers, treadControllers, armControllers) controllerGroupAttributeName : str The name of the type of rig GROUP that is saved (i.e. wheelControllerGroups, treadControllerGroups, armControllerGroups) Methods ------- writeToNode() Takes the rigging info and stores it in a node """ def __init__(self): """Initialize default values""" self.mainController = "" self.mainControllerGroup ="" self.controllerAttributeName = "" self.controllerGroupAttributeName = "" def writeToNode(self): """Takes the rigging info and stores it in a node""" saveData(attributeName=self.controllerGroupAttributeName, value=self.mainControllerGroup) saveData(attributeName=self.controllerAttributeName, value=self.mainController) def createDataNode(nodeName): """Creates a new network node if it was not previously created Parameters ---------- nodeName : str The name of the rigging data node """ # Create node if it doesn't exist if not cmds.objExists(nodeName): cmds.createNode("network", name=nodeName) def createDataAttribute(nodeName, attributeName): """Creates new attribute on the node if it doesn't exist. It creates multi attributes, which are lists that can store multiple indices of data of the same type (i.e. multiple strings) Parameters ---------- nodeName : str The name of the rigging data node to create a new attribute into attributeName : str The name of the desired attribute to store the info """ # Create attribute if it doesn't exist on the node if not cmds.attributeQuery(attributeName, node=nodeName, exists=True): cmds.addAttr(nodeName, shortName=attributeName, dataType="string", multi=True) def saveData(nodeName="rigDataNode", attributeName="myAttr", value=""): """Save data in the specified attribute on the node. Parameters ---------- nodeName : str The name of the rigging data node to create a new attribute into attributeName : str The name of the desired attribute to store the info value : str The information to store (i.e. the namme of the controllers which will be used in other step) """ # Try to create a new node createDataNode(nodeName) # Trye to create an attribute on that node createDataAttribute(nodeName, attributeName) # Get the first element [0] of the attribute theAttr = cmds.getAttr("{}.{}[0]".format(nodeName, attributeName)) # Check if that element is valid (the attribute list has at least one attribute) if theAttr: # Get entire list of attributes attrList = getData(attributeName=attributeName) # If the value is already in the list (e.g. object was deleted and created new one with the same name) # exit the function if value in attrList: return # The index where we want to save the new value is the same as the length of the list # Because we want to store it in the end of the multi attribute elementIndex = len(attrList) # If the element is not valid (the list is empty), # we add our value to the index 0 else: elementIndex = 0 # Set the attribute value # Using format function to put variables inside {}'s # This way we build the attribute's name using the function's parameters # String is {nodeName}.{attributeName}{elementIndex} cmds.setAttr("{}.{}[{}]".format(nodeName, attributeName, elementIndex), value, type="string") """ theAttr = cmds.getAttr("{}.{}[*]".format(nodeName, attributeName)) size = cmds.getAttr("{}.{}".format(nodeName, attributeName),size=True) """ def getData(nodeName="rigDataNode", attributeName="myAttr"): """Get data from a specified attribute on the node. Parameters ---------- nodeName : str The name of the node where the attribute is located attributeName : str The name of the attribute to retrieve the info from """ # If the attribute doesn't exist, return an empty list if not cmds.attributeQuery(attributeName, node=nodeName, exists=True): return [] # Get the size of the attribute # This is because when the attribute has only one element, it returns it as a single string # but when it has multiple elements, it returns it as a list size = cmds.getAttr("{}.{}".format(nodeName, attributeName),size=True) # Get the attribute information theAttr = cmds.getAttr("{}.{}[*]".format(nodeName, attributeName)) # If the size is one element, save it to a list and return it if size == 1: return [theAttr] # Else, if the list has more than one element, return it as it is (already a list) elif size>1: return theAttr # If the attribute is empty, return empty list else: return [] def deleteValue(nodeName="rigDataNode", attributeName="myAttr", value=""): """Delete a specified value from the attribute list on the node. Parameters ---------- nodeName : str The name of the rigging data node to delete a value from attributeName : str The name of the attribute containing that value value : str The exact value to delete from the attribute """ # Exit the function if the node doesn't exist if not cmds.objExists(nodeName): return # Get the attribute list from the node dataList = getData(nodeName=nodeName, attributeName=attributeName) # If it is empty (or doesn't exist), exit the function if not dataList: return # Delete each element on the attribute using their indexes for index in xrange(len(dataList)): # removeMultiInstance removes an element by giving the name of the attribute and the index of the element cmds.removeMultiInstance("{}.{}[{}]".format(nodeName, attributeName, index)) # Create a new list containing only the elements that are not value # This is a list comprehension. It uses a for statement to iterate over a list # and at the same time compares the elements with the value given to see that they are not equal # then every element that succeeds the verification is added to the new list # [] are necessary to wrap the line to specify that we are saving a list newList = [element for element in dataList if not element == value] # Save each element on the new list to the node for element in newList: saveData(nodeName=nodeName, attributeName=attributeName, value=element) def deleteDataAttribute(nodeName="rigDataNode", attributeName="myAttr"): """Delete the entire attribute from the node. Parameters ---------- nodeName : str The name of the node that contains the attribute attributeName : str The name of the attribute that is going to be deleted """ # Exit the function if the node doesn't exist if not cmds.objExists(nodeName): return # Delete the attribute if it exists if cmds.attributeQuery(attributeName, node=nodeName, exists=True): cmds.deleteAttr(nodeName, attribute=attributeName)
0
0
0
bdc72d2e2682ca17e97115fa3e5b4f56f301576d
1,921
py
Python
aries_cloudagent/protocols/revocation_notification/v1_0/handlers/tests/test_revoke_handler.py
kuraakhilesh8230/aries-cloudagent-python
ee384d1330f6a50ff45a507392ce54f92900f23a
[ "Apache-2.0" ]
4
2019-07-01T13:12:50.000Z
2019-07-02T20:01:37.000Z
aries_cloudagent/protocols/revocation_notification/v1_0/handlers/tests/test_revoke_handler.py
kuraakhilesh8230/aries-cloudagent-python
ee384d1330f6a50ff45a507392ce54f92900f23a
[ "Apache-2.0" ]
51
2021-01-12T05:50:50.000Z
2022-03-25T06:03:13.000Z
aries_cloudagent/protocols/revocation_notification/v1_0/handlers/tests/test_revoke_handler.py
kuraakhilesh8230/aries-cloudagent-python
ee384d1330f6a50ff45a507392ce54f92900f23a
[ "Apache-2.0" ]
12
2019-06-24T22:17:44.000Z
2019-07-02T19:49:31.000Z
"""Test RevokeHandler.""" import pytest from ......config.settings import Settings from ......core.event_bus import EventBus, MockEventBus from ......core.in_memory import InMemoryProfile from ......core.profile import Profile from ......messaging.request_context import RequestContext from ......messaging.responder import MockResponder, BaseResponder from ...messages.revoke import Revoke from ..revoke_handler import RevokeHandler @pytest.fixture @pytest.fixture @pytest.fixture @pytest.fixture @pytest.fixture @pytest.mark.asyncio @pytest.mark.asyncio
27.84058
78
0.756897
"""Test RevokeHandler.""" import pytest from ......config.settings import Settings from ......core.event_bus import EventBus, MockEventBus from ......core.in_memory import InMemoryProfile from ......core.profile import Profile from ......messaging.request_context import RequestContext from ......messaging.responder import MockResponder, BaseResponder from ...messages.revoke import Revoke from ..revoke_handler import RevokeHandler @pytest.fixture def event_bus(): yield MockEventBus() @pytest.fixture def responder(): yield MockResponder() @pytest.fixture def profile(event_bus): yield InMemoryProfile.test_profile(bind={EventBus: event_bus}) @pytest.fixture def message(): yield Revoke(thread_id="mock_thread_id", comment="mock_comment") @pytest.fixture def context(profile: Profile, message: Revoke): request_context = RequestContext(profile) request_context.message = message yield request_context @pytest.mark.asyncio async def test_handle( context: RequestContext, responder: BaseResponder, event_bus: MockEventBus ): await RevokeHandler().handle(context, responder) assert event_bus.events [(_, received)] = event_bus.events assert received.topic == RevokeHandler.RECIEVED_TOPIC assert "thread_id" in received.payload assert "comment" in received.payload @pytest.mark.asyncio async def test_handle_monitor( context: RequestContext, responder: BaseResponder, event_bus: MockEventBus ): context.settings["revocation.monitor_notification"] = True await RevokeHandler().handle(context, responder) [(_, webhook), (_, received)] = event_bus.events assert webhook.topic == RevokeHandler.WEBHOOK_TOPIC assert "thread_id" in webhook.payload assert "comment" in webhook.payload assert received.topic == RevokeHandler.RECIEVED_TOPIC assert "thread_id" in received.payload assert "comment" in received.payload
1,195
0
154
ecf2055ea110bcb9f0572f57c0cfa8cc49cbc007
11,805
py
Python
synthesis/write_java.py
jajajaqlt/nsg
1873f2b5e10441110c3c69940ceb4650f9684ac0
[ "Apache-2.0" ]
10
2021-11-02T18:30:38.000Z
2022-03-21T06:31:33.000Z
synthesis/write_java.py
rohanmukh/nag
f2c4b8e60a97c58a6a1c549cc8b4753ebfe8a5e3
[ "Apache-2.0" ]
2
2021-11-05T18:40:42.000Z
2022-03-30T04:33:08.000Z
synthesis/write_java.py
rohanmukh/nag
f2c4b8e60a97c58a6a1c549cc8b4753ebfe8a5e3
[ "Apache-2.0" ]
2
2021-11-03T19:14:06.000Z
2021-11-03T23:47:09.000Z
# Copyright 2017 Rice University # # 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 from copy import deepcopy from program_helper.ast.ops import * from program_helper.ast.ops.concepts.DAPICallMulti import DAPICallMulti from program_helper.ast.ops.concepts.DExceptionVarDecl import DExceptionVarDecl from program_helper.ast.ops.concepts.DInfix import DInfix from program_helper.ast.ops.concepts.DInternalAPICall import DInternalAPICall from program_helper.ast.ops.concepts.DReturnVar import DReturnVar
41.421053
129
0.567302
# Copyright 2017 Rice University # # 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 from copy import deepcopy from program_helper.ast.ops import * from program_helper.ast.ops.concepts.DAPICallMulti import DAPICallMulti from program_helper.ast.ops.concepts.DExceptionVarDecl import DExceptionVarDecl from program_helper.ast.ops.concepts.DInfix import DInfix from program_helper.ast.ops.concepts.DInternalAPICall import DInternalAPICall from program_helper.ast.ops.concepts.DReturnVar import DReturnVar class Write_Java: def __init__(self, rename_vars=True): self.rename_vars = rename_vars return def add_comment(self, comment): comment_lines = comment.split('\n') header = '' for comment in comment_lines: header += "// " + comment + '\n' return header def program_synthesize_from_json(self, json_input, comment='', prob=None, beam_id=None, mapper=None): self.field_map_dict = {i: j for i, j in enumerate(mapper[20:])} self.fp_map_dict = {i: j for i, j in enumerate(mapper[10:20])} self.int_var_mapper_dict = {i: j for i, j in enumerate(mapper[:10])} prog = self.add_comment(comment) fts = json_input['field_types'] for j, ft in enumerate(fts): if ft['_returns'] is not None: prog += ft['_returns'] + ' field_' + str( self.field_map_dict[j] ) if j < len(fts) - 1: prog += ', ' prog += ';\n' if prob is not None: prog += "// log_prob :: " + str(prob) + '\n' if beam_id is not None: prog += "// beam id :: " + str(beam_id) + '\n' prog += json_input['return_type'] + " " + json_input["method"] + "(" fps = json_input['formal_params'] for j, fp in enumerate(fps): if fp['_returns'] is not None: prog += fp['_returns'] + ' fp_' + str( self.fp_map_dict[j] ) if j < len(fps) - 1: prog += ', ' prog += '){\n' temp_prog , _= self.synthesize_body_from_json(json_input['ast']['_nodes'], tab_len=1, variable_count=0) prog += temp_prog prog += "\n}" return prog def handle_bracket(self, call, var_ids): if call == 'DAPICallSingle' or call == 'DAPICallMultiple'\ or call == 'DStop' or call == 'DInfix' or '(' not in call: return call bracketed_str = '(' arg_types = DAPICallMulti.get_formal_types_from_data(call) for i, (typ, fp) in enumerate(zip(arg_types, var_ids)): bracketed_str += typ + ': ' + fp bracketed_str += ',' if i < len(arg_types) - 1 else '' bracketed_str += ')' return bracketed_str def extract_apiname(self, call, expr_var): name = call.split('(')[0] name = name + '.' # The extra dot is a hack, makes sure last api is included name_comps = [] #name.split('.') word = '' stack = [] for char in name: if char == '<': stack.append(1) word += char elif char == '>': stack.pop() word += char elif char == '.' and len(stack) == 0: new_word = deepcopy(word) name_comps.append(new_word) word = '' else: word += char if expr_var == "system_package": output = '.'.join(name_comps[-2:]) else: output = name_comps[-1] return output def handle_DVarDecl(self, js, var_id=0, tab_len=0): id = js['_id'] # output_prog = "\t" * tab_len + "// Using stmt->DVarDecl " + "\n" output_prog = "\t" * tab_len + js['_returns'] + " " + id + ";" # output_prog += " // init an object \n" if clsinit_or_not else "\n" return output_prog def handle_DClsInit(self, js, tab_len=0): # output_prog = "\t" * tab_len + "// Using stmt->DClsInit " + "\n" output_prog = "\t" * tab_len output_prog += js['_returns'] + " " + js["_id"] + " = " \ if js["_id"] != 'no_return_var' else "" call = js["_call"] output_prog += "new " + call.split('(')[0] output_prog += self.handle_bracket(call, js["fp"]) output_prog += ";\n" return output_prog def handle_DInfix(self, js, tab_len=0, variable_count=0): output_prog = "\t" * tab_len output_prog += "\t" * tab_len temp_prog, _ = self.synthesize_body_from_json(js['_left'], tab_len=0, variable_count=variable_count) output_prog += temp_prog output_prog = output_prog[:-2] + " " + js["_op"][0] + " " temp_prog, _ = self.synthesize_body_from_json(js['_right'], tab_len=0, variable_count=variable_count) output_prog += temp_prog output_prog += ';\n' # but this will be pruned return output_prog def handle_DAPIInvoke(self, js, tab_len=0): output_prog = "\t" * tab_len expr_var = js["expr_var_id"] output_prog += js["ret_var_id"] + " = " if js["ret_var_id"] != 'no_return_var' else "" output_prog += expr_var + "." if expr_var != "system_package" else "" for j, calls in enumerate(js['_calls']): call = calls["_call"] output_prog += self.extract_apiname(call, expr_var) output_prog += self.handle_bracket(call, calls['fp']) output_prog += "." if j < len(js['_calls']) - 1 else ";\n" return output_prog def handle_DBranch(self, js, tab_len=0, variable_count=0): output_prog = "\t" * tab_len + "if (" new_variable_count = variable_count if len(js['_cond']) == 0: output_prog += "true){\n" else: temp_prog, new_variable_count = self.synthesize_body_from_json(js['_cond'], tab_len=0, variable_count=variable_count) output_prog += temp_prog[:-2] + "){\n" temp_prog, _ = self.synthesize_body_from_json(js['_then'], tab_len=tab_len + 1, variable_count=new_variable_count) output_prog += temp_prog if len(js['_else']) > 0: output_prog += "\t" * tab_len + "}else {\n" temp_prog, _ = self.synthesize_body_from_json(js['_else'], tab_len=tab_len + 1, variable_count=new_variable_count) output_prog += temp_prog output_prog += "\t" * tab_len + "}\n" return output_prog def handle_DLoop(self, js, tab_len=0, variable_count=0): output_prog = "\t" * tab_len + "while (" new_variable_count = variable_count if len(js['_cond']) == 0: output_prog += "true){\n" else: temp_prog, new_variable_count = self.synthesize_body_from_json(js['_cond'], tab_len=0, variable_count=variable_count) output_prog += temp_prog[:-2] + "){\n" temp_prog, _ = self.synthesize_body_from_json(js['_body'], tab_len=tab_len + 1, variable_count=new_variable_count) output_prog += temp_prog output_prog += "\t" * tab_len + "}\n" return output_prog def handle_DExcept(self, js, tab_len=0, variable_count=0): output_prog = "\t" * tab_len + "try {\n" temp_prog, _ = self.synthesize_body_from_json(js['_try'], tab_len=tab_len + 1, variable_count=variable_count) output_prog += temp_prog output_prog += "\t" * tab_len + "}\n" output_prog += "\t" * tab_len + "catch(" temp_prog, _ = self.synthesize_body_from_json(js['_catch'], tab_len=tab_len + 1, variable_count=variable_count) output_prog += temp_prog output_prog += "\t" * tab_len + ")\n" return output_prog def handle_DReturnVar(self, js, tab_len=0): output_prog = "\t" * tab_len _id = " " + js["_id"] if js["_id"] != 'no_return_var' else "" output_prog += "return" + _id + ";\n" return output_prog def handle_DStop(self, js, tab_len=0): output_prog = "\t" * tab_len + "}\n" return output_prog def handle_DSubTree(self, js, tab_len=0): output_prog = "\t" * tab_len + "{\n" temp_prog, _ = self.synthesize_body_from_json(js['_nodes'], tab_len=tab_len + 1) output_prog += temp_prog output_prog += "\t" * tab_len + "}\n" return output_prog def handle_DInternalAPICall(self, js, tab_len=0): output_prog = "\t" * tab_len output_prog += js["ret_var_id"] + " = " if js["ret_var_id"] != 'no_return_var' else "" output_prog += js["int_method_id"] + "(" for i, fp in enumerate(js["fps"]): output_prog += fp output_prog += ',' if i < len(js["fps"]) - 1 else '' output_prog += ')' return output_prog def synthesize_body_from_json(self, json_array, tab_len=0, variable_count=0): output_prog = "" for js in json_array: if js["node"] == DSubTree.name(): output_prog += self.handle_DSubTree(js, tab_len=tab_len) elif js["node"] in [DVarDecl.name(), DVarDeclCls.name(), DExceptionVarDecl.name()]: output_prog += self.handle_DVarDecl(js, tab_len=tab_len, # var_id=variable_count, # clsinit_or_not=DVarDeclCls.name() == js["node"] ) variable_count += 1 elif js["node"] == DAPIInvoke.name(): output_prog += self.handle_DAPIInvoke(js, tab_len=tab_len) elif js["node"] == DClsInit.name(): output_prog += self.handle_DClsInit(js, tab_len=tab_len) # TODO: Does Infix even need variable count elif js["node"] == DInfix.name(): output_prog += self.handle_DInfix(js, tab_len=tab_len, variable_count=variable_count) elif js["node"] == DBranch.name(): output_prog += self.handle_DBranch(js, tab_len=tab_len, variable_count=variable_count) elif js["node"] == DLoop.name(): output_prog += self.handle_DLoop(js, tab_len=tab_len, variable_count=variable_count) elif js["node"] == DExcept.name(): output_prog += self.handle_DExcept(js, tab_len=tab_len, variable_count=variable_count) elif js["node"] == DStop.name(): output_prog += self.handle_DStop(js, tab_len=tab_len) elif js["node"] == DReturnVar.name(): output_prog += self.handle_DReturnVar(js, tab_len=tab_len) elif js["node"] == DInternalAPICall.name(): output_prog += self.handle_DInternalAPICall(js, tab_len=tab_len) # elif js["node"] == DVarAssign.name(): # output_prog += "\t" * tab_len + js["_returns"] + " $" + js["_id"] + " = " # output_prog += "$" + js["_rhs_id"] + ";\n" else: print("Unknown type " + js["node"] + " encountered " + "\n") # raise Exception return output_prog, variable_count
10,287
-4
481
577ff58d5cf3dd48a3b5025de081d36df0453fc8
1,636
py
Python
venv/Lib/site-packages/statsmodels/tools/tests/test_sequences.py
EkremBayar/bayar
aad1a32044da671d0b4f11908416044753360b39
[ "MIT" ]
6,931
2015-01-01T11:41:55.000Z
2022-03-31T17:03:24.000Z
venv/Lib/site-packages/statsmodels/tools/tests/test_sequences.py
EkremBayar/bayar
aad1a32044da671d0b4f11908416044753360b39
[ "MIT" ]
6,137
2015-01-01T00:33:45.000Z
2022-03-31T22:53:17.000Z
venv/Lib/site-packages/statsmodels/tools/tests/test_sequences.py
EkremBayar/bayar
aad1a32044da671d0b4f11908416044753360b39
[ "MIT" ]
2,608
2015-01-02T21:32:31.000Z
2022-03-31T07:38:30.000Z
import numpy as np import numpy.testing as npt from statsmodels.tools import sequences
35.565217
83
0.616748
import numpy as np import numpy.testing as npt from statsmodels.tools import sequences def test_discrepancy(): space_0 = [[0.1, 0.5], [0.2, 0.4], [0.3, 0.3], [0.4, 0.2], [0.5, 0.1]] space_1 = [[1, 3], [2, 6], [3, 2], [4, 5], [5, 1], [6, 4]] space_2 = [[1, 5], [2, 4], [3, 3], [4, 2], [5, 1], [6, 6]] corners = np.array([[0.5, 0.5], [6.5, 6.5]]) npt.assert_allclose(sequences.discrepancy(space_0), 0.1353, atol=1e-4) # From Fang et al. Design and modeling for computer experiments, 2006 npt.assert_allclose(sequences.discrepancy(space_1, corners), 0.0081, atol=1e-4) npt.assert_allclose(sequences.discrepancy(space_2, corners), 0.0105, atol=1e-4) def test_van_der_corput(): sample = sequences.van_der_corput(10) out = [0., 0.5, 0.25, 0.75, 0.125, 0.625, 0.375, 0.875, 0.0625, 0.5625] npt.assert_almost_equal(sample, out) sample = sequences.van_der_corput(5, start_index=3) out = [0.75, 0.125, 0.625, 0.375, 0.875] npt.assert_almost_equal(sample, out) def test_primes(): primes = sequences.primes_from_2_to(50) out = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] npt.assert_allclose(primes, out) def test_halton(): corners = np.array([[0, 2], [10, 5]]) sample = sequences.halton(dim=2, n_sample=5, bounds=corners) out = np.array([[5., 3.], [2.5, 4.], [7.5, 2.3], [1.25, 3.3], [6.25, 4.3]]) npt.assert_almost_equal(sample, out, decimal=1) sample = sequences.halton(dim=2, n_sample=3, bounds=corners, start_index=2) out = np.array([[7.5, 2.3], [1.25, 3.3], [6.25, 4.3]]) npt.assert_almost_equal(sample, out, decimal=1)
1,453
0
92
01c8ffb32ae80f7960704c7b88ed605914b4e037
3,805
py
Python
finsky/protos/book_doc_details_pb2.py
mmcloughlin/finsky
f21ccdbebf86e55a542c658b6972cb1f3fb5f119
[ "MIT" ]
59
2015-07-11T18:53:59.000Z
2021-09-08T03:16:17.000Z
finsky/protos/book_doc_details_pb2.py
mmcloughlin/finsky
f21ccdbebf86e55a542c658b6972cb1f3fb5f119
[ "MIT" ]
10
2015-07-01T08:09:29.000Z
2021-12-06T01:23:00.000Z
finsky/protos/book_doc_details_pb2.py
mmcloughlin/finsky
f21ccdbebf86e55a542c658b6972cb1f3fb5f119
[ "MIT" ]
14
2015-08-15T22:04:02.000Z
2021-03-03T09:14:39.000Z
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: book_doc_details.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='book_doc_details.proto', package='BookDocDetails', syntax='proto2', serialized_pb=_b('\n\x16\x62ook_doc_details.proto\x12\x0e\x42ookDocDetails\"v\n\x0b\x42ookDetails\x12\x11\n\tpublisher\x18\x04 \x01(\t\x12\x17\n\x0fpublicationDate\x18\x05 \x01(\t\x12\x0c\n\x04isbn\x18\x06 \x01(\t\x12\x15\n\rnumberOfPages\x18\x07 \x01(\x05\x12\x16\n\x0e\x61\x62outTheAuthor\x18\x11 \x01(\tB2\n com.google.android.finsky.protosB\x0e\x42ookDocDetails') ) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _BOOKDETAILS = _descriptor.Descriptor( name='BookDetails', full_name='BookDocDetails.BookDetails', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='publisher', full_name='BookDocDetails.BookDetails.publisher', index=0, number=4, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='publicationDate', full_name='BookDocDetails.BookDetails.publicationDate', index=1, number=5, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='isbn', full_name='BookDocDetails.BookDetails.isbn', index=2, number=6, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='numberOfPages', full_name='BookDocDetails.BookDetails.numberOfPages', index=3, number=7, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='aboutTheAuthor', full_name='BookDocDetails.BookDetails.aboutTheAuthor', index=4, number=17, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto2', extension_ranges=[], oneofs=[ ], serialized_start=42, serialized_end=160, ) DESCRIPTOR.message_types_by_name['BookDetails'] = _BOOKDETAILS BookDetails = _reflection.GeneratedProtocolMessageType('BookDetails', (_message.Message,), dict( DESCRIPTOR = _BOOKDETAILS, __module__ = 'book_doc_details_pb2' # @@protoc_insertion_point(class_scope:BookDocDetails.BookDetails) )) _sym_db.RegisterMessage(BookDetails) DESCRIPTOR.has_options = True DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n com.google.android.finsky.protosB\016BookDocDetails')) # @@protoc_insertion_point(module_scope)
38.05
369
0.750066
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: book_doc_details.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='book_doc_details.proto', package='BookDocDetails', syntax='proto2', serialized_pb=_b('\n\x16\x62ook_doc_details.proto\x12\x0e\x42ookDocDetails\"v\n\x0b\x42ookDetails\x12\x11\n\tpublisher\x18\x04 \x01(\t\x12\x17\n\x0fpublicationDate\x18\x05 \x01(\t\x12\x0c\n\x04isbn\x18\x06 \x01(\t\x12\x15\n\rnumberOfPages\x18\x07 \x01(\x05\x12\x16\n\x0e\x61\x62outTheAuthor\x18\x11 \x01(\tB2\n com.google.android.finsky.protosB\x0e\x42ookDocDetails') ) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _BOOKDETAILS = _descriptor.Descriptor( name='BookDetails', full_name='BookDocDetails.BookDetails', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='publisher', full_name='BookDocDetails.BookDetails.publisher', index=0, number=4, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='publicationDate', full_name='BookDocDetails.BookDetails.publicationDate', index=1, number=5, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='isbn', full_name='BookDocDetails.BookDetails.isbn', index=2, number=6, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='numberOfPages', full_name='BookDocDetails.BookDetails.numberOfPages', index=3, number=7, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='aboutTheAuthor', full_name='BookDocDetails.BookDetails.aboutTheAuthor', index=4, number=17, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto2', extension_ranges=[], oneofs=[ ], serialized_start=42, serialized_end=160, ) DESCRIPTOR.message_types_by_name['BookDetails'] = _BOOKDETAILS BookDetails = _reflection.GeneratedProtocolMessageType('BookDetails', (_message.Message,), dict( DESCRIPTOR = _BOOKDETAILS, __module__ = 'book_doc_details_pb2' # @@protoc_insertion_point(class_scope:BookDocDetails.BookDetails) )) _sym_db.RegisterMessage(BookDetails) DESCRIPTOR.has_options = True DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n com.google.android.finsky.protosB\016BookDocDetails')) # @@protoc_insertion_point(module_scope)
0
0
0
8b3e705ea470405e32c4419d8579f4b5bcce600d
4,095
py
Python
examples/wallstreetbets-analytics/aggregates/aggregate.py
admariner/beneath
a6aa2c220e4a646be792379528ae673f4bef440b
[ "MIT" ]
65
2021-04-27T13:13:09.000Z
2022-01-24T00:26:06.000Z
examples/wallstreetbets-analytics/aggregates/aggregate.py
admariner/beneath
a6aa2c220e4a646be792379528ae673f4bef440b
[ "MIT" ]
22
2021-10-06T10:30:40.000Z
2021-12-10T11:36:55.000Z
examples/wallstreetbets-analytics/aggregates/aggregate.py
admariner/beneath
a6aa2c220e4a646be792379528ae673f4bef440b
[ "MIT" ]
4
2021-04-24T15:29:51.000Z
2022-03-30T16:20:12.000Z
import asyncio import beneath from datetime import datetime, timedelta from config import BLACKLIST asyncio.run(main())
44.032258
172
0.689621
import asyncio import beneath from datetime import datetime, timedelta from config import BLACKLIST async def main(): client = beneath.Client() await client.start() # TABLE 1: indexed by symbol table = await client.find_table( "examples/wallstreetbets-analytics/stock-metrics-24h-by-symbol" ) yesterday = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d") metrics = await beneath.query_warehouse( f""" with vars as ( select timestamp("{yesterday}") as date, .01 as sentiment_cutoff, ), stock_mentions_posts_calc_sentiment as ( select symbol, timestamp, (title_polarity*num_mentions_title+text_polarity*num_mentions_body)/(num_mentions_title+num_mentions_body) as polarity, (title_subjectivity*num_mentions_title+text_subjectivity*num_mentions_body)/(num_mentions_title+num_mentions_body) as subjectivity, from `examples/wallstreetbets-analytics/r-wallstreetbets-posts-stock-mentions` m, vars join `examples/wallstreetbets-analytics/r-wallstreetbets-posts-sentiment` s on m.post_id=s.post_id where timestamp_trunc(timestamp, day) = vars.date ), stock_mentions_posts as ( select symbol, timestamp_trunc(timestamp, day) as day, count(*) as num_mentions, countif(polarity >= vars.SENTIMENT_CUTOFF) as num_positive, countif(polarity < vars.SENTIMENT_CUTOFF and polarity > -vars.SENTIMENT_CUTOFF) as num_neutral, countif(polarity <= -vars.SENTIMENT_CUTOFF) as num_negative, avg(polarity) as avg_polarity, avg(subjectivity) as avg_subjectivity from stock_mentions_posts_calc_sentiment, vars group by symbol, timestamp_trunc(timestamp, day) ), stock_mentions_comments as ( select symbol, timestamp_trunc(timestamp, day) as day, count(*) as num_mentions, countif(polarity >= vars.SENTIMENT_CUTOFF) as num_positive, countif(polarity < vars.SENTIMENT_CUTOFF and polarity > -vars.SENTIMENT_CUTOFF) as num_neutral, countif(polarity <= -vars.SENTIMENT_CUTOFF) as num_negative, avg(polarity) as avg_polarity, avg(subjectivity) as avg_subjectivity from `examples/wallstreetbets-analytics/r-wallstreetbets-comments-stock-mentions` m, vars join `examples/wallstreetbets-analytics/r-wallstreetbets-comments-sentiment` s on m.comment_id=s.comment_id where timestamp_trunc(timestamp, day) = vars.date group by symbol, timestamp_trunc(timestamp, day) ) select coalesce(p.symbol, c.symbol) as symbol, coalesce(p.day, c.day) as day, ifnull(p.num_mentions, 0) + ifnull(c.num_mentions,0) as num_mentions, ifnull(p.num_positive, 0) + ifnull(c.num_positive,0) as num_positive, ifnull(p.num_neutral, 0) + ifnull(c.num_neutral,0) as num_neutral, ifnull(p.num_negative, 0) + ifnull(c.num_negative,0) as num_negative, (ifnull(p.num_mentions*p.avg_polarity, 0) + ifnull(c.num_mentions*c.avg_polarity, 0))/(ifnull(p.num_mentions, 0) + ifnull(c.num_mentions,0)) as avg_polarity, (ifnull(p.num_mentions*p.avg_subjectivity, 0) + ifnull(c.num_mentions*c.avg_subjectivity, 0))/(ifnull(p.num_mentions, 0) + ifnull(c.num_mentions,0)) as avg_subjectivity from stock_mentions_posts p full join stock_mentions_comments c on p.symbol = c.symbol and p.day = c.day order by symbol, day """ ) metrics = metrics.loc[~metrics["symbol"].isin(BLACKLIST)] await table.write(metrics.to_dict("records")) # TABLE 2: indexed by timestamp table = await client.find_table( "examples/wallstreetbets-analytics/stock-metrics-24h-by-timestamp" ) metrics["num_mentions_rank"] = metrics.groupby(["day"])["num_mentions"].rank( ascending=False, method="min" ) metrics = metrics.loc[metrics["num_mentions_rank"] <= 25] await table.write(metrics.to_dict("records")) await client.stop() asyncio.run(main())
3,948
0
23
9e76014eb85bcda4f6997a33f3f39af789aa84ff
2,866
py
Python
tests/test_send_commands.py
lig/ansq
ef734e143a2f982f92616611b1c7b2d7f0c4cc92
[ "MIT" ]
14
2020-05-22T22:54:04.000Z
2022-02-16T12:15:45.000Z
tests/test_send_commands.py
Ivashkaization/ansq
f89d0ad29fa067ab0169fdee2910aff58b65c790
[ "MIT" ]
31
2020-05-28T12:10:45.000Z
2022-03-31T04:39:48.000Z
tests/test_send_commands.py
Ivashkaization/ansq
f89d0ad29fa067ab0169fdee2910aff58b65c790
[ "MIT" ]
7
2020-05-28T10:40:03.000Z
2022-03-28T19:54:02.000Z
import asyncio from time import sleep, time import pytest from ansq import open_connection from ansq.tcp.connection import NSQConnection from ansq.tcp.exceptions import ConnectionClosedError @pytest.mark.asyncio @pytest.mark.asyncio @pytest.mark.asyncio @pytest.mark.asyncio @pytest.mark.asyncio @pytest.mark.asyncio @pytest.mark.asyncio @pytest.mark.asyncio
24.084034
81
0.7097
import asyncio from time import sleep, time import pytest from ansq import open_connection from ansq.tcp.connection import NSQConnection from ansq.tcp.exceptions import ConnectionClosedError @pytest.mark.asyncio async def test_command_pub(): nsq = await open_connection() assert nsq.status.is_connected response = await nsq.pub("test_topic", f"test_message1, timestamp={time()}") assert response.is_ok await nsq.close() assert nsq.is_closed @pytest.mark.asyncio async def test_command_pub_after_reconnect(): nsq = await open_connection() assert nsq.status.is_connected response = await nsq.pub("test_topic", f"test_message1, timestamp={time()}") assert response.is_ok assert await nsq.reconnect() assert nsq.status.is_connected response2 = await nsq.pub("test_topic", f"test_message1, timestamp={time()}") assert response2.is_ok await nsq.close() assert nsq.is_closed @pytest.mark.asyncio async def test_command_mpub(): nsq = await open_connection() assert nsq.status.is_connected messages = ["message" for _ in range(10)] response = await nsq.mpub("test_topic", messages) assert response.is_ok await nsq.close() assert nsq.is_closed @pytest.mark.asyncio async def test_command_without_identity(): nsq = NSQConnection() await nsq.connect() assert nsq.status.is_connected response = await nsq.pub("test_topic", "test_message") assert response.is_ok await nsq.close() assert nsq.is_closed @pytest.mark.asyncio async def test_command_without_connection(): nsq = NSQConnection() assert nsq.status.is_init with pytest.raises( AssertionError, match="^You should call `connect` method first$", ): await nsq.pub("test_topic", "test_message") await nsq.close() assert nsq.status.is_init @pytest.mark.asyncio async def test_command_sub(): nsq = NSQConnection() await nsq.connect() assert nsq.status.is_connected response = await nsq.sub("test_topic", "channel1") assert response.is_ok await nsq.close() assert nsq.is_closed @pytest.mark.asyncio async def test_command_with_closed_connection(): nsq = await open_connection() await nsq.close() with pytest.raises(ConnectionClosedError, match="^Connection is closed$"): await nsq.pub("test_topic", "test_message") @pytest.mark.asyncio async def test_command_with_concurrently_closed_connection(): nsq = await open_connection() async def close(): await nsq.close() async def blocking_wait_and_pub(): sleep(0.1) await nsq.pub("test_topic", "test_message") with pytest.raises(ConnectionClosedError, match="^Connection is closed$"): await asyncio.wait_for( asyncio.gather(close(), blocking_wait_and_pub()), timeout=1, )
2,313
0
176
f7b882e2ba7b43a7c88aa4eb623d02e8e8a6b467
476
py
Python
Python/EXERCICIOS/FOR/CRV054 - FOR.py
ccpn1988/Python
94c84aa6f3ef9d05d64c3d87212dfd67694f4544
[ "MIT" ]
null
null
null
Python/EXERCICIOS/FOR/CRV054 - FOR.py
ccpn1988/Python
94c84aa6f3ef9d05d64c3d87212dfd67694f4544
[ "MIT" ]
null
null
null
Python/EXERCICIOS/FOR/CRV054 - FOR.py
ccpn1988/Python
94c84aa6f3ef9d05d64c3d87212dfd67694f4544
[ "MIT" ]
null
null
null
# 054 - LER ANO DE NASCIMENTO DE 07 PESSOAS E MOSTRAR QUANTAS PESSOAS SÂO MAIORES DE IDADE. from datetime import date atual = date.today().year tmaior = 0 tmenor = 0 for pessoa in range(1, 8): nasc = int(input(f'Em que ano {pessoa}° a pessoa nasceu? ')) idade = atual - nasc if idade >= 21: tmaior += 1 else: tmenor += 1 print(f'Ao todo tivemos {tmaior} pessoas maiores de idade') print(f'E também tivemos {tmenor} pessoas menores de ideade')
29.75
91
0.668067
# 054 - LER ANO DE NASCIMENTO DE 07 PESSOAS E MOSTRAR QUANTAS PESSOAS SÂO MAIORES DE IDADE. from datetime import date atual = date.today().year tmaior = 0 tmenor = 0 for pessoa in range(1, 8): nasc = int(input(f'Em que ano {pessoa}° a pessoa nasceu? ')) idade = atual - nasc if idade >= 21: tmaior += 1 else: tmenor += 1 print(f'Ao todo tivemos {tmaior} pessoas maiores de idade') print(f'E também tivemos {tmenor} pessoas menores de ideade')
0
0
0
0da64122a0a753645e96c62f0e39c3e1eb7eb001
956
py
Python
app/api/permissions.py
sashis/eduquate
9157d59d428e8bbd272d14f8b09c07c957dacdb7
[ "MIT" ]
null
null
null
app/api/permissions.py
sashis/eduquate
9157d59d428e8bbd272d14f8b09c07c957dacdb7
[ "MIT" ]
null
null
null
app/api/permissions.py
sashis/eduquate
9157d59d428e8bbd272d14f8b09c07c957dacdb7
[ "MIT" ]
null
null
null
from functools import reduce from rest_framework.permissions import BasePermission, SAFE_METHODS
28.969697
86
0.680962
from functools import reduce from rest_framework.permissions import BasePermission, SAFE_METHODS class IsObjectOwner(BasePermission): def has_object_permission(self, request, view, obj): assert hasattr(view, 'owner_field'), ( f"{view.__class__.__name__} class has no 'owner_field' attribute defined." ) if view.owner_field is None: return obj == request.user try: owner = reduce(getattr, view.owner_field.split('__'), obj) except AttributeError: return False return owner == request.user class ReadOnly(BasePermission): def has_permission(self, request, view): return request.method in SAFE_METHODS def has_object_permission(self, request, view, obj): return request.method in SAFE_METHODS class IsTutor(BasePermission): def has_permission(self, request, view): return getattr(request.user, 'is_tutor', False)
646
34
175
35eed1f3fa046377e6452e930c53cfaad4133e33
755
py
Python
sera/commands/install.py
bretth/sera
507976b9ace58bdf4c8055dbfcf2fc10840eacb2
[ "Apache-2.0" ]
null
null
null
sera/commands/install.py
bretth/sera
507976b9ace58bdf4c8055dbfcf2fc10840eacb2
[ "Apache-2.0" ]
12
2016-10-04T20:19:45.000Z
2017-01-31T03:59:57.000Z
sera/commands/install.py
bretth/sera
507976b9ace58bdf4c8055dbfcf2fc10840eacb2
[ "Apache-2.0" ]
null
null
null
import shutil import click from .main import main from ..settings import service_template @main.group("install") def install(): """Install a configuration or service""" @install.command() @click.pass_context @click.option('--path', '-p', help="Path to installed file") def sera(ctx, path): """Locally install systemd service""" if ctx.parent.params['watcher']: click.echo("This command runs locally") raise click.Abort path = path or '/etc/systemd/system/sera.service' if ctx.obj['verbosity']: click.echo('Installing service at %s' % path) output = service_template.substitute( executable=shutil.which('sera'), user='root') with open(path, 'w') as file: file.write(output)
25.166667
60
0.660927
import shutil import click from .main import main from ..settings import service_template @main.group("install") def install(): """Install a configuration or service""" @install.command() @click.pass_context @click.option('--path', '-p', help="Path to installed file") def sera(ctx, path): """Locally install systemd service""" if ctx.parent.params['watcher']: click.echo("This command runs locally") raise click.Abort path = path or '/etc/systemd/system/sera.service' if ctx.obj['verbosity']: click.echo('Installing service at %s' % path) output = service_template.substitute( executable=shutil.which('sera'), user='root') with open(path, 'w') as file: file.write(output)
0
0
0
a6172a57ec332dc717fbcf4654e3a076ea850e06
760
py
Python
app/settings.py
zhenyit/mask_detection
c381e262118ee06a5f6c3d48ce885972ccde217e
[ "MIT" ]
1
2021-02-21T12:07:04.000Z
2021-02-21T12:07:04.000Z
app/settings.py
zhenyit/mask_detection
c381e262118ee06a5f6c3d48ce885972ccde217e
[ "MIT" ]
null
null
null
app/settings.py
zhenyit/mask_detection
c381e262118ee06a5f6c3d48ce885972ccde217e
[ "MIT" ]
null
null
null
import os from datetime import timedelta from dotenv import load_dotenv load_dotenv() SECRET_KEY = os.urandom(32) # SQLite Database Config APP_PATH = os.path.dirname(os.path.abspath(__file__)) SQLALCHEMY_DATABASE_URI = 'sqlite:///' + APP_PATH + '/models/sqlite.db' SQLALCHEMY_TRACK_MODIFICATIONS = True # setting up email server variables MAIL_SERVER = 'smtp.live.com' MAIL_PORT = 587 MAIL_USE_TLS = True MAIL_USERNAME = os.getenv('MAIL_USERNAME') MAIL_PASSWORD = os.getenv('MAIL_PASSWORD') ADMINS = ['ece1779@hotmail.com'] PERMANTENT_SESSION_LIFETIME = timedelta(hours=24) MAX_CONTENT_LENGTH = 4 * 8 * 1024 * 1024 # 2MB ALLOWED_EXTENSIONS = set( ['jpg', 'JPG', 'jpeg', 'JPEG', 'png', 'PNG', 'bmp', 'BMP']) UPLOAD_FOLDER = "./app/static/uploads/"
25.333333
71
0.738158
import os from datetime import timedelta from dotenv import load_dotenv load_dotenv() SECRET_KEY = os.urandom(32) # SQLite Database Config APP_PATH = os.path.dirname(os.path.abspath(__file__)) SQLALCHEMY_DATABASE_URI = 'sqlite:///' + APP_PATH + '/models/sqlite.db' SQLALCHEMY_TRACK_MODIFICATIONS = True # setting up email server variables MAIL_SERVER = 'smtp.live.com' MAIL_PORT = 587 MAIL_USE_TLS = True MAIL_USERNAME = os.getenv('MAIL_USERNAME') MAIL_PASSWORD = os.getenv('MAIL_PASSWORD') ADMINS = ['ece1779@hotmail.com'] PERMANTENT_SESSION_LIFETIME = timedelta(hours=24) MAX_CONTENT_LENGTH = 4 * 8 * 1024 * 1024 # 2MB ALLOWED_EXTENSIONS = set( ['jpg', 'JPG', 'jpeg', 'JPEG', 'png', 'PNG', 'bmp', 'BMP']) UPLOAD_FOLDER = "./app/static/uploads/"
0
0
0
98f192a8bc04e0f17848096cd40ed569b3cb8d09
7,430
py
Python
TokenScraper/CoinMarketCap Dev API/coincap_ERC-20_DevAPI.py
SamIlic/Web-Scraping
fae1e0b000adda18abff44e4c60fbad77e872314
[ "MIT" ]
1
2022-02-22T12:15:28.000Z
2022-02-22T12:15:28.000Z
TokenScraper/CoinMarketCap Dev API/coincap_ERC-20_DevAPI.py
SamIlic/Web-Scraping
fae1e0b000adda18abff44e4c60fbad77e872314
[ "MIT" ]
null
null
null
TokenScraper/CoinMarketCap Dev API/coincap_ERC-20_DevAPI.py
SamIlic/Web-Scraping
fae1e0b000adda18abff44e4c60fbad77e872314
[ "MIT" ]
1
2022-02-22T12:15:30.000Z
2022-02-22T12:15:30.000Z
""" # NOTE (for Sam): Run on "QSTrader" Conda Virtual Enviroment > "source activate QSTrader" > Run via "python coincap_ERC-20_ranker.py" Summary of script 1) Open Top ERC-20 file & create a DataFrame with the info 2) Get ID's for all ERC-20 tokens using Global API 3) Use Ticker(Specific Currency) API to get info on each ERC-20 token 4) Create a DataFrame with all the info 5) Write DataFrame to .xlsx file # NOTE: Code must be run on a Virtual Environment in order to import "prettytable" (as least this was the case for me) """ import re import xlrd import json import requests import datetime import numpy as np import pandas as pd from openpyxl import load_workbook from colorama import Fore, Back, Style ### 1) Open Top ERC-20 Tokens File file_path = r"/Users/YoungFreeesh/Visual Studio Code/_Python/Web Scraping/TokenScraper/CoinMarketCap Dev API/CMC-ID-Map.xlsx" # top_ERC_df = pd.read_csv(file_path, header=0,index_col=0) # for .csv top_ERC_df = pd.read_excel(file_path, sheetname = "Top ERC-20") # read all data from "Top ERC-20" headers = list(top_ERC_df.columns.values) # get the headers --> ERC-20 Token, Ticker, ID, CoinMarketCap URL, Market Cap (yyyy-mm-dd) top_ERC_df = pd.DataFrame(top_ERC_df) # convert top_ERC_df to a DateFrame # Get IDs ERC_ID_List = top_ERC_df.iloc[:,2] # print(ERC_ID_List) # Set Currency convert = 'USD' ### CoinMarketCap API # EXAMPLE API KEY Call --> https://pro-api.coinmarketcap.com/v1/cryptocurrency/map?CMC_PRO_API_KEY=a3e5008f-c6b1-471d-9b4c-c4424e8b7d1f API_Key = Sorry # Sam's personal API Key # listings_url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/historical' + API_Key # Not Supported in Free subscription plan listings_url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest' + API_Key # Listings Latest url_end = '?structure=array&convert=' + convert # Might not be necessary anymore request = requests.get(listings_url) results = request.json() data = results['data'] # All Data #currencyData = results['data'][0] # All Currencies # print(json.dumps(results, sort_keys=True, indent=4)) ### Initilaize List elements --> will be used to create DataFrame --> used to create .xlsx file id_num_List = list() name_List = list() symbol_List = list() website_slug_List = list() cmc_rank_List = list() num_markets_List = list() circulating_supply_List = list() total_supply_List = list() percent_total_supply_circulating_List = list() max_supply_List = list() last_updated_List = list() # ['quote']['USD'] price_List = list() volume_24h_List = list() market_cap_List = list() percent_change_1h_List = list() percent_change_24h_List = list() percent_change_7d_List = list() jjj = 0 #for currency in currencyData: # For each for currency in data: # For each if currency['id'] in ERC_ID_List.values: # ONLY FOR ERC-20 Tokens ### Get Data for ticker id_num = currency['id'] rank = currency['cmc_rank'] name = currency['name'] symbol = currency['symbol'] website_slug = currency['slug'] website_slug = "https://coinmarketcap.com/currencies/" + website_slug + "/" num_markets = currency['num_markets'] circulating_supply = currency['circulating_supply'] total_supply = currency['total_supply'] if circulating_supply is None: circulating_supply = 0 if total_supply is None: total_supply = 0 percent_total_supply_circulating = "None" else: # percent_total_supply_circulating = int(round(circulating_supply/total_supply*100)) percent_total_supply_circulating = round(circulating_supply/total_supply*100) max_supply = currency['max_supply'] last_updated = currency['last_updated'] # Quotes quotes = currency['quote'][convert] price = round(quotes['price'],4) volume = round(quotes['volume_24h']) percent_change_1h = quotes['percent_change_1h'] percent_change_24h = quotes['percent_change_24h'] percent_change_7d = quotes['percent_change_7d'] market_cap = quotes['market_cap'] print(jjj,': ', name, " (", symbol, ")") jjj += 1 ### Append List Elements id_num_List.append(id_num) cmc_rank_List.append(rank) name_List.append(name) symbol_List.append(symbol) website_slug_List.append(website_slug) num_markets_List.append(num_markets) circulating_supply_List.append(circulating_supply) total_supply_List.append(total_supply) max_supply_List.append(max_supply) last_updated_List.append(last_updated) price_List.append(price) volume_24h_List.append(volume) percent_change_1h_List.append(percent_change_1h) percent_change_24h_List.append(percent_change_24h) percent_change_7d_List.append(percent_change_7d) market_cap_List.append(market_cap) ### Create DataFrame from Lists ##df = pd.DataFrame(data=temp, index=ranking) ranker_List = pd.DataFrame( list(zip(cmc_rank_List, name_List, symbol_List, price_List, market_cap_List, volume_24h_List, num_markets_List, percent_total_supply_circulating_List, circulating_supply_List, total_supply_List, max_supply_List, percent_change_1h_List, percent_change_24h_List, percent_change_7d_List, id_num_List, last_updated_List, website_slug_List)), columns=['Name', 'Ticker', 'Price ($)', 'Market Cap ($)', 'Daily Volume ($)', 'Number of Markets', '% of Total Supply Circulating', 'Circulating Supply', 'Total Supply', 'Max Supply', '% Change: 1h', '% Change: 24h', '% Change: 7d', 'ID', 'Last Updated', 'CoinMarketCap URL'], index=cmc_rank_List) ranker_List.index.name = "CMC Rank" # Rename Index #print(name_List) print(name_List) print(ranker_List) """ ### Ordering in Excel Sheet cmc_rank_List name_List symbol_List price_List market_cap_List volume_24h_List num_markets_List percent_total_supply_circulating_List circulating_supply_List total_supply_List max_supply_List percent_change_1h_List percent_change_24h_List percent_change_7d_List id_num_List last_updated_List website_slug_List """ # Get Time stamp for market cap timeStamp = str(datetime.datetime.today().strftime(' (%Y-%m-%d)')) # Today, as an Integer ### Create Excel File fileName = "MASTER-ERC-20" + timeStamp file_path_HardDrive = r"/Users/YoungFreeesh/Visual Studio Code/_Python/Web Scraping/TokenScraper/CoinMarketCap Dev API/" + fileName + ".xlsx" writer_HardDrive = pd.ExcelWriter(file_path_HardDrive)#, engine='openpyxl') ranker_List.to_excel(writer_HardDrive, startrow= 0 , index=True, sheet_name= 'Summary') # write to "MASTER-Ercot.xlsx" spreadsheet writer_HardDrive.save() writer_HardDrive.close()
34.55814
142
0.664065
""" # NOTE (for Sam): Run on "QSTrader" Conda Virtual Enviroment > "source activate QSTrader" > Run via "python coincap_ERC-20_ranker.py" Summary of script 1) Open Top ERC-20 file & create a DataFrame with the info 2) Get ID's for all ERC-20 tokens using Global API 3) Use Ticker(Specific Currency) API to get info on each ERC-20 token 4) Create a DataFrame with all the info 5) Write DataFrame to .xlsx file # NOTE: Code must be run on a Virtual Environment in order to import "prettytable" (as least this was the case for me) """ import re import xlrd import json import requests import datetime import numpy as np import pandas as pd from openpyxl import load_workbook from colorama import Fore, Back, Style ### 1) Open Top ERC-20 Tokens File file_path = r"/Users/YoungFreeesh/Visual Studio Code/_Python/Web Scraping/TokenScraper/CoinMarketCap Dev API/CMC-ID-Map.xlsx" # top_ERC_df = pd.read_csv(file_path, header=0,index_col=0) # for .csv top_ERC_df = pd.read_excel(file_path, sheetname = "Top ERC-20") # read all data from "Top ERC-20" headers = list(top_ERC_df.columns.values) # get the headers --> ERC-20 Token, Ticker, ID, CoinMarketCap URL, Market Cap (yyyy-mm-dd) top_ERC_df = pd.DataFrame(top_ERC_df) # convert top_ERC_df to a DateFrame # Get IDs ERC_ID_List = top_ERC_df.iloc[:,2] # print(ERC_ID_List) # Set Currency convert = 'USD' ### CoinMarketCap API # EXAMPLE API KEY Call --> https://pro-api.coinmarketcap.com/v1/cryptocurrency/map?CMC_PRO_API_KEY=a3e5008f-c6b1-471d-9b4c-c4424e8b7d1f API_Key = Sorry # Sam's personal API Key # listings_url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/historical' + API_Key # Not Supported in Free subscription plan listings_url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest' + API_Key # Listings Latest url_end = '?structure=array&convert=' + convert # Might not be necessary anymore request = requests.get(listings_url) results = request.json() data = results['data'] # All Data #currencyData = results['data'][0] # All Currencies # print(json.dumps(results, sort_keys=True, indent=4)) ### Initilaize List elements --> will be used to create DataFrame --> used to create .xlsx file id_num_List = list() name_List = list() symbol_List = list() website_slug_List = list() cmc_rank_List = list() num_markets_List = list() circulating_supply_List = list() total_supply_List = list() percent_total_supply_circulating_List = list() max_supply_List = list() last_updated_List = list() # ['quote']['USD'] price_List = list() volume_24h_List = list() market_cap_List = list() percent_change_1h_List = list() percent_change_24h_List = list() percent_change_7d_List = list() jjj = 0 #for currency in currencyData: # For each for currency in data: # For each if currency['id'] in ERC_ID_List.values: # ONLY FOR ERC-20 Tokens ### Get Data for ticker id_num = currency['id'] rank = currency['cmc_rank'] name = currency['name'] symbol = currency['symbol'] website_slug = currency['slug'] website_slug = "https://coinmarketcap.com/currencies/" + website_slug + "/" num_markets = currency['num_markets'] circulating_supply = currency['circulating_supply'] total_supply = currency['total_supply'] if circulating_supply is None: circulating_supply = 0 if total_supply is None: total_supply = 0 percent_total_supply_circulating = "None" else: # percent_total_supply_circulating = int(round(circulating_supply/total_supply*100)) percent_total_supply_circulating = round(circulating_supply/total_supply*100) max_supply = currency['max_supply'] last_updated = currency['last_updated'] # Quotes quotes = currency['quote'][convert] price = round(quotes['price'],4) volume = round(quotes['volume_24h']) percent_change_1h = quotes['percent_change_1h'] percent_change_24h = quotes['percent_change_24h'] percent_change_7d = quotes['percent_change_7d'] market_cap = quotes['market_cap'] print(jjj,': ', name, " (", symbol, ")") jjj += 1 ### Append List Elements id_num_List.append(id_num) cmc_rank_List.append(rank) name_List.append(name) symbol_List.append(symbol) website_slug_List.append(website_slug) num_markets_List.append(num_markets) circulating_supply_List.append(circulating_supply) total_supply_List.append(total_supply) max_supply_List.append(max_supply) last_updated_List.append(last_updated) price_List.append(price) volume_24h_List.append(volume) percent_change_1h_List.append(percent_change_1h) percent_change_24h_List.append(percent_change_24h) percent_change_7d_List.append(percent_change_7d) market_cap_List.append(market_cap) ### Create DataFrame from Lists ##df = pd.DataFrame(data=temp, index=ranking) ranker_List = pd.DataFrame( list(zip(cmc_rank_List, name_List, symbol_List, price_List, market_cap_List, volume_24h_List, num_markets_List, percent_total_supply_circulating_List, circulating_supply_List, total_supply_List, max_supply_List, percent_change_1h_List, percent_change_24h_List, percent_change_7d_List, id_num_List, last_updated_List, website_slug_List)), columns=['Name', 'Ticker', 'Price ($)', 'Market Cap ($)', 'Daily Volume ($)', 'Number of Markets', '% of Total Supply Circulating', 'Circulating Supply', 'Total Supply', 'Max Supply', '% Change: 1h', '% Change: 24h', '% Change: 7d', 'ID', 'Last Updated', 'CoinMarketCap URL'], index=cmc_rank_List) ranker_List.index.name = "CMC Rank" # Rename Index #print(name_List) print(name_List) print(ranker_List) """ ### Ordering in Excel Sheet cmc_rank_List name_List symbol_List price_List market_cap_List volume_24h_List num_markets_List percent_total_supply_circulating_List circulating_supply_List total_supply_List max_supply_List percent_change_1h_List percent_change_24h_List percent_change_7d_List id_num_List last_updated_List website_slug_List """ # Get Time stamp for market cap timeStamp = str(datetime.datetime.today().strftime(' (%Y-%m-%d)')) # Today, as an Integer ### Create Excel File fileName = "MASTER-ERC-20" + timeStamp file_path_HardDrive = r"/Users/YoungFreeesh/Visual Studio Code/_Python/Web Scraping/TokenScraper/CoinMarketCap Dev API/" + fileName + ".xlsx" writer_HardDrive = pd.ExcelWriter(file_path_HardDrive)#, engine='openpyxl') ranker_List.to_excel(writer_HardDrive, startrow= 0 , index=True, sheet_name= 'Summary') # write to "MASTER-Ercot.xlsx" spreadsheet writer_HardDrive.save() writer_HardDrive.close()
0
0
0
95785ab1ca666f93525815ee3dd8bb11851fa2b1
862
py
Python
bot.py
DreamBNC/Python-Service-Bot
2625e471e332de7a99f1933f82437c54ec97af97
[ "MIT" ]
1
2016-08-09T21:29:52.000Z
2016-08-09T21:29:52.000Z
bot.py
DreamBNC/Python-Service-Bot
2625e471e332de7a99f1933f82437c54ec97af97
[ "MIT" ]
null
null
null
bot.py
DreamBNC/Python-Service-Bot
2625e471e332de7a99f1933f82437c54ec97af97
[ "MIT" ]
null
null
null
# WIP # DreamBNC Bot 2 # (c) DreamBNC # Loading essential libraries (needed for connecting to IRC) import zirc, ssl print("DreamBNC Service Bot") print("(c) 2016 DreamBNC dev team.") print("Initalizing.") # setting variables bncprovider = DreamBNC bncweb = dreambnc.xyz server1 = Mushroom print("Initalized; connecting...") # connecting using zirc self.config = zirc.IRCConfig(host="irc.freenode.net", port=6697, nickname="%bncprovider", ident="%bncprovider", realname="%bncprovider Service Bot - http://%bncweb", # variables are being an pain; we have to hard code this # We should also probably add some way to input a server pass channels=['#DreamBNC'], sasl_user="user", sasl_pass="pw") self.connect(self.config) self.start() Bot()
24.628571
62
0.726218
# WIP # DreamBNC Bot 2 # (c) DreamBNC # Loading essential libraries (needed for connecting to IRC) import zirc, ssl print("DreamBNC Service Bot") print("(c) 2016 DreamBNC dev team.") print("Initalizing.") # setting variables bncprovider = DreamBNC bncweb = dreambnc.xyz server1 = Mushroom print("Initalized; connecting...") # connecting using zirc class Bot(zirc.Client): def __init__(self): self.connection = zirc.Socket(wrapper=ssl.wrap_socket) self.config = zirc.IRCConfig(host="irc.freenode.net", port=6697, nickname="%bncprovider", ident="%bncprovider", realname="%bncprovider Service Bot - http://%bncweb", # variables are being an pain; we have to hard code this # We should also probably add some way to input a server pass channels=['#DreamBNC'], sasl_user="user", sasl_pass="pw") self.connect(self.config) self.start() Bot()
-2
87
22
3ae785bd76a0b7c709a9fbc4fef0f36252efeff6
765
py
Python
sus/tests/test_engines.py
ResupinePuma/SUS
f1035482d9a911e472385fe724fc4583c2c67ffd
[ "MIT" ]
1
2022-02-20T17:50:43.000Z
2022-02-20T17:50:43.000Z
sus/tests/test_engines.py
ResupinePuma/SUS
f1035482d9a911e472385fe724fc4583c2c67ffd
[ "MIT" ]
null
null
null
sus/tests/test_engines.py
ResupinePuma/SUS
f1035482d9a911e472385fe724fc4583c2c67ffd
[ "MIT" ]
null
null
null
from sus.engines import telegram, reddit, rss import vcr import unittest
36.428571
135
0.679739
from sus.engines import telegram, reddit, rss import vcr import unittest class EngineTests(unittest.TestCase): @vcr.use_cassette('./sus/tests/cassettes/telegram.yaml') def test_telegram(self): self.assertGreater(len(telegram.scrab({"url": "https://t.me/s/durov", "time_limit_hours": 24*31*6})), 0) @vcr.use_cassette('./sus/tests/cassettes/reddit.yaml') def test_reddit(self): self.assertGreater(len(reddit.scrab({"url": "https://www.reddit.com/r/announcements/", "time_limit_hours": 24*31*6})), 0) @vcr.use_cassette('./sus/tests/cassettes/rss.yaml') def test_rss(self): self.assertGreater(len(rss.scrab({"url": "https://feeds.bbci.co.uk/news/world/europe/rss.xml", "time_limit_hours": 24*31})), 0)
381
272
23
ff3ee4e0aa72c96a6b61185f57659ec9f099df4c
3,401
py
Python
Quantize/Quantizers_test.py
stevenygd/TensorQuant-Experiment
f084b57c22a3c2d4fa49d77b56a35e9017149789
[ "Apache-2.0" ]
null
null
null
Quantize/Quantizers_test.py
stevenygd/TensorQuant-Experiment
f084b57c22a3c2d4fa49d77b56a35e9017149789
[ "Apache-2.0" ]
null
null
null
Quantize/Quantizers_test.py
stevenygd/TensorQuant-Experiment
f084b57c22a3c2d4fa49d77b56a35e9017149789
[ "Apache-2.0" ]
null
null
null
import tensorflow as tf import numpy as np import Quantizers import math import time import struct from tensorflow.python.ops import standard_ops from tensorflow.python.ops import nn hex_lambda = lambda x : hex(struct.unpack('<I', struct.pack('<f', x))[0]) toHex = np.vectorize(hex_lambda) input_width = input_height = 4 batch_size = 2 input_channels = 2 entries = input_width*input_height*batch_size*input_channels testdata_scale=10 threshold = 5 inputs_vals = np.random.normal(size=(batch_size,input_width,input_height,input_channels))*testdata_scale #inputs_vals = 1.0 - 2.0**-np.arange(entries) inputs = tf.constant(inputs_vals,dtype=tf.float32) #inputs = tf.zeros_like(inputs) quantizer_log = Quantizers.LogarithmicQuantizer() output_log = quantizer_log.quantize(inputs) gold_output_log = log2(inputs) quantizer_sparse = Quantizers.SparseQuantizer(threshold) output_sparse = quantizer_sparse.quantize(inputs) gold_output_sparse = sparse(inputs, threshold) quantizer_halffp = Quantizers.HalffpQuantizer() output_halffp = quantizer_halffp.quantize(inputs) gold_output_halffp = halffp(inputs) with tf.Session() as sess: ''' print('input:') print(toHex(sess.run(inputs))) print('quantized:') print(toHex(sess.run(output_halffp))) print('gold quantized:') print(toHex(sess.run(gold_output_halffp))) ''' result_log=np.sum( np.absolute(gold_output_log.eval().flatten()-output_log.eval().flatten())) result_sparse=np.sum( np.absolute(gold_output_sparse.eval().flatten()-output_sparse.eval().flatten())) # rounding in TF FP16 format is different than in Halffp kernel implementation! # mantissa is rounded up in TF FP16 and cut in kernel. # rounding bit in integer representation has value 8192, difference between TF FP16 and # kernel is 0 or that number. gold_output_halffp = np.array( [struct.unpack('<I', struct.pack('<f', x))[0] for x in gold_output_halffp.eval().flatten()]) output_halffp = np.array( [struct.unpack('<I', struct.pack('<f', x))[0] for x in output_halffp.eval().flatten()]) result_halffp = gold_output_halffp-output_halffp result_halffp = np.absolute( np.sum( (result_halffp==0).astype(np.int32) + (result_halffp==8192).astype(np.int32) ) - result_halffp.size) #result_halffp=np.sum(np.absolute(gold_output_halffp.eval().flatten()-output_halffp.eval().flatten())) ''' start=time.time() for i in range(100000): output_halffp.eval() runtime = time.time()-start print('kernel-version time: %fs'%runtime) start=time.time() for i in range(100000): gold_output_halffp.eval() runtime = time.time()-start print('tf-version time: %fs'%runtime) ''' print('LogQuantizer test:') check(result_log) print('SparseQuantizer test:') check(result_sparse) print('HalffpQuantizer test:') check(result_halffp)
29.068376
104
0.707439
import tensorflow as tf import numpy as np import Quantizers import math import time import struct from tensorflow.python.ops import standard_ops from tensorflow.python.ops import nn hex_lambda = lambda x : hex(struct.unpack('<I', struct.pack('<f', x))[0]) toHex = np.vectorize(hex_lambda) input_width = input_height = 4 batch_size = 2 input_channels = 2 entries = input_width*input_height*batch_size*input_channels testdata_scale=10 threshold = 5 def check(val): if val>0: print('---failed!---') else: print('+++passed!+++') def log2(tensor): signs=tf.sign(tensor) tensor= tf.floor(tf.log(tf.abs(tensor))/math.log(2)) tensor= tf.pow(2*tf.ones_like(tensor),tensor) tensor= tensor*signs return tensor def sparse(tensor, threshold): tensor = tensor*tf.to_float(tf.abs(tensor)>threshold) return tensor def halffp(tensor): tensor = tf.cast(tensor,tf.float16) return tensor inputs_vals = np.random.normal(size=(batch_size,input_width,input_height,input_channels))*testdata_scale #inputs_vals = 1.0 - 2.0**-np.arange(entries) inputs = tf.constant(inputs_vals,dtype=tf.float32) #inputs = tf.zeros_like(inputs) quantizer_log = Quantizers.LogarithmicQuantizer() output_log = quantizer_log.quantize(inputs) gold_output_log = log2(inputs) quantizer_sparse = Quantizers.SparseQuantizer(threshold) output_sparse = quantizer_sparse.quantize(inputs) gold_output_sparse = sparse(inputs, threshold) quantizer_halffp = Quantizers.HalffpQuantizer() output_halffp = quantizer_halffp.quantize(inputs) gold_output_halffp = halffp(inputs) with tf.Session() as sess: ''' print('input:') print(toHex(sess.run(inputs))) print('quantized:') print(toHex(sess.run(output_halffp))) print('gold quantized:') print(toHex(sess.run(gold_output_halffp))) ''' result_log=np.sum( np.absolute(gold_output_log.eval().flatten()-output_log.eval().flatten())) result_sparse=np.sum( np.absolute(gold_output_sparse.eval().flatten()-output_sparse.eval().flatten())) # rounding in TF FP16 format is different than in Halffp kernel implementation! # mantissa is rounded up in TF FP16 and cut in kernel. # rounding bit in integer representation has value 8192, difference between TF FP16 and # kernel is 0 or that number. gold_output_halffp = np.array( [struct.unpack('<I', struct.pack('<f', x))[0] for x in gold_output_halffp.eval().flatten()]) output_halffp = np.array( [struct.unpack('<I', struct.pack('<f', x))[0] for x in output_halffp.eval().flatten()]) result_halffp = gold_output_halffp-output_halffp result_halffp = np.absolute( np.sum( (result_halffp==0).astype(np.int32) + (result_halffp==8192).astype(np.int32) ) - result_halffp.size) #result_halffp=np.sum(np.absolute(gold_output_halffp.eval().flatten()-output_halffp.eval().flatten())) ''' start=time.time() for i in range(100000): output_halffp.eval() runtime = time.time()-start print('kernel-version time: %fs'%runtime) start=time.time() for i in range(100000): gold_output_halffp.eval() runtime = time.time()-start print('tf-version time: %fs'%runtime) ''' print('LogQuantizer test:') check(result_log) print('SparseQuantizer test:') check(result_sparse) print('HalffpQuantizer test:') check(result_halffp)
393
0
92
298728a2e15813871cd0299700345ed04b777f24
3,044
py
Python
airflow/sensors/hive_partition_sensor.py
suensummit/airflow
37a342d0e96a91ce2d34085e225a4e86f54c4e21
[ "Apache-2.0" ]
3
2019-10-03T21:38:59.000Z
2019-10-04T00:39:03.000Z
airflow/sensors/hive_partition_sensor.py
suensummit/airflow
37a342d0e96a91ce2d34085e225a4e86f54c4e21
[ "Apache-2.0" ]
20
2017-04-18T19:47:46.000Z
2020-01-13T04:19:24.000Z
airflow/sensors/hive_partition_sensor.py
suensummit/airflow
37a342d0e96a91ce2d34085e225a4e86f54c4e21
[ "Apache-2.0" ]
5
2017-06-19T19:55:47.000Z
2020-10-10T00:49:20.000Z
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF 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. from airflow.sensors.base_sensor_operator import BaseSensorOperator from airflow.utils.decorators import apply_defaults class HivePartitionSensor(BaseSensorOperator): """ Waits for a partition to show up in Hive. Note: Because ``partition`` supports general logical operators, it can be inefficient. Consider using NamedHivePartitionSensor instead if you don't need the full flexibility of HivePartitionSensor. :param table: The name of the table to wait for, supports the dot notation (my_database.my_table) :type table: str :param partition: The partition clause to wait for. This is passed as is to the metastore Thrift client ``get_partitions_by_filter`` method, and apparently supports SQL like notation as in ``ds='2015-01-01' AND type='value'`` and comparison operators as in ``"ds>=2015-01-01"`` :type partition: str :param metastore_conn_id: reference to the metastore thrift service connection id :type metastore_conn_id: str """ template_fields = ('schema', 'table', 'partition',) ui_color = '#C5CAE9' @apply_defaults
40.052632
91
0.669842
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF 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. from airflow.sensors.base_sensor_operator import BaseSensorOperator from airflow.utils.decorators import apply_defaults class HivePartitionSensor(BaseSensorOperator): """ Waits for a partition to show up in Hive. Note: Because ``partition`` supports general logical operators, it can be inefficient. Consider using NamedHivePartitionSensor instead if you don't need the full flexibility of HivePartitionSensor. :param table: The name of the table to wait for, supports the dot notation (my_database.my_table) :type table: str :param partition: The partition clause to wait for. This is passed as is to the metastore Thrift client ``get_partitions_by_filter`` method, and apparently supports SQL like notation as in ``ds='2015-01-01' AND type='value'`` and comparison operators as in ``"ds>=2015-01-01"`` :type partition: str :param metastore_conn_id: reference to the metastore thrift service connection id :type metastore_conn_id: str """ template_fields = ('schema', 'table', 'partition',) ui_color = '#C5CAE9' @apply_defaults def __init__(self, table, partition="ds='{{ ds }}'", metastore_conn_id='metastore_default', schema='default', poke_interval=60 * 3, *args, **kwargs): super().__init__( poke_interval=poke_interval, *args, **kwargs) if not partition: partition = "ds='{{ ds }}'" self.metastore_conn_id = metastore_conn_id self.table = table self.partition = partition self.schema = schema def poke(self, context): if '.' in self.table: self.schema, self.table = self.table.split('.') self.log.info( 'Poking for table %s.%s, partition %s', self.schema, self.table, self.partition ) if not hasattr(self, 'hook'): from airflow.hooks.hive_hooks import HiveMetastoreHook self.hook = HiveMetastoreHook( metastore_conn_id=self.metastore_conn_id) return self.hook.check_for_partition( self.schema, self.table, self.partition)
1,045
0
53
56975f404ec591ff536aa967cda09455639f1f89
7,627
py
Python
app/controllers/admin/routes.py
BCStudentSoftwareDevTeam/celts
b14f3aea8fb3777d9e04feafbbb0f23f02ad5cf5
[ "BSD-3-Clause" ]
null
null
null
app/controllers/admin/routes.py
BCStudentSoftwareDevTeam/celts
b14f3aea8fb3777d9e04feafbbb0f23f02ad5cf5
[ "BSD-3-Clause" ]
147
2021-06-11T18:27:53.000Z
2022-03-22T18:50:35.000Z
app/controllers/admin/routes.py
BCStudentSoftwareDevTeam/celts
b14f3aea8fb3777d9e04feafbbb0f23f02ad5cf5
[ "BSD-3-Clause" ]
2
2021-09-16T18:46:21.000Z
2021-11-10T19:10:17.000Z
from flask import request, render_template, url_for, g, Flask, redirect, flash, abort, json, jsonify, session from peewee import DoesNotExist from playhouse.shortcuts import model_to_dict, dict_to_model import json from datetime import datetime from dateutil import parser from app import app from app.models.program import Program from app.models.event import Event from app.models.facilitator import Facilitator from app.models.eventParticipant import EventParticipant from app.models.eventRsvp import EventRsvp from app.models.user import User from app.models.term import Term from app.models.eventTemplate import EventTemplate from app.models.outsideParticipant import OutsideParticipant from app.models.eventParticipant import EventParticipant from app.models.programEvent import ProgramEvent from app.logic.participants import trainedParticipants from app.logic.volunteers import getEventLengthInHours from app.logic.utils import selectSurroundingTerms from app.logic.events import deleteEvent, getAllFacilitators, attemptSaveEvent, preprocessEventData, calculateRecurringEventFrequency from app.logic.courseManagement import pendingCourses, approvedCourses from app.controllers.admin import admin_bp from app.controllers.admin.volunteers import getVolunteers from app.controllers.admin.userManagement import manageUsers @admin_bp.route('/switch_user', methods=['POST']) @admin_bp.route('/template_select') @admin_bp.route('/event/<templateid>/create', methods=['GET','POST']) @admin_bp.route('/event/<templateid>/<programid>/create', methods=['GET','POST']) @admin_bp.route('/event/<eventId>/edit', methods=['GET','POST']) @admin_bp.route('/event/<eventId>/delete', methods=['POST']) @admin_bp.route('/makeRecurringEvents', methods=['POST']) @admin_bp.route('/volunteerProfile', methods=['POST']) @admin_bp.route('/search_student', methods=['GET']) @admin_bp.route('/addParticipants', methods = ['GET']) def addParticipants(): '''Renders the page, will be removed once merged with full page''' return render_template('addParticipants.html', title="Add Participants") @admin_bp.route('/courseManagement', methods = ['GET', 'POST']) @admin_bp.route('/courseManagement/<term>', methods = ['GET', 'POST']) def courseManagement(term = None): ''' Renders the page for admins to manage Course Proposals ''' term = Term.get_or_none(Term.id == term) if not term: term = g.current_term pending = pendingCourses(term) approved = approvedCourses(term) terms = selectSurroundingTerms(g.current_term) return render_template('/admin/courseManagement.html', pendingCourses = pending, approvedCourses = approved, terms = terms, term = term)
38.715736
133
0.687164
from flask import request, render_template, url_for, g, Flask, redirect, flash, abort, json, jsonify, session from peewee import DoesNotExist from playhouse.shortcuts import model_to_dict, dict_to_model import json from datetime import datetime from dateutil import parser from app import app from app.models.program import Program from app.models.event import Event from app.models.facilitator import Facilitator from app.models.eventParticipant import EventParticipant from app.models.eventRsvp import EventRsvp from app.models.user import User from app.models.term import Term from app.models.eventTemplate import EventTemplate from app.models.outsideParticipant import OutsideParticipant from app.models.eventParticipant import EventParticipant from app.models.programEvent import ProgramEvent from app.logic.participants import trainedParticipants from app.logic.volunteers import getEventLengthInHours from app.logic.utils import selectSurroundingTerms from app.logic.events import deleteEvent, getAllFacilitators, attemptSaveEvent, preprocessEventData, calculateRecurringEventFrequency from app.logic.courseManagement import pendingCourses, approvedCourses from app.controllers.admin import admin_bp from app.controllers.admin.volunteers import getVolunteers from app.controllers.admin.userManagement import manageUsers @admin_bp.route('/switch_user', methods=['POST']) def switchUser(): if app.env == "production": print(f"An attempt was made to switch to another user by {g.current_user.username}!") abort(403) print(f"Switching user from {g.current_user} to",request.form['newuser']) session['current_user'] = model_to_dict(User.get_by_id(request.form['newuser'])) return redirect(request.referrer) @admin_bp.route('/template_select') def templateSelect(): allprograms = Program.select().order_by(Program.programName) visibleTemplates = EventTemplate.select().where(EventTemplate.isVisible==True).order_by(EventTemplate.name) return render_template("/events/template_selector.html", programs=allprograms, templates=visibleTemplates ) @admin_bp.route('/event/<templateid>/create', methods=['GET','POST']) @admin_bp.route('/event/<templateid>/<programid>/create', methods=['GET','POST']) def createEvent(templateid, programid=None): if not g.current_user.isAdmin: abort(403) # Validate given URL program = None try: template = EventTemplate.get_by_id(templateid) if programid: program = Program.get_by_id(programid) except DoesNotExist as e: print("Invalid template or program id:", e) flash("There was an error with your selection. Please try again or contact Systems Support.", "danger") return redirect(url_for("admin.program_picker")) # Get the data for the form, from the template or the form submission eventData = template.templateData if request.method == "POST": eventData = request.form.copy() if program: # TODO need to handle the multiple programs case eventData["program"] = program # Try to save the form if request.method == "POST": try: saveSuccess, validationErrorMessage = attemptSaveEvent(eventData) except Exception as e: print("Error saving event:", e) saveSuccess = False validationErrorMessage = "Unknown Error Saving Event. Please try again" if saveSuccess: noun = (eventData['isRecurring'] == 'on' and "Events" or "Event") # pluralize flash(f"{noun} successfully created!", 'success') return redirect(url_for("main.events", term = eventData['term'])) else: flash(validationErrorMessage, 'warning') # make sure our data is the same regardless of GET or POST preprocessEventData(eventData) futureTerms = selectSurroundingTerms(g.current_term) return render_template(f"/admin/{template.templateFile}", template = template, eventData = eventData, futureTerms = futureTerms, allFacilitators = getAllFacilitators()) @admin_bp.route('/event/<eventId>/edit', methods=['GET','POST']) def editEvent(eventId): if request.method == "POST" and not g.current_user.isAdmin: abort(403) # Validate given URL try: event = Event.get_by_id(eventId) except DoesNotExist as e: print(f"Unknown event: {eventId}") abort(404) eventData = model_to_dict(event, recurse=False) if request.method == "POST": # Attempt to save form eventData = request.form.copy() saveSuccess, validationErrorMessage = attemptSaveEvent(eventData) if saveSuccess: flash("Event successfully updated!", "success") return redirect(url_for("admin.editEvent", eventId = eventId)) else: flash(validationErrorMessage, 'warning') preprocessEventData(eventData) futureTerms = selectSurroundingTerms(g.current_term) userHasRSVPed = EventRsvp.get_or_none(EventRsvp.user == g.current_user, EventRsvp.event == event) isPastEvent = (datetime.now() >= datetime.combine(event.startDate, event.timeStart)) return render_template("admin/createSingleEvent.html", eventData = eventData, allFacilitators = getAllFacilitators(), futureTerms = futureTerms, isPastEvent = isPastEvent, userHasRSVPed = userHasRSVPed) @admin_bp.route('/event/<eventId>/delete', methods=['POST']) def deleteRoute(eventId): try: term = Event.get(Event.id == eventId).term deleteEvent(eventId) flash("Event removed", "success") return redirect(url_for("main.events")) except Exception as e: print('Error while canceling event:', e) return "", 500 @admin_bp.route('/makeRecurringEvents', methods=['POST']) def addRecurringEvents(): recurringEvents = calculateRecurringEventFrequency(preprocessEventData(request.form.copy())) return json.dumps(recurringEvents, default=str) @admin_bp.route('/volunteerProfile', methods=['POST']) def volunteerProfile(): volunteerName= request.form.copy() username = volunteerName['searchStudentsInput'].strip("()") user=username.split('(')[-1] return redirect(url_for('main.profilePage', username=user)) @admin_bp.route('/search_student', methods=['GET']) def studentSearchPage(): if g.current_user.isAdmin: return render_template("/searchStudentPage.html") abort(403) @admin_bp.route('/addParticipants', methods = ['GET']) def addParticipants(): '''Renders the page, will be removed once merged with full page''' return render_template('addParticipants.html', title="Add Participants") @admin_bp.route('/courseManagement', methods = ['GET', 'POST']) @admin_bp.route('/courseManagement/<term>', methods = ['GET', 'POST']) def courseManagement(term = None): ''' Renders the page for admins to manage Course Proposals ''' term = Term.get_or_none(Term.id == term) if not term: term = g.current_term pending = pendingCourses(term) approved = approvedCourses(term) terms = selectSurroundingTerms(g.current_term) return render_template('/admin/courseManagement.html', pendingCourses = pending, approvedCourses = approved, terms = terms, term = term)
4,611
0
176
a04c386a7755577c38e7b1543dff12ea31edb648
2,259
py
Python
abrir_cam.py
kbueso/Python
a18a23bbf6ba3f214c2ed751a20348fe415c6dbe
[ "MIT" ]
null
null
null
abrir_cam.py
kbueso/Python
a18a23bbf6ba3f214c2ed751a20348fe415c6dbe
[ "MIT" ]
null
null
null
abrir_cam.py
kbueso/Python
a18a23bbf6ba3f214c2ed751a20348fe415c6dbe
[ "MIT" ]
null
null
null
import cv2 as cv import functions import os cam = cv.VideoCapture(0) #Iniciando WebCam file_name = "haarcascade_frontalface_alt2.xml" classifier = cv.CascadeClassifier(f"{cv.haarcascades}{os.sep}{file_name}") #Modelo para reconhecer faces dataframe = functions.load_dataframe() #Cargando dataframe com las imagenes para entrenamiento X_train, y_train = functions.train_test(dataframe) #Dividindo conjuntos de treino e teste pca = functions.pca_model(X_train) #Modelo PCA para extracion de contornos de imagen X_train = pca.transform(X_train) #Conjunto de contornos extraídos knn = functions.knn(X_train, y_train) #Entrenando con modelo de clasificacion KNN #Rótulo de clasificaciones label = { 0: "Sin mascara", 1: "Con mascara" } #Abriendo Webcam... while True: status, frame = cam.read() #Leyendo imagen y extrayendo frame if not status: break if cv.waitKey(1) & 0xff == ord('q'): break #Transformando la imagen en escala de griz gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) #Detectando rostros en imagen faces = classifier.detectMultiScale(gray) #Iterando las caras encontradas for x,y,w,h in faces: gray_face = gray[y:y+h, x:x+w] #Recortando region de la cara if gray_face.shape[0] >= 200 and gray_face.shape[1] >= 200: gray_face = cv.resize(gray_face, (160,160)) #Redimensionando vector = pca.transform([gray_face.flatten()]) #Extrayendo contornos de la imagem pred = knn.predict(vector)[0] #Clasificando la imagen classification = label[pred] #Mostrando rectangulos alrededor del rostro if pred == 0: cv.rectangle(frame, (x,y), (x+w, y+h), (0,0,255), 3) print("\a") elif pred == 1: cv.rectangle(frame, (x,y), (x+w, y+h), (0,255,0), 3) #Escribiendo clasificacion y cantidad de rostros vistos cv.putText(frame, classification, (x - 20,y + h + 50), cv.FONT_HERSHEY_SIMPLEX, 0.5, (255,0,0), 2, cv.LINE_AA) cv.putText(frame, f"{len(faces)} rostros identificados",(20,20), cv.FONT_HERSHEY_SIMPLEX, 0.5, (255,0,0), 2, cv.LINE_AA) #Mostrando frame cv.imshow("Cam", frame)
35.296875
132
0.654714
import cv2 as cv import functions import os cam = cv.VideoCapture(0) #Iniciando WebCam file_name = "haarcascade_frontalface_alt2.xml" classifier = cv.CascadeClassifier(f"{cv.haarcascades}{os.sep}{file_name}") #Modelo para reconhecer faces dataframe = functions.load_dataframe() #Cargando dataframe com las imagenes para entrenamiento X_train, y_train = functions.train_test(dataframe) #Dividindo conjuntos de treino e teste pca = functions.pca_model(X_train) #Modelo PCA para extracion de contornos de imagen X_train = pca.transform(X_train) #Conjunto de contornos extraídos knn = functions.knn(X_train, y_train) #Entrenando con modelo de clasificacion KNN #Rótulo de clasificaciones label = { 0: "Sin mascara", 1: "Con mascara" } #Abriendo Webcam... while True: status, frame = cam.read() #Leyendo imagen y extrayendo frame if not status: break if cv.waitKey(1) & 0xff == ord('q'): break #Transformando la imagen en escala de griz gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) #Detectando rostros en imagen faces = classifier.detectMultiScale(gray) #Iterando las caras encontradas for x,y,w,h in faces: gray_face = gray[y:y+h, x:x+w] #Recortando region de la cara if gray_face.shape[0] >= 200 and gray_face.shape[1] >= 200: gray_face = cv.resize(gray_face, (160,160)) #Redimensionando vector = pca.transform([gray_face.flatten()]) #Extrayendo contornos de la imagem pred = knn.predict(vector)[0] #Clasificando la imagen classification = label[pred] #Mostrando rectangulos alrededor del rostro if pred == 0: cv.rectangle(frame, (x,y), (x+w, y+h), (0,0,255), 3) print("\a") elif pred == 1: cv.rectangle(frame, (x,y), (x+w, y+h), (0,255,0), 3) #Escribiendo clasificacion y cantidad de rostros vistos cv.putText(frame, classification, (x - 20,y + h + 50), cv.FONT_HERSHEY_SIMPLEX, 0.5, (255,0,0), 2, cv.LINE_AA) cv.putText(frame, f"{len(faces)} rostros identificados",(20,20), cv.FONT_HERSHEY_SIMPLEX, 0.5, (255,0,0), 2, cv.LINE_AA) #Mostrando frame cv.imshow("Cam", frame)
0
0
0
d2a0ec8516b7c6d8905c9cf4d37d838a8a61333c
1,911
py
Python
app/images.py
jkpawlowski96/Web-scraper
5b6db52198b10e6de619a4db7e5a1ba652e98c45
[ "MIT" ]
1
2021-05-16T16:30:37.000Z
2021-05-16T16:30:37.000Z
app/images.py
jkpawlowski96/Web-scraper
5b6db52198b10e6de619a4db7e5a1ba652e98c45
[ "MIT" ]
null
null
null
app/images.py
jkpawlowski96/Web-scraper
5b6db52198b10e6de619a4db7e5a1ba652e98c45
[ "MIT" ]
null
null
null
from PIL import Image import urllib.request as request import requests from io import BytesIO, StringIO from bs4 import BeautifulSoup import numpy as np def get_images_links(address): """ Scrap website from images links :param address: website address example: https://www.youtube.com/ :return: images links """ page = request.urlopen(address) # html soup = BeautifulSoup(page, 'html.parser') tags = soup.findAll('img') # all images print(tags) images = [] # scrap from images links in a look for img in tags: try: images.append(img['src']) except: pass return images def get_images_bytes(links): """ Transform images links into bytes format to load as Pillow object later :param address: list of images links :return: images as bytes """ images = [] # transform to bytes in a look for link in links: try: img = image_from_url(link) # download as Pillow object img = image_to_bytes(img) # transform into bytes format as a universal solution images.append(img) # add except: pass return images def image_from_url(url): """ Download image from url :param url: url of image :return: image Pillow object """ response = requests.get(url) return Image.open(BytesIO(response.content)) def image_to_bytes(image: Image): """ Transform image to bytes format :param image: image Pillow object :return: bytes """ imgByteArr = BytesIO() image.save(imgByteArr, format=image.format) imgByteArr = imgByteArr.getvalue() return imgByteArr def bytes_to_image(bytes): """ Inverse transform of bytes into image (To use for others) :param bytes: mage in bytes format :return: image Pillow object """ return Image.open(BytesIO(bytes))
24.818182
92
0.644689
from PIL import Image import urllib.request as request import requests from io import BytesIO, StringIO from bs4 import BeautifulSoup import numpy as np def get_images_links(address): """ Scrap website from images links :param address: website address example: https://www.youtube.com/ :return: images links """ page = request.urlopen(address) # html soup = BeautifulSoup(page, 'html.parser') tags = soup.findAll('img') # all images print(tags) images = [] # scrap from images links in a look for img in tags: try: images.append(img['src']) except: pass return images def get_images_bytes(links): """ Transform images links into bytes format to load as Pillow object later :param address: list of images links :return: images as bytes """ images = [] # transform to bytes in a look for link in links: try: img = image_from_url(link) # download as Pillow object img = image_to_bytes(img) # transform into bytes format as a universal solution images.append(img) # add except: pass return images def image_from_url(url): """ Download image from url :param url: url of image :return: image Pillow object """ response = requests.get(url) return Image.open(BytesIO(response.content)) def image_to_bytes(image: Image): """ Transform image to bytes format :param image: image Pillow object :return: bytes """ imgByteArr = BytesIO() image.save(imgByteArr, format=image.format) imgByteArr = imgByteArr.getvalue() return imgByteArr def bytes_to_image(bytes): """ Inverse transform of bytes into image (To use for others) :param bytes: mage in bytes format :return: image Pillow object """ return Image.open(BytesIO(bytes))
0
0
0
436633cf53bf232151db89075191af639502c428
1,770
py
Python
ck/connection/http.py
hczhcz/PyCK
6a635c0bd911bef413400ae348e38ea5e85c4e6b
[ "MIT" ]
3
2020-03-19T10:10:20.000Z
2020-12-26T10:53:37.000Z
ck/connection/http.py
hczhcz/PyCK
6a635c0bd911bef413400ae348e38ea5e85c4e6b
[ "MIT" ]
null
null
null
ck/connection/http.py
hczhcz/PyCK
6a635c0bd911bef413400ae348e38ea5e85c4e6b
[ "MIT" ]
3
2020-11-05T02:42:38.000Z
2021-03-24T06:39:41.000Z
import http.client import threading import typing
23.918919
74
0.567232
import http.client import threading import typing def run_http( host: str, port: int, path: str, headers: typing.Dict[str, str], gen_stdin: typing.Generator[bytes, None, None], gen_stdout: typing.Generator[None, bytes, None], gen_stderr: typing.Generator[None, bytes, None], buffer_size: int = 1 << 20, join_interval: float = 0.1 ) -> typing.Callable[[], int]: connection = None response = None error = None # create thread def post_request() -> None: nonlocal connection nonlocal response nonlocal error try: connection = http.client.HTTPConnection(host, port) connection.request('POST', path, gen_stdin, headers) response = connection.getresponse() if response.status == 200: gen_out = gen_stdout else: gen_out = gen_stderr next(gen_stdout) next(gen_stderr) data = response.read(buffer_size) while data: gen_out.send(data) data = response.read(buffer_size) gen_stdout.send(b'') gen_stderr.send(b'') except BaseException as raw_error: # pylint: disable=broad-except error = raw_error thread = threading.Thread(target=post_request) thread.start() # join thread def join() -> int: while error is None and thread.is_alive(): thread.join(join_interval) if error is not None: if connection: connection.close() raise error # pylint: disable=raising-bad-type assert response return response.status return join
1,696
0
23
976023701895aae99b62d02a4f829bb4c063b92c
7,200
py
Python
model/dsc.py
Mhaiyang/iccv
04a8ee52c2323d7ff5cdf03c0be1466e8180d2eb
[ "MIT" ]
2
2019-01-10T03:44:03.000Z
2019-05-24T08:50:14.000Z
model/dsc.py
Mhaiyang/iccv
04a8ee52c2323d7ff5cdf03c0be1466e8180d2eb
[ "MIT" ]
null
null
null
model/dsc.py
Mhaiyang/iccv
04a8ee52c2323d7ff5cdf03c0be1466e8180d2eb
[ "MIT" ]
null
null
null
""" @Time : 2019-1-9 04:41 @Author : TaylorMei @Email : mhy845879017@gmail.com @Project : iccv @File : dsc.py @Function: """ import torch import torch.nn.functional as F from torch import nn from backbone.resnext.resnext101_regular import ResNeXt101 # Module Function # Module Class # Network Class
38.709677
114
0.650833
""" @Time : 2019-1-9 04:41 @Author : TaylorMei @Email : mhy845879017@gmail.com @Project : iccv @File : dsc.py @Function: """ import torch import torch.nn.functional as F from torch import nn from backbone.resnext.resnext101_regular import ResNeXt101 # Module Function # Module Class class LayerConv(nn.Module): def __init__(self, in_planes, out_planes, kernel_size, stride, padding, relu): super(LayerConv, self).__init__() self.conv = nn.Conv2d(in_channels=in_planes, out_channels=out_planes, kernel_size=kernel_size, stride=stride, padding=padding) self.relu = nn.ReLU() if relu else None def forward(self, x): x = self.conv(x) if self.relu is not None: x = self.relu(x) return x class GlobalConv(nn.Module): def __init__(self, in_planes, out_planes, kernel_size, stride, padding, relu): super(GlobalConv, self).__init__() self.conv = nn.Conv2d(in_channels=in_planes, out_channels=out_planes, kernel_size=kernel_size, stride=stride, padding=padding) self.relu = nn.ReLU() if relu else None def forward(self, x): x = self.conv(x) if self.relu is not None: x = self.relu(x) return x class Predict(nn.Module): def __init__(self, in_planes=32, out_planes=1, kernel_size=1): super(Predict, self).__init__() self.conv = nn.Conv2d(in_planes, out_planes, kernel_size) def forward(self, x): y = self.conv(x) return y # Network Class class DSC(nn.Module): def __init__(self): super(DSC, self).__init__() resnext = ResNeXt101() self.layer0 = resnext.layer0 self.layer1 = resnext.layer1 self.layer2 = resnext.layer2 self.layer3 = resnext.layer3 self.layer4 = resnext.layer4 self.layer4_conv1 = LayerConv(2048, 1024, 7, 1, 3, True) self.layer4_conv2 = LayerConv(1024, 1024, 7, 1, 3, True) self.layer4_conv3 = LayerConv(1024, 32, 1, 1, 0, False) self.layer3_conv1 = LayerConv(1024, 512, 5, 1, 2, True) self.layer3_conv2 = LayerConv(512, 512, 5, 1, 2, True) self.layer3_conv3 = LayerConv(512, 32, 1, 1, 0, False) self.layer2_conv1 = LayerConv(512, 256, 5, 1, 2, True) self.layer2_conv2 = LayerConv(256, 256, 5, 1, 2, True) self.layer2_conv3 = LayerConv(256, 32, 1, 1, 0, False) self.layer1_conv1 = LayerConv(256, 128, 3, 1, 1, True) self.layer1_conv2 = LayerConv(128, 128, 3, 1, 1, True) self.layer1_conv3 = LayerConv(128, 32, 1, 1, 0, False) self.layer0_conv1 = LayerConv(64, 128, 3, 1, 1, True) self.layer0_conv2 = LayerConv(128, 128, 3, 1, 1, True) self.layer0_conv3 = LayerConv(128, 32, 1, 1, 0, False) self.relu = nn.ReLU() self.global_conv = GlobalConv(160, 32, 1, 1, 0, True) self.layer4_predict = Predict(32, 1, 1) self.layer3_predict_ori = Predict(32, 1, 1) self.layer3_predict = Predict(2, 1, 1) self.layer2_predict_ori = Predict(32, 1, 1) self.layer2_predict = Predict(3, 1, 1) self.layer1_predict_ori = Predict(32, 1, 1) self.layer1_predict = Predict(4, 1, 1) self.layer0_predict_ori = Predict(32, 1, 1) self.layer0_predict = Predict(5, 1, 1) self.global_predict = Predict(32, 1, 1) self.fusion_predict = Predict(6, 1, 1) for m in self.modules(): if isinstance(m, nn.ReLU): m.inplace = True def forward(self, x): layer0 = self.layer0(x) layer1 = self.layer1(layer0) layer2 = self.layer2(layer1) layer3 = self.layer3(layer2) layer4 = self.layer4(layer3) layer4_conv1 = self.layer4_conv1(layer4) layer4_conv2 = self.layer4_conv2(layer4_conv1) layer4_conv3 = self.layer4_conv3(layer4_conv2) layer4_up = F.upsample(layer4_conv3, size=x.size()[2:], mode='bilinear', align_corners=True) layer4_up = self.relu(layer4_up) layer3_conv1 = self.layer3_conv1(layer3) layer3_conv2 = self.layer3_conv2(layer3_conv1) layer3_conv3 = self.layer3_conv3(layer3_conv2) layer3_up = F.upsample(layer3_conv3, size=x.size()[2:], mode='bilinear', align_corners=True) layer3_up = self.relu(layer3_up) layer2_conv1 = self.layer2_conv1(layer2) layer2_conv2 = self.layer2_conv2(layer2_conv1) layer2_conv3 = self.layer2_conv3(layer2_conv2) layer2_up = F.upsample(layer2_conv3, size=x.size()[2:], mode='bilinear', align_corners=True) layer2_up = self.relu(layer2_up) layer1_conv1 = self.layer1_conv1(layer1) layer1_conv2 = self.layer1_conv2(layer1_conv1) layer1_conv3 = self.layer1_conv3(layer1_conv2) layer1_up = F.upsample(layer1_conv3, size=x.size()[2:], mode='bilinear', align_corners=True) layer1_up = self.relu(layer1_up) layer0_conv1 = self.layer0_conv1(layer0) layer0_conv2 = self.layer0_conv2(layer0_conv1) layer0_conv3 = self.layer0_conv3(layer0_conv2) layer0_up = F.upsample(layer0_conv3, size=x.size()[2:], mode='bilinear', align_corners=True) layer0_up = self.relu(layer0_up) global_concat = torch.cat((layer0_up, layer1_up, layer2_up, layer3_up, layer4_up), 1) global_conv = self.global_conv(global_concat) layer4_predict = self.layer4_predict(layer4_up) layer3_predict_ori = self.layer3_predict_ori(layer3_up) layer3_concat = torch.cat((layer3_predict_ori, layer4_predict), 1) layer3_predict = self.layer3_predict(layer3_concat) layer2_predict_ori = self.layer2_predict_ori(layer2_up) layer2_concat = torch.cat((layer2_predict_ori, layer3_predict_ori, layer4_predict), 1) layer2_predict = self.layer2_predict(layer2_concat) layer1_predict_ori = self.layer1_predict_ori(layer1_up) layer1_concat = torch.cat((layer1_predict_ori, layer2_predict_ori, layer3_predict_ori, layer4_predict), 1) layer1_predict = self.layer1_predict(layer1_concat) layer0_predict_ori = self.layer0_predict_ori(layer0_up) layer0_concat = torch.cat((layer0_predict_ori, layer1_predict_ori, layer2_predict_ori, layer3_predict_ori, layer4_predict), 1) layer0_predict = self.layer0_predict(layer0_concat) global_predict = self.global_predict(global_conv) # fusion fusion_concat = torch.cat((layer0_predict, layer1_predict, layer2_predict, layer3_predict, layer4_predict, global_predict), 1) fusion_predict = self.fusion_predict(fusion_concat) if self.training: return layer4_predict, layer3_predict, layer2_predict, layer1_predict, layer0_predict, \ global_predict, fusion_predict return F.sigmoid(layer4_predict), F.sigmoid(layer3_predict), F.sigmoid(layer2_predict), \ F.sigmoid(layer1_predict), F.sigmoid(layer0_predict), F.sigmoid(global_predict), \ F.sigmoid(fusion_predict)
6,545
17
302
e2b1f43d3ecbc2dea164169f5ea8f19cfc51fd32
756
py
Python
utils/discriminators/DiscriminatorGAN.py
ynakaDream/Deep-Learning-GANs
2e00405079c131245f4dd23eb494a27a2b12598d
[ "MIT" ]
4
2019-01-14T04:38:51.000Z
2020-02-13T20:38:10.000Z
utils/discriminators/DiscriminatorGAN.py
ynakaDream/Deep-Learning-GANs
2e00405079c131245f4dd23eb494a27a2b12598d
[ "MIT" ]
null
null
null
utils/discriminators/DiscriminatorGAN.py
ynakaDream/Deep-Learning-GANs
2e00405079c131245f4dd23eb494a27a2b12598d
[ "MIT" ]
null
null
null
import torch.nn as nn import torch.nn.functional as F
31.5
57
0.596561
import torch.nn as nn import torch.nn.functional as F class DiscriminatorGAN(nn.Module): def __init__(self, input, output): super().__init__() self.fc1 = nn.Linear(input, 128) self.fc2 = nn.Linear(128, 256) self.fc3 = nn.Linear(256, 512) self.fc4 = nn.Linear(512, 1024) self.fc5 = nn.Linear(1024, output) self.sig = nn.Sigmoid() def forward(self, x): x = x.view(x.size(0), -1) x = F.leaky_relu(self.fc1(x), negative_slope=0.2) x = F.leaky_relu(self.fc2(x), negative_slope=0.2) x = F.leaky_relu(self.fc3(x), negative_slope=0.2) x = F.leaky_relu(self.fc4(x), negative_slope=0.2) output = self.sig(self.fc5(x)) return output.squeeze()
612
13
76
3dffd45d760d1e054befe2d05fa6f64fc356cc1e
41
py
Python
thread-renderer/src/generating/__init__.py
FToovvr/adnmb-quests-tools
eb3c594cb94ff803edde4705ab67e8de060c7efb
[ "MIT" ]
null
null
null
thread-renderer/src/generating/__init__.py
FToovvr/adnmb-quests-tools
eb3c594cb94ff803edde4705ab67e8de060c7efb
[ "MIT" ]
null
null
null
thread-renderer/src/generating/__init__.py
FToovvr/adnmb-quests-tools
eb3c594cb94ff803edde4705ab67e8de060c7efb
[ "MIT" ]
null
null
null
from .generating import OutputsGenerator
20.5
40
0.878049
from .generating import OutputsGenerator
0
0
0
e1e1b6141776eb67390f56f962e945f8ae672af2
735
py
Python
NitrotypePy/api/access.py
RangerEmerald/NitrotypePy
b68e9ce8918708778def249c2f57ffc49926d805
[ "MIT" ]
1
2022-02-02T03:06:58.000Z
2022-02-02T03:06:58.000Z
NitrotypePy/api/access.py
RangerEmerald/NitrotypePy
b68e9ce8918708778def249c2f57ffc49926d805
[ "MIT" ]
null
null
null
NitrotypePy/api/access.py
RangerEmerald/NitrotypePy
b68e9ce8918708778def249c2f57ffc49926d805
[ "MIT" ]
null
null
null
try: import cloudscraper except ModuleNotFoundError: raise ModuleNotFoundError("Unable to load cloudscraper") def access(endpoint=""): """The function used to access the entirety of nitrotype. Endpoint -------- https://www.nitrotype.com/{endpoint} endpoint : str The end url to access. Returns ------- str A string of the html of the webpage, or of a json from the api. """ base_url = "https://www.nitrotype.com/" scraper = None try: scraper = cloudscraper.create_scraper() except: scraper = cloudscraper.CloudScraper() finally: if scraper: return scraper.get(base_url + str(endpoint)).text return False
21.617647
71
0.619048
try: import cloudscraper except ModuleNotFoundError: raise ModuleNotFoundError("Unable to load cloudscraper") def access(endpoint=""): """The function used to access the entirety of nitrotype. Endpoint -------- https://www.nitrotype.com/{endpoint} endpoint : str The end url to access. Returns ------- str A string of the html of the webpage, or of a json from the api. """ base_url = "https://www.nitrotype.com/" scraper = None try: scraper = cloudscraper.create_scraper() except: scraper = cloudscraper.CloudScraper() finally: if scraper: return scraper.get(base_url + str(endpoint)).text return False
0
0
0
6de67a6f2629812232468239d97bf3449d0dd06f
953
py
Python
example/backend/migrations/0006_auto_20211122_0910.py
martimarkov/django-ajax-datatable
d132504a199cb2afe2cfd74a2e6d5d5f2969c4a4
[ "MIT" ]
1
2021-11-19T13:36:30.000Z
2021-11-19T13:36:30.000Z
example/backend/migrations/0006_auto_20211122_0910.py
martimarkov/django-ajax-datatable
d132504a199cb2afe2cfd74a2e6d5d5f2969c4a4
[ "MIT" ]
null
null
null
example/backend/migrations/0006_auto_20211122_0910.py
martimarkov/django-ajax-datatable
d132504a199cb2afe2cfd74a2e6d5d5f2969c4a4
[ "MIT" ]
null
null
null
# Generated by Django 3.0.8 on 2021-11-22 09:10 from django.db import migrations, models
30.741935
127
0.559286
# Generated by Django 3.0.8 on 2021-11-22 09:10 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('backend', '0005_auto_20210606_0651'), ] operations = [ migrations.CreateModel( name='Tag2', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(choices=[('rock', 'Rock'), ('pop', 'Pop'), ('new-age', 'New Age')], max_length=256)), ], ), migrations.AlterField( model_name='track', name='tags', field=models.ManyToManyField(blank=True, to='backend.Tag'), ), migrations.AddField( model_name='track', name='tags2', field=models.ManyToManyField(blank=True, to='backend.Tag2', verbose_name='tags w/choices'), ), ]
0
839
23
93f832cdbf2242b47ab3b0ac7e517856e501a723
16,675
py
Python
ChecklistPanel.py
bopopescu/Lauecollect
60ae2b05ea8596ba0decf426e37aeaca0bc8b6be
[ "MIT" ]
null
null
null
ChecklistPanel.py
bopopescu/Lauecollect
60ae2b05ea8596ba0decf426e37aeaca0bc8b6be
[ "MIT" ]
1
2019-10-22T21:28:31.000Z
2019-10-22T21:39:12.000Z
ChecklistPanel.py
bopopescu/Lauecollect
60ae2b05ea8596ba0decf426e37aeaca0bc8b6be
[ "MIT" ]
2
2019-06-06T15:06:46.000Z
2020-07-20T02:03:22.000Z
#!/usr/bin/env python """Controls when data collection is suspended, in case the X-ray beam is down Friedrich Schotte, Date created: 2017-02-24 Date last modified: 2018-03-15 """ __version__ = "1.2.9" # logging from checklist import checklist import wx, wx3_compatibility from EditableControls import TextCtrl,ComboBox from logging import debug,info,warn,error if __name__ == '__main__': from pdb import pm import logging from tempfile import gettempdir logging.basicConfig( level=logging.DEBUG, format="%(asctime)s %(levelname)s %(module)s.%(funcName)s: %(message)s", filename=gettempdir()+"/ChecklistPanel.log", ) import autoreload # Needed to initialize WX library app = wx.App(redirect=False) ChecklistPanel() app.MainLoop()
36.487965
86
0.610735
#!/usr/bin/env python """Controls when data collection is suspended, in case the X-ray beam is down Friedrich Schotte, Date created: 2017-02-24 Date last modified: 2018-03-15 """ __version__ = "1.2.9" # logging from checklist import checklist import wx, wx3_compatibility from EditableControls import TextCtrl,ComboBox from logging import debug,info,warn,error class ChecklistPanel(wx.Frame): name = "ChecklistPanel" from persistent_property import persistent_property from collections import OrderedDict as odict AllView = range(0,20) CustomView = persistent_property("CustomView",range(0,20)) views = odict([("All","AllView"),("Custom","CustomView")]) view = persistent_property("view","All") attributes = ["OK"] refresh_period = 1.0 # s def __init__(self,parent=None,title="Suspend Checklist"): wx.Frame.__init__(self,parent=parent,title=title) from Icon import SetIcon SetIcon(self,"Checklist") # Controls self.panel = wx.Panel(self) self.controls = [] # Menus menuBar = wx.MenuBar() self.ViewMenu = wx.Menu() for i in range(0,len(self.views)): self.ViewMenu.AppendCheckItem(10+i,self.views.keys()[i]) self.ViewMenu.AppendSeparator() menuBar.Append (self.ViewMenu,"&View") menu = wx.Menu() menu.AppendCheckItem(200,"Setup") menu.AppendSeparator() menu.Append(201,"Add Line") menu.Append(202,"Remove Line") menuBar.Append(menu,"&More") menu = wx.Menu() menu.Append(wx.ID_ABOUT,"About...") menuBar.Append(menu,"&Help") self.SetMenuBar(menuBar) # Callbacks self.Bind(wx.EVT_MENU_OPEN,self.OnOpenView) for i in range(0,len(self.views)): self.Bind(wx.EVT_MENU,self.OnSelectView,id=10+i) self.Bind(wx.EVT_MENU,self.OnSetup,id=200) self.Bind(wx.EVT_MENU,self.OnAdd,id=201) self.Bind(wx.EVT_MENU,self.OnRemove,id=202) self.Bind(wx.EVT_MENU,self.OnAbout,id=wx.ID_ABOUT) self.Bind(wx.EVT_CLOSE,self.OnClose) # Layout self.sizer = wx.BoxSizer(wx.VERTICAL) self.panel.SetSizer(self.sizer) self.update_controls() self.Show() # Refresh from numpy import nan self.values = {"OK": nan} self.old_values = {} self.Bind(wx.EVT_TIMER,self.OnUpdate) from threading import Thread self.thread = Thread(target=self.keep_updated,name=self.name) self.thread.start() def keep_updated(self): """Periodically refresh the displayed settings.""" from time import time,sleep while True: try: t0 = time() while time() < t0+self.refresh_period: sleep(0.1) if self.Shown: self.update_data() if self.data_changed: event = wx.PyCommandEvent(wx.EVT_TIMER.typeId,self.Id) # call OnUpdate in GUI thread wx.PostEvent(self.EventHandler,event) except wx.PyDeadObjectError: break def refresh(self): """Force update""" from threading import Thread self.thread = Thread(target=self.refresh_background,name=self.name+".refresh") self.thread.start() def refresh_background(self): """Force update""" self.update_data() if self.data_changed: event = wx.PyCommandEvent(wx.EVT_TIMER.typeId,self.Id) wx.PostEvent(self.EventHandler,event) # call OnUpdate in GUI thread def update_data(self): """Retreive status information""" self.old_values = dict(self.values) # make a copy for n in self.attributes: self.values[n] = getattr(checklist,n) @property def data_changed(self): """Did the last 'update_data' change the data to be plotted?""" changed = (self.values != self.old_values) return changed def OnUpdate(self,event): """Periodically refresh the displayed settings.""" self.refresh_status() def refresh_status(self,event=None): """Update title to show whether all checks passed""" from numpy import isnan OK = self.values["OK"] status = "?" if isnan(OK) else "OK" if OK else "not OK" self.Title = self.Title.split(":")[0]+": %s" % status def update_controls(self): if len(self.controls) != checklist.N: for control in self.controls: control.Destroy() ##self.sizer.DeleteWindows() # not compatible with wx 4.0 self.controls = [] for i in range(checklist.N): self.controls += [ChecklistControl(self.panel,i)] for i in range(0,len(self.controls)): self.sizer.Add(self.controls[i],flag=wx.ALL|wx.EXPAND,proportion=1) self.panel.Sizer.Fit(self) if not self.view in self.views: self.view = self.views.keys()[0] self.View = getattr(self,self.views[self.view]) def get_View(self): """Which control to show? List of 0-based integers""" view = [i for (i,c) in enumerate(self.controls) if c.Shown] return view def set_View(self,value): currently_shown = [c.Shown for c in self.controls] shown = [False]*len(self.controls) for i in value: if i < len(shown): shown[i] = True if shown != currently_shown: for i in range(0,len(self.controls)): self.controls[i].Shown = shown[i] self.panel.Sizer.Fit(self) View = property(get_View,set_View) def OnOpenView(self,event): """Called if the "View" menu is selected""" for i in range(0,len(self.views)): self.ViewMenu.Check(10+i,self.views.keys()[i] == self.view) for i in range(0,len(self.controls)): try: self.ViewMenu.Remove(100+i) except: pass self.ViewMenu.AppendCheckItem(100+i,self.controls[i].Title) self.ViewMenu.Check(100+i,self.controls[i].Shown) self.ViewMenu.Enable(100+i,self.view != "All") self.Bind(wx.EVT_MENU,self.OnView,id=100+i) def OnSelectView(self,event): """Called if the view is toogled between 'All' and 'Custome' from the 'View ' menu.""" n = event.Id-10 self.view = self.views.keys()[n] self.View = getattr(self,self.views.values()[n]) def OnView(self,event): """Called if one of the items of the "View" menu is checked or unchecked.""" n = event.Id-100 self.controls[n].Shown = event.Checked() self.panel.Sizer.Fit(self) setattr(self,self.views[self.view],self.View) # save modified view def OnSetup(self,event): """Enable 'setup' mode, allowing the panel to be configured""" for control in self.controls: control.setup = event.Checked() self.panel.Sizer.Fit(self) def OnAdd(self,event): checklist.N += 1 self.update_controls() def OnRemove(self,event): if checklist.N > 0: checklist.N -= 1 self.update_controls() def OnAbout(self,event): """Show panel with additional parameters""" from os.path import basename from inspect import getfile from os.path import getmtime from datetime import datetime filename = getfile(lambda x: None) info = basename(filename)+" "+__version__ import checklist as module filename = getfile(module) if hasattr(module,"__source_timestamp__"): timestamp = module.__source_timestamp__ filename = filename.replace(".pyc",".py") else: timestamp = getmtime(getfile(module)) info += "\n"+basename(filename)+" "+module.__version__ info += " ("+str(datetime.fromtimestamp(timestamp))+")" info += "\nwx "+wx.__version__ info += "\n\n"+__doc__ dlg = wx.MessageDialog(self,info,"About",wx.OK|wx.ICON_INFORMATION) dlg.CenterOnParent() dlg.ShowModal() dlg.Destroy() def OnClose(self,event): """Called when the windows's close button is clicked""" self.Destroy() class ChecklistControl(wx.Panel): name = "ChecklistControl" attributes = "formatted_value","OK","test_code_OK" refresh_period = 1.0 def __init__(self,parent,n): self.values = {"formatted_value":"","OK":True,"test_code_OK":False} self.old_values = {} wx.Panel.__init__(self,parent) self.Title = "Test %d" % n self.n = n self.myEnabled = wx.CheckBox(self,size=(320,-1)) from wx.lib.buttons import GenButton self.State = GenButton(self,size=(25,20)) self.Setup = wx.Button(self,size=(60,-1),label="More...") self.Setup.Shown = False self.Bind(wx.EVT_CHECKBOX,self.OnEnable,self.myEnabled) self.Bind(wx.EVT_BUTTON,self.OnSetup,self.State) self.Bind(wx.EVT_BUTTON,self.OnSetup,self.Setup) # Layout self.layout = wx.BoxSizer(wx.HORIZONTAL) flag = wx.ALL|wx.ALIGN_CENTER_VERTICAL|wx.EXPAND self.layout.Add(self.myEnabled,flag=flag,proportion=1) self.layout.Add(self.State,flag=flag) self.layout.Add(self.Setup,flag=flag) # Leave a 10 pixel wide border. self.box = wx.BoxSizer(wx.VERTICAL) self.box.Add(self.layout,flag=wx.ALL,border=5) self.SetSizer(self.box) self.Fit() self.refresh_label() # Periodically refresh the displayed settings. self.Bind(wx.EVT_TIMER,self.OnUpdate) from threading import Thread self.thread = Thread(target=self.keep_updated,name=self.name) self.thread.start() def keep_updated(self): """Periodically refresh the displayed settings.""" from time import time,sleep while True: try: t0 = time() while time() < t0+self.refresh_period: sleep(0.1) if self.Shown: self.update_data() if self.data_changed: event = wx.PyCommandEvent(wx.EVT_TIMER.typeId,self.Id) # call OnUpdate in GUI thread wx.PostEvent(self.EventHandler,event) except wx.PyDeadObjectError: break def refresh(self): """Force update""" from threading import Thread self.thread = Thread(target=self.refresh_background,name=self.name+".refresh") self.thread.start() def refresh_background(self): """Force update""" self.update_data() if self.data_changed: event = wx.PyCommandEvent(wx.EVT_TIMER.typeId,self.Id) wx.PostEvent(self.EventHandler,event) # call OnUpdate in GUI thread def update_data(self): """Retreive status information""" self.old_values = dict(self.values) # make a copy for n in self.attributes: self.values[n] = getattr(checklist.test(self.n),n) @property def data_changed(self): """Did the last 'update_data' change the data to be plotted?""" changed = (self.values != self.old_values) return changed def OnUpdate(self,event): """Periodically refresh the displayed settings.""" self.refresh_status() def refresh_label(self,event=None): """Update the controls with current values""" self.Title = checklist.test(self.n).label self.myEnabled.Value = checklist.test(self.n).enabled self.myEnabled.Label = checklist.test(self.n).label def refresh_status(self,event=None): """Update the controls with current values""" red = (255,0,0) green = (0,255,0) gray = (180,180,180) label = checklist.test(self.n).label self.myEnabled.Label = "%s: %s" % (label,self.values["formatted_value"]) color = green if self.values["OK"] else red if not self.values["test_code_OK"]: color = gray self.State.BackgroundColour = color self.State.ForegroundColour = color self.State.Refresh() # work-around for a GenButton bug in Windows def OnEnable(self,event): checklist.test(self.n).enabled = event.Checked() self.refresh() def get_setup(self): """'Setup' mode enabled? (Allows reconfiguring parameters)""" value = self.Setup.Shown return value def set_setup(self,value): self.Setup.Shown = value self.Layout() self.Fit() setup = property(get_setup,set_setup) def OnSetup(self,event): """""" dlg = SetupPanel(self,self.n) dlg.CenterOnParent() dlg.Show() class SetupPanel(wx.Frame): def __init__(self,parent,n): self.n = n wx.Frame.__init__(self,parent=parent,title="Setup") self.panel = wx.Panel(self) # Controls style = wx.TE_PROCESS_ENTER self.myLabel = ComboBox(self.panel,size=(320,-1),style=style) self.Value = ComboBox(self.panel,size=(320,-1),style=style) self.Format = ComboBox(self.panel,size=(320,-1),style=style) self.Test = ComboBox(self.panel,size=(320,-1),style=style) # Callbacks self.Bind (wx.EVT_COMBOBOX,self.OnLabel,self.myLabel) self.Bind (wx.EVT_TEXT_ENTER,self.OnLabel,self.myLabel) self.Bind (wx.EVT_COMBOBOX,self.OnValue,self.Value) self.Bind (wx.EVT_TEXT_ENTER,self.OnValue,self.Value) self.Bind (wx.EVT_COMBOBOX,self.OnFormat,self.Format) self.Bind (wx.EVT_TEXT_ENTER,self.OnFormat,self.Format) self.Bind (wx.EVT_COMBOBOX,self.OnTest,self.Test) self.Bind (wx.EVT_TEXT_ENTER,self.OnTest,self.Test) self.Bind (wx.EVT_SIZE,self.OnResize) # Layout self.layout = wx.BoxSizer() grid = wx.FlexGridSizer(cols=2,hgap=5,vgap=5) flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL|wx.EXPAND label = "Label:" grid.Add(wx.StaticText(self.panel,label=label),flag=flag) grid.Add(self.myLabel,flag=flag,proportion=1) label = "Value:" grid.Add(wx.StaticText(self.panel,label=label),flag=flag) grid.Add(self.Value,flag=flag,proportion=1) label = "Format:" grid.Add(wx.StaticText(self.panel,label=label),flag=flag) grid.Add(self.Format,flag=flag,proportion=1) label = "Test:" grid.Add(wx.StaticText(self.panel,label=label),flag=flag) grid.Add(self.Test,flag=flag,proportion=1) # Leave a 10-pixel wide space around the panel. self.layout.Add(grid,flag=wx.EXPAND|wx.ALL,proportion=1,border=10) self.panel.SetSizer(self.layout) self.panel.Fit() self.Fit() # Intialization labels,values,formats,tests = [],[],[],[] for label in checklist.defaults: labels += [label] values += [checklist.defaults[label]["value"]] formats += [checklist.defaults[label]["format"]] tests += [checklist.defaults[label]["test"]] self.myLabel.Items = labels self.Value.Items = values self.Format.Items = formats self.Test.Items = tests self.refresh() def refresh(self,Event=0): self.myLabel.Value = checklist.test(self.n).label self.Value.Value = checklist.test(self.n).value_code self.Format.Value = checklist.test(self.n).format self.Test.Value = checklist.test(self.n).test_code def OnLabel(self,event): checklist.test(self.n).label = self.myLabel.Value self.refresh() def OnValue(self,event): checklist.test(self.n).value_code = self.Value.Value self.refresh() def OnFormat(self,event): checklist.test(self.n).format = self.Format.Value self.refresh() def OnTest(self,event): checklist.test(self.n).test_code = self.Test.Value self.refresh() def OnResize(self,event): """Rearange contents to fit best into new size""" self.panel.Fit() event.Skip() if __name__ == '__main__': from pdb import pm import logging from tempfile import gettempdir logging.basicConfig( level=logging.DEBUG, format="%(asctime)s %(levelname)s %(module)s.%(funcName)s: %(message)s", filename=gettempdir()+"/ChecklistPanel.log", ) import autoreload # Needed to initialize WX library app = wx.App(redirect=False) ChecklistPanel() app.MainLoop()
7,469
8,329
69
60ac941679c0f11de1c3686002d8acf273e59fd2
21,830
py
Python
PrevendoCustomerChurnEmOperadorasDeTelecom.py
luizfmello01/Projeto04_PrevendoCustomerChurnEmOperadorasDeTelecom
ac0119a9cd07ee9cea7e20247cb0b571b801d937
[ "MIT" ]
null
null
null
PrevendoCustomerChurnEmOperadorasDeTelecom.py
luizfmello01/Projeto04_PrevendoCustomerChurnEmOperadorasDeTelecom
ac0119a9cd07ee9cea7e20247cb0b571b801d937
[ "MIT" ]
null
null
null
PrevendoCustomerChurnEmOperadorasDeTelecom.py
luizfmello01/Projeto04_PrevendoCustomerChurnEmOperadorasDeTelecom
ac0119a9cd07ee9cea7e20247cb0b571b801d937
[ "MIT" ]
null
null
null
# Bibliotecas import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import numpy as np from scipy.stats import shapiro from scipy.stats import chi2 from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.feature_selection import SelectKBest, f_classif # !pip install imbalanced-learn from imblearn.over_sampling import SMOTE from sklearn.naive_bayes import GaussianNB from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.model_selection import KFold from sklearn.model_selection import cross_validate from sklearn.metrics import classification_report from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import GradientBoostingClassifier # !pip install xgboost from xgboost import XGBClassifier from sklearn.model_selection import GridSearchCV from sklearn.metrics import confusion_matrix import pickle # Config pandas pd.set_option("max_columns", 1000) # In[2]: # Datasets treino_raw = pd.read_csv("../Datasets/telecom_treino.csv", sep = ",") teste_raw = pd.read_csv("../Datasets/telecom_teste.csv", sep = ",") # ## 3.0 - Análise Exploratória de Dados # In[3]: # Primeiras linhas do dataset treino_raw.head() # A coluna "Unnamed: 0" pode ser removida do dataset porque é um índice e para o treinamento do modelo a coluna não tem relevância.<br/> # As colunas categóricas e TARGET estão com o tipo de dados em String, será realizado um LabelEncoder (Transformação de categorias em valores numéricos) para melhor performance do modelo. # In[4]: # Dimensões do dataset treino_raw.shape # O dataset tem um bom número de registro, porém tem que ter cuidado ao realizar remoção de registros para não afetar a performance do modelo. # In[5]: # Tipo de dado de cada atributo treino_raw.dtypes # Conforme visto anteriormente, o dataset tem algumas variáveis com o tipo Object (Strings) que representam variáveis categóricas, devem ser transformadas para números. # In[6]: # Valores missing treino_raw.isna().sum() # O dataset não contem valores missing. # In[7]: # Valores unicos de cada atributo for i in treino_raw.columns: print(i, "-> ", treino_raw[i].nunique(), sep="") # O dataset tem muitos valores unicos, o que indica que temos bastantes variáveis numéricas, pode-se fazer quantization das variáveis númericas para uma melhor performance do modelo # In[8]: # Separar atributos númericos e categóricos variaveis_numericas = [] variaveis_categoricas = [] for i in treino_raw.columns: if ( treino_raw[i].dtype == 'O' ): variaveis_categoricas.append(i) else: variaveis_numericas.append(i) # In[9]: # Retirar o atributo "Unnamed: 0" da lista de variaveis numericas variaveis_numericas.remove("Unnamed: 0") # ### Variáveis numéricas # In[10]: # Sumário estatístico das variáveis numéricas treino_raw[variaveis_numericas].describe() # A média e mediana das variáveis numéricas estão muito aproximadas, o desvio padrão está com valor baixo, indica que os dados estão próximos da média. # In[11]: # Gráfico de dispersão entre as variáveis total_day_minutes e total_day_charge fig = plt.figure(figsize=(10,6)) sns.scatterplot(data = treino_raw[variaveis_numericas], x = "total_day_minutes", y = "total_day_charge") plt.title("Relação de total_day_minutes e total_day_charge") plt.show() # De acordo com o scatterplot, temos uma correlação positiva das variáveis, conforme cresce os minutos falados no dia, sobe o custo. # In[12]: # Gráfico de dispersão entre as variáveis total_eve_minutes e total_eve_charge fig = plt.figure(figsize=(10,6)) sns.scatterplot(data = treino_raw[variaveis_numericas], x = "total_eve_minutes", y = "total_eve_charge") plt.title("Relação de total_eve_minutes e total_eve_charge") plt.show() # De acordo com o scatterplot, temos uma correlação positiva das variáveis, conforme cresce os minutos falados na vespera, sobe o custo, porém o custo é menor do que os minutos falados no dia e custo do dia. # In[13]: # Histograma treino_raw[variaveis_numericas].hist(figsize=(16,10)) plt.show() # De acordo com os histogramas, as variáveis númericas estão aparentemente em uma distribuição normal com exceção da variável "number_vmail_messages" # In[14]: # Boxplot treino_raw[variaveis_numericas].plot(kind='box', layout=(5,3), subplots=True, figsize=(20,15)) plt.show() # De acordo com os boxplots, todas as variáveis numéricas tem valores outliers, a maioria dos outliers estão concentrados no 1º e 3º quartil. # In[15]: # Teste de hipótese para validar distribuição gaussiana # H0 -> É uma distribuição gaussiana # Ha -> Não é uma distribuição gaussiana # In[16]: for i in variaveis_numericas: teste_gaussiano(i, treino_raw[i]) # Algumas variáveis não estão em uma distribuição normal, será realizado normalização nas variáveis para melhor performance do modelo preditivo. # In[17]: # Correlação das variáveis numéricas figure = plt.figure(figsize=(16,10)) sns.heatmap(treino_raw[variaveis_numericas].corr(), cmap='BrBG', vmin=-1, vmax=1, annot=True) plt.show() # O dataset tem poucas variáveis correlacionadas, porém as correlações existentes são fortes. # In[18]: # Simetria das variáveis numéricas treino_raw[variaveis_numericas].skew() # As variáveis estão simétricas, algumas com uma leve distorção para a cauda esquerda e outras para a cauda direita, mas o valor da distorção é muito baixo. # ### Variáveis categóricas # In[19]: # Barplot de cada variável agrupado pela variável TARGET (Churn) for i in treino_raw[variaveis_categoricas].drop("churn", axis = 1).columns: pd.crosstab(treino_raw[i], treino_raw["churn"]).plot(kind = "bar", stacked = True, figsize = (12,6), title = i) # In[20]: # Countplot para contar os valores das variáveis categóricas for i in variaveis_categoricas: if ( i == "state" ): val_figsize = (16,6) else: val_figsize = (10,6) fig = plt.figure(figsize=val_figsize) sns.countplot(x = i, data = treino_raw) plt.show() # De acordo com os gráfico de barras, os estados com mais registros são WV e MN, o código de área com mais registro é area_code_415, a maioria dos registros não tem plano internacional e não tem plano de correio de voz. A variável TARGET (churn) está desbalanceada, tem mais de 2500 registros com churn no e aproximadamente 500 registros com churn yes, para melhor performance do modelo preditivo, precisa-se balancear a variável churn. # In[21]: # Label Encoder das variáveis categóricas para realizar análise de correlação treino_raw_le = treino_raw.copy() for i in variaveis_categoricas: print("Realizando label encoder da variável", i) le = LabelEncoder() le.fit(treino_raw[i]) treino_raw_le[i] = le.transform(treino_raw_le[i]) # In[22]: # Exibir primeiras linhas do dataset depois do labelencoder das variáveis categóricas treino_raw_le.head() # In[23]: # Análise de correlação com Spearman sns.heatmap(treino_raw_le[variaveis_categoricas].corr(method="spearman"), cmap='BrBG', vmin=-1, vmax=1, annot=True) plt.show() # Realizado LabelEncoder nas variáveis para realizar análise de correlação. A correlação das variáveis preditoras com a variável target é fraca, muito próxima de zero, a variável preditora que tem mais correlação com a variável target é International_Plan. # ## 4.0 - Manipulação de dados # In[24]: # Cópia do dataset original para efetuar as manipulações treino_munging = treino_raw.copy() # Declarar função para estruturar e manipular os dados do dataset para treinar o modelo de machine learning.<br/> # As técnicas utilizadas dentro da função "estruturar_dados" foram criadas de acordo com as necessidades descobertas na análise exploratória. # In[25]: # Declarar e Treinar LabelEncoder para cada variável categorica le = [] # Adicionar cada variável categorica no LabelEncoder for i in variaveis_categoricas: le.append((i, LabelEncoder())) # Treinar LabelEncoder de cada variável categórica for var, modelo in le: modelo.fit(treino_munging[var]) print("Concluído LabelEncoder da variável", var) # In[26]: # Função para realizar a manipulação dos dados standard_scaler = StandardScaler() # Função para inverter o label encoder das variáveis categóricas e normalização das variáveis numéricas # In[27]: # Utilizar a função para realizar a manipulação dos dados (Remover variável "Unnamed: 0", tranformar variáveis categóricas que # estão em formato texto para número e normalizar as variáveis númericas) treino_munging = tratar_dados(treino_munging) # In[28]: # Exibir primeiras linhas do dataset manipulado treino_munging.head() # O dataset está com as variáveis categóricas transformadas para número e as variáveis numéricas estão normalizadas, mas será que essas variáveis numéricas estão mesmo normalizadas? Vamos plotar histograma para confirmar. # In[29]: # Histograma das variáveis numéricas treino_munging[variaveis_numericas].hist(figsize=(15,10)) plt.show() # As variáveis númericas com exceção da variável "number_vmail_messages" estão em formato de distribuição normal. # In[30]: # Boxplot das variáveis numéricas treino_munging[variaveis_numericas].plot(kind='box', layout=(5,3), subplots=True, figsize=(20,15)) plt.show() # De acordo com os graficos exibidos acima, as variáveis númericas do dataset tem muitos outliers, será realizado remoção dos outliers. # In[31]: # Função para remover outlier da variável com método do desvio padrão # In[32]: # Remover outliers do dataset utilizando a função criada a cima e gravar em uma nova variável # # Copiar dataset e gravar em uma nova variável treino_munging_no_outliers = treino_munging.copy() # Percorrer cada variável numérica e retirar outlier de cada variável. for i in variaveis_numericas: treino_munging_no_outliers[i] = remover_outlier(treino_munging_no_outliers[i]) # A função remover_outlier deixa os valores outliers como nulos, vamos remover os valores nulos do dataset treino_munging_no_outliers = treino_munging_no_outliers.dropna() # In[33]: # Boxplot das variáveis numéricas treino_munging_no_outliers[variaveis_numericas].plot(kind='box', layout=(5,3), subplots=True, figsize=(20,15)) plt.show() # De acordo com os gráficos acima, foram removidos os outliers do dataset. # In[34]: # Exibir primeiras linhas do dataset treino_munging_no_outliers.head() # In[35]: # Dimensões do dataset treino_munging_no_outliers.shape # O dataset continua com uma boa quantidade de registros para o treinamento do modelo de machine learning, foram removidos 514 registros ao eliminar os outliers das variáveis numéricas. # ## 5.0 - Feature Selection (Seleção de variáveis) # In[36]: # Utilizar o método SelectKBest do SKLearn com o método estatistico f_classif (ANOVA) para selecionas as melhores variáveis para o modelo de machine learning predict = treino_munging_no_outliers.drop(["churn"], axis = 1) target = treino_munging_no_outliers["churn"] kbest = SelectKBest(f_classif, k=15) kbest.fit_transform( X = predict, y = target) print("Concluído treinamento do SelectKBest com método ANOVA") # In[37]: # Criar dataframe com o resultado da seleção de variáveis resultado_fs = pd.DataFrame({ 'Variavel': predict.columns, 'Selecionado': kbest.get_support(), 'Score': kbest.scores_ }).sort_values("Score", ascending = False).reset_index().drop("index", axis = 1) # In[38]: # 8 variáveis com mais score para o treinamento do modelo variaveis_predict = resultado_fs.iloc[0:8].Variavel.values # In[39]: # Manter somente as variáveis que foram selecionadas na lista de variáveis numéricas variaveis_numericas_novas = [] for i in variaveis_numericas.copy(): if ( i in variaveis_predict ): variaveis_numericas_novas.append(i) variaveis_numericas = variaveis_numericas_novas.copy() # In[40]: # Exibir variaveis preditoras selecionadas variaveis_predict # As variaveis exibidas acima serão utilizadas para o treinamento do modelo de machine learning porque são as variáveis que tiveram mais score na seleção de variáveis # ## 6.0 - Preparar dataset de treino e teste para o treinamento # In[41]: # Primeiras linhas do dataset de teste teste_raw.head() # In[42]: # Tratar o dataset de teste teste_munging = tratar_dados(teste_raw) # In[43]: # Manter somente variáveis da feature selection (seleção de variáveis) nos datasets e separar dados de treino e de teste # # Dataset de treino x_treino = treino_munging_no_outliers[variaveis_predict] y_treino = treino_munging_no_outliers["churn"] # Dataset de teste x_teste = teste_munging[variaveis_predict] y_teste = teste_munging["churn"] # In[44]: # Primeiras linhas do dataset de teste sem a variável target após o tratamento dos dados x_teste.head() # In[45]: # Balancear dataset de treino x_treino_balanceado, y_treino_balanceado = SMOTE().fit_resample(x_treino, y_treino) # In[46]: # Dimensões do dataset de treino balanceado print("Dimensões das variáveis preditoras:", x_treino_balanceado.shape) print("Quantidade de registros da variável target:", y_treino_balanceado.count()) # Dataset está com 4940 registros, com 8 variáveis preditoras e uma variável target após o balanceamento da classe target. # ## 7.0 - Treinamento do Modelo de Machine Learning # In[47]: # In[48]: # Treinar modelos de regressão logistica e naive bayes com a técnica de cross validation modelos = obter_modelos() k = KFold(n_splits=10) for nome, modelo in modelos: cv = cross_validate(estimator = modelo, X = x_treino_balanceado, y = y_treino_balanceado, cv = k, scoring=['accuracy', 'recall', 'precision']) print( "%s:\n\tAcurácia: %.3f \n\tRecall: %.3f \n\tPrecisão: %.3f \n" % ( nome, np.mean(cv["test_accuracy"]), np.mean(cv["test_recall"]), np.mean(cv["test_precision"])) ) # Os modelos que apresentaram melhores resultados foram KNN e SVM, vamos realizar treinamento desses modelos individualmente para serem avaliados com dados de teste. # In[49]: # Treinamento do modelo KNN modelo_knn_v1 = KNeighborsClassifier() modelo_knn_v1.probability=True modelo_knn_v1.fit(X = x_treino_balanceado, y = y_treino_balanceado) print("Concluído treinamento do algoritmo KNN") # In[50]: # Treinamento do modelo SVM Classifier modelo_svm_v1 = SVC() modelo_svm_v1.probability=True modelo_svm_v1.fit(X = x_treino_balanceado, y = y_treino_balanceado) print("Concluído treinamento do algoritmo SVM") # ## 8.0 - Avaliação do Modelo de Machine Learning # Métricas escolhida para avalição do modelo: Recall # In[51]: # Avaliação do modelo KNN com os dados de teste previsao_knn_v1 = modelo_knn_v1.predict(x_teste) print( "Avaliação do modelo KNN:\n" ) print( classification_report(y_teste, previsao_knn_v1) ) # In[52]: # Avaliação do modelo SVM com os dados de teste previsao_svm_v1 = modelo_svm_v1.predict(x_teste) print( "Avaliação do modelo SVM:\n" ) print( classification_report(y_teste, previsao_svm_v1) ) # O modelo SVM foi superior na métrica recall, esse modelo é o escolhido para receber otimização de hiperparametros. # ## 9.0 - Otimização do Modelo de Machine Learning # In[53]: # Treinar modelo Random Forest para realizar otimização modelo_rfc_v1 = RandomForestClassifier(n_estimators=1000) modelo_rfc_v1.fit(x_treino_balanceado, y_treino_balanceado) print("Concluído treinamento do algoritmo Random Forest") # In[54]: # Avaliação do modelo Random Forest com os dados de teste previsao_rfc_v1 = modelo_rfc_v1.predict(x_teste) print( "Avaliação do modelo Random Forest Classifier:\n" ) print( classification_report(y_teste, previsao_rfc_v1) ) # O modelo Random Forest não teve um recall superior ao modelo SVM. # In[55]: # Treinar modelo XGBoost para realizar otimização modelo_xgb_v1 = XGBClassifier(n_estimators=500) modelo_xgb_v1.fit(x_treino_balanceado, y_treino_balanceado) print("Concluído treinamento do algoritmo XGBoost") # In[56]: # Avaliação do modelo XGBoost com os dados de teste previsao_xgb_v1 = modelo_xgb_v1.predict(x_teste) previsao_xgb_v1 = [round(value) for value in previsao_xgb_v1] print( "Avaliação do modelo XGBoost Classifier:\n" ) print( classification_report(y_teste, previsao_xgb_v1) ) # O modelo XGBoost não teve um recall superior ao modelo SVM. # In[57]: # Otimizar hiperparametros do modelo SVM com GridSearchCV # # Parametros do Grid param_grid = {'C': [0.1], 'kernel': ['rbf'], 'gamma': ['scale'], 'tol': [0.001], 'class_weight': [{0:1.0, 1:1.10}, {0:1.0, 1:1.12}] } # Treinar GridSearchCV grid = GridSearchCV(SVC(), param_grid, refit=True, verbose=2, cv=KFold(n_splits=6), scoring='recall') grid.fit(x_treino_balanceado, y_treino_balanceado) # In[58]: # Exibir melhores parametros encontrados com o GridSearchCV print("Melhores parametros:") print(grid.best_params_) # In[59]: pd.DataFrame(grid.cv_results_).sort_values(["rank_test_score"]).head() # In[60]: # Avaliar modelo treinado com GridSearchCV utilizando os dados de teste grid_previsoes = grid.predict(x_teste) print( "Matriz de confusão:\n" ) print( confusion_matrix(y_teste, grid_previsoes) ) print( "\nRelatório de classificação:\n" ) print( classification_report(y_teste, grid_previsoes) ) # O modelo treinado com os hyperparametros ('C': 0.1, 'class_weight': {0: 1.0, 1: 1.12}, 'gamma': 'scale', 'kernel': 'rbf', 'tol': 0.001) será o modelo escolhido para entrega final do projeto. # Modelo teve uma queda de 3% de recall para a classe 0 (No), porém teve um aumento de 5% de recall para a classe 1 (Yes). # ## 10.0 - Salvar o Modelo de Machine Learning para Entrega Final do Projeto # In[61]: # Treinamento do modelo final modelo_svm_final = SVC(C=0.1, class_weight={0:1.0, 1:1.12}, gamma='scale', kernel='rbf', tol=0.001) modelo_svm_final.probability = True modelo_svm_final.fit(x_treino_balanceado, y_treino_balanceado) print( "Treinamento do Modelo SVM (Versão final) realizado com sucesso" ) # In[62]: # Prever resultado de Churn e a probabilidade para os dados de teste previsao_modelo_svm_final = modelo_svm_final.predict(x_teste) previsao_prob_modelo_svm_final = modelo_svm_final.predict_proba(x_teste) df_previsoes = pd.DataFrame({ 'churn': pd.Series(previsao_modelo_svm_final, dtype=np.int32), 'Probabilidade_ChurnNo': pd.Series(np.round(previsao_prob_modelo_svm_final.transpose()[0], 2), dtype=np.float32), 'Probabilidade_ChurnYes': pd.Series(np.round(previsao_prob_modelo_svm_final.transpose()[1], 2), dtype=np.float32) }) # In[63]: # Dataset de teste com a previsão e probabilidade de churn teste_resultado = inverter_dados(x_teste.join(df_previsoes)) teste_resultado.head() # In[64]: # Salvar modelo de machine learning nome_arquivo = "../modelo/modelo_svm_final.sav" pickle.dump(modelo_svm_final, open(nome_arquivo, 'wb')) # ## FIM.
28.498695
436
0.736051
# Bibliotecas import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import numpy as np from scipy.stats import shapiro from scipy.stats import chi2 from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.feature_selection import SelectKBest, f_classif # !pip install imbalanced-learn from imblearn.over_sampling import SMOTE from sklearn.naive_bayes import GaussianNB from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC from sklearn.model_selection import KFold from sklearn.model_selection import cross_validate from sklearn.metrics import classification_report from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import GradientBoostingClassifier # !pip install xgboost from xgboost import XGBClassifier from sklearn.model_selection import GridSearchCV from sklearn.metrics import confusion_matrix import pickle # Config pandas pd.set_option("max_columns", 1000) # In[2]: # Datasets treino_raw = pd.read_csv("../Datasets/telecom_treino.csv", sep = ",") teste_raw = pd.read_csv("../Datasets/telecom_teste.csv", sep = ",") # ## 3.0 - Análise Exploratória de Dados # In[3]: # Primeiras linhas do dataset treino_raw.head() # A coluna "Unnamed: 0" pode ser removida do dataset porque é um índice e para o treinamento do modelo a coluna não tem relevância.<br/> # As colunas categóricas e TARGET estão com o tipo de dados em String, será realizado um LabelEncoder (Transformação de categorias em valores numéricos) para melhor performance do modelo. # In[4]: # Dimensões do dataset treino_raw.shape # O dataset tem um bom número de registro, porém tem que ter cuidado ao realizar remoção de registros para não afetar a performance do modelo. # In[5]: # Tipo de dado de cada atributo treino_raw.dtypes # Conforme visto anteriormente, o dataset tem algumas variáveis com o tipo Object (Strings) que representam variáveis categóricas, devem ser transformadas para números. # In[6]: # Valores missing treino_raw.isna().sum() # O dataset não contem valores missing. # In[7]: # Valores unicos de cada atributo for i in treino_raw.columns: print(i, "-> ", treino_raw[i].nunique(), sep="") # O dataset tem muitos valores unicos, o que indica que temos bastantes variáveis numéricas, pode-se fazer quantization das variáveis númericas para uma melhor performance do modelo # In[8]: # Separar atributos númericos e categóricos variaveis_numericas = [] variaveis_categoricas = [] for i in treino_raw.columns: if ( treino_raw[i].dtype == 'O' ): variaveis_categoricas.append(i) else: variaveis_numericas.append(i) # In[9]: # Retirar o atributo "Unnamed: 0" da lista de variaveis numericas variaveis_numericas.remove("Unnamed: 0") # ### Variáveis numéricas # In[10]: # Sumário estatístico das variáveis numéricas treino_raw[variaveis_numericas].describe() # A média e mediana das variáveis numéricas estão muito aproximadas, o desvio padrão está com valor baixo, indica que os dados estão próximos da média. # In[11]: # Gráfico de dispersão entre as variáveis total_day_minutes e total_day_charge fig = plt.figure(figsize=(10,6)) sns.scatterplot(data = treino_raw[variaveis_numericas], x = "total_day_minutes", y = "total_day_charge") plt.title("Relação de total_day_minutes e total_day_charge") plt.show() # De acordo com o scatterplot, temos uma correlação positiva das variáveis, conforme cresce os minutos falados no dia, sobe o custo. # In[12]: # Gráfico de dispersão entre as variáveis total_eve_minutes e total_eve_charge fig = plt.figure(figsize=(10,6)) sns.scatterplot(data = treino_raw[variaveis_numericas], x = "total_eve_minutes", y = "total_eve_charge") plt.title("Relação de total_eve_minutes e total_eve_charge") plt.show() # De acordo com o scatterplot, temos uma correlação positiva das variáveis, conforme cresce os minutos falados na vespera, sobe o custo, porém o custo é menor do que os minutos falados no dia e custo do dia. # In[13]: # Histograma treino_raw[variaveis_numericas].hist(figsize=(16,10)) plt.show() # De acordo com os histogramas, as variáveis númericas estão aparentemente em uma distribuição normal com exceção da variável "number_vmail_messages" # In[14]: # Boxplot treino_raw[variaveis_numericas].plot(kind='box', layout=(5,3), subplots=True, figsize=(20,15)) plt.show() # De acordo com os boxplots, todas as variáveis numéricas tem valores outliers, a maioria dos outliers estão concentrados no 1º e 3º quartil. # In[15]: # Teste de hipótese para validar distribuição gaussiana # H0 -> É uma distribuição gaussiana # Ha -> Não é uma distribuição gaussiana def teste_gaussiano(nome_variavel, dados_variavel): alpha = 0.05 stat, p = shapiro(dados_variavel) if p > alpha: print("Variável", nome_variavel, "está em uma distribuição gaussiana (Falha ao rejeitar H0)") print("\tP-Value: %.3f" % p) else: print("Variável", nome_variavel, "não está em uma distribuição gaussiana (Rejeitar H0)") print("\tP-Value: %.3f" % p) print() # In[16]: for i in variaveis_numericas: teste_gaussiano(i, treino_raw[i]) # Algumas variáveis não estão em uma distribuição normal, será realizado normalização nas variáveis para melhor performance do modelo preditivo. # In[17]: # Correlação das variáveis numéricas figure = plt.figure(figsize=(16,10)) sns.heatmap(treino_raw[variaveis_numericas].corr(), cmap='BrBG', vmin=-1, vmax=1, annot=True) plt.show() # O dataset tem poucas variáveis correlacionadas, porém as correlações existentes são fortes. # In[18]: # Simetria das variáveis numéricas treino_raw[variaveis_numericas].skew() # As variáveis estão simétricas, algumas com uma leve distorção para a cauda esquerda e outras para a cauda direita, mas o valor da distorção é muito baixo. # ### Variáveis categóricas # In[19]: # Barplot de cada variável agrupado pela variável TARGET (Churn) for i in treino_raw[variaveis_categoricas].drop("churn", axis = 1).columns: pd.crosstab(treino_raw[i], treino_raw["churn"]).plot(kind = "bar", stacked = True, figsize = (12,6), title = i) # In[20]: # Countplot para contar os valores das variáveis categóricas for i in variaveis_categoricas: if ( i == "state" ): val_figsize = (16,6) else: val_figsize = (10,6) fig = plt.figure(figsize=val_figsize) sns.countplot(x = i, data = treino_raw) plt.show() # De acordo com os gráfico de barras, os estados com mais registros são WV e MN, o código de área com mais registro é area_code_415, a maioria dos registros não tem plano internacional e não tem plano de correio de voz. A variável TARGET (churn) está desbalanceada, tem mais de 2500 registros com churn no e aproximadamente 500 registros com churn yes, para melhor performance do modelo preditivo, precisa-se balancear a variável churn. # In[21]: # Label Encoder das variáveis categóricas para realizar análise de correlação treino_raw_le = treino_raw.copy() for i in variaveis_categoricas: print("Realizando label encoder da variável", i) le = LabelEncoder() le.fit(treino_raw[i]) treino_raw_le[i] = le.transform(treino_raw_le[i]) # In[22]: # Exibir primeiras linhas do dataset depois do labelencoder das variáveis categóricas treino_raw_le.head() # In[23]: # Análise de correlação com Spearman sns.heatmap(treino_raw_le[variaveis_categoricas].corr(method="spearman"), cmap='BrBG', vmin=-1, vmax=1, annot=True) plt.show() # Realizado LabelEncoder nas variáveis para realizar análise de correlação. A correlação das variáveis preditoras com a variável target é fraca, muito próxima de zero, a variável preditora que tem mais correlação com a variável target é International_Plan. # ## 4.0 - Manipulação de dados # In[24]: # Cópia do dataset original para efetuar as manipulações treino_munging = treino_raw.copy() # Declarar função para estruturar e manipular os dados do dataset para treinar o modelo de machine learning.<br/> # As técnicas utilizadas dentro da função "estruturar_dados" foram criadas de acordo com as necessidades descobertas na análise exploratória. # In[25]: # Declarar e Treinar LabelEncoder para cada variável categorica le = [] # Adicionar cada variável categorica no LabelEncoder for i in variaveis_categoricas: le.append((i, LabelEncoder())) # Treinar LabelEncoder de cada variável categórica for var, modelo in le: modelo.fit(treino_munging[var]) print("Concluído LabelEncoder da variável", var) # In[26]: # Função para realizar a manipulação dos dados standard_scaler = StandardScaler() def tratar_dados(dataset): # Remover variável "Unnamed: 0" do dataset try: dataset = dataset.drop(["Unnamed: 0"], axis = 1) print("Concluído remoção da variável 'Unnamed: 0'") except: print("O dataset não tem a variável 'Unnamed: 0'") # Transformar variáveis categóricas que estão em formato de texto para número for var, modelo in le: try: dataset[var] = modelo.fit_transform(dataset[var]) print("Concluído LabelEncoder da variável", var) except: print("O dataset não tem a variável", var) # Normalizar as variáveis numéricas dataset[variaveis_numericas] = standard_scaler.fit_transform(X = dataset[variaveis_numericas], y = dataset["churn"]) print("Concluído normalização das variáveis numéricas") return dataset # Função para inverter o label encoder das variáveis categóricas e normalização das variáveis numéricas def inverter_dados(dataset): # Transformar variáveis categóricas que estão em formato de texto para número for var, modelo in le: try: dataset[var] = modelo.inverse_transform(dataset[var]) print("Concluído inversão de LabelEncoder da variável", var) except: print("O dataset não tem a variável", var) # Normalizar as variáveis numéricas dataset[variaveis_numericas] = standard_scaler.inverse_transform(X = dataset[variaveis_numericas]) return dataset # In[27]: # Utilizar a função para realizar a manipulação dos dados (Remover variável "Unnamed: 0", tranformar variáveis categóricas que # estão em formato texto para número e normalizar as variáveis númericas) treino_munging = tratar_dados(treino_munging) # In[28]: # Exibir primeiras linhas do dataset manipulado treino_munging.head() # O dataset está com as variáveis categóricas transformadas para número e as variáveis numéricas estão normalizadas, mas será que essas variáveis numéricas estão mesmo normalizadas? Vamos plotar histograma para confirmar. # In[29]: # Histograma das variáveis numéricas treino_munging[variaveis_numericas].hist(figsize=(15,10)) plt.show() # As variáveis númericas com exceção da variável "number_vmail_messages" estão em formato de distribuição normal. # In[30]: # Boxplot das variáveis numéricas treino_munging[variaveis_numericas].plot(kind='box', layout=(5,3), subplots=True, figsize=(20,15)) plt.show() # De acordo com os graficos exibidos acima, as variáveis númericas do dataset tem muitos outliers, será realizado remoção dos outliers. # In[31]: # Função para remover outlier da variável com método do desvio padrão def remover_outlier(valor): # Calcular estatística de média e desvio padrão media, desvio_padrao = np.mean(valor), np.std(valor) # Identificar outliers valor_corte = desvio_padrao * 2.5 baixo, alto = media - valor_corte, media + valor_corte valor = np.where(valor > alto, np.nan, valor) valor = np.where(valor < baixo, np.nan, valor) return valor # In[32]: # Remover outliers do dataset utilizando a função criada a cima e gravar em uma nova variável # # Copiar dataset e gravar em uma nova variável treino_munging_no_outliers = treino_munging.copy() # Percorrer cada variável numérica e retirar outlier de cada variável. for i in variaveis_numericas: treino_munging_no_outliers[i] = remover_outlier(treino_munging_no_outliers[i]) # A função remover_outlier deixa os valores outliers como nulos, vamos remover os valores nulos do dataset treino_munging_no_outliers = treino_munging_no_outliers.dropna() # In[33]: # Boxplot das variáveis numéricas treino_munging_no_outliers[variaveis_numericas].plot(kind='box', layout=(5,3), subplots=True, figsize=(20,15)) plt.show() # De acordo com os gráficos acima, foram removidos os outliers do dataset. # In[34]: # Exibir primeiras linhas do dataset treino_munging_no_outliers.head() # In[35]: # Dimensões do dataset treino_munging_no_outliers.shape # O dataset continua com uma boa quantidade de registros para o treinamento do modelo de machine learning, foram removidos 514 registros ao eliminar os outliers das variáveis numéricas. # ## 5.0 - Feature Selection (Seleção de variáveis) # In[36]: # Utilizar o método SelectKBest do SKLearn com o método estatistico f_classif (ANOVA) para selecionas as melhores variáveis para o modelo de machine learning predict = treino_munging_no_outliers.drop(["churn"], axis = 1) target = treino_munging_no_outliers["churn"] kbest = SelectKBest(f_classif, k=15) kbest.fit_transform( X = predict, y = target) print("Concluído treinamento do SelectKBest com método ANOVA") # In[37]: # Criar dataframe com o resultado da seleção de variáveis resultado_fs = pd.DataFrame({ 'Variavel': predict.columns, 'Selecionado': kbest.get_support(), 'Score': kbest.scores_ }).sort_values("Score", ascending = False).reset_index().drop("index", axis = 1) # In[38]: # 8 variáveis com mais score para o treinamento do modelo variaveis_predict = resultado_fs.iloc[0:8].Variavel.values # In[39]: # Manter somente as variáveis que foram selecionadas na lista de variáveis numéricas variaveis_numericas_novas = [] for i in variaveis_numericas.copy(): if ( i in variaveis_predict ): variaveis_numericas_novas.append(i) variaveis_numericas = variaveis_numericas_novas.copy() # In[40]: # Exibir variaveis preditoras selecionadas variaveis_predict # As variaveis exibidas acima serão utilizadas para o treinamento do modelo de machine learning porque são as variáveis que tiveram mais score na seleção de variáveis # ## 6.0 - Preparar dataset de treino e teste para o treinamento # In[41]: # Primeiras linhas do dataset de teste teste_raw.head() # In[42]: # Tratar o dataset de teste teste_munging = tratar_dados(teste_raw) # In[43]: # Manter somente variáveis da feature selection (seleção de variáveis) nos datasets e separar dados de treino e de teste # # Dataset de treino x_treino = treino_munging_no_outliers[variaveis_predict] y_treino = treino_munging_no_outliers["churn"] # Dataset de teste x_teste = teste_munging[variaveis_predict] y_teste = teste_munging["churn"] # In[44]: # Primeiras linhas do dataset de teste sem a variável target após o tratamento dos dados x_teste.head() # In[45]: # Balancear dataset de treino x_treino_balanceado, y_treino_balanceado = SMOTE().fit_resample(x_treino, y_treino) # In[46]: # Dimensões do dataset de treino balanceado print("Dimensões das variáveis preditoras:", x_treino_balanceado.shape) print("Quantidade de registros da variável target:", y_treino_balanceado.count()) # Dataset está com 4940 registros, com 8 variáveis preditoras e uma variável target após o balanceamento da classe target. # ## 7.0 - Treinamento do Modelo de Machine Learning # In[47]: def obter_modelos(): modelos = [] modelos.append( ("Naive Bayes", GaussianNB()) ) modelos.append( ("Regressão Logística", LogisticRegression()) ) modelos.append( ("KNN", KNeighborsClassifier()) ) modelos.append( ("SVM Classificador", SVC()) ) return modelos # In[48]: # Treinar modelos de regressão logistica e naive bayes com a técnica de cross validation modelos = obter_modelos() k = KFold(n_splits=10) for nome, modelo in modelos: cv = cross_validate(estimator = modelo, X = x_treino_balanceado, y = y_treino_balanceado, cv = k, scoring=['accuracy', 'recall', 'precision']) print( "%s:\n\tAcurácia: %.3f \n\tRecall: %.3f \n\tPrecisão: %.3f \n" % ( nome, np.mean(cv["test_accuracy"]), np.mean(cv["test_recall"]), np.mean(cv["test_precision"])) ) # Os modelos que apresentaram melhores resultados foram KNN e SVM, vamos realizar treinamento desses modelos individualmente para serem avaliados com dados de teste. # In[49]: # Treinamento do modelo KNN modelo_knn_v1 = KNeighborsClassifier() modelo_knn_v1.probability=True modelo_knn_v1.fit(X = x_treino_balanceado, y = y_treino_balanceado) print("Concluído treinamento do algoritmo KNN") # In[50]: # Treinamento do modelo SVM Classifier modelo_svm_v1 = SVC() modelo_svm_v1.probability=True modelo_svm_v1.fit(X = x_treino_balanceado, y = y_treino_balanceado) print("Concluído treinamento do algoritmo SVM") # ## 8.0 - Avaliação do Modelo de Machine Learning # Métricas escolhida para avalição do modelo: Recall # In[51]: # Avaliação do modelo KNN com os dados de teste previsao_knn_v1 = modelo_knn_v1.predict(x_teste) print( "Avaliação do modelo KNN:\n" ) print( classification_report(y_teste, previsao_knn_v1) ) # In[52]: # Avaliação do modelo SVM com os dados de teste previsao_svm_v1 = modelo_svm_v1.predict(x_teste) print( "Avaliação do modelo SVM:\n" ) print( classification_report(y_teste, previsao_svm_v1) ) # O modelo SVM foi superior na métrica recall, esse modelo é o escolhido para receber otimização de hiperparametros. # ## 9.0 - Otimização do Modelo de Machine Learning # In[53]: # Treinar modelo Random Forest para realizar otimização modelo_rfc_v1 = RandomForestClassifier(n_estimators=1000) modelo_rfc_v1.fit(x_treino_balanceado, y_treino_balanceado) print("Concluído treinamento do algoritmo Random Forest") # In[54]: # Avaliação do modelo Random Forest com os dados de teste previsao_rfc_v1 = modelo_rfc_v1.predict(x_teste) print( "Avaliação do modelo Random Forest Classifier:\n" ) print( classification_report(y_teste, previsao_rfc_v1) ) # O modelo Random Forest não teve um recall superior ao modelo SVM. # In[55]: # Treinar modelo XGBoost para realizar otimização modelo_xgb_v1 = XGBClassifier(n_estimators=500) modelo_xgb_v1.fit(x_treino_balanceado, y_treino_balanceado) print("Concluído treinamento do algoritmo XGBoost") # In[56]: # Avaliação do modelo XGBoost com os dados de teste previsao_xgb_v1 = modelo_xgb_v1.predict(x_teste) previsao_xgb_v1 = [round(value) for value in previsao_xgb_v1] print( "Avaliação do modelo XGBoost Classifier:\n" ) print( classification_report(y_teste, previsao_xgb_v1) ) # O modelo XGBoost não teve um recall superior ao modelo SVM. # In[57]: # Otimizar hiperparametros do modelo SVM com GridSearchCV # # Parametros do Grid param_grid = {'C': [0.1], 'kernel': ['rbf'], 'gamma': ['scale'], 'tol': [0.001], 'class_weight': [{0:1.0, 1:1.10}, {0:1.0, 1:1.12}] } # Treinar GridSearchCV grid = GridSearchCV(SVC(), param_grid, refit=True, verbose=2, cv=KFold(n_splits=6), scoring='recall') grid.fit(x_treino_balanceado, y_treino_balanceado) # In[58]: # Exibir melhores parametros encontrados com o GridSearchCV print("Melhores parametros:") print(grid.best_params_) # In[59]: pd.DataFrame(grid.cv_results_).sort_values(["rank_test_score"]).head() # In[60]: # Avaliar modelo treinado com GridSearchCV utilizando os dados de teste grid_previsoes = grid.predict(x_teste) print( "Matriz de confusão:\n" ) print( confusion_matrix(y_teste, grid_previsoes) ) print( "\nRelatório de classificação:\n" ) print( classification_report(y_teste, grid_previsoes) ) # O modelo treinado com os hyperparametros ('C': 0.1, 'class_weight': {0: 1.0, 1: 1.12}, 'gamma': 'scale', 'kernel': 'rbf', 'tol': 0.001) será o modelo escolhido para entrega final do projeto. # Modelo teve uma queda de 3% de recall para a classe 0 (No), porém teve um aumento de 5% de recall para a classe 1 (Yes). # ## 10.0 - Salvar o Modelo de Machine Learning para Entrega Final do Projeto # In[61]: # Treinamento do modelo final modelo_svm_final = SVC(C=0.1, class_weight={0:1.0, 1:1.12}, gamma='scale', kernel='rbf', tol=0.001) modelo_svm_final.probability = True modelo_svm_final.fit(x_treino_balanceado, y_treino_balanceado) print( "Treinamento do Modelo SVM (Versão final) realizado com sucesso" ) # In[62]: # Prever resultado de Churn e a probabilidade para os dados de teste previsao_modelo_svm_final = modelo_svm_final.predict(x_teste) previsao_prob_modelo_svm_final = modelo_svm_final.predict_proba(x_teste) df_previsoes = pd.DataFrame({ 'churn': pd.Series(previsao_modelo_svm_final, dtype=np.int32), 'Probabilidade_ChurnNo': pd.Series(np.round(previsao_prob_modelo_svm_final.transpose()[0], 2), dtype=np.float32), 'Probabilidade_ChurnYes': pd.Series(np.round(previsao_prob_modelo_svm_final.transpose()[1], 2), dtype=np.float32) }) # In[63]: # Dataset de teste com a previsão e probabilidade de churn teste_resultado = inverter_dados(x_teste.join(df_previsoes)) teste_resultado.head() # In[64]: # Salvar modelo de machine learning nome_arquivo = "../modelo/modelo_svm_final.sav" pickle.dump(modelo_svm_final, open(nome_arquivo, 'wb')) # ## FIM.
2,449
0
112
b54cc2f8011e885fcaf35b074d8ab57d62f80215
178
py
Python
extheano/__init__.py
koheimiya/extheano
ea099a6395ca8772660b2c715fb26cde12738181
[ "MIT" ]
2
2016-06-13T13:58:23.000Z
2017-04-05T05:19:56.000Z
extheano/__init__.py
koheimiya/extheano
ea099a6395ca8772660b2c715fb26cde12738181
[ "MIT" ]
null
null
null
extheano/__init__.py
koheimiya/extheano
ea099a6395ca8772660b2c715fb26cde12738181
[ "MIT" ]
null
null
null
__all__ = [] from .nodebuffer import NodeBuffer, NodeDescriptor, BufferSet from .nodebuffer import Scanner as _Scanner scan = _Scanner.scan from .jit import JITCompiler as jit
22.25
61
0.797753
__all__ = [] from .nodebuffer import NodeBuffer, NodeDescriptor, BufferSet from .nodebuffer import Scanner as _Scanner scan = _Scanner.scan from .jit import JITCompiler as jit
0
0
0
56c2047b0a57c8dc94ee7191641a00a00c0de033
5,344
py
Python
scripts/generative/gvae_exp.py
choderalab/pinot
413a349ab42912d8a668a645effde8e70ba608a6
[ "MIT" ]
13
2020-03-23T21:53:06.000Z
2021-09-28T19:29:35.000Z
scripts/generative/gvae_exp.py
choderalab/pinot
413a349ab42912d8a668a645effde8e70ba608a6
[ "MIT" ]
89
2020-03-27T21:18:55.000Z
2021-04-02T19:36:50.000Z
scripts/generative/gvae_exp.py
choderalab/pinot
413a349ab42912d8a668a645effde8e70ba608a6
[ "MIT" ]
2
2020-04-25T03:23:40.000Z
2021-02-19T18:35:27.000Z
from __future__ import division from __future__ import print_function import argparse parser = argparse.ArgumentParser() parser.add_argument('--epochs', type=int, default=100, help='Number of epochs to train.') parser.add_argument('--split',nargs='+', type=float, default=[0.9, 0.1, 0.], help="train, test, validation split, default = [0.8, 0.2] (No validation)") parser.add_argument('--batch_size', type=int, default=10, help="batch-size, i.e, how many molecules get 'merged' to form a graph per iteration during traing") parser.add_argument('--lr', type=float, default=0.001, help='Learning rate.') parser.add_argument('--hidden_dims', nargs='+', type=int, default=[256, 128], help="hidden dimension 1") parser.add_argument('--embedding_dim', type=int, default=64, help="node embedding dimension") parser.add_argument('--html', type=str, default="results.html", help="File to save results to") args = parser.parse_args() import torch from torch import optim # import time # import numpy as np # import scipy.sparse as sp import dgl import pinot from pinot.data.utils import batch, split from pinot.generative.torch_gvae.model import GCNModelVAE # from pinot.generative.torch_gvae.loss import negative_ELBO # from pinot.app.experiment import Train, Test, TrainAndTest, MultipleTrainAndTest from pinot.app.experiment import TrainAndTest from pinot.app.report import html ################ METRICS ON EDGE PREDICTION ################### if __name__ == '__main__': run(args)
38.724638
158
0.690868
from __future__ import division from __future__ import print_function import argparse parser = argparse.ArgumentParser() parser.add_argument('--epochs', type=int, default=100, help='Number of epochs to train.') parser.add_argument('--split',nargs='+', type=float, default=[0.9, 0.1, 0.], help="train, test, validation split, default = [0.8, 0.2] (No validation)") parser.add_argument('--batch_size', type=int, default=10, help="batch-size, i.e, how many molecules get 'merged' to form a graph per iteration during traing") parser.add_argument('--lr', type=float, default=0.001, help='Learning rate.') parser.add_argument('--hidden_dims', nargs='+', type=int, default=[256, 128], help="hidden dimension 1") parser.add_argument('--embedding_dim', type=int, default=64, help="node embedding dimension") parser.add_argument('--html', type=str, default="results.html", help="File to save results to") args = parser.parse_args() import torch from torch import optim # import time # import numpy as np # import scipy.sparse as sp import dgl import pinot from pinot.data.utils import batch, split from pinot.generative.torch_gvae.model import GCNModelVAE # from pinot.generative.torch_gvae.loss import negative_ELBO # from pinot.app.experiment import Train, Test, TrainAndTest, MultipleTrainAndTest from pinot.app.experiment import TrainAndTest from pinot.app.report import html def run(args): # Grab some data from esol ds = pinot.data.esol() # Divide the molecules into train/test/val train_data, test_data, _ = split(ds, args.split) N_molecules = len(train_data) # "Batching" multiple molecules into groups, each groups # forming a "macro-molecule" (graph) batched_train_data = batch(train_data, args.batch_size) print("Training on ", N_molecules, "molecules") print("and batched into", len(batched_train_data), "batches") # Initialize the model and the optimization scheme feat_dim = train_data[0][0].ndata["h"].shape[1] num_atom_types = 100 model = GCNModelVAE(feat_dim, gcn_hidden_dims=args.hidden_dims, embedding_dim=64, num_atom_types=num_atom_types) optimizer = optim.Adam(model.parameters(), args.lr) # Setting up training and testing train_and_test = TrainAndTest(model, batched_train_data, test_data, optimizer, [accuracy_edge_prediction, true_negative_edge_prediction,\ true_positive_edge_prediction, accuracy_node_prediction,\ negative_elbo_loss], n_epochs=args.epochs) results = train_and_test.run() print("Optimization Finished! Now printing results to", args.html) html_string = html(results) f_handle = open(args.html, 'w') f_handle.write(html_string) f_handle.close() ################ METRICS ON EDGE PREDICTION ################### def accuracy_edge_prediction(net, g, y): unbatched_subgraphs = dgl.unbatch(g) decoded_subgraphs, _, _ = net.encode_and_decode(g) assert(len(decoded_subgraphs) == len(unbatched_subgraphs)) avg_acc = 0. for i, subg in enumerate(unbatched_subgraphs): edge_pred, _ = decoded_subgraphs[i] adj_mat = subg.adjacency_matrix(True).to_dense() acc = torch.mean((( (edge_pred > 0.5) & (adj_mat == 1))\ | ((edge_pred < 0.5) & (adj_mat == 0) )).float()) avg_acc += acc / len(unbatched_subgraphs) return avg_acc def true_negative_edge_prediction(net, g, y): unbatched_subgraphs = dgl.unbatch(g) decoded_subgraphs, _, _ = net.encode_and_decode(g) assert(len(decoded_subgraphs) == len(unbatched_subgraphs)) avg_tn = 0. for i, subg in enumerate(unbatched_subgraphs): edge_pred, _ = decoded_subgraphs[i] adj_mat = subg.adjacency_matrix(True).to_dense() true_negatives = ((edge_pred < 0.5) & (adj_mat==0)).int().sum() all_negatives = (adj_mat == 0).int().sum() tn = true_negatives.float()/all_negatives avg_tn += tn / len(unbatched_subgraphs) return avg_tn def true_positive_edge_prediction(net, g, y): unbatched_subgraphs = dgl.unbatch(g) decoded_subgraphs, _, _ = net.encode_and_decode(g) assert(len(decoded_subgraphs) == len(unbatched_subgraphs)) avg_tp = 0. for i, subg in enumerate(unbatched_subgraphs): edge_pred, _ = decoded_subgraphs[i] adj_mat = subg.adjacency_matrix(True).to_dense() true_positives = ((edge_pred > 0.5) & (adj_mat==1)).int().sum() all_positives = (adj_mat == 1).int().sum() tp = true_positives.float()/all_positives avg_tp += tp / len(unbatched_subgraphs) return avg_tp def accuracy_node_prediction(net, g, y): unbatched_subgraphs = dgl.unbatch(g) decoded_subgraphs, _, _ = net.encode_and_decode(g) assert(len(decoded_subgraphs) == len(unbatched_subgraphs)) avg_acc = 0. for i, subg in enumerate(unbatched_subgraphs): _, node_preds = decoded_subgraphs[i] node_types = subg.ndata["type"] node_type_preds = torch.argmax(node_preds, 1) acc = torch.mean((node_type_preds == node_types).float()) avg_acc += acc /len(unbatched_subgraphs) return torch.mean((node_type_preds == node_types).float()) def negative_elbo_loss(net, g, y): return net.loss(g).detach() if __name__ == '__main__': run(args)
3,722
0
138
8622ecd45a8d63e35951cef4e1bacd406e0af713
69,136
py
Python
kuber/latest/authorization_v1.py
datalayer-externals/kuber
4d577950ce7d1be2b882fbe66827dc3d7e67b350
[ "MIT" ]
1
2019-06-11T04:57:34.000Z
2019-06-11T04:57:34.000Z
kuber/latest/authorization_v1.py
datalayer-externals/kuber
4d577950ce7d1be2b882fbe66827dc3d7e67b350
[ "MIT" ]
1
2019-05-05T22:08:13.000Z
2019-05-06T11:43:32.000Z
kuber/latest/authorization_v1.py
datalayer-externals/kuber
4d577950ce7d1be2b882fbe66827dc3d7e67b350
[ "MIT" ]
2
2021-05-08T14:47:56.000Z
2021-10-15T21:47:04.000Z
import typing # noqa: F401 from kubernetes import client # noqa: F401 from kuber import kube_api as _kube_api # noqa: F401 from kuber import definitions as _kuber_definitions # noqa: F401 from kuber import _types # noqa: F401 from kuber.latest.meta_v1 import ListMeta # noqa: F401 from kuber.latest.meta_v1 import ObjectMeta # noqa: F401 from kuber.latest.meta_v1 import Status # noqa: F401 from kuber.latest.meta_v1 import StatusDetails # noqa: F401 class LocalSubjectAccessReview(_kuber_definitions.Resource): """ LocalSubjectAccessReview checks whether or not a user or group can perform an action in a given namespace. Having a namespace scoped resource makes it much easier to grant namespace scoped policy that includes permissions checking. """ def __init__( self, metadata: "ObjectMeta" = None, spec: "SubjectAccessReviewSpec" = None, status: "SubjectAccessReviewStatus" = None, ): """Create LocalSubjectAccessReview instance.""" super(LocalSubjectAccessReview, self).__init__( api_version="authorization/v1", kind="LocalSubjectAccessReview" ) self._properties = { "metadata": metadata if metadata is not None else ObjectMeta(), "spec": spec if spec is not None else SubjectAccessReviewSpec(), "status": status if status is not None else SubjectAccessReviewStatus(), } self._types = { "apiVersion": (str, None), "kind": (str, None), "metadata": (ObjectMeta, None), "spec": (SubjectAccessReviewSpec, None), "status": (SubjectAccessReviewStatus, None), } @property def metadata(self) -> "ObjectMeta": """ Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig- architecture/api-conventions.md#metadata """ return typing.cast( "ObjectMeta", self._properties.get("metadata"), ) @metadata.setter def metadata(self, value: typing.Union["ObjectMeta", dict]): """ Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig- architecture/api-conventions.md#metadata """ if isinstance(value, dict): value = typing.cast( ObjectMeta, ObjectMeta().from_dict(value), ) self._properties["metadata"] = value @property def spec(self) -> "SubjectAccessReviewSpec": """ Spec holds information about the request being evaluated. spec.namespace must be equal to the namespace you made the request against. If empty, it is defaulted. """ return typing.cast( "SubjectAccessReviewSpec", self._properties.get("spec"), ) @spec.setter def spec(self, value: typing.Union["SubjectAccessReviewSpec", dict]): """ Spec holds information about the request being evaluated. spec.namespace must be equal to the namespace you made the request against. If empty, it is defaulted. """ if isinstance(value, dict): value = typing.cast( SubjectAccessReviewSpec, SubjectAccessReviewSpec().from_dict(value), ) self._properties["spec"] = value @property def status(self) -> "SubjectAccessReviewStatus": """ Status is filled in by the server and indicates whether the request is allowed or not """ return typing.cast( "SubjectAccessReviewStatus", self._properties.get("status"), ) @status.setter def status(self, value: typing.Union["SubjectAccessReviewStatus", dict]): """ Status is filled in by the server and indicates whether the request is allowed or not """ if isinstance(value, dict): value = typing.cast( SubjectAccessReviewStatus, SubjectAccessReviewStatus().from_dict(value), ) self._properties["status"] = value def create_resource(self, namespace: "str" = None) -> "SubjectAccessReviewStatus": """ Creates the LocalSubjectAccessReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the create is complete. """ names = [ "create_namespaced_local_subject_access_review", "create_local_subject_access_review", ] response = _kube_api.execute( action="create", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict()}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def replace_resource(self, namespace: "str" = None) -> "SubjectAccessReviewStatus": """ Replaces the LocalSubjectAccessReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the replace is complete. """ names = [ "replace_namespaced_local_subject_access_review", "replace_local_subject_access_review", ] response = _kube_api.execute( action="replace", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict(), "name": self.metadata.name}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def patch_resource(self, namespace: "str" = None) -> "SubjectAccessReviewStatus": """ Patches the LocalSubjectAccessReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the replace is complete. """ names = [ "patch_namespaced_local_subject_access_review", "patch_local_subject_access_review", ] response = _kube_api.execute( action="patch", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict(), "name": self.metadata.name}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def get_resource_status( self, namespace: "str" = None ) -> "SubjectAccessReviewStatus": """ Returns status information about the given resource within the cluster. """ names = [ "read_namespaced_local_subject_access_review", "read_local_subject_access_review", ] response = _kube_api.execute( action="read", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def read_resource(self, namespace: str = None): """ Reads the LocalSubjectAccessReview from the currently configured Kubernetes cluster and returns the low-level definition object. """ names = [ "read_namespaced_local_subject_access_review", "read_local_subject_access_review", ] return _kube_api.execute( action="read", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name}, ) def delete_resource( self, namespace: str = None, propagation_policy: str = "Foreground", grace_period_seconds: int = 10, ): """ Deletes the LocalSubjectAccessReview from the currently configured Kubernetes cluster. """ names = [ "delete_namespaced_local_subject_access_review", "delete_local_subject_access_review", ] body = client.V1DeleteOptions( propagation_policy=propagation_policy, grace_period_seconds=grace_period_seconds, ) _kube_api.execute( action="delete", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name, "body": body}, ) @staticmethod def get_resource_api( api_client: client.ApiClient = None, **kwargs ) -> "client.AuthorizationV1Api": """ Returns an instance of the kubernetes API client associated with this object. """ if api_client: kwargs["apl_client"] = api_client return client.AuthorizationV1Api(**kwargs) class NonResourceAttributes(_kuber_definitions.Definition): """ NonResourceAttributes includes the authorization attributes available for non-resource requests to the Authorizer interface """ def __init__( self, path: str = None, verb: str = None, ): """Create NonResourceAttributes instance.""" super(NonResourceAttributes, self).__init__( api_version="authorization/v1", kind="NonResourceAttributes" ) self._properties = { "path": path if path is not None else "", "verb": verb if verb is not None else "", } self._types = { "path": (str, None), "verb": (str, None), } @property def path(self) -> str: """ Path is the URL path of the request """ return typing.cast( str, self._properties.get("path"), ) @path.setter def path(self, value: str): """ Path is the URL path of the request """ self._properties["path"] = value @property def verb(self) -> str: """ Verb is the standard HTTP verb """ return typing.cast( str, self._properties.get("verb"), ) @verb.setter def verb(self, value: str): """ Verb is the standard HTTP verb """ self._properties["verb"] = value class NonResourceRule(_kuber_definitions.Definition): """ NonResourceRule holds information that describes a rule for the non-resource """ def __init__( self, non_resource_urls: typing.List[str] = None, verbs: typing.List[str] = None, ): """Create NonResourceRule instance.""" super(NonResourceRule, self).__init__( api_version="authorization/v1", kind="NonResourceRule" ) self._properties = { "nonResourceURLs": non_resource_urls if non_resource_urls is not None else [], "verbs": verbs if verbs is not None else [], } self._types = { "nonResourceURLs": (list, str), "verbs": (list, str), } @property def non_resource_urls(self) -> typing.List[str]: """ NonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path. "*" means all. """ return typing.cast( typing.List[str], self._properties.get("nonResourceURLs"), ) @non_resource_urls.setter def non_resource_urls(self, value: typing.List[str]): """ NonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path. "*" means all. """ self._properties["nonResourceURLs"] = value @property def verbs(self) -> typing.List[str]: """ Verb is a list of kubernetes non-resource API verbs, like: get, post, put, delete, patch, head, options. "*" means all. """ return typing.cast( typing.List[str], self._properties.get("verbs"), ) @verbs.setter def verbs(self, value: typing.List[str]): """ Verb is a list of kubernetes non-resource API verbs, like: get, post, put, delete, patch, head, options. "*" means all. """ self._properties["verbs"] = value class ResourceAttributes(_kuber_definitions.Definition): """ ResourceAttributes includes the authorization attributes available for resource requests to the Authorizer interface """ def __init__( self, group: str = None, name: str = None, namespace: str = None, resource: str = None, subresource: str = None, verb: str = None, version: str = None, ): """Create ResourceAttributes instance.""" super(ResourceAttributes, self).__init__( api_version="authorization/v1", kind="ResourceAttributes" ) self._properties = { "group": group if group is not None else "", "name": name if name is not None else "", "namespace": namespace if namespace is not None else "", "resource": resource if resource is not None else "", "subresource": subresource if subresource is not None else "", "verb": verb if verb is not None else "", "version": version if version is not None else "", } self._types = { "group": (str, None), "name": (str, None), "namespace": (str, None), "resource": (str, None), "subresource": (str, None), "verb": (str, None), "version": (str, None), } @property def group(self) -> str: """ Group is the API Group of the Resource. "*" means all. """ return typing.cast( str, self._properties.get("group"), ) @group.setter def group(self, value: str): """ Group is the API Group of the Resource. "*" means all. """ self._properties["group"] = value @property def name(self) -> str: """ Name is the name of the resource being requested for a "get" or deleted for a "delete". "" (empty) means all. """ return typing.cast( str, self._properties.get("name"), ) @name.setter def name(self, value: str): """ Name is the name of the resource being requested for a "get" or deleted for a "delete". "" (empty) means all. """ self._properties["name"] = value @property def namespace(self) -> str: """ Namespace is the namespace of the action being requested. Currently, there is no distinction between no namespace and all namespaces "" (empty) is defaulted for LocalSubjectAccessReviews "" (empty) is empty for cluster- scoped resources "" (empty) means "all" for namespace scoped resources from a SubjectAccessReview or SelfSubjectAccessReview """ return typing.cast( str, self._properties.get("namespace"), ) @namespace.setter def namespace(self, value: str): """ Namespace is the namespace of the action being requested. Currently, there is no distinction between no namespace and all namespaces "" (empty) is defaulted for LocalSubjectAccessReviews "" (empty) is empty for cluster- scoped resources "" (empty) means "all" for namespace scoped resources from a SubjectAccessReview or SelfSubjectAccessReview """ self._properties["namespace"] = value @property def resource(self) -> str: """ Resource is one of the existing resource types. "*" means all. """ return typing.cast( str, self._properties.get("resource"), ) @resource.setter def resource(self, value: str): """ Resource is one of the existing resource types. "*" means all. """ self._properties["resource"] = value @property def subresource(self) -> str: """ Subresource is one of the existing resource types. "" means none. """ return typing.cast( str, self._properties.get("subresource"), ) @subresource.setter def subresource(self, value: str): """ Subresource is one of the existing resource types. "" means none. """ self._properties["subresource"] = value @property def verb(self) -> str: """ Verb is a kubernetes resource API verb, like: get, list, watch, create, update, delete, proxy. "*" means all. """ return typing.cast( str, self._properties.get("verb"), ) @verb.setter def verb(self, value: str): """ Verb is a kubernetes resource API verb, like: get, list, watch, create, update, delete, proxy. "*" means all. """ self._properties["verb"] = value @property def version(self) -> str: """ Version is the API Version of the Resource. "*" means all. """ return typing.cast( str, self._properties.get("version"), ) @version.setter def version(self, value: str): """ Version is the API Version of the Resource. "*" means all. """ self._properties["version"] = value class ResourceRule(_kuber_definitions.Definition): """ ResourceRule is the list of actions the subject is allowed to perform on resources. The list ordering isn't significant, may contain duplicates, and possibly be incomplete. """ def __init__( self, api_groups: typing.List[str] = None, resource_names: typing.List[str] = None, resources: typing.List[str] = None, verbs: typing.List[str] = None, ): """Create ResourceRule instance.""" super(ResourceRule, self).__init__( api_version="authorization/v1", kind="ResourceRule" ) self._properties = { "apiGroups": api_groups if api_groups is not None else [], "resourceNames": resource_names if resource_names is not None else [], "resources": resources if resources is not None else [], "verbs": verbs if verbs is not None else [], } self._types = { "apiGroups": (list, str), "resourceNames": (list, str), "resources": (list, str), "verbs": (list, str), } @property def api_groups(self) -> typing.List[str]: """ APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of the enumerated resources in any API group will be allowed. "*" means all. """ return typing.cast( typing.List[str], self._properties.get("apiGroups"), ) @api_groups.setter def api_groups(self, value: typing.List[str]): """ APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of the enumerated resources in any API group will be allowed. "*" means all. """ self._properties["apiGroups"] = value @property def resource_names(self) -> typing.List[str]: """ ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. "*" means all. """ return typing.cast( typing.List[str], self._properties.get("resourceNames"), ) @resource_names.setter def resource_names(self, value: typing.List[str]): """ ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. "*" means all. """ self._properties["resourceNames"] = value @property def resources(self) -> typing.List[str]: """ Resources is a list of resources this rule applies to. "*" means all in the specified apiGroups. "*/foo" represents the subresource 'foo' for all resources in the specified apiGroups. """ return typing.cast( typing.List[str], self._properties.get("resources"), ) @resources.setter def resources(self, value: typing.List[str]): """ Resources is a list of resources this rule applies to. "*" means all in the specified apiGroups. "*/foo" represents the subresource 'foo' for all resources in the specified apiGroups. """ self._properties["resources"] = value @property def verbs(self) -> typing.List[str]: """ Verb is a list of kubernetes resource API verbs, like: get, list, watch, create, update, delete, proxy. "*" means all. """ return typing.cast( typing.List[str], self._properties.get("verbs"), ) @verbs.setter def verbs(self, value: typing.List[str]): """ Verb is a list of kubernetes resource API verbs, like: get, list, watch, create, update, delete, proxy. "*" means all. """ self._properties["verbs"] = value class SelfSubjectAccessReview(_kuber_definitions.Resource): """ SelfSubjectAccessReview checks whether or the current user can perform an action. Not filling in a spec.namespace means "in all namespaces". Self is a special case, because users should always be able to check whether they can perform an action """ def __init__( self, metadata: "ObjectMeta" = None, spec: "SelfSubjectAccessReviewSpec" = None, status: "SubjectAccessReviewStatus" = None, ): """Create SelfSubjectAccessReview instance.""" super(SelfSubjectAccessReview, self).__init__( api_version="authorization/v1", kind="SelfSubjectAccessReview" ) self._properties = { "metadata": metadata if metadata is not None else ObjectMeta(), "spec": spec if spec is not None else SelfSubjectAccessReviewSpec(), "status": status if status is not None else SubjectAccessReviewStatus(), } self._types = { "apiVersion": (str, None), "kind": (str, None), "metadata": (ObjectMeta, None), "spec": (SelfSubjectAccessReviewSpec, None), "status": (SubjectAccessReviewStatus, None), } @property def metadata(self) -> "ObjectMeta": """ Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig- architecture/api-conventions.md#metadata """ return typing.cast( "ObjectMeta", self._properties.get("metadata"), ) @metadata.setter def metadata(self, value: typing.Union["ObjectMeta", dict]): """ Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig- architecture/api-conventions.md#metadata """ if isinstance(value, dict): value = typing.cast( ObjectMeta, ObjectMeta().from_dict(value), ) self._properties["metadata"] = value @property def spec(self) -> "SelfSubjectAccessReviewSpec": """ Spec holds information about the request being evaluated. user and groups must be empty """ return typing.cast( "SelfSubjectAccessReviewSpec", self._properties.get("spec"), ) @spec.setter def spec(self, value: typing.Union["SelfSubjectAccessReviewSpec", dict]): """ Spec holds information about the request being evaluated. user and groups must be empty """ if isinstance(value, dict): value = typing.cast( SelfSubjectAccessReviewSpec, SelfSubjectAccessReviewSpec().from_dict(value), ) self._properties["spec"] = value @property def status(self) -> "SubjectAccessReviewStatus": """ Status is filled in by the server and indicates whether the request is allowed or not """ return typing.cast( "SubjectAccessReviewStatus", self._properties.get("status"), ) @status.setter def status(self, value: typing.Union["SubjectAccessReviewStatus", dict]): """ Status is filled in by the server and indicates whether the request is allowed or not """ if isinstance(value, dict): value = typing.cast( SubjectAccessReviewStatus, SubjectAccessReviewStatus().from_dict(value), ) self._properties["status"] = value def create_resource(self, namespace: "str" = None) -> "SubjectAccessReviewStatus": """ Creates the SelfSubjectAccessReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the create is complete. """ names = [ "create_namespaced_self_subject_access_review", "create_self_subject_access_review", ] response = _kube_api.execute( action="create", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict()}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def replace_resource(self, namespace: "str" = None) -> "SubjectAccessReviewStatus": """ Replaces the SelfSubjectAccessReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the replace is complete. """ names = [ "replace_namespaced_self_subject_access_review", "replace_self_subject_access_review", ] response = _kube_api.execute( action="replace", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict(), "name": self.metadata.name}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def patch_resource(self, namespace: "str" = None) -> "SubjectAccessReviewStatus": """ Patches the SelfSubjectAccessReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the replace is complete. """ names = [ "patch_namespaced_self_subject_access_review", "patch_self_subject_access_review", ] response = _kube_api.execute( action="patch", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict(), "name": self.metadata.name}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def get_resource_status( self, namespace: "str" = None ) -> "SubjectAccessReviewStatus": """ Returns status information about the given resource within the cluster. """ names = [ "read_namespaced_self_subject_access_review", "read_self_subject_access_review", ] response = _kube_api.execute( action="read", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def read_resource(self, namespace: str = None): """ Reads the SelfSubjectAccessReview from the currently configured Kubernetes cluster and returns the low-level definition object. """ names = [ "read_namespaced_self_subject_access_review", "read_self_subject_access_review", ] return _kube_api.execute( action="read", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name}, ) def delete_resource( self, namespace: str = None, propagation_policy: str = "Foreground", grace_period_seconds: int = 10, ): """ Deletes the SelfSubjectAccessReview from the currently configured Kubernetes cluster. """ names = [ "delete_namespaced_self_subject_access_review", "delete_self_subject_access_review", ] body = client.V1DeleteOptions( propagation_policy=propagation_policy, grace_period_seconds=grace_period_seconds, ) _kube_api.execute( action="delete", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name, "body": body}, ) @staticmethod def get_resource_api( api_client: client.ApiClient = None, **kwargs ) -> "client.AuthorizationV1Api": """ Returns an instance of the kubernetes API client associated with this object. """ if api_client: kwargs["apl_client"] = api_client return client.AuthorizationV1Api(**kwargs) class SelfSubjectAccessReviewSpec(_kuber_definitions.Definition): """ SelfSubjectAccessReviewSpec is a description of the access request. Exactly one of ResourceAuthorizationAttributes and NonResourceAuthorizationAttributes must be set """ def __init__( self, non_resource_attributes: "NonResourceAttributes" = None, resource_attributes: "ResourceAttributes" = None, ): """Create SelfSubjectAccessReviewSpec instance.""" super(SelfSubjectAccessReviewSpec, self).__init__( api_version="authorization/v1", kind="SelfSubjectAccessReviewSpec" ) self._properties = { "nonResourceAttributes": non_resource_attributes if non_resource_attributes is not None else NonResourceAttributes(), "resourceAttributes": resource_attributes if resource_attributes is not None else ResourceAttributes(), } self._types = { "nonResourceAttributes": (NonResourceAttributes, None), "resourceAttributes": (ResourceAttributes, None), } @property def non_resource_attributes(self) -> "NonResourceAttributes": """ NonResourceAttributes describes information for a non- resource access request """ return typing.cast( "NonResourceAttributes", self._properties.get("nonResourceAttributes"), ) @non_resource_attributes.setter def non_resource_attributes( self, value: typing.Union["NonResourceAttributes", dict] ): """ NonResourceAttributes describes information for a non- resource access request """ if isinstance(value, dict): value = typing.cast( NonResourceAttributes, NonResourceAttributes().from_dict(value), ) self._properties["nonResourceAttributes"] = value @property def resource_attributes(self) -> "ResourceAttributes": """ ResourceAuthorizationAttributes describes information for a resource access request """ return typing.cast( "ResourceAttributes", self._properties.get("resourceAttributes"), ) @resource_attributes.setter def resource_attributes(self, value: typing.Union["ResourceAttributes", dict]): """ ResourceAuthorizationAttributes describes information for a resource access request """ if isinstance(value, dict): value = typing.cast( ResourceAttributes, ResourceAttributes().from_dict(value), ) self._properties["resourceAttributes"] = value class SelfSubjectRulesReview(_kuber_definitions.Resource): """ SelfSubjectRulesReview enumerates the set of actions the current user can perform within a namespace. The returned list of actions may be incomplete depending on the server's authorization mode, and any errors experienced during the evaluation. SelfSubjectRulesReview should be used by UIs to show/hide actions, or to quickly let an end user reason about their permissions. It should NOT Be used by external systems to drive authorization decisions as this raises confused deputy, cache lifetime/revocation, and correctness concerns. SubjectAccessReview, and LocalAccessReview are the correct way to defer authorization decisions to the API server. """ def __init__( self, metadata: "ObjectMeta" = None, spec: "SelfSubjectRulesReviewSpec" = None, status: "SubjectRulesReviewStatus" = None, ): """Create SelfSubjectRulesReview instance.""" super(SelfSubjectRulesReview, self).__init__( api_version="authorization/v1", kind="SelfSubjectRulesReview" ) self._properties = { "metadata": metadata if metadata is not None else ObjectMeta(), "spec": spec if spec is not None else SelfSubjectRulesReviewSpec(), "status": status if status is not None else SubjectRulesReviewStatus(), } self._types = { "apiVersion": (str, None), "kind": (str, None), "metadata": (ObjectMeta, None), "spec": (SelfSubjectRulesReviewSpec, None), "status": (SubjectRulesReviewStatus, None), } @property def metadata(self) -> "ObjectMeta": """ Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig- architecture/api-conventions.md#metadata """ return typing.cast( "ObjectMeta", self._properties.get("metadata"), ) @metadata.setter def metadata(self, value: typing.Union["ObjectMeta", dict]): """ Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig- architecture/api-conventions.md#metadata """ if isinstance(value, dict): value = typing.cast( ObjectMeta, ObjectMeta().from_dict(value), ) self._properties["metadata"] = value @property def spec(self) -> "SelfSubjectRulesReviewSpec": """ Spec holds information about the request being evaluated. """ return typing.cast( "SelfSubjectRulesReviewSpec", self._properties.get("spec"), ) @spec.setter def spec(self, value: typing.Union["SelfSubjectRulesReviewSpec", dict]): """ Spec holds information about the request being evaluated. """ if isinstance(value, dict): value = typing.cast( SelfSubjectRulesReviewSpec, SelfSubjectRulesReviewSpec().from_dict(value), ) self._properties["spec"] = value @property def status(self) -> "SubjectRulesReviewStatus": """ Status is filled in by the server and indicates the set of actions a user can perform. """ return typing.cast( "SubjectRulesReviewStatus", self._properties.get("status"), ) @status.setter def status(self, value: typing.Union["SubjectRulesReviewStatus", dict]): """ Status is filled in by the server and indicates the set of actions a user can perform. """ if isinstance(value, dict): value = typing.cast( SubjectRulesReviewStatus, SubjectRulesReviewStatus().from_dict(value), ) self._properties["status"] = value def create_resource(self, namespace: "str" = None) -> "SubjectRulesReviewStatus": """ Creates the SelfSubjectRulesReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the create is complete. """ names = [ "create_namespaced_self_subject_rules_review", "create_self_subject_rules_review", ] response = _kube_api.execute( action="create", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict()}, ) output = SubjectRulesReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def replace_resource(self, namespace: "str" = None) -> "SubjectRulesReviewStatus": """ Replaces the SelfSubjectRulesReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the replace is complete. """ names = [ "replace_namespaced_self_subject_rules_review", "replace_self_subject_rules_review", ] response = _kube_api.execute( action="replace", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict(), "name": self.metadata.name}, ) output = SubjectRulesReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def patch_resource(self, namespace: "str" = None) -> "SubjectRulesReviewStatus": """ Patches the SelfSubjectRulesReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the replace is complete. """ names = [ "patch_namespaced_self_subject_rules_review", "patch_self_subject_rules_review", ] response = _kube_api.execute( action="patch", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict(), "name": self.metadata.name}, ) output = SubjectRulesReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def get_resource_status( self, namespace: "str" = None ) -> "SubjectRulesReviewStatus": """ Returns status information about the given resource within the cluster. """ names = [ "read_namespaced_self_subject_rules_review", "read_self_subject_rules_review", ] response = _kube_api.execute( action="read", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name}, ) output = SubjectRulesReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def read_resource(self, namespace: str = None): """ Reads the SelfSubjectRulesReview from the currently configured Kubernetes cluster and returns the low-level definition object. """ names = [ "read_namespaced_self_subject_rules_review", "read_self_subject_rules_review", ] return _kube_api.execute( action="read", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name}, ) def delete_resource( self, namespace: str = None, propagation_policy: str = "Foreground", grace_period_seconds: int = 10, ): """ Deletes the SelfSubjectRulesReview from the currently configured Kubernetes cluster. """ names = [ "delete_namespaced_self_subject_rules_review", "delete_self_subject_rules_review", ] body = client.V1DeleteOptions( propagation_policy=propagation_policy, grace_period_seconds=grace_period_seconds, ) _kube_api.execute( action="delete", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name, "body": body}, ) @staticmethod def get_resource_api( api_client: client.ApiClient = None, **kwargs ) -> "client.AuthorizationV1Api": """ Returns an instance of the kubernetes API client associated with this object. """ if api_client: kwargs["apl_client"] = api_client return client.AuthorizationV1Api(**kwargs) class SelfSubjectRulesReviewSpec(_kuber_definitions.Definition): """ SelfSubjectRulesReviewSpec defines the specification for SelfSubjectRulesReview. """ def __init__( self, namespace: str = None, ): """Create SelfSubjectRulesReviewSpec instance.""" super(SelfSubjectRulesReviewSpec, self).__init__( api_version="authorization/v1", kind="SelfSubjectRulesReviewSpec" ) self._properties = { "namespace": namespace if namespace is not None else "", } self._types = { "namespace": (str, None), } @property def namespace(self) -> str: """ Namespace to evaluate rules for. Required. """ return typing.cast( str, self._properties.get("namespace"), ) @namespace.setter def namespace(self, value: str): """ Namespace to evaluate rules for. Required. """ self._properties["namespace"] = value class SubjectAccessReview(_kuber_definitions.Resource): """ SubjectAccessReview checks whether or not a user or group can perform an action. """ def __init__( self, metadata: "ObjectMeta" = None, spec: "SubjectAccessReviewSpec" = None, status: "SubjectAccessReviewStatus" = None, ): """Create SubjectAccessReview instance.""" super(SubjectAccessReview, self).__init__( api_version="authorization/v1", kind="SubjectAccessReview" ) self._properties = { "metadata": metadata if metadata is not None else ObjectMeta(), "spec": spec if spec is not None else SubjectAccessReviewSpec(), "status": status if status is not None else SubjectAccessReviewStatus(), } self._types = { "apiVersion": (str, None), "kind": (str, None), "metadata": (ObjectMeta, None), "spec": (SubjectAccessReviewSpec, None), "status": (SubjectAccessReviewStatus, None), } @property def metadata(self) -> "ObjectMeta": """ Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig- architecture/api-conventions.md#metadata """ return typing.cast( "ObjectMeta", self._properties.get("metadata"), ) @metadata.setter def metadata(self, value: typing.Union["ObjectMeta", dict]): """ Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig- architecture/api-conventions.md#metadata """ if isinstance(value, dict): value = typing.cast( ObjectMeta, ObjectMeta().from_dict(value), ) self._properties["metadata"] = value @property def spec(self) -> "SubjectAccessReviewSpec": """ Spec holds information about the request being evaluated """ return typing.cast( "SubjectAccessReviewSpec", self._properties.get("spec"), ) @spec.setter def spec(self, value: typing.Union["SubjectAccessReviewSpec", dict]): """ Spec holds information about the request being evaluated """ if isinstance(value, dict): value = typing.cast( SubjectAccessReviewSpec, SubjectAccessReviewSpec().from_dict(value), ) self._properties["spec"] = value @property def status(self) -> "SubjectAccessReviewStatus": """ Status is filled in by the server and indicates whether the request is allowed or not """ return typing.cast( "SubjectAccessReviewStatus", self._properties.get("status"), ) @status.setter def status(self, value: typing.Union["SubjectAccessReviewStatus", dict]): """ Status is filled in by the server and indicates whether the request is allowed or not """ if isinstance(value, dict): value = typing.cast( SubjectAccessReviewStatus, SubjectAccessReviewStatus().from_dict(value), ) self._properties["status"] = value def create_resource(self, namespace: "str" = None) -> "SubjectAccessReviewStatus": """ Creates the SubjectAccessReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the create is complete. """ names = [ "create_namespaced_subject_access_review", "create_subject_access_review", ] response = _kube_api.execute( action="create", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict()}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def replace_resource(self, namespace: "str" = None) -> "SubjectAccessReviewStatus": """ Replaces the SubjectAccessReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the replace is complete. """ names = [ "replace_namespaced_subject_access_review", "replace_subject_access_review", ] response = _kube_api.execute( action="replace", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict(), "name": self.metadata.name}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def patch_resource(self, namespace: "str" = None) -> "SubjectAccessReviewStatus": """ Patches the SubjectAccessReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the replace is complete. """ names = [ "patch_namespaced_subject_access_review", "patch_subject_access_review", ] response = _kube_api.execute( action="patch", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict(), "name": self.metadata.name}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def get_resource_status( self, namespace: "str" = None ) -> "SubjectAccessReviewStatus": """ Returns status information about the given resource within the cluster. """ names = [ "read_namespaced_subject_access_review", "read_subject_access_review", ] response = _kube_api.execute( action="read", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def read_resource(self, namespace: str = None): """ Reads the SubjectAccessReview from the currently configured Kubernetes cluster and returns the low-level definition object. """ names = [ "read_namespaced_subject_access_review", "read_subject_access_review", ] return _kube_api.execute( action="read", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name}, ) def delete_resource( self, namespace: str = None, propagation_policy: str = "Foreground", grace_period_seconds: int = 10, ): """ Deletes the SubjectAccessReview from the currently configured Kubernetes cluster. """ names = [ "delete_namespaced_subject_access_review", "delete_subject_access_review", ] body = client.V1DeleteOptions( propagation_policy=propagation_policy, grace_period_seconds=grace_period_seconds, ) _kube_api.execute( action="delete", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name, "body": body}, ) @staticmethod def get_resource_api( api_client: client.ApiClient = None, **kwargs ) -> "client.AuthorizationV1Api": """ Returns an instance of the kubernetes API client associated with this object. """ if api_client: kwargs["apl_client"] = api_client return client.AuthorizationV1Api(**kwargs) class SubjectAccessReviewSpec(_kuber_definitions.Definition): """ SubjectAccessReviewSpec is a description of the access request. Exactly one of ResourceAuthorizationAttributes and NonResourceAuthorizationAttributes must be set """ def __init__( self, extra: dict = None, groups: typing.List[str] = None, non_resource_attributes: "NonResourceAttributes" = None, resource_attributes: "ResourceAttributes" = None, uid: str = None, user: str = None, ): """Create SubjectAccessReviewSpec instance.""" super(SubjectAccessReviewSpec, self).__init__( api_version="authorization/v1", kind="SubjectAccessReviewSpec" ) self._properties = { "extra": extra if extra is not None else {}, "groups": groups if groups is not None else [], "nonResourceAttributes": non_resource_attributes if non_resource_attributes is not None else NonResourceAttributes(), "resourceAttributes": resource_attributes if resource_attributes is not None else ResourceAttributes(), "uid": uid if uid is not None else "", "user": user if user is not None else "", } self._types = { "extra": (dict, None), "groups": (list, str), "nonResourceAttributes": (NonResourceAttributes, None), "resourceAttributes": (ResourceAttributes, None), "uid": (str, None), "user": (str, None), } @property def extra(self) -> dict: """ Extra corresponds to the user.Info.GetExtra() method from the authenticator. Since that is input to the authorizer it needs a reflection here. """ return typing.cast( dict, self._properties.get("extra"), ) @extra.setter def extra(self, value: dict): """ Extra corresponds to the user.Info.GetExtra() method from the authenticator. Since that is input to the authorizer it needs a reflection here. """ self._properties["extra"] = value @property def groups(self) -> typing.List[str]: """ Groups is the groups you're testing for. """ return typing.cast( typing.List[str], self._properties.get("groups"), ) @groups.setter def groups(self, value: typing.List[str]): """ Groups is the groups you're testing for. """ self._properties["groups"] = value @property def non_resource_attributes(self) -> "NonResourceAttributes": """ NonResourceAttributes describes information for a non- resource access request """ return typing.cast( "NonResourceAttributes", self._properties.get("nonResourceAttributes"), ) @non_resource_attributes.setter def non_resource_attributes( self, value: typing.Union["NonResourceAttributes", dict] ): """ NonResourceAttributes describes information for a non- resource access request """ if isinstance(value, dict): value = typing.cast( NonResourceAttributes, NonResourceAttributes().from_dict(value), ) self._properties["nonResourceAttributes"] = value @property def resource_attributes(self) -> "ResourceAttributes": """ ResourceAuthorizationAttributes describes information for a resource access request """ return typing.cast( "ResourceAttributes", self._properties.get("resourceAttributes"), ) @resource_attributes.setter def resource_attributes(self, value: typing.Union["ResourceAttributes", dict]): """ ResourceAuthorizationAttributes describes information for a resource access request """ if isinstance(value, dict): value = typing.cast( ResourceAttributes, ResourceAttributes().from_dict(value), ) self._properties["resourceAttributes"] = value @property def uid(self) -> str: """ UID information about the requesting user. """ return typing.cast( str, self._properties.get("uid"), ) @uid.setter def uid(self, value: str): """ UID information about the requesting user. """ self._properties["uid"] = value @property def user(self) -> str: """ User is the user you're testing for. If you specify "User" but not "Groups", then is it interpreted as "What if User were not a member of any groups """ return typing.cast( str, self._properties.get("user"), ) @user.setter def user(self, value: str): """ User is the user you're testing for. If you specify "User" but not "Groups", then is it interpreted as "What if User were not a member of any groups """ self._properties["user"] = value class SubjectAccessReviewStatus(_kuber_definitions.Definition): """ SubjectAccessReviewStatus """ def __init__( self, allowed: bool = None, denied: bool = None, evaluation_error: str = None, reason: str = None, ): """Create SubjectAccessReviewStatus instance.""" super(SubjectAccessReviewStatus, self).__init__( api_version="authorization/v1", kind="SubjectAccessReviewStatus" ) self._properties = { "allowed": allowed if allowed is not None else None, "denied": denied if denied is not None else None, "evaluationError": evaluation_error if evaluation_error is not None else "", "reason": reason if reason is not None else "", } self._types = { "allowed": (bool, None), "denied": (bool, None), "evaluationError": (str, None), "reason": (str, None), } @property def allowed(self) -> bool: """ Allowed is required. True if the action would be allowed, false otherwise. """ return typing.cast( bool, self._properties.get("allowed"), ) @allowed.setter def allowed(self, value: bool): """ Allowed is required. True if the action would be allowed, false otherwise. """ self._properties["allowed"] = value @property def denied(self) -> bool: """ Denied is optional. True if the action would be denied, otherwise false. If both allowed is false and denied is false, then the authorizer has no opinion on whether to authorize the action. Denied may not be true if Allowed is true. """ return typing.cast( bool, self._properties.get("denied"), ) @denied.setter def denied(self, value: bool): """ Denied is optional. True if the action would be denied, otherwise false. If both allowed is false and denied is false, then the authorizer has no opinion on whether to authorize the action. Denied may not be true if Allowed is true. """ self._properties["denied"] = value @property def evaluation_error(self) -> str: """ EvaluationError is an indication that some error occurred during the authorization check. It is entirely possible to get an error and be able to continue determine authorization status in spite of it. For instance, RBAC can be missing a role, but enough roles are still present and bound to reason about the request. """ return typing.cast( str, self._properties.get("evaluationError"), ) @evaluation_error.setter def evaluation_error(self, value: str): """ EvaluationError is an indication that some error occurred during the authorization check. It is entirely possible to get an error and be able to continue determine authorization status in spite of it. For instance, RBAC can be missing a role, but enough roles are still present and bound to reason about the request. """ self._properties["evaluationError"] = value @property def reason(self) -> str: """ Reason is optional. It indicates why a request was allowed or denied. """ return typing.cast( str, self._properties.get("reason"), ) @reason.setter def reason(self, value: str): """ Reason is optional. It indicates why a request was allowed or denied. """ self._properties["reason"] = value class SubjectRulesReviewStatus(_kuber_definitions.Definition): """ SubjectRulesReviewStatus contains the result of a rules check. This check can be incomplete depending on the set of authorizers the server is configured with and any errors experienced during evaluation. Because authorization rules are additive, if a rule appears in a list it's safe to assume the subject has that permission, even if that list is incomplete. """ def __init__( self, evaluation_error: str = None, incomplete: bool = None, non_resource_rules: typing.List["NonResourceRule"] = None, resource_rules: typing.List["ResourceRule"] = None, ): """Create SubjectRulesReviewStatus instance.""" super(SubjectRulesReviewStatus, self).__init__( api_version="authorization/v1", kind="SubjectRulesReviewStatus" ) self._properties = { "evaluationError": evaluation_error if evaluation_error is not None else "", "incomplete": incomplete if incomplete is not None else None, "nonResourceRules": non_resource_rules if non_resource_rules is not None else [], "resourceRules": resource_rules if resource_rules is not None else [], } self._types = { "evaluationError": (str, None), "incomplete": (bool, None), "nonResourceRules": (list, NonResourceRule), "resourceRules": (list, ResourceRule), } @property def evaluation_error(self) -> str: """ EvaluationError can appear in combination with Rules. It indicates an error occurred during rule evaluation, such as an authorizer that doesn't support rule evaluation, and that ResourceRules and/or NonResourceRules may be incomplete. """ return typing.cast( str, self._properties.get("evaluationError"), ) @evaluation_error.setter def evaluation_error(self, value: str): """ EvaluationError can appear in combination with Rules. It indicates an error occurred during rule evaluation, such as an authorizer that doesn't support rule evaluation, and that ResourceRules and/or NonResourceRules may be incomplete. """ self._properties["evaluationError"] = value @property def incomplete(self) -> bool: """ Incomplete is true when the rules returned by this call are incomplete. This is most commonly encountered when an authorizer, such as an external authorizer, doesn't support rules evaluation. """ return typing.cast( bool, self._properties.get("incomplete"), ) @incomplete.setter def incomplete(self, value: bool): """ Incomplete is true when the rules returned by this call are incomplete. This is most commonly encountered when an authorizer, such as an external authorizer, doesn't support rules evaluation. """ self._properties["incomplete"] = value @property def non_resource_rules(self) -> typing.List["NonResourceRule"]: """ NonResourceRules is the list of actions the subject is allowed to perform on non-resources. The list ordering isn't significant, may contain duplicates, and possibly be incomplete. """ return typing.cast( typing.List["NonResourceRule"], self._properties.get("nonResourceRules"), ) @non_resource_rules.setter def non_resource_rules( self, value: typing.Union[typing.List["NonResourceRule"], typing.List[dict]] ): """ NonResourceRules is the list of actions the subject is allowed to perform on non-resources. The list ordering isn't significant, may contain duplicates, and possibly be incomplete. """ cleaned: typing.List[NonResourceRule] = [] for item in value: if isinstance(item, dict): item = typing.cast( NonResourceRule, NonResourceRule().from_dict(item), ) cleaned.append(typing.cast(NonResourceRule, item)) self._properties["nonResourceRules"] = cleaned @property def resource_rules(self) -> typing.List["ResourceRule"]: """ ResourceRules is the list of actions the subject is allowed to perform on resources. The list ordering isn't significant, may contain duplicates, and possibly be incomplete. """ return typing.cast( typing.List["ResourceRule"], self._properties.get("resourceRules"), ) @resource_rules.setter def resource_rules( self, value: typing.Union[typing.List["ResourceRule"], typing.List[dict]] ): """ ResourceRules is the list of actions the subject is allowed to perform on resources. The list ordering isn't significant, may contain duplicates, and possibly be incomplete. """ cleaned: typing.List[ResourceRule] = [] for item in value: if isinstance(item, dict): item = typing.cast( ResourceRule, ResourceRule().from_dict(item), ) cleaned.append(typing.cast(ResourceRule, item)) self._properties["resourceRules"] = cleaned
32.321646
88
0.592007
import typing # noqa: F401 from kubernetes import client # noqa: F401 from kuber import kube_api as _kube_api # noqa: F401 from kuber import definitions as _kuber_definitions # noqa: F401 from kuber import _types # noqa: F401 from kuber.latest.meta_v1 import ListMeta # noqa: F401 from kuber.latest.meta_v1 import ObjectMeta # noqa: F401 from kuber.latest.meta_v1 import Status # noqa: F401 from kuber.latest.meta_v1 import StatusDetails # noqa: F401 class LocalSubjectAccessReview(_kuber_definitions.Resource): """ LocalSubjectAccessReview checks whether or not a user or group can perform an action in a given namespace. Having a namespace scoped resource makes it much easier to grant namespace scoped policy that includes permissions checking. """ def __init__( self, metadata: "ObjectMeta" = None, spec: "SubjectAccessReviewSpec" = None, status: "SubjectAccessReviewStatus" = None, ): """Create LocalSubjectAccessReview instance.""" super(LocalSubjectAccessReview, self).__init__( api_version="authorization/v1", kind="LocalSubjectAccessReview" ) self._properties = { "metadata": metadata if metadata is not None else ObjectMeta(), "spec": spec if spec is not None else SubjectAccessReviewSpec(), "status": status if status is not None else SubjectAccessReviewStatus(), } self._types = { "apiVersion": (str, None), "kind": (str, None), "metadata": (ObjectMeta, None), "spec": (SubjectAccessReviewSpec, None), "status": (SubjectAccessReviewStatus, None), } @property def metadata(self) -> "ObjectMeta": """ Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig- architecture/api-conventions.md#metadata """ return typing.cast( "ObjectMeta", self._properties.get("metadata"), ) @metadata.setter def metadata(self, value: typing.Union["ObjectMeta", dict]): """ Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig- architecture/api-conventions.md#metadata """ if isinstance(value, dict): value = typing.cast( ObjectMeta, ObjectMeta().from_dict(value), ) self._properties["metadata"] = value @property def spec(self) -> "SubjectAccessReviewSpec": """ Spec holds information about the request being evaluated. spec.namespace must be equal to the namespace you made the request against. If empty, it is defaulted. """ return typing.cast( "SubjectAccessReviewSpec", self._properties.get("spec"), ) @spec.setter def spec(self, value: typing.Union["SubjectAccessReviewSpec", dict]): """ Spec holds information about the request being evaluated. spec.namespace must be equal to the namespace you made the request against. If empty, it is defaulted. """ if isinstance(value, dict): value = typing.cast( SubjectAccessReviewSpec, SubjectAccessReviewSpec().from_dict(value), ) self._properties["spec"] = value @property def status(self) -> "SubjectAccessReviewStatus": """ Status is filled in by the server and indicates whether the request is allowed or not """ return typing.cast( "SubjectAccessReviewStatus", self._properties.get("status"), ) @status.setter def status(self, value: typing.Union["SubjectAccessReviewStatus", dict]): """ Status is filled in by the server and indicates whether the request is allowed or not """ if isinstance(value, dict): value = typing.cast( SubjectAccessReviewStatus, SubjectAccessReviewStatus().from_dict(value), ) self._properties["status"] = value def create_resource(self, namespace: "str" = None) -> "SubjectAccessReviewStatus": """ Creates the LocalSubjectAccessReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the create is complete. """ names = [ "create_namespaced_local_subject_access_review", "create_local_subject_access_review", ] response = _kube_api.execute( action="create", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict()}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def replace_resource(self, namespace: "str" = None) -> "SubjectAccessReviewStatus": """ Replaces the LocalSubjectAccessReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the replace is complete. """ names = [ "replace_namespaced_local_subject_access_review", "replace_local_subject_access_review", ] response = _kube_api.execute( action="replace", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict(), "name": self.metadata.name}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def patch_resource(self, namespace: "str" = None) -> "SubjectAccessReviewStatus": """ Patches the LocalSubjectAccessReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the replace is complete. """ names = [ "patch_namespaced_local_subject_access_review", "patch_local_subject_access_review", ] response = _kube_api.execute( action="patch", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict(), "name": self.metadata.name}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def get_resource_status( self, namespace: "str" = None ) -> "SubjectAccessReviewStatus": """ Returns status information about the given resource within the cluster. """ names = [ "read_namespaced_local_subject_access_review", "read_local_subject_access_review", ] response = _kube_api.execute( action="read", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def read_resource(self, namespace: str = None): """ Reads the LocalSubjectAccessReview from the currently configured Kubernetes cluster and returns the low-level definition object. """ names = [ "read_namespaced_local_subject_access_review", "read_local_subject_access_review", ] return _kube_api.execute( action="read", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name}, ) def delete_resource( self, namespace: str = None, propagation_policy: str = "Foreground", grace_period_seconds: int = 10, ): """ Deletes the LocalSubjectAccessReview from the currently configured Kubernetes cluster. """ names = [ "delete_namespaced_local_subject_access_review", "delete_local_subject_access_review", ] body = client.V1DeleteOptions( propagation_policy=propagation_policy, grace_period_seconds=grace_period_seconds, ) _kube_api.execute( action="delete", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name, "body": body}, ) @staticmethod def get_resource_api( api_client: client.ApiClient = None, **kwargs ) -> "client.AuthorizationV1Api": """ Returns an instance of the kubernetes API client associated with this object. """ if api_client: kwargs["apl_client"] = api_client return client.AuthorizationV1Api(**kwargs) def __enter__(self) -> "LocalSubjectAccessReview": return self def __exit__(self, exc_type, exc_val, exc_tb): return False class NonResourceAttributes(_kuber_definitions.Definition): """ NonResourceAttributes includes the authorization attributes available for non-resource requests to the Authorizer interface """ def __init__( self, path: str = None, verb: str = None, ): """Create NonResourceAttributes instance.""" super(NonResourceAttributes, self).__init__( api_version="authorization/v1", kind="NonResourceAttributes" ) self._properties = { "path": path if path is not None else "", "verb": verb if verb is not None else "", } self._types = { "path": (str, None), "verb": (str, None), } @property def path(self) -> str: """ Path is the URL path of the request """ return typing.cast( str, self._properties.get("path"), ) @path.setter def path(self, value: str): """ Path is the URL path of the request """ self._properties["path"] = value @property def verb(self) -> str: """ Verb is the standard HTTP verb """ return typing.cast( str, self._properties.get("verb"), ) @verb.setter def verb(self, value: str): """ Verb is the standard HTTP verb """ self._properties["verb"] = value def __enter__(self) -> "NonResourceAttributes": return self def __exit__(self, exc_type, exc_val, exc_tb): return False class NonResourceRule(_kuber_definitions.Definition): """ NonResourceRule holds information that describes a rule for the non-resource """ def __init__( self, non_resource_urls: typing.List[str] = None, verbs: typing.List[str] = None, ): """Create NonResourceRule instance.""" super(NonResourceRule, self).__init__( api_version="authorization/v1", kind="NonResourceRule" ) self._properties = { "nonResourceURLs": non_resource_urls if non_resource_urls is not None else [], "verbs": verbs if verbs is not None else [], } self._types = { "nonResourceURLs": (list, str), "verbs": (list, str), } @property def non_resource_urls(self) -> typing.List[str]: """ NonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path. "*" means all. """ return typing.cast( typing.List[str], self._properties.get("nonResourceURLs"), ) @non_resource_urls.setter def non_resource_urls(self, value: typing.List[str]): """ NonResourceURLs is a set of partial urls that a user should have access to. *s are allowed, but only as the full, final step in the path. "*" means all. """ self._properties["nonResourceURLs"] = value @property def verbs(self) -> typing.List[str]: """ Verb is a list of kubernetes non-resource API verbs, like: get, post, put, delete, patch, head, options. "*" means all. """ return typing.cast( typing.List[str], self._properties.get("verbs"), ) @verbs.setter def verbs(self, value: typing.List[str]): """ Verb is a list of kubernetes non-resource API verbs, like: get, post, put, delete, patch, head, options. "*" means all. """ self._properties["verbs"] = value def __enter__(self) -> "NonResourceRule": return self def __exit__(self, exc_type, exc_val, exc_tb): return False class ResourceAttributes(_kuber_definitions.Definition): """ ResourceAttributes includes the authorization attributes available for resource requests to the Authorizer interface """ def __init__( self, group: str = None, name: str = None, namespace: str = None, resource: str = None, subresource: str = None, verb: str = None, version: str = None, ): """Create ResourceAttributes instance.""" super(ResourceAttributes, self).__init__( api_version="authorization/v1", kind="ResourceAttributes" ) self._properties = { "group": group if group is not None else "", "name": name if name is not None else "", "namespace": namespace if namespace is not None else "", "resource": resource if resource is not None else "", "subresource": subresource if subresource is not None else "", "verb": verb if verb is not None else "", "version": version if version is not None else "", } self._types = { "group": (str, None), "name": (str, None), "namespace": (str, None), "resource": (str, None), "subresource": (str, None), "verb": (str, None), "version": (str, None), } @property def group(self) -> str: """ Group is the API Group of the Resource. "*" means all. """ return typing.cast( str, self._properties.get("group"), ) @group.setter def group(self, value: str): """ Group is the API Group of the Resource. "*" means all. """ self._properties["group"] = value @property def name(self) -> str: """ Name is the name of the resource being requested for a "get" or deleted for a "delete". "" (empty) means all. """ return typing.cast( str, self._properties.get("name"), ) @name.setter def name(self, value: str): """ Name is the name of the resource being requested for a "get" or deleted for a "delete". "" (empty) means all. """ self._properties["name"] = value @property def namespace(self) -> str: """ Namespace is the namespace of the action being requested. Currently, there is no distinction between no namespace and all namespaces "" (empty) is defaulted for LocalSubjectAccessReviews "" (empty) is empty for cluster- scoped resources "" (empty) means "all" for namespace scoped resources from a SubjectAccessReview or SelfSubjectAccessReview """ return typing.cast( str, self._properties.get("namespace"), ) @namespace.setter def namespace(self, value: str): """ Namespace is the namespace of the action being requested. Currently, there is no distinction between no namespace and all namespaces "" (empty) is defaulted for LocalSubjectAccessReviews "" (empty) is empty for cluster- scoped resources "" (empty) means "all" for namespace scoped resources from a SubjectAccessReview or SelfSubjectAccessReview """ self._properties["namespace"] = value @property def resource(self) -> str: """ Resource is one of the existing resource types. "*" means all. """ return typing.cast( str, self._properties.get("resource"), ) @resource.setter def resource(self, value: str): """ Resource is one of the existing resource types. "*" means all. """ self._properties["resource"] = value @property def subresource(self) -> str: """ Subresource is one of the existing resource types. "" means none. """ return typing.cast( str, self._properties.get("subresource"), ) @subresource.setter def subresource(self, value: str): """ Subresource is one of the existing resource types. "" means none. """ self._properties["subresource"] = value @property def verb(self) -> str: """ Verb is a kubernetes resource API verb, like: get, list, watch, create, update, delete, proxy. "*" means all. """ return typing.cast( str, self._properties.get("verb"), ) @verb.setter def verb(self, value: str): """ Verb is a kubernetes resource API verb, like: get, list, watch, create, update, delete, proxy. "*" means all. """ self._properties["verb"] = value @property def version(self) -> str: """ Version is the API Version of the Resource. "*" means all. """ return typing.cast( str, self._properties.get("version"), ) @version.setter def version(self, value: str): """ Version is the API Version of the Resource. "*" means all. """ self._properties["version"] = value def __enter__(self) -> "ResourceAttributes": return self def __exit__(self, exc_type, exc_val, exc_tb): return False class ResourceRule(_kuber_definitions.Definition): """ ResourceRule is the list of actions the subject is allowed to perform on resources. The list ordering isn't significant, may contain duplicates, and possibly be incomplete. """ def __init__( self, api_groups: typing.List[str] = None, resource_names: typing.List[str] = None, resources: typing.List[str] = None, verbs: typing.List[str] = None, ): """Create ResourceRule instance.""" super(ResourceRule, self).__init__( api_version="authorization/v1", kind="ResourceRule" ) self._properties = { "apiGroups": api_groups if api_groups is not None else [], "resourceNames": resource_names if resource_names is not None else [], "resources": resources if resources is not None else [], "verbs": verbs if verbs is not None else [], } self._types = { "apiGroups": (list, str), "resourceNames": (list, str), "resources": (list, str), "verbs": (list, str), } @property def api_groups(self) -> typing.List[str]: """ APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of the enumerated resources in any API group will be allowed. "*" means all. """ return typing.cast( typing.List[str], self._properties.get("apiGroups"), ) @api_groups.setter def api_groups(self, value: typing.List[str]): """ APIGroups is the name of the APIGroup that contains the resources. If multiple API groups are specified, any action requested against one of the enumerated resources in any API group will be allowed. "*" means all. """ self._properties["apiGroups"] = value @property def resource_names(self) -> typing.List[str]: """ ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. "*" means all. """ return typing.cast( typing.List[str], self._properties.get("resourceNames"), ) @resource_names.setter def resource_names(self, value: typing.List[str]): """ ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. "*" means all. """ self._properties["resourceNames"] = value @property def resources(self) -> typing.List[str]: """ Resources is a list of resources this rule applies to. "*" means all in the specified apiGroups. "*/foo" represents the subresource 'foo' for all resources in the specified apiGroups. """ return typing.cast( typing.List[str], self._properties.get("resources"), ) @resources.setter def resources(self, value: typing.List[str]): """ Resources is a list of resources this rule applies to. "*" means all in the specified apiGroups. "*/foo" represents the subresource 'foo' for all resources in the specified apiGroups. """ self._properties["resources"] = value @property def verbs(self) -> typing.List[str]: """ Verb is a list of kubernetes resource API verbs, like: get, list, watch, create, update, delete, proxy. "*" means all. """ return typing.cast( typing.List[str], self._properties.get("verbs"), ) @verbs.setter def verbs(self, value: typing.List[str]): """ Verb is a list of kubernetes resource API verbs, like: get, list, watch, create, update, delete, proxy. "*" means all. """ self._properties["verbs"] = value def __enter__(self) -> "ResourceRule": return self def __exit__(self, exc_type, exc_val, exc_tb): return False class SelfSubjectAccessReview(_kuber_definitions.Resource): """ SelfSubjectAccessReview checks whether or the current user can perform an action. Not filling in a spec.namespace means "in all namespaces". Self is a special case, because users should always be able to check whether they can perform an action """ def __init__( self, metadata: "ObjectMeta" = None, spec: "SelfSubjectAccessReviewSpec" = None, status: "SubjectAccessReviewStatus" = None, ): """Create SelfSubjectAccessReview instance.""" super(SelfSubjectAccessReview, self).__init__( api_version="authorization/v1", kind="SelfSubjectAccessReview" ) self._properties = { "metadata": metadata if metadata is not None else ObjectMeta(), "spec": spec if spec is not None else SelfSubjectAccessReviewSpec(), "status": status if status is not None else SubjectAccessReviewStatus(), } self._types = { "apiVersion": (str, None), "kind": (str, None), "metadata": (ObjectMeta, None), "spec": (SelfSubjectAccessReviewSpec, None), "status": (SubjectAccessReviewStatus, None), } @property def metadata(self) -> "ObjectMeta": """ Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig- architecture/api-conventions.md#metadata """ return typing.cast( "ObjectMeta", self._properties.get("metadata"), ) @metadata.setter def metadata(self, value: typing.Union["ObjectMeta", dict]): """ Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig- architecture/api-conventions.md#metadata """ if isinstance(value, dict): value = typing.cast( ObjectMeta, ObjectMeta().from_dict(value), ) self._properties["metadata"] = value @property def spec(self) -> "SelfSubjectAccessReviewSpec": """ Spec holds information about the request being evaluated. user and groups must be empty """ return typing.cast( "SelfSubjectAccessReviewSpec", self._properties.get("spec"), ) @spec.setter def spec(self, value: typing.Union["SelfSubjectAccessReviewSpec", dict]): """ Spec holds information about the request being evaluated. user and groups must be empty """ if isinstance(value, dict): value = typing.cast( SelfSubjectAccessReviewSpec, SelfSubjectAccessReviewSpec().from_dict(value), ) self._properties["spec"] = value @property def status(self) -> "SubjectAccessReviewStatus": """ Status is filled in by the server and indicates whether the request is allowed or not """ return typing.cast( "SubjectAccessReviewStatus", self._properties.get("status"), ) @status.setter def status(self, value: typing.Union["SubjectAccessReviewStatus", dict]): """ Status is filled in by the server and indicates whether the request is allowed or not """ if isinstance(value, dict): value = typing.cast( SubjectAccessReviewStatus, SubjectAccessReviewStatus().from_dict(value), ) self._properties["status"] = value def create_resource(self, namespace: "str" = None) -> "SubjectAccessReviewStatus": """ Creates the SelfSubjectAccessReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the create is complete. """ names = [ "create_namespaced_self_subject_access_review", "create_self_subject_access_review", ] response = _kube_api.execute( action="create", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict()}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def replace_resource(self, namespace: "str" = None) -> "SubjectAccessReviewStatus": """ Replaces the SelfSubjectAccessReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the replace is complete. """ names = [ "replace_namespaced_self_subject_access_review", "replace_self_subject_access_review", ] response = _kube_api.execute( action="replace", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict(), "name": self.metadata.name}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def patch_resource(self, namespace: "str" = None) -> "SubjectAccessReviewStatus": """ Patches the SelfSubjectAccessReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the replace is complete. """ names = [ "patch_namespaced_self_subject_access_review", "patch_self_subject_access_review", ] response = _kube_api.execute( action="patch", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict(), "name": self.metadata.name}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def get_resource_status( self, namespace: "str" = None ) -> "SubjectAccessReviewStatus": """ Returns status information about the given resource within the cluster. """ names = [ "read_namespaced_self_subject_access_review", "read_self_subject_access_review", ] response = _kube_api.execute( action="read", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def read_resource(self, namespace: str = None): """ Reads the SelfSubjectAccessReview from the currently configured Kubernetes cluster and returns the low-level definition object. """ names = [ "read_namespaced_self_subject_access_review", "read_self_subject_access_review", ] return _kube_api.execute( action="read", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name}, ) def delete_resource( self, namespace: str = None, propagation_policy: str = "Foreground", grace_period_seconds: int = 10, ): """ Deletes the SelfSubjectAccessReview from the currently configured Kubernetes cluster. """ names = [ "delete_namespaced_self_subject_access_review", "delete_self_subject_access_review", ] body = client.V1DeleteOptions( propagation_policy=propagation_policy, grace_period_seconds=grace_period_seconds, ) _kube_api.execute( action="delete", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name, "body": body}, ) @staticmethod def get_resource_api( api_client: client.ApiClient = None, **kwargs ) -> "client.AuthorizationV1Api": """ Returns an instance of the kubernetes API client associated with this object. """ if api_client: kwargs["apl_client"] = api_client return client.AuthorizationV1Api(**kwargs) def __enter__(self) -> "SelfSubjectAccessReview": return self def __exit__(self, exc_type, exc_val, exc_tb): return False class SelfSubjectAccessReviewSpec(_kuber_definitions.Definition): """ SelfSubjectAccessReviewSpec is a description of the access request. Exactly one of ResourceAuthorizationAttributes and NonResourceAuthorizationAttributes must be set """ def __init__( self, non_resource_attributes: "NonResourceAttributes" = None, resource_attributes: "ResourceAttributes" = None, ): """Create SelfSubjectAccessReviewSpec instance.""" super(SelfSubjectAccessReviewSpec, self).__init__( api_version="authorization/v1", kind="SelfSubjectAccessReviewSpec" ) self._properties = { "nonResourceAttributes": non_resource_attributes if non_resource_attributes is not None else NonResourceAttributes(), "resourceAttributes": resource_attributes if resource_attributes is not None else ResourceAttributes(), } self._types = { "nonResourceAttributes": (NonResourceAttributes, None), "resourceAttributes": (ResourceAttributes, None), } @property def non_resource_attributes(self) -> "NonResourceAttributes": """ NonResourceAttributes describes information for a non- resource access request """ return typing.cast( "NonResourceAttributes", self._properties.get("nonResourceAttributes"), ) @non_resource_attributes.setter def non_resource_attributes( self, value: typing.Union["NonResourceAttributes", dict] ): """ NonResourceAttributes describes information for a non- resource access request """ if isinstance(value, dict): value = typing.cast( NonResourceAttributes, NonResourceAttributes().from_dict(value), ) self._properties["nonResourceAttributes"] = value @property def resource_attributes(self) -> "ResourceAttributes": """ ResourceAuthorizationAttributes describes information for a resource access request """ return typing.cast( "ResourceAttributes", self._properties.get("resourceAttributes"), ) @resource_attributes.setter def resource_attributes(self, value: typing.Union["ResourceAttributes", dict]): """ ResourceAuthorizationAttributes describes information for a resource access request """ if isinstance(value, dict): value = typing.cast( ResourceAttributes, ResourceAttributes().from_dict(value), ) self._properties["resourceAttributes"] = value def __enter__(self) -> "SelfSubjectAccessReviewSpec": return self def __exit__(self, exc_type, exc_val, exc_tb): return False class SelfSubjectRulesReview(_kuber_definitions.Resource): """ SelfSubjectRulesReview enumerates the set of actions the current user can perform within a namespace. The returned list of actions may be incomplete depending on the server's authorization mode, and any errors experienced during the evaluation. SelfSubjectRulesReview should be used by UIs to show/hide actions, or to quickly let an end user reason about their permissions. It should NOT Be used by external systems to drive authorization decisions as this raises confused deputy, cache lifetime/revocation, and correctness concerns. SubjectAccessReview, and LocalAccessReview are the correct way to defer authorization decisions to the API server. """ def __init__( self, metadata: "ObjectMeta" = None, spec: "SelfSubjectRulesReviewSpec" = None, status: "SubjectRulesReviewStatus" = None, ): """Create SelfSubjectRulesReview instance.""" super(SelfSubjectRulesReview, self).__init__( api_version="authorization/v1", kind="SelfSubjectRulesReview" ) self._properties = { "metadata": metadata if metadata is not None else ObjectMeta(), "spec": spec if spec is not None else SelfSubjectRulesReviewSpec(), "status": status if status is not None else SubjectRulesReviewStatus(), } self._types = { "apiVersion": (str, None), "kind": (str, None), "metadata": (ObjectMeta, None), "spec": (SelfSubjectRulesReviewSpec, None), "status": (SubjectRulesReviewStatus, None), } @property def metadata(self) -> "ObjectMeta": """ Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig- architecture/api-conventions.md#metadata """ return typing.cast( "ObjectMeta", self._properties.get("metadata"), ) @metadata.setter def metadata(self, value: typing.Union["ObjectMeta", dict]): """ Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig- architecture/api-conventions.md#metadata """ if isinstance(value, dict): value = typing.cast( ObjectMeta, ObjectMeta().from_dict(value), ) self._properties["metadata"] = value @property def spec(self) -> "SelfSubjectRulesReviewSpec": """ Spec holds information about the request being evaluated. """ return typing.cast( "SelfSubjectRulesReviewSpec", self._properties.get("spec"), ) @spec.setter def spec(self, value: typing.Union["SelfSubjectRulesReviewSpec", dict]): """ Spec holds information about the request being evaluated. """ if isinstance(value, dict): value = typing.cast( SelfSubjectRulesReviewSpec, SelfSubjectRulesReviewSpec().from_dict(value), ) self._properties["spec"] = value @property def status(self) -> "SubjectRulesReviewStatus": """ Status is filled in by the server and indicates the set of actions a user can perform. """ return typing.cast( "SubjectRulesReviewStatus", self._properties.get("status"), ) @status.setter def status(self, value: typing.Union["SubjectRulesReviewStatus", dict]): """ Status is filled in by the server and indicates the set of actions a user can perform. """ if isinstance(value, dict): value = typing.cast( SubjectRulesReviewStatus, SubjectRulesReviewStatus().from_dict(value), ) self._properties["status"] = value def create_resource(self, namespace: "str" = None) -> "SubjectRulesReviewStatus": """ Creates the SelfSubjectRulesReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the create is complete. """ names = [ "create_namespaced_self_subject_rules_review", "create_self_subject_rules_review", ] response = _kube_api.execute( action="create", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict()}, ) output = SubjectRulesReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def replace_resource(self, namespace: "str" = None) -> "SubjectRulesReviewStatus": """ Replaces the SelfSubjectRulesReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the replace is complete. """ names = [ "replace_namespaced_self_subject_rules_review", "replace_self_subject_rules_review", ] response = _kube_api.execute( action="replace", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict(), "name": self.metadata.name}, ) output = SubjectRulesReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def patch_resource(self, namespace: "str" = None) -> "SubjectRulesReviewStatus": """ Patches the SelfSubjectRulesReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the replace is complete. """ names = [ "patch_namespaced_self_subject_rules_review", "patch_self_subject_rules_review", ] response = _kube_api.execute( action="patch", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict(), "name": self.metadata.name}, ) output = SubjectRulesReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def get_resource_status( self, namespace: "str" = None ) -> "SubjectRulesReviewStatus": """ Returns status information about the given resource within the cluster. """ names = [ "read_namespaced_self_subject_rules_review", "read_self_subject_rules_review", ] response = _kube_api.execute( action="read", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name}, ) output = SubjectRulesReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def read_resource(self, namespace: str = None): """ Reads the SelfSubjectRulesReview from the currently configured Kubernetes cluster and returns the low-level definition object. """ names = [ "read_namespaced_self_subject_rules_review", "read_self_subject_rules_review", ] return _kube_api.execute( action="read", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name}, ) def delete_resource( self, namespace: str = None, propagation_policy: str = "Foreground", grace_period_seconds: int = 10, ): """ Deletes the SelfSubjectRulesReview from the currently configured Kubernetes cluster. """ names = [ "delete_namespaced_self_subject_rules_review", "delete_self_subject_rules_review", ] body = client.V1DeleteOptions( propagation_policy=propagation_policy, grace_period_seconds=grace_period_seconds, ) _kube_api.execute( action="delete", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name, "body": body}, ) @staticmethod def get_resource_api( api_client: client.ApiClient = None, **kwargs ) -> "client.AuthorizationV1Api": """ Returns an instance of the kubernetes API client associated with this object. """ if api_client: kwargs["apl_client"] = api_client return client.AuthorizationV1Api(**kwargs) def __enter__(self) -> "SelfSubjectRulesReview": return self def __exit__(self, exc_type, exc_val, exc_tb): return False class SelfSubjectRulesReviewSpec(_kuber_definitions.Definition): """ SelfSubjectRulesReviewSpec defines the specification for SelfSubjectRulesReview. """ def __init__( self, namespace: str = None, ): """Create SelfSubjectRulesReviewSpec instance.""" super(SelfSubjectRulesReviewSpec, self).__init__( api_version="authorization/v1", kind="SelfSubjectRulesReviewSpec" ) self._properties = { "namespace": namespace if namespace is not None else "", } self._types = { "namespace": (str, None), } @property def namespace(self) -> str: """ Namespace to evaluate rules for. Required. """ return typing.cast( str, self._properties.get("namespace"), ) @namespace.setter def namespace(self, value: str): """ Namespace to evaluate rules for. Required. """ self._properties["namespace"] = value def __enter__(self) -> "SelfSubjectRulesReviewSpec": return self def __exit__(self, exc_type, exc_val, exc_tb): return False class SubjectAccessReview(_kuber_definitions.Resource): """ SubjectAccessReview checks whether or not a user or group can perform an action. """ def __init__( self, metadata: "ObjectMeta" = None, spec: "SubjectAccessReviewSpec" = None, status: "SubjectAccessReviewStatus" = None, ): """Create SubjectAccessReview instance.""" super(SubjectAccessReview, self).__init__( api_version="authorization/v1", kind="SubjectAccessReview" ) self._properties = { "metadata": metadata if metadata is not None else ObjectMeta(), "spec": spec if spec is not None else SubjectAccessReviewSpec(), "status": status if status is not None else SubjectAccessReviewStatus(), } self._types = { "apiVersion": (str, None), "kind": (str, None), "metadata": (ObjectMeta, None), "spec": (SubjectAccessReviewSpec, None), "status": (SubjectAccessReviewStatus, None), } @property def metadata(self) -> "ObjectMeta": """ Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig- architecture/api-conventions.md#metadata """ return typing.cast( "ObjectMeta", self._properties.get("metadata"), ) @metadata.setter def metadata(self, value: typing.Union["ObjectMeta", dict]): """ Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig- architecture/api-conventions.md#metadata """ if isinstance(value, dict): value = typing.cast( ObjectMeta, ObjectMeta().from_dict(value), ) self._properties["metadata"] = value @property def spec(self) -> "SubjectAccessReviewSpec": """ Spec holds information about the request being evaluated """ return typing.cast( "SubjectAccessReviewSpec", self._properties.get("spec"), ) @spec.setter def spec(self, value: typing.Union["SubjectAccessReviewSpec", dict]): """ Spec holds information about the request being evaluated """ if isinstance(value, dict): value = typing.cast( SubjectAccessReviewSpec, SubjectAccessReviewSpec().from_dict(value), ) self._properties["spec"] = value @property def status(self) -> "SubjectAccessReviewStatus": """ Status is filled in by the server and indicates whether the request is allowed or not """ return typing.cast( "SubjectAccessReviewStatus", self._properties.get("status"), ) @status.setter def status(self, value: typing.Union["SubjectAccessReviewStatus", dict]): """ Status is filled in by the server and indicates whether the request is allowed or not """ if isinstance(value, dict): value = typing.cast( SubjectAccessReviewStatus, SubjectAccessReviewStatus().from_dict(value), ) self._properties["status"] = value def create_resource(self, namespace: "str" = None) -> "SubjectAccessReviewStatus": """ Creates the SubjectAccessReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the create is complete. """ names = [ "create_namespaced_subject_access_review", "create_subject_access_review", ] response = _kube_api.execute( action="create", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict()}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def replace_resource(self, namespace: "str" = None) -> "SubjectAccessReviewStatus": """ Replaces the SubjectAccessReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the replace is complete. """ names = [ "replace_namespaced_subject_access_review", "replace_subject_access_review", ] response = _kube_api.execute( action="replace", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict(), "name": self.metadata.name}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def patch_resource(self, namespace: "str" = None) -> "SubjectAccessReviewStatus": """ Patches the SubjectAccessReview in the currently configured Kubernetes cluster and returns the status information returned by the Kubernetes API after the replace is complete. """ names = [ "patch_namespaced_subject_access_review", "patch_subject_access_review", ] response = _kube_api.execute( action="patch", resource=self, names=names, namespace=namespace, api_client=None, api_args={"body": self.to_dict(), "name": self.metadata.name}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def get_resource_status( self, namespace: "str" = None ) -> "SubjectAccessReviewStatus": """ Returns status information about the given resource within the cluster. """ names = [ "read_namespaced_subject_access_review", "read_subject_access_review", ] response = _kube_api.execute( action="read", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name}, ) output = SubjectAccessReviewStatus() if response is not None: output.from_dict(_kube_api.to_kuber_dict(response.status)) return output def read_resource(self, namespace: str = None): """ Reads the SubjectAccessReview from the currently configured Kubernetes cluster and returns the low-level definition object. """ names = [ "read_namespaced_subject_access_review", "read_subject_access_review", ] return _kube_api.execute( action="read", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name}, ) def delete_resource( self, namespace: str = None, propagation_policy: str = "Foreground", grace_period_seconds: int = 10, ): """ Deletes the SubjectAccessReview from the currently configured Kubernetes cluster. """ names = [ "delete_namespaced_subject_access_review", "delete_subject_access_review", ] body = client.V1DeleteOptions( propagation_policy=propagation_policy, grace_period_seconds=grace_period_seconds, ) _kube_api.execute( action="delete", resource=self, names=names, namespace=namespace, api_client=None, api_args={"name": self.metadata.name, "body": body}, ) @staticmethod def get_resource_api( api_client: client.ApiClient = None, **kwargs ) -> "client.AuthorizationV1Api": """ Returns an instance of the kubernetes API client associated with this object. """ if api_client: kwargs["apl_client"] = api_client return client.AuthorizationV1Api(**kwargs) def __enter__(self) -> "SubjectAccessReview": return self def __exit__(self, exc_type, exc_val, exc_tb): return False class SubjectAccessReviewSpec(_kuber_definitions.Definition): """ SubjectAccessReviewSpec is a description of the access request. Exactly one of ResourceAuthorizationAttributes and NonResourceAuthorizationAttributes must be set """ def __init__( self, extra: dict = None, groups: typing.List[str] = None, non_resource_attributes: "NonResourceAttributes" = None, resource_attributes: "ResourceAttributes" = None, uid: str = None, user: str = None, ): """Create SubjectAccessReviewSpec instance.""" super(SubjectAccessReviewSpec, self).__init__( api_version="authorization/v1", kind="SubjectAccessReviewSpec" ) self._properties = { "extra": extra if extra is not None else {}, "groups": groups if groups is not None else [], "nonResourceAttributes": non_resource_attributes if non_resource_attributes is not None else NonResourceAttributes(), "resourceAttributes": resource_attributes if resource_attributes is not None else ResourceAttributes(), "uid": uid if uid is not None else "", "user": user if user is not None else "", } self._types = { "extra": (dict, None), "groups": (list, str), "nonResourceAttributes": (NonResourceAttributes, None), "resourceAttributes": (ResourceAttributes, None), "uid": (str, None), "user": (str, None), } @property def extra(self) -> dict: """ Extra corresponds to the user.Info.GetExtra() method from the authenticator. Since that is input to the authorizer it needs a reflection here. """ return typing.cast( dict, self._properties.get("extra"), ) @extra.setter def extra(self, value: dict): """ Extra corresponds to the user.Info.GetExtra() method from the authenticator. Since that is input to the authorizer it needs a reflection here. """ self._properties["extra"] = value @property def groups(self) -> typing.List[str]: """ Groups is the groups you're testing for. """ return typing.cast( typing.List[str], self._properties.get("groups"), ) @groups.setter def groups(self, value: typing.List[str]): """ Groups is the groups you're testing for. """ self._properties["groups"] = value @property def non_resource_attributes(self) -> "NonResourceAttributes": """ NonResourceAttributes describes information for a non- resource access request """ return typing.cast( "NonResourceAttributes", self._properties.get("nonResourceAttributes"), ) @non_resource_attributes.setter def non_resource_attributes( self, value: typing.Union["NonResourceAttributes", dict] ): """ NonResourceAttributes describes information for a non- resource access request """ if isinstance(value, dict): value = typing.cast( NonResourceAttributes, NonResourceAttributes().from_dict(value), ) self._properties["nonResourceAttributes"] = value @property def resource_attributes(self) -> "ResourceAttributes": """ ResourceAuthorizationAttributes describes information for a resource access request """ return typing.cast( "ResourceAttributes", self._properties.get("resourceAttributes"), ) @resource_attributes.setter def resource_attributes(self, value: typing.Union["ResourceAttributes", dict]): """ ResourceAuthorizationAttributes describes information for a resource access request """ if isinstance(value, dict): value = typing.cast( ResourceAttributes, ResourceAttributes().from_dict(value), ) self._properties["resourceAttributes"] = value @property def uid(self) -> str: """ UID information about the requesting user. """ return typing.cast( str, self._properties.get("uid"), ) @uid.setter def uid(self, value: str): """ UID information about the requesting user. """ self._properties["uid"] = value @property def user(self) -> str: """ User is the user you're testing for. If you specify "User" but not "Groups", then is it interpreted as "What if User were not a member of any groups """ return typing.cast( str, self._properties.get("user"), ) @user.setter def user(self, value: str): """ User is the user you're testing for. If you specify "User" but not "Groups", then is it interpreted as "What if User were not a member of any groups """ self._properties["user"] = value def __enter__(self) -> "SubjectAccessReviewSpec": return self def __exit__(self, exc_type, exc_val, exc_tb): return False class SubjectAccessReviewStatus(_kuber_definitions.Definition): """ SubjectAccessReviewStatus """ def __init__( self, allowed: bool = None, denied: bool = None, evaluation_error: str = None, reason: str = None, ): """Create SubjectAccessReviewStatus instance.""" super(SubjectAccessReviewStatus, self).__init__( api_version="authorization/v1", kind="SubjectAccessReviewStatus" ) self._properties = { "allowed": allowed if allowed is not None else None, "denied": denied if denied is not None else None, "evaluationError": evaluation_error if evaluation_error is not None else "", "reason": reason if reason is not None else "", } self._types = { "allowed": (bool, None), "denied": (bool, None), "evaluationError": (str, None), "reason": (str, None), } @property def allowed(self) -> bool: """ Allowed is required. True if the action would be allowed, false otherwise. """ return typing.cast( bool, self._properties.get("allowed"), ) @allowed.setter def allowed(self, value: bool): """ Allowed is required. True if the action would be allowed, false otherwise. """ self._properties["allowed"] = value @property def denied(self) -> bool: """ Denied is optional. True if the action would be denied, otherwise false. If both allowed is false and denied is false, then the authorizer has no opinion on whether to authorize the action. Denied may not be true if Allowed is true. """ return typing.cast( bool, self._properties.get("denied"), ) @denied.setter def denied(self, value: bool): """ Denied is optional. True if the action would be denied, otherwise false. If both allowed is false and denied is false, then the authorizer has no opinion on whether to authorize the action. Denied may not be true if Allowed is true. """ self._properties["denied"] = value @property def evaluation_error(self) -> str: """ EvaluationError is an indication that some error occurred during the authorization check. It is entirely possible to get an error and be able to continue determine authorization status in spite of it. For instance, RBAC can be missing a role, but enough roles are still present and bound to reason about the request. """ return typing.cast( str, self._properties.get("evaluationError"), ) @evaluation_error.setter def evaluation_error(self, value: str): """ EvaluationError is an indication that some error occurred during the authorization check. It is entirely possible to get an error and be able to continue determine authorization status in spite of it. For instance, RBAC can be missing a role, but enough roles are still present and bound to reason about the request. """ self._properties["evaluationError"] = value @property def reason(self) -> str: """ Reason is optional. It indicates why a request was allowed or denied. """ return typing.cast( str, self._properties.get("reason"), ) @reason.setter def reason(self, value: str): """ Reason is optional. It indicates why a request was allowed or denied. """ self._properties["reason"] = value def __enter__(self) -> "SubjectAccessReviewStatus": return self def __exit__(self, exc_type, exc_val, exc_tb): return False class SubjectRulesReviewStatus(_kuber_definitions.Definition): """ SubjectRulesReviewStatus contains the result of a rules check. This check can be incomplete depending on the set of authorizers the server is configured with and any errors experienced during evaluation. Because authorization rules are additive, if a rule appears in a list it's safe to assume the subject has that permission, even if that list is incomplete. """ def __init__( self, evaluation_error: str = None, incomplete: bool = None, non_resource_rules: typing.List["NonResourceRule"] = None, resource_rules: typing.List["ResourceRule"] = None, ): """Create SubjectRulesReviewStatus instance.""" super(SubjectRulesReviewStatus, self).__init__( api_version="authorization/v1", kind="SubjectRulesReviewStatus" ) self._properties = { "evaluationError": evaluation_error if evaluation_error is not None else "", "incomplete": incomplete if incomplete is not None else None, "nonResourceRules": non_resource_rules if non_resource_rules is not None else [], "resourceRules": resource_rules if resource_rules is not None else [], } self._types = { "evaluationError": (str, None), "incomplete": (bool, None), "nonResourceRules": (list, NonResourceRule), "resourceRules": (list, ResourceRule), } @property def evaluation_error(self) -> str: """ EvaluationError can appear in combination with Rules. It indicates an error occurred during rule evaluation, such as an authorizer that doesn't support rule evaluation, and that ResourceRules and/or NonResourceRules may be incomplete. """ return typing.cast( str, self._properties.get("evaluationError"), ) @evaluation_error.setter def evaluation_error(self, value: str): """ EvaluationError can appear in combination with Rules. It indicates an error occurred during rule evaluation, such as an authorizer that doesn't support rule evaluation, and that ResourceRules and/or NonResourceRules may be incomplete. """ self._properties["evaluationError"] = value @property def incomplete(self) -> bool: """ Incomplete is true when the rules returned by this call are incomplete. This is most commonly encountered when an authorizer, such as an external authorizer, doesn't support rules evaluation. """ return typing.cast( bool, self._properties.get("incomplete"), ) @incomplete.setter def incomplete(self, value: bool): """ Incomplete is true when the rules returned by this call are incomplete. This is most commonly encountered when an authorizer, such as an external authorizer, doesn't support rules evaluation. """ self._properties["incomplete"] = value @property def non_resource_rules(self) -> typing.List["NonResourceRule"]: """ NonResourceRules is the list of actions the subject is allowed to perform on non-resources. The list ordering isn't significant, may contain duplicates, and possibly be incomplete. """ return typing.cast( typing.List["NonResourceRule"], self._properties.get("nonResourceRules"), ) @non_resource_rules.setter def non_resource_rules( self, value: typing.Union[typing.List["NonResourceRule"], typing.List[dict]] ): """ NonResourceRules is the list of actions the subject is allowed to perform on non-resources. The list ordering isn't significant, may contain duplicates, and possibly be incomplete. """ cleaned: typing.List[NonResourceRule] = [] for item in value: if isinstance(item, dict): item = typing.cast( NonResourceRule, NonResourceRule().from_dict(item), ) cleaned.append(typing.cast(NonResourceRule, item)) self._properties["nonResourceRules"] = cleaned @property def resource_rules(self) -> typing.List["ResourceRule"]: """ ResourceRules is the list of actions the subject is allowed to perform on resources. The list ordering isn't significant, may contain duplicates, and possibly be incomplete. """ return typing.cast( typing.List["ResourceRule"], self._properties.get("resourceRules"), ) @resource_rules.setter def resource_rules( self, value: typing.Union[typing.List["ResourceRule"], typing.List[dict]] ): """ ResourceRules is the list of actions the subject is allowed to perform on resources. The list ordering isn't significant, may contain duplicates, and possibly be incomplete. """ cleaned: typing.List[ResourceRule] = [] for item in value: if isinstance(item, dict): item = typing.cast( ResourceRule, ResourceRule().from_dict(item), ) cleaned.append(typing.cast(ResourceRule, item)) self._properties["resourceRules"] = cleaned def __enter__(self) -> "SubjectRulesReviewStatus": return self def __exit__(self, exc_type, exc_val, exc_tb): return False
1,202
0
702
8ad10cf34c4403953a74288a3efa2108f1669f41
4,360
py
Python
safe_transaction_service/history/tests/test_index_service.py
becoswap-dev/safe-transaction-service
bf2d3060874ee6f4d7883f15780cfa6456d9d9cf
[ "MIT" ]
67
2019-08-16T16:26:42.000Z
2022-03-21T20:32:43.000Z
safe_transaction_service/history/tests/test_index_service.py
becoswap-dev/safe-transaction-service
bf2d3060874ee6f4d7883f15780cfa6456d9d9cf
[ "MIT" ]
550
2019-07-11T12:09:06.000Z
2022-03-31T16:32:00.000Z
safe_transaction_service/history/tests/test_index_service.py
becoswap-dev/safe-transaction-service
bf2d3060874ee6f4d7883f15780cfa6456d9d9cf
[ "MIT" ]
83
2019-12-06T11:22:32.000Z
2022-03-30T10:09:22.000Z
from django.test import TestCase from eth_account import Account from web3 import Web3 from gnosis.eth.tests.ethereum_test_case import EthereumTestCaseMixin from ..models import EthereumTx, MultisigTransaction, SafeStatus from ..services.index_service import ( EthereumBlockHashMismatch, IndexService, IndexServiceProvider, TransactionNotFoundException, ) from .factories import EthereumTxFactory, MultisigTransactionFactory, SafeStatusFactory
42.745098
110
0.718119
from django.test import TestCase from eth_account import Account from web3 import Web3 from gnosis.eth.tests.ethereum_test_case import EthereumTestCaseMixin from ..models import EthereumTx, MultisigTransaction, SafeStatus from ..services.index_service import ( EthereumBlockHashMismatch, IndexService, IndexServiceProvider, TransactionNotFoundException, ) from .factories import EthereumTxFactory, MultisigTransactionFactory, SafeStatusFactory class TestIndexService(EthereumTestCaseMixin, TestCase): def test_create_or_update_from_tx_hashes_existing(self): index_service: IndexService = IndexServiceProvider() self.assertListEqual(index_service.txs_create_or_update_from_tx_hashes([]), []) tx_hashes = [ "0x52fcb05f2ad209d53d84b0a9a7ce6474ab415db88bc364c088758d70c8b5b0ef" ] with self.assertRaisesMessage(TransactionNotFoundException, tx_hashes[0]): index_service.txs_create_or_update_from_tx_hashes(tx_hashes) # Test with database txs. Use block_number > current_block_number to prevent storing blocks with wrong # hashes that will be indexed by next tests current_block_number = self.ethereum_client.current_block_number ethereum_txs = [ EthereumTxFactory(block__number=current_block_number + 100 + i) for i in range(4) ] tx_hashes = [ethereum_tx.tx_hash for ethereum_tx in ethereum_txs] db_txs = index_service.txs_create_or_update_from_tx_hashes(tx_hashes) self.assertEqual(len(db_txs), len(tx_hashes)) for db_tx in db_txs: self.assertIsNotNone(db_tx) # Test with real txs value = 6 real_tx_hashes = [ self.send_ether(Account.create().address, value) for _ in range(2) ] ethereum_txs = index_service.txs_create_or_update_from_tx_hashes(real_tx_hashes) self.assertEqual(len(ethereum_txs), len(ethereum_txs)) for ethereum_tx in ethereum_txs: self.assertEqual(ethereum_tx.value, value) # Remove blocks and try again EthereumTx.objects.filter(tx_hash__in=real_tx_hashes).update(block=None) ethereum_txs = index_service.txs_create_or_update_from_tx_hashes(real_tx_hashes) for ethereum_tx in ethereum_txs: self.assertIsNotNone(ethereum_tx.block) # Test mixed tx_hashes = tx_hashes + real_tx_hashes mixed_txs = index_service.txs_create_or_update_from_tx_hashes(tx_hashes) self.assertEqual(len(mixed_txs), len(tx_hashes)) for mixed_tx in mixed_txs: self.assertIsNotNone(mixed_tx) # Test block hash changes ethereum_tx = ethereum_txs[0] ethereum_tx.block.block_hash = Web3.keccak(text="aloha") ethereum_tx.block.save(update_fields=["block_hash"]) tx_hash = ethereum_tx.tx_hash # Uses database index_service.txs_create_or_update_from_tx_hashes([tx_hash]) ethereum_tx.delete() # Try to fetch again with self.assertRaises(EthereumBlockHashMismatch): index_service.txs_create_or_update_from_tx_hashes([tx_hash]) def test_reprocess_addresses(self): index_service: IndexService = IndexServiceProvider() self.assertIsNone(index_service.reprocess_addresses([])) safe_status = SafeStatusFactory() MultisigTransactionFactory() # It shouldn't be deleted MultisigTransactionFactory(safe=safe_status.address) # It should be deleted MultisigTransactionFactory( safe=safe_status.address, ethereum_tx=None ) # It shouldn't be deleted self.assertIsNone(index_service.reprocess_addresses([safe_status.address])) self.assertEqual(SafeStatus.objects.count(), 0) self.assertEqual(MultisigTransaction.objects.count(), 2) def test_reprocess_all(self): index_service: IndexService = IndexServiceProvider() for _ in range(5): safe_status = SafeStatusFactory() MultisigTransactionFactory(safe=safe_status.address) MultisigTransactionFactory(ethereum_tx=None) # It shouldn't be deleted self.assertIsNone(index_service.reprocess_all()) self.assertEqual(SafeStatus.objects.count(), 0) self.assertEqual(MultisigTransaction.objects.count(), 1)
3,758
35
103
d77f9868884df422417b5e97e91ff3e08b0c1013
37,960
py
Python
tests/tests_bian.py
devashah1992/bianPython
e0b92b092c23c07d09446abf5f5d765e0bfe1c4e
[ "MIT" ]
null
null
null
tests/tests_bian.py
devashah1992/bianPython
e0b92b092c23c07d09446abf5f5d765e0bfe1c4e
[ "MIT" ]
null
null
null
tests/tests_bian.py
devashah1992/bianPython
e0b92b092c23c07d09446abf5f5d765e0bfe1c4e
[ "MIT" ]
null
null
null
from __future__ import print_function from faker import Faker from flask import Flask, request from requests.auth import * from flask_restful import Api import json from nose.tools import eq_ from halo_flask.exceptions import ApiError from halo_flask.flask.utilx import status from halo_bian.bian.abs_bian_srv import AbsBianMixin,ActivationAbsBianMixin,ConfigurationAbsBianMixin,FeedbackAbsBianMixin from halo_bian.bian.db import AbsBianDbMixin from halo_bian.bian.exceptions import BianException,BianError from halo_flask.apis import * from halo_flask.flask.utilx import Util from halo_flask.flask.servicex import FoiBusinessEvent,SagaBusinessEvent from halo_flask.flask.filter import RequestFilterClear from halo_bian.bian.bian import BianCategory,ActionTerms,Feature,ControlRecord,GenericArtifact,BianContext,BianRequestFilter,FunctionalPatterns from halo_flask.ssm import set_app_param_config,set_host_param_config from halo_flask.flask.viewsx import load_global_data from halo_flask.base_util import BaseUtil import unittest fake = Faker() app = Flask(__name__) api = Api(app) class TestUserDetailTestCase(unittest.TestCase): """ Tests /users detail operations. """ session_id = None
47.688442
217
0.653056
from __future__ import print_function from faker import Faker from flask import Flask, request from requests.auth import * from flask_restful import Api import json from nose.tools import eq_ from halo_flask.exceptions import ApiError from halo_flask.flask.utilx import status from halo_bian.bian.abs_bian_srv import AbsBianMixin,ActivationAbsBianMixin,ConfigurationAbsBianMixin,FeedbackAbsBianMixin from halo_bian.bian.db import AbsBianDbMixin from halo_bian.bian.exceptions import BianException,BianError from halo_flask.apis import * from halo_flask.flask.utilx import Util from halo_flask.flask.servicex import FoiBusinessEvent,SagaBusinessEvent from halo_flask.flask.filter import RequestFilterClear from halo_bian.bian.bian import BianCategory,ActionTerms,Feature,ControlRecord,GenericArtifact,BianContext,BianRequestFilter,FunctionalPatterns from halo_flask.ssm import set_app_param_config,set_host_param_config from halo_flask.flask.viewsx import load_global_data from halo_flask.base_util import BaseUtil import unittest fake = Faker() app = Flask(__name__) api = Api(app) class OutboundApi(AbsBaseApi): name = 'Outbound' class CAFeature(Feature): pass class BankingProduct(GenericArtifact): pass class CAControlRecord(BankingProduct): pass class CAContext(BianContext): TESTER = "Tester" BianContext.items[TESTER]="test" class BianRequestFilterX(BianRequestFilter): def augment_event_with_data(self, event, halo_request, halo_response): raise BianException("req") return event class BianRequestFilterClear(RequestFilterClear): pass class RequestFilterClearX(RequestFilterClear): def run(self): for event in self.eventx: logger.debug("insert_events_to_repository " + str(event.serialize())) class A1(AbsBianMixin):#the basic def set_back_api(self, halo_request, foi=None): if not foi:#not in seq if halo_request.request.method == HTTPChoice.get.value: return CnnApi(halo_request.context,HTTPChoice.get.value) if halo_request.request.method == HTTPChoice.delete.value: return CnnApi(halo_request.context,HTTPChoice.delete.value) return super(A1,self).set_back_api(halo_request,foi) def set_added_api_vars(self, bian_request,vars, seq=None, dict=None): logger.debug("in set_api_vars " + str(bian_request)) if seq == '3': if "name" in bian_request.request.args: name = bian_request.request.args['name'] if name not in vars: vars['name'] = name return vars def execute_api(self,halo_request, back_api, back_vars, back_headers, back_auth, back_data=None, seq=None, dict=None): logger.debug("in execute_api "+back_api.name) if back_api: timeout = Util.get_timeout(halo_request.request) try: seq_msg = "" if seq: seq_msg = "seq = " + seq + "." if seq == '3': back_api.set_api_url('ID', back_vars['name']) ret = back_api.run(timeout, headers=back_headers,auth=back_auth, data=back_data) msg = "in execute_api. " + seq_msg + " code= " + str(ret.status_code) logger.info(msg) return ret except ApiError as e: raise BianException(e) return None class A2(A1):# customized def validate_req(self, bian_request): print("in validate_req ") if bian_request: if "name" in bian_request.request.args: name = bian_request.request.args['name'] if not name: raise BianError("missing value for query var name") return True def set_api_headers(self,bian_request, seq=None, dict=None): print("in set_api_headers ") headers = {'Accept':'application/json'} return headers def set_api_vars(self,bian_request, seq=None, dict=None): print("in set_api_vars " + str(bian_request)) ret = {} name = bian_request.request.args['name'] if name: ret['name'] = name if bian_request: ret["bq"] = bian_request.behavior_qualifier ret["id"] = bian_request.cr_reference_id return ret def set_api_auth(self,bian_request, seq=None, dict=None): print("in set_api_auth ") user = '' pswd = '' return HTTPBasicAuth(user,pswd) def execute_api(self,bian_request, back_api, back_vars, back_headers,back_auth,back_data, seq=None, dict=None): print("in execute_api ") if back_api: timeout = Util.get_timeout(bian_request.request) try: back_api.set_api_url('ID',back_vars['name']) ret = back_api.get(timeout,headers=back_headers,auth=back_auth) return ret except ApiError as e: raise BianException(e) return None def create_resp_payload(self, bian_request,dict_back_json): print("in create_resp_payload " + str(dict_back_json)) if dict_back_json: return self.map_from_json(dict_back_json,{}) return dict_back_json def map_from_json(self,dict_back_json,payload): print("in map_from_json") payload['name'] = "test"#dict_back_json[1]["title"] return payload class MyBusinessEvent(FoiBusinessEvent): pass class SaBusinessEvent(SagaBusinessEvent): pass class A3(AbsBianMixin):# the foi filter_separator = "#" filter_key_values = {None: {'customer-reference-id': 'customerId','amount':'amount','user':'user','page_no':'page_no','count':'count'}} filter_chars = {None: ['=','>']} def set_back_api(self,bian_request,foi=None): if foi: return super(A3,self).set_back_api(bian_request,foi) print("in set_back_api ") api = TstApi(bian_request.context) api.set_api_url("ID","1") return api def validate_req_depositsandwithdrawals(self, bian_request): print("in validate_req_deposit ") if bian_request: if "name" in bian_request.request.args: name = bian_request.request.args['name'] if not name: raise BianError("missing value for query var name") return True def validate_pre_depositsandwithdrawals(self, bian_request): print("in validate_req_deposit ") if bian_request: if "name" in bian_request.request.args: name = bian_request.request.args['name'] if not name: raise BianError("missing value for query var name") return True def set_back_api_depositsandwithdrawals(self,bian_request,foi=None): if foi: return self.set_back_api(bian_request,foi) print("in set_back_api_deposit ") TstApi(bian_request.context) def set_api_headers_depositsandwithdrawals(self, bian_request,foi=None,dict=None): print("in set_api_headers_deposit ") headers = {'Accept':'application/json'} return headers def set_api_vars_depositsandwithdrawals(self, bian_request,foi=None,dict=None): print("in set_api_vars_deposit " + str(bian_request)) ret = {} name = None if 'name' in bian_request.request.args: name = bian_request.request.args['name'] if name: ret['name'] = name if bian_request: ret["bq"] = bian_request.behavior_qualifier ret["id"] = bian_request.cr_reference_id return ret def set_api_auth_depositsandwithdrawals(self, bian_request,foi=None,dict=None): print("in set_api_auth_deposit ") user = '' pswd = '' return HTTPBasicAuth(user,pswd) def execute_api_depositsandwithdrawals(self, bian_request, back_api, back_vars, back_headers,back_auth,back_data,foi=None,dict=None): print("in execute_api_deposit ") if back_api: timeout = Util.get_timeout(bian_request.request) try: back_api.set_api_url('ID',back_vars['name']) ret = back_api.get(timeout,headers=back_headers,auth=back_auth) return ret except ApiError as e: raise BianException(e) return None def create_resp_payload_depositsandwithdrawals(self, bian_request,dict): print("in create_resp_payload_deposit " + str(dict)) if dict: return self.map_from_json_depositsandwithdrawals(dict,{}) return {} def extract_json_depositsandwithdrawals(self,bian_request,back_json,foi=None): print("in extract_json_deposit") return {"title":"good"} def map_from_json_depositsandwithdrawals(self, dict, payload): print("in map_from_json_deposit") payload['name'] = dict['1']["title"] return payload def set_resp_headers_depositsandwithdrawals(self, bian_request,headers): return self.set_resp_headers(bian_request,headers) def validate_post_depositsandwithdrawals(self, bian_request,ret): return True class A4(AbsBianMixin):# the foi def set_back_api(self,bian_request,foi=None): print("in set_back_api ") if foi: return super(A4,self).set_back_api(bian_request,foi) api = TstApi(bian_request.context) api.set_api_url("ID", "1") return api def create_resp_payload(self,halo_request, dict): print("in create_resp_payload") json = dict['1'] return {"name":json["title"]} class A5(A3): def set_back_api_depositsandwithdrawals(self, bian_request, foi=None): if foi: return self.set_back_api(bian_request, foi) print("in set_back_api_deposit ") return GoogleApi(bian_request.context) class A6(A5): def validate_req_depositsandwithdrawals_deposits(self,bian_request): return def validate_pre_depositsandwithdrawals_deposits(self,bian_request): return def set_back_api_depositsandwithdrawals_deposits(self,bian_request): return def set_api_headers_depositsandwithdrawals_deposits(self,bian_request): return def set_api_vars_depositsandwithdrawals_deposits(self,bian_request): return def set_api_auth_depositsandwithdrawals_deposits(self,bian_request): return def execute_api_depositsandwithdrawals_deposits(self,bian_request, back_api, back_vars, back_headers, back_auth, back_data): return def extract_json_depositsandwithdrawals_deposits(self,bian_request, back_response): return def create_resp_payload_depositsandwithdrawals_deposits(self,bian_request, dict): return def set_resp_headers_depositsandwithdrawals_deposits(self,bian_request,headers): return def validate_post_depositsandwithdrawals_deposits(self,halo_request, halo_response): return class X1(ActivationAbsBianMixin): pass class X2(ConfigurationAbsBianMixin): pass class X3(FeedbackAbsBianMixin): pass class BianDbMixin(AbsBianDbMixin): pass class TestUserDetailTestCase(unittest.TestCase): """ Tests /users detail operations. """ session_id = None def setUp(self): #app.config.from_pyfile('../settings.py') app.config.from_object('settings') def test_00_get_request_returns_a_given_string(self): from halo_flask.flask.viewsx import load_global_data app.config['ENV_TYPE'] = LOC app.config['SSM_TYPE'] = "AWS" #app.config['FUNC_NAME'] = "FUNC_NAME" app.config['HALO_HOST'] = "halo_bian" app.config['AWS_REGION'] = 'us-east-1' app.config["INIT_CLASS_NAME"] = 'halo_bian.bian.abs_bian_srv.BianGlobalService' app.config["INIT_DATA_MAP"] = {'INIT_STATE': "Idle", 'PROP_URL': "C:\\dev\projects\\halo\\framework\\test179\\bian_service_domains\\halo_contact_dialogue\\env\\config\\bian_setting_mapping.json"} with app.test_request_context('/?name=Peter'): try: if 'INIT_DATA_MAP' in app.config and 'INIT_CLASS_NAME' in app.config: data_map = app.config['INIT_DATA_MAP'] class_name = app.config['INIT_CLASS_NAME'] load_global_data(class_name, data_map) except Exception as e: eq_(e.__class__.__name__, "NoApiClassException") def test_0_get_request_returns_a_given_string(self): json = { "serviceDomainActivationActionTaskRecord": {}, "serviceDomainCenterReference": "SCR793499", "serviceDomainServiceReference": "CPASSR703914", "serviceDomainServiceConfigurationRecord": { "serviceDomainServiceConfigurationSettingReference": "700761", "serviceDomainServiceConfigurationSettingType": "string", "serviceDomainServiceConfigurationSetup": { "serviceDomainServiceConfigurationParameter": "string" } } } app.config["DBACCESS_CLASS"] = "tests.tests_bian.BianDbMixin" app.config['ENV_TYPE'] = LOC app.config['SSM_TYPE'] = "AWS" app.config['HALO_HOST'] = "halo_bian" #app.config['FUNC_NAME'] = "FUNC_NAME" app.config['AWS_REGION'] = 'us-east-1' app.config["INIT_CLASS_NAME"] = 'halo_bian.bian.abs_bian_srv.BianGlobalService' app.config["INIT_DATA_MAP"] = {'INIT_STATE': "Idle", 'PROP_URL': "C:\\dev\projects\\halo\\framework\\test179\\bian_service_domains\\halo_contact_dialogue\\env\\config\\bian_setting_mapping.json"} with app.test_request_context('/?name=Peter',json=json): app.config['HALO_HOST'] = "halo_bian" if 'INIT_DATA_MAP' in app.config and 'INIT_CLASS_NAME' in app.config: data_map = app.config['INIT_DATA_MAP'] class_name = app.config['INIT_CLASS_NAME'] load_global_data(class_name, data_map) self.x1 = X1() self.x1.bian_action = ActionTerms.ACTIVATE self.x1.functional_pattern = FunctionalPatterns.FULFILL self.x1.filter_separator = ";" ret = self.x1.process_post(request, {}) assert ret.code == status.HTTP_200_OK def test_1_get_request_returns_a_given_string(self): with app.test_request_context('/?name=Peter'): self.a1 = A1() ret = self.a1.process_get(request, {}) assert ret.code == status.HTTP_200_OK def test_2_get_request_with_ref_returns_a_given_string(self): with app.test_request_context('/?name=Peter'): self.a1 = A1() ret = self.a1.process_get(request, {"cr_reference_id": "123"}) assert ret.code == status.HTTP_200_OK def test_3_get_request_with_ref_bq_returns_a_given_string(self): with app.test_request_context('/?name=Peter'): self.a1 = A1() try: ret = self.a1.process_get(request, {"cr_reference_id": "123", "behavior_qualifier": "DepositsandWithdrawals"}) assert False except Exception as e: print(str(e) + " " + str(type(e).__name__)) assert type(e).__name__ == 'HaloMethodNotImplementedException' def test_4_get_request_with_bad_bq_returns_a_given_string(self): with app.test_request_context('/?name=Peter'): self.a1 = A1() try: ret = self.a1.process_get(request, {"cr_reference_id": "123", "behavior_qualifier": "456"}) assert False except Exception as e: print(str(e) + " " + str(type(e).__name__)) assert type(e).__name__ == 'IllegalBQError' def test_5_post_request_returns_a_given_error(self): with app.test_request_context(method='POST',path='/tst'): self.a1 = A1() try: ret = self.a1.process_post(request, {}) assert False except Exception as e: print(str(e) + " " + str(type(e))) assert type(e).__name__ == "IllegalActionTermError" def test_6_post_request_returns_a_given_error1(self): with app.test_request_context(method='POST',path='/'): self.a1 = A1() try: ret = self.a1.process_post(request, {}) assert False except Exception as e: print(str(e) + " " + str(type(e))) assert type(e).__name__ == "IllegalActionTermError" def test_7_post_request_returns_a_given_string(self): with app.test_request_context(method='POST',path='/?name=Peter'): self.a1 = A1() self.a1.bian_action = ActionTerms.INITIATE ret = self.a1.process_post(request, {}) assert ret.code == status.HTTP_201_CREATED def test_8_patch_request_returns_a_given_string(self): with app.test_request_context(method='PATCH',path='/?name=Peter'): self.a1 = A1() ret = self.a1.process_patch(request, {}) assert ret.code == status.HTTP_202_ACCEPTED def test_90_put_request_returns_a_given_string(self): with app.test_request_context(method='PUT',path='/tst?name=1'): self.a1 = A1() ret = self.a1.process_put(request, {}) assert ret.code == status.HTTP_202_ACCEPTED def test_91_delete_request_returns_a_given_string(self): with app.test_request_context(method='DELETE',path='/tst'): self.a1 = A1() ret = self.a1.process_delete(request, {}) assert ret.code == status.HTTP_200_OK def test_92_get_request_returns_a_given_stringx_for_test(self): with app.test_request_context('/tst'): self.a1 = A1() ret = self.a1.process_get(request, {}) assert ret.code == status.HTTP_200_OK def test_93_full_request_returns_a_given_string(self): with app.test_request_context('/?name=1'): self.a2 = A2() ret = self.a2.process_get(request, {"cr_reference_id":"1"}) assert ret.code == status.HTTP_200_OK assert ret.payload["name"] == 'test' def test_94_request_returns_a_given_string(self): with app.test_request_context('/x?name=1'): self.a4 = A4() ret = self.a4.process_get(request, {}) assert ret.code == status.HTTP_200_OK assert ret.payload["name"] == 'delectus aut autem' def test_95_bq_request_returns_a_given_string(self): with app.test_request_context('/?name=1'): self.a3 = A3() self.a3.filter_separator = ";" ret = self.a3.process_get(request, {"behavior_qualifier":"DepositsandWithdrawals"}) assert ret.code == status.HTTP_200_OK assert ret.payload["name"] == 'good' def test_96_cf_request_returns_a_given_string(self): with app.test_request_context('/?collection-filter=amount>100'): self.a3 = A3() ret = self.a3.process_get(request, {}) assert ret.request.collection_filter[0] == "amount>100" def test_97_cf_request_returns_a_given_list(self): with app.test_request_context(method='POST',path='/?name=john&collection-filter=amount>100; user = 100 ; page_no = 2 ; count=20'): self.a3 = A3() self.a3.bian_action = ActionTerms.EXECUTE self.a3.filter_separator = ";" ret = self.a3.process_post(request, {}) assert ret.request.collection_filter[0] == "amount>100" assert ret.request.collection_filter[1] == "user = 100" assert ret.request.collection_filter[2] == "page_no = 2" assert ret.request.collection_filter[3] == "count=20" def test_98_action_request_returns_a_given_error(self): with app.test_request_context('/?collection-filter=amount>100'): self.a3 = A3() self.a3.bian_action = ActionTerms.EVALUATE try: ret = self.a3.process_get(request, {}) assert ret.request.collection_filter[0] != "amount>100" except Exception as e: assert type(e).__name__ == "IllegalActionTermError" def test_990_mask_cr_request_returns_a_given_error(self): with app.test_request_context('/consumer-loan/1a/consumer-loan-fulfillment-arrangement/2/depositsandwithdrawals/3/?collection-filter=amount>100'): self.a3 = A3() self.a3.bian_action = ActionTerms.EXECUTE try: ret = self.a3.process_get(request, {"cr_reference_id":"2","bq_reference_id":"3a"}) assert False except Exception as e: assert type(e).__name__ == "IllegalBQError" def test_991_mask_bq_request_returns_a_given_error(self): with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/2/depositsandwithdrawals/1b/?collection-filter=amount>100'): self.a3 = A3() self.a3.bian_action = ActionTerms.EXECUTE try: ret = self.a3.process_get(request, {"cr_reference_id":"","bq_reference_id":""}) assert False except Exception as e: assert type(e).__name__ == "IllegalBQError" def test_992_request_returns_a_response(self): with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/1/depositsandwithdrawals/1/?name=peter&collection-filter=amount>100'): self.a3 = A3() self.a3.bian_action = ActionTerms.EXECUTE ret = self.a3.process_get(request, {"cr_reference_id":"1","bq_reference_id":"1"}) assert ret.code == status.HTTP_200_OK assert len(ret.request.collection_filter) == 1 assert ret.request.action_term == ActionTerms.EXECUTE assert ret.request.cr_reference_id == "1" assert ret.request.bq_reference_id == "1" assert ret.request.request == request def test_993_request_returns_a_response(self): with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/1/depositsandwithdrawals/1/?name=peter&collection-filter=amount>100'): self.a3 = A3() self.a3.bian_action = ActionTerms.EXECUTE ret = self.a3.process_put(request, {"cr_reference_id":"1","bq_reference_id":"1"}) assert ret.code == 200 def test_995_control_record_returns_a_given_list(self): with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement//?name=1&queryparams=amount>100@x=y'): self.a3 = A3() ret = self.a3.process_get(request, {"sd_reference_id":"1","behavior_qualifier":"DepositsandWithdrawals"}) print("x=" + str(ret.payload)) assert ret.code == status.HTTP_200_OK assert ret.request.behavior_qualifier == 'DepositsandWithdrawals' assert ret.request.request == request assert ret.request.sd_reference_id == "1" assert len(ret.request.query_params) == 2 assert ret.request.query_params[0] == 'amount>100' assert ret.request.query_params[1] == 'x=y' def test_996_request_sub_returns_a_response(self): with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/1/depositsandwithdrawals/1/?name=peter&collection-filter=amount>100',headers={'x-bian-devparty': 'Your value'}): app.config["BIAN_CONTEXT_LIST"] = [BianContext.APP_CLIENT] self.a5 = A5() self.a5.bian_action = ActionTerms.EXECUTE ret = self.a5.process_put(request, {"sd_reference_id":"1","cr_reference_id":"1","bq_reference_id":"1"}) assert ret.code == 200 def test_997_request_sub_returns_a_response(self): with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/1/depositsandwithdrawals/1/?name=peter&collection-filter=amount>100',headers={'x-bian-devparty1': 'Your value'}): app.config["BIAN_CONTEXT_LIST"] = [BianContext.APP_CLIENT] self.a5 = A5() self.a5.bian_action = ActionTerms.EXECUTE try: ret = self.a5.process_put(request, {"sd_reference_id":"1","cr_reference_id":"1","bq_reference_id":"1"}) except Exception as e: assert type(e).__name__ == "MissingBianContextException" def test_998_request_sub_returns_a_response(self): with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/2/depositsandwithdrawals/3/?name=peter&collection-filter=amount>100',headers={'x-bian-devparty': 'Your value'}): app.config["BIAN_CONTEXT_LIST"] = [BianContext.APP_CLIENT] self.a5 = A5() self.a5.bian_action = ActionTerms.EXECUTE ret = self.a5.process_put(request, {"cr_reference_id":"2","bq_reference_id":"3","sbq_reference_id":"4"}) assert ret.code == 200 def test_999_request_sub_returns_a_response(self): with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/2/depositsandwithdrawals/3/?name=peter&collection-filter=amount>100',headers={'x-bian-devparty': 'Your value'}): app.config["HALO_CONTEXT_CLASS"] = None self.a5 = A5() self.a5.bian_action = ActionTerms.EXECUTE ret = self.a5.process_put(request, {"sd_reference_id":"1","cr_reference_id":"2","bq_reference_id":"3"}) assert ret.code == 200 def test_9991_request_sub_returns_a_response(self): with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/2/depositsandwithdrawals/3/?name=peter&collection-filter=amount>100',headers={'x-bian-devparty': 'Your value'}): self.a5 = A5() self.a5.bian_action = ActionTerms.EXECUTE ret = self.a5.process_put(request, {"sd_reference_id":"1","cr_reference_id":"1","bq_reference_id":"3"}) assert ret.code == 200 def test_9992_request_sub_returns_a_response(self): with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/2/servicefees/3/?name=peter&collection-filter=amount>100',headers={'x-bian-devparty': 'Your value'}): app.config["BIAN_CONTEXT_LIST"] = [CAContext.TESTER] self.a5 = A5() self.a5.bian_action = ActionTerms.EXECUTE try: ret = self.a5.process_put(request, {"sd_reference_id":"1","cr_reference_id":"1","bq_reference_id":"3"}) except Exception as e: assert type(e).__name__ == "HaloMethodNotImplementedException" def test_9993_request_sub_returns_a_response(self): with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/2/depositsandwithdrawals/3/deposits/4/?name=peter&collection-filter=amount>100',headers={'x-bian-devparty': 'Your value'}): app.config["HALO_CONTEXT_CLASS"] = None self.a6 = A6() self.a6.bian_action = ActionTerms.EXECUTE ret = self.a6.process_put(request, {"sd_reference_id":"1","cr_reference_id":"2","bq_reference_id":"3","sbq_reference_id":"4"}) assert ret.code == 200 def test_99931_request_sub_returns_a_response(self): with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/2/depositsandwithdrawals/3/deposits/1/?name=peter&collection-filter=amount>100',headers={'x-bian-devparty': 'Your value'}): app.config["HALO_CONTEXT_CLASS"] = None self.a6 = A6() self.a6.bian_action = ActionTerms.EXECUTE ret = self.a6.process_put(request, {"sd_reference_id":"1","cr_reference_id":"2","bq_reference_id":"3","sbq_reference_id":"1"}) assert ret.code == 200 def test_9994_request_sub_returns_a_response(self): with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/2/depositsandwithdrawals/3/?name=peter&collection-filter=amount>100',headers={'x-bian-devparty': 'Your value'}): self.a5 = A5() self.a5.bian_action = ActionTerms.EXECUTE try: ret = self.a5.process_put(request, {"cr_reference_id":"1","bq_reference_id":"1","sbq_reference_id":"1"}) except Exception as e: assert type(e).__name__ == "IllegalBQError" def test_9995_request_sub_returns_a_response(self): with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/2/depositsandwithdrawals/3/deposits/1/?name=peter&collection-filter=amount>100',headers={'x-bian-devparty': 'Your value'}): app.config["REQUEST_FILTER_CLASS"] = 'halo_bian.bian.bian.BianRequestFilter' self.a6 = A6() self.a6.bian_action = ActionTerms.EXECUTE ret = self.a6.process_put(request, {"sd_reference_id":"1","cr_reference_id":"2","bq_reference_id":"3","sbq_reference_id":"1"}) assert ret.code == 200 def test_9996_request_sub_returns_a_response(self): with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/2/depositsandwithdrawals/3/deposits/1/?name=peter&collection-filter=amount>100',headers={'x-bian-devparty': 'Your value'}): app.config["REQUEST_FILTER_CLASS"] = 'tests_bian.BianRequestFilterX' self.a6 = A6() self.a6.bian_action = ActionTerms.EXECUTE try: ret = self.a6.process_put(request, {"sd_reference_id":"1","cr_reference_id":"2","bq_reference_id":"3","sbq_reference_id":"1"}) except Exception as e: assert type(e).__name__ == "BianException" def test_9997_request_sub_returns_a_response(self): with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/2/depositsandwithdrawals/3/deposits/1/?name=peter&collection-filter=amount>100',headers={'x-bian-devparty': 'Your value'}): app.config["REQUEST_FILTER_CLEAR_CLASS"] = 'tests_bian.BianRequestFilterClear' self.a6 = A6() self.a6.bian_action = ActionTerms.EXECUTE ret = self.a6.process_put(request, {"sd_reference_id":"1","cr_reference_id":"2","bq_reference_id":"3","sbq_reference_id":"1"}) assert ret.code == 200 def test_9998_request_sub_returns_a_response(self): with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/2/depositsandwithdrawals/3/deposits/1/?name=peter&collection-filter=amount>100',headers={'x-bian-devparty': 'Your value'}): app.config["REQUEST_FILTER_CLEAR_CLASS"] = 'tests_bian.RequestFilterClearX' self.a6 = A6() self.a6.bian_action = ActionTerms.EXECUTE try: ret = self.a6.process_put(request, {"sd_reference_id":"1","cr_reference_id":"2","bq_reference_id":"3","sbq_reference_id":"1"}) except Exception as e: assert type(e).__name__ == "BianException" def test_99991_request_sub_returns_a_response(self): json = { "serviceDomainActivationActionTaskRecord": {}, "serviceDomainCenterReference": "SCR793499", "serviceDomainServiceReference": "CPASSR703914", "serviceDomainServiceConfigurationRecord": { "serviceDomainServiceConfigurationSettingReference": "700761", "serviceDomainServiceConfigurationSettingType": "string", "serviceDomainServiceConfigurationSetup": { "serviceDomainServiceConfigurationParameter": "string" } } } with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/2/depositsandwithdrawals/3/deposits/1/?name=peter',headers={'x-bian-devparty': 'Your value'},json=json): self.x1 = X1() self.x1.bian_action = ActionTerms.ACTIVATE ret = self.x1.process_post(request, {}) print(ret.payload) self.session_id = ret.payload["serviceDomainServicingSessionReference"] assert ret.code == 200 def test_99992_request_sub_returns_a_response(self): json = { "serviceDomainConfigurationActionTaskRecord": {}, "serviceDomainServicingSessionReference": "SSSR764367", "serviceDomainServiceReference": "CPASSR744740", "serviceDomainServiceConfigurationRecord": { "serviceDomainServiceConfigurationSettingReference": "710630", "serviceDomainServiceConfigurationSettingType": "string", "serviceDomainServiceConfigurationSetup": { "serviceDomainServiceConfigurationParameter": "string" }, "serviceDomainServiceSubscription": { "serviceDomainServiceSubscriberReference": "756221", "serviceDomainServiceSubscriberAccessProfile": "string" }, "serviceDomainServiceAgreement": { "serviceDomainServiceAgreementReference": "721156", "serviceDomainServiceUserReference": "733696", "serviceDomainServiceAgreementTermsandConditions": "string" } } } with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/2/depositsandwithdrawals/3/deposits/1/?name=peter',headers={'x-bian-devparty': 'Your value'},json=json): from halo_flask.flask.viewsx import load_global_data app.config['SSM_TYPE'] = "AWS" app.config["INIT_CLASS_NAME"] = 'halo_bian.bian.abs_bian_srv.BianGlobalService' app.config["INIT_DATA_MAP"] = {'INIT_STATE': "Idle", 'PROP_URL': "C:\\dev\\projects\\halo\\halo_bian\\halo_bian\\env\\config\\bian_setting_mapping.json"} load_global_data(app.config["INIT_CLASS_NAME"], app.config["INIT_DATA_MAP"]) self.x2 = X2() self.x2.bian_action = ActionTerms.CONFIGURE ret = self.x2.process_put(request, {"sd_reference_id":self.session_id}) assert ret.code == 200 def test_99993_request_sub_returns_a_response(self): json = { "serviceDomainFeedbackActionTaskRecord": {}, "serviceDomainFeedbackActionRecord": { "serviceDomainServicingSessionReference": "796678", "controlRecordInstanceReference": "724385", "behaviorQualifierInstanceReference": "789747", "feedbackRecordType": "string", "feedbackRecord": {} } } with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/2/depositsandwithdrawals/3/deposits/1/?name=peter',headers={'x-bian-devparty': 'Your value'},json=json): self.x3 = X3() self.x3.bian_action = ActionTerms.FEEDBACK ret = self.x3.process_put(request, {"sd_reference_id":self.session_id}) assert ret.code == 200 def test_99994_request_sub_returns_a_response(self): json = { "serviceDomainFeedbackActionTaskRecord": {}, "serviceDomainFeedbackActionRecord": { "serviceDomainServicingSessionReference": "796678", "controlRecordInstanceReference": "724385", "behaviorQualifierInstanceReference": "789747", "feedbackRecordType": "string", "feedbackRecord": {} } } with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/2/depositsandwithdrawals/3/deposits/1/?name=peter',headers={'x-bian-devparty': 'Your value'},json=json): self.x3 = X3() self.x3.bian_action = ActionTerms.FEEDBACK ret = self.x3.process_put(request, {"sd_reference_id":self.session_id,"cr_reference_id":"2"}) assert ret.code == 200 def test_99995_request_sub_returns_a_response(self): json = { "serviceDomainFeedbackActionTaskRecord": {}, "serviceDomainFeedbackActionRecord": { "serviceDomainServicingSessionReference": "796678", "controlRecordInstanceReference": "724385", "behaviorQualifierInstanceReference": "789747", "feedbackRecordType": "string", "feedbackRecord": {} } } with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/2/depositsandwithdrawals/3/deposits/1/?name=peter',headers={'x-bian-devparty': 'Your value'},json=json): self.x3 = X3() self.x3.bian_action = ActionTerms.FEEDBACK ret = self.x3.process_put(request, {"sd_reference_id":self.session_id,"cr_reference_id":"2","bq_reference_id":"3"}) assert ret.code == 200 def test_99996_request_sub_returns_a_response(self): json = { "serviceDomainFeedbackActionTaskRecord": {}, "serviceDomainFeedbackActionRecord": { "serviceDomainServicingSessionReference": "796678", "controlRecordInstanceReference": "724385", "behaviorQualifierInstanceReference": "789747", "feedbackRecordType": "string", "feedbackRecord": {} } } with app.test_request_context('/consumer-loan/1/consumer-loan-fulfillment-arrangement/2/depositsandwithdrawals/3/deposits/1/?name=peter',headers={'x-bian-devparty': 'Your value'},json=json): self.x3 = X3() self.x3.bian_action = ActionTerms.FEEDBACK ret = self.x3.process_put(request, {"sd_reference_id":self.session_id,"cr_reference_id":"2","bq_reference_id":"3","sbq_reference_id":"1"}) assert ret.code == 200
33,436
968
2,340
76ea23e2c20a282da1d09a527396d6354b723e6a
14,852
py
Python
tripleo_common/image/builder/buildah.py
openstack/tripleo-common
7e8942329a453142155763851a3b19251bbe662b
[ "Apache-2.0" ]
52
2015-04-17T12:06:09.000Z
2021-11-23T09:46:30.000Z
tripleo_common/image/builder/buildah.py
openstack/tripleo-common
7e8942329a453142155763851a3b19251bbe662b
[ "Apache-2.0" ]
null
null
null
tripleo_common/image/builder/buildah.py
openstack/tripleo-common
7e8942329a453142155763851a3b19251bbe662b
[ "Apache-2.0" ]
47
2015-10-09T15:22:38.000Z
2021-04-22T04:35:57.000Z
# Copyright 2019 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # from concurrent import futures import os import pathlib import tenacity from oslo_concurrency import processutils from oslo_config import cfg from oslo_log import log as logging from tripleo_common import constants from tripleo_common.image.builder import base from tripleo_common.utils import process CONF = cfg.CONF LOG = logging.getLogger(__name__ + ".BuildahBuilder") class BuildahBuilder(base.BaseBuilder): """Builder to build container images with Buildah.""" log = LOG def __init__(self, work_dir, deps, base='fedora', img_type='binary', tag='latest', namespace='master', registry_address='127.0.0.1:8787', push_containers=True, volumes=[], excludes=[], build_timeout=None, debug=False): """Setup the parameters to build with Buildah. :params work_dir: Directory where the Dockerfiles or Containerfiles are generated by Kolla. :params deps: Dictionary defining the container images dependencies. :params base: Base image on which the containers are built. Default to fedora. :params img_type: Method used to build the image. All TripleO images are built from binary method. Can be set to false to remove it from image name. :params tag: Tag used to identify the images that we build. Default to latest. :params namespace: Namespace used to build the containers. Default to master. :params registry_address: IP + port of the registry where we push the images. Default is 127.0.0.1:8787. :params push: Flag to bypass registry push if False. Default is True :params volumes: Bind mount volumes used during buildah bud. Default to []. :params excludes: List of images to skip. Default to []. :params build_timeout: Timeout. Default to constants.BUILD_TIMEOUT :params debug: Enable debug flag. Default to False. """ logging.register_options(CONF) if debug: CONF.debug = True logging.setup(CONF, '') super(BuildahBuilder, self).__init__() if build_timeout is None: self.build_timeout = constants.BUILD_TIMEOUT else: self.build_timeout = build_timeout self.work_dir = work_dir self.deps = deps self.base = base self.img_type = img_type self.tag = tag self.namespace = namespace self.registry_address = registry_address self.push_containers = push_containers self.volumes = volumes self.excludes = excludes self.debug = debug # Each container image has a Dockerfile or a Containerfile. # Buildah needs to know the base directory later. self.cont_map = {os.path.basename(root): root for root, dirs, fnames in os.walk(self.work_dir) if 'Dockerfile' in fnames or 'Containerfile' in fnames} # Building images with root so overlayfs is used, and not fuse-overlay # from userspace, which would be slower. self.buildah_cmd = ['sudo', 'buildah'] if self.debug: self.buildah_cmd.append('--log-level=debug') def _find_container_dir(self, container_name): """Return the path of the Dockerfile/Containerfile directory. :params container_name: Name of the container. """ if container_name not in self.cont_map: self.log.error('Container not found in Kolla ' 'deps: %s' % container_name) return self.cont_map.get(container_name, '') def _get_destination(self, container_name): """Return the destination of a container image to push. :params container_name: Name of the container. """ destination = "{}/{}/{}".format( self.registry_address, self.namespace, self.base, ) if self.img_type: destination += '-' + self.img_type destination += '-' + container_name + ':' + self.tag return destination def _generate_container(self, container_name): """Generate a container image by building and pushing the image. :params container_name: Name of the container. """ if container_name in self.excludes: return # NOTE(mwhahaha): Use a try catch block so we can better log issues # as this is called in a multiprocess fashion so the exception # loses some information when it reaches _multi_build try: self.build(container_name, self._find_container_dir(container_name)) if self.push_containers: self.push(self._get_destination(container_name)) except Exception as e: self.log.exception(e) raise @tenacity.retry( # Retry up to 5 times: 0, 1, 5, 21, 85 # http://exponentialbackoffcalculator.com/ reraise=True, wait=tenacity.wait_random_exponential(multiplier=4, max=60), stop=tenacity.stop_after_attempt(5), before_sleep=tenacity.after_log(LOG, logging.WARNING) ) def build(self, container_name, container_build_path): """Build an image from a given directory. :params container_name: Name of the container. :params container_build_path: Directory where the Dockerfile or Containerfile and other files are located to build the image. """ # 'buildah bud' is the command we want because Kolla uses Dockefile to # build images. # TODO(emilien): Stop ignoring TLS. The deployer should either secure # the registry or add it to insecure_registries. logfile = container_build_path + '/' + container_name + '-build.log' # TODO(ramishra) Hack to make the logfile readable by current user, # as we're running buildah as root. This would be removed once we # move to rootless buildah. pathlib.Path(logfile).touch() bud_args = ['bud'] for v in self.volumes: bud_args.extend(['--volume', v]) if self.debug: # TODO(bogdando): add --log-rusage for newer buildah bud_args.extend(['--loglevel=3']) # TODO(aschultz): drop --format docker when oci format is properly # supported by the undercloud registry bud_args.extend(['--format', 'docker', '--tls-verify=False', '--logfile', logfile, '-t', self._get_destination(container_name), container_build_path]) args = self.buildah_cmd + bud_args self.log.info("Building %s image with: %s" % (container_name, ' '.join(args))) process.execute( *args, check_exit_code=True, run_as_root=False, use_standard_locale=True ) @tenacity.retry( # Retry up to 10 times with jittered exponential backoff reraise=True, wait=tenacity.wait_random_exponential(multiplier=1, max=15), stop=tenacity.stop_after_attempt(10), before_sleep=tenacity.after_log(LOG, logging.WARNING) ) def push(self, destination): """Push an image to a container registry. :params destination: URL to used to push the container. It contains the registry address, namespace, base, img_type (optional), container name and tag. """ # TODO(emilien): Stop ignoring TLS. The deployer should either secure # the registry or add it to insecure_registries. # TODO(emilien) We need to figure out how we can push to something # else than a Docker registry. args = self.buildah_cmd + ['push', '--tls-verify=False', destination, 'docker://' + destination] self.log.info("Pushing %s image with: %s" % (destination, ' '.join(args))) if self.debug: # buildah push logs to stderr, since there is no --log* opt # so we'll use the current logging context for that process.execute(*args, log_stdout=True, run_as_root=False, use_standard_locale=True, logger=self.log, loglevel=logging.DEBUG) else: process.execute(*args, run_as_root=False, use_standard_locale=True) def build_all(self, deps=None): """Build all containers. This function will thread the build process allowing it to complete in the shortest possible time. :params deps: Dictionary defining the container images dependencies. """ if deps is None: deps = self.deps container_deps = self._generate_deps(deps=deps, containers=list()) self.log.debug("All container deps: {}".format(container_deps)) for containers in container_deps: self.log.info("Processing containers: {}".format(containers)) if isinstance(deps, (list,)): self._multi_build(containers=containers) else: self._multi_build(containers=[containers]) def _generate_deps(self, deps, containers, prio_list=None): """Browse containers dependencies and return an an array. When the dependencies are generated they're captured in an array, which contains additional arrays. This data structure is later used in a futures queue. :params deps: Dictionary defining the container images dependencies. :params containers: List used to keep track of dependent containers. :params prio_list: List used to keep track of nested dependencies. :returns: list """ self.log.debug("Process deps: {}".format(deps)) if isinstance(deps, str): if prio_list: prio_list.append(deps) else: containers.append([deps]) elif isinstance(deps, (dict,)): parents = list(deps.keys()) if prio_list: prio_list.extend(parents) else: containers.append(parents) for value in deps.values(): self.log.debug("Recursing with: {}".format(value)) self._generate_deps( deps=value, containers=containers ) elif isinstance(deps, (list,)): dep_list = list() dep_rehash_list = list() for item in deps: if isinstance(item, str): dep_list.append(item) else: dep_rehash_list.append(item) if dep_list: containers.append(dep_list) for item in dep_rehash_list: self.log.debug("Recursing with: {}".format(item)) self._generate_deps( deps=item, containers=containers, prio_list=dep_list ) self.log.debug("Constructed containers: {}".format(containers)) return containers def _multi_build(self, containers): """Build mutliple containers. Multi-thread the build process for all containers defined within the containers list. :params containers: List defining the container images. """ # Workers will use the processor core count with a max of 8. If # the containers array has a length less-than the expected processor # count, the workers will be adjusted to meet the expectations of the # work being processed. workers = min( min( 8, max( 2, processutils.get_worker_count() ) ), len(containers) ) with futures.ThreadPoolExecutor(max_workers=workers) as executor: future_to_build = { executor.submit( self._generate_container, container_name ): container_name for container_name in containers } done, not_done = futures.wait( future_to_build, timeout=self.build_timeout, return_when=futures.FIRST_EXCEPTION ) # NOTE(cloudnull): Once the job has been completed all completed # jobs are checked for exceptions. If any jobs # failed a SystemError will be raised using the # exception information. If any job was loaded # but not executed a SystemError will be raised. exceptions = list() for job in done: if job._exception: exceptions.append( "\nException information: {exception}".format( exception=job._exception ) ) if exceptions: raise RuntimeError( '\nThe following errors were detected during ' 'container build(s):\n{exceptions}'.format( exceptions='\n'.join(exceptions) ) ) if not_done: error_msg = ( 'The following jobs were incomplete: {}'.format( [future_to_build[job] for job in not_done] ) ) jobs_with_exceptions = [{ 'container': future_to_build[job], 'exception': job._exception} for job in not_done if job._exception] if jobs_with_exceptions: for job_with_exception in jobs_with_exceptions: error_msg = error_msg + os.linesep + ( "%(container)s raised the following " "exception: %(exception)s" % job_with_exception) raise SystemError(error_msg)
38.677083
78
0.588406
# Copyright 2019 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # from concurrent import futures import os import pathlib import tenacity from oslo_concurrency import processutils from oslo_config import cfg from oslo_log import log as logging from tripleo_common import constants from tripleo_common.image.builder import base from tripleo_common.utils import process CONF = cfg.CONF LOG = logging.getLogger(__name__ + ".BuildahBuilder") class BuildahBuilder(base.BaseBuilder): """Builder to build container images with Buildah.""" log = LOG def __init__(self, work_dir, deps, base='fedora', img_type='binary', tag='latest', namespace='master', registry_address='127.0.0.1:8787', push_containers=True, volumes=[], excludes=[], build_timeout=None, debug=False): """Setup the parameters to build with Buildah. :params work_dir: Directory where the Dockerfiles or Containerfiles are generated by Kolla. :params deps: Dictionary defining the container images dependencies. :params base: Base image on which the containers are built. Default to fedora. :params img_type: Method used to build the image. All TripleO images are built from binary method. Can be set to false to remove it from image name. :params tag: Tag used to identify the images that we build. Default to latest. :params namespace: Namespace used to build the containers. Default to master. :params registry_address: IP + port of the registry where we push the images. Default is 127.0.0.1:8787. :params push: Flag to bypass registry push if False. Default is True :params volumes: Bind mount volumes used during buildah bud. Default to []. :params excludes: List of images to skip. Default to []. :params build_timeout: Timeout. Default to constants.BUILD_TIMEOUT :params debug: Enable debug flag. Default to False. """ logging.register_options(CONF) if debug: CONF.debug = True logging.setup(CONF, '') super(BuildahBuilder, self).__init__() if build_timeout is None: self.build_timeout = constants.BUILD_TIMEOUT else: self.build_timeout = build_timeout self.work_dir = work_dir self.deps = deps self.base = base self.img_type = img_type self.tag = tag self.namespace = namespace self.registry_address = registry_address self.push_containers = push_containers self.volumes = volumes self.excludes = excludes self.debug = debug # Each container image has a Dockerfile or a Containerfile. # Buildah needs to know the base directory later. self.cont_map = {os.path.basename(root): root for root, dirs, fnames in os.walk(self.work_dir) if 'Dockerfile' in fnames or 'Containerfile' in fnames} # Building images with root so overlayfs is used, and not fuse-overlay # from userspace, which would be slower. self.buildah_cmd = ['sudo', 'buildah'] if self.debug: self.buildah_cmd.append('--log-level=debug') def _find_container_dir(self, container_name): """Return the path of the Dockerfile/Containerfile directory. :params container_name: Name of the container. """ if container_name not in self.cont_map: self.log.error('Container not found in Kolla ' 'deps: %s' % container_name) return self.cont_map.get(container_name, '') def _get_destination(self, container_name): """Return the destination of a container image to push. :params container_name: Name of the container. """ destination = "{}/{}/{}".format( self.registry_address, self.namespace, self.base, ) if self.img_type: destination += '-' + self.img_type destination += '-' + container_name + ':' + self.tag return destination def _generate_container(self, container_name): """Generate a container image by building and pushing the image. :params container_name: Name of the container. """ if container_name in self.excludes: return # NOTE(mwhahaha): Use a try catch block so we can better log issues # as this is called in a multiprocess fashion so the exception # loses some information when it reaches _multi_build try: self.build(container_name, self._find_container_dir(container_name)) if self.push_containers: self.push(self._get_destination(container_name)) except Exception as e: self.log.exception(e) raise @tenacity.retry( # Retry up to 5 times: 0, 1, 5, 21, 85 # http://exponentialbackoffcalculator.com/ reraise=True, wait=tenacity.wait_random_exponential(multiplier=4, max=60), stop=tenacity.stop_after_attempt(5), before_sleep=tenacity.after_log(LOG, logging.WARNING) ) def build(self, container_name, container_build_path): """Build an image from a given directory. :params container_name: Name of the container. :params container_build_path: Directory where the Dockerfile or Containerfile and other files are located to build the image. """ # 'buildah bud' is the command we want because Kolla uses Dockefile to # build images. # TODO(emilien): Stop ignoring TLS. The deployer should either secure # the registry or add it to insecure_registries. logfile = container_build_path + '/' + container_name + '-build.log' # TODO(ramishra) Hack to make the logfile readable by current user, # as we're running buildah as root. This would be removed once we # move to rootless buildah. pathlib.Path(logfile).touch() bud_args = ['bud'] for v in self.volumes: bud_args.extend(['--volume', v]) if self.debug: # TODO(bogdando): add --log-rusage for newer buildah bud_args.extend(['--loglevel=3']) # TODO(aschultz): drop --format docker when oci format is properly # supported by the undercloud registry bud_args.extend(['--format', 'docker', '--tls-verify=False', '--logfile', logfile, '-t', self._get_destination(container_name), container_build_path]) args = self.buildah_cmd + bud_args self.log.info("Building %s image with: %s" % (container_name, ' '.join(args))) process.execute( *args, check_exit_code=True, run_as_root=False, use_standard_locale=True ) @tenacity.retry( # Retry up to 10 times with jittered exponential backoff reraise=True, wait=tenacity.wait_random_exponential(multiplier=1, max=15), stop=tenacity.stop_after_attempt(10), before_sleep=tenacity.after_log(LOG, logging.WARNING) ) def push(self, destination): """Push an image to a container registry. :params destination: URL to used to push the container. It contains the registry address, namespace, base, img_type (optional), container name and tag. """ # TODO(emilien): Stop ignoring TLS. The deployer should either secure # the registry or add it to insecure_registries. # TODO(emilien) We need to figure out how we can push to something # else than a Docker registry. args = self.buildah_cmd + ['push', '--tls-verify=False', destination, 'docker://' + destination] self.log.info("Pushing %s image with: %s" % (destination, ' '.join(args))) if self.debug: # buildah push logs to stderr, since there is no --log* opt # so we'll use the current logging context for that process.execute(*args, log_stdout=True, run_as_root=False, use_standard_locale=True, logger=self.log, loglevel=logging.DEBUG) else: process.execute(*args, run_as_root=False, use_standard_locale=True) def build_all(self, deps=None): """Build all containers. This function will thread the build process allowing it to complete in the shortest possible time. :params deps: Dictionary defining the container images dependencies. """ if deps is None: deps = self.deps container_deps = self._generate_deps(deps=deps, containers=list()) self.log.debug("All container deps: {}".format(container_deps)) for containers in container_deps: self.log.info("Processing containers: {}".format(containers)) if isinstance(deps, (list,)): self._multi_build(containers=containers) else: self._multi_build(containers=[containers]) def _generate_deps(self, deps, containers, prio_list=None): """Browse containers dependencies and return an an array. When the dependencies are generated they're captured in an array, which contains additional arrays. This data structure is later used in a futures queue. :params deps: Dictionary defining the container images dependencies. :params containers: List used to keep track of dependent containers. :params prio_list: List used to keep track of nested dependencies. :returns: list """ self.log.debug("Process deps: {}".format(deps)) if isinstance(deps, str): if prio_list: prio_list.append(deps) else: containers.append([deps]) elif isinstance(deps, (dict,)): parents = list(deps.keys()) if prio_list: prio_list.extend(parents) else: containers.append(parents) for value in deps.values(): self.log.debug("Recursing with: {}".format(value)) self._generate_deps( deps=value, containers=containers ) elif isinstance(deps, (list,)): dep_list = list() dep_rehash_list = list() for item in deps: if isinstance(item, str): dep_list.append(item) else: dep_rehash_list.append(item) if dep_list: containers.append(dep_list) for item in dep_rehash_list: self.log.debug("Recursing with: {}".format(item)) self._generate_deps( deps=item, containers=containers, prio_list=dep_list ) self.log.debug("Constructed containers: {}".format(containers)) return containers def _multi_build(self, containers): """Build mutliple containers. Multi-thread the build process for all containers defined within the containers list. :params containers: List defining the container images. """ # Workers will use the processor core count with a max of 8. If # the containers array has a length less-than the expected processor # count, the workers will be adjusted to meet the expectations of the # work being processed. workers = min( min( 8, max( 2, processutils.get_worker_count() ) ), len(containers) ) with futures.ThreadPoolExecutor(max_workers=workers) as executor: future_to_build = { executor.submit( self._generate_container, container_name ): container_name for container_name in containers } done, not_done = futures.wait( future_to_build, timeout=self.build_timeout, return_when=futures.FIRST_EXCEPTION ) # NOTE(cloudnull): Once the job has been completed all completed # jobs are checked for exceptions. If any jobs # failed a SystemError will be raised using the # exception information. If any job was loaded # but not executed a SystemError will be raised. exceptions = list() for job in done: if job._exception: exceptions.append( "\nException information: {exception}".format( exception=job._exception ) ) if exceptions: raise RuntimeError( '\nThe following errors were detected during ' 'container build(s):\n{exceptions}'.format( exceptions='\n'.join(exceptions) ) ) if not_done: error_msg = ( 'The following jobs were incomplete: {}'.format( [future_to_build[job] for job in not_done] ) ) jobs_with_exceptions = [{ 'container': future_to_build[job], 'exception': job._exception} for job in not_done if job._exception] if jobs_with_exceptions: for job_with_exception in jobs_with_exceptions: error_msg = error_msg + os.linesep + ( "%(container)s raised the following " "exception: %(exception)s" % job_with_exception) raise SystemError(error_msg)
0
0
0
2510f4d75121878a4de9bf307f8d87dc38d3a446
4,976
py
Python
deep_phospho/proteomics_utils/gen_dp_lib.py
weizhenFrank/DeepPhospho
e720b867528d92f9a1a5ec840484989af2b8eb63
[ "MIT" ]
2
2021-11-25T01:06:18.000Z
2021-12-22T06:34:53.000Z
deep_phospho/proteomics_utils/gen_dp_lib.py
weizhenFrank/DeepPhospho
e720b867528d92f9a1a5ec840484989af2b8eb63
[ "MIT" ]
null
null
null
deep_phospho/proteomics_utils/gen_dp_lib.py
weizhenFrank/DeepPhospho
e720b867528d92f9a1a5ec840484989af2b8eb63
[ "MIT" ]
1
2021-04-26T03:00:48.000Z
2021-04-26T03:00:48.000Z
import os import re import json import pandas as pd from deep_phospho import proteomics_utils as prot_utils from deep_phospho.proteomics_utils.post_analysis import spectronaut as SN def generate_spec_lib( data_name, output_folder, pred_ion_path, pred_rt_path, min_frag_inten=5, min_frag_num=4, max_frag_num=15, allowed_extra_min_frag_inten=3, save_path=None, logger=None ): """ :param data_name: :param output_folder: :param pred_ion_path: :param pred_rt_path: :param min_frag_inten: min fragment intensity to be kept :param min_frag_num: min fragment number to keep this precursor :param max_frag_num: max fragment number to be kept for one precursor :param allowed_extra_min_frag_inten: :param save_path: :param logger: """ if logger is not None: logger.info(f'Reading predicted results for {data_name}') with open(pred_ion_path, 'r') as f: pred_ion = json.load(f) pred_rts = dict(pd.read_csv(pred_rt_path, sep='\t')[['sequence', 'pred']].values) pred_lib_rows = [] loss_num = 0 if logger is not None: logger.info(f'Start generating library for {data_name}') for intprec, pred_spec in pred_ion.items(): if 'U' in intprec or 'X' in intprec: continue intpep, prec_charge = intprec.split('.') modpep = SN.sn_utils.intseq_to_sn_modpep(intpep) strip_pep = re.sub(r'\[.+?\]', '', modpep.replace('_', '')) if intpep in pred_rts: pred_rt = pred_rts[intpep] else: loss_num += 1 continue prec = f'{modpep}.{prec_charge}' prec_mz = prot_utils.calc.calc_prec_mz(prec) prec_basic_data_list = [prec_charge, modpep, strip_pep, pred_rt, modpep, prec_mz] pred_spec = prot_utils.calc.normalize_intensity(pred_spec, max_num=100) pred_spec = prot_utils.calc.keep_top_n_inten(pred_spec, top_n=15) for frag, inten in pred_spec.items(): frag_type, frag_num, frag_charge, frag_losstype = re.findall(r'([abcxyz])(\d+)\+(\d)-(.+)', frag)[0] if int(frag_num) in (1, 2): continue if float(inten) <= 5: continue frag_mz = prot_utils.calc.calc_fragment_mz(modpep, frag_type, frag_num, frag_charge, frag_losstype) frag_losstype = SN.sn_constant.LossType.Readable_to_SN[frag_losstype] pred_lib_rows.append(prec_basic_data_list + [frag_losstype, frag_num, frag_type, frag_charge, frag_mz, inten]) pred_lib_df = pd.DataFrame(pred_lib_rows, columns=SN.SpectronautLibrary.LibBasicCols) pred_lib_df['Prec'] = pred_lib_df['ModifiedPeptide'] + '.' + pred_lib_df['PrecursorCharge'].astype(str) if logger is not None: logger.info(f'Total {len(set(pred_lib_df["Prec"]))} precursors in initial {data_name} library') pred_lib_df = pred_lib_df.groupby('Prec').filter(lambda x: len(x) >= 4) if logger is not None: logger.info(f'Total {len(set(pred_lib_df["Prec"]))} precursors in final {data_name} library') pred_lib_df = pred_lib_df[SN.SpectronautLibrary.LibBasicCols] if save_path is not None: lib_path = save_path else: lib_path = os.path.join(output_folder, f'Library-{data_name}-DP_I5_n{max_frag_num}.xls') if logger is not None: logger.info(f'Saving generated library to {lib_path}') pred_lib_df.to_csv(lib_path, sep='\t', index=False) return lib_path
37.69697
122
0.668006
import os import re import json import pandas as pd from deep_phospho import proteomics_utils as prot_utils from deep_phospho.proteomics_utils.post_analysis import spectronaut as SN def generate_spec_lib( data_name, output_folder, pred_ion_path, pred_rt_path, min_frag_inten=5, min_frag_num=4, max_frag_num=15, allowed_extra_min_frag_inten=3, save_path=None, logger=None ): """ :param data_name: :param output_folder: :param pred_ion_path: :param pred_rt_path: :param min_frag_inten: min fragment intensity to be kept :param min_frag_num: min fragment number to keep this precursor :param max_frag_num: max fragment number to be kept for one precursor :param allowed_extra_min_frag_inten: :param save_path: :param logger: """ if logger is not None: logger.info(f'Reading predicted results for {data_name}') with open(pred_ion_path, 'r') as f: pred_ion = json.load(f) pred_rts = dict(pd.read_csv(pred_rt_path, sep='\t')[['sequence', 'pred']].values) pred_lib_rows = [] loss_num = 0 if logger is not None: logger.info(f'Start generating library for {data_name}') for intprec, pred_spec in pred_ion.items(): if 'U' in intprec or 'X' in intprec: continue intpep, prec_charge = intprec.split('.') modpep = SN.sn_utils.intseq_to_sn_modpep(intpep) strip_pep = re.sub(r'\[.+?\]', '', modpep.replace('_', '')) if intpep in pred_rts: pred_rt = pred_rts[intpep] else: loss_num += 1 continue prec = f'{modpep}.{prec_charge}' prec_mz = prot_utils.calc.calc_prec_mz(prec) prec_basic_data_list = [prec_charge, modpep, strip_pep, pred_rt, modpep, prec_mz] pred_spec = prot_utils.calc.normalize_intensity(pred_spec, max_num=100) pred_spec = prot_utils.calc.keep_top_n_inten(pred_spec, top_n=15) for frag, inten in pred_spec.items(): frag_type, frag_num, frag_charge, frag_losstype = re.findall(r'([abcxyz])(\d+)\+(\d)-(.+)', frag)[0] if int(frag_num) in (1, 2): continue if float(inten) <= 5: continue frag_mz = prot_utils.calc.calc_fragment_mz(modpep, frag_type, frag_num, frag_charge, frag_losstype) frag_losstype = SN.sn_constant.LossType.Readable_to_SN[frag_losstype] pred_lib_rows.append(prec_basic_data_list + [frag_losstype, frag_num, frag_type, frag_charge, frag_mz, inten]) pred_lib_df = pd.DataFrame(pred_lib_rows, columns=SN.SpectronautLibrary.LibBasicCols) pred_lib_df['Prec'] = pred_lib_df['ModifiedPeptide'] + '.' + pred_lib_df['PrecursorCharge'].astype(str) if logger is not None: logger.info(f'Total {len(set(pred_lib_df["Prec"]))} precursors in initial {data_name} library') pred_lib_df = pred_lib_df.groupby('Prec').filter(lambda x: len(x) >= 4) if logger is not None: logger.info(f'Total {len(set(pred_lib_df["Prec"]))} precursors in final {data_name} library') pred_lib_df = pred_lib_df[SN.SpectronautLibrary.LibBasicCols] if save_path is not None: lib_path = save_path else: lib_path = os.path.join(output_folder, f'Library-{data_name}-DP_I5_n{max_frag_num}.xls') if logger is not None: logger.info(f'Saving generated library to {lib_path}') pred_lib_df.to_csv(lib_path, sep='\t', index=False) return lib_path def merge_lib(main_lib_path, add_libs_path, output_folder, task_name, save_path=None, logger=None): if logger is not None: logger.info(f'Loading main library {main_lib_path}') main_lib = SN.SpectronautLibrary(main_lib_path) main_lib.add_intpep() main_lib = main_lib.to_df() # TODO add_libs_path can be either list or dict for add_lib_name, add_lib_path in add_libs_path.items(): if logger is not None: logger.info(f'Loading additional library {add_lib_path}') add_lib = SN.SpectronautLibrary(add_lib_path) add_lib.retain_basic_cols() add_lib.add_intpep() add_lib = add_lib.to_df() added_peps = set(add_lib['IntPep']) - set(main_lib['IntPep']) add_lib = add_lib[add_lib['IntPep'].isin(added_peps)] add_lib['Prec'] = add_lib['ModifiedPeptide'] + '.' + add_lib['PrecursorCharge'].astype(str) add_lib = add_lib.groupby('Prec').filter(lambda x: len(x) >= 3) add_lib = add_lib[SN.SpectronautLibrary.LibBasicCols + ['IntPep']] main_lib = main_lib.append(add_lib) main_lib = main_lib[SN.SpectronautLibrary.LibBasicCols] if save_path is None: save_path = os.path.join(output_folder, f'HybridLibrary-{task_name}-DP_I5_n30.xls') if logger is not None: logger.info(f'Saving hybrid library {save_path}') main_lib.to_csv(save_path, sep='\t', index=False) return save_path
1,410
0
23
0371c9c42945a8e4ea127cc077ce2715110eed65
3,428
py
Python
old_src/showcontrol.py
cscashby/pi-showcontrol
2cc9b2b34ec8eeebede7609535b3c1e937b700cb
[ "MIT" ]
3
2017-05-07T18:13:09.000Z
2017-08-25T09:35:26.000Z
old_src/showcontrol.py
cscashby/pi-showcontrol
2cc9b2b34ec8eeebede7609535b3c1e937b700cb
[ "MIT" ]
6
2017-05-07T11:36:45.000Z
2017-07-31T15:30:20.000Z
old_src/showcontrol.py
cscashby/pi-showcontrol
2cc9b2b34ec8eeebede7609535b3c1e937b700cb
[ "MIT" ]
null
null
null
#!/usr/bin/python3 import time import signal import sys import os import threading import json import Adafruit_CharLCD as LCD import imp from pythonosc import osc_message_builder from pythonosc import udp_client from pythonosc import dispatcher from pythonosc import osc_server from config import * from lcd import * global keyThreads keyThreads = [] global importedModules importedModules = {} if __name__ == "__main__": setup() for serverName in config()['oscServers']: print("Starting OSC UDP server: {}".format(serverName)) start_server(serverName) start_keyThread(key_charLCD)
30.607143
97
0.703326
#!/usr/bin/python3 import time import signal import sys import os import threading import json import Adafruit_CharLCD as LCD import imp from pythonosc import osc_message_builder from pythonosc import udp_client from pythonosc import dispatcher from pythonosc import osc_server from config import * from lcd import * global keyThreads keyThreads = [] global importedModules importedModules = {} def send_osc(oscCommands): for server, m in oscCommands.items(): ip = config()['oscServers'][server]['ip'] port = config()['oscServers'][server]['port'] client = udp_client.SimpleUDPClient(ip, port) client.send_message(m, []) def get_cuename(): send_osc("/cue/selected/displayName") def start_server(serverName): listenIP = config()['settings']['listenIP'] listenPort = config()['oscServers'][serverName]['responsePort'] d = dispatcher.Dispatcher() for string, fn in config()['oscServers'][serverName]['responseCallback'].items(): d.map(string, get_function(fn)) global servers servers = {} print("Starting server on {}, port {}".format(listenIP, listenPort)) server = osc_server.ThreadingOSCUDPServer((listenIP, listenPort), d) servers[serverName] = server server_thread = threading.Thread(target=server.serve_forever) server_thread.start() def start_keyThread(function): global threads_running threads_running = True key_thread = threading.Thread(target=function) keyThreads.append(key_thread) key_thread.daemon = True key_thread.start() def setup(): # Configure signal handler for a clean exit def signal_handler(signal, frame): lcd().clear() lcd().set_color(0.0,0.0,0.0) for port, server in servers.items(): server.shutdown() global threads_running threads_running = False for t in keyThreads: t.join(1000) os._exit(0) signal.signal(signal.SIGINT, signal_handler) lcd_setText("Press play") # Import modules required for OSC responses # First import base module f, filename, description = imp.find_module("modules") module = imp.load_module("modules", f, filename, description) for imp_mod in config()['importModules']: try: f, filename, description = imp.find_module(imp_mod, [filename]) module = imp.load_module(imp_mod, f, filename, description) importedModules[imp_mod] = module print("Successfully loaded {} from {}".format(imp_mod, filename)) except ImportError as err: print("Could not import: {} error {}".format(imp_mod, err)) def key_charLCD(): print('Waiting for key press') while threads_running: for action in config()['keyActions']['charLCD']: if lcd().is_pressed(action['keyCode']): lcd().clear() lcd_setText(action['lcdMessage']) c = action['lcdColor'] lcd().set_color(c[0], c[1], c[2]) for oscAction in action['OSC']: send_osc(oscAction) for otherAction,args in action['Actions'].items(): get_function(otherAction)(*args) time.sleep(config()['settings']['debounceTime']) def get_function(fn): # TODO: Error check or make more generic - action has to be format: module.function at present a = fn.split(".") return getattr(importedModules[a[0]], a[1]) if __name__ == "__main__": setup() for serverName in config()['oscServers']: print("Starting OSC UDP server: {}".format(serverName)) start_server(serverName) start_keyThread(key_charLCD)
2,666
0
161
49e20921b4c92a181e06cb3bc780c2e8dc4816fd
7,648
py
Python
easytransfer/model_zoo/modeling_utils.py
mczhuge/Kaleido-BERT
50579660fb8dc1e250c7cc40e0f10294c54532e3
[ "MIT" ]
109
2021-04-14T04:15:53.000Z
2022-03-24T05:24:43.000Z
easytransfer/model_zoo/modeling_utils.py
NoLoPhe/Kaleido-BERT
1b14073e3ad3490c50bbd1e7e94846830671b332
[ "MIT" ]
12
2021-04-18T13:21:07.000Z
2022-01-27T09:42:51.000Z
easytransfer/model_zoo/modeling_utils.py
NoLoPhe/Kaleido-BERT
1b14073e3ad3490c50bbd1e7e94846830671b332
[ "MIT" ]
12
2021-04-25T08:40:09.000Z
2022-03-24T08:56:29.000Z
# coding=utf-8 # Copyright (c) 2019 Alibaba PAI team. # # 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 json import re import os import tensorflow as tf from tensorflow.python import pywrap_tensorflow from tensorflow.python.framework import errors_impl from tensorflow.python.platform import gfile from easytransfer.engines.model import FLAGS from easytransfer import layers
37.674877
116
0.63363
# coding=utf-8 # Copyright (c) 2019 Alibaba PAI team. # # 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 json import re import os import tensorflow as tf from tensorflow.python import pywrap_tensorflow from tensorflow.python.framework import errors_impl from tensorflow.python.platform import gfile from easytransfer.engines.model import FLAGS from easytransfer import layers class PretrainedConfig(object): def __init__(self, **kwargs): # Additional attributes without default values for key, value in kwargs.items(): try: setattr(self, key, value) except AttributeError as err: tf.logging.error("Can't set {} with value {} for {}".format(key, value, self)) raise err @classmethod def get(cls, json_file, **kwargs): config_dict = cls._dict_from_json_file(json_file) return cls.from_dict(config_dict, **kwargs) @classmethod def from_dict(cls, config_dict, **kwargs): config = cls(**config_dict) for key, value in kwargs.items(): setattr(config, key, value) return config @classmethod def _dict_from_json_file(cls, json_file): with gfile.GFile(json_file, mode='r') as reader: text = reader.read() return json.loads(text) class PreTrainedModel(layers.Layer): config_class = None pretrained_model_archive_map = {} pretrained_config_archive_map = {} @classmethod def dummy_inputs(self, seq_length): """ Dummy inputs to build the network. Returns: tf.Tensor with dummy inputs """ #input_ids = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]] input_ids = [[1]*seq_length] return tf.constant(input_ids) def __init__(self, config, **kwargs): kwargs.clear() super(PreTrainedModel, self).__init__(**kwargs) if not isinstance(config, PretrainedConfig): raise ValueError( "Parameter config in `{}(config)` should be an instance of class `PretrainedConfig`. " "To create a model from a pretrained model use " "`model = {}.from_pretrained(PRETRAINED_MODEL_NAME)`".format( self.__class__.__name__, self.__class__.__name__ ) ) # Save config in model self.config = config @classmethod def get(cls, pretrained_model_name_or_path, **kwargs): if pretrained_model_name_or_path in cls.pretrained_config_archive_map: config_path = cls.pretrained_config_archive_map[pretrained_model_name_or_path] config_path = os.path.join(FLAGS.modelZooBasePath, config_path) else: config_path = os.path.join(os.path.dirname(pretrained_model_name_or_path), "config.json") config = cls.config_class.get( config_path, **kwargs) model = cls(config, **kwargs) model(model.dummy_inputs(kwargs.get('input_sequence_length', 512)), mode='eval', output_features=False) archive_file = None if pretrained_model_name_or_path in cls.pretrained_model_archive_map: archive_file = cls.pretrained_model_archive_map[pretrained_model_name_or_path] archive_file = os.path.join(FLAGS.modelZooBasePath, archive_file) elif "/" in pretrained_model_name_or_path: archive_file = pretrained_model_name_or_path if tf.gfile.Exists(archive_file+".data-00000-of-00001"): model._init_from_pretrained_model(archive_file) else: tf.logging.info("archive file {} does not exists".format(archive_file)) tf.logging.info("ckpt {} not in model zoo, random initialization".format(pretrained_model_name_or_path)) return model def _init_from_pretrained_model(self, pretrained_model_path): tvars = tf.trainable_variables() network_name_to_variable = {} for var in tvars: name = var.name m = re.match("^(.*):\\d+$", name) if m is not None: name = m.group(1) network_name_to_variable[name] = var try: reader = pywrap_tensorflow.NewCheckpointReader(pretrained_model_path) var_to_shape_map = reader.get_variable_to_shape_map() except errors_impl.DataLossError: raise ImportError( '`load_weights` requires correct tf ckpts.') assignment_map = {} for key in var_to_shape_map: if "Adam" in key or "beta1_power" in key or "beta2_power" in key: continue if "global_step" in key: continue var = None if "pre_trained_model" in key: root_key = key.replace(key.split("/")[0]+"/","") else: root_key = key for network_key in network_name_to_variable.keys(): if root_key in network_key: var = network_name_to_variable[network_key] break if var is None: print("Variable: {} in ckpt not in trainable variable".format(key)) continue #raise ValueError("ckpt var name {} not in trainable variable".format(key)) assignment_map[key] = var tf.logging.info("Load key {} from {}".format(key, pretrained_model_path)) tf.logging.info("Load weights from {}".format(pretrained_model_path)) tf.train.init_from_checkpoint(pretrained_model_path, assignment_map) def init_from_checkpoint_without_training_ops(pretrained_model_path): tvars = tf.trainable_variables() network_name_to_variable = {} for var in tvars: name = var.name m = re.match("^(.*):\\d+$", name) if m is not None: name = m.group(1) network_name_to_variable[name] = var try: reader = pywrap_tensorflow.NewCheckpointReader(pretrained_model_path) var_to_shape_map = reader.get_variable_to_shape_map() except errors_impl.DataLossError: raise ImportError( '`load_weights` requires correct tf ckpts.') assignment_map = {} for key in var_to_shape_map: if "Adam" in key or "beta1_power" in key or "beta2_power" in key: continue if "global_step" in key: continue var = None if "pre_trained_model" in key: root_key = key.replace(key.split("/")[0]+"/","") else: root_key = key for network_key in network_name_to_variable.keys(): if root_key in network_key: var = network_name_to_variable[network_key] break if var is None: print("Variable: {} in ckpt not in trainable variable".format(key)) continue #raise ValueError("ckpt var name {} not in trainable variable".format(key)) assignment_map[key] = var tf.logging.info("Load weights from {}".format(pretrained_model_path)) tf.train.init_from_checkpoint(pretrained_model_path, assignment_map)
5,993
705
69
b9dc0df31309f5eb24cb2c055d9194cf73ff1aa4
13,013
py
Python
test/test_reward_estimation.py
BaiLiping/BLPtensorforce
01bc0b7130a497c9dfff9caa2fd5df919ffe7552
[ "Apache-2.0" ]
1
2021-12-25T16:54:16.000Z
2021-12-25T16:54:16.000Z
test/test_reward_estimation.py
BaiLiping/BLPtensorforce
01bc0b7130a497c9dfff9caa2fd5df919ffe7552
[ "Apache-2.0" ]
null
null
null
test/test_reward_estimation.py
BaiLiping/BLPtensorforce
01bc0b7130a497c9dfff9caa2fd5df919ffe7552
[ "Apache-2.0" ]
null
null
null
# Copyright 2020 Tensorforce Team. 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 from test.unittest_base import UnittestBase
47.148551
98
0.64474
# Copyright 2020 Tensorforce Team. 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 from test.unittest_base import UnittestBase class TestRewardEstimation(UnittestBase, unittest.TestCase): agent = dict( policy=dict(network=dict(type='auto', size=8, depth=1, rnn=2), distributions=dict( int_action2=dict(type='categorical', temperature_mode='predicted'), int_action3=dict(type='categorical', temperature_mode='global'), gaussian_action2=dict(type='gaussian', stddev_mode='global'), gaussian_action3=dict( type='gaussian', stddev_mode='global', bounded_transform='clipping' ), beta_action='beta' )), update=4, optimizer=dict(optimizer='adam', learning_rate=1e-3), objective='policy_gradient', reward_estimation=dict( horizon=3, estimate_advantage=True, predict_horizon_values='late', return_processing=dict(type='clipping', lower=-1.0, upper=1.0), advantage_processing='batch_normalization' ), l2_regularization=0.01, entropy_regularization=0.01, state_preprocessing='linear_normalization', reward_preprocessing=dict(type='clipping', lower=-1.0, upper=1.0), exploration=0.01, variable_noise=0.01, config=dict(device='CPU', eager_mode=True, create_debug_assertions=True, tf_log_level=20), tracking='all' ) def test_no_horizon_estimate(self): self.start_tests(name='no horizon estimate') # shortest horizon reward_estimation = dict( horizon=1, discount=0.99, predict_horizon_values=False, return_processing='batch_normalization' ) self.unittest(reward_estimation=reward_estimation) # horizon as long as episode reward_estimation = dict( horizon=10, discount=0.99, predict_horizon_values=False, return_processing='batch_normalization' ) self.unittest(reward_estimation=reward_estimation) # episode horizon reward_estimation = dict( horizon='episode', discount=0.99, predict_horizon_values=False, return_processing='batch_normalization' ) self.unittest(reward_estimation=reward_estimation) def test_early_horizon_estimate(self): self.start_tests(name='early horizon estimate') # TODO: action value doesn't exist for Beta actions = dict( bool_action=dict(type='bool', shape=(1,)), int_action1=dict(type='int', shape=(), num_values=4), int_action2=dict(type='int', shape=(2,), num_values=3), int_action3=dict(type='int', shape=(2, 1), num_values=2), gaussian_action1=dict(type='float', shape=(1, 2), min_value=1.0, max_value=2.0), gaussian_action2=dict(type='float', shape=(1,), min_value=-2.0, max_value=1.0) ) reward_estimation = dict( horizon='episode', predict_horizon_values='early', predict_action_values=True, return_processing='batch_normalization' ) # Implicit baseline = policy self.unittest(actions=actions, reward_estimation=reward_estimation, config=dict( buffer_observe=3, device='CPU', eager_mode=True, create_debug_assertions=True, tf_log_level=20 )) # TODO: action value doesn't exist for Beta actions = dict( bool_action=dict(type='bool', shape=(1,)), int_action1=dict(type='int', shape=(), num_values=4), int_action2=dict(type='int', shape=(2,), num_values=3), int_action3=dict(type='int', shape=(2, 1), num_values=2), gaussian_action1=dict(type='float', shape=(1, 2), min_value=1.0, max_value=2.0), gaussian_action2=dict(type='float', shape=(1,), min_value=-2.0, max_value=1.0) ) update = dict(unit='episodes', batch_size=1) reward_estimation = dict( horizon=3, predict_horizon_values='early', return_processing='batch_normalization' ) # Implicit baseline = policy baseline_optimizer = dict(optimizer='adam', learning_rate=1e-3) baseline_objective = 'state_value' self.unittest( actions=actions, update=update, reward_estimation=reward_estimation, baseline_optimizer=baseline_optimizer, baseline_objective=baseline_objective, config=dict( buffer_observe='episode', device='CPU', eager_mode=True, create_debug_assertions=True, tf_log_level=20 ) # or 1? ) reward_estimation = dict( horizon='episode', predict_horizon_values='early', predict_terminal_values=True, return_processing='batch_normalization' ) # TODO: baseline horizon has to be equal to policy horizon baseline = dict(network=dict(type='auto', size=7, depth=1, rnn=2)) # Implicit baseline_optimizer = 1.0 baseline_objective = 'state_value' self.unittest( reward_estimation=reward_estimation, baseline=baseline, baseline_objective=baseline_objective ) # Action-value baseline compatible with discrete actions actions = dict( bool_action=dict(type='bool', shape=(1,)), int_action1=dict(type='int', shape=(), num_values=4), int_action2=dict(type='int', shape=(2,), num_values=3), int_action3=dict(type='int', shape=(2, 1), num_values=2) ) reward_estimation = dict( horizon=3, predict_horizon_values='early', predict_action_values=True, predict_terminal_values=True, return_processing='batch_normalization' ) baseline = dict(network=dict(type='auto', size=7, depth=1, rnn=1)) baseline_optimizer = dict(optimizer='adam', learning_rate=1e-3) baseline_objective = 'action_value' self.unittest( actions=actions, reward_estimation=reward_estimation, baseline=baseline, baseline_optimizer=baseline_optimizer, baseline_objective=baseline_objective ) def test_late_horizon_estimate(self): self.start_tests(name='late horizon estimate') # TODO: action value doesn't exist for Beta actions = dict( bool_action=dict(type='bool', shape=(1,)), int_action1=dict(type='int', shape=(), num_values=4), int_action2=dict(type='int', shape=(2,), num_values=3), int_action3=dict(type='int', shape=(2, 1), num_values=2), gaussian_action1=dict(type='float', shape=(1, 2), min_value=1.0, max_value=2.0), gaussian_action2=dict(type='float', shape=(1,), min_value=-2.0, max_value=1.0) ) reward_estimation = dict( horizon=3, predict_horizon_values='late', return_processing='batch_normalization' ) # Implicit baseline = policy # Implicit baseline_optimizer = 1.0 baseline_objective = 'state_value' self.unittest( actions=actions, reward_estimation=reward_estimation, baseline_objective=baseline_objective ) # Action-value baseline compatible with discrete actions actions = dict( bool_action=dict(type='bool', shape=(1,)), int_action1=dict(type='int', shape=(), num_values=4), int_action2=dict(type='int', shape=(2,), num_values=3), int_action3=dict(type='int', shape=(2, 1), num_values=2) ) reward_estimation = dict( horizon=3, predict_horizon_values='late', predict_action_values=True, return_processing='batch_normalization' ) # TODO: baseline horizon has to be equal to policy horizon baseline = dict(network=dict(type='auto', size=7, depth=1, rnn=2)) baseline_optimizer = 2.0 baseline_objective = 'action_value' self.unittest( actions=actions, reward_estimation=reward_estimation, baseline=baseline, baseline_optimizer=baseline_optimizer, baseline_objective=baseline_objective ) # TODO: state value doesn't exist for Beta actions = dict( bool_action=dict(type='bool', shape=(1,)), int_action1=dict(type='int', shape=(), num_values=4), int_action2=dict(type='int', shape=(2,), num_values=3), int_action3=dict(type='int', shape=(2, 1), num_values=2), gaussian_action1=dict(type='float', shape=(1, 2), min_value=1.0, max_value=2.0), gaussian_action2=dict(type='float', shape=(1,), min_value=-2.0, max_value=1.0) ) reward_estimation = dict( horizon=3, predict_horizon_values='late', predict_terminal_values=True, return_processing='batch_normalization' ) # Implicit baseline = policy baseline_optimizer = dict(optimizer='adam', learning_rate=1e-3) baseline_objective = 'state_value' self.unittest( actions=actions, reward_estimation=reward_estimation, baseline_optimizer=baseline_optimizer, baseline_objective=baseline_objective ) reward_estimation = dict( horizon=3, predict_horizon_values='late', predict_action_values=True, predict_terminal_values=True, return_processing='batch_normalization' ) # TODO: baseline horizon has to be equal to policy horizon # (Not specifying customized distributions since action value doesn't exist for Beta) baseline = dict( type='parametrized_distributions', network=dict(type='auto', size=7, depth=1, rnn=2) ) baseline_optimizer = dict(optimizer='adam', learning_rate=1e-3) baseline_objective = 'action_value' self.unittest( reward_estimation=reward_estimation, baseline=baseline, baseline_optimizer=baseline_optimizer, baseline_objective=baseline_objective ) def test_advantage_estimate(self): self.start_tests(name='advantage estimate') reward_estimation = dict( horizon=3, estimate_advantage=True, predict_horizon_values=False, return_processing=dict(type='clipping', lower=-1.0, upper=1.0), advantage_processing='batch_normalization' ) # TODO: baseline horizon has to be equal to policy horizon baseline = dict(network=dict(type='auto', size=7, depth=1, rnn=2)) # Implicit advantage computation as part of loss self.unittest(reward_estimation=reward_estimation, baseline=baseline) # TODO: action value doesn't exist for Beta actions = dict( bool_action=dict(type='bool', shape=(1,)), int_action1=dict(type='int', shape=(), num_values=4), int_action2=dict(type='int', shape=(2,), num_values=3), int_action3=dict(type='int', shape=(2, 1), num_values=2), gaussian_action1=dict(type='float', shape=(1, 2), min_value=1.0, max_value=2.0), gaussian_action2=dict(type='float', shape=(1,), min_value=-2.0, max_value=1.0) ) reward_estimation = dict( horizon='episode', estimate_advantage=True, predict_horizon_values='early', predict_action_values=True, return_processing=dict(type='clipping', lower=-1.0, upper=1.0), advantage_processing='batch_normalization' ) # Implicit baseline = policy # Implicit baseline_optimizer = 1.0 baseline_objective = 'state_value' self.unittest( actions=actions, reward_estimation=reward_estimation, baseline_objective=baseline_objective ) reward_estimation = dict( horizon=3, estimate_advantage=True, predict_horizon_values='late', predict_terminal_values=True, return_processing=dict(type='clipping', lower=-1.0, upper=1.0), advantage_processing='batch_normalization' ) baseline = dict(network=dict(type='auto', size=7, depth=1, rnn=1)) baseline_optimizer = dict(optimizer='adam', learning_rate=1e-3) baseline_objective = 'state_value' self.unittest( reward_estimation=reward_estimation, baseline=baseline, baseline_optimizer=baseline_optimizer, baseline_objective=baseline_objective )
10,890
1,354
23
b60c408e7d5e29894ac397aff64595f1fd2bf711
2,254
py
Python
examples/11_bottles_of_beer/bottles.py
ktruong2004/be434-fall-2021
cad03aa7ce033fa3c813daf48dd9216976e1874b
[ "MIT" ]
null
null
null
examples/11_bottles_of_beer/bottles.py
ktruong2004/be434-fall-2021
cad03aa7ce033fa3c813daf48dd9216976e1874b
[ "MIT" ]
null
null
null
examples/11_bottles_of_beer/bottles.py
ktruong2004/be434-fall-2021
cad03aa7ce033fa3c813daf48dd9216976e1874b
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 """ Author : ktruong <ktruong@localhost> Date : 2021-10-25 Purpose: Rock the Casbah """ import argparse import sys # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Rock the Casbah', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-n', '--num', help='A named integer argument', metavar='int', type=int, default=10) args = parser.parse_args() if args.num < 1: sys.exit(f'--num "{args.num}" must be greater than 0') return args # -------------------------------------------------- def main(): """Make a jazz noise here""" args = get_args() # verses = [] # for number in range(args.num, 0, -1): # verses.append(verse(number)) # verses = [verse(n) for n in range(args.num, 0,-1)] verses = map(verse, range(args.num, 0, -1)) print('\n\n'.join(verses)) # -------------------------------------------------- def verse(bottle): """Number of the bottles""" next_bottle = bottle - 1 s1 = '' if bottle == 1 else 's' s2 = '' if next_bottle == 1 else 's' num_next = 'No more' if next_bottle == 0 else next_bottle return '\n'.join([ f'{bottle} bottle{s1} of beer on the wall,', f'{bottle} bottle{s1} of beer,', f'Take one down, pass it around,', f'{num_next} bottle{s2} of beer on the wall!', ]) # -------------------------------------------------- def test_verse(): """Test verse""" last_verse = verse(1) assert last_verse == '\n'.join([ '1 bottle of beer on the wall,', '1 bottle of beer,', 'Take one down, pass it around,', 'No more bottles of beer on the wall!' ]) two_bottles = verse(2) assert two_bottles == '\n'.join([ '2 bottles of beer on the wall,', '2 bottles of beer,', 'Take one down, pass it around,', '1 bottle of beer on the wall!' ]) # -------------------------------------------------- if __name__ == '__main__': main()
26.517647
73
0.484028
#!/usr/bin/env python3 """ Author : ktruong <ktruong@localhost> Date : 2021-10-25 Purpose: Rock the Casbah """ import argparse import sys # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Rock the Casbah', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-n', '--num', help='A named integer argument', metavar='int', type=int, default=10) args = parser.parse_args() if args.num < 1: sys.exit(f'--num "{args.num}" must be greater than 0') return args # -------------------------------------------------- def main(): """Make a jazz noise here""" args = get_args() # verses = [] # for number in range(args.num, 0, -1): # verses.append(verse(number)) # verses = [verse(n) for n in range(args.num, 0,-1)] verses = map(verse, range(args.num, 0, -1)) print('\n\n'.join(verses)) # -------------------------------------------------- def verse(bottle): """Number of the bottles""" next_bottle = bottle - 1 s1 = '' if bottle == 1 else 's' s2 = '' if next_bottle == 1 else 's' num_next = 'No more' if next_bottle == 0 else next_bottle return '\n'.join([ f'{bottle} bottle{s1} of beer on the wall,', f'{bottle} bottle{s1} of beer,', f'Take one down, pass it around,', f'{num_next} bottle{s2} of beer on the wall!', ]) # -------------------------------------------------- def test_verse(): """Test verse""" last_verse = verse(1) assert last_verse == '\n'.join([ '1 bottle of beer on the wall,', '1 bottle of beer,', 'Take one down, pass it around,', 'No more bottles of beer on the wall!' ]) two_bottles = verse(2) assert two_bottles == '\n'.join([ '2 bottles of beer on the wall,', '2 bottles of beer,', 'Take one down, pass it around,', '1 bottle of beer on the wall!' ]) # -------------------------------------------------- if __name__ == '__main__': main()
0
0
0
2e4db69ceefb49cf3e32158d2f245c9d399c644d
10,038
py
Python
app/vsm.py
Informationretrieval2016/furnito_webapp
e2a58918ebde33f9d7c52ed33445f6409d5da4d5
[ "Apache-2.0" ]
null
null
null
app/vsm.py
Informationretrieval2016/furnito_webapp
e2a58918ebde33f9d7c52ed33445f6409d5da4d5
[ "Apache-2.0" ]
null
null
null
app/vsm.py
Informationretrieval2016/furnito_webapp
e2a58918ebde33f9d7c52ed33445f6409d5da4d5
[ "Apache-2.0" ]
null
null
null
import string from invert_index import Invert_Index import config import json import numpy as np import pandas as pd import math from file_reader import File_Reader from file_writer import File_Writer
40.152
114
0.608687
import string from invert_index import Invert_Index import config import json import numpy as np import pandas as pd import math from file_reader import File_Reader from file_writer import File_Writer class VSM: def __init__(self): self.ii = Invert_Index() self.fr = File_Reader() self.fw = File_Writer() self.pl_path = config.posting_list_path self.pl = {} self.hash_dict = self.ii.posting_list() self.csv_path = config.vector_space_path #self.build_vector_space() def get_termid(self, query_list): ''' @usage: according user query, find term id from dictionary @arg query_list: list of user query @return: list of term id, example user query for [chair, desk], return [24, 45] ''' #step 1, find index of current user query term_id = [] for query in query_list: try: term_id.append(self.hash_dict.keys()[self.hash_dict.values().index(query)]) except: pass return term_id def get_docs(self, term_id): ''' @usage: according to query index, get related documents @arg: term_id, id of user query terms @return: dict of document location, {24: [doc1, doc5, doc7], 45: [doc8, dic11, doc22]} ''' with open(self.pl_path) as pl_file: self.pl = json.load(pl_file) term_location = {} for term in term_id: term_location[term] = self.pl[str(term)] return term_location def build_query_vector(self, term_id): ''' @usage: build query vector @arg term_id: list of terms id @return: pandas data frame 1 row * n columns ''' #build query vector #init a pandas data frame query_vector = pd.DataFrame(index = [1], columns = range(0, len(self.hash_dict))) query_vector = query_vector.fillna(0) for term in term_id: query_vector.xs(1, copy = False)[term_id] = 1 query_vector = np.array(map(list, query_vector.values)) return query_vector def build_vector_space(self): ''' @usage: build simple vector space model @arg term_location: dict of term id and term docs, for example {1: [doc1, doc3]} @arg term_id: list of term id ''' docs = self.fr.load_file_names() #init a dataframe, rows are docs, columns are terms df = pd.DataFrame(index = docs, columns = range(0, len(self.hash_dict))) df = df.fillna(0) for current_doc in docs: content = self.fr.read_file(current_doc) content = self.clean(content) #construct vector space for term in content.split(): #get term_id by term try: term_id = self.hash_dict.keys()[self.hash_dict.values().index(term)] #add current dataframe df.xs(current_doc, copy = False)[term_id] += 1 except: pass #insert a line into matrix indicate document frequency document_frequency = [] for i in range(0, len(self.hash_dict)): #if current term >=1 means current term appear in doc temp_df = list(df.ix[:,i] >= 1) document_frequency.append(sum(temp_df)) #write to dataframe df = pd.DataFrame(np.array([document_frequency]), columns = range(0, len(self.hash_dict))).append(df) df.to_csv(self.csv_path, sep = ',') def simple_vector_space(self, query_vector): ''' @usage: compute score of ranking use simple vector space @arg query_vector: vector of user query @return: dict of score ''' score_dict = {} term_id = self.get_termid(query_vector) term_location = self.get_docs(term_id) query_vector = self.build_query_vector(term_id) unique_locations = [] #get unique documents for k in term_location: unique_locations.extend(term_location[k]) unique_locations = list(set(unique_locations)) #get these lines from vector space df = pd.read_csv(self.csv_path, header = None, encoding = "utf-8", skiprows = 2) df = df.loc[df[0].isin(unique_locations)] for index, row in df.iterrows(): current_file = row[0] doc_vector = row[1:] doc_vector = np.array(doc_vector, dtype=pd.Series) score = np.sum(query_vector * doc_vector) score_dict[current_file] = score return score_dict def tfidf_vector_space(self, query_vector): ''' @usage: compute score according to tf-idf @arg query_vector: list of user query @return: dict of final score ''' score_dict = {} term_id = self.get_termid(query_vector) term_location = self.get_docs(term_id) query_vector = self.build_query_vector(term_id) unique_locations = [] for k in term_location: unique_locations.extend(term_location[k]) unique_locations = list(set(unique_locations)) document_frequency = [] #read df, first row is document frequency, other rows are term frequency df=pd.read_csv(self.csv_path, header = None, encoding="utf-8", skiprows=1) document_frequency = df.iloc[[0]] document_frequency = document_frequency.ix[:, document_frequency.columns!=0] document_frequency = np.array(map(list, document_frequency.values)) idf = self.idf(document_frequency) df=df.loc[df[0].isin(unique_locations)] for index, row in df.iterrows(): current_file = row[0] doc_vector = row[1:] doc_vector = np.array(doc_vector, pd.Series) doc_vector = doc_vector * idf score = np.sum(query_vector * doc_vector) score_dict[current_file] = score return score_dict def pln_vector_space(self, query_vector): ''' @usage: compute pivot-length-normalization vector score @arg query_vector: vector of user query @return: score ''' score_dict = {} term_id = self.get_termid(query_vector) term_location = self.get_docs(term_id) query_vector = self.build_query_vector(term_id) #init document length, for normalization doc length doc_length = self.fr.load_doc_length() avg_doc_length = sum(doc_length.values())/len(doc_length) #get doc locations unique_locations = [] for k in term_location: unique_locations.extend(term_location[k]) unique_locations = list(set(unique_locations)) #read vector space df = pd.read_csv(self.csv_path, header = None, encoding="utf-8", skiprows=1) document_frequency = df.iloc[[0]] document_frequency = document_frequency.ix[:, document_frequency.columns!=0] document_frequency = np.array(map(list, document_frequency.values)) idf = self.idf(document_frequency) df = df.loc[df[0].isin(unique_locations)] for index, row in df.iterrows(): current_file = row[0] doc_vector = row[1:].tolist() doc_vector = np.array(doc_vector) doc_term = (np.log10(1 + np.log10(1 + doc_vector)))/(doc_length[current_file]/avg_doc_length) score = np.sum(query_vector * (doc_term*idf)) if math.isnan(score): pass else: score_dict[current_file] = score return score_dict def bm25_vector_space(self, user_query): ''' @usage: use bm-25 model to build ranking system @arg user_query: list of user query @return: score ''' score_dict = {} term_id = self.get_termid(user_query) term_location = self.get_docs(term_id) query_vector = self.build_query_vector(term_id) doc_length = self.fr.load_doc_length() avg_doc_length = sum(doc_length.values())/len(doc_length) #find overlap between user query and vector space unique_location = [] for k in term_location: unique_location.extend(term_location[k]) unique_location = list(set(unique_location)) document_frequency = [] #load df df = pd.read_csv(self.csv_path, header = None, encoding = 'utf-8', skiprows=1) document_frequency = df.iloc[[0]] document_frequency = document_frequency.ix[:,document_frequency.columns!=0] document_frequency = np.array(map(list,document_frequency.values)) idf = self.idf(document_frequency) #filter df to files current user is retrieving df = df.loc[df[0].isin(unique_location)] for index, row in df.iterrows(): current_file = row[0] doc_vector = row[1:].tolist() doc_vector = np.array(doc_vector) doc_term = ((10+1)*doc_vector)/(doc_vector+10 * (1-0.5+0.5*(doc_length[current_file]/avg_doc_length))) score = np.sum(query_vector * (doc_term * idf)) score_dict[current_file] = score return score_dict def clean(self, content): ''' @usage: clean content, remove @arg content: content of document @return: cleaned content ''' punc = set(string.punctuation) content = ''.join([x for x in content if not x.isdigit()]) content = ''.join([x for x in content if x not in punc]) content = ''.join([x.lower() for x in content]) content = ' '.join(content.split()) return content def idf(self, document_frequency): ''' @usage: compute inverse document frequency @arg document_frequency: frequency of terms appear in document @return: score of idf ''' idf = np.log2(float(len(self.fr.load_file_names()) + 1)/document_frequency) return idf
296
9,518
23
5bf5d720c8028c2aa7e3bdee89a1800fa00452a8
2,081
py
Python
navegador.py
paulofv/tp-cliente-servidor
8b5d05ae888c983b5a39233a16fc93f3070e497f
[ "BSD-2-Clause" ]
null
null
null
navegador.py
paulofv/tp-cliente-servidor
8b5d05ae888c983b5a39233a16fc93f3070e497f
[ "BSD-2-Clause" ]
null
null
null
navegador.py
paulofv/tp-cliente-servidor
8b5d05ae888c983b5a39233a16fc93f3070e497f
[ "BSD-2-Clause" ]
null
null
null
#coding: utf-8 import sys import socket import os PORT = 80 #porta padrão caso usuário não especifique if len(sys.argv) == 1: # Verifica se o usuario passou pelo menos o parametro obrigatorio print "Nao foi informado a url no paramentro!\n" sys.exit() if len(sys.argv) == 3: # Verifica se o usuario especificou a porta PORT = int(sys.argv[2]) link = sys.argv[1].replace("https://", "").replace("http://", "") #remove http:// ou https:// do link HOST = link.split('/') #separar o host do resto da url HOST = HOST[0] socketnav = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #inicia o socket socketnav.connect((HOST, PORT)) print "Conectando a " + HOST + "\n\n" url = link.split('/') nomearq = '' if len(url) > 1: nomearq = url[len(url)-1] #recebe o nome do arquivo caso seja especificado del url[0] caminho = '' if type(url) == list: for i in url: caminho += '/' + i # monta o caminho para ser feita a requisicao else: caminho = '/' if len(nomearq) == 0: nomearq = "index.html" requisicao = 'GET '+ caminho + ' HTTP/1.0\r\nHost: ' + HOST + '\r\n\r\n' # monta requisicao socketnav.sendall(requisicao) # envia a requisicao pagina = '' while (True): rcv = socketnav.recv(4096) if not rcv: break pagina += rcv linhas = pagina.split('\n'); #separa o conteudo recebido em linhas i = 0 while(True): #separa o cabecalho da Cabeçalho HTTP do conteudo if len(linhas[i]) == 1: inicio = i + 1 break i += 1 salvar = True i = 0 print "Cabeçalho HTTP" #imprimindo o Cabeçalho HTTP na tela while(i < inicio): print(linhas[i]) i += 1 if "404" in linhas[i]: # se o arquivo nao existe nao salva salvar = False if salvar: dir = './' + HOST # pasta pra salvar o conteudo if not os.path.isdir(dir): # verifica se ja existe, se nao existe cria os.makedirs(dir) arqsaida = dir + '/' + nomearq arquivo_saida = open(arqsaida,"w") # criando arquivo de saida while (inicio < len(linhas)): # salvando o conteudo no arquivo arquivo_saida.write(linhas[inicio]) arquivo_saida.write("\n") inicio += 1 socketnav.close
23.382022
101
0.662662
#coding: utf-8 import sys import socket import os PORT = 80 #porta padrão caso usuário não especifique if len(sys.argv) == 1: # Verifica se o usuario passou pelo menos o parametro obrigatorio print "Nao foi informado a url no paramentro!\n" sys.exit() if len(sys.argv) == 3: # Verifica se o usuario especificou a porta PORT = int(sys.argv[2]) link = sys.argv[1].replace("https://", "").replace("http://", "") #remove http:// ou https:// do link HOST = link.split('/') #separar o host do resto da url HOST = HOST[0] socketnav = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #inicia o socket socketnav.connect((HOST, PORT)) print "Conectando a " + HOST + "\n\n" url = link.split('/') nomearq = '' if len(url) > 1: nomearq = url[len(url)-1] #recebe o nome do arquivo caso seja especificado del url[0] caminho = '' if type(url) == list: for i in url: caminho += '/' + i # monta o caminho para ser feita a requisicao else: caminho = '/' if len(nomearq) == 0: nomearq = "index.html" requisicao = 'GET '+ caminho + ' HTTP/1.0\r\nHost: ' + HOST + '\r\n\r\n' # monta requisicao socketnav.sendall(requisicao) # envia a requisicao pagina = '' while (True): rcv = socketnav.recv(4096) if not rcv: break pagina += rcv linhas = pagina.split('\n'); #separa o conteudo recebido em linhas i = 0 while(True): #separa o cabecalho da Cabeçalho HTTP do conteudo if len(linhas[i]) == 1: inicio = i + 1 break i += 1 salvar = True i = 0 print "Cabeçalho HTTP" #imprimindo o Cabeçalho HTTP na tela while(i < inicio): print(linhas[i]) i += 1 if "404" in linhas[i]: # se o arquivo nao existe nao salva salvar = False if salvar: dir = './' + HOST # pasta pra salvar o conteudo if not os.path.isdir(dir): # verifica se ja existe, se nao existe cria os.makedirs(dir) arqsaida = dir + '/' + nomearq arquivo_saida = open(arqsaida,"w") # criando arquivo de saida while (inicio < len(linhas)): # salvando o conteudo no arquivo arquivo_saida.write(linhas[inicio]) arquivo_saida.write("\n") inicio += 1 socketnav.close
0
0
0
ed35599c92749feb364e4b561ea3e5b68d3d86c6
456
py
Python
day6/height.py
dikshaa1702/ml
c35f279b8fa7544517ca713c2c1e55f08270d4c3
[ "Apache-2.0" ]
1
2019-06-13T13:52:09.000Z
2019-06-13T13:52:09.000Z
day6/height.py
dikshaa1702/ml
c35f279b8fa7544517ca713c2c1e55f08270d4c3
[ "Apache-2.0" ]
null
null
null
day6/height.py
dikshaa1702/ml
c35f279b8fa7544517ca713c2c1e55f08270d4c3
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Mon May 13 11:22:01 2019 @author: DiPu """ from functools import reduce people =[{'name': 'Mary', 'height': 160}, {'name': 'Isla', 'height': 80}, {'name': 'Sam'}] b=(list(filter(lambda x: True if 'height' in x else False,people))) g=list(map(lambda x:x['height'],b )) c=len((list(filter(lambda x: True if 'height' in x else False,people)))) d=reduce(lambda x,y:x+y,g) print("average height:",d/c)
30.4
72
0.609649
# -*- coding: utf-8 -*- """ Created on Mon May 13 11:22:01 2019 @author: DiPu """ from functools import reduce people =[{'name': 'Mary', 'height': 160}, {'name': 'Isla', 'height': 80}, {'name': 'Sam'}] b=(list(filter(lambda x: True if 'height' in x else False,people))) g=list(map(lambda x:x['height'],b )) c=len((list(filter(lambda x: True if 'height' in x else False,people)))) d=reduce(lambda x,y:x+y,g) print("average height:",d/c)
0
0
0
b9cf41cc30e8da1d9edf096602212846e3958cd2
3,858
py
Python
alan/abstract/questions.py
DotSlashCommunity/alan-server
1a933e4a6b40656cc2413d55a72b498d610f1bd7
[ "MIT" ]
null
null
null
alan/abstract/questions.py
DotSlashCommunity/alan-server
1a933e4a6b40656cc2413d55a72b498d610f1bd7
[ "MIT" ]
null
null
null
alan/abstract/questions.py
DotSlashCommunity/alan-server
1a933e4a6b40656cc2413d55a72b498d610f1bd7
[ "MIT" ]
null
null
null
# @author ksdme # abstracts methods on question model from random import shuffle from alan.db.models import ReplyModel def getQuestion(qno, qmodel): """ read a question from the given qmodel """ try: return qmodel.get(qmodel.id == qno) except qmodel.DoesNotExist: return None def getOffset(using, cycle=20): """ calculates the offset using a number 'using' subject """ val = int(using) val *= int(str(val)[0]) while val > cycle: using = map(int, str(val)) val = sum(using) return val def getOffsettedQuestion(roll, qno, qmodel, cycle=20): """ calculates the question that corrosponds to the databse entry """ # ensure the qno is in range if qno > cycle or qno < 1: return None return getQuestion( (((getOffset(roll, cycle) + qno)%cycle) + 1), qmodel) def shuffledAnswers(question): """ simply shuffles the ans and returns the list """ answers = [ question.opt_a, question.opt_b, question.opt_c, question.opt_d ] shuffle(answers) return answers def getQuestionStatus(roll, qno, rmodel, cycle=20): """ this here lets you know the current status of the question, i.e it has been answered or is editable etc, !!!you don't need offsetted qno!!! """ # ensure qno if qno > cycle or qno < 1: return None try: reply = rmodel.get(rmodel.roll == roll) return reply.replies[unicode(qno)] except rmodel.DoesNotExist: return None def isEditableQuestion(roll, qno, rmodel, cycle=20): """ check if the question is editable, i.e returns true if it was unanswered """ status = getQuestionStatus(roll, qno, rmodel, cycle) # ignore errors if status is None: return False # if it still is unanswered if status == ReplyModel.UNANSWERED: return True return False def getAllReplied(roll, rmodel): """ returns all those questions to which an answer has been submitted """ try: model = rmodel.get(rmodel.roll == roll) except rmodel.DoesNotExist: return { "e": True } # the questions that are empty qs = map(lambda l: l[0] if l[1] != -1 else None, model.replies.iteritems()) qs = filter(lambda l: l is not None, qs) return qs def verifyAnswer(question, answer): """ requires a question instance and the submitted answer, validates it """ return question.answer == answer def getPresentableQuestion(roll, qno, qmodel, rmodel, cycle=20): """ completely abstracts away the question selection and forming process, questions and options """ question = getOffsettedQuestion( roll, qno, qmodel, cycle) # ensure max if question is None: return { "e": True } return { "q": question.question, "o": shuffledAnswers(question), "l": not isEditableQuestion(roll, qno, rmodel, cycle) } def getPresentableSubmission(roll, qno, answer, qmodel, rmodel, rmodelgen, cycle=20): """ validates and lets you know if the submitted answer was right """ # check if we have an answer if answer is None or answer == "": return { "e": True, "m": "e" } # non-offset qno, now do it only if it is an editable one if not isEditableQuestion(roll, qno, rmodel, cycle): return { "e": True, "m": "l" } question = getOffsettedQuestion( roll, qno, qmodel, cycle) # if bad question no if question is None: return { "e": True } # verify the answer and do recording correct = verifyAnswer(question, answer) # this is the base thing that manages all try: player = rmodel.get(rmodel.roll == roll) except reply.DoesNotExist: return { "e": True, "m": "n" } # apparetly json loads # make the qno's unicode qno = unicode(qno) if player.replies[qno] == rmodelgen.UNANSWERED: player.replies[qno] = rmodelgen.CORRECT if correct else rmodelgen.WRONG player.save() return { "e": False } else: return { "e": True, "m": "l" } # let the guy know we # didn't get any error return { "e": True }
20.305263
85
0.681441
# @author ksdme # abstracts methods on question model from random import shuffle from alan.db.models import ReplyModel def getQuestion(qno, qmodel): """ read a question from the given qmodel """ try: return qmodel.get(qmodel.id == qno) except qmodel.DoesNotExist: return None def getOffset(using, cycle=20): """ calculates the offset using a number 'using' subject """ val = int(using) val *= int(str(val)[0]) while val > cycle: using = map(int, str(val)) val = sum(using) return val def getOffsettedQuestion(roll, qno, qmodel, cycle=20): """ calculates the question that corrosponds to the databse entry """ # ensure the qno is in range if qno > cycle or qno < 1: return None return getQuestion( (((getOffset(roll, cycle) + qno)%cycle) + 1), qmodel) def shuffledAnswers(question): """ simply shuffles the ans and returns the list """ answers = [ question.opt_a, question.opt_b, question.opt_c, question.opt_d ] shuffle(answers) return answers def getQuestionStatus(roll, qno, rmodel, cycle=20): """ this here lets you know the current status of the question, i.e it has been answered or is editable etc, !!!you don't need offsetted qno!!! """ # ensure qno if qno > cycle or qno < 1: return None try: reply = rmodel.get(rmodel.roll == roll) return reply.replies[unicode(qno)] except rmodel.DoesNotExist: return None def isEditableQuestion(roll, qno, rmodel, cycle=20): """ check if the question is editable, i.e returns true if it was unanswered """ status = getQuestionStatus(roll, qno, rmodel, cycle) # ignore errors if status is None: return False # if it still is unanswered if status == ReplyModel.UNANSWERED: return True return False def getAllReplied(roll, rmodel): """ returns all those questions to which an answer has been submitted """ try: model = rmodel.get(rmodel.roll == roll) except rmodel.DoesNotExist: return { "e": True } # the questions that are empty qs = map(lambda l: l[0] if l[1] != -1 else None, model.replies.iteritems()) qs = filter(lambda l: l is not None, qs) return qs def verifyAnswer(question, answer): """ requires a question instance and the submitted answer, validates it """ return question.answer == answer def getPresentableQuestion(roll, qno, qmodel, rmodel, cycle=20): """ completely abstracts away the question selection and forming process, questions and options """ question = getOffsettedQuestion( roll, qno, qmodel, cycle) # ensure max if question is None: return { "e": True } return { "q": question.question, "o": shuffledAnswers(question), "l": not isEditableQuestion(roll, qno, rmodel, cycle) } def getPresentableSubmission(roll, qno, answer, qmodel, rmodel, rmodelgen, cycle=20): """ validates and lets you know if the submitted answer was right """ # check if we have an answer if answer is None or answer == "": return { "e": True, "m": "e" } # non-offset qno, now do it only if it is an editable one if not isEditableQuestion(roll, qno, rmodel, cycle): return { "e": True, "m": "l" } question = getOffsettedQuestion( roll, qno, qmodel, cycle) # if bad question no if question is None: return { "e": True } # verify the answer and do recording correct = verifyAnswer(question, answer) # this is the base thing that manages all try: player = rmodel.get(rmodel.roll == roll) except reply.DoesNotExist: return { "e": True, "m": "n" } # apparetly json loads # make the qno's unicode qno = unicode(qno) if player.replies[qno] == rmodelgen.UNANSWERED: player.replies[qno] = rmodelgen.CORRECT if correct else rmodelgen.WRONG player.save() return { "e": False } else: return { "e": True, "m": "l" } # let the guy know we # didn't get any error return { "e": True }
0
0
0
6347be9abf7d48e5ad4f3a89677d852d3403a2d3
753
py
Python
coh2stats/weeklystats/routes.py
ZEDGR/coh2stats
0d6f0f0ca62a57c0644072727d90451f4e3b7a0e
[ "MIT" ]
1
2017-10-15T09:24:20.000Z
2017-10-15T09:24:20.000Z
coh2stats/weeklystats/routes.py
ZEDGR/coh2stats
0d6f0f0ca62a57c0644072727d90451f4e3b7a0e
[ "MIT" ]
1
2021-06-02T00:58:27.000Z
2021-06-02T00:58:27.000Z
coh2stats/weeklystats/routes.py
ZEDGR/coh2stats
0d6f0f0ca62a57c0644072727d90451f4e3b7a0e
[ "MIT" ]
null
null
null
from flask import render_template, Blueprint from coh2stats.weeklystats.utils import get_players_stats from coh2stats.weeklystats.utils import get_teams_stats from coh2stats import dao import os stats = Blueprint('stats', __name__) @stats.route('/weeklystats/1v1/latest') @stats.route('/weeklystats/teams/latest')
31.375
67
0.802125
from flask import render_template, Blueprint from coh2stats.weeklystats.utils import get_players_stats from coh2stats.weeklystats.utils import get_teams_stats from coh2stats import dao import os stats = Blueprint('stats', __name__) @stats.route('/weeklystats/1v1/latest') def weeklystats_1v1(): current_results, previous_results = dao.get_weeklystats_1v1() stats = get_players_stats(current_results, previous_results) return render_template('results_1v1.html', stats=stats) @stats.route('/weeklystats/teams/latest') def weeklystats_teams(): current_results, previous_results = dao.get_weeklystats_teams() stats = get_teams_stats(current_results, previous_results) return render_template('results_teams.html', stats=stats)
390
0
44
321d4d6311b8ff4c4a7b730f362f0523b1db2c8c
1,722
py
Python
5.py
mjenrungrot/AdventOfCode2020
ad2607fe6c4418327a97b863146f7a5af3361afe
[ "MIT" ]
null
null
null
5.py
mjenrungrot/AdventOfCode2020
ad2607fe6c4418327a97b863146f7a5af3361afe
[ "MIT" ]
null
null
null
5.py
mjenrungrot/AdventOfCode2020
ad2607fe6c4418327a97b863146f7a5af3361afe
[ "MIT" ]
null
null
null
import sys if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == 'extra': extra() else: main()
24.253521
79
0.47619
import sys def extra(): fp = open("5.input") lines = list(map(lambda x: (x.strip()[:7], x.strip()[7:]), fp.readlines())) occupied = set() max_seat_id = -1 for _, line in enumerate(lines): seat = line[0] seat = list(map(lambda ch: int(ch == 'B'), seat)) base = 64 row_no = 0 for _, ch in enumerate(seat): row_no += ch * base base //= 2 col = line[1] col = list(map(lambda ch: int(ch == 'R'), col)) base = 4 col_no = 0 for _, ch in enumerate(col): col_no += ch * base base //= 2 seat_id = row_no * 8 + col_no occupied.add(seat_id) max_seat_id = max(max_seat_id, seat_id) ans = -1 for i in range(max_seat_id): if i not in occupied and (i + 1) in occupied and (i - 1) in occupied: ans = i break print(ans) def main(): fp = open("5.input") lines = list(map(lambda x: (x.strip()[:7], x.strip()[7:]), fp.readlines())) ans = -1 for _, line in enumerate(lines): seat = line[0] seat = list(map(lambda ch: int(ch == 'B'), seat)) base = 64 row_no = 0 for _, ch in enumerate(seat): row_no += ch * base base //= 2 col = line[1] col = list(map(lambda ch: int(ch == 'R'), col)) base = 4 col_no = 0 for _, ch in enumerate(col): col_no += ch * base base //= 2 seat_id = row_no * 8 + col_no ans = max(ans, seat_id) print(ans) if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == 'extra': extra() else: main()
1,539
0
46