content
stringlengths
1
1.04M
input_ids
listlengths
1
774k
ratio_char_token
float64
0.38
22.9
token_count
int64
1
774k
import os import h5py import numpy as np import torch from torch.utils.data import Dataset
[ 11748, 28686, 198, 198, 11748, 289, 20, 9078, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 28034, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 16092, 292, 316, 628, 198 ]
3.133333
30
class DivideByZeroException(ArithmeticException): """ The exception that is thrown when there is an attempt to divide an integral or decimal value by zero. DivideByZeroException() DivideByZeroException(message: str) DivideByZeroException(message: str,innerException: Exception) """ def ZZZ(self): """hardcoded/mock instance of the class""" return DivideByZeroException() instance=ZZZ() """hardcoded/returns an instance of the class""" def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass @staticmethod def __new__(self,message=None,innerException=None): """ __new__(cls: type) __new__(cls: type,message: str) __new__(cls: type,message: str,innerException: Exception) __new__(cls: type,info: SerializationInfo,context: StreamingContext) """ pass SerializeObjectState=None
[ 4871, 46894, 3886, 28667, 16922, 7, 3163, 29848, 16922, 2599, 201, 198, 37227, 201, 198, 383, 6631, 326, 318, 8754, 618, 612, 318, 281, 2230, 284, 14083, 281, 19287, 393, 32465, 1988, 416, 6632, 13, 201, 201, 198, 220, 201, 201, 198, ...
3.014577
343
#!/usr/bin/env python # coding=utf-8 """ core.tenhou.log """ __author__ = 'Rnd495' import os import json import datetime import urllib from core.configs import Configs configs = Configs.instance() class Log(object): """ Log """ @property @property @property @property @property @property @property @property @property @property @property @property @property @property @staticmethod @staticmethod @staticmethod class StatisticForSubLog(object): """ StatisticForSubLog """ @property @property @property @property @property @property @property @property @property @property @property @property @property @property def get_results(ref_list, player_name): """ do statistics on given refs for given player result dict format (example value is avg value on data set 2015/05/15) : { fulu_chong : 0.3940, dama : 0.1165, win_time : 11.50, chong : 0.1347, win : 0.2484, win_point : 6690, ends_listening : 0.5170, fulu : 0.3717, after_richi : 0.0288, now_line_days : 3.71, max_line_days : 16.67, first_richi : 0.1597, count : 1000, } :param ref_list: ref list :param player_name: player name :return: result dict """ counter = {} adder = {} game_date_text_set = set() ref_counter = 0 for ref in ref_list: ref_counter += 1 log = Log(ref) game_date_text_set.add(log.time.strftime("%Y%m%d")) player_index = log.get_player_index(player_name) if player_index < 0: # should not be here continue for sub_log in log.sub_log: statistics = StatisticForSubLog(sub_log) results = statistics.get_result(player_index) for key, value in results.iteritems(): if value is not None: counter[key] = counter.get(key, 0) + 1 adder[key] = adder.get(key, 0) + value results = {} for key, value in counter.iteritems(): results[key] = (adder[key] / float(value)) if value else 0 max_line_days = now_line_days = 0 last_date = None for date_text in sorted(game_date_text_set): now_date = datetime.datetime.strptime(date_text, "%Y%m%d") if last_date: if int((now_date - last_date).days) <= 1: now_line_days += 1 max_line_days = max(max_line_days, now_line_days) else: now_line_days = 1 last_date = now_date results['max_line_days'] = max_line_days results['now_line_days'] = now_line_days results['count'] = ref_counter return results if __name__ == '__main__': import time from sqlalchemy import func, desc from core.models import get_new_session, PlayerLog session = get_new_session() counter = func.count(PlayerLog.name) query = session.query(PlayerLog.name).filter((PlayerLog.lobby == '0000') & (PlayerLog.name != 'NoName')) \ .group_by(PlayerLog.name).having(counter >= 50).order_by(desc(counter)) results = {} for name in (row[0] for row in query): start_time = time.time() query = session.query(PlayerLog.ref).filter((PlayerLog.name == name) & (PlayerLog.lobby == '0000')) refs = [row[0] for row in query] results[name] = get_results(refs, name) size = len(refs) time_cost = time.time() - start_time hz = size / time_cost print '%6d' % size, '%.2fs' % time_cost, '%.2fHz' % hz, name session.close() data_lists = {} for row in results.itervalues(): for key, value in row.iteritems(): data_lists.setdefault(key, []).append(value) print '' print '%20s' % 'type', '%6s' % 'avg', '%6s' % 'max', '%6s' % 'min', '%6s' % 'mu' # import numpy as np from scipy.stats import norm # import matplotlib.pyplot as plt for key, data_list in data_lists.iteritems(): avg = sum(data_list) / float(len(data_list)) mu, std = norm.fit(data_list) print '%20s' % key, format_data(avg), format_data(max(data_list)), format_data(min(data_list)), format_data( mu), std # # # Plot the histogram. # plt.hist(data_list, bins=25, normed=True, alpha=0.6, color='g') # # # Plot the PDF. # xmin, xmax = plt.xlim() # x = np.linspace(xmin, xmax, 100) # p = norm.pdf(x, mu, std) # plt.plot(x, p, 'k', linewidth=2) # title = "%s fit results: mu = %.2f, std = %.2f" % (key, mu, std) # plt.title(title) # # plt.show()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 28, 40477, 12, 23, 198, 198, 37811, 198, 7295, 13, 1452, 15710, 13, 6404, 198, 37811, 198, 198, 834, 9800, 834, 796, 705, 49, 358, 33781, 6, 198, 198, 11748, 28686, 198, ...
2.122761
2,289
import pytest from eth_abi import decode_single from eth_tester.exceptions import TransactionFailed # web3 returns f"execution reverted: {err_str}" # TODO move exception string parsing logic into assert_tx_failed invalid_code = [ """ @external def test(a: int128) -> int128: assert a > 1, "" return 1 + a """, """ @external def test(a: int128) -> int128: raise "" """, """ @external def test(): assert create_forwarder_to(self) """, ] @pytest.mark.parametrize("code", invalid_code) valid_code = [ """ @external def mint(_to: address, _value: uint256): raise """, """ @internal def ret1() -> int128: return 1 @external def test(): assert self.ret1() == 1 """, """ @internal def valid_address(sender: address) -> bool: selfdestruct(sender) @external def test(): assert self.valid_address(msg.sender) """, """ @external def test(): assert raw_call(msg.sender, b'', max_outsize=1, gas=10, value=1000*1000) == b'' """, """ @external def test(): assert create_forwarder_to(self) == self """, ] @pytest.mark.parametrize("code", valid_code)
[ 11748, 12972, 9288, 198, 6738, 4555, 62, 17914, 1330, 36899, 62, 29762, 198, 6738, 4555, 62, 4879, 353, 13, 1069, 11755, 1330, 45389, 37, 6255, 628, 198, 2, 3992, 18, 5860, 277, 1, 18558, 1009, 50239, 25, 1391, 8056, 62, 2536, 36786, ...
2.520697
459
#!/usr/bin/python # -*- coding: utf-8; -*- # # 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. # # @author: Eduardo S. Scarpellini # @author: Luiz Ozaki __copyright__ = "Copyright 2012, Locaweb IDC" from netl2api.l2api.exceptions import * from netl2api.l2api.autocache import L2APIAutoCache from netl2api.l2api.transport import SysSSHTransport #, TransportManager __all__ = ["L2API"] class L2API(L2APIAutoCache): """ Base class for L2 operations. Vendor-specific classes should extend this, declare 'self.__VENDOR__' (vendor str), 'self.__HWTYPE__' (hardware type str), 'self.prompt_mark', 'self.error_mark' and 'self.config_term_cmd' (see transport classes for understand these three last parameters). Ex.: class ExampleVendorAPI(L2API): def __init__(self, *args, **kwargs): self.__VENDOR__ = "ExampleVendor" self.__HWTYPE__ = "stackable_switch" self.prompt_mark = "#" self.error_mark = "% Error:" self.config_term_cmd = "terminal length 0" super(ExampleVendorAPI, self).__init__(*args, **kwargs) ... def show_version(self): ... def show_interfaces(self): .... """ # def __del__(self): # if self.transport is not None: # try: # self.transport.close() # except Exception: # pass
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 26, 532, 9, 12, 198, 2, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, ...
2.441574
813
# # This file is part of the PyMeasure package. # # Copyright (c) 2013-2022 PyMeasure Developers # # 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. # from pymeasure.instruments import Instrument from pymeasure.instruments.validators import truncated_range, strict_discrete_set class Agilent8257D(Instrument): """Represents the Agilent 8257D Signal Generator and provides a high-level interface for interacting with the instrument. .. code-block:: python generator = Agilent8257D("GPIB::1") generator.power = 0 # Sets the output power to 0 dBm generator.frequency = 5 # Sets the output frequency to 5 GHz generator.enable() # Enables the output """ power = Instrument.control( ":POW?;", ":POW %g dBm;", """ A floating point property that represents the output power in dBm. This property can be set. """ ) frequency = Instrument.control( ":FREQ?;", ":FREQ %e Hz;", """ A floating point property that represents the output frequency in Hz. This property can be set. """ ) start_frequency = Instrument.control( ":SOUR:FREQ:STAR?", ":SOUR:FREQ:STAR %e Hz", """ A floating point property that represents the start frequency in Hz. This property can be set. """ ) center_frequency = Instrument.control( ":SOUR:FREQ:CENT?", ":SOUR:FREQ:CENT %e Hz;", """ A floating point property that represents the center frequency in Hz. This property can be set. """ ) stop_frequency = Instrument.control( ":SOUR:FREQ:STOP?", ":SOUR:FREQ:STOP %e Hz", """ A floating point property that represents the stop frequency in Hz. This property can be set. """ ) start_power = Instrument.control( ":SOUR:POW:STAR?", ":SOUR:POW:STAR %e dBm", """ A floating point property that represents the start power in dBm. This property can be set. """ ) stop_power = Instrument.control( ":SOUR:POW:STOP?", ":SOUR:POW:STOP %e dBm", """ A floating point property that represents the stop power in dBm. This property can be set. """ ) dwell_time = Instrument.control( ":SOUR:SWE:DWEL1?", ":SOUR:SWE:DWEL1 %.3f", """ A floating point property that represents the settling time in seconds at the current frequency or power setting. This property can be set. """ ) step_points = Instrument.control( ":SOUR:SWE:POIN?", ":SOUR:SWE:POIN %d", """ An integer number of points in a step sweep. This property can be set. """ ) is_enabled = Instrument.measurement( ":OUTPUT?", """ Reads a boolean value that is True if the output is on. """, cast=bool ) has_modulation = Instrument.measurement( ":OUTPUT:MOD?", """ Reads a boolean value that is True if the modulation is enabled. """, cast=bool ) ######################## # Amplitude modulation # ######################## has_amplitude_modulation = Instrument.measurement( ":SOUR:AM:STAT?", """ Reads a boolean value that is True if the amplitude modulation is enabled. """, cast=bool ) amplitude_depth = Instrument.control( ":SOUR:AM:DEPT?", ":SOUR:AM:DEPT %g", """ A floating point property that controls the amplitude modulation in precent, which can take values from 0 to 100 %. """, validator=truncated_range, values=[0, 100] ) AMPLITUDE_SOURCES = { 'internal': 'INT', 'internal 2': 'INT2', 'external': 'EXT', 'external 2': 'EXT2' } amplitude_source = Instrument.control( ":SOUR:AM:SOUR?", ":SOUR:AM:SOUR %s", """ A string property that controls the source of the amplitude modulation signal, which can take the values: 'internal', 'internal 2', 'external', and 'external 2'. """, validator=strict_discrete_set, values=AMPLITUDE_SOURCES, map_values=True ) #################### # Pulse modulation # #################### has_pulse_modulation = Instrument.measurement( ":SOUR:PULM:STAT?", """ Reads a boolean value that is True if the pulse modulation is enabled. """, cast=bool ) PULSE_SOURCES = { 'internal': 'INT', 'external': 'EXT', 'scalar': 'SCAL' } pulse_source = Instrument.control( ":SOUR:PULM:SOUR?", ":SOUR:PULM:SOUR %s", """ A string property that controls the source of the pulse modulation signal, which can take the values: 'internal', 'external', and 'scalar'. """, validator=strict_discrete_set, values=PULSE_SOURCES, map_values=True ) PULSE_INPUTS = { 'square': 'SQU', 'free-run': 'FRUN', 'triggered': 'TRIG', 'doublet': 'DOUB', 'gated': 'GATE' } pulse_input = Instrument.control( ":SOUR:PULM:SOUR:INT?", ":SOUR:PULM:SOUR:INT %s", """ A string property that controls the internally generated modulation input for the pulse modulation, which can take the values: 'square', 'free-run', 'triggered', 'doublet', and 'gated'. """, validator=strict_discrete_set, values=PULSE_INPUTS, map_values=True ) pulse_frequency = Instrument.control( ":SOUR:PULM:INT:FREQ?", ":SOUR:PULM:INT:FREQ %g", """ A floating point property that controls the pulse rate frequency in Hertz, which can take values from 0.1 Hz to 10 MHz. """, validator=truncated_range, values=[0.1, 10e6] ) ######################## # Low-Frequency Output # ######################## low_freq_out_amplitude = Instrument.control( ":SOUR:LFO:AMPL? ", ":SOUR:LFO:AMPL %g VP", """A floating point property that controls the peak voltage (amplitude) of the low frequency output in volts, which can take values from 0-3.5V""", validator=truncated_range, values=[0, 3.5] ) LOW_FREQUENCY_SOURCES = { 'internal': 'INT', 'internal 2': 'INT2', 'function': 'FUNC', 'function 2': 'FUNC2' } low_freq_out_source = Instrument.control( ":SOUR:LFO:SOUR?", ":SOUR:LFO:SOUR %s", """A string property which controls the source of the low frequency output, which can take the values 'internal [2]' for the inernal source, or 'function [2]' for an internal function generator which can be configured.""", validator=strict_discrete_set, values=LOW_FREQUENCY_SOURCES, map_values=True ) def enable_low_freq_out(self): """Enables low frequency output""" self.write(":SOUR:LFO:STAT ON") def disable_low_freq_out(self): """Disables low frequency output""" self.write(":SOUR:LFO:STAT OFF") def config_low_freq_out(self, source='internal', amplitude=3): """ Configures the low-frequency output signal. :param source: The source for the low-frequency output signal. :param amplitude: Amplitude of the low-frequency output """ self.enable_low_freq_out() self.low_freq_out_source = source self.low_freq_out_amplitude = amplitude ####################### # Internal Oscillator # ####################### internal_frequency = Instrument.control( ":SOUR:AM:INT:FREQ?", ":SOUR:AM:INT:FREQ %g", """ A floating point property that controls the frequency of the internal oscillator in Hertz, which can take values from 0.5 Hz to 1 MHz. """, validator=truncated_range, values=[0.5, 1e6] ) INTERNAL_SHAPES = { 'sine': 'SINE', 'triangle': 'TRI', 'square': 'SQU', 'ramp': 'RAMP', 'noise': 'NOIS', 'dual-sine': 'DUAL', 'swept-sine': 'SWEP' } internal_shape = Instrument.control( ":SOUR:AM:INT:FUNC:SHAP?", ":SOUR:AM:INT:FUNC:SHAP %s", """ A string property that controls the shape of the internal oscillations, which can take the values: 'sine', 'triangle', 'square', 'ramp', 'noise', 'dual-sine', and 'swept-sine'. """, validator=strict_discrete_set, values=INTERNAL_SHAPES, map_values=True ) def enable(self): """ Enables the output of the signal. """ self.write(":OUTPUT ON;") def disable(self): """ Disables the output of the signal. """ self.write(":OUTPUT OFF;") def disable_modulation(self): """ Disables the signal modulation. """ self.write(":OUTPUT:MOD OFF;") self.write(":lfo:stat off;") def config_amplitude_modulation(self, frequency=1e3, depth=100.0, shape='sine'): """ Configures the amplitude modulation of the output signal. :param frequency: A modulation frequency for the internal oscillator :param depth: A linear depth precentage :param shape: A string that describes the shape for the internal oscillator """ self.enable_amplitude_modulation() self.amplitude_source = 'internal' self.internal_frequency = frequency self.internal_shape = shape self.amplitude_depth = depth def enable_amplitude_modulation(self): """ Enables amplitude modulation of the output signal. """ self.write(":SOUR:AM:STAT ON") def disable_amplitude_modulation(self): """ Disables amplitude modulation of the output signal. """ self.write(":SOUR:AM:STAT OFF") def config_pulse_modulation(self, frequency=1e3, input='square'): """ Configures the pulse modulation of the output signal. :param frequency: A pulse rate frequency in Hertz :param input: A string that describes the internal pulse input """ self.enable_pulse_modulation() self.pulse_source = 'internal' self.pulse_input = input self.pulse_frequency = frequency def enable_pulse_modulation(self): """ Enables pulse modulation of the output signal. """ self.write(":SOUR:PULM:STAT ON") def disable_pulse_modulation(self): """ Disables pulse modulation of the output signal. """ self.write(":SOUR:PULM:STAT OFF") def config_step_sweep(self): """ Configures a step sweep through frequency """ self.write(":SOUR:FREQ:MODE SWE;" ":SOUR:SWE:GEN STEP;" ":SOUR:SWE:MODE AUTO;") def start_step_sweep(self): """ Starts a step sweep. """ self.write(":SOUR:SWE:CONT:STAT ON") def stop_step_sweep(self): """ Stops a step sweep. """ self.write(":SOUR:SWE:CONT:STAT OFF") def shutdown(self): """ Shuts down the instrument by disabling any modulation and the output signal. """ self.disable_modulation() self.disable()
[ 2, 198, 2, 770, 2393, 318, 636, 286, 262, 9485, 47384, 5301, 13, 198, 2, 198, 2, 15069, 357, 66, 8, 2211, 12, 1238, 1828, 9485, 47384, 34152, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048,...
2.482474
4,850
# -*- coding: utf-8 -*- # # Copyright 2020 Google LLC. 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. """S3 API-specific resource subclasses.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import collections from googlecloudsdk.api_lib.storage import errors from googlecloudsdk.command_lib.storage.resources import resource_reference from googlecloudsdk.command_lib.storage.resources import resource_util _INCOMPLETE_OBJECT_METADATA_WARNING = ( 'Use "-j", the JSON flag, to view additional S3 metadata.') def _json_dump_recursion_helper(metadata): """See _get_json_dump docstring.""" if isinstance(metadata, list): return [_json_dump_recursion_helper(item) for item in metadata] if not isinstance(metadata, dict): return resource_util.convert_to_json_parsable_type(metadata) # Sort by key to make sure dictionary always prints in correct order. formatted_dict = collections.OrderedDict(sorted(metadata.items())) for key, value in formatted_dict.items(): if isinstance(value, dict): # Recursively handle dictionaries. formatted_dict[key] = _json_dump_recursion_helper(value) elif isinstance(value, list): # Recursively handled lists, which may contain more dicts, like ACLs. formatted_list = [_json_dump_recursion_helper(item) for item in value] if formatted_list: # Ignore empty lists. formatted_dict[key] = formatted_list elif value or resource_util.should_preserve_falsy_metadata_value(value): formatted_dict[key] = resource_util.convert_to_json_parsable_type(value) return formatted_dict def _get_json_dump(resource): """Formats S3 resource metadata as JSON. Args: resource (S3BucketResource|S3ObjectResource): Resource object. Returns: Formatted JSON string. """ return resource_util.configured_json_dumps( collections.OrderedDict([ ('url', resource.storage_url.url_string), ('type', resource.TYPE_STRING), ('metadata', _json_dump_recursion_helper(resource.metadata)), ])) def _get_error_or_exists_string(value): """Returns error if value is error or existence string.""" if isinstance(value, errors.S3ApiError): return value else: return resource_util.get_exists_string(value) def _get_formatted_acl_section(acl_metadata): """Returns formatted ACLs, error, or formatted none value.""" if isinstance(acl_metadata, errors.S3ApiError): return resource_util.get_padded_metadata_key_value_line('ACL', acl_metadata) elif acl_metadata: return resource_util.get_metadata_json_section_string( 'ACL', acl_metadata, _json_dump_recursion_helper) else: return resource_util.get_padded_metadata_key_value_line('ACL', '[]') def _get_full_bucket_metadata_string(resource): """Formats S3 resource metadata as string with rows. Args: resource (S3BucketResource): Resource with metadata. Returns: Formatted multi-line string. """ # Hardcoded strings found in Boto docs: # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html logging_enabled_value = _get_error_or_exists_string( resource.metadata['LoggingEnabled']) website_value = _get_error_or_exists_string(resource.metadata['Website']) cors_value = _get_error_or_exists_string(resource.metadata['CORSRules']) encryption_value = _get_error_or_exists_string( resource.metadata['ServerSideEncryptionConfiguration']) lifecycle_configuration_value = _get_error_or_exists_string( resource.metadata['LifecycleConfiguration']) if isinstance(resource.metadata['Versioning'], errors.S3ApiError): versioning_enabled_value = resource.metadata['Versioning'] else: versioning_status = resource.metadata['Versioning'].get('Status') if versioning_status == 'Enabled': versioning_enabled_value = True elif versioning_status == 'Suspended': versioning_enabled_value = False else: versioning_enabled_value = None if isinstance(resource.metadata['Payer'], errors.S3ApiError): requester_pays_value = resource.metadata['Payer'] elif resource.metadata['Payer'] == 'Requester': requester_pays_value = True elif resource.metadata['Payer'] == 'BucketOwner': requester_pays_value = False else: requester_pays_value = None return ( '{bucket_url}:\n' '{location_constraint_line}' '{versioning_enabled_line}' '{logging_config_line}' '{website_config_line}' '{cors_config_line}' '{encryption_config_line}' '{lifecycle_config_line}' '{requester_pays_line}' '{acl_section}' ).format( bucket_url=resource.storage_url.versionless_url_string, location_constraint_line=resource_util.get_padded_metadata_key_value_line( 'Location Constraint', resource.metadata['LocationConstraint']), versioning_enabled_line=resource_util.get_padded_metadata_key_value_line( 'Versioning Enabled', versioning_enabled_value), logging_config_line=resource_util.get_padded_metadata_key_value_line( 'Logging Configuration', logging_enabled_value), website_config_line=resource_util.get_padded_metadata_key_value_line( 'Website Configuration', website_value), cors_config_line=resource_util.get_padded_metadata_key_value_line( 'CORS Configuration', cors_value), encryption_config_line=resource_util.get_padded_metadata_key_value_line( 'Encryption Configuration', encryption_value), lifecycle_config_line=resource_util.get_padded_metadata_key_value_line( 'Lifecycle Configuration', lifecycle_configuration_value), requester_pays_line=resource_util.get_padded_metadata_key_value_line( 'Requester Pays Enabled', requester_pays_value), # Remove ending newline character because this is the last list item. acl_section=_get_formatted_acl_section(resource.metadata['ACL'])[:-1]) def _get_full_object_metadata_string(resource): """Formats S3 resource metadata as string with rows. Args: resource (S3ObjectResource): Resource with metadata. Returns: Formatted multi-line string. """ # Hardcoded strings found in Boto docs: # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html if 'LastModified' in resource.metadata: optional_time_updated_line = resource_util.get_padded_metadata_time_line( 'Update Time', resource.metadata['LastModified']) else: optional_time_updated_line = '' if 'StorageClass' in resource.metadata: optional_storage_class_line = resource_util.get_padded_metadata_key_value_line( 'Storage Class', resource.metadata['StorageClass']) else: optional_storage_class_line = '' if 'CacheControl' in resource.metadata: optional_cache_control_line = resource_util.get_padded_metadata_key_value_line( 'Cache-Control', resource.metadata['CacheControl']) else: optional_cache_control_line = '' if 'CacheDisposition' in resource.metadata: optional_content_disposition_line = resource_util.get_padded_metadata_key_value_line( 'Cache-Disposition', resource.metadata['CacheDisposition']) else: optional_content_disposition_line = '' if 'ContentEncoding' in resource.metadata: optional_content_encoding_line = resource_util.get_padded_metadata_key_value_line( 'Content-Encoding', resource.metadata['ContentEncoding']) else: optional_content_encoding_line = '' if 'ContentLanguage' in resource.metadata: optional_content_language_line = resource_util.get_padded_metadata_key_value_line( 'Content-Language', resource.metadata['ContentLanguage']) else: optional_content_language_line = '' if 'PartsCount' in resource.metadata: optional_component_count_line = ( resource_util.get_padded_metadata_key_value_line( 'Component-Count', resource.metadata['PartsCount'])) else: optional_component_count_line = '' if resource.md5_hash is not None: optional_md5_line = resource_util.get_padded_metadata_key_value_line( 'Hash (MD5)', resource.md5_hash) elif 'SSECustomerAlgorithm' in resource.metadata: optional_md5_line = resource_util.get_padded_metadata_key_value_line( 'Hash (MD5)', 'Underlying data encrypted') else: optional_md5_line = '' if 'SSECustomerAlgorithm' in resource.metadata: optional_encryption_algorithm_line = ( resource_util.get_padded_metadata_key_value_line( 'Encryption Algorithm', resource.metadata['SSECustomerAlgorithm'])) else: optional_encryption_algorithm_line = '' if resource.generation: optional_generation_line = resource_util.get_padded_metadata_key_value_line( 'Generation', resource.generation) else: optional_generation_line = '' return ( '{object_url}:\n' '{optional_time_updated_line}' '{optional_storage_class_line}' '{optional_cache_control_line}' '{optional_content_disposition_line}' '{optional_content_encoding_line}' '{optional_content_language_line}' '{content_length_line}' '{content_type_line}' '{optional_component_count_line}' '{optional_md5_line}' '{optional_encryption_algorithm_line}' '{etag_line}' '{optional_generation_line}' '{acl_section}' ' {incomplete_warning}').format( object_url=resource.storage_url.versionless_url_string, optional_time_updated_line=optional_time_updated_line, optional_storage_class_line=optional_storage_class_line, optional_cache_control_line=optional_cache_control_line, optional_content_disposition_line=optional_content_disposition_line, optional_content_encoding_line=optional_content_encoding_line, optional_content_language_line=optional_content_language_line, content_length_line=resource_util.get_padded_metadata_key_value_line( 'Content-Length', resource.size), content_type_line=resource_util.get_padded_metadata_key_value_line( 'Content-Type', resource.metadata.get('ContentType')), optional_component_count_line=optional_component_count_line, optional_md5_line=optional_md5_line, optional_encryption_algorithm_line=optional_encryption_algorithm_line, etag_line=resource_util.get_padded_metadata_key_value_line( 'ETag', resource.etag), optional_generation_line=optional_generation_line, acl_section=_get_formatted_acl_section(resource.metadata.get('ACL')), incomplete_warning=_INCOMPLETE_OBJECT_METADATA_WARNING) class S3BucketResource(resource_reference.BucketResource): """API-specific subclass for handling metadata.""" class S3ObjectResource(resource_reference.ObjectResource): """API-specific subclass for handling metadata.""" def __init__(self, storage_url_object, content_type=None, creation_time=None, etag=None, crc32c_hash=None, md5_hash=None, metadata=None, metageneration=None, size=None): """Initializes resource. Args are a subset of attributes.""" super(S3ObjectResource, self).__init__( storage_url_object, content_type=content_type, creation_time=creation_time, etag=etag, crc32c_hash=None, md5_hash=md5_hash, metadata=metadata, metageneration=metageneration, size=size)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 1303, 198, 2, 15069, 12131, 3012, 11419, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198...
2.696754
4,498
import typing from apistar import Settings from apistar.interfaces import Auth from apistar.types import ReturnValue from raven import Client __version__ = "0.2.0"
[ 11748, 19720, 198, 198, 6738, 2471, 47229, 1330, 16163, 198, 6738, 2471, 47229, 13, 3849, 32186, 1330, 26828, 198, 6738, 2471, 47229, 13, 19199, 1330, 8229, 11395, 198, 6738, 37735, 1330, 20985, 198, 198, 834, 9641, 834, 796, 366, 15, 1...
3.541667
48
# import necessary libraries # from models import create_classes import pandas as pd import os import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func from sqlite3 import connect import json from flask import ( Flask, render_template, jsonify, request, redirect, jsonify) # Read data from csv #csv_file = "data/Chicago Health Atlas.csv" #df = pd.read_csv(csv_file) #df.head() #df.rename(columns={"VRDIBR_2015-2019":"VRDIBR_2015_2019","VRDIAR_2015-2018":"VRDIAR_2015_2018","VRDTH_2015-2019":"VRDTH_2015_2019","VRCAR_2015-2019":"VRCAR_2015_2019","VRADR_2015-2019":"VRADR_2015_2019","HDX_2015-2019":"HDX_2015_2019"},inplace=True) #creating sqlite engine to create database #engine = create_engine('sqlite:///data/Chicago_Health_database.db') #engine = create_engine('sqlite:///C:/Users/doyel/Desktop/project3_flask_ex1/data/mydatabase.db') #Table name : Chicago_Health_Atlas #df.to_sql('Chicago_Health_Atlas',con=engine,if_exists='replace') ##################################################################### engine = create_engine("sqlite:///data/mydatabase.db") # reflect an existing database into a new model Base = automap_base() # reflect the tables Base.prepare(engine, reflect=True) # Save reference to the table print(Base.classes.keys()) Healthatlas = Base.classes.healthatlas #Actors = Base.classes.actors ################################################# # Flask Setup ################################################# app = Flask(__name__) # --------------------------------------------------------- # Web site @app.route("/") @app.route("/data.html") @app.route("/templates/map.html") @app.route("/templates/d3_chart.html") # --------------------------------------------------------- # API to call "when data.html" page is loading with community information table @app.route("/api/community") # API to call when a disease is selectd from list by user in "data.html" page @app.route("/api/deceases/<decease>") @app.route("/api/geojson") @app.route('/api/d3_chart/<field_x>/<field_y>') if __name__ == "__main__": app.run()
[ 2, 1330, 3306, 12782, 198, 2, 422, 4981, 1330, 2251, 62, 37724, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 28686, 198, 11748, 44161, 282, 26599, 198, 6738, 44161, 282, 26599, 13, 2302, 13, 2306, 296, 499, 1330, 3557, 499, 62, ...
3.056259
711
import logging from models import tag as Tag, business as Business, business_tag_join_table logging.getLogger().setLevel(logging.INFO) def business_exists(yelp_id, conn): """Return True if the business exists.""" return conn.execute(Business.select().where(Business.c.yelp_id == yelp_id))\ .first() is not None def delete_business(yelp_id, conn): """Delete the business with the given yelp id.""" return conn.execute(Business.delete().where(Business.c.yelp_id == yelp_id))
[ 11748, 18931, 198, 198, 6738, 4981, 1330, 7621, 355, 17467, 11, 1597, 355, 7320, 11, 1597, 62, 12985, 62, 22179, 62, 11487, 198, 198, 6404, 2667, 13, 1136, 11187, 1362, 22446, 2617, 4971, 7, 6404, 2667, 13, 10778, 8, 628, 198, 198, ...
2.802198
182
from random import random from random import choice import numpy as np import plotly.express as px import struct import operator ### # Broadly the same as "basic_functions.py" but updated to include motility # intentionally trying to keep them separate so as not to slow down the basic version ###
[ 6738, 4738, 1330, 4738, 198, 6738, 4738, 1330, 3572, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 7110, 306, 13, 42712, 355, 279, 87, 198, 11748, 2878, 198, 11748, 10088, 198, 198, 21017, 198, 2, 9765, 306, 262, 976, 355, 366, 3548...
3.853659
82
import pandas as pd
[ 11748, 19798, 292, 355, 279, 67 ]
3.166667
6
""" TSP SIMULATED ANNEALING """ # Imports import matplotlib.pyplot as plt import pandas as pd import numpy as np # read data from file filename = "eil51.tsp" f = open(f"TSP-configurations/{filename}.txt", "r") network = f.readlines()[6:-1] # create dictionary to store coordinates nodes = dict() # split data and put in dict for node in network: node = [int(x) for x in node.rstrip().split(' ')] nodes[node[0]] = node[1:] x = [x[0] for x in nodes.values()] y = [y[1] for y in nodes.values()] # load in data of optimal path data = pd.read_csv("data/eil51.tsp.tsp-batch-20.txt", sep="\t") colname = "428.87" z = list(map(float,list(data[f'{colname}-19']))) # optimum so far (costs = 428.87175639203394) # r= [1.0, 32, 11, 38, 5, 37, 17, 4, 18, 47, 12, 46, 51.0, 27, 6, 48, 23, 7, 43, 24, 14, 25, 13, 41, 40, 19, 42, 44, 15, 45, 33, 39, 10, 49, 9, 30, 34, 21, 50, 16, 2, 29, 20, 35, 36, 3, 28, 31, 26, 8, 22, 1.0] temp = [] # get coordinates of each point for item in z: temp.append(nodes[item]) temp = np.array(temp) # path = [temp[i:i+2] for i in range(len(temp)-2+1)] # print(path) # Plot the nodes and coordinates fig, ax = plt.subplots() ax.scatter(x, y, color="deeppink") for i, txt in enumerate(nodes.keys()): ax.annotate(txt, (x[i], y[i])) ax.plot(*temp.T, color="deeppink", alpha=0.5) ax.set_title(f"Shortest Route: {filename}, costs: {colname}", fontsize=16) # plt.savefig("plots/eil51-opt-route-3.png") plt.show()
[ 37811, 309, 4303, 23749, 6239, 11617, 3537, 12161, 1847, 2751, 37227, 198, 198, 2, 1846, 3742, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 11748, 19798, 292, 355, 279, 67, 198, 11748, 299, 32152, 355, 45941, 628, ...
2.300633
632
import astropy.units as u import pytest from benchmark import Benchmark, benchmark @benchmark( { "log.initial.system.Age": {"value": 3.155760e13, "unit": u.sec}, "log.initial.system.Time": {"value": 0.000000, "unit": u.sec}, "log.initial.system.TotAngMom": { "value": 6.747268e40, "unit": (u.kg * u.m ** 2) / u.sec, }, "log.initial.system.TotEnergy": {"value": -2.482441e43, "unit": u.Joule}, "log.initial.system.PotEnergy": {"value": -2.482440e43, "unit": u.Joule}, "log.initial.system.KinEnergy": {"value": 5.347271e34, "unit": u.Joule}, "log.initial.system.DeltaTime": {"value": 0.000000, "unit": u.sec}, "log.initial.star.Mass": {"value": 1.988416e30, "unit": u.kg}, "log.initial.star.Obliquity": {"value": 0.000000, "unit": u.rad}, "log.initial.star.PrecA": {"value": 0.000000, "unit": u.rad}, "log.initial.star.Xobl": {"value": 0.000000}, "log.initial.star.Yobl": {"value": 0.000000}, "log.initial.star.Zobl": {"value": 1.000000}, "log.initial.star.Radius": {"value": 6.378100e06, "unit": u.m}, "log.initial.star.RadGyra": {"value": 0.500000}, "log.initial.star.RotAngMom": { "value": 1.470605e39, "unit": (u.kg * u.m ** 2) / u.sec, }, "log.initial.star.RotKinEnergy": {"value": 5.347271e34, "unit": u.Joule}, "log.initial.star.RotVel": {"value": 463.828521, "unit": u.m / u.sec}, "log.initial.star.BodyType": {"value": 0.000000}, "log.initial.star.RotRate": {"value": 7.272205e-05, "unit": 1 / u.sec}, "log.initial.star.RotPer": {"value": 8.640000e04, "unit": u.sec}, "log.initial.star.Density": {"value": 1.829552e09, "unit": u.kg / u.m ** 3}, "log.initial.star.SurfEnFluxTotal": { "value": 4.474499e-12, "unit": u.kg / u.sec ** 3, }, "log.initial.star.TidalQ": {"value": 1.000000e06}, "log.initial.star.ImK2": {"value": -5.000000e-07}, "log.initial.star.K2": {"value": 0.500000}, "log.initial.star.K2Man": {"value": 0.010000}, "log.initial.star.Imk2Man": {"value": 0.000000}, "log.initial.star.TidalQMantle": {"value": 100.000000}, "log.initial.star.HEcc": {"value": 0.000000}, "log.initial.star.HZLimitDryRunaway": {"value": 3.036202e09, "unit": u.m}, "log.initial.star.HZLimRecVenus": {"value": 2.502002e09, "unit": u.m}, "log.initial.star.HZLimRunaway": {"value": 3.267138e09, "unit": u.m}, "log.initial.star.HZLimMoistGreenhouse": {"value": 3.310536e09, "unit": u.m}, "log.initial.star.HZLimMaxGreenhouse": {"value": 5.611497e09, "unit": u.m}, "log.initial.star.HZLimEarlyMars": {"value": 6.122597e09, "unit": u.m}, "log.initial.star.Instellation": { "value": -1.000000, "unit": u.kg / u.sec ** 3, }, "log.initial.star.KEcc": {"value": 0.000000}, "log.initial.star.Eccentricity": {"value": -1.000000}, "log.initial.star.OrbEnergy": {"value": 0.000000, "unit": u.Joule}, "log.initial.star.MeanMotion": {"value": -1.000000, "unit": 1 / u.sec}, "log.initial.star.OrbPeriod": {"value": -1.000000, "unit": u.sec}, "log.initial.star.SemiMajorAxis": {"value": -1.000000, "unit": u.m}, "log.initial.star.CriticalSemiMajorAxis": {"value": -1.000000, "unit": u.m}, "log.initial.star.COPP": {"value": 0.000000}, "log.initial.star.OrbAngMom": { "value": 0.000000, "unit": (u.kg * u.m ** 2) / u.sec, }, "log.initial.star.LongP": {"value": 0.000000, "unit": u.rad}, "log.initial.star.LXUVTot": {"value": 1.923000e20, "unit": u.kg / u.sec ** 3}, "log.initial.star.TotOrbEnergy": {"value": -2.119237e35, "unit": u.Joule}, "log.initial.star.OrbPotEnergy": {"value": -1.000000, "unit": u.Joule}, "log.initial.star.LostEnergy": {"value": 5.562685e-309, "unit": u.Joule}, "log.initial.star.LostAngMom": { "value": 5.562685e-309, "unit": (u.kg * u.m ** 2) / u.sec, }, "log.initial.star.LockTime": {"value": -1.000000, "unit": u.sec}, "log.initial.star.BodyDsemiDtEqtide": {"value": -1.000000}, "log.initial.star.BodyDeccDt": {"value": -1.000000}, "log.initial.star.DOblDtEqtide": {"value": 0.000000, "unit": u.rad / u.sec}, "log.initial.star.DRotPerDtEqtide": {"value": 2.054554e-27}, "log.initial.star.DRotRateDtEqtide": { "value": -1.729298e-36, "unit": 1 / u.sec ** 2, }, "log.initial.star.EqRotRateDiscrete": { "value": 6.296062e-06, "unit": 1 / u.sec, }, "log.initial.star.EqRotPerDiscrete": {"value": 9.979547e05, "unit": u.sec}, "log.initial.star.EqRotRateCont": {"value": 8.688566e-06, "unit": 1 / u.sec}, "log.initial.star.EqRotPerCont": {"value": 7.231556e05, "unit": u.sec}, "log.initial.star.EqRotPer": {"value": 9.979547e05, "unit": u.sec}, "log.initial.star.EqTidePower": {"value": 0.000000, "unit": 1 / u.sec}, "log.initial.star.GammaRot": {"value": -1.000000, "unit": u.sec}, "log.initial.star.GammaOrb": {"value": -1.000000, "unit": u.sec}, "log.initial.star.OceanK2": {"value": 0.010000}, "log.initial.star.EnvTidalQ": {"value": -1.000000}, "log.initial.star.OceanTidalQ": {"value": -1.000000}, "log.initial.star.TideLock": {"value": 0.000000}, "log.initial.star.RotTimeEqtide": {"value": 0.000000, "unit": u.sec}, "log.initial.star.EnvK2": {"value": 0.010000}, "log.initial.star.OblTimeEqtide": {"value": -1.000000}, "log.initial.star.PowerEqtide": {"value": 2287.372458, "unit": u.W}, "log.initial.star.SurfEnFluxEqtide": { "value": 4.474499e-12, "unit": u.kg / u.sec ** 3, }, "log.initial.star.Luminosity": {"value": 1.923000e23, "unit": u.W}, "log.initial.star.LXUVStellar": {"value": 1.923000e20, "unit": u.W}, "log.initial.star.Temperature": {"value": 5778.000000, "unit": u.K}, "log.initial.star.LXUVFrac": {"value": 0.001000}, "log.initial.star.RossbyNumber": {"value": 0.078260}, "log.initial.star.DRotPerDtStellar": {"value": 6.530034e-18}, "log.initial.auto.Mass": {"value": 2.000000, "unit": u.Mearth}, "log.initial.auto.Obliquity": {"value": 0.785398, "unit": u.rad}, "log.initial.auto.PrecA": {"value": 0.000000, "unit": u.rad}, "log.initial.auto.Xobl": {"value": 0.707107}, "log.initial.auto.Yobl": {"value": 0.000000}, "log.initial.auto.Zobl": {"value": 0.707107}, "log.initial.auto.Radius": {"value": 2.096446e08, "unit": u.m}, "log.initial.auto.RadGyra": {"value": 0.400000}, "log.initial.auto.RotAngMom": { "value": 1.221650e37, "unit": (u.kg * u.m ** 2) / u.sec, }, "log.initial.auto.RotKinEnergy": {"value": 8.884088e32, "unit": u.Joule}, "log.initial.auto.RotVel": {"value": 3.049157e04, "unit": u.m / u.sec}, "log.initial.auto.BodyType": {"value": 0.000000}, "log.initial.auto.RotRate": {"value": 0.000145, "unit": 1 / u.sec}, "log.initial.auto.RotPer": {"value": 0.500000, "unit": u.day}, "log.initial.auto.Density": {"value": 0.309474, "unit": u.kg / u.m ** 3}, "log.initial.auto.SurfEnFluxTotal": { "value": 2.324795e04, "unit": u.kg / u.sec ** 3, }, "log.initial.auto.TidalQ": {"value": -1.000000e05}, "log.initial.auto.ImK2": {"value": -5.000000e-06}, "log.initial.auto.K2": {"value": 0.500000}, "log.initial.auto.K2Man": {"value": 0.300000}, "log.initial.auto.Imk2Man": {"value": -0.003000}, "log.initial.auto.TidalQMantle": {"value": 100.000000}, "log.initial.auto.HEcc": {"value": 0.000000}, "log.initial.auto.HZLimitDryRunaway": {"value": 3.098811e09, "unit": u.m}, "log.initial.auto.HZLimRecVenus": {"value": 2.502002e09, "unit": u.m}, "log.initial.auto.HZLimRunaway": {"value": 3.267138e09, "unit": u.m}, "log.initial.auto.HZLimMoistGreenhouse": {"value": 3.310536e09, "unit": u.m}, "log.initial.auto.HZLimMaxGreenhouse": {"value": 5.611497e09, "unit": u.m}, "log.initial.auto.HZLimEarlyMars": {"value": 6.122597e09, "unit": u.m}, "log.initial.auto.Instellation": { "value": 69.788358, "unit": u.kg / u.sec ** 3, }, "log.initial.auto.KEcc": {"value": 0.200000}, "log.initial.auto.Eccentricity": {"value": 0.200000}, "log.initial.auto.OrbEnergy": {"value": -5.298093e34, "unit": u.Joule}, "log.initial.auto.MeanMotion": {"value": 6.296062e-06, "unit": 1 / u.sec}, "log.initial.auto.OrbPeriod": {"value": 9.979547e05, "unit": u.sec}, "log.initial.auto.SemiMajorAxis": {"value": 0.100000, "unit": u.au}, "log.initial.auto.CriticalSemiMajorAxis": {"value": -1.000000, "unit": u.m}, "log.initial.auto.COPP": {"value": 0.000000}, "log.initial.auto.OrbAngMom": { "value": 1.648983e40, "unit": (u.kg * u.m ** 2) / u.sec, }, "log.initial.auto.LongP": {"value": 0.000000, "unit": u.rad}, "log.initial.auto.LXUVTot": {"value": -1.000000, "unit": u.kg / u.sec ** 3}, "log.initial.auto.TotOrbEnergy": {"value": -2.119237e35, "unit": u.Joule}, "log.initial.auto.OrbPotEnergy": {"value": -1.059619e35, "unit": u.Joule}, "log.initial.auto.LostEnergy": {"value": 5.562685e-309, "unit": u.Joule}, "log.initial.auto.TidalRadius": {"value": 2.096446e08, "unit": u.m}, "log.initial.auto.DsemiDtEqtide": {"value": 0.000192, "unit": u.m / u.sec}, "log.initial.auto.DeccDtEqtide": {"value": 4.036352e-15, "unit": 1 / u.sec}, "log.initial.auto.DMeanMotionDtEqtide": { "value": -1.211805e-19, "unit": 1 / u.sec ** 2, }, "log.initial.auto.DOrbPerDtEqtide": {"value": 1.920766e-08}, "log.initial.auto.EccTimeEqtide": {"value": 4.954969e13, "unit": u.sec}, "log.initial.auto.SemiTimeEqtide": {"value": 7.793412e13, "unit": u.sec}, "log.initial.auto.DHEccDtEqtide": {"value": 0.000000, "unit": 1 / u.sec}, "log.initial.auto.DKEccDtEqtide": {"value": 4.036352e-15, "unit": 1 / u.sec}, "log.initial.auto.DXoblDtEqtide": {"value": 1.462258e-12, "unit": 1 / u.sec}, "log.initial.auto.DYoblDtEqtide": {"value": 0.000000, "unit": 1 / u.sec}, "log.initial.auto.DZoblDtEqtide": {"value": -1.462258e-12, "unit": 1 / u.sec}, "log.initial.auto.LockTime": {"value": -1.000000, "unit": u.sec}, "log.initial.auto.BodyDsemiDtEqtide": {"value": -1.000000}, "log.initial.auto.BodyDeccDt": {"value": -1.000000}, "log.initial.auto.DOblDtEqtide": {"value": 2.067945e-12, "unit": u.rad / u.sec}, "log.initial.auto.DRotPerDtEqtide": {"value": 3.287202e-07}, "log.initial.auto.DRotRateDtEqtide": { "value": -1.106722e-15, "unit": 1 / u.sec ** 2, }, "log.initial.auto.EqRotRateDiscrete": { "value": 6.296062e-06, "unit": 1 / u.sec, }, "log.initial.auto.EqRotPerDiscrete": {"value": 9.979547e05, "unit": u.sec}, "log.initial.auto.EqRotRateCont": {"value": 8.688566e-06, "unit": 1 / u.sec}, "log.initial.auto.EqRotPerCont": {"value": 7.231556e05, "unit": u.sec}, "log.initial.auto.EqRotPer": {"value": 9.979547e05, "unit": u.sec}, "log.initial.auto.EqTidePower": {"value": 0.000000, "unit": 1 / u.sec}, "log.initial.auto.GammaRot": {"value": -1.000000, "unit": u.sec}, "log.initial.auto.GammaOrb": {"value": -1.000000, "unit": u.sec}, "log.initial.auto.OceanK2": {"value": 0.010000}, "log.initial.auto.EnvTidalQ": {"value": -1.000000}, "log.initial.auto.OceanTidalQ": {"value": -1.000000}, "log.initial.auto.TideLock": {"value": 0.000000}, "log.initial.auto.RotTimeEqtide": {"value": 1.314188e11, "unit": u.sec}, "log.initial.auto.EnvK2": {"value": 0.500000}, "log.initial.auto.OblTimeEqtide": {"value": -1.000000}, "log.initial.auto.PowerEqtide": {"value": 1.284046e22, "unit": u.W}, "log.initial.auto.SurfEnFluxEqtide": { "value": 2.324895e04, "unit": u.kg / u.sec ** 3, }, "log.initial.auto.SurfWaterMass": {"value": 0.000000, "unit": u.kg}, "log.initial.auto.EnvelopeMass": {"value": 1.000000, "unit": u.Mearth}, "log.initial.auto.OxygenMass": {"value": 0.000000, "unit": u.kg}, "log.initial.auto.RGLimit": {"value": 3.099115e09, "unit": u.m}, "log.initial.auto.XO": {"value": 0.000000}, "log.initial.auto.EtaO": {"value": 0.000000}, "log.initial.auto.PlanetRadius": {"value": 32.869442, "unit": u.Rearth}, "log.initial.auto.OxygenMantleMass": {"value": 0.000000, "unit": u.kg}, "log.initial.auto.RadXUV": {"value": -1.000000, "unit": u.m}, "log.initial.auto.RadSolid": {"value": -1.000000, "unit": u.m}, "log.initial.auto.PresXUV": {"value": 5.000000}, "log.initial.auto.ScaleHeight": {"value": -1.000000, "unit": u.m}, "log.initial.auto.ThermTemp": {"value": 400.000000, "unit": u.K}, "log.initial.auto.AtmGasConst": {"value": 4124.000000}, "log.initial.auto.PresSurf": {"value": -1.000000, "unit": u.Pa}, "log.initial.auto.DEnvMassDt": {"value": -2.508715e09, "unit": u.kg / u.sec}, "log.initial.auto.FXUV": {"value": 0.069788, "unit": u.W / u.m ** 2}, "log.initial.auto.AtmXAbsEffH2O": {"value": 0.300000}, "log.initial.auto.RocheRadius": {"value": 1.885546e08, "unit": u.m}, "log.initial.auto.BondiRadius": {"value": 7.899468e08, "unit": u.m}, "log.initial.auto.HEscapeRegime": {"value": 3.000000}, "log.initial.auto.RRCriticalFlux": {"value": 0.000139, "unit": u.W / u.m ** 2}, "log.initial.auto.KTide": {"value": 1.000000}, "log.initial.auto.RGDuration": {"value": 1.00000e06, "unit": u.yr}, "log.initial.bondi.Mass": {"value": 2.000000, "unit": u.Mearth}, "log.initial.bondi.Obliquity": {"value": 0.785398, "unit": u.rad}, "log.initial.bondi.PrecA": {"value": 0.000000, "unit": u.rad}, "log.initial.bondi.Xobl": {"value": 0.707107}, "log.initial.bondi.Yobl": {"value": 0.000000}, "log.initial.bondi.Zobl": {"value": 0.707107}, "log.initial.bondi.Radius": {"value": 2.096446e08, "unit": u.m}, "log.initial.bondi.RadGyra": {"value": 0.400000}, "log.initial.bondi.RotAngMom": { "value": 1.221650e37, "unit": (u.kg * u.m ** 2) / u.sec, }, "log.initial.bondi.RotKinEnergy": {"value": 8.884088e32, "unit": u.Joule}, "log.initial.bondi.RotVel": {"value": 3.049157e04, "unit": u.m / u.sec}, "log.initial.bondi.BodyType": {"value": 0.000000}, "log.initial.bondi.RotRate": {"value": 0.000145, "unit": 1 / u.sec}, "log.initial.bondi.RotPer": {"value": 0.500000, "unit": u.day}, "log.initial.bondi.Density": {"value": 0.309474, "unit": u.kg / u.m ** 3}, "log.initial.bondi.SurfEnFluxTotal": { "value": 2.324795e04, "unit": u.kg / u.sec ** 3, }, "log.initial.bondi.TidalQ": {"value": -1.000000e05}, "log.initial.bondi.ImK2": {"value": -5.000000e-06}, "log.initial.bondi.K2": {"value": 0.500000}, "log.initial.bondi.K2Man": {"value": 0.300000}, "log.initial.bondi.Imk2Man": {"value": -0.003000}, "log.initial.bondi.TidalQMantle": {"value": 100.000000}, "log.initial.bondi.HEcc": {"value": 0.000000}, "log.initial.bondi.HZLimitDryRunaway": {"value": 3.098811e09, "unit": u.m}, "log.initial.bondi.HZLimRecVenus": {"value": 2.502002e09, "unit": u.m}, "log.initial.bondi.HZLimRunaway": {"value": 3.267138e09, "unit": u.m}, "log.initial.bondi.HZLimMoistGreenhouse": {"value": 3.310536e09, "unit": u.m}, "log.initial.bondi.HZLimMaxGreenhouse": {"value": 5.611497e09, "unit": u.m}, "log.initial.bondi.HZLimEarlyMars": {"value": 6.122597e09, "unit": u.m}, "log.initial.bondi.Instellation": { "value": 69.788358, "unit": u.kg / u.sec ** 3, }, "log.initial.bondi.KEcc": {"value": 0.200000}, "log.initial.bondi.Eccentricity": {"value": 0.200000}, "log.initial.bondi.OrbEnergy": {"value": -5.298093e34, "unit": u.Joule}, "log.initial.bondi.MeanMotion": {"value": 6.296062e-06, "unit": 1 / u.sec}, "log.initial.bondi.OrbPeriod": {"value": 9.979547e05, "unit": u.sec}, "log.initial.bondi.SemiMajorAxis": {"value": 0.100000, "unit": u.au}, "log.initial.bondi.CriticalSemiMajorAxis": {"value": -1.000000, "unit": u.m}, "log.initial.bondi.COPP": {"value": 0.000000}, "log.initial.bondi.OrbAngMom": { "value": 1.648983e40, "unit": (u.kg * u.m ** 2) / u.sec, }, "log.initial.bondi.LongP": {"value": 0.000000, "unit": u.rad}, "log.initial.bondi.LXUVTot": {"value": -1.000000, "unit": u.kg / u.sec ** 3}, "log.initial.bondi.TotOrbEnergy": {"value": -2.119237e35, "unit": u.Joule}, "log.initial.bondi.OrbPotEnergy": {"value": -1.059619e35, "unit": u.Joule}, "log.initial.bondi.LostEnergy": {"value": 5.562685e-309, "unit": u.Joule}, "log.initial.bondi.TidalRadius": {"value": 2.096446e08, "unit": u.m}, "log.initial.bondi.DsemiDtEqtide": {"value": 0.000192, "unit": u.m / u.sec}, "log.initial.bondi.DeccDtEqtide": {"value": 4.036352e-15, "unit": 1 / u.sec}, "log.initial.bondi.DMeanMotionDtEqtide": { "value": -1.211805e-19, "unit": 1 / u.sec ** 2, }, "log.initial.bondi.DOrbPerDtEqtide": {"value": 1.920766e-08}, "log.initial.bondi.EccTimeEqtide": {"value": 4.954969e13, "unit": u.sec}, "log.initial.bondi.SemiTimeEqtide": {"value": 7.793412e13, "unit": u.sec}, "log.initial.bondi.DHEccDtEqtide": {"value": 0.000000, "unit": 1 / u.sec}, "log.initial.bondi.DKEccDtEqtide": {"value": 4.036352e-15, "unit": 1 / u.sec}, "log.initial.bondi.DXoblDtEqtide": {"value": 1.462258e-12, "unit": 1 / u.sec}, "log.initial.bondi.DYoblDtEqtide": {"value": 0.000000, "unit": 1 / u.sec}, "log.initial.bondi.DZoblDtEqtide": {"value": -1.462258e-12, "unit": 1 / u.sec}, "log.initial.bondi.LockTime": {"value": -1.000000, "unit": u.sec}, "log.initial.bondi.BodyDsemiDtEqtide": {"value": -1.000000}, "log.initial.bondi.BodyDeccDt": {"value": -1.000000}, "log.initial.bondi.DOblDtEqtide": { "value": 2.067945e-12, "unit": u.rad / u.sec, }, "log.initial.bondi.DRotPerDtEqtide": {"value": 3.287202e-07}, "log.initial.bondi.DRotRateDtEqtide": { "value": -1.106722e-15, "unit": 1 / u.sec ** 2, }, "log.initial.bondi.EqRotRateDiscrete": { "value": 6.296062e-06, "unit": 1 / u.sec, }, "log.initial.bondi.EqRotPerDiscrete": {"value": 9.979547e05, "unit": u.sec}, "log.initial.bondi.EqRotRateCont": {"value": 8.688566e-06, "unit": 1 / u.sec}, "log.initial.bondi.EqRotPerCont": {"value": 7.231556e05, "unit": u.sec}, "log.initial.bondi.EqRotPer": {"value": 9.979547e05, "unit": u.sec}, "log.initial.bondi.EqTidePower": {"value": 0.000000, "unit": 1 / u.sec}, "log.initial.bondi.GammaRot": {"value": -1.000000, "unit": u.sec}, "log.initial.bondi.GammaOrb": {"value": -1.000000, "unit": u.sec}, "log.initial.bondi.OceanK2": {"value": 0.010000}, "log.initial.bondi.EnvTidalQ": {"value": -1.000000}, "log.initial.bondi.OceanTidalQ": {"value": -1.000000}, "log.initial.bondi.TideLock": {"value": 0.000000}, "log.initial.bondi.RotTimeEqtide": {"value": 1.314188e11, "unit": u.sec}, "log.initial.bondi.EnvK2": {"value": 0.500000}, "log.initial.bondi.OblTimeEqtide": {"value": -1.000000}, "log.initial.bondi.PowerEqtide": {"value": 1.284046e22, "unit": u.W}, "log.initial.bondi.SurfEnFluxEqtide": { "value": 2.324895e04, "unit": u.kg / u.sec ** 3, }, "log.initial.bondi.SurfWaterMass": {"value": 0.000000, "unit": u.kg}, "log.initial.bondi.EnvelopeMass": {"value": 1.000000, "unit": u.Mearth}, "log.initial.bondi.OxygenMass": {"value": 0.000000, "unit": u.kg}, "log.initial.bondi.RGLimit": {"value": 3.099115e09, "unit": u.m}, "log.initial.bondi.XO": {"value": 0.000000}, "log.initial.bondi.EtaO": {"value": 0.000000}, "log.initial.bondi.PlanetRadius": {"value": 32.869442, "unit": u.Rearth}, "log.initial.bondi.OxygenMantleMass": {"value": 0.000000, "unit": u.kg}, "log.initial.bondi.RadXUV": {"value": -1.000000, "unit": u.m}, "log.initial.bondi.RadSolid": {"value": -1.000000, "unit": u.m}, "log.initial.bondi.PresXUV": {"value": 5.000000}, "log.initial.bondi.ScaleHeight": {"value": -1.000000, "unit": u.m}, "log.initial.bondi.ThermTemp": {"value": 400.000000, "unit": u.K}, "log.initial.bondi.AtmGasConst": {"value": 4124.000000}, "log.initial.bondi.PresSurf": {"value": -1.000000, "unit": u.Pa}, "log.initial.bondi.DEnvMassDt": {"value": -1.230386e15, "unit": u.kg / u.sec}, "log.initial.bondi.FXUV": {"value": 0.069788, "unit": u.W / u.m ** 2}, "log.initial.bondi.AtmXAbsEffH2O": {"value": 0.300000}, "log.initial.bondi.RocheRadius": {"value": 1.885546e08, "unit": u.m}, "log.initial.bondi.BondiRadius": {"value": 7.899468e08, "unit": u.m}, "log.initial.bondi.HEscapeRegime": {"value": 5.000000}, "log.initial.bondi.RRCriticalFlux": {"value": 0.000139, "unit": u.W / u.m ** 2}, "log.initial.bondi.KTide": {"value": 1.000000}, "log.initial.bondi.RGDuration": {"value": 1.00000e06, "unit": u.yr}, "log.initial.el.Mass": {"value": 2.000000, "unit": u.Mearth}, "log.initial.el.Obliquity": {"value": 0.410152, "unit": u.rad}, "log.initial.el.PrecA": {"value": 0.000000, "unit": u.rad}, "log.initial.el.Xobl": {"value": 0.398749}, "log.initial.el.Yobl": {"value": 0.000000}, "log.initial.el.Zobl": {"value": 0.917060}, "log.initial.el.Radius": {"value": 2.096446e08, "unit": u.m}, "log.initial.el.RadGyra": {"value": 0.400000}, "log.initial.el.RotAngMom": { "value": 6.108249e36, "unit": (u.kg * u.m ** 2) / u.sec, }, "log.initial.el.RotKinEnergy": {"value": 2.221022e32, "unit": u.Joule}, "log.initial.el.RotVel": {"value": 1.524578e04, "unit": u.m / u.sec}, "log.initial.el.BodyType": {"value": 0.000000}, "log.initial.el.RotRate": {"value": 7.272205e-05, "unit": 1 / u.sec}, "log.initial.el.RotPer": {"value": 1.000000, "unit": u.day}, "log.initial.el.Density": {"value": 0.309474, "unit": u.kg / u.m ** 3}, "log.initial.el.SurfEnFluxTotal": { "value": 1.100803e04, "unit": u.kg / u.sec ** 3, }, "log.initial.el.TidalQ": {"value": -1.000000e05}, "log.initial.el.ImK2": {"value": -5.000000e-06}, "log.initial.el.K2": {"value": 0.500000}, "log.initial.el.K2Man": {"value": 0.300000}, "log.initial.el.Imk2Man": {"value": -0.003000}, "log.initial.el.TidalQMantle": {"value": 100.000000}, "log.initial.el.HEcc": {"value": 0.000000}, "log.initial.el.HZLimitDryRunaway": {"value": 3.098811e09, "unit": u.m}, "log.initial.el.HZLimRecVenus": {"value": 2.502002e09, "unit": u.m}, "log.initial.el.HZLimRunaway": {"value": 3.267138e09, "unit": u.m}, "log.initial.el.HZLimMoistGreenhouse": {"value": 3.310536e09, "unit": u.m}, "log.initial.el.HZLimMaxGreenhouse": {"value": 5.611497e09, "unit": u.m}, "log.initial.el.HZLimEarlyMars": {"value": 6.122597e09, "unit": u.m}, "log.initial.el.Instellation": {"value": 69.788358, "unit": u.kg / u.sec ** 3}, "log.initial.el.KEcc": {"value": 0.200000}, "log.initial.el.Eccentricity": {"value": 0.200000}, "log.initial.el.OrbEnergy": {"value": -5.298093e34, "unit": u.Joule}, "log.initial.el.MeanMotion": {"value": 6.296062e-06, "unit": 1 / u.sec}, "log.initial.el.OrbPeriod": {"value": 9.979547e05, "unit": u.sec}, "log.initial.el.SemiMajorAxis": {"value": 0.100000, "unit": u.au}, "log.initial.el.CriticalSemiMajorAxis": {"value": -1.000000, "unit": u.m}, "log.initial.el.COPP": {"value": 0.000000}, "log.initial.el.OrbAngMom": { "value": 1.648983e40, "unit": (u.kg * u.m ** 2) / u.sec, }, "log.initial.el.LongP": {"value": 0.000000, "unit": u.rad}, "log.initial.el.LXUVTot": {"value": -1.000000, "unit": u.kg / u.sec ** 3}, "log.initial.el.TotOrbEnergy": {"value": -2.119237e35, "unit": u.Joule}, "log.initial.el.OrbPotEnergy": {"value": -1.059619e35, "unit": u.Joule}, "log.initial.el.LostEnergy": {"value": 5.562685e-309, "unit": u.Joule}, "log.initial.el.TidalRadius": {"value": 2.096446e08, "unit": u.m}, "log.initial.el.DsemiDtEqtide": {"value": 0.000192, "unit": u.m / u.sec}, "log.initial.el.DeccDtEqtide": {"value": 4.036352e-15, "unit": 1 / u.sec}, "log.initial.el.DMeanMotionDtEqtide": { "value": -1.211805e-19, "unit": 1 / u.sec ** 2, }, "log.initial.el.DOrbPerDtEqtide": {"value": 1.920766e-08}, "log.initial.el.EccTimeEqtide": {"value": 4.954969e13, "unit": u.sec}, "log.initial.el.SemiTimeEqtide": {"value": 7.793412e13, "unit": u.sec}, "log.initial.el.DHEccDtEqtide": {"value": 0.000000, "unit": 1 / u.sec}, "log.initial.el.DKEccDtEqtide": {"value": 4.036352e-15, "unit": 1 / u.sec}, "log.initial.el.DXoblDtEqtide": {"value": 2.139632e-12, "unit": 1 / u.sec}, "log.initial.el.DYoblDtEqtide": {"value": 0.000000, "unit": 1 / u.sec}, "log.initial.el.DZoblDtEqtide": {"value": -9.303384e-13, "unit": 1 / u.sec}, "log.initial.el.LockTime": {"value": -1.000000, "unit": u.sec}, "log.initial.el.BodyDsemiDtEqtide": {"value": -1.000000}, "log.initial.el.BodyDeccDt": {"value": -1.000000}, "log.initial.el.DOblDtEqtide": {"value": 2.333143e-12, "unit": u.rad / u.sec}, "log.initial.el.DRotPerDtEqtide": {"value": 1.314881e-06}, "log.initial.el.DRotRateDtEqtide": { "value": -1.106722e-15, "unit": 1 / u.sec ** 2, }, "log.initial.el.EqRotRateDiscrete": {"value": 6.296062e-06, "unit": 1 / u.sec}, "log.initial.el.EqRotPerDiscrete": {"value": 9.979547e05, "unit": u.sec}, "log.initial.el.EqRotRateCont": {"value": 8.688566e-06, "unit": 1 / u.sec}, "log.initial.el.EqRotPerCont": {"value": 7.231556e05, "unit": u.sec}, "log.initial.el.EqRotPer": {"value": 9.979547e05, "unit": u.sec}, "log.initial.el.EqTidePower": {"value": 0.000000, "unit": 1 / u.sec}, "log.initial.el.GammaRot": {"value": -1.000000, "unit": u.sec}, "log.initial.el.GammaOrb": {"value": -1.000000, "unit": u.sec}, "log.initial.el.OceanK2": {"value": 0.010000}, "log.initial.el.EnvTidalQ": {"value": -1.000000}, "log.initial.el.OceanTidalQ": {"value": -1.000000}, "log.initial.el.TideLock": {"value": 0.000000}, "log.initial.el.RotTimeEqtide": {"value": 6.570938e10, "unit": u.sec}, "log.initial.el.EnvK2": {"value": 0.500000}, "log.initial.el.OblTimeEqtide": {"value": -1.000000}, "log.initial.el.PowerEqtide": {"value": 6.080320e21, "unit": u.W}, "log.initial.el.SurfEnFluxEqtide": { "value": 1.100903e04, "unit": u.kg / u.sec ** 3, }, "log.initial.el.SurfWaterMass": {"value": 0.000000, "unit": u.kg}, "log.initial.el.EnvelopeMass": {"value": 1.000000, "unit": u.Mearth}, "log.initial.el.OxygenMass": {"value": 0.000000, "unit": u.kg}, "log.initial.el.RGLimit": {"value": 3.099115e09, "unit": u.m}, "log.initial.el.XO": {"value": 0.000000}, "log.initial.el.EtaO": {"value": 0.000000}, "log.initial.el.PlanetRadius": {"value": 32.869442, "unit": u.Rearth}, "log.initial.el.OxygenMantleMass": {"value": 0.000000, "unit": u.kg}, "log.initial.el.RadXUV": {"value": -1.000000, "unit": u.m}, "log.initial.el.RadSolid": {"value": -1.000000, "unit": u.m}, "log.initial.el.PresXUV": {"value": 5.000000}, "log.initial.el.ScaleHeight": {"value": -1.000000, "unit": u.m}, "log.initial.el.ThermTemp": {"value": 400.000000, "unit": u.K}, "log.initial.el.AtmGasConst": {"value": 4124.000000}, "log.initial.el.PresSurf": {"value": -1.000000, "unit": u.Pa}, "log.initial.el.DEnvMassDt": {"value": -2.508715e09, "unit": u.kg / u.sec}, "log.initial.el.FXUV": {"value": 0.069788, "unit": u.W / u.m ** 2}, "log.initial.el.AtmXAbsEffH2O": {"value": 0.300000}, "log.initial.el.RocheRadius": {"value": 1.885546e08, "unit": u.m}, "log.initial.el.BondiRadius": {"value": 7.899468e08, "unit": u.m}, "log.initial.el.HEscapeRegime": {"value": 3.000000}, "log.initial.el.RRCriticalFlux": {"value": 0.000139, "unit": u.W / u.m ** 2}, "log.initial.el.KTide": {"value": 1.000000}, "log.initial.el.RGDuration": {"value": 1.00000e06, "unit": u.yr}, "log.initial.rr.Mass": {"value": 2.000000, "unit": u.Mearth}, "log.initial.rr.Obliquity": {"value": 0.785398, "unit": u.rad}, "log.initial.rr.PrecA": {"value": 0.000000, "unit": u.rad}, "log.initial.rr.Xobl": {"value": 0.707107}, "log.initial.rr.Yobl": {"value": 0.000000}, "log.initial.rr.Zobl": {"value": 0.707107}, "log.initial.rr.Radius": {"value": 2.096446e08, "unit": u.m}, "log.initial.rr.RadGyra": {"value": 0.400000}, "log.initial.rr.RotAngMom": { "value": 1.221650e37, "unit": (u.kg * u.m ** 2) / u.sec, }, "log.initial.rr.RotKinEnergy": {"value": 8.884088e32, "unit": u.Joule}, "log.initial.rr.RotVel": {"value": 3.049157e04, "unit": u.m / u.sec}, "log.initial.rr.BodyType": {"value": 0.000000}, "log.initial.rr.RotRate": {"value": 0.000145, "unit": 1 / u.sec}, "log.initial.rr.RotPer": {"value": 0.500000, "unit": u.day}, "log.initial.rr.Density": {"value": 0.309474, "unit": u.kg / u.m ** 3}, "log.initial.rr.SurfEnFluxTotal": { "value": 2.324795e04, "unit": u.kg / u.sec ** 3, }, "log.initial.rr.TidalQ": {"value": -1.000000e05}, "log.initial.rr.ImK2": {"value": -5.000000e-06}, "log.initial.rr.K2": {"value": 0.500000}, "log.initial.rr.K2Man": {"value": 0.300000}, "log.initial.rr.Imk2Man": {"value": -0.003000}, "log.initial.rr.TidalQMantle": {"value": 100.000000}, "log.initial.rr.HEcc": {"value": 0.000000}, "log.initial.rr.HZLimitDryRunaway": {"value": 3.098811e09, "unit": u.m}, "log.initial.rr.HZLimRecVenus": {"value": 2.502002e09, "unit": u.m}, "log.initial.rr.HZLimRunaway": {"value": 3.267138e09, "unit": u.m}, "log.initial.rr.HZLimMoistGreenhouse": {"value": 3.310536e09, "unit": u.m}, "log.initial.rr.HZLimMaxGreenhouse": {"value": 5.611497e09, "unit": u.m}, "log.initial.rr.HZLimEarlyMars": {"value": 6.122597e09, "unit": u.m}, "log.initial.rr.Instellation": {"value": 69.788358, "unit": u.kg / u.sec ** 3}, "log.initial.rr.KEcc": {"value": 0.200000}, "log.initial.rr.Eccentricity": {"value": 0.200000}, "log.initial.rr.OrbEnergy": {"value": -5.298093e34, "unit": u.Joule}, "log.initial.rr.MeanMotion": {"value": 6.296062e-06, "unit": 1 / u.sec}, "log.initial.rr.OrbPeriod": {"value": 9.979547e05, "unit": u.sec}, "log.initial.rr.SemiMajorAxis": {"value": 0.100000, "unit": u.au}, "log.initial.rr.CriticalSemiMajorAxis": {"value": -1.000000, "unit": u.m}, "log.initial.rr.COPP": {"value": 0.000000}, "log.initial.rr.OrbAngMom": { "value": 1.648983e40, "unit": (u.kg * u.m ** 2) / u.sec, }, "log.initial.rr.LongP": {"value": 0.000000, "unit": u.rad}, "log.initial.rr.LXUVTot": {"value": -1.000000, "unit": u.kg / u.sec ** 3}, "log.initial.rr.TotOrbEnergy": {"value": -2.119237e35, "unit": u.Joule}, "log.initial.rr.OrbPotEnergy": {"value": -1.059619e35, "unit": u.Joule}, "log.initial.rr.LostEnergy": {"value": 5.562685e-309, "unit": u.Joule}, "log.initial.rr.TidalRadius": {"value": 2.096446e08, "unit": u.m}, "log.initial.rr.DsemiDtEqtide": {"value": 0.000192, "unit": u.m / u.sec}, "log.initial.rr.DeccDtEqtide": {"value": 4.036352e-15, "unit": 1 / u.sec}, "log.initial.rr.DMeanMotionDtEqtide": { "value": -1.211805e-19, "unit": 1 / u.sec ** 2, }, "log.initial.rr.DOrbPerDtEqtide": {"value": 1.920766e-08}, "log.initial.rr.EccTimeEqtide": {"value": 4.954969e13, "unit": u.sec}, "log.initial.rr.SemiTimeEqtide": {"value": 7.793412e13, "unit": u.sec}, "log.initial.rr.DHEccDtEqtide": {"value": 0.000000, "unit": 1 / u.sec}, "log.initial.rr.DKEccDtEqtide": {"value": 4.036352e-15, "unit": 1 / u.sec}, "log.initial.rr.DXoblDtEqtide": {"value": 1.462258e-12, "unit": 1 / u.sec}, "log.initial.rr.DYoblDtEqtide": {"value": 0.000000, "unit": 1 / u.sec}, "log.initial.rr.DZoblDtEqtide": {"value": -1.462258e-12, "unit": 1 / u.sec}, "log.initial.rr.LockTime": {"value": -1.000000, "unit": u.sec}, "log.initial.rr.BodyDsemiDtEqtide": {"value": -1.000000}, "log.initial.rr.BodyDeccDt": {"value": -1.000000}, "log.initial.rr.DOblDtEqtide": {"value": 2.067945e-12, "unit": u.rad / u.sec}, "log.initial.rr.DRotPerDtEqtide": {"value": 3.287202e-07}, "log.initial.rr.DRotRateDtEqtide": { "value": -1.106722e-15, "unit": 1 / u.sec ** 2, }, "log.initial.rr.EqRotRateDiscrete": {"value": 6.296062e-06, "unit": 1 / u.sec}, "log.initial.rr.EqRotPerDiscrete": {"value": 9.979547e05, "unit": u.sec}, "log.initial.rr.EqRotRateCont": {"value": 8.688566e-06, "unit": 1 / u.sec}, "log.initial.rr.EqRotPerCont": {"value": 7.231556e05, "unit": u.sec}, "log.initial.rr.EqRotPer": {"value": 9.979547e05, "unit": u.sec}, "log.initial.rr.EqTidePower": {"value": 0.000000, "unit": 1 / u.sec}, "log.initial.rr.GammaRot": {"value": -1.000000, "unit": u.sec}, "log.initial.rr.GammaOrb": {"value": -1.000000, "unit": u.sec}, "log.initial.rr.OceanK2": {"value": 0.010000}, "log.initial.rr.EnvTidalQ": {"value": -1.000000}, "log.initial.rr.OceanTidalQ": {"value": -1.000000}, "log.initial.rr.TideLock": {"value": 0.000000}, "log.initial.rr.RotTimeEqtide": {"value": 1.314188e11, "unit": u.sec}, "log.initial.rr.EnvK2": {"value": 0.500000}, "log.initial.rr.OblTimeEqtide": {"value": -1.000000}, "log.initial.rr.PowerEqtide": {"value": 1.284046e22, "unit": u.W}, "log.initial.rr.SurfEnFluxEqtide": { "value": 2.324895e04, "unit": u.kg / u.sec ** 3, }, "log.initial.rr.SurfWaterMass": {"value": 0.000000, "unit": u.kg}, "log.initial.rr.EnvelopeMass": {"value": 1.000000, "unit": u.Mearth}, "log.initial.rr.OxygenMass": {"value": 0.000000, "unit": u.kg}, "log.initial.rr.RGLimit": {"value": 3.099115e09, "unit": u.m}, "log.initial.rr.XO": {"value": 0.000000}, "log.initial.rr.EtaO": {"value": 0.000000}, "log.initial.rr.PlanetRadius": {"value": 32.869442, "unit": u.Rearth}, "log.initial.rr.OxygenMantleMass": {"value": 0.000000, "unit": u.kg}, "log.initial.rr.RadXUV": {"value": -1.000000, "unit": u.m}, "log.initial.rr.RadSolid": {"value": -1.000000, "unit": u.m}, "log.initial.rr.PresXUV": {"value": 5.000000}, "log.initial.rr.ScaleHeight": {"value": -1.000000, "unit": u.m}, "log.initial.rr.ThermTemp": {"value": 400.000000, "unit": u.K}, "log.initial.rr.AtmGasConst": {"value": 4124.000000}, "log.initial.rr.PresSurf": {"value": -1.000000, "unit": u.Pa}, "log.initial.rr.DEnvMassDt": {"value": -1.119308e08, "unit": u.kg / u.sec}, "log.initial.rr.FXUV": {"value": 0.069788, "unit": u.W / u.m ** 2}, "log.initial.rr.AtmXAbsEffH2O": {"value": 0.300000}, "log.initial.rr.RocheRadius": {"value": 1.885546e08, "unit": u.m}, "log.initial.rr.BondiRadius": {"value": 7.899468e08, "unit": u.m}, "log.initial.rr.HEscapeRegime": {"value": 6.000000}, "log.initial.rr.RRCriticalFlux": {"value": 0.000139, "unit": u.W / u.m ** 2}, "log.initial.rr.KTide": {"value": 1.000000}, "log.initial.rr.RGDuration": {"value": 1.00000e06, "unit": u.yr}, "log.final.system.Age": {"value": 6.311520e13, "unit": u.sec, "rtol": 1e-4}, "log.final.system.Time": {"value": 3.155760e13, "unit": u.sec, "rtol": 1e-4}, "log.final.system.TotAngMom": { "value": 5.425277e40, "unit": (u.kg * u.m ** 2) / u.sec, "rtol": 1e-4, }, "log.final.system.TotEnergy": { "value": -2.482441e43, "unit": u.Joule, "rtol": 1e-4, }, "log.final.system.PotEnergy": { "value": -2.482440e43, "unit": u.Joule, "rtol": 1e-4, }, "log.final.system.KinEnergy": { "value": 5.347271e34, "unit": u.Joule, "rtol": 1e-4, }, "log.final.system.DeltaTime": { "value": 4.863245e08, "unit": u.sec, "rtol": 1e-4, }, "log.final.star.Mass": {"value": 1.988416e30, "unit": u.kg, "rtol": 1e-4}, "log.final.star.Obliquity": {"value": 0.000000, "unit": u.rad, "rtol": 1e-4}, "log.final.star.PrecA": {"value": 0.000000, "unit": u.rad, "rtol": 1e-4}, "log.final.star.Xobl": {"value": 0.000000, "rtol": 1e-4}, "log.final.star.Yobl": {"value": 0.000000, "rtol": 1e-4}, "log.final.star.Zobl": {"value": 1.000000, "rtol": 1e-4}, "log.final.star.Radius": {"value": 6.378100e06, "unit": u.m, "rtol": 1e-4}, "log.final.star.RadGyra": {"value": 0.500000, "rtol": 1e-4}, "log.final.star.RotAngMom": { "value": 1.470605e39, "unit": (u.kg * u.m ** 2) / u.sec, "rtol": 1e-4, }, "log.final.star.RotKinEnergy": { "value": 5.347271e34, "unit": u.Joule, "rtol": 1e-4, }, "log.final.star.RotVel": { "value": 463.828520, "unit": u.m / u.sec, "rtol": 1e-4, }, "log.final.star.BodyType": {"value": 0.000000, "rtol": 1e-4}, "log.final.star.RotRate": { "value": 7.272205e-05, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.star.RotPer": {"value": 8.640000e04, "unit": u.sec, "rtol": 1e-4}, "log.final.star.Density": { "value": 1.829552e09, "unit": u.kg / u.m ** 3, "rtol": 1e-4, }, "log.final.star.SurfEnFluxTotal": { "value": 3.025764e-12, "unit": u.kg / u.sec ** 3, "rtol": 1e-4, }, "log.final.star.TidalQ": {"value": 1.000000e06, "rtol": 1e-4}, "log.final.star.ImK2": {"value": -5.000000e-07, "rtol": 1e-4}, "log.final.star.K2": {"value": 0.500000, "rtol": 1e-4}, "log.final.star.K2Man": {"value": 0.010000, "rtol": 1e-4}, "log.final.star.Imk2Man": {"value": 0.000000, "rtol": 1e-4}, "log.final.star.TidalQMantle": {"value": 100.000000, "rtol": 1e-4}, "log.final.star.HEcc": {"value": 0.000000, "rtol": 1e-4}, "log.final.star.HZLimitDryRunaway": { "value": 3.036202e09, "unit": u.m, "rtol": 1e-4, }, "log.final.star.HZLimRecVenus": { "value": 2.502002e09, "unit": u.m, "rtol": 1e-4, }, "log.final.star.HZLimRunaway": { "value": 3.267138e09, "unit": u.m, "rtol": 1e-4, }, "log.final.star.HZLimMoistGreenhouse": { "value": 3.310536e09, "unit": u.m, "rtol": 1e-4, }, "log.final.star.HZLimMaxGreenhouse": { "value": 5.611497e09, "unit": u.m, "rtol": 1e-4, }, "log.final.star.HZLimEarlyMars": { "value": 6.122597e09, "unit": u.m, "rtol": 1e-4, }, "log.final.star.Instellation": { "value": -1.000000, "unit": u.kg / u.sec ** 3, "rtol": 1e-4, }, "log.final.star.KEcc": {"value": 0.000000, "rtol": 1e-4}, "log.final.star.Eccentricity": {"value": -1.000000, "rtol": 1e-4}, "log.final.star.OrbEnergy": {"value": 0.000000, "unit": u.Joule, "rtol": 1e-4}, "log.final.star.MeanMotion": { "value": -1.000000, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.star.OrbPeriod": {"value": -1.000000, "unit": u.sec, "rtol": 1e-4}, "log.final.star.SemiMajorAxis": {"value": -1.000000, "unit": u.m, "rtol": 1e-4}, "log.final.star.CriticalSemiMajorAxis": { "value": -1.000000, "unit": u.m, "rtol": 1e-4, }, "log.final.star.COPP": {"value": 0.000000, "rtol": 1e-4}, "log.final.star.OrbAngMom": { "value": 0.000000, "unit": (u.kg * u.m ** 2) / u.sec, "rtol": 1e-4, }, "log.final.star.LongP": {"value": 0.000000, "unit": u.rad, "rtol": 1e-4}, "log.final.star.LXUVTot": { "value": 1.923000e20, "unit": u.kg / u.sec ** 3, "rtol": 1e-4, }, "log.final.star.TotOrbEnergy": { "value": -1.740032e35, "unit": u.Joule, "rtol": 1e-4, }, "log.final.star.OrbPotEnergy": { "value": -1.000000, "unit": u.Joule, "rtol": 1e-4, }, "log.final.star.LostEnergy": { "value": 2.550749e26, "unit": u.Joule, "rtol": 1e-4, }, "log.final.star.LostAngMom": { "value": 3.507532e30, "unit": (u.kg * u.m ** 2) / u.sec, "rtol": 1e-4, }, "log.final.star.LockTime": {"value": -1.000000, "unit": u.sec, "rtol": 1e-4}, "log.final.star.BodyDsemiDtEqtide": {"value": -1.000000, "rtol": 1e-4}, "log.final.star.BodyDeccDt": {"value": -1.000000, "rtol": 1e-4}, "log.final.star.DOblDtEqtide": { "value": 0.000000, "unit": u.rad / u.sec, "rtol": 1e-4, }, "log.final.star.DRotPerDtEqtide": {"value": 1.380178e-27, "rtol": 1e-4}, "log.final.star.DRotRateDtEqtide": { "value": -1.161683e-36, "unit": 1 / u.sec ** 2, "rtol": 1e-4, }, "log.final.star.EqRotRateDiscrete": { "value": 6.510710e-06, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.star.EqRotPerDiscrete": { "value": 9.650538e05, "unit": u.sec, "rtol": 1e-4, }, "log.final.star.EqRotRateCont": { "value": 7.554427e-06, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.star.EqRotPerCont": { "value": 8.317222e05, "unit": u.sec, "rtol": 1e-4, }, "log.final.star.EqRotPer": {"value": 9.650538e05, "unit": u.sec, "rtol": 1e-4}, "log.final.star.EqTidePower": { "value": 0.000000, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.star.GammaRot": {"value": -1.000000, "unit": u.sec, "rtol": 1e-4}, "log.final.star.GammaOrb": {"value": -1.000000, "unit": u.sec, "rtol": 1e-4}, "log.final.star.OceanK2": {"value": 0.010000, "rtol": 1e-4}, "log.final.star.EnvTidalQ": {"value": -1.000000, "rtol": 1e-4}, "log.final.star.OceanTidalQ": {"value": -1.000000, "rtol": 1e-4}, "log.final.star.TideLock": {"value": 0.000000, "rtol": 1e-4}, "log.final.star.RotTimeEqtide": { "value": 2.047960e-37, "unit": u.sec, "rtol": 1e-4, }, "log.final.star.EnvK2": {"value": 0.010000, "rtol": 1e-4}, "log.final.star.OblTimeEqtide": {"value": -1.000000, "rtol": 1e-4}, "log.final.star.PowerEqtide": {"value": 1546.776661, "unit": u.W, "rtol": 1e-4}, "log.final.star.SurfEnFluxEqtide": { "value": 3.025764e-12, "unit": u.kg / u.sec ** 3, "rtol": 1e-4, }, "log.final.star.Luminosity": {"value": 1.923000e23, "unit": u.W, "rtol": 1e-4}, "log.final.star.LXUVStellar": {"value": 1.923000e20, "unit": u.W, "rtol": 1e-4}, "log.final.star.Temperature": {"value": 5778.000000, "unit": u.K, "rtol": 1e-4}, "log.final.star.LXUVFrac": {"value": 0.001000, "rtol": 1e-4}, "log.final.star.RossbyNumber": {"value": 0.078260, "rtol": 1e-4}, "log.final.star.DRotPerDtStellar": {"value": 6.530034e-18, "rtol": 1e-4}, "log.final.auto.Mass": {"value": 1.411359, "unit": u.Mearth, "rtol": 1e-4}, "log.final.auto.Obliquity": {"value": 0.000000, "unit": u.rad, "rtol": 1e-4}, "log.final.auto.PrecA": {"value": 0.000000, "unit": u.rad, "rtol": 1e-4}, "log.final.auto.Xobl": {"value": 1.570471e-162, "rtol": 1e-4}, "log.final.auto.Yobl": {"value": 0.000000, "rtol": 1e-4}, "log.final.auto.Zobl": {"value": 1.000002, "rtol": 1e-4}, "log.final.auto.Radius": {"value": 1.630278e08, "unit": u.m, "rtol": 1e-4}, "log.final.auto.RadGyra": {"value": 0.400000, "rtol": 1e-4}, "log.final.auto.RotAngMom": { "value": 2.333687e35, "unit": (u.kg * u.m ** 2) / u.sec, "rtol": 1e-4, }, "log.final.auto.RotKinEnergy": { "value": 7.596980e29, "unit": u.Joule, "rtol": 1e-4, }, "log.final.auto.RotVel": { "value": 1061.426957, "unit": u.m / u.sec, "rtol": 1e-4, }, "log.final.auto.BodyType": {"value": 0.000000, "rtol": 1e-4}, "log.final.auto.RotRate": { "value": 6.510710e-06, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.auto.RotPer": {"value": 11.169604, "unit": u.day, "rtol": 1e-4}, "log.final.auto.Density": { "value": 0.464405, "unit": u.kg / u.m ** 3, "rtol": 1e-4, }, "log.final.auto.SurfEnFluxTotal": { "value": 52.542587, "unit": u.kg / u.sec ** 3, "rtol": 1e-4, }, "log.final.auto.TidalQ": {"value": -1.000000e05, "rtol": 1e-4}, "log.final.auto.ImK2": {"value": -5.000000e-06, "rtol": 1e-4}, "log.final.auto.K2": {"value": 0.500000, "rtol": 1e-4}, "log.final.auto.K2Man": {"value": 0.300000, "rtol": 1e-4}, "log.final.auto.Imk2Man": {"value": -0.003000, "rtol": 1e-4}, "log.final.auto.TidalQMantle": {"value": 100.000000, "rtol": 1e-4}, "log.final.auto.HEcc": {"value": 0.000000, "rtol": 1e-4}, "log.final.auto.HZLimitDryRunaway": { "value": 3.062148e09, "unit": u.m, "rtol": 1e-4, }, "log.final.auto.HZLimRecVenus": { "value": 2.502002e09, "unit": u.m, "rtol": 1e-4, }, "log.final.auto.HZLimRunaway": { "value": 3.267138e09, "unit": u.m, "rtol": 1e-4, }, "log.final.auto.HZLimMoistGreenhouse": { "value": 3.310536e09, "unit": u.m, "rtol": 1e-4, }, "log.final.auto.HZLimMaxGreenhouse": { "value": 5.611497e09, "unit": u.m, "rtol": 1e-4, }, "log.final.auto.HZLimEarlyMars": { "value": 6.122597e09, "unit": u.m, "rtol": 1e-4, }, "log.final.auto.Instellation": { "value": 72.115242, "unit": u.kg / u.sec ** 3, "rtol": 1e-4, }, "log.final.auto.KEcc": {"value": 0.129902, "rtol": 1e-4}, "log.final.auto.Eccentricity": {"value": 0.129902, "rtol": 1e-4}, "log.final.auto.OrbEnergy": { "value": -3.823257e34, "unit": u.Joule, "rtol": 1e-4, }, "log.final.auto.MeanMotion": { "value": 6.510710e-06, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.auto.OrbPeriod": {"value": 9.650538e05, "unit": u.sec, "rtol": 1e-4}, "log.final.auto.SemiMajorAxis": {"value": 0.097790, "unit": u.au, "rtol": 1e-4}, "log.final.auto.CriticalSemiMajorAxis": { "value": -1.000000, "unit": u.m, "rtol": 1e-4, }, "log.final.auto.COPP": {"value": 0.000000, "rtol": 1e-4}, "log.final.auto.OrbAngMom": { "value": 1.164500e40, "unit": (u.kg * u.m ** 2) / u.sec, "rtol": 1e-4, }, "log.final.auto.LongP": {"value": 0.000000, "unit": u.rad, "rtol": 1e-4}, "log.final.auto.LXUVTot": { "value": -1.000000, "unit": u.kg / u.sec ** 3, "rtol": 1e-4, }, "log.final.auto.TotOrbEnergy": { "value": -1.740032e35, "unit": u.Joule, "rtol": 1e-4, }, "log.final.auto.OrbPotEnergy": { "value": -7.646514e34, "unit": u.Joule, "rtol": 1e-4, }, "log.final.auto.LostEnergy": { "value": 1.264526e33, "unit": u.Joule, "rtol": 1e-4, }, "log.final.auto.TidalRadius": {"value": 1.630278e08, "unit": u.m, "rtol": 1e-4}, "log.final.auto.DsemiDtEqtide": { "value": -6.842553e-06, "unit": u.m / u.sec, "rtol": 1e-4, }, "log.final.auto.DeccDtEqtide": { "value": -1.800337e-15, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.auto.DMeanMotionDtEqtide": { "value": 4.567924e-21, "unit": 1 / u.sec ** 2, "rtol": 1e-4, }, "log.final.auto.DOrbPerDtEqtide": {"value": -6.770832e-10, "rtol": 1e-4}, "log.final.auto.EccTimeEqtide": { "value": 7.215422e13, "unit": u.sec, "rtol": 1e-4, }, "log.final.auto.SemiTimeEqtide": { "value": 2.137966e15, "unit": u.sec, "rtol": 1e-4, }, "log.final.auto.DHEccDtEqtide": { "value": -0.000000, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.auto.DKEccDtEqtide": { "value": -1.800337e-15, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.auto.DXoblDtEqtide": { "value": 0.000000, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.auto.DYoblDtEqtide": { "value": 0.000000, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.auto.DZoblDtEqtide": { "value": 0.000000, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.auto.LockTime": {"value": 2.398144e11, "unit": u.sec, "rtol": 1e-4}, "log.final.auto.BodyDsemiDtEqtide": {"value": -1.000000, "rtol": 1e-4}, "log.final.auto.BodyDeccDt": {"value": -1.000000, "rtol": 1e-4}, "log.final.auto.DOblDtEqtide": { "value": 0.000000, "unit": u.rad / u.sec, "rtol": 1e-4, }, "log.final.auto.DRotPerDtEqtide": {"value": -8.245322e-298, "rtol": 1e-4}, "log.final.auto.DRotRateDtEqtide": { "value": 5.562685e-309, "unit": 1 / u.sec ** 2, "rtol": 1e-4, }, "log.final.auto.EqRotRateDiscrete": { "value": 6.510710e-06, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.auto.EqRotPerDiscrete": { "value": 9.650538e05, "unit": u.sec, "rtol": 1e-4, }, "log.final.auto.EqRotRateCont": { "value": 7.554427e-06, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.auto.EqRotPerCont": { "value": 8.317222e05, "unit": u.sec, "rtol": 1e-4, }, "log.final.auto.EqRotPer": {"value": 9.650538e05, "unit": u.sec, "rtol": 1e-4}, "log.final.auto.EqTidePower": { "value": 0.000000, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.auto.GammaRot": {"value": -1.000000, "unit": u.sec, "rtol": 1e-4}, "log.final.auto.GammaOrb": {"value": -1.000000, "unit": u.sec, "rtol": 1e-4}, "log.final.auto.OceanK2": {"value": 0.010000, "rtol": 1e-4}, "log.final.auto.EnvTidalQ": {"value": -1.000000, "rtol": 1e-4}, "log.final.auto.OceanTidalQ": {"value": -1.000000, "rtol": 1e-4}, "log.final.auto.TideLock": {"value": 1.000000, "rtol": 1e-4}, "log.final.auto.RotTimeEqtide": { "value": 1.170426e303, "unit": u.sec, "rtol": 1e-4, }, "log.final.auto.EnvK2": {"value": 0.500000, "rtol": 1e-4}, "log.final.auto.OblTimeEqtide": {"value": -1.000000, "rtol": 1e-4}, "log.final.auto.PowerEqtide": {"value": 1.788269e19, "unit": u.W, "rtol": 1e-4}, "log.final.auto.SurfEnFluxEqtide": { "value": 53.542587, "unit": u.kg / u.sec ** 3, "rtol": 1e-4, }, "log.final.auto.SurfWaterMass": {"value": 0.000000, "unit": u.kg, "rtol": 1e-4}, "log.final.auto.EnvelopeMass": { "value": 0.411359, "unit": u.Mearth, "rtol": 1e-4, }, "log.final.auto.OxygenMass": {"value": 0.000000, "unit": u.kg, "rtol": 1e-4}, "log.final.auto.RGLimit": {"value": 3.141989e09, "unit": u.m, "rtol": 1e-4}, "log.final.auto.XO": {"value": 0.000000, "rtol": 1e-4}, "log.final.auto.EtaO": {"value": 0.000000, "rtol": 1e-4}, "log.final.auto.PlanetRadius": { "value": 25.560564, "unit": u.Rearth, "rtol": 1e-4, }, "log.final.auto.OxygenMantleMass": { "value": 0.000000, "unit": u.kg, "rtol": 1e-4, }, "log.final.auto.RadXUV": {"value": -1.000000, "unit": u.m, "rtol": 1e-4}, "log.final.auto.RadSolid": {"value": -1.000000, "unit": u.m, "rtol": 1e-4}, "log.final.auto.PresXUV": {"value": 5.000000, "rtol": 1e-4}, "log.final.auto.ScaleHeight": {"value": -1.000000, "unit": u.m, "rtol": 1e-4}, "log.final.auto.ThermTemp": {"value": 400.000000, "unit": u.K, "rtol": 1e-4}, "log.final.auto.AtmGasConst": {"value": 4124.000000, "rtol": 1e-4}, "log.final.auto.PresSurf": {"value": -1.000000, "unit": u.Pa, "rtol": 1e-4}, "log.final.auto.DEnvMassDt": { "value": -7.802590e07, "unit": u.kg / u.sec, "rtol": 1e-4, }, "log.final.auto.FXUV": { "value": 0.072115, "unit": u.W / u.m ** 2, "rtol": 1e-4, }, "log.final.auto.AtmXAbsEffH2O": {"value": 0.300000, "rtol": 1e-4}, "log.final.auto.RocheRadius": {"value": 1.641596e08, "unit": u.m, "rtol": 1e-4}, "log.final.auto.BondiRadius": {"value": 5.637137e08, "unit": u.m, "rtol": 1e-4}, "log.final.auto.HEscapeRegime": {"value": 6.000000, "rtol": 1e-4}, "log.final.auto.RRCriticalFlux": { "value": 1.470664e-06, "unit": u.W / u.m ** 2, "rtol": 1e-4, }, "log.final.auto.KTide": {"value": 0.100000, "rtol": 1e-4}, "log.final.auto.RGDuration": {"value": 1.00000e06, "unit": u.yr, "rtol": 1e-4}, "log.final.bondi.Mass": {"value": 1.000000, "unit": u.Mearth, "rtol": 1e-4}, "log.final.bondi.Obliquity": { "value": 2.992105e-54, "unit": u.rad, "rtol": 1e-4, }, "log.final.bondi.PrecA": {"value": 0.000000, "unit": u.rad, "rtol": 1e-4}, "log.final.bondi.Xobl": {"value": 2.992105e-54, "rtol": 1e-4}, "log.final.bondi.Yobl": {"value": 0.000000, "rtol": 1e-4}, "log.final.bondi.Zobl": {"value": 1.000000, "rtol": 1e-4}, "log.final.bondi.Radius": {"value": 6.378100e06, "unit": u.m, "rtol": 1e-4}, "log.final.bondi.RadGyra": {"value": 0.400000, "rtol": 1e-4}, "log.final.bondi.RotAngMom": { "value": 2.447267e32, "unit": (u.kg * u.m ** 2) / u.sec, "rtol": 1e-4, }, "log.final.bondi.RotKinEnergy": { "value": 7.703654e26, "unit": u.Joule, "rtol": 1e-4, }, "log.final.bondi.RotVel": { "value": 40.154732, "unit": u.m / u.sec, "rtol": 1e-4, }, "log.final.bondi.BodyType": {"value": 0.000000, "rtol": 1e-4}, "log.final.bondi.RotRate": { "value": 6.295720e-06, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.bondi.RotPer": {"value": 11.551030, "unit": u.day, "rtol": 1e-4}, "log.final.bondi.Density": { "value": 5495.038549, "unit": u.kg / u.m ** 3, "rtol": 1e-4, }, "log.final.bondi.SurfEnFluxTotal": { "value": 3.855526, "unit": u.kg / u.sec ** 3, "rtol": 1e-4, }, "log.final.bondi.TidalQ": {"value": -100.000000, "rtol": 1e-4}, "log.final.bondi.ImK2": {"value": -0.003000, "rtol": 1e-4}, "log.final.bondi.K2": {"value": 0.500000, "rtol": 1e-4}, "log.final.bondi.K2Man": {"value": 0.300000, "rtol": 1e-4}, "log.final.bondi.Imk2Man": {"value": -0.003000, "rtol": 1e-4}, "log.final.bondi.TidalQMantle": {"value": 100.000000, "rtol": 1e-4}, "log.final.bondi.HEcc": {"value": 0.000000, "rtol": 1e-4}, "log.final.bondi.HZLimitDryRunaway": { "value": 3.098815e09, "unit": u.m, "rtol": 1e-4, }, "log.final.bondi.HZLimRecVenus": { "value": 2.502002e09, "unit": u.m, "rtol": 1e-4, }, "log.final.bondi.HZLimRunaway": { "value": 3.267138e09, "unit": u.m, "rtol": 1e-4, }, "log.final.bondi.HZLimMoistGreenhouse": { "value": 3.310536e09, "unit": u.m, "rtol": 1e-4, }, "log.final.bondi.HZLimMaxGreenhouse": { "value": 5.611497e09, "unit": u.m, "rtol": 1e-4, }, "log.final.bondi.HZLimEarlyMars": { "value": 6.122597e09, "unit": u.m, "rtol": 1e-4, }, "log.final.bondi.Instellation": { "value": 69.783534, "unit": u.kg / u.sec ** 3, "rtol": 1e-4, }, "log.final.bondi.KEcc": {"value": 0.200007, "rtol": 1e-4}, "log.final.bondi.Eccentricity": {"value": 0.200007, "rtol": 1e-4}, "log.final.bondi.OrbEnergy": { "value": -2.648953e34, "unit": u.Joule, "rtol": 1e-4, }, "log.final.bondi.MeanMotion": { "value": 6.295720e-06, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.bondi.OrbPeriod": { "value": 9.980090e05, "unit": u.sec, "rtol": 1e-4, }, "log.final.bondi.SemiMajorAxis": { "value": 0.100004, "unit": u.au, "rtol": 1e-4, }, "log.final.bondi.CriticalSemiMajorAxis": { "value": -1.000000, "unit": u.m, "rtol": 1e-4, }, "log.final.bondi.COPP": {"value": 0.000000, "rtol": 1e-4}, "log.final.bondi.OrbAngMom": { "value": 8.245061e39, "unit": (u.kg * u.m ** 2) / u.sec, "rtol": 1e-4, }, "log.final.bondi.LongP": {"value": 0.000000, "unit": u.rad, "rtol": 1e-4}, "log.final.bondi.LXUVTot": { "value": -1.000000, "unit": u.kg / u.sec ** 3, "rtol": 1e-4, }, "log.final.bondi.TotOrbEnergy": { "value": -1.740032e35, "unit": u.Joule, "rtol": 1e-4, }, "log.final.bondi.OrbPotEnergy": { "value": -5.297906e34, "unit": u.Joule, "rtol": 1e-4, }, "log.final.bondi.LostEnergy": { "value": 3.022858e31, "unit": u.Joule, "rtol": 1e-4, }, "log.final.bondi.TidalRadius": { "value": 6.378100e06, "unit": u.m, "rtol": 1e-4, }, "log.final.bondi.DsemiDtEqtide": { "value": -1.113122e-09, "unit": u.m / u.sec, "rtol": 1e-4, }, "log.final.bondi.DeccDtEqtide": { "value": -1.860062e-19, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.bondi.DMeanMotionDtEqtide": { "value": 7.026492e-25, "unit": 1 / u.sec ** 2, "rtol": 1e-4, }, "log.final.bondi.DOrbPerDtEqtide": {"value": -1.113852e-13, "rtol": 1e-4}, "log.final.bondi.EccTimeEqtide": { "value": 1.075269e18, "unit": u.sec, "rtol": 1e-4, }, "log.final.bondi.SemiTimeEqtide": { "value": 1.343996e19, "unit": u.sec, "rtol": 1e-4, }, "log.final.bondi.DHEccDtEqtide": { "value": -0.000000, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.bondi.DKEccDtEqtide": { "value": -1.860062e-19, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.bondi.DXoblDtEqtide": { "value": -1.366908e-65, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.bondi.DYoblDtEqtide": { "value": 0.000000, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.bondi.DZoblDtEqtide": { "value": 4.089932e-119, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.bondi.LockTime": {"value": 4.919130e12, "unit": u.sec, "rtol": 1e-4}, "log.final.bondi.BodyDsemiDtEqtide": {"value": -1.000000, "rtol": 1e-4}, "log.final.bondi.BodyDeccDt": {"value": -1.000000, "rtol": 1e-4}, "log.final.bondi.DOblDtEqtide": { "value": -1.366908e-65, "unit": u.rad / u.sec, "rtol": 1e-4, }, "log.final.bondi.DRotPerDtEqtide": {"value": -8.818069e-298, "rtol": 1e-4}, "log.final.bondi.DRotRateDtEqtide": { "value": 5.562685e-309, "unit": 1 / u.sec ** 2, "rtol": 1e-4, }, "log.final.bondi.EqRotRateDiscrete": { "value": 6.295720e-06, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.bondi.EqRotPerDiscrete": { "value": 9.980090e05, "unit": u.sec, "rtol": 1e-4, }, "log.final.bondi.EqRotRateCont": { "value": 8.688253e-06, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.bondi.EqRotPerCont": { "value": 7.231816e05, "unit": u.sec, "rtol": 1e-4, }, "log.final.bondi.EqRotPer": {"value": 9.980090e05, "unit": u.sec, "rtol": 1e-4}, "log.final.bondi.EqTidePower": { "value": 0.000000, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.bondi.GammaRot": {"value": -1.000000, "unit": u.sec, "rtol": 1e-4}, "log.final.bondi.GammaOrb": {"value": -1.000000, "unit": u.sec, "rtol": 1e-4}, "log.final.bondi.OceanK2": {"value": 0.010000, "rtol": 1e-4}, "log.final.bondi.EnvTidalQ": {"value": -1.000000, "rtol": 1e-4}, "log.final.bondi.OceanTidalQ": {"value": -1.000000, "rtol": 1e-4}, "log.final.bondi.TideLock": {"value": 1.000000, "rtol": 1e-4}, "log.final.bondi.RotTimeEqtide": { "value": 1.131777e303, "unit": u.sec, "rtol": 1e-4, }, "log.final.bondi.EnvK2": {"value": 0.500000, "rtol": 1e-4}, "log.final.bondi.OblTimeEqtide": {"value": -1.000000, "rtol": 1e-4}, "log.final.bondi.PowerEqtide": { "value": 1.970952e15, "unit": u.W, "rtol": 1e-4, }, "log.final.bondi.SurfEnFluxEqtide": { "value": 3.855526, "unit": u.kg / u.sec ** 3, "rtol": 1e-4, }, "log.final.bondi.SurfWaterMass": { "value": 0.000000, "unit": u.kg, "rtol": 1e-4, }, "log.final.bondi.EnvelopeMass": { "value": 0.000000, "unit": u.Mearth, "rtol": 1e-4, }, "log.final.bondi.OxygenMass": {"value": 0.000000, "unit": u.kg, "rtol": 1e-4}, "log.final.bondi.RGLimit": {"value": 3.147864e09, "unit": u.m, "rtol": 1e-4}, "log.final.bondi.XO": {"value": 0.000000, "rtol": 1e-4}, "log.final.bondi.EtaO": {"value": 0.000000, "rtol": 1e-4}, "log.final.bondi.PlanetRadius": { "value": 1.000000, "unit": u.Rearth, "rtol": 1e-4, }, "log.final.bondi.OxygenMantleMass": { "value": 0.000000, "unit": u.kg, "rtol": 1e-4, }, "log.final.bondi.RadXUV": {"value": -1.000000, "unit": u.m, "rtol": 1e-4}, "log.final.bondi.RadSolid": {"value": -1.000000, "unit": u.m, "rtol": 1e-4}, "log.final.bondi.PresXUV": {"value": 5.000000, "rtol": 1e-4}, "log.final.bondi.ScaleHeight": {"value": -1.000000, "unit": u.m, "rtol": 1e-4}, "log.final.bondi.ThermTemp": {"value": 400.000000, "unit": u.K, "rtol": 1e-4}, "log.final.bondi.AtmGasConst": {"value": 4124.000000, "rtol": 1e-4}, "log.final.bondi.PresSurf": {"value": -1.000000, "unit": u.Pa, "rtol": 1e-4}, "log.final.bondi.DEnvMassDt": { "value": 5.562685e-309, "unit": u.kg / u.sec, "rtol": 1e-4, }, "log.final.bondi.FXUV": { "value": 0.069784, "unit": u.W / u.m ** 2, "rtol": 1e-4, }, "log.final.bondi.AtmXAbsEffH2O": {"value": 0.300000, "rtol": 1e-4}, "log.final.bondi.RocheRadius": { "value": 1.496611e08, "unit": u.m, "rtol": 1e-4, }, "log.final.bondi.BondiRadius": { "value": 3.949665e08, "unit": u.m, "rtol": 1e-4, }, "log.final.bondi.HEscapeRegime": {"value": 8.000000, "rtol": 1e-4}, "log.final.bondi.RRCriticalFlux": { "value": 1.080455, "unit": u.W / u.m ** 2, "rtol": 1e-4, }, "log.final.bondi.KTide": {"value": 0.936113, "rtol": 1e-4}, "log.final.bondi.RGDuration": {"value": 1.00000e06, "unit": u.yr, "rtol": 1e-4}, "log.final.el.Mass": {"value": 1.986370, "unit": u.Mearth, "rtol": 1e-4}, "log.final.el.Obliquity": {"value": 0.000000, "unit": u.rad, "rtol": 1e-4}, "log.final.el.PrecA": {"value": 0.000000, "unit": u.rad, "rtol": 1e-4}, "log.final.el.Xobl": {"value": 1.563609e-162, "rtol": 1e-4}, "log.final.el.Yobl": {"value": 0.000000, "rtol": 1e-4}, "log.final.el.Zobl": {"value": 1.000000, "rtol": 1e-4}, "log.final.el.Radius": {"value": 2.084572e08, "unit": u.m, "rtol": 1e-4}, "log.final.el.RadGyra": {"value": 0.400000, "rtol": 1e-4}, "log.final.el.RotAngMom": { "value": 5.470333e35, "unit": (u.kg * u.m ** 2) / u.sec, "rtol": 1e-4, }, "log.final.el.RotKinEnergy": { "value": 1.814054e30, "unit": u.Joule, "rtol": 1e-4, }, "log.final.el.RotVel": { "value": 1382.558099, "unit": u.m / u.sec, "rtol": 1e-4, }, "log.final.el.BodyType": {"value": 0.000000, "rtol": 1e-4}, "log.final.el.RotRate": { "value": 6.632335e-06, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.el.RotPer": {"value": 10.964773, "unit": u.day, "rtol": 1e-4}, "log.final.el.Density": { "value": 0.312647, "unit": u.kg / u.m ** 3, "rtol": 1e-4, }, "log.final.el.SurfEnFluxTotal": { "value": 33.098849, "unit": u.kg / u.sec ** 3, "rtol": 1e-4, }, "log.final.el.TidalQ": {"value": -1.000000e05, "rtol": 1e-4}, "log.final.el.ImK2": {"value": -5.000000e-06, "rtol": 1e-4}, "log.final.el.K2": {"value": 0.500000, "rtol": 1e-4}, "log.final.el.K2Man": {"value": 0.300000, "rtol": 1e-4}, "log.final.el.Imk2Man": {"value": -0.003000, "rtol": 1e-4}, "log.final.el.TidalQMantle": {"value": 100.000000, "rtol": 1e-4}, "log.final.el.HEcc": {"value": 0.000000, "rtol": 1e-4}, "log.final.el.HZLimitDryRunaway": { "value": 3.043341e09, "unit": u.m, "rtol": 1e-4, }, "log.final.el.HZLimRecVenus": {"value": 2.502002e09, "unit": u.m, "rtol": 1e-4}, "log.final.el.HZLimRunaway": {"value": 3.267138e09, "unit": u.m, "rtol": 1e-4}, "log.final.el.HZLimMoistGreenhouse": { "value": 3.310536e09, "unit": u.m, "rtol": 1e-4, }, "log.final.el.HZLimMaxGreenhouse": { "value": 5.611497e09, "unit": u.m, "rtol": 1e-4, }, "log.final.el.HZLimEarlyMars": { "value": 6.122597e09, "unit": u.m, "rtol": 1e-4, }, "log.final.el.Instellation": { "value": 73.462978, "unit": u.kg / u.sec ** 3, "rtol": 1e-4, }, "log.final.el.KEcc": {"value": 0.068456, "rtol": 1e-4}, "log.final.el.Eccentricity": {"value": 0.068456, "rtol": 1e-4}, "log.final.el.OrbEnergy": { "value": -5.447720e34, "unit": u.Joule, "rtol": 1e-4, }, "log.final.el.MeanMotion": { "value": 6.632335e-06, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.el.OrbPeriod": {"value": 9.473564e05, "unit": u.sec, "rtol": 1e-4}, "log.final.el.SemiMajorAxis": {"value": 0.096591, "unit": u.au, "rtol": 1e-4}, "log.final.el.CriticalSemiMajorAxis": { "value": -1.000000, "unit": u.m, "rtol": 1e-4, }, "log.final.el.COPP": {"value": 0.000000, "rtol": 1e-4}, "log.final.el.OrbAngMom": { "value": 1.638922e40, "unit": (u.kg * u.m ** 2) / u.sec, "rtol": 1e-4, }, "log.final.el.LongP": {"value": 0.000000, "unit": u.rad, "rtol": 1e-4}, "log.final.el.LXUVTot": { "value": -1.000000, "unit": u.kg / u.sec ** 3, "rtol": 1e-4, }, "log.final.el.TotOrbEnergy": { "value": -1.740032e35, "unit": u.Joule, "rtol": 1e-4, }, "log.final.el.OrbPotEnergy": { "value": -1.089544e35, "unit": u.Joule, "rtol": 1e-4, }, "log.final.el.LostEnergy": { "value": 2.085924e33, "unit": u.Joule, "rtol": 1e-4, }, "log.final.el.TidalRadius": {"value": 2.084572e08, "unit": u.m, "rtol": 1e-4}, "log.final.el.DsemiDtEqtide": { "value": -4.938887e-06, "unit": u.m / u.sec, "rtol": 1e-4, }, "log.final.el.DeccDtEqtide": { "value": -2.496493e-15, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.el.DMeanMotionDtEqtide": { "value": 3.400372e-21, "unit": 1 / u.sec ** 2, "rtol": 1e-4, }, "log.final.el.DOrbPerDtEqtide": {"value": -4.857058e-10, "rtol": 1e-4}, "log.final.el.EccTimeEqtide": { "value": 2.742067e13, "unit": u.sec, "rtol": 1e-4, }, "log.final.el.SemiTimeEqtide": { "value": 2.925710e15, "unit": u.sec, "rtol": 1e-4, }, "log.final.el.DHEccDtEqtide": { "value": -0.000000, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.el.DKEccDtEqtide": { "value": -2.496493e-15, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.el.DXoblDtEqtide": { "value": 0.000000, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.el.DYoblDtEqtide": { "value": 0.000000, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.el.DZoblDtEqtide": { "value": 0.000000, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.el.LockTime": {"value": 8.193554e10, "unit": u.sec, "rtol": 1e-4}, "log.final.el.BodyDsemiDtEqtide": {"value": -1.000000, "rtol": 1e-4}, "log.final.el.BodyDeccDt": {"value": -1.000000, "rtol": 1e-4}, "log.final.el.DOblDtEqtide": { "value": 0.000000, "unit": u.rad / u.sec, "rtol": 1e-4, }, "log.final.el.DRotPerDtEqtide": {"value": -7.945685e-298, "rtol": 1e-4}, "log.final.el.DRotRateDtEqtide": { "value": 5.562685e-309, "unit": 1 / u.sec ** 2, "rtol": 1e-4, }, "log.final.el.EqRotRateDiscrete": { "value": 6.632335e-06, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.el.EqRotPerDiscrete": { "value": 9.473564e05, "unit": u.sec, "rtol": 1e-4, }, "log.final.el.EqRotRateCont": { "value": 6.927597e-06, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.el.EqRotPerCont": { "value": 9.069791e05, "unit": u.sec, "rtol": 1e-4, }, "log.final.el.EqRotPer": {"value": 9.473564e05, "unit": u.sec, "rtol": 1e-4}, "log.final.el.EqTidePower": { "value": 0.000000, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.el.GammaRot": {"value": -1.000000, "unit": u.sec, "rtol": 1e-4}, "log.final.el.GammaOrb": {"value": -1.000000, "unit": u.sec, "rtol": 1e-4}, "log.final.el.OceanK2": {"value": 0.010000, "rtol": 1e-4}, "log.final.el.EnvTidalQ": {"value": -1.000000, "rtol": 1e-4}, "log.final.el.OceanTidalQ": {"value": -1.000000, "rtol": 1e-4}, "log.final.el.TideLock": {"value": 1.000000, "rtol": 1e-4}, "log.final.el.RotTimeEqtide": { "value": 1.192290e303, "unit": u.sec, "rtol": 1e-4, }, "log.final.el.EnvK2": {"value": 0.500000, "rtol": 1e-4}, "log.final.el.OblTimeEqtide": {"value": -1.000000, "rtol": 1e-4}, "log.final.el.PowerEqtide": {"value": 1.862016e19, "unit": u.W, "rtol": 1e-4}, "log.final.el.SurfEnFluxEqtide": { "value": 34.098849, "unit": u.kg / u.sec ** 3, "rtol": 1e-4, }, "log.final.el.SurfWaterMass": {"value": 0.000000, "unit": u.kg, "rtol": 1e-4}, "log.final.el.EnvelopeMass": { "value": 0.986370, "unit": u.Mearth, "rtol": 1e-4, }, "log.final.el.OxygenMass": {"value": 0.000000, "unit": u.kg, "rtol": 1e-4}, "log.final.el.RGLimit": {"value": 3.127704e09, "unit": u.m, "rtol": 1e-4}, "log.final.el.XO": {"value": 0.000000, "rtol": 1e-4}, "log.final.el.EtaO": {"value": 0.000000, "rtol": 1e-4}, "log.final.el.PlanetRadius": { "value": 32.683276, "unit": u.Rearth, "rtol": 1e-4, }, "log.final.el.OxygenMantleMass": { "value": 0.000000, "unit": u.kg, "rtol": 1e-4, }, "log.final.el.RadXUV": {"value": -1.000000, "unit": u.m, "rtol": 1e-4}, "log.final.el.RadSolid": {"value": -1.000000, "unit": u.m, "rtol": 1e-4}, "log.final.el.PresXUV": {"value": 5.000000, "rtol": 1e-4}, "log.final.el.ScaleHeight": {"value": -1.000000, "unit": u.m, "rtol": 1e-4}, "log.final.el.ThermTemp": {"value": 400.000000, "unit": u.K, "rtol": 1e-4}, "log.final.el.AtmGasConst": {"value": 4124.000000, "rtol": 1e-4}, "log.final.el.PresSurf": {"value": -1.000000, "unit": u.Pa, "rtol": 1e-4}, "log.final.el.DEnvMassDt": { "value": -2.614005e09, "unit": u.kg / u.sec, "rtol": 1e-4, }, "log.final.el.FXUV": {"value": 0.073463, "unit": u.W / u.m ** 2, "rtol": 1e-4}, "log.final.el.AtmXAbsEffH2O": {"value": 0.300000, "rtol": 1e-4}, "log.final.el.RocheRadius": {"value": 1.817114e08, "unit": u.m, "rtol": 1e-4}, "log.final.el.BondiRadius": {"value": 7.982897e08, "unit": u.m, "rtol": 1e-4}, "log.final.el.HEscapeRegime": {"value": 3.000000, "rtol": 1e-4}, "log.final.el.RRCriticalFlux": { "value": 0.000139, "unit": u.W / u.m ** 2, "rtol": 1e-4, }, "log.final.el.KTide": {"value": 1.000000, "rtol": 1e-4}, "log.final.el.RGDuration": {"value": 1.00000e06, "unit": u.yr, "rtol": 1e-4}, "log.final.rr.Mass": {"value": 1.999399, "unit": u.Mearth, "rtol": 1e-4}, "log.final.rr.Obliquity": {"value": 0.000000, "unit": u.rad, "rtol": 1e-4}, "log.final.rr.PrecA": {"value": 0.000000, "unit": u.rad, "rtol": 1e-4}, "log.final.rr.Xobl": {"value": 1.563665e-162, "rtol": 1e-4}, "log.final.rr.Yobl": {"value": 0.000000, "rtol": 1e-4}, "log.final.rr.Zobl": {"value": 1.000000, "rtol": 1e-4}, "log.final.rr.Radius": {"value": 2.095926e08, "unit": u.m, "rtol": 1e-4}, "log.final.rr.RadGyra": {"value": 0.400000, "rtol": 1e-4}, "log.final.rr.RotAngMom": { "value": 5.561691e35, "unit": (u.kg * u.m ** 2) / u.sec, "rtol": 1e-4, }, "log.final.rr.RotKinEnergy": { "value": 1.842803e30, "unit": u.Joule, "rtol": 1e-4, }, "log.final.rr.RotVel": { "value": 1388.922578, "unit": u.m / u.sec, "rtol": 1e-4, }, "log.final.rr.BodyType": {"value": 0.000000, "rtol": 1e-4}, "log.final.rr.RotRate": { "value": 6.626773e-06, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.rr.RotPer": {"value": 10.973977, "unit": u.day, "rtol": 1e-4}, "log.final.rr.Density": { "value": 0.309611, "unit": u.kg / u.m ** 3, "rtol": 1e-4, }, "log.final.rr.SurfEnFluxTotal": { "value": 33.332187, "unit": u.kg / u.sec ** 3, "rtol": 1e-4, }, "log.final.rr.TidalQ": {"value": -1.000000e05, "rtol": 1e-4}, "log.final.rr.ImK2": {"value": -5.000000e-06, "rtol": 1e-4}, "log.final.rr.K2": {"value": 0.500000, "rtol": 1e-4}, "log.final.rr.K2Man": {"value": 0.300000, "rtol": 1e-4}, "log.final.rr.Imk2Man": {"value": -0.003000, "rtol": 1e-4}, "log.final.rr.TidalQMantle": {"value": 100.000000, "rtol": 1e-4}, "log.final.rr.HEcc": {"value": 0.000000, "rtol": 1e-4}, "log.final.rr.HZLimitDryRunaway": { "value": 3.043303e09, "unit": u.m, "rtol": 1e-4, }, "log.final.rr.HZLimRecVenus": {"value": 2.502002e09, "unit": u.m, "rtol": 1e-4}, "log.final.rr.HZLimRunaway": {"value": 3.267138e09, "unit": u.m, "rtol": 1e-4}, "log.final.rr.HZLimMoistGreenhouse": { "value": 3.310536e09, "unit": u.m, "rtol": 1e-4, }, "log.final.rr.HZLimMaxGreenhouse": { "value": 5.611497e09, "unit": u.m, "rtol": 1e-4, }, "log.final.rr.HZLimEarlyMars": { "value": 6.122597e09, "unit": u.m, "rtol": 1e-4, }, "log.final.rr.Instellation": { "value": 73.379922, "unit": u.kg / u.sec ** 3, "rtol": 1e-4, }, "log.final.rr.KEcc": {"value": 0.068275, "rtol": 1e-4}, "log.final.rr.Eccentricity": {"value": 0.068275, "rtol": 1e-4}, "log.final.rr.OrbEnergy": { "value": -5.480386e34, "unit": u.Joule, "rtol": 1e-4, }, "log.final.rr.MeanMotion": { "value": 6.626773e-06, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.rr.OrbPeriod": {"value": 9.481516e05, "unit": u.sec, "rtol": 1e-4}, "log.final.rr.SemiMajorAxis": {"value": 0.096645, "unit": u.au, "rtol": 1e-4}, "log.final.rr.CriticalSemiMajorAxis": { "value": -1.000000, "unit": u.m, "rtol": 1e-4, }, "log.final.rr.COPP": {"value": 0.000000, "rtol": 1e-4}, "log.final.rr.OrbAngMom": { "value": 1.650154e40, "unit": (u.kg * u.m ** 2) / u.sec, "rtol": 1e-4, }, "log.final.rr.LongP": {"value": 0.000000, "unit": u.rad, "rtol": 1e-4}, "log.final.rr.LXUVTot": { "value": -1.000000, "unit": u.kg / u.sec ** 3, "rtol": 1e-4, }, "log.final.rr.TotOrbEnergy": { "value": -1.740032e35, "unit": u.Joule, "rtol": 1e-4, }, "log.final.rr.OrbPotEnergy": { "value": -1.096077e35, "unit": u.Joule, "rtol": 1e-4, }, "log.final.rr.LostEnergy": { "value": 2.725921e33, "unit": u.Joule, "rtol": 1e-4, }, "log.final.rr.TidalRadius": {"value": 2.095926e08, "unit": u.m, "rtol": 1e-4}, "log.final.rr.DsemiDtEqtide": { "value": -4.999833e-06, "unit": u.m / u.sec, "rtol": 1e-4, }, "log.final.rr.DeccDtEqtide": { "value": -2.532564e-15, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.rr.DMeanMotionDtEqtide": { "value": 3.437522e-21, "unit": 1 / u.sec ** 2, "rtol": 1e-4, }, "log.final.rr.DOrbPerDtEqtide": {"value": -4.918370e-10, "rtol": 1e-4}, "log.final.rr.EccTimeEqtide": { "value": 2.695885e13, "unit": u.sec, "rtol": 1e-4, }, "log.final.rr.SemiTimeEqtide": { "value": 2.891664e15, "unit": u.sec, "rtol": 1e-4, }, "log.final.rr.DHEccDtEqtide": { "value": -0.000000, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.rr.DKEccDtEqtide": { "value": -2.532564e-15, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.rr.DXoblDtEqtide": { "value": 0.000000, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.rr.DYoblDtEqtide": { "value": 0.000000, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.rr.DZoblDtEqtide": { "value": 0.000000, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.rr.LockTime": {"value": 1.711407e11, "unit": u.sec, "rtol": 1e-4}, "log.final.rr.BodyDsemiDtEqtide": {"value": -1.000000, "rtol": 1e-4}, "log.final.rr.BodyDeccDt": {"value": -1.000000, "rtol": 1e-4}, "log.final.rr.DOblDtEqtide": { "value": 0.000000, "unit": u.rad / u.sec, "rtol": 1e-4, }, "log.final.rr.DRotPerDtEqtide": {"value": -7.959031e-298, "rtol": 1e-4}, "log.final.rr.DRotRateDtEqtide": { "value": 5.562685e-309, "unit": 1 / u.sec ** 2, "rtol": 1e-4, }, "log.final.rr.EqRotRateDiscrete": { "value": 6.626773e-06, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.rr.EqRotPerDiscrete": { "value": 9.481516e05, "unit": u.sec, "rtol": 1e-4, }, "log.final.rr.EqRotRateCont": { "value": 6.920233e-06, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.rr.EqRotPerCont": { "value": 9.079442e05, "unit": u.sec, "rtol": 1e-4, }, "log.final.rr.EqRotPer": {"value": 9.481516e05, "unit": u.sec, "rtol": 1e-4}, "log.final.rr.EqTidePower": { "value": 0.000000, "unit": 1 / u.sec, "rtol": 1e-4, }, "log.final.rr.GammaRot": {"value": -1.000000, "unit": u.sec, "rtol": 1e-4}, "log.final.rr.GammaOrb": {"value": -1.000000, "unit": u.sec, "rtol": 1e-4}, "log.final.rr.OceanK2": {"value": 0.010000, "rtol": 1e-4}, "log.final.rr.EnvTidalQ": {"value": -1.000000, "rtol": 1e-4}, "log.final.rr.OceanTidalQ": {"value": -1.000000, "rtol": 1e-4}, "log.final.rr.TideLock": {"value": 1.000000, "rtol": 1e-4}, "log.final.rr.RotTimeEqtide": { "value": 1.191290e303, "unit": u.sec, "rtol": 1e-4, }, "log.final.rr.EnvK2": {"value": 0.500000, "rtol": 1e-4}, "log.final.rr.OblTimeEqtide": {"value": -1.000000, "rtol": 1e-4}, "log.final.rr.PowerEqtide": {"value": 1.895236e19, "unit": u.W, "rtol": 1e-4}, "log.final.rr.SurfEnFluxEqtide": { "value": 34.332187, "unit": u.kg / u.sec ** 3, "rtol": 1e-4, }, "log.final.rr.SurfWaterMass": {"value": 0.000000, "unit": u.kg, "rtol": 1e-4}, "log.final.rr.EnvelopeMass": { "value": 0.999399, "unit": u.Mearth, "rtol": 1e-4, }, "log.final.rr.OxygenMass": {"value": 0.000000, "unit": u.kg, "rtol": 1e-4}, "log.final.rr.RGLimit": {"value": 3.127270e09, "unit": u.m, "rtol": 1e-4}, "log.final.rr.XO": {"value": 0.000000, "rtol": 1e-4}, "log.final.rr.EtaO": {"value": 0.000000, "rtol": 1e-4}, "log.final.rr.PlanetRadius": { "value": 32.861293, "unit": u.Rearth, "rtol": 1e-4, }, "log.final.rr.OxygenMantleMass": { "value": 0.000000, "unit": u.kg, "rtol": 1e-4, }, "log.final.rr.RadXUV": {"value": -1.000000, "unit": u.m, "rtol": 1e-4}, "log.final.rr.RadSolid": {"value": -1.000000, "unit": u.m, "rtol": 1e-4}, "log.final.rr.PresXUV": {"value": 5.000000, "rtol": 1e-4}, "log.final.rr.ScaleHeight": {"value": -1.000000, "unit": u.m, "rtol": 1e-4}, "log.final.rr.ThermTemp": {"value": 400.000000, "unit": u.K, "rtol": 1e-4}, "log.final.rr.AtmGasConst": {"value": 4124.000000, "rtol": 1e-4}, "log.final.rr.PresSurf": {"value": -1.000000, "unit": u.Pa, "rtol": 1e-4}, "log.final.rr.DEnvMassDt": { "value": -1.147322e08, "unit": u.kg / u.sec, "rtol": 1e-4, }, "log.final.rr.FXUV": {"value": 0.073380, "unit": u.W / u.m ** 2, "rtol": 1e-4}, "log.final.rr.AtmXAbsEffH2O": {"value": 0.300000, "rtol": 1e-4}, "log.final.rr.RocheRadius": {"value": 1.822097e08, "unit": u.m, "rtol": 1e-4}, "log.final.rr.BondiRadius": {"value": 8.033012e08, "unit": u.m, "rtol": 1e-4}, "log.final.rr.HEscapeRegime": {"value": 6.000000, "rtol": 1e-4}, "log.final.rr.RRCriticalFlux": { "value": 0.000139, "unit": u.W / u.m ** 2, "rtol": 1e-4, }, "log.final.rr.KTide": {"value": 1.000000, "rtol": 1e-4}, "log.final.rr.RGDuration": {"value": 1.00000e06, "unit": u.yr, "rtol": 1e-4}, } )
[ 11748, 6468, 28338, 13, 41667, 355, 334, 198, 11748, 12972, 9288, 198, 6738, 18335, 1330, 25187, 4102, 11, 18335, 628, 198, 31, 26968, 4102, 7, 198, 220, 220, 220, 1391, 198, 220, 220, 220, 220, 220, 220, 220, 366, 6404, 13, 36733, ...
1.754299
51,404
#!/usr/bin/python # Copyright (c) 2013, 2014-2017 Oracle and/or its affiliates. All rights reserved. """Provide Module Description """ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# __author__ = "Andrew Hopkinson (Oracle Cloud Solutions A-Team)" __copyright__ = "Copyright (c) 2013, 2014-2017 Oracle and/or its affiliates. All rights reserved." __ekitversion__ = "@VERSION@" __ekitrelease__ = "@RELEASE@" __version__ = "1.0.0.0" __date__ = "@BUILDDATE@" __status__ = "Development" __module__ = "upload_storage_object" # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~# import datetime import getopt import hashlib import json import locale import logging import multiprocessing import operator import os import requests import shutil import subprocess import sys import tempfile from contextlib import closing # Import utility methods from oscsutils import callRESTApi from oscsutils import getPassword from oscsutils import printJSON from authenticate_oscs import authenticate from oc_exceptions import REST401Exception # Define methods # Read Module Arguments # Main processing function # Main function to kick off processing if __name__ == "__main__": main(sys.argv[1:])
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 15069, 357, 66, 8, 2211, 11, 1946, 12, 5539, 18650, 290, 14, 273, 663, 29116, 13, 1439, 2489, 10395, 13, 628, 198, 37811, 15946, 485, 19937, 12489, 198, 37811, 198, 198, 2, 220, 27156, ...
3.699422
346
''' Module for SNooPy to download/parse data from the Open Supernova Catalog. ''' from __future__ import print_function import six import json if six.PY3: import urllib.request as urllib else: import urllib from astropy.coordinates import Angle from snpy import sn,lc,fset from numpy import array,log10 import astropy.units as u from snpy.filters import spectrum from snpy.specobj import timespec # Some well-known publications and their mappings: pubs = { '1999AJ....117..707R': # Riess et al. (1999) Standard Photometry CfAbands, '2006AJ....131..527J': # Jha et al. (2006) Standard Photometry CfAbands, '2009ApJ...700..331H': # Hicken et al. (2009) CfA3 Natural Photometry CfAbands, '2012ApJS..200...12H': # Hicken et al. (2012) CfA4 Natural Photometry CfAbands } # telescope,band --> SNooPy filter database # We do this by matching (band,system,telescope,observatory) info from the # database to SNooPy filters. ftrans = {} ftrans_standard = {} standard_warnings = {} for band in ['u','g','r','i','B','V','Y','J','H','K']: ftrans[(band,"CSP",'',"LCO")] = band for band in ['U','B','V','R','I']: ftrans[(band,'','kait2','')] = band+'kait' for band in ['U','B','V','R','I']: ftrans[(band,'','kait3','')] = band+'kait' for band in ['J','H','Ks']: ftrans[(band,'','PAIRITEL','')] = band+'2m' for band in ['B','V','R','I']: ftrans[(band,'','kait4', '')] = band+'kait' for band in ['U','V','B']: ftrans[(band, 'Vega','Swift','')] = band+"_UVOT" for band in ['UVW1','UVW2','UVM2']: ftrans[(band, 'Vega','Swift','')] = band for band in ['g','r','i','z']: ftrans[(band, '', 'PS1','')] = "ps1_"+band # These are for data in (what I'm assuming) would be standard filters. # We will issue a warning, though. for band in ['U','B','V','R','I']: ftrans_standard[(band,'','','')] = band+"s" standard_warnings[band] = "Johnson/Kron/Cousins " for band in ['u','g','r','i','z']: ftrans_standard[(band,'','','')] = band+"_40" standard_warnings[band] = "Sloan (APO) " for band in ["u'","g'","r'","i'","z'"]: ftrans_standard[(band,'','','')] = band[0]+"_40" standard_warnings[band] = "Sloan (USNO-40) " for band in ["J","H","Ks"]: ftrans_standard[(band[0],'','','')] = band+"2m" standard_warnings[band[0]] = "2MASS " # Our own photometric systems: def CSP_systems(filt, MJD): '''Given a filter name and MJD date, output the correct telescope and system information.''' if filt == "V": if MJD < 53748.0: return (dict(telescope='Swope',instrument='Site2',band='V-3014', zeropoint="{:.4f}".format(fset['V0'].zp))) elif MJD < 53759.0: return (dict(telescope='Swope',instrument='Site2',band='V-3009', zeropoint="{:.4f}".format(fset['V1'].zp))) elif MJD < 56566.0: return (dict(telescope='Swope',instrument='Site2',band='V-9844', zeropoint="{:.4f}".format(fset['V'].zp))) else: return (dict(telescope='Swope',instrument='e2v',band='V-9844', zeropoint="{:.4f}".format(fset['V2'].zp))) if filt == "Jrc2": return (dict(telescope='Swope',instrument='RetroCam',band='J', zeropoint="{:.4f}".format(fset[filt].zp))) if filt in ['u','g','r','i','B']: if MJD < 56566.0: return (dict(telescope='Swope',instrument='Site2',band=filt, zeropoint="{:.4f}".format(fset[filt].zp))) else: return (dict(telescope='Swope',instrument='e2v',band=filt, zeropoint="{:.4f}".format(fset[filt+'2'].zp))) if filt in ['Y','J','H']: if MJD < 55743.0: return (dict(telescope='Swope',instrument='RetroCam',band=filt, zeropoint="{:.4f}".format(fset[filt].zp))) else: return (dict(telescope='DuPont',instrument='RetroCam',band=filt, zeropoint="{:.4f}".format(fset[filt+'d'].zp))) return({}) MJD_offsets = { 'MJD':0, 'JD':-2400000.5 } warning_message = { 'upperlims_noerr':'Warning: Data lacking errorbars or with upper-limits not imported', 'upperlims':'Warning: Data with upper-limits not imported', } OSC_template = '''https://sne.space/astrocats/astrocats/supernovae/output/json/{}.json''' def get_obj(url, full_data=True, allow_no_errors=False, missing_error=0.01): '''Attempt to build a SNooPy object from a Open Supernova Catalog server URL.''' if url.find('osc:') == 0: # Try to construct a url based only on a name. url = OSC_template.format(url.split(':')[1]) try: uf = urllib.urlopen(url) except: return None,"Invalid URL" try: d = json.load(uf) except: uf.close() if full_data: return None,"Failed to decode JSON",None return None,"Failed to decode JSON" else: uf.close() # We now have the JSON data. Get the info we need d = list(d.values())[0] name = d['name'] if 'redshift' not in d or 'ra' not in d or 'dec' not in d: return None,"No redshift, RA, or DEC found" zhel = float(d['redshift'][0]['value']) ra = Angle(" ".join([d['ra'][0]['value'],d['ra'][0]['u_value']])).degree decl = Angle(" ".join([d['dec'][0]['value'],d['dec'][0]['u_value']])).degree snobj = sn(name, ra=ra, dec=decl, z=zhel) # All primary sources all_sources_dict = [item for item in d['sources'] \ if not item.get('secondary',False)] all_sources_dict2 = [item for item in d['sources'] \ if item.get('secondary',False)] all_sources = {} for source in all_sources_dict: all_sources[source['alias']] = (source.get('bibcode',''), source.get('reference','')) all_sources2 = {} for source in all_sources_dict2: all_sources2[source['alias']] = (source.get('bibcode',''), source.get('reference','')) # Next, the photometry. used_sources = [] MJD = {} mags = {} emags = {} sids = {} known_unknowns = [] unknown_unknowns = [] warnings = [] photometry = d.get('photometry', []) for p in photometry: if p.get('upperlimit',False): continue t = (p.get('band',''),p.get('system',''),p.get('telescope',''), p.get('observatory','')) # Deal with source of photometry ss = p.get('source').split(',') this_source = None for s in ss: if s in all_sources: this_source = all_sources[s] break if this_source is None: for s in ss: if s in all_sources2: this_source = all_sources2[s] if this_source is None: print("Warning: no primary source, skipping") continue bibcode = this_source[0] if bibcode in pubs: b = pubs[bibcode](t[0],float(p['time'])) elif t in ftrans: b = ftrans[t] elif t in ftrans_standard: b = ftrans_standard[t] if t not in known_unknowns: known_unknowns.append(t) print("Warning: no telescope/system info, assuming ", \ standard_warnings[b[0]], b[0]) elif (t[0],"","","") in ftrans_standard: b = ftrans_standard[(t[0],"","","")] if t not in known_unknowns: known_unknowns.append(t) print("Warning: telescope/system defined by %s/%s/%s not "\ "recognized, assuming %s %s" %\ (t[1],t[2],t[3],standard_warnings[t[0]],t[0])) else: # No idea if t not in unknown_unknowns: unknown_unknowns.append(t) print("Warning: telescope/system defined by %s/%s/%s not "\ "recognized and can't figure out the filter %s" % \ (t[1],t[2],t[3],t[0])) unknown_unknowns.append(t) continue if b not in MJD: MJD[b] = [] mags[b] = [] emags[b] = [] sids[b] = [] if 'time' in p and 'magnitude' in p: if not allow_no_errors and 'e_magnitude' not in p and\ 'e_lower_magnitude' not in p and 'e_upper_magnitude' not in p: if 'upperlims' not in warnings: warnings.append('upperlims') continue MJD[b].append(float(p['time'])) mags[b].append(float(p['magnitude'])) if 'e_magnitude' in p: emags[b].append(float(p['e_magnitude'])) elif 'e_lower_magnitude' in p and 'e_upper_magnitude' in p: emags[b].append((float(p['e_lower_magnitude']) +\ float(p['e_upper_magnitude']))/2) else: emags[b].append(missing_error) elif 'time' in p and 'countrate' in p and 'zeropoint' in p: if not allow_no_errors and 'e_countrate' not in p: if 'upperlims' not in warnings: warnings.append('upperlims') continue if float(p['countrate']) < 0: continue MJD[b].append(float(p['time'])) mags[b].append(-2.5*log10(float(p['countrate'])) + \ float(p['zeropoint'])) ec = p.get('e_countrate',None) if ec is not None: emags[b].append(1.087*float(p['e_countrate'])/float(p['countrate'])) else: emags[b].append(missing_error) else: if 'upperlims_noerr' not in warnings: warnings.append('upperlims_noerr') continue if this_source not in used_sources: used_sources.append(this_source) # At this point we're actually using the photometry, so find source sid = used_sources.index(this_source) sids[b].append(sid) for b in MJD: if len(MJD[b]) > 0: snobj.data[b] = lc(snobj, b, array(MJD[b]), array(mags[b]), array(emags[b]), sids=array(sids[b], dtype=int)) snobj.data[b].time_sort() snobj.sources = used_sources snobj.get_restbands() if len(unknown_unknowns) > 0: unknown_unknowns = list(set(unknown_unknowns)) print("Warning: the following photometry was not recognized by SNooPy") print("and was not imported:") for item in unknown_unknowns: print(item) if warnings: for warning in warnings: print(warning_message[warning]) # lastly, the spectroscopy if d.get('spectra',None) is not None: spectra = [] dates = [] sids = [] for s in d['spectra']: wu = s.get('u_wavelengths', 'Agnstrom') fu = s.get('u_fluxes', 'Uncalibrated') try: wu = u.Unit(wu) except ValueError: print("Warning: unrecognized unit for wavelength: {}".format(wu)) print(" assuming Angstroms") wu = u.Angstrom if fu == 'Uncalibrated': fluxed = False fu = u.dimensionless_unscaled else: try: fu = u.Unit(fu) fluxed = True except ValueError: print("Warning: unrecognized unit for flux: {}".format(fu)) fluxed = False fu = u.dimensionless_unscaled tu = s.get('u_time', 'MJD') t = float(s['time']) if tu not in MJD_offsets: print("Warning: unrecognized time unit: {}".format(tu)) if len(s['time'].split('.')[0]) == 7 and s['time'][0] == '2': print(" assuming JD") t = t - 2400000.5 elif len(s['time'].split('.')[0]) == 5 and s['time'][0] == '5': print(" assuming MJD") else: print(" skipping this spectrum.") continue w = array([float(item[0]) for item in s['data']])*wu f = array([float(item[1]) for item in s['data']])*fu dr = s.get('deredshifted', False) if dr: w = w*(1+zhel) # At this point, we should be able to convert to the units we want w = w.to('Angstrom').value if fluxed: f = f.to('erg / (s cm2 Angstrom)') f = f.value # source reference srcs = s.get('source','').split(',') this_source = None for src in srcs: if src in all_sources: this_source = all_sources[src] break if this_source is None: print("Warning: spectrum has no source") if this_source not in used_sources: used_sources.append(this_source) # At this point we're actually using the spectroscopy, so find source sid = used_sources.index(this_source) sids.append(sid) spectra.append(spectrum(wave=w, flux=f, fluxed=fluxed, name="Spectrum MJD={:.1f}".format(t))) dates.append(t) snobj.sdata = timespec(snobj, dates, spectra) snobj.sdata.sids = sids if full_data: # make a dictionary of the remaining OSC meta data and make it a member # variable snobj.osc_meta = {} for key in d.keys(): if key not in ['name','redshift','ra','dec','sources','photometry', 'spectra']: snobj.osc_meta[key] = d[key] return(snobj,'Success') def to_osc(s, ref=None, bibcode=None, source=1): '''Given a supernova object, s, output to JSON format suitable for upload to the OSC.''' data = {s.name:{"name":s.name}} if ref or bibcode: sources = [dict(bibcode=bibcode, name=ref, alias=str(source))] data['sources'] = sources phot = [] for filt in s.data: for i in range(len(s.data[filt].MJD)): datum = dict(survey='CSP', observatory='LCO') datum.update(CSP_systems(filt, s.data[filt].MJD[i])) datum['time'] = "{:.3f}".format(s.data[filt].MJD[i]) datum['u_time'] = "MJD" datum['magnitude'] = "{:.3f}".format(s.data[filt].mag[i]) flux,eflux = s.data[filt].flux[i],s.data[filt].e_flux[i] datum['flux'] = "{:.5f}".format(flux) datum['u_flux'] = "s^-1 cm^-2" datum['e_flux'] = "{:.5f}".format(eflux) datum['e_upper_magnitude'] = "{:.3f}".format( -2.5*log10((flux-eflux)/flux)) datum['e_lower_magnitude'] = "{:.3f}".format( -2.5*log10(flux/(flux+eflux))) datum['source'] = "{}".format(source) phot.append(datum) data['photometry'] = phot return json.dumps(data, indent=4)
[ 7061, 6, 198, 26796, 329, 11346, 2238, 20519, 284, 4321, 14, 29572, 1366, 422, 262, 4946, 3115, 38438, 44515, 13, 198, 7061, 6, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 11748, 2237, 198, 11748, 33918, 198, 361, 22...
2.044028
7,041
from menu import Menu, MenuItem from coffee_maker import CoffeeMaker from money_machine import MoneyMachine money_machine = MoneyMachine() coffee_maker = CoffeeMaker() menu = Menu() coffee_maker.report() money_machine.report() coffee_machine_is_on = True while coffee_machine_is_on: choices = menu.get_items() user_order = input(f'Please choose a coffee: ({choices})>>> ') if user_order == 'off': coffee_machine_is_on = False elif user_order == 'report': coffee_maker.report() money_machine.report() else: drink = menu.find_drink(user_order) if coffee_maker.is_resource_sufficient(drink) and money_machine.make_payment(drink.cost): coffee_maker.make_coffee(drink)
[ 6738, 6859, 1330, 21860, 11, 21860, 7449, 198, 6738, 6891, 62, 10297, 1330, 19443, 48890, 198, 6738, 1637, 62, 30243, 1330, 12911, 37573, 198, 198, 26316, 62, 30243, 796, 12911, 37573, 3419, 198, 1073, 5853, 62, 10297, 796, 19443, 48890, ...
2.657143
280
# Copyright (c) 2013-2018, Rethink Robotics Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import errno import rospy import intera_dataflow from intera_core_msgs.msg import ( DigitalIOState, DigitalOutputCommand, ) class DigitalIO(object): """ DEPRECATION WARNING: This interface will likely be removed in the future. Transition to using the IO Framework and the wrapper classes: gripper.py, cuff.py, camera.py Interface class for a simple Digital Input and/or Output on the Intera robots. Input - read input state Output - turn output On/Off - read current output state """ def __init__(self, component_id): """ Constructor. @param component_id: unique id of the digital component """ self._id = component_id self._component_type = 'digital_io' self._is_output = False self._state = None self.state_changed = intera_dataflow.Signal() type_ns = '/robot/' + self._component_type topic_base = type_ns + '/' + self._id self._sub_state = rospy.Subscriber( topic_base + '/state', DigitalIOState, self._on_io_state) intera_dataflow.wait_for( lambda: self._state != None, timeout=2.0, timeout_msg="Failed to get current digital_io state from %s" \ % (topic_base,), ) # check if output-capable before creating publisher if self._is_output: self._pub_output = rospy.Publisher( type_ns + '/command', DigitalOutputCommand, queue_size=10) def _on_io_state(self, msg): """ Updates the internally stored state of the Digital Input/Output. """ new_state = (msg.state == DigitalIOState.PRESSED) if self._state is None: self._is_output = not msg.isInputOnly old_state = self._state self._state = new_state # trigger signal if changed if old_state is not None and old_state != new_state: self.state_changed(new_state) @property def is_output(self): """ Accessor to check if IO is capable of output. """ return self._is_output @property def state(self): """ Current state of the Digital Input/Output. """ return self._state @state.setter def state(self, value): """ Control the state of the Digital Output. (is_output must be True) @type value: bool @param value: new state to output {True, False} """ self.set_output(value) def set_output(self, value, timeout=2.0): """ Control the state of the Digital Output. Use this function for finer control over the wait_for timeout. @type value: bool @param value: new state {True, False} of the Output. @type timeout: float @param timeout: Seconds to wait for the io to reflect command. If 0, just command once and return. [0] """ if not self._is_output: raise IOError(errno.EACCES, "Component is not an output [%s: %s]" % (self._component_type, self._id)) cmd = DigitalOutputCommand() cmd.name = self._id cmd.value = value self._pub_output.publish(cmd) if not timeout == 0: intera_dataflow.wait_for( test=lambda: self.state == value, timeout=timeout, rate=100, timeout_msg=("Failed to command digital io to: %r" % (value,)), body=lambda: self._pub_output.publish(cmd) )
[ 2, 15069, 357, 66, 8, 2211, 12, 7908, 11, 371, 2788, 676, 47061, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11...
2.363787
1,806
# -*- coding: utf-8 -*- # Copyright 2016 Yelp 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 __future__ import absolute_import from __future__ import unicode_literals import pytest from replication_handler.models.mysql_dumps import MySQLDumps @pytest.mark.itest @pytest.mark.itest_db
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 1584, 44628, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428...
3.5
228
# import dependencies from flask import Flask, jsonify, render_template, request, redirect from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func, inspect import pandas as pd import numpy as np import datetime as dt # database setup using automap engine = create_engine("sqlite:///chi_db.sqlite") Base = automap_base() # reflect the tables Base.prepare(engine, reflect=True) # Save references to the tables AllCrime = Base.classes.all_crime # Create our session (link) from Python to the DB session = Session(engine) # initialize Flask app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///chi_db.sqlite" @app.route("/crimehistory") if __name__ == "__main__": app.run(debug=True)
[ 2, 1330, 20086, 198, 6738, 42903, 1330, 46947, 11, 33918, 1958, 11, 8543, 62, 28243, 11, 2581, 11, 18941, 198, 6738, 44161, 282, 26599, 13, 2302, 13, 2306, 296, 499, 1330, 3557, 499, 62, 8692, 198, 6738, 44161, 282, 26599, 13, 579, ...
3.070039
257
# -*- coding: utf-8 -*- import os import sys from logging import getLogger from typing import Any, List, Tuple import cv2 import numpy as np import torch from bidi.algorithm import get_display from .detection import get_detector, get_textbox from .imgproc import loadImage from .recognition import get_recognizer, get_text from .settings import * from .utils import calculate_md5, download_and_unzip, get_image_list, get_paragraph, group_text_box if sys.version_info[0] == 2: from io import open from six.moves.urllib.request import urlretrieve from pathlib2 import Path else: from urllib.request import urlretrieve from pathlib import Path LOGGER = getLogger(__name__)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 11748, 28686, 198, 11748, 25064, 198, 6738, 18931, 1330, 651, 11187, 1362, 198, 6738, 19720, 1330, 4377, 11, 7343, 11, 309, 29291, 198, 198, 11748, 269, 85, 17, 198...
3.017316
231
# local from src.utils.images import ImagesHelper from src.dtypes import ImagesInner
[ 2, 1957, 198, 6738, 12351, 13, 26791, 13, 17566, 1330, 5382, 47429, 198, 6738, 12351, 13, 67, 19199, 1330, 5382, 818, 1008, 628 ]
3.73913
23
import sys import os sys.path.append(os.path.abspath(".")) sys.dont_write_bytecode = True __author__ = "bigfatnoob" import copy import signal import time import re import rpy2 import rpy2.robjects as robjects from rpy2 import rinterface from rpy2.robjects import pandas2ri from rpy2.robjects.functions import SignatureTranslatedFunction from collections import OrderedDict from analysis.helpers import constants as a_consts from analysis import execute from misconceptions.common import datatypes from misconceptions.rUtils import generator, dataframer from utils import cache pandas2ri.activate() rinterface.set_writeconsole_warnerror(None) rinterface.set_writeconsole_regular(None) r_source = robjects.r['source'] R_GEN_PREFIX = "gen_func_r_" FUNC_BODY_REGEX = r'function\s*\(.*?\)\s*((.|\s)+)' FUNCTION_STORE = "/Users/panzer/Raise/ProgramRepair/CodeSeer/code/src/main/python/expt/r_functions.pkl"
[ 11748, 25064, 198, 11748, 28686, 198, 198, 17597, 13, 6978, 13, 33295, 7, 418, 13, 6978, 13, 397, 2777, 776, 7203, 526, 4008, 198, 17597, 13, 67, 756, 62, 13564, 62, 26327, 8189, 796, 6407, 198, 198, 834, 9800, 834, 796, 366, 14261,...
2.840491
326
from __future__ import annotations from typing import Match import pyjokes from bot.config import Config from bot.data import command from bot.data import esc from bot.data import format_msg @command('!joke', '!yoke')
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 198, 6738, 19720, 1330, 13225, 198, 198, 11748, 12972, 73, 3369, 198, 198, 6738, 10214, 13, 11250, 1330, 17056, 198, 6738, 10214, 13, 7890, 1330, 3141, 198, 6738, 10214, 13, 7890, 1330, 3671, 1...
3.484375
64
#!/usr/bin/env python import os import sys import logging import argparse import time import ngskit.barcodes as barcodes from ngskit.utils import fasta_tools, fastq_tools #import barcodes #from utils import fasta_tools, fastq_tools def trimming(demultiplexed_fastq, barcode, quality_threshold, trgt_len, output_fmt, output_folder): """Extract seq from the FASTAQ demultiplexed files. Trim barcodes + Constant Parameters ---------- demultiplexed_fastq : str Path of the demultiplexed fastq file barcode : barcode.object Barcode object wiht info about barcode and constant regions quality_threshold : int reading quality Threshold, any sequence will be trimmed under that level trgt_len : int length in bases of the target sequences. output_fmt : str Output format, by default fasta working_folder : str Output folder to save files with trimmed sequences Returns ------- output format save fasta or fastq Notes ----- Result str, in Fasta format >FASTAQ_ID+ length + Quality ATGATGGTAGTAGTAGAAAGATAGATGATGATGAT it will be storage: /data_path/Sequences/Sample_id.fasta """ # Init the output format, retunr a function logger = logging.getLogger(__name__) create_folder(output_folder) # if output_fmt == 'fasta': save_seq = fasta_tools.write_fasta_sequence filehdl_output = open(output_folder+'/'+barcode.id+'.fasta','a') logger.info('Output file: %s' % (output_folder+'/'+barcode.id+'.fasta')) if output_fmt == 'fastq': save_seq = fastq_tools.write_fastq_sequence filehdl_output = open(output_folder+'/'+barcode.id+'.fastq','a') logger.info('Output file: %s' % (output_folder+'/'+barcode.id+'.fastq')) # check barcodes integrity, peplength, fastq # barcodes_list = barcodes.read(barcode_file) # Stats nseqs = 0 ntrimed = 0 # Open Fastq file with open(demultiplexed_fastq, 'r') as read1: for read1_id in read1: # Read 4 by 4 # ID lane info, seq info etc # Read seq and Quality info read1_seq, read1_strand, read1_qual = [next(read1) for _ in range(3)] #Translate the Quality to a list of Integers qual = [ord(c)-33 for c in read1_qual.strip()] target_sequence = read1_seq[barcode.b1_len+barcode.c1_len: barcode.b1_len+barcode.c1_len+trgt_len] #remove the quality of the barcode and the constant region target_qual = qual[barcode.b1_len+barcode.c1_len: barcode.b1_len+barcode.c1_len+trgt_len] nseqs += 1 # Control try: avg_quality = sum(target_qual)/float(len(target_qual)) except ZeroDivisionError: logger.error('Sequence with no lenght or no score', exc_info=True) logger.error(read1_seq,read1_qual,target_qual,target_qual,trgt_len) sys.exit() if len(target_sequence) == trgt_len and avg_quality >= quality_threshold: ntrimed += 1 # save output format # attach Qavgm and length origin to the id seq_id = '{}_Q:{:.2f}_F:{}'.format(read1_id.strip(), avg_quality, trgt_len) save_seq([seq_id, target_sequence, target_qual], file_output=filehdl_output) # save else: # Stats pass logger.info('Read %i Sequences' % (nseqs)) logger.info('Trimmed %i Sequences' % (ntrimed)) filehdl_output.close() def get_options(): """Get arguments from command line. Parameters ---------- Returns ------- """ parser = argparse.ArgumentParser(description=""" Trimming Fastq sequences tool Usage Trimming: %prog -d [demultiplexed Folder]-b [BarCode_file.inp] -q [Quality threshold]\ -m [method] --output_fmt fasta """) parser.add_argument('-d', '--input_folder', action="store", dest="input_folder", default=False, help='Folder \ contains demultiplexed folders and files', required=True) parser.add_argument('-b', '--barcode_file', action="store", dest="barcode_file", default=False, help='File that \ contains barcodes and cosntant regions', required=True) parser.add_argument('-o', '--out_folder', action="store", dest="out_folder", default='Sequences', help='Output folder, called \ Sequences by default') # optional Arguments parser.add_argument('-m', '--trimming_method', action="store", dest="trimming_method", default='standard', type=str, choices=['standard', 'dynamic'], help="""standard Trimm sequences according barcode file configuration, ignores float window output files\n dynamic Trimm sequences using file lenght label, or output of float window demultiplex """) # Default 1 parser.add_argument('-q', '--quality', action="store", dest="quality", default=30, type=int, help='Quality reading threshold \ (default 30)') parser.add_argument('--output_fmt', help='Output format, default fasta', dest='output_fmt', default='fasta', action='store') parser.add_argument('--force-lenght', help='force a lenght and ignore file label, overwrites dynamic option', dest='force_lenght', default=False, action='store') options = parser.parse_args() return options def main(): """Pipeline Control. Parameters ---------- opts """ opts = get_options() # init logging time_stamp = time.ctime() seconds_time = int(time.time()) logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%m-%d %H:%M', filename= opts.input_folder+ '/Logs/Trimming_'+opts.input_folder.rpartition('/')[-1]+'_'+opts.barcode_file+'_{}.log'.format(seconds_time), filemode='w') logger = logging.getLogger(__name__) logger.info('JOB START {4} {1} {2} {0} {3}'.format(*time_stamp.split())) # DEMULTIPLEX # Check inputs # Load Barcodes info # check barcodes integrity, peplength, fastq barcodes_list = barcodes.read(opts.barcode_file) # make output folder # Init Logging logger.info('#### TRIMMING ####') # incompatible logger.info('Method: {}'.format(opts.trimming_method)) logger.info('Quality threshold: {}'.format(opts.quality)) logger.info('Output format: {}'.format(opts.output_fmt)) # logger.info('Barcode file: {}'.format(opts.barcode_file)) logger.info('Input folder: {}'.format(opts.input_folder)) output_folder = opts.input_folder+'/'+opts.out_folder logger.info('Output folder: {}'.format(output_folder)) logger.info('Force target lenght: %s', opts.force_lenght) # foreach sample in barcodes for barcode in barcodes_list: logger.info('Triming Sample: {}'.format(barcode.id)) # folder must == sample id in the barcode # TODO: need to improve this line, it can be problematic working_folder = './'+opts.input_folder+'/'+barcode.id+'/' # get all fastq under the folder for demultiplexed_fastq in os.listdir(working_folder): # ToDO: only get fastq files #ToDo: only those I want (target lenthg) # if method is dynamic, get all the files in the folder if opts.trimming_method == 'dynamic': # To do # read lenght from the filename seq_length = get_length_label(demultiplexed_fastq) # modifiy target size # Skip empty vectors if seq_length: # modify output folder dir_emultiplexed_fastq = working_folder+demultiplexed_fastq # trim! trimming(dir_emultiplexed_fastq, barcode, quality_threshold= opts.quality, trgt_len= seq_length, output_fmt= opts.output_fmt, output_folder=output_folder+'_'+str(seq_length)) # raw_name = demultiplexed_file.replace('_F.fastq','') # read the length from the file elif opts.trimming_method == 'standard': # Trim time dir_emultiplexed_fastq = working_folder+demultiplexed_fastq # ignore files from dynamic target seq_length = get_length_label(demultiplexed_fastq) if seq_length != barcode.trgt_len: logger.info("file label and barcode lenght are different: %s SKIPPING FILE", demultiplexed_fastq) continue else: logger.info('Triming file: {}'.format(demultiplexed_fastq)) trimming(dir_emultiplexed_fastq, barcode, quality_threshold= opts.quality, trgt_len= barcode.trgt_len, output_fmt= opts.output_fmt, output_folder=output_folder) # add here, multilenghts trimmming elif opts.trimming_method == 'force': # Todo: this option can be useful in the future continue else: # unknow method pass # DONE time_stamp = time.ctime() logger.info('JOB ENDS {4} {1} {2} {0} {3}'.format(*time_stamp.split())) return # def main(): # # Read argtments # opts = get_options() # # init logging # time_stamp = time.ctime() # logging.basicConfig(level=logging.INFO, # format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', # datefmt='%m-%d %H:%M', # filename= 'Trimming_'+opts.input_folder+'_'+opts.barcode_file+'_{4}_{1}_{2}_{0}_{3}.log'.format(*time_stamp.split()), # filemode='w') # logger = logging.getLogger(__name__) # logger.info('JOB START {4} {1} {2} {0} {3}'.format(*time_stamp.split())) # # DEMULTIPLEX # workflow(opts) # # DONE # time_stamp = time.ctime() # logger.info('JOB ENDS {4} {1} {2} {0} {3}'.format(*time_stamp.split())) if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 11748, 28686, 198, 11748, 25064, 198, 11748, 18931, 198, 11748, 1822, 29572, 198, 11748, 640, 198, 198, 11748, 23370, 8135, 270, 13, 65, 5605, 4147, 355, 2318, 40148, 198, 6738, 23370, 8...
2.057078
5,326
from checkov.yaml_doc.base_registry import Registry registry = Registry()
[ 6738, 2198, 709, 13, 88, 43695, 62, 15390, 13, 8692, 62, 2301, 4592, 1330, 33432, 198, 198, 2301, 4592, 796, 33432, 3419, 198 ]
3.26087
23
""" Internal api methods for current service. Example: from anthill.platform.api.internal import as_internal, InternalAPI @as_internal() async def your_internal_api_method(api: InternalAPI, *params, **options): # current_service = api.service ... """ from anthill.platform.api.internal import as_internal, InternalAPI @as_internal() @as_internal()
[ 37811, 198, 37693, 40391, 5050, 329, 1459, 2139, 13, 198, 198, 16281, 25, 628, 220, 220, 220, 422, 26794, 359, 13, 24254, 13, 15042, 13, 32538, 1330, 355, 62, 32538, 11, 18628, 17614, 628, 220, 220, 220, 2488, 292, 62, 32538, 3419, ...
3.039683
126
#!/usr/bin/env mdl # -*- coding: utf-8 -*- # ======================================= # File Name : # Purpose : # Creation Date : # Last Modified : # Created By : sunpeiqin # ======================================= import os import sys import argparse import magic import keyword import importlib import collections import re import tabulate import numpy as np import tensorflow as tf def import_python_source_as_module(fpath, mod_name=None): """ import a python source as a module; its directory is added to ``sys.path`` during importing, and ``sys.path`` would be restored afterwards. Modules newly loaded in the same directory as *fpath* would have an attribute `__dynamic_loaded_by_spq__` set to 1, and fpath itself would have that value set to 2. :type fpath: str :param fpath: python source file path :type mod_name: str or None :param mod_name: target module name; if it exists in `sys.modules`, the corresponding module would be directly returned; otherwise it is added to ``sys.modules`` afterward. If it is None, module name would be derived from *fpath* by replacing '/' to '.' and special chars to '_' """ fpath = os.path.realpath(fpath) if mod_name is None: # automatically generate mod_name mod_name = [] for i in fpath.split(os.path.sep): v = '' for j in i: if not j.isidentifier() and not j.isdigit(): j = '_' v += j if not v.isidentifier() or keyword.iskeyword(v): v = '_' + v assert v.isidentifier() and not keyword.iskeyword(v), ( 'failed to convert to python identifier: in={} out={}'.format( i, v)) mod_name.append(v) mod_name = '_'.join(mod_name) if mod_name in sys.modules: return sys.modules[mod_name] old_path = sys.path[:] mod_dir = os.path.dirname(fpath) sys.path.append(mod_dir) old_mod_names = set(sys.modules.keys()) try: final_mod = importlib.machinery.SourceFileLoader( mod_name, fpath).load_module() finally: sys.path.remove(mod_dir) sys.modules[mod_name] = final_mod for name, mod in list(sys.modules.items()): if name in old_mod_names: continue try: fpath = getattr(mod, '__file__', None) except Exception as exc: print('caught exception {} while trying to get ' 'read __file__ attr from {}'.format(repr(exc), name)) continue if fpath is not None and ( os.path.dirname(os.path.realpath(fpath)).startswith(mod_dir)): try: mod.__dynamic_loaded_by_spq__ = 1 except Exception: pass try: final_mod.__dynamic_loaded_by_spq__ = 2 except Exception: pass return final_mod def load_network(network, get_kwargs={}): '''load a model defined by model.py''' network = os.path.realpath(network) mf = magic.from_file(network, mime=True) mf = mf.decode('utf-8') if isinstance(mf, bytes) else mf if mf.startswith('text'): return import_python_source_as_module(network).Model().build() else: print('Only supports a model.py which defines a network') exit(0) if __name__ == "__main__": actions = [InfoAction,] parser = argparse.ArgumentParser() parser.add_argument('network') subparsers = parser.add_subparsers(help='action') for i in actions: i.add_subparser(subparsers) args = parser.parse_args() # load network load_network(args.network) if hasattr(args, 'func'): args.func(args) else: print('no action given')
[ 2, 48443, 14629, 14, 8800, 14, 24330, 285, 25404, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 46111, 50155, 198, 2, 9220, 6530, 1058, 198, 2, 32039, 1058, 198, 2, 21582, 7536, 1058, 198, 2, 4586, 40499, ...
2.335583
1,630
# -*- coding: utf-8 -*- import numpy as np import random #Load embedding vocabulary #Load embedding vocabulary #Load embeddings filtered by pre-given vocabulary #Load embedding matrices input/output #Split training and development data
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 4738, 198, 198, 2, 8912, 11525, 12083, 25818, 198, 198, 2, 8912, 11525, 12083, 25818, 628, 198, 2, 8912, 11525, 67, 654, 29083...
3.507246
69
import discord from discord.ext import commands from discord.ext.commands import Cog from helpers.checks import check_if_staff from helpers.userlogs import setwatch
[ 11748, 36446, 198, 6738, 36446, 13, 2302, 1330, 9729, 198, 6738, 36446, 13, 2302, 13, 9503, 1746, 1330, 327, 519, 198, 6738, 49385, 13, 42116, 1330, 2198, 62, 361, 62, 28120, 198, 6738, 49385, 13, 7220, 6404, 82, 1330, 900, 8340, 628,...
3.883721
43
# Copyright 2020 Google LLC # # 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 # # https://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. """Tests for candidate_sampler_config_builder.""" from research.carls.candidate_sampling import candidate_sampler_config_builder as cs_config_builder from research.carls.candidate_sampling import candidate_sampler_config_pb2 as cs_config_pb2 import tensorflow as tf if __name__ == '__main__': tf.test.main()
[ 2, 15069, 12131, 3012, 11419, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 733...
3.545817
251
from context import ROOT_DIR, nnUtils, train_came, came import tensorflow as tf import numpy as np import argparse import os import progressbar import random os.environ['TF_CPP_MIN_LOG_LEVEL']='2' if __name__ == "__main__": args = parse_args() data_x, data_y = train_came.build_dataset(train_came.training_systems, args.antipattern, args.history_length) data_x, data_y = nnUtils.shuffle(data_x, data_y) bar = progressbar.ProgressBar(maxval=args.n_test, \ widgets=['Performing cross validation: ' ,progressbar.Percentage()]) bar.start() output_file_path = os.path.join(ROOT_DIR, 'experiments', 'tuning', 'results', 'came_' + args.antipattern + '_' + str(args.history_length) + '.csv') params = [] perfs = [] for i in range(args.n_test): learning_rate, beta, gamma, nb_filters, kernel_sizes, pool_sizes, dense_sizes = generateRandomHyperParameters(args.history_length) params.append([learning_rate, beta, gamma, nb_filters, kernel_sizes, pool_sizes, dense_sizes]) predictions = np.empty(shape=[0, 1]) for j in range(args.n_fold): x_train, y_train, x_test, y_test = get_cross_validation_dataset(data_x, data_y, j, args.n_fold) # New graph tf.reset_default_graph() # Create model model = came.CAME( nb_metrics=x_train.shape[-1], history_length=args.history_length, filters=nb_filters, kernel_sizes=kernel_sizes, pool_sizes=pool_sizes, dense_sizes=dense_sizes) with tf.Session() as session: # Initialize the variables of the TensorFlow graph. session.run(tf.global_variables_initializer()) train( session=session, model=model, x_train=x_train, y_train=y_train, num_step=args.n_step, lr=learning_rate, beta=beta, gamma=gamma) predictions = np.concatenate((predictions, session.run(model.inference, feed_dict={model.input_x: x_test})), axis=0) perfs.append(nnUtils.f_measure(predictions, data_y)) indexes = np.argsort(np.array(perfs)) with open(output_file_path, 'w') as file: file.write("Learning rate;Beta;Gamma;Filters;Kernel;Pool;Dense;F-measure\n") for j in reversed(indexes): for k in range(len(params[j])): file.write(str(params[j][k]) + ';') file.write(str(perfs[j]) + '\n') bar.update(i+1) bar.finish()
[ 6738, 4732, 1330, 15107, 2394, 62, 34720, 11, 299, 77, 18274, 4487, 11, 4512, 62, 66, 480, 11, 1625, 198, 198, 11748, 11192, 273, 11125, 220, 220, 220, 220, 220, 220, 220, 355, 48700, 198, 11748, 299, 32152, 220, 220, 220, 220, 220,...
2.303303
999
import typing import pytest from genshin import paginators @pytest.fixture(name="counting_paginator")
[ 11748, 19720, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 308, 641, 20079, 1330, 279, 23183, 2024, 628, 198, 198, 31, 9078, 9288, 13, 69, 9602, 7, 3672, 2625, 9127, 278, 62, 79, 363, 20900, 4943, 628, 628, 628, 628 ]
2.85
40
import os import errno from twitter.common import log from twitter.common.recordio import ThriftRecordReader from gen.twitter.thermos.ttypes import RunnerCkpt
[ 11748, 28686, 198, 11748, 11454, 3919, 198, 198, 6738, 17044, 13, 11321, 1330, 2604, 198, 6738, 17044, 13, 11321, 13, 22105, 952, 1330, 16283, 2135, 23739, 33634, 198, 6738, 2429, 13, 6956, 13, 490, 16785, 13, 83, 19199, 1330, 21529, 34...
3.659091
44
# Copyright 2017 Lenovo # # 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 codecs import confluent.discovery.handlers.bmc as bmchandler import pyghmi.exceptions as pygexc import pyghmi.ipmi.private.util as pygutil import confluent.util as util import struct
[ 2, 15069, 2177, 40269, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, 2, 921, 743, 7330, 257,...
3.628571
210
"""add country code to table Revision ID: 0367b739bb81 Revises: 1e09924c1938 Create Date: 2022-01-27 16:10:57.297020 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '0367b739bb81' down_revision = '1e09924c1938' branch_labels = None depends_on = None
[ 37811, 2860, 1499, 2438, 284, 3084, 198, 198, 18009, 1166, 4522, 25, 657, 27824, 65, 22, 2670, 11848, 6659, 198, 18009, 2696, 25, 352, 68, 15, 2079, 1731, 66, 1129, 2548, 198, 16447, 7536, 25, 33160, 12, 486, 12, 1983, 1467, 25, 940...
2.508065
124
#!/usr/bin/env python import os import smach_based_introspection_framework.offline_part.visualize_dataset as m if __name__ == "__main__": m.run()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 11748, 28686, 198, 11748, 895, 620, 62, 3106, 62, 600, 305, 31308, 62, 30604, 13, 2364, 1370, 62, 3911, 13, 41464, 1096, 62, 19608, 292, 316, 355, 285, 198, 198, 361, 11593, 367...
2.576271
59
from core.loggers import log, dlog from core import messages from core.vectors import ModuleExec from core.module import Module from core.config import base_path from http.server import HTTPServer, BaseHTTPRequestHandler from tempfile import gettempdir from socketserver import ThreadingMixIn from urllib.parse import urlparse, urlunparse, ParseResult from io import StringIO from http.client import HTTPResponse import threading import re import os import sys import socket import ssl import select import http.client import urllib.parse import threading import time import json import re from http.server import HTTPServer, BaseHTTPRequestHandler from socketserver import ThreadingMixIn from io import BytesIO from subprocess import Popen, PIPE from html.parser import HTMLParser from tempfile import mkdtemp re_valid_ip = re.compile( "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$") re_valid_hostname = re.compile("^(([a-zA-Z0-9\-]+)\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$") temp_certdir = mkdtemp() lock = threading.Lock() # Create path for the CA certificates and keys cert_folder = os.path.join(base_path, 'certs') try: os.makedirs(cert_folder) except: pass # # Most of the Proxy part has been taken from https://github.com/inaz2/proxy2 # class Proxy(Module): """Run local proxy to pivot HTTP/HTTPS browsing through the target."""
[ 6738, 4755, 13, 6404, 5355, 1330, 2604, 11, 288, 6404, 198, 6738, 4755, 1330, 6218, 198, 6738, 4755, 13, 303, 5217, 1330, 19937, 23002, 198, 6738, 4755, 13, 21412, 1330, 19937, 198, 6738, 4755, 13, 11250, 1330, 2779, 62, 6978, 198, 67...
2.721591
528
from .construct import GraspConstruct, MultiStartGraspConstruct
[ 6738, 764, 41571, 1330, 1902, 5126, 42316, 11, 15237, 10434, 8642, 5126, 42316, 201, 198 ]
4.333333
15
import pytest
[ 11748, 12972, 9288, 628 ]
3.75
4
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from django.conf import settings from django.http import HttpResponse from django.views.decorators.cache import never_cache from django.utils.decorators import method_decorator from uw_saml.decorators import group_required from course_grader.views.rest_dispatch import RESTDispatch from course_grader.models import ( SubmittedGradeRoster as SubmittedGradeRosterModel) from course_grader.dao.person import person_from_regid, person_display_name from course_grader.dao.section import section_from_label from course_grader.dao.term import term_from_param from uw_sws_graderoster.models import GradeRoster from lxml import etree from logging import getLogger import csv logger = getLogger(__name__) @method_decorator(group_required(settings.GRADEPAGE_SUPPORT_GROUP), name='dispatch') @method_decorator(never_cache, name='dispatch') @method_decorator(group_required(settings.GRADEPAGE_SUPPORT_GROUP), name='dispatch') @method_decorator(never_cache, name='dispatch')
[ 2, 15069, 33448, 33436, 12, 2043, 11, 2059, 286, 2669, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 2928...
2.948787
371
import json import os.path import subprocess import boto3 # This is all cribbed from the django branch's cluster_management/deployment_helpers folder # TODO once the branches are merged, use that code and NOT this code
[ 11748, 33918, 201, 198, 11748, 28686, 13, 6978, 201, 198, 11748, 850, 14681, 201, 198, 201, 198, 11748, 275, 2069, 18, 201, 198, 201, 198, 2, 770, 318, 477, 48083, 3077, 422, 262, 42625, 14208, 8478, 338, 13946, 62, 27604, 14, 2934, ...
3.064103
78
"""Boundarys for Responses from TelescopeController (TC) and Requests to TC. Data entry and exit point into use_cases layer. """ class TelescopeControllerResponseBoundary: """Contains Responses from TelescopeController Device. """ def __init__( self, ra_response = None, dec_response = None, validate_response = None): """Store Responses of Telescope Controller as floats. """ self.ra_response = ra_response self.dec_response = dec_response self.validate_response = validate_response def set_ra_response(self, ra): """Set ra response. Input: ra as float in hours """ self.ra_response = ra def set_dec_response(self, dec): """Set dec response. Input: dec as float in degrees """ self.dec_response = dec def set_validate_response(self, valid): """Set validate response. Input: valid as boolean (accounts for Returns of Telesope Controllere to set_target etc) """ self.validate_response = valid def reset_responses(self): """Reset all responses to None. """ self.ra_response = None self.dec_response = None self.validate_response = None def retrieve_position(self): """Returns ra and dec_responses. """ return (self.ra_response, self.dec_response) class TelescopeControllerRequestBoundary: """Interface for commands to TelescopeController Device. """
[ 37811, 49646, 560, 82, 329, 20549, 274, 422, 36789, 22130, 357, 4825, 8, 290, 9394, 3558, 284, 17283, 13, 198, 220, 220, 6060, 5726, 290, 8420, 966, 656, 779, 62, 33964, 7679, 13, 198, 37811, 198, 198, 4871, 36789, 22130, 31077, 49646...
2.229249
759
# -*- coding: utf-8 -*- """ Created on Tue Feb 25 18:04:32 2020 @author: Dragana """ import mne import microstates as mst import numpy as np HC_RS_path = 'C:/Users/.../Documents/RS_EEG/' subj_folder = ['subj01', 'subj02', 'subj03', 'subj04', 'subj05'] # Parameteres setting up chan_to_drop = ['E67', 'E73', 'E247', 'E251', 'E256', 'E243', 'E246', 'E250', 'E255', 'E82', 'E91', 'E254', 'E249', 'E245', 'E242', 'E253', 'E252', 'E248', 'E244', 'E241', 'E92', 'E102', 'E103', 'E111', 'E112', 'E120', 'E121', 'E133', 'E134', 'E145', 'E146', 'E156', 'E165', 'E166', 'E174', 'E175', 'E187', 'E188', 'E199', 'E200', 'E208', 'E209', 'E216', 'E217', 'E228', 'E229', 'E232', 'E233', 'E236', 'E237', 'E240', 'E218', 'E227', 'E231', 'E235', 'E239', 'E219', 'E225', 'E226', 'E230', 'E234', 'E238'] pax = len(subj_folder) # number of participants n_states = 4 n_inits = 10 EGI256 = True if EGI256 == True: n_channels = 256 - len(chan_to_drop) grouped_maps = np.array([], dtype=np.int64).reshape(0, n_channels) for i, f in enumerate(subj_folder): fname = HC_RS_path + f + '/' + f +'_clean-epo.fif' epochs = mne.read_epochs(fname, preload=True) if EGI256 == True: epochs.drop_channels(chan_to_drop) data = epochs.get_data() # Segment the data in microstates maps, segmentation, gev, gfp_peaks = mst.segment(data, n_states, n_inits) grouped_maps = np.concatenate((grouped_maps, maps), axis=0) # Transpose the maps from maps(n_maps, n_channels) to maps(n_channels, n_maps) # and treat the n_maps as a sample in time. grouped_maps_T = grouped_maps.transpose() # Find the group maps using k-means clustering group_maps, group_gev = mst.segment(grouped_maps_T, n_states, n_inits, use_peaks=False) # Plot the maps mst.viz.plot_maps(group_maps, epochs.info) # Fitting the maps back to the original epoched data by subject grouped_segment, all_p = [], [] for i, f in enumerate(subj_folder): fname = HC_RS_path + f + '/' + f +'_clean-epo.fif' epochs = mne.read_epochs(fname, preload=True) if EGI256 == True: epochs.drop_channels(chan_to_drop) data = epochs.get_data() n_epochs, n_chans, n_samples = data.shape # Make the data 2D data = np.hstack(data) # Compute final microstate segmentations on the original data activation = group_maps.dot(data) segmentation = np.argmax(np.abs(activation), axis=0) # Add all the per subject segmentations in one array # (n_times, subjects) grouped_segment.append(segmentation) # Plot the segmentation per subject sfreq = epochs.info['sfreq'] times = np.arange(0, len(data[1])/sfreq, 1/sfreq) mst.viz.plot_segmentation(segmentation[:500], data[:, :500], times[:500]) # p_empirical epoched_data = True p_hat = mst.analysis.p_empirical(segmentation, n_epochs, n_samples, n_states, epoched_data) all_p.append(p_hat) # p_empirical printing print("\n\t Empirical symbol distribution (RTT) per subject:\n") for i in range(pax): print("\n Subject", i) for j in range(n_states): print("\n\t\t p", j, " = {0:.5f}".format(all_p[i][j])) all_p = np.vstack(all_p) all_p /= pax all_p_sum = np.sum(all_p, axis=0) print("\n\t Empirical symbol distribution (RTT) for all subjects:\n") for i in range(n_states): print("\n\t\t p", i, " = {0:.5f}".format(all_p_sum[i]))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 41972, 319, 30030, 3158, 1679, 1248, 25, 3023, 25, 2624, 12131, 198, 198, 31, 9800, 25, 12697, 2271, 198, 37811, 198, 11748, 285, 710, 198, 11748, 4580, 2721...
2.134592
1,642
# # Copyright 2011 Shopzilla.com # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this 1 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. # """The base Controller API Provides the BaseController class for subclassing. """ from pylons.controllers import WSGIController from pylons.templating import render_mako as render
[ 2, 198, 2, 15069, 2813, 13705, 16496, 13, 785, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 352, 2845, 287, 11846, 351, 262, 13789, 13, 198, ...
3.707317
205
from . import DATA_DIR import sys import glob from .background_systems import BackgroundSystemModel from .export import ExportInventory from inspect import currentframe, getframeinfo from pathlib import Path from scipy import sparse import csv import itertools import numexpr as ne import numpy as np import xarray as xr REMIND_FILES_DIR = DATA_DIR / "IAM" class InventoryCalculation: """ Build and solve the inventory for results characterization and inventory export Vehicles to be analyzed can be filtered by passing a `scope` dictionary. Some assumptions in the background system can also be adjusted by passing a `background_configuration` dictionary. .. code-block:: python scope = { 'powertrain':['BEV', 'FCEV', 'ICEV-p'], } bc = {'country':'CH', # considers electricity network losses for Switzerland 'custom electricity mix' : [[1,0,0,0,0,0,0,0,0,0], # in this case, 100% hydropower for the first year [0,1,0,0,0,0,0,0,0,0], [0,0,1,0,0,0,0,0,0,0], [0,0,0,1,0,0,0,0,0,0], ], # in this case, 100% nuclear for the second year 'fuel blend':{ 'cng':{ #specify fuel bland for compressed gas 'primary fuel':{ 'type':'biogas', 'share':[0.9, 0.8, 0.7, 0.6] # shares per year. Must total 1 for each year. }, 'secondary fuel':{ 'type':'syngas', 'share': [0.1, 0.2, 0.3, 0.4] } }, 'diesel':{ 'primary fuel':{ 'type':'synthetic diesel', 'share':[0.9, 0.8, 0.7, 0.6] }, 'secondary fuel':{ 'type':'biodiesel - cooking oil', 'share': [0.1, 0.2, 0.3, 0.4] } }, 'petrol':{ 'primary fuel':{ 'type':'petrol', 'share':[0.9, 0.8, 0.7, 0.6] }, 'secondary fuel':{ 'type':'bioethanol - wheat straw', 'share': [0.1, 0.2, 0.3, 0.4] } }, 'hydrogen':{ 'primary fuel':{'type':'electrolysis', 'share':[1, 0, 0, 0]}, 'secondary fuel':{'type':'smr - natural gas', 'share':[0, 1, 1, 1]} } }, 'energy storage': { 'electric': { 'type':'NMC', 'origin': 'NO' }, 'hydrogen': { 'type':'carbon fiber' } } } InventoryCalculation(CarModel.array, background_configuration=background_configuration, scope=scope, scenario="RCP26") The `custom electricity mix` key in the background_configuration dictionary defines an electricity mix to apply, under the form of one or several array(s), depending on teh number of years to analyze, that should total 1, of which the indices correspond to: - [0]: hydro-power - [1]: nuclear - [2]: natural gas - [3]: solar power - [4]: wind power - [5]: biomass - [6]: coal - [7]: oil - [8]: geothermal - [9]: waste incineration If none is given, the electricity mix corresponding to the country specified in `country` will be selected. If no country is specified, Europe applies. The `primary` and `secondary` fuel keys contain an array with shares of alternative petrol fuel for each year, to create a custom blend. If none is provided, a blend provided by the Integrated Assessment model REMIND is used, which will depend on the REMIND energy scenario selected. Here is a list of available fuel pathways: Hydrogen technologies -------------------- electrolysis smr - natural gas smr - natural gas with CCS smr - biogas smr - biogas with CCS coal gasification wood gasification wood gasification with CCS Natural gas technologies ------------------------ cng biogas syngas Diesel technologies ------------------- diesel biodiesel - algae biodiesel - cooking oil synthetic diesel Petrol technologies ------------------- petrol bioethanol - wheat straw bioethanol - maize starch bioethanol - sugarbeet bioethanol - forest residues synthetic gasoline :ivar array: array from the CarModel class :vartype array: CarModel.array :ivar scope: dictionary that contains filters for narrowing the analysis :ivar background_configuration: dictionary that contains choices for background system :ivar scenario: REMIND energy scenario to use ("SSP2-Baseline": business-as-usual, "SSP2-PkBudg1100": limits cumulative GHG emissions to 1,100 gigatons by 2100, "static": no forward-looking modification of the background inventories). "SSP2-Baseline" selected by default. .. code-block:: python """ def __getitem__(self, key): """ Make class['foo'] automatically filter for the parameter 'foo' Makes the model code much cleaner :param key: Parameter name :type key: str :return: `array` filtered after the parameter selected """ return self.temp_array.sel(parameter=key) def get_results_table(self, split, sensitivity=False): """ Format an xarray.DataArray array to receive the results. :param split: "components" or "impact categories". Split by impact categories only applicable when "endpoint" level is applied. :return: xarrray.DataArray """ if split == "components": cat = [ "direct - exhaust", "direct - non-exhaust", "energy chain", "maintenance", "glider", "EoL", "powertrain", "energy storage", "road", ] dict_impact_cat = list(self.impact_categories.keys()) if sensitivity == False: response = xr.DataArray( np.zeros( ( self.B.shape[1], len(self.scope["size"]), len(self.scope["powertrain"]), len(self.scope["year"]), len(cat), self.iterations, ) ), coords=[ dict_impact_cat, self.scope["size"], self.scope["powertrain"], self.scope["year"], cat, np.arange(0, self.iterations), ], dims=[ "impact_category", "size", "powertrain", "year", "impact", "value", ], ) else: params = [a for a in self.array.value.values] response = xr.DataArray( np.zeros( ( self.B.shape[1], len(self.scope["size"]), len(self.scope["powertrain"]), len(self.scope["year"]), self.iterations, ) ), coords=[ dict_impact_cat, self.scope["size"], self.scope["powertrain"], self.scope["year"], params, ], dims=["impact_category", "size", "powertrain", "year", "parameter"], ) return response def get_split_indices(self): """ Return list of indices to split the results into categories. :return: list of indices :rtype: list """ filename = "dict_split.csv" filepath = DATA_DIR / filename if not filepath.is_file(): raise FileNotFoundError("The dictionary of splits could not be found.") with open(filepath) as f: csv_list = [[val.strip() for val in r.split(";")] for r in f.readlines()] (_, _, *header), *data = csv_list csv_dict = {} for row in data: key, sub_key, *values = row if key in csv_dict: if sub_key in csv_dict[key]: csv_dict[key][sub_key].append( {"search by": values[0], "search for": values[1]} ) else: csv_dict[key][sub_key] = [ {"search by": values[0], "search for": values[1]} ] else: csv_dict[key] = { sub_key: [{"search by": values[0], "search for": values[1]}] } flatten = itertools.chain.from_iterable d = {} l = [] d['direct - exhaust'] = [] d['direct - exhaust'].append( self.inputs[("Carbon dioxide, fossil", ("air",), "kilogram")] ) d['direct - exhaust'].append( self.inputs[("Carbon dioxide, from soil or biomass stock", ("air",), "kilogram")] ) d['direct - exhaust'].append( self.inputs[("Cadmium", ("air", "urban air close to ground"), "kilogram")] ) d['direct - exhaust'].append( self.inputs[("Copper", ("air", "urban air close to ground"), "kilogram")] ) d['direct - exhaust'].append( self.inputs[("Chromium", ("air", "urban air close to ground"), "kilogram")] ) d['direct - exhaust'].append( self.inputs[("Nickel", ("air", "urban air close to ground"), "kilogram")] ) d['direct - exhaust'].append( self.inputs[("Selenium", ("air", "urban air close to ground"), "kilogram")] ) d['direct - exhaust'].append( self.inputs[("Zinc", ("air", "urban air close to ground"), "kilogram")] ) d['direct - exhaust'].append( self.inputs[("Chromium VI", ("air", "urban air close to ground"), "kilogram")] ) d['direct - exhaust'].extend(self.index_emissions) d['direct - exhaust'].extend(self.index_noise) l.append(d['direct - exhaust']) for cat in csv_dict["components"]: d[cat] = list( flatten( [ self.get_index_of_flows([l["search for"]], l["search by"]) for l in csv_dict["components"][cat] ] ) ) l.append(d[cat]) list_ind = [d[x] for x in d] maxLen = max(map(len, list_ind)) for row in list_ind: while len(row) < maxLen: row.extend([len(self.inputs) - 1]) return list(d.keys()), list_ind def get_A_matrix(self): """ Load the A matrix. The A matrix contains exchanges of products (rows) between activities (columns). :return: A matrix with three dimensions of shape (number of values, number of products, number of activities). :rtype: numpy.ndarray """ filename = "A_matrix.csv" filepath = ( Path(getframeinfo(currentframe()).filename) .resolve() .parent.joinpath("data/" + filename) ) if not filepath.is_file(): raise FileNotFoundError("The technology matrix could not be found.") initial_A = np.genfromtxt(filepath, delimiter=";") new_A = np.identity(len(self.inputs)) new_A[0 : np.shape(initial_A)[0], 0 : np.shape(initial_A)[0]] = initial_A # Resize the matrix to fit the number of iterations in `array` new_A = np.resize(new_A, (self.array.shape[1], new_A.shape[0], new_A.shape[1])) return new_A def get_B_matrix(self): """ Load the B matrix. The B matrix contains impact assessment figures for a give impact assessment method, per unit of activity. Its length column-wise equals the length of the A matrix row-wise. Its length row-wise equals the number of impact assessment methods. :param method: only "recipe" and "ilcd" available at the moment. :param level: only "midpoint" available at the moment. :return: an array with impact values per unit of activity for each method. :rtype: numpy.ndarray """ if self.method == "recipe": if self.method_type == "midpoint": list_file_names = glob.glob( str(REMIND_FILES_DIR) + "/*recipe_midpoint*{}*.csv".format(self.scenario) ) B = np.zeros((len(list_file_names), 21, len(self.inputs))) else: list_file_names = glob.glob( str(REMIND_FILES_DIR) + "/*recipe_endpoint*{}*.csv".format(self.scenario) ) B = np.zeros((len(list_file_names), 3, len(self.inputs))) else: list_file_names = glob.glob( str(REMIND_FILES_DIR) + "/*ilcd*{}*.csv".format(self.scenario) ) B = np.zeros((len(list_file_names), 19, len(self.inputs))) for f in list_file_names: initial_B = np.genfromtxt(f, delimiter=";") new_B = np.zeros((np.shape(initial_B)[0], len(self.inputs),)) new_B[0 : np.shape(initial_B)[0], 0 : np.shape(initial_B)[1]] = initial_B B[list_file_names.index(f), :, :] = new_B list_impact_categories = list(self.impact_categories.keys()) if self.scenario != "static": response = xr.DataArray( B, coords=[ [2005, 2010, 2020, 2030, 2040, 2050], list_impact_categories, list(self.inputs.keys()), ], dims=["year", "category", "activity"], ) else: response = xr.DataArray( B, coords=[ [2020], list_impact_categories, list(self.inputs.keys()), ], dims=["year", "category", "activity"], ) return response def get_dict_input(self): """ Load a dictionary with tuple ("name of activity", "location", "unit", "reference product") as key, row/column indices as values. :return: dictionary with `label:index` pairs. :rtype: dict """ filename = "dict_inputs_A_matrix.csv" filepath = DATA_DIR / filename if not filepath.is_file(): raise FileNotFoundError( "The dictionary of activity labels could not be found." ) csv_dict = {} count = 0 with open(filepath) as f: input_dict = csv.reader(f, delimiter=";") for row in input_dict: if "(" in row[1]: new_str = row[1].replace("(", "") new_str = new_str.replace(")", "") new_str = [s.strip() for s in new_str.split(",") if s] t = () for s in new_str: if "low population" in s: s = "low population density, long-term" t += (s,) break else: t += (s.replace("'", ""),) csv_dict[(row[0], t, row[2])] = count else: csv_dict[(row[0], row[1], row[2], row[3])] = count count += 1 return csv_dict def get_dict_impact_categories(self): """ Load a dictionary with available impact assessment methods as keys, and assessment level and categories as values. ..code-block:: python {'recipe': {'midpoint': ['freshwater ecotoxicity', 'human toxicity', 'marine ecotoxicity', 'terrestrial ecotoxicity', 'metal depletion', 'agricultural land occupation', 'climate change', 'fossil depletion', 'freshwater eutrophication', 'ionising radiation', 'marine eutrophication', 'natural land transformation', 'ozone depletion', 'particulate matter formation', 'photochemical oxidant formation', 'terrestrial acidification', 'urban land occupation', 'water depletion', 'human noise', 'primary energy, non-renewable', 'primary energy, renewable'] } } :return: dictionary :rtype: dict """ filename = "dict_impact_categories.csv" filepath = DATA_DIR / filename if not filepath.is_file(): raise FileNotFoundError( "The dictionary of impact categories could not be found." ) csv_dict = {} with open(filepath) as f: input_dict = csv.reader(f, delimiter=";") for row in input_dict: if row[0] == self.method and row[3] == self.method_type: csv_dict[row[2]] = {'method':row[1], 'category':row[2], 'type':row[3], 'abbreviation':row[4], 'unit':row[5], 'source':row[6]} return csv_dict def get_rev_dict_input(self): """ Reverse the self.inputs dictionary. :return: reversed dictionary :rtype: dict """ return {v: k for k, v in self.inputs.items()} def get_index_vehicle_from_array( self, items_to_look_for, items_to_look_for_also=None, method="or" ): """ Return list of row/column indices of self.array of labels that contain the string defined in `items_to_look_for`. :param items_to_look_for: string to search for :return: list """ if not isinstance(items_to_look_for, list): items_to_look_for = [items_to_look_for] if not items_to_look_for_also is None: if not isinstance(items_to_look_for_also, list): items_to_look_for_also = [items_to_look_for_also] list_vehicles = self.array.desired.values.tolist() if method == "or": return [ list_vehicles.index(c) for c in list_vehicles if set(items_to_look_for).intersection(c) ] if method == "and": return [ list_vehicles.index(c) for c in list_vehicles if set(items_to_look_for).intersection(c) and set(items_to_look_for_also).intersection(c) ] def get_index_of_flows(self, items_to_look_for, search_by="name"): """ Return list of row/column indices of self.A of labels that contain the string defined in `items_to_look_for`. :param items_to_look_for: string :param search_by: "name" or "compartment" (for elementary flows) :return: list of row/column indices :rtype: list """ if search_by == "name": return [ int(self.inputs[c]) for c in self.inputs if all(ele in c[0].lower() for ele in items_to_look_for) ] if search_by == "compartment": return [ int(self.inputs[c]) for c in self.inputs if all(ele in c[1] for ele in items_to_look_for) ] def export_lci( self, presamples=True, ecoinvent_compatibility=True, ecoinvent_version="3.6", db_name="carculator db", ): """ Export the inventory as a dictionary. Also return a list of arrays that contain pre-sampled random values if :meth:`stochastic` of :class:`CarModel` class has been called. :param presamples: boolean. :param ecoinvent_compatibility: bool. If True, compatible with ecoinvent. If False, compatible with REMIND-ecoinvent. :param ecoinvent_version: str. "3.5", "3.6" or "uvek" :return: inventory, and optionally, list of arrays containing pre-sampled values. :rtype: list """ # Create electricity and fuel market datasets self.create_electricity_market_for_fuel_prep() # Create electricity market dataset for battery production self.create_electricity_market_for_battery_production() self.set_inputs_in_A_matrix(self.array.values) if presamples == True: lci, array = ExportInventory( self.A, self.rev_inputs, db_name=db_name ).write_lci(presamples, ecoinvent_compatibility, ecoinvent_version) return (lci, array) else: lci = ExportInventory(self.A, self.rev_inputs, db_name=db_name).write_lci( presamples, ecoinvent_compatibility, ecoinvent_version ) return lci def export_lci_to_bw( self, presamples=True, ecoinvent_compatibility=True, ecoinvent_version="3.6", db_name="carculator db", ): """ Export the inventory as a `brightway2` bw2io.importers.base_lci.LCIImporter object with the inventory in the `data` attribute. .. code-block:: python # get the inventory i, _ = ic.export_lci_to_bw() # import it in a Brightway2 project i.match_database('ecoinvent 3.6 cutoff', fields=('name', 'unit', 'location', 'reference product')) i.match_database("biosphere3", fields=('name', 'unit', 'categories')) i.match_database(fields=('name', 'unit', 'location', 'reference product')) i.match_database(fields=('name', 'unit', 'categories')) # Create an additional biosphere database for the few flows that do not # exist in "biosphere3" i.create_new_biosphere("additional_biosphere", relink=True) # Check if all exchanges link i.statistics() # Register the database i.write_database() :return: LCIImport object that can be directly registered in a `brightway2` project. :rtype: bw2io.importers.base_lci.LCIImporter """ # Create electricity and fuel market datasets self.create_electricity_market_for_fuel_prep() # Create electricity market dataset for battery production self.create_electricity_market_for_battery_production() self.set_inputs_in_A_matrix(self.array.values) if presamples == True: lci, array = ExportInventory( self.A, self.rev_inputs, db_name=db_name ).write_lci_to_bw(presamples, ecoinvent_compatibility, ecoinvent_version) return (lci, array) else: lci = ExportInventory( self.A, self.rev_inputs, db_name=db_name ).write_lci_to_bw(presamples, ecoinvent_compatibility, ecoinvent_version) return lci def export_lci_to_excel( self, directory=None, ecoinvent_compatibility=True, ecoinvent_version="3.6", software_compatibility="brightway2", filename=None, ): """ Export the inventory as an Excel file (if the destination software is Brightway2) or a CSV file (if the destination software is Simapro) file. Also return the file path where the file is stored. :param directory: directory where to save the file. :type directory: str :param ecoinvent_compatibility: If True, compatible with ecoinvent. If False, compatible with REMIND-ecoinvent. :param ecoinvent_version: "3.6", "3.5" or "uvek" :param software_compatibility: "brightway2" or "simapro" :return: file path where the file is stored. :rtype: str """ if software_compatibility not in ("brightway2", "simapro"): raise NameError( "The destination software argument is not valid. Choose between 'brightway2' or 'simapro'." ) # Simapro inventory only for ecoinvent 3.5 or UVEK if software_compatibility == "simapro": if ecoinvent_version == "3.6": print( "Simapro-compatible inventory export is only available for ecoinvent 3.5 or UVEK." ) return ecoinvent_compatibility = True ecoinvent_version = "3.5" # Create electricity and fuel market datasets self.create_electricity_market_for_fuel_prep() # Create electricity market dataset for battery production self.create_electricity_market_for_battery_production() self.set_inputs_in_A_matrix(self.array.values) fp = ExportInventory( self.A, self.rev_inputs, db_name=filename or "carculator db" ).write_lci_to_excel( directory, ecoinvent_compatibility, ecoinvent_version, software_compatibility, filename, ) return fp def define_electricity_mix_for_fuel_prep(self): """ This function defines a fuel mix based either on user-defined mix, or on default mixes for a given country. The mix is calculated as the average mix, weighted by the distribution of annually driven kilometers. :return: """ try: losses_to_low = float(self.bs.losses[self.country]["LV"]) except KeyError: # If losses for the country are not found, assume EU average losses_to_low = float(self.bs.losses["RER"]["LV"]) if "custom electricity mix" in self.background_configuration: # If a special electricity mix is specified, we use it mix = self.background_configuration["custom electricity mix"] else: use_year = [ int(i) for i in ( self.array.values[ self.array_inputs["lifetime kilometers"], :, self.get_index_vehicle_from_array( [ "BEV", "FCEV", "PHEV-p", "PHEV-d", "ICEV-p", "ICEV-d", "HEV-p", "HEV-d", "ICEV-g", ] ), ] / self.array.values[ self.array_inputs["kilometers per year"], :, self.get_index_vehicle_from_array( [ "BEV", "FCEV", "PHEV-p", "PHEV-d", "ICEV-p", "ICEV-d", "HEV-p", "HEV-d", "ICEV-g", ] ), ] ) .mean(axis=1) .reshape(-1, len(self.scope["year"])) .mean(axis=0) ] mix = [ self.bs.electricity_mix.sel( country=self.country, variable=[ "Hydro", "Nuclear", "Gas", "Solar", "Wind", "Biomass", "Coal", "Oil", "Geothermal", "Waste", ], ) .interp( year=np.arange(y, y + use_year[self.scope["year"].index(y)]), kwargs={"fill_value": "extrapolate"}, ) .mean(axis=0) .values if y + use_year[self.scope["year"].index(y)] <= 2050 else self.bs.electricity_mix.sel( country=self.country, variable=[ "Hydro", "Nuclear", "Gas", "Solar", "Wind", "Biomass", "Coal", "Oil", "Geothermal", "Waste", ], ) .interp(year=np.arange(y, 2051), kwargs={"fill_value": "extrapolate"}) .mean(axis=0) .values for y in self.scope["year"] ] return mix def create_electricity_market_for_fuel_prep(self): """ This function fills the electricity market that supplies battery charging operations and hydrogen production through electrolysis. """ try: losses_to_low = float(self.bs.losses[self.country]["LV"]) except KeyError: # If losses for the country are not found, assume EU average losses_to_low = float(self.bs.losses["RER"]["LV"]) # Fill the electricity markets for battery charging and hydrogen production for y in self.scope["year"]: m = np.array(self.mix[self.scope["year"].index(y)]).reshape(-1, 10, 1) # Add electricity technology shares self.A[ np.ix_( np.arange(self.iterations), [self.inputs[self.elec_map[t]] for t in self.elec_map], [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "electricity market for fuel preparation" in i[0] ], ) ] = (m * -1 * losses_to_low) # Add transmission network for high and medium voltage self.A[ :, self.inputs[ ( "transmission network construction, electricity, high voltage", "CH", "kilometer", "transmission network, electricity, high voltage", ) ], [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "electricity market for fuel preparation" in i[0] ], ] = (6.58e-9 * -1 * losses_to_low) self.A[ :, self.inputs[ ( "transmission network construction, electricity, medium voltage", "CH", "kilometer", "transmission network, electricity, medium voltage", ) ], [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "electricity market for fuel preparation" in i[0] ], ] = (1.86e-8 * -1 * losses_to_low) self.A[ :, self.inputs[ ( "transmission network construction, long-distance", "UCTE", "kilometer", "transmission network, long-distance", ) ], [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "electricity market for fuel preparation" in i[0] ], ] = (3.17e-10 * -1 * losses_to_low) # Add distribution network, low voltage self.A[ :, self.inputs[ ( "distribution network construction, electricity, low voltage", "CH", "kilometer", "distribution network, electricity, low voltage", ) ], [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "electricity market for fuel preparation" in i[0] ], ] = (8.74e-8 * -1 * losses_to_low) # Add supply of sulfur hexafluoride for transformers self.A[ :, self.inputs[ ( "market for sulfur hexafluoride, liquid", "RER", "kilogram", "sulfur hexafluoride, liquid", ) ], [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "electricity market for fuel preparation" in i[0] ], ] = ((5.4e-8 + 2.99e-9) * -1 * losses_to_low) # Add SF_6 leakage self.A[ :, self.inputs[("Sulfur hexafluoride", ("air",), "kilogram")], [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "electricity market for fuel preparation" in i[0] ], ] = ((5.4e-8 + 2.99e-9) * -1 * losses_to_low) def create_electricity_market_for_battery_production(self): """ This function fills in the column in `self.A` concerned with the electricity mix used for manufacturing battery cells :return: """ battery_tech = self.background_configuration["energy storage"]["electric"][ "type" ] battery_origin = self.background_configuration["energy storage"]["electric"][ "origin" ] try: losses_to_low = float(self.bs.losses[battery_origin]["LV"]) except KeyError: losses_to_low = float(self.bs.losses["CN"]["LV"]) mix_battery_manufacturing = ( self.bs.electricity_mix.sel( country=battery_origin, variable=[ "Hydro", "Nuclear", "Gas", "Solar", "Wind", "Biomass", "Coal", "Oil", "Geothermal", "Waste", ], ) .interp(year=self.scope["year"], kwargs={"fill_value": "extrapolate"}) .values ) # Fill the electricity markets for battery production for y in self.scope["year"]: m = np.array( mix_battery_manufacturing[self.scope["year"].index(y)] ).reshape(-1, 10, 1) self.A[ np.ix_( np.arange(self.iterations), [self.inputs[self.elec_map[t]] for t in self.elec_map], [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "electricity market for energy storage production" in i[0] ], ) ] = (m * losses_to_low * -1) # Add transmission network for high and medium voltage self.A[ :, self.inputs[ ( "transmission network construction, electricity, high voltage", "CH", "kilometer", "transmission network, electricity, high voltage", ) ], [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "electricity market for energy storage production" in i[0] ], ] = (6.58e-9 * -1 * losses_to_low) self.A[ :, self.inputs[ ( "transmission network construction, electricity, medium voltage", "CH", "kilometer", "transmission network, electricity, medium voltage", ) ], [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "electricity market for energy storage production" in i[0] ], ] = (1.86e-8 * -1 * losses_to_low) self.A[ :, self.inputs[ ( "transmission network construction, long-distance", "UCTE", "kilometer", "transmission network, long-distance", ) ], [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "electricity market for energy storage production" in i[0] ], ] = (3.17e-10 * -1 * losses_to_low) # Add distribution network, low voltage self.A[ :, self.inputs[ ( "distribution network construction, electricity, low voltage", "CH", "kilometer", "distribution network, electricity, low voltage", ) ], [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "electricity market for energy storage production" in i[0] ], ] = (8.74e-8 * -1 * losses_to_low) # Add supply of sulfur hexafluoride for transformers self.A[ :, self.inputs[ ( "market for sulfur hexafluoride, liquid", "RER", "kilogram", "sulfur hexafluoride, liquid", ) ], [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "electricity market for energy storage production" in i[0] ], ] = ((5.4e-8 + 2.99e-9) * -1 * losses_to_low) # Add SF_6 leakage self.A[ :, self.inputs[("Sulfur hexafluoride", ("air",), "kilogram")], [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "electricity market for energy storage production" in i[0] ], ] = ((5.4e-8 + 2.99e-9) * -1 * losses_to_low) def set_actual_range(self): """ Set the actual range considering the blend. Liquid bio-fuels and synthetic fuels typically have a lower calorific value. Hence, the need to recalculate the vehicle range. Modifies parameter `range` of `array` in place """ if {"ICEV-p", "HEV-p", "PHEV-p"}.intersection(set(self.scope["powertrain"])): for y in self.scope["year"]: share_primary = self.fuel_blends["petrol"]["primary"]["share"][ self.scope["year"].index(y) ] lhv_primary = self.fuel_blends["petrol"]["primary"]["lhv"] share_secondary = self.fuel_blends["petrol"]["secondary"]["share"][ self.scope["year"].index(y) ] lhv_secondary = self.fuel_blends["petrol"]["secondary"]["lhv"] index = self.get_index_vehicle_from_array( ["ICEV-p", "HEV-p", "PHEV-p"], y, method="and" ) self.array.values[self.array_inputs["range"], :, index] = ( ( ( self.array.values[self.array_inputs["fuel mass"], :, index] * share_primary * lhv_primary ) + ( self.array.values[self.array_inputs["fuel mass"], :, index] * share_secondary * lhv_secondary ) ) * 1000 / self.array.values[self.array_inputs["TtW energy"], :, index] ) if {"ICEV-d", "HEV-d", "PHEV-d"}.intersection(set(self.scope["powertrain"])): for y in self.scope["year"]: share_primary = self.fuel_blends["diesel"]["primary"]["share"][ self.scope["year"].index(y) ] lhv_primary = self.fuel_blends["diesel"]["primary"]["lhv"] share_secondary = self.fuel_blends["diesel"]["secondary"]["share"][ self.scope["year"].index(y) ] lhv_secondary = self.fuel_blends["diesel"]["secondary"]["lhv"] index = self.get_index_vehicle_from_array( ["ICEV-d", "PHEV-d", "HEV-d"], y, method="and" ) self.array.values[self.array_inputs["range"], :, index] = ( ( ( self.array.values[self.array_inputs["fuel mass"], :, index] * share_primary * lhv_primary ) + ( self.array.values[self.array_inputs["fuel mass"], :, index] * share_secondary * lhv_secondary ) ) * 1000 / self.array.values[self.array_inputs["TtW energy"], :, index] ) def define_fuel_blends(self): """ This function defines fuel blends from what is passed in `background_configuration`. It populates a dictionary `self.fuel_blends` that contains the respective shares, lower heating values and CO2 emission factors of the fuels used. :return: """ fuels_lhv = { "petrol": 42.4, "bioethanol - wheat straw": 26.8, "bioethanol - maize starch": 26.8, "bioethanol - sugarbeet": 26.8, "bioethanol - forest residues": 26.8, "synthetic gasoline": 42.4, "diesel": 42.8, "biodiesel - cooking oil": 31.7, "biodiesel - algae": 31.7, "synthetic diesel": 43.3, "cng": 55.5, "biogas": 55.5, "syngas": 55.5 } fuels_CO2 = { "petrol": 3.18, "bioethanol - wheat straw": 1.91, "bioethanol - maize starch": 1.91, "bioethanol - sugarbeet": 1.91, "bioethanol - forest residues": 1.91, "synthetic gasoline": 3.18, "diesel": 3.14, "biodiesel - cooking oil": 2.85, "biodiesel - algae": 2.85, "synthetic diesel": 3.16, "cng": 2.65, "biogas": 2.65, "syngas": 2.65 } if {"ICEV-p", "HEV-p", "PHEV-p"}.intersection(set(self.scope["powertrain"])): fuel_type = "petrol" primary, secondary, primary_share, secondary_share = self.find_fuel_shares( fuel_type ) self.create_fuel_markets( fuel_type, primary, secondary, primary_share, secondary_share ) self.fuel_blends[fuel_type] = { "primary": { "type": primary, "share": primary_share, "lhv": fuels_lhv[primary], "CO2": fuels_CO2[primary], }, "secondary": { "type": secondary, "share": secondary_share, "lhv": fuels_lhv[secondary], "CO2": fuels_CO2[secondary], }, } if {"ICEV-d", "HEV-d", "PHEV-d"}.intersection(set(self.scope["powertrain"])): fuel_type = "diesel" primary, secondary, primary_share, secondary_share = self.find_fuel_shares( fuel_type ) self.create_fuel_markets( fuel_type, primary, secondary, primary_share, secondary_share ) self.fuel_blends[fuel_type] = { "primary": { "type": primary, "share": primary_share, "lhv": fuels_lhv[primary], "CO2": fuels_CO2[primary], }, "secondary": { "type": secondary, "share": secondary_share, "lhv": fuels_lhv[secondary], "CO2": fuels_CO2[secondary], }, } if {"ICEV-g"}.intersection(set(self.scope["powertrain"])): fuel_type = "cng" primary, secondary, primary_share, secondary_share = self.find_fuel_shares( fuel_type ) self.create_fuel_markets( fuel_type, primary, secondary, primary_share, secondary_share ) self.fuel_blends[fuel_type] = { "primary": {"type": primary, "share": primary_share, "lhv": fuels_lhv[primary], "CO2": fuels_CO2[primary]}, "secondary": {"type": secondary, "share": secondary_share, "lhv": fuels_lhv[primary], "CO2": fuels_CO2[primary]}, } if {"FCEV"}.intersection(set(self.scope["powertrain"])): fuel_type = "hydrogen" primary, secondary, primary_share, secondary_share = self.find_fuel_shares( fuel_type ) self.create_fuel_markets( fuel_type, primary, secondary, primary_share, secondary_share ) self.fuel_blends[fuel_type] = { "primary": {"type": primary, "share": primary_share}, "secondary": {"type": secondary, "share": secondary_share}, } if {"BEV", "PHEV-p", "PHEV-d"}.intersection(set(self.scope["powertrain"])): fuel_type = "electricity" self.create_fuel_markets(fuel_type) def create_fuel_markets( self, fuel_type, primary=None, secondary=None, primary_share=None, secondary_share=None, ): """ This function creates markets for fuel, considering a given blend, a given fuel type and a given year. It also adds separate electricity input in case hydrogen from electrolysis is needed somewhere in the fuel supply chain. :return: """ d_fuels = { "electrolysis": { "name": ( "Hydrogen, gaseous, 700 bar, from electrolysis, at H2 fuelling station", "RER", "kilogram", "Hydrogen, gaseous, 700 bar, from electrolysis, at H2 fuelling station", ), "additional electricity": 58, }, "smr - natural gas": { "name": ( "Hydrogen, gaseous, 700 bar, from SMR NG w/o CCS, at H2 fuelling station", "RER", "kilogram", "Hydrogen, gaseous, 700 bar, from SMR NG w/o CCS, at H2 fuelling station", ), "additional electricity": 0, }, "smr - natural gas with CCS": { "name": ( "Hydrogen, gaseous, 700 bar, from SMR NG w CCS, at H2 fuelling station", "RER", "kilogram", "Hydrogen, gaseous, 700 bar, from SMR NG w CCS, at H2 fuelling station", ), "additional electricity": 0, }, "smr - biogas": { "name": ( "Hydrogen, gaseous, 700 bar, from SMR of biogas, at H2 fuelling station", "RER", "kilogram", "Hydrogen, gaseous, 700 bar, from SMR of biogas, at H2 fuelling station", ), "additional electricity": 0, }, "smr - biogas with CCS": { "name": ( "Hydrogen, gaseous, 700 bar, from SMR of biogas with CCS, at H2 fuelling station", "RER", "kilogram", "Hydrogen, gaseous, 700 bar, from SMR of biogas with CCS, at H2 fuelling station", ), "additional electricity": 0, }, "coal gasification": { "name": ( "Hydrogen, gaseous, 700 bar, from coal gasification, at H2 fuelling station", "RER", "kilogram", "Hydrogen, gaseous, 700 bar, from coal gasification, at H2 fuelling station", ), "additional electricity": 0, }, "wood gasification": { "name": ( "Hydrogen, gaseous, 700 bar, from dual fluidised bed gasification of woody biomass, at H2 fuelling station", "CH", "kilogram", "Hydrogen, gaseous, 700 bar", ), "additional electricity": 0, }, "wood gasification with CCS": { "name": ( "Hydrogen, gaseous, 700 bar, from dual fluidised bed gasification of woody biomass with CCS, at H2 fuelling station", "CH", "kilogram", "Hydrogen, gaseous, 700 bar", ), "additional electricity": 0, }, "cng": { "name": ( "market for natural gas, from high pressure network (1-5 bar), at service station", "GLO", "kilogram", "natural gas, from high pressure network (1-5 bar), at service station", ), "additional electricity": 0, }, "biogas": { "name": ( "biogas upgrading - sewage sludge - amine scrubbing - best", "CH", "kilogram", "biogas upgrading - sewage sludge - amine scrubbing - best", ), "additional electricity": 0, }, "syngas": { "name": ( "Methane production, synthetic, from electrochemical methanation", "RER", "kilogram", "Methane, synthetic", ), "additional electricity": 58 * 0.50779661, }, "diesel": { "name": ( "market for diesel", "Europe without Switzerland", "kilogram", "diesel", ), "additional electricity": 0, }, "biodiesel - algae": { "name": ( "Biodiesel from algae", "RER", "kilogram", "Biodiesel from algae", ), "additional electricity": 0, }, "biodiesel - cooking oil": { "name": ( "Biodiesel from cooking oil", "RER", "kilogram", "Biodiesel from cooking oil", ), "additional electricity": 0, }, "synthetic diesel": { "name": ( "Diesel production, synthetic, Fischer Tropsch process", "RER", "kilogram", "Diesel, synthetic", ), "additional electricity": 58 * 0.2875, }, "petrol": { "name": ( "market for petrol, low-sulfur", "Europe without Switzerland", "kilogram", "petrol, low-sulfur", ), "additional electricity": 0, }, "bioethanol - wheat straw": { "name": ( "Ethanol from wheat straw pellets", "RER", "kilogram", "Ethanol from wheat straw pellets", ), "additional electricity": 0, }, "bioethanol - forest residues": { "name": ( "Ethanol from forest residues", "RER", "kilogram", "Ethanol from forest residues", ), "additional electricity": 0, }, "bioethanol - sugarbeet": { "name": ( "Ethanol from sugarbeet", "RER", "kilogram", "Ethanol from sugarbeet", ), "additional electricity": 0, }, "bioethanol - maize starch": { "name": ( "Ethanol from maize starch", "RER", "kilogram", "Ethanol from maize starch", ), "additional electricity": 0, }, "synthetic gasoline": { "name": ( "Gasoline production, synthetic, from methanol", "RER", "kilogram", "Gasoline, synthetic", ), "additional electricity": 58 * 0.328, }, } d_dataset_name = { "petrol": "fuel supply for gasoline vehicles, ", "diesel": "fuel supply for diesel vehicles, ", "cng": "fuel supply for gas vehicles, ", "hydrogen": "fuel supply for hydrogen vehicles, ", "electricity": "electricity supply for electric vehicles, ", } if fuel_type != "electricity": for y in self.scope["year"]: dataset_name = d_dataset_name[fuel_type] + str(y) fuel_market_index = [ self.inputs[i] for i in self.inputs if i[0] == dataset_name ][0] primary_fuel_activity_index = self.inputs[d_fuels[primary]["name"]] secondary_fuel_activity_index = self.inputs[d_fuels[secondary]["name"]] self.A[:, primary_fuel_activity_index, fuel_market_index] = ( -1 * primary_share[self.scope["year"].index(y)] ) self.A[:, secondary_fuel_activity_index, fuel_market_index] = ( -1 * secondary_share[self.scope["year"].index(y)] ) additional_electricity = ( d_fuels[primary]["additional electricity"] * primary_share[self.scope["year"].index(y)] ) + ( d_fuels[secondary]["additional electricity"] * secondary_share[self.scope["year"].index(y)] ) if additional_electricity > 0: electricity_mix_index = [ self.inputs[i] for i in self.inputs if i[0] == "electricity market for fuel preparation, " + str(y) ][0] self.A[:, electricity_mix_index, fuel_market_index] = ( -1 * additional_electricity ) else: for y in self.scope["year"]: dataset_name = d_dataset_name[fuel_type] + str(y) electricity_market_index = [ self.inputs[i] for i in self.inputs if i[0] == dataset_name ][0] electricity_mix_index = [ self.inputs[i] for i in self.inputs if i[0] == "electricity market for fuel preparation, " + str(y) ][0] self.A[:, electricity_mix_index, electricity_market_index] = -1 def set_inputs_in_A_matrix(self, array): """ Fill-in the A matrix. Does not return anything. Modifies in place. Shape of the A matrix (values, products, activities). :param array: :attr:`array` from :class:`CarModel` class """ # Glider self.A[ :, self.inputs[ ( "market for glider, passenger car", "GLO", "kilogram", "glider, passenger car", ) ], -self.number_of_cars :, ] = ( (array[self.array_inputs["glider base mass"], :]) / array[self.array_inputs["lifetime kilometers"], :] * -1 ) self.A[ :, self.inputs[ ("Glider lightweighting", "GLO", "kilogram", "Glider lightweighting") ], -self.number_of_cars :, ] = ( ( array[self.array_inputs["lightweighting"], :] * array[self.array_inputs["glider base mass"], :] ) / array[self.array_inputs["lifetime kilometers"], :] * -1 ) self.A[ :, self.inputs[ ( "maintenance, passenger car", "RER", "unit", "passenger car maintenance", ) ], -self.number_of_cars :, ] = (array[self.array_inputs["curb mass"], :] / 1240 / 150000 * -1) # Glider EoL self.A[ :, self.inputs[ ( "market for manual dismantling of used electric passenger car", "GLO", "unit", "manual dismantling of used electric passenger car", ) ], -self.number_of_cars :, ] = ( array[self.array_inputs["curb mass"], :] * (1 - array[self.array_inputs["combustion power share"], :]) / array[self.array_inputs["lifetime kilometers"], :] * -1 ) self.A[ :, self.inputs[ ( "market for manual dismantling of used passenger car with internal combustion engine", "GLO", "unit", "manual dismantling of used passenger car with internal combustion engine", ) ], -self.number_of_cars :, ] = ( array[self.array_inputs["curb mass"], :] * array[self.array_inputs["combustion power share"], :] / array[self.array_inputs["lifetime kilometers"], :] * -1 ) # Powertrain components self.A[ :, self.inputs[ ( "market for charger, electric passenger car", "GLO", "kilogram", "charger, electric passenger car", ) ], -self.number_of_cars :, ] = ( array[self.array_inputs["charger mass"], :] / array[self.array_inputs["lifetime kilometers"], :] * -1 ) self.A[ :, self.inputs[ ( "market for converter, for electric passenger car", "GLO", "kilogram", "converter, for electric passenger car", ) ], -self.number_of_cars :, ] = ( array[self.array_inputs["converter mass"], :] / array[self.array_inputs["lifetime kilometers"], :] * -1 ) self.A[ :, self.inputs[ ( "market for electric motor, electric passenger car", "GLO", "kilogram", "electric motor, electric passenger car", ) ], -self.number_of_cars :, ] = ( array[self.array_inputs["electric engine mass"], :] / array[self.array_inputs["lifetime kilometers"], :] * -1 ) self.A[ :, self.inputs[ ( "market for inverter, for electric passenger car", "GLO", "kilogram", "inverter, for electric passenger car", ) ], -self.number_of_cars :, ] = ( array[self.array_inputs["inverter mass"], :] / array[self.array_inputs["lifetime kilometers"], :] * -1 ) self.A[ :, self.inputs[ ( "market for power distribution unit, for electric passenger car", "GLO", "kilogram", "power distribution unit, for electric passenger car", ) ], -self.number_of_cars :, ] = ( array[self.array_inputs["power distribution unit mass"], :] / array[self.array_inputs["lifetime kilometers"], :] * -1 ) l_elec_pt = [ "charger mass", "converter mass", "inverter mass", "power distribution unit mass", "electric engine mass", "fuel cell stack mass", "fuel cell ancillary BoP mass", "fuel cell essential BoP mass", "battery cell mass", "battery BoP mass", ] self.A[ :, self.inputs[ ( "market for used powertrain from electric passenger car, manual dismantling", "GLO", "kilogram", "used powertrain from electric passenger car, manual dismantling", ) ], -self.number_of_cars :, ] = ( array[[self.array_inputs[l] for l in l_elec_pt], :].sum(axis=0) / array[self.array_inputs["lifetime kilometers"], :] ) self.A[ :, self.inputs[ ( "market for internal combustion engine, passenger car", "GLO", "kilogram", "internal combustion engine, for passenger car", ) ], -self.number_of_cars :, ] = ( ( array[ [ self.array_inputs[l] for l in ["combustion engine mass", "powertrain mass"] ], :, ].sum(axis=0) ) / array[self.array_inputs["lifetime kilometers"], :] * -1 ) self.A[ :, self.inputs[("Ancillary BoP", "GLO", "kilogram", "Ancillary BoP")], -self.number_of_cars :, ] = ( array[self.array_inputs["fuel cell ancillary BoP mass"], :] / array[self.array_inputs["lifetime kilometers"], :] * -1 ) self.A[ :, self.inputs[("Essential BoP", "GLO", "kilogram", "Essential BoP")], -self.number_of_cars :, ] = ( array[self.array_inputs["fuel cell essential BoP mass"], :] / array[self.array_inputs["lifetime kilometers"], :] * -1 ) self.A[ :, self.inputs[("Stack", "GLO", "kilowatt", "Stack")], -self.number_of_cars :, ] = ( array[self.array_inputs["fuel cell stack mass"], :] / array[self.array_inputs["lifetime kilometers"], :] * -1 ) # Start of printout print( "****************** IMPORTANT BACKGROUND PARAMETERS ******************", end="\n * ", ) # Energy storage print( "The country of use is " + self.country, end="\n * ", ) battery_tech = self.background_configuration["energy storage"]["electric"][ "type" ] battery_origin = self.background_configuration["energy storage"]["electric"][ "origin" ] print( "Power and energy batteries produced in " + battery_origin + " using " + battery_tech + " chemistry.", end="\n * ", ) # Use the NMC inventory of Schmidt et al. 2019 self.A[ :, self.inputs[("Battery BoP", "GLO", "kilogram", "Battery BoP")], -self.number_of_cars :, ] = ( ( array[self.array_inputs["battery BoP mass"], :] * (1 + array[self.array_inputs["battery lifetime replacements"], :]) ) / array[self.array_inputs["lifetime kilometers"], :] * -1 ) battery_cell_label = ( "Battery cell, " + battery_tech, "GLO", "kilogram", "Battery cell", ) self.A[:, self.inputs[battery_cell_label], -self.number_of_cars :,] = ( ( array[self.array_inputs["battery cell mass"], :] * (1 + array[self.array_inputs["fuel cell lifetime replacements"], :]) ) / array[self.array_inputs["lifetime kilometers"], :] * -1 ) # Set an input of electricity, given the country of manufacture self.A[ :, self.inputs[ ( "market group for electricity, medium voltage", "World", "kilowatt hour", "electricity, medium voltage", ) ], self.inputs[battery_cell_label], ] = 0 for y in self.scope["year"]: index = self.get_index_vehicle_from_array(y) self.A[ np.ix_( np.arange(self.iterations), [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "electricity market for energy storage production" in i[0] ], [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "Passenger" in i[0] ], ) ] = ( array[ self.array_inputs["battery cell production electricity"], :, index ].T * self.A[ :, self.inputs[battery_cell_label], [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "Passenger" in i[0] ], ] ).reshape( self.iterations, 1, -1 ) index_A = [ self.inputs[c] for c in self.inputs if any( ele in c[0] for ele in ["ICEV-d", "ICEV-p", "HEV-p", "PHEV-p", "PHEV-d", "HEV-d"] ) ] index = self.get_index_vehicle_from_array( ["ICEV-d", "ICEV-p", "HEV-p", "PHEV-p", "PHEV-d", "HEV-d"] ) self.A[ :, self.inputs[ ( "polyethylene production, high density, granulate", "RER", "kilogram", "polyethylene, high density, granulate", ) ], index_A, ] = ( array[self.array_inputs["fuel tank mass"], :, index] / array[self.array_inputs["lifetime kilometers"], :, index] * -1 ).T index = self.get_index_vehicle_from_array("ICEV-g") self.A[ :, self.inputs[ ( "glass fibre reinforced plastic production, polyamide, injection moulded", "RER", "kilogram", "glass fibre reinforced plastic, polyamide, injection moulded", ) ], self.index_cng, ] = ( array[self.array_inputs["fuel tank mass"], :, index] / array[self.array_inputs["lifetime kilometers"], :, index] * -1 ).T if "hydrogen" in self.background_configuration["energy storage"]: # If a customization dict is passed hydro_tank_technology = self.background_configuration["energy storage"][ "hydrogen" ]["type"] else: hydro_tank_technology = "carbon fiber" dict_tank_map = { "carbon fiber": ( "Fuel tank, compressed hydrogen gas, 700bar", "GLO", "kilogram", "Fuel tank, compressed hydrogen gas, 700bar", ), "hdpe": ( "Fuel tank, compressed hydrogen gas, 700bar, with HDPE liner", "RER", "kilogram", "Hydrogen tank", ), "aluminium": ( "Fuel tank, compressed hydrogen gas, 700bar, with aluminium liner", "RER", "kilogram", "Hydrogen tank", ), } index = self.get_index_vehicle_from_array("FCEV") self.A[ :, self.inputs[dict_tank_map[hydro_tank_technology]], self.index_fuel_cell, ] = ( array[self.array_inputs["fuel tank mass"], :, index] / array[self.array_inputs["lifetime kilometers"], :, index] * -1 ).T for y in self.scope["year"]: sum_renew, co2_intensity_tech = self.define_renewable_rate_in_mix() if self.scope["year"].index(y) + 1 == len(self.scope["year"]): end_str = "\n * " else: end_str = "\n \t * " print( "in " + str(y) + ", % of renewable: " + str(np.round(sum_renew * 100, 0)) + "%" + ", GHG intensity per kWh: " + str( int( np.sum( co2_intensity_tech * self.mix[self.scope["year"].index(y)] ) ) ) + " g. CO2-eq.", end=end_str, ) if any( True for x in ["BEV", "PHEV-p", "PHEV-d"] if x in self.scope["powertrain"] ): for y in self.scope["year"]: index = self.get_index_vehicle_from_array( ["BEV", "PHEV-p", "PHEV-d"], y, method="and" ) self.A[ np.ix_( np.arange(self.iterations), [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "electricity supply for electric vehicles" in i[0] ], [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "Passenger" in i[0] and any( True for x in ["BEV", "PHEV-p", "PHEV-d"] if x in i[0] ) ], ) ] = ( array[self.array_inputs["electricity consumption"], :, index] * -1 ).T.reshape( self.iterations, 1, -1 ) if "FCEV" in self.scope["powertrain"]: index = self.get_index_vehicle_from_array("FCEV") print( "{} is completed by {}.".format( self.fuel_blends["hydrogen"]["primary"]["type"], self.fuel_blends["hydrogen"]["secondary"]["type"], ), end="\n \t * ", ) for y in self.scope["year"]: if self.scope["year"].index(y) + 1 == len(self.scope["year"]): end_str = "\n * " else: end_str = "\n \t * " print( "in " + str(y) + " _________________________________________ " + str( np.round( self.fuel_blends["hydrogen"]["secondary"]["share"][ self.scope["year"].index(y) ] * 100, 0, ) ) + "%", end=end_str, ) # Primary fuel share for y in self.scope["year"]: ind_A = [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "Passenger" in i[0] and "FCEV" in i[0] ] ind_array = [ x for x in self.get_index_vehicle_from_array(y) if x in index ] self.A[ :, [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "fuel supply for hydrogen vehicles" in i[0] ], ind_A, ] = ( array[self.array_inputs["fuel mass"], :, ind_array] / array[self.array_inputs["range"], :, ind_array] * -1 ).T if "ICEV-g" in self.scope["powertrain"]: index = self.get_index_vehicle_from_array("ICEV-g") print( "{} is completed by {}.".format( self.fuel_blends["cng"]["primary"]["type"], self.fuel_blends["cng"]["secondary"]["type"], ), end="\n \t * ", ) for y in self.scope["year"]: if self.scope["year"].index(y) + 1 == len(self.scope["year"]): end_str = "\n * " else: end_str = "\n \t * " print( "in " + str(y) + " _________________________________________ " + str( np.round( self.fuel_blends["cng"]["secondary"]["share"][ self.scope["year"].index(y) ] * 100, 0, ) ) + "%", end=end_str, ) # Primary fuel share for y in self.scope["year"]: ind_A = [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "Passenger" in i[0] and "ICEV-g" in i[0] ] ind_array = [ x for x in self.get_index_vehicle_from_array(y) if x in index ] self.A[ :, [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "fuel supply for gas vehicles" in i[0] ], ind_A, ] = ( (array[self.array_inputs["fuel mass"], :, ind_array]) / array[self.array_inputs["range"], :, ind_array] * -1 ).T # Fuel-based emissions from CNG, CO2 # The share and CO2 emissions factor of CNG is retrieved, if used share_fossil = 0 CO2_fossil = 0 if self.fuel_blends["cng"]["primary"]["type"] == "cng": share_fossil += self.fuel_blends["cng"]["primary"]["share"][ self.scope["year"].index(y) ] CO2_fossil = self.fuel_blends["cng"]["primary"]["CO2"] if self.fuel_blends["cng"]["secondary"]["type"] == "cng": share_fossil += self.fuel_blends["cng"]["secondary"]["share"][ self.scope["year"].index(y) ] CO2_fossil = self.fuel_blends["cng"]["primary"]["CO2"] self.A[ :, self.inputs[("Carbon dioxide, fossil", ("air",), "kilogram")], ind_A, ] = ( array[self.array_inputs["fuel mass"], :, ind_array] * share_fossil * CO2_fossil / array[self.array_inputs["range"], :, ind_array] * -1 ).T # Fuel-based CO2 emission from alternative petrol # The share of non-fossil gas in the blend is retrieved # As well as the CO2 emission factor of the fuel share_non_fossil = 0 CO2_non_fossil = 0 if self.fuel_blends["cng"]["primary"]["type"] != "cng": share_non_fossil += self.fuel_blends["cng"]["primary"]["share"][ self.scope["year"].index(y) ] CO2_non_fossil = self.fuel_blends["cng"]["primary"]["CO2"] if self.fuel_blends["cng"]["secondary"]["type"] != "cng": share_non_fossil += self.fuel_blends["cng"]["secondary"]["share"][ self.scope["year"].index(y) ] CO2_non_fossil = self.fuel_blends["cng"]["secondary"]["CO2"] self.A[ :, self.inputs[("Carbon dioxide, from soil or biomass stock", ("air",), "kilogram")], ind_A, ] = ( ( (array[self.array_inputs["fuel mass"], :, ind_array] * share_non_fossil * CO2_non_fossil) ) / array[self.array_inputs["range"], :, ind_array] * -1 ).T if [i for i in self.scope["powertrain"] if i in ["ICEV-d", "PHEV-d", "HEV-d"]]: index = self.get_index_vehicle_from_array(["ICEV-d", "PHEV-d", "HEV-d"]) print( "{} is completed by {}.".format( self.fuel_blends["diesel"]["primary"]["type"], self.fuel_blends["diesel"]["secondary"]["type"], ), end="\n \t * ", ) for y in self.scope["year"]: if self.scope["year"].index(y) + 1 == len(self.scope["year"]): end_str = "\n * " else: end_str = "\n \t * " print( "in " + str(y) + " _________________________________________ " + str( np.round( self.fuel_blends["diesel"]["secondary"]["share"][ self.scope["year"].index(y) ] * 100, 0, ) ) + "%", end=end_str, ) for y in self.scope["year"]: ind_A = [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "Passenger" in i[0] and any(x in i[0] for x in ["ICEV-d", "PHEV-d", "HEV-d"]) ] ind_array = [ x for x in self.get_index_vehicle_from_array(y) if x in index ] # Fuel supply self.A[ :, [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "fuel supply for diesel vehicles" in i[0] ], ind_A, ] = ( (array[self.array_inputs["fuel mass"], :, ind_array]) / array[self.array_inputs["range"], :, ind_array] * -1 ).T share_fossil = 0 CO2_fossil = 0 # Fuel-based CO2 emission from conventional petrol if self.fuel_blends["diesel"]["primary"]["type"] == "diesel": share_fossil += self.fuel_blends["diesel"]["primary"]["share"][ self.scope["year"].index(y) ] CO2_fossil = self.fuel_blends["diesel"]["primary"]["CO2"] if self.fuel_blends["diesel"]["secondary"]["type"] == "diesel": share_fossil += self.fuel_blends["diesel"]["secondary"]["share"][ self.scope["year"].index(y) ] CO2_fossil = self.fuel_blends["diesel"]["secondary"]["CO2"] self.A[ :, self.inputs[("Carbon dioxide, fossil", ("air",), "kilogram")], ind_A, ] = ( ( (array[self.array_inputs["fuel mass"], :, ind_array] * share_fossil * CO2_fossil) ) / array[self.array_inputs["range"], :, ind_array] * -1 ).T share_non_fossil = 0 CO2_non_fossil = 0 # Fuel-based CO2 emission from alternative petrol # The share of non-fossil fuel in the blend is retrieved # As well as the CO2 emission factor of the fuel if self.fuel_blends["diesel"]["primary"]["type"] != "diesel": share_non_fossil += self.fuel_blends["diesel"]["primary"]["share"][ self.scope["year"].index(y) ] CO2_non_fossil = self.fuel_blends["diesel"]["primary"]["CO2"] if self.fuel_blends["diesel"]["secondary"]["type"] != "diesel": share_non_fossil += self.fuel_blends["diesel"]["secondary"]["share"][ self.scope["year"].index(y) ] CO2_non_fossil = self.fuel_blends["diesel"]["secondary"]["CO2"] self.A[ :, self.inputs[("Carbon dioxide, from soil or biomass stock", ("air",), "kilogram")], ind_A, ] = ( ( (array[self.array_inputs["fuel mass"], :, ind_array] * share_non_fossil * CO2_non_fossil) ) / array[self.array_inputs["range"], :, ind_array] * -1 ).T # Heavy metals emissions from conventional diesel # Emission factors from Spielmann et al., Transport Services Data v.2 (2007) # Cadmium, 0.01 mg/kg diesel self.A[ :, self.inputs[ ("Cadmium", ("air", "urban air close to ground"), "kilogram") ], ind_A, ] = ( ( (array[self.array_inputs["fuel mass"], :, ind_array] * share_fossil) * 1e-8 ) / array[self.array_inputs["range"], :, ind_array] * -1 ).T # Copper, 1.7 mg/kg diesel self.A[ :, self.inputs[ ("Copper", ("air", "urban air close to ground"), "kilogram") ], ind_A, ] = ( ( (array[self.array_inputs["fuel mass"], :, ind_array] * share_fossil) * 1.7e-6 ) / array[self.array_inputs["range"], :, ind_array] * -1 ).T # Chromium, 0.05 mg/kg diesel self.A[ :, self.inputs[ ("Chromium", ("air", "urban air close to ground"), "kilogram") ], ind_A, ] = ( ( (array[self.array_inputs["fuel mass"], :, ind_array] * share_fossil) * 5.0e-8 ) / array[self.array_inputs["range"], :, ind_array] * -1 ).T # Nickel, 0.07 mg/kg diesel self.A[ :, self.inputs[ ("Nickel", ("air", "urban air close to ground"), "kilogram") ], ind_A, ] = ( ( (array[self.array_inputs["fuel mass"], :, ind_array] * share_fossil) * 7.0e-8 ) / array[self.array_inputs["range"], :, ind_array] * -1 ).T # Selenium, 0.01 mg/kg diesel self.A[ :, self.inputs[ ("Selenium", ("air", "urban air close to ground"), "kilogram") ], ind_A, ] = ( ( (array[self.array_inputs["fuel mass"], :, ind_array] * share_fossil) * 1.0e-8 ) / array[self.array_inputs["range"], :, ind_array] * -1 ).T # Zinc, 1 mg/kg diesel self.A[ :, self.inputs[ ("Zinc", ("air", "urban air close to ground"), "kilogram") ], ind_A, ] = ( ( (array[self.array_inputs["fuel mass"], :, ind_array] * share_fossil) * 1.0e-6 ) / array[self.array_inputs["range"], :, ind_array] * -1 ).T # Chromium VI, 0.0001 mg/kg diesel self.A[ :, self.inputs[ ( "Chromium VI", ("air", "urban air close to ground"), "kilogram", ) ], ind_A, ] = ( ( (array[self.array_inputs["fuel mass"], :, ind_array] * share_fossil) * 1.0e-10 ) / array[self.array_inputs["range"], :, ind_array] * -1 ).T if [i for i in self.scope["powertrain"] if i in ["ICEV-p", "HEV-p", "PHEV-p"]]: index = self.get_index_vehicle_from_array(["ICEV-p", "HEV-p", "PHEV-p"]) print( "{} is completed by {}.".format( self.fuel_blends["petrol"]["primary"]["type"], self.fuel_blends["petrol"]["secondary"]["type"], ), end="\n \t * ", ) for y in self.scope["year"]: if self.scope["year"].index(y) + 1 == len(self.scope["year"]): end_str = "\n * " else: end_str = "\n \t * " print( "in " + str(y) + " _________________________________________ " + str( np.round( self.fuel_blends["petrol"]["secondary"]["share"][ self.scope["year"].index(y) ] * 100, 0, ) ) + "%", end=end_str, ) for y in self.scope["year"]: ind_A = [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "Passenger" in i[0] and any(x in i[0] for x in ["ICEV-p", "HEV-p", "PHEV-p"]) ] ind_array = [ x for x in self.get_index_vehicle_from_array(y) if x in index ] # Fuel supply self.A[ :, [ self.inputs[i] for i in self.inputs if str(y) in i[0] and "fuel supply for gasoline vehicles" in i[0] ], ind_A, ] = ( (array[self.array_inputs["fuel mass"], :, ind_array]) / array[self.array_inputs["range"], :, ind_array] * -1 ).T share_fossil = 0 CO2_fossil = 0 # Fuel-based CO2 emission from conventional petrol if self.fuel_blends["petrol"]["primary"]["type"] == "petrol": share_fossil += self.fuel_blends["petrol"]["primary"]["share"][ self.scope["year"].index(y) ] CO2_fossil = self.fuel_blends["petrol"]["primary"]["CO2"] if self.fuel_blends["petrol"]["secondary"]["type"] == "petrol": share_fossil += self.fuel_blends["petrol"]["secondary"]["share"][ self.scope["year"].index(y) ] CO2_fossil = self.fuel_blends["petrol"]["secondary"]["CO2"] self.A[ :, self.inputs[("Carbon dioxide, fossil", ("air",), "kilogram")], ind_A, ] = ( ( (array[self.array_inputs["fuel mass"], :, ind_array] * share_fossil * CO2_fossil) ) / array[self.array_inputs["range"], :, ind_array] * -1 ).T share_non_fossil = 0 CO2_non_fossil = 0 # Fuel-based CO2 emission from alternative petrol # The share of non-fossil fuel in the blend is retrieved # As well as the CO2 emission factor of the fuel if self.fuel_blends["petrol"]["primary"]["type"] != "petrol": share_non_fossil += self.fuel_blends["petrol"]["primary"]["share"][ self.scope["year"].index(y) ] CO2_non_fossil = self.fuel_blends["petrol"]["primary"]["CO2"] if self.fuel_blends["petrol"]["secondary"]["type"] != "petrol": share_non_fossil += self.fuel_blends["petrol"]["secondary"]["share"][ self.scope["year"].index(y) ] CO2_non_fossil = self.fuel_blends["petrol"]["secondary"]["CO2"] self.A[ :, self.inputs[("Carbon dioxide, from soil or biomass stock", ("air",), "kilogram")], ind_A, ] = ( ( (array[self.array_inputs["fuel mass"], :, ind_array] * share_non_fossil * CO2_non_fossil) ) / array[self.array_inputs["range"], :, ind_array] * -1 ).T # Heavy metals emissions from conventional petrol # Cadmium, 0.01 mg/kg gasoline self.A[ :, self.inputs[ ("Cadmium", ("air", "urban air close to ground"), "kilogram") ], ind_A, ] = ( ( (array[self.array_inputs["fuel mass"], :, ind_array] * share_fossil) * 1e-8 ) / array[self.array_inputs["range"], :, ind_array] * -1 ).T # Copper, 1.7 mg/kg gasoline self.A[ :, self.inputs[ ("Copper", ("air", "urban air close to ground"), "kilogram") ], ind_A, ] = ( ( (array[self.array_inputs["fuel mass"], :, ind_array] * share_fossil) * 1.7e-6 ) / array[self.array_inputs["range"], :, ind_array] * -1 ).T # Chromium, 0.05 mg/kg gasoline self.A[ :, self.inputs[ ("Chromium", ("air", "urban air close to ground"), "kilogram") ], ind_A, ] = ( ( (array[self.array_inputs["fuel mass"], :, ind_array] * share_fossil) * 5.0e-8 ) / array[self.array_inputs["range"], :, ind_array] * -1 ).T # Nickel, 0.07 mg/kg gasoline self.A[ :, self.inputs[ ("Nickel", ("air", "urban air close to ground"), "kilogram") ], ind_A, ] = ( ( (array[self.array_inputs["fuel mass"], :, ind_array] * share_fossil) * 7.0e-8 ) / array[self.array_inputs["range"], :, ind_array] * -1 ).T # Selenium, 0.01 mg/kg gasoline self.A[ :, self.inputs[ ("Selenium", ("air", "urban air close to ground"), "kilogram") ], ind_A, ] = ( ( (array[self.array_inputs["fuel mass"], :, ind_array] * share_fossil) * 1.0e-8 ) / array[self.array_inputs["range"], :, ind_array] * -1 ).T # Zinc, 1 mg/kg gasoline self.A[ :, self.inputs[ ("Zinc", ("air", "urban air close to ground"), "kilogram") ], ind_A, ] = ( ( (array[self.array_inputs["fuel mass"], :, ind_array] * share_fossil) * 1.0e-6 ) / array[self.array_inputs["range"], :, ind_array] * -1 ).T # Chromium VI, 0.0001 mg/kg gasoline self.A[ :, self.inputs[ ( "Chromium VI", ("air", "urban air close to ground"), "kilogram", ) ], ind_A, ] = ( ( (array[self.array_inputs["fuel mass"], :, ind_array] * share_fossil) * 1.0e-10 ) / array[self.array_inputs["range"], :, ind_array] * -1 ).T # Non-exhaust emissions self.A[ :, self.inputs[ ( "market for road wear emissions, passenger car", "GLO", "kilogram", "road wear emissions, passenger car", ) ], -self.number_of_cars :, ] = (array[self.array_inputs["driving mass"], :] * 1e-08) self.A[ :, self.inputs[ ( "market for tyre wear emissions, passenger car", "GLO", "kilogram", "tyre wear emissions, passenger car", ) ], -self.number_of_cars :, ] = (array[self.array_inputs["driving mass"], :] * 6e-08) self.A[ :, self.inputs[ ( "market for brake wear emissions, passenger car", "GLO", "kilogram", "brake wear emissions, passenger car", ) ], -self.number_of_cars :, ] = (array[self.array_inputs["driving mass"], :] * 5e-09) # Infrastructure self.A[ :, self.inputs[("market for road", "GLO", "meter-year", "road")], -self.number_of_cars :, ] = (5.37e-7 * array[self.array_inputs["driving mass"], :] * -1) # Infrastructure maintenance self.A[ :, self.inputs[ ("market for road maintenance", "RER", "meter-year", "road maintenance") ], -self.number_of_cars :, ] = (1.29e-3 * -1) # Exhaust emissions # Non-fuel based emissions self.A[:, self.index_emissions, -self.number_of_cars :] = ( array[ [ self.array_inputs[self.map_non_fuel_emissions[self.rev_inputs[x]]] for x in self.index_emissions ] ] * -1 ).transpose([1, 0, 2]) # Noise emissions self.A[:, self.index_noise, -self.number_of_cars :] = ( array[ [ self.array_inputs[self.map_noise_emissions[self.rev_inputs[x]]] for x in self.index_noise ] ] * -1 ).transpose([1, 0, 2]) print("*********************************************************************")
[ 6738, 764, 1330, 42865, 62, 34720, 198, 11748, 25064, 198, 11748, 15095, 198, 6738, 764, 25249, 62, 10057, 82, 1330, 25353, 11964, 17633, 198, 6738, 764, 39344, 1330, 36472, 818, 17158, 198, 6738, 10104, 1330, 1459, 14535, 11, 651, 14535,...
1.66917
61,923
# Django settings for gtd project. import os from django.contrib.messages import constants as message_constants DEBUG = get_debug_settings() BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = "America/Los_Angeles" # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = "en-us" SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "project.urls" LOGIN_URL = "/login" LOGIN_REDIRECT_URL = "todo:lists" LOGOUT_REDIRECT_URL = "home" SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_SECURITY_WARN_AFTER = 5 SESSION_SECURITY_EXPIRE_AFTER = 12 # See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application WSGI_APPLICATION = "project.wsgi.application" INSTALLED_APPS = ( "django.contrib.admin", "django.contrib.admindocs", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.flatpages", "django.contrib.messages", "django.contrib.sessions", "django.contrib.sites", "django.contrib.staticfiles", "todo", "django_extensions", ) # Static files and uploads STATIC_URL = "/static/" STATICFILES_DIRS = [os.path.join(BASE_DIR, "project", "static")] STATIC_ROOT = os.path.join(BASE_DIR, "static") # Uploaded media MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = "/media/" # Without this, uploaded files > 4MB end up with perm 0600, unreadable by web server process FILE_UPLOAD_PERMISSIONS = 0o644 TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(BASE_DIR, "project", "templates")], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.template.context_processors.i18n", "django.template.context_processors.media", "django.template.context_processors.static", "django.template.context_processors.tz", "django.contrib.messages.context_processors.messages", # Your stuff: custom template context processors go here ] }, } ] # Override CSS class for the ERROR tag level to match Bootstrap class name MESSAGE_TAGS = {message_constants.ERROR: "danger"} #################################################################### # Environment specific settings #################################################################### SECRET_KEY = os.environ.get('SECRET_KEY', 'lksdf98wrhkjs88dsf8-324ksdm') # DEBUG = True ALLOWED_HOSTS = ["*"] DATABASES = get_db_settings() EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # TODO-specific settings TODO_STAFF_ONLY = False TODO_DEFAULT_LIST_SLUG = 'tickets' TODO_DEFAULT_ASSIGNEE = None TODO_PUBLIC_SUBMIT_REDIRECT = '/' #################################################################### # ####################################################################
[ 2, 37770, 6460, 329, 308, 8671, 1628, 13, 198, 11748, 28686, 198, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 37348, 1095, 1330, 38491, 355, 3275, 62, 9979, 1187, 198, 198, 30531, 796, 651, 62, 24442, 62, 33692, 3419, 198, 198, 33, ...
2.633199
1,494
from flask_restful import Resource import requests import json import os import redis HEADER = { 'User-Agent': 'CompuServe Classic/1.22', 'Accept': 'application/json', 'Host': os.getenv("HOST"), 'Authorization': f'Bearer {os.getenv("ACESS_TOKEN")}' } class Search(Resource): """Recurso responsável por retornar lista de artistas, para o usuário escolher""" def get(self, artist_name): """ Retorna lista de artistas """ querystring = {"q": artist_name} url = f"https://{os.getenv('HOST')}/search" try: response = requests.get(url=url, headers=HEADER, params=querystring) if response.status_code != '200': return json.loads(response.text), response.status_code except Exception as e: print(e) return {"message": "Internal server error."}, 500 data = json.loads(response.text) return data, 200
[ 6738, 42903, 62, 2118, 913, 1330, 20857, 198, 198, 11748, 7007, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 2266, 271, 628, 198, 37682, 1137, 796, 1391, 198, 220, 220, 220, 705, 12982, 12, 36772, 10354, 705, 7293, 84, 50, 3760, ...
2.33414
413
# https://leetcode.com/problems/first-unique-character-in-a-string/
[ 2, 3740, 1378, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 11085, 12, 34642, 12, 22769, 12, 259, 12, 64, 12, 8841, 14, 198 ]
2.72
25
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 4981, 11, 15720, 602, 628 ]
2.891892
37
# Copyright (c) OpenMMLab. All rights reserved. from mmdet.datasets import DATASETS from .coco_video_dataset import CocoVideoDataset @DATASETS.register_module() class YouTubeVISDataset(CocoVideoDataset): """YouTube VIS dataset for video instance segmentation.""" CLASSES_2019_version = ('person', 'giant_panda', 'lizard', 'parrot', 'skateboard', 'sedan', 'ape', 'dog', 'snake', 'monkey', 'hand', 'rabbit', 'duck', 'cat', 'cow', 'fish', 'train', 'horse', 'turtle', 'bear', 'motorbike', 'giraffe', 'leopard', 'fox', 'deer', 'owl', 'surfboard', 'airplane', 'truck', 'zebra', 'tiger', 'elephant', 'snowboard', 'boat', 'shark', 'mouse', 'frog', 'eagle', 'earless_seal', 'tennis_racket') CLASSES_2021_version = ('airplane', 'bear', 'bird', 'boat', 'car', 'cat', 'cow', 'deer', 'dog', 'duck', 'earless_seal', 'elephant', 'fish', 'flying_disc', 'fox', 'frog', 'giant_panda', 'giraffe', 'horse', 'leopard', 'lizard', 'monkey', 'motorbike', 'mouse', 'parrot', 'person', 'rabbit', 'shark', 'skateboard', 'snake', 'snowboard', 'squirrel', 'surfboard', 'tennis_racket', 'tiger', 'train', 'truck', 'turtle', 'whale', 'zebra') @classmethod
[ 2, 15069, 357, 66, 8, 4946, 44, 5805, 397, 13, 1439, 2489, 10395, 13, 198, 6738, 8085, 15255, 13, 19608, 292, 1039, 1330, 360, 1404, 1921, 32716, 198, 198, 6738, 764, 66, 25634, 62, 15588, 62, 19608, 292, 316, 1330, 48222, 10798, 27...
1.804299
884
# SPDX-FileCopyrightText: 2021 easyDiffraction contributors <support@easydiffraction.org> # SPDX-License-Identifier: BSD-3-Clause # © 2021 Contributors to the easyDiffraction project <https://github.com/easyScience/easyDiffractionApp> __author__ = 'github.com/andrewsazonov' __version__ = '0.0.1' from random import random from PySide2.QtCore import QPointF from PySide2.QtCharts import QtCharts
[ 2, 30628, 55, 12, 8979, 15269, 8206, 25, 33448, 2562, 28813, 7861, 20420, 1279, 11284, 31, 38171, 26069, 7861, 13, 2398, 29, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 347, 10305, 12, 18, 12, 2601, 682, 198, 2, 10673, 33448,...
3.061069
131
# -*- coding: utf-8 -*- # python imports import os import subprocess import sys, traceback from flask.ext.migrate import MigrateCommand from flask.ext.script import Manager from database import manager as database_manager try: from project import app from project.application import configure_app from project.config import DefaultConfig, DevelopmentConfig, ProductionConfig except ImportError: print ' *** please install/update requirements or fix the problem ***' traceback.print_exc(file=sys.stdout) exit(0) manager = Manager(app) manager.add_command('database', database_manager) manager.add_command('migration', MigrateCommand) fwpath = os.path.abspath(os.path.dirname(__file__)) venv_dir = os.path.join(fwpath, 'venv') @manager.command @manager.command @manager.command @manager.command if __name__ == '__main__': manager.run()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 21015, 17944, 198, 11748, 28686, 198, 11748, 850, 14681, 198, 11748, 25064, 11, 12854, 1891, 198, 6738, 42903, 13, 2302, 13, 76, 42175, 1330, 337, 42175, 21575, ...
3.193431
274
"""PROV model fpr GitLab2PROV.""" __author__ = "Claas de Boer, Andreas Schreiber, Lynn von Kurnatowski" __copyright__ = "Copyright 2020, German Aerospace Center (DLR) and individual contributors" __license__ = "MIT" __version__ = "0.5" __status__ = "Development" from prov.model import ProvDocument from prov.constants import PROV_LABEL from prov.dot import prov_to_dot add = ProvDocument() add.set_default_namespace("gitlab2prov:") add.activity("Commit", other_attributes={"prov:type": "commit", "title": "", "message": "", "id": "", "short_id": "", "prov:startedAt": "", "prov:endedAt": ""}) add.activity("Parent Commit", other_attributes={"prov:type": "commit", "title": "", "message": "", "id": "", "short_id": "", "prov:startedAt": "", "prov:endedAt": ""}) add.agent("Committer", other_attributes={"prov:type": "user", "prov:role": "committer", "name": "", "email": ""}) add.agent("Author", other_attributes={"prov:type": "user", "prov:role": "author", "name": "", "email": ""}) add.entity("File", other_attributes={"prov:type": "file", "path_at_addition": ""}) add.entity("File Version", other_attributes={"prov:type": "file_version", "old_path": "", "new_path": ""}) add.wasInformedBy("Commit", "Parent Commit") add.wasAssociatedWith("Commit", "Committer") add.wasAssociatedWith("Commit", "Author") add.wasGeneratedBy("File", "Commit") add.wasGeneratedBy("File Version", "Commit") add.wasAttributedTo("File", "Author") add.wasAttributedTo("File Version", "Author") add.specializationOf("File Version", "File") mod = ProvDocument() mod.set_default_namespace("gitlab2prov:") mod.activity("Commit", other_attributes={"prov:type": "commit", "title": "", "message": "", "id": "", "short_id": "", "prov:startedAt": "", "prov:endedAt": ""},) mod.activity("Parent Commit", other_attributes={"prov:type": "commit", "title": "", "message": "", "id": "", "short_id": "", "prov:startedAt": "", "prov:endedAt": ""},) mod.agent("Committer", other_attributes={"prov:type": "user", "prov:role": "committer", "name": "", "email": ""}) mod.agent("Author", other_attributes={"prov:type": "user", "prov:role": "author", "name": "", "email": "",}) mod.entity("File", other_attributes={"prov:type": "file", "path_at_addition": ""}) mod.entity("File Version N", other_attributes={"prov:type": "file_version", "new_path": "", "old_path": ""}) mod.entity("File Version N-1", other_attributes={"prov:type": "file_version", "new_path": "", "old_path": ""}) mod.wasInformedBy("Commit", "Parent Commit") mod.wasAssociatedWith("Commit", "Author") mod.wasAssociatedWith("Commit", "Committer") mod.used("Commit", "File Version N-1") mod.wasGeneratedBy("File Version N", "Commit") mod.wasRevisionOf("File Version N", "File Version N-1") mod.specializationOf("File Version N", "File") mod.specializationOf("File Version N-1", "File") mod.wasAttributedTo("File Version N", "Author") rem = ProvDocument() rem.set_default_namespace("gitlab2prov:") rem.activity("Commit", other_attributes={"prov:type": "commit", "title": "", "message": "", "id": "", "short_id": "", "prov:startedAt": "", "prov:endedAt": ""}) rem.activity("Parent Commit", other_attributes={"prov:type": "commit", "title": "", "message": "", "id": "", "short_id": "", "prov:startedAt": "", "prov:endedAt": ""}) rem.agent("Committer", other_attributes={"prov:type": "user", "prov:role": "committer", "name": "", "email": ""}) rem.agent("Author", other_attributes={"prov:type": "user", "prov:role": "author", "name": "", "email": ""}) rem.entity("File", other_attributes={"prov:type": "file", "path_at_addition": ""}) rem.entity("File Version", other_attributes={"prov:type": "file_version", "new_path": "", "old_path": ""}) rem.wasInformedBy("Commit", "Parent Commit") rem.wasAssociatedWith("Commit", "Committer") rem.wasAssociatedWith("Commit", "Author") rem.wasInvalidatedBy("File Version", "Commit") rem.specializationOf("File Version", "File") com = ProvDocument() com.set_default_namespace("gitlab2prov:") com.agent("Creator", other_attributes={"prov:type": "user", "prov:role": "creator", "name": ""}) com.agent("Annotator", other_attributes={"prov:type": "user", "prov:role": "initiator", "name": ""}) com.activity("Commit Creation", other_attributes={"prov:type": "creation", "prov:startedAt": "", "prov:endedAt": ""}) com.activity("Commit Annotation", other_attributes={"prov:type": "event", "prov:startedAt": "", "prov:endedAt": "", "event": ""}) com.activity("Git Commit", other_attributes={"prov:type": "commit", "title": "", "message": "", "id": "", "short_id": "", "prov:startedAt": "", "prov:endedAt": ""}) com.wasInformedBy("Commit Creation", "Git Commit") com.entity("Commit", other_attributes={"prov:type": "commit_resource", "title": "", "message": "", "short_id": "", "id": ""}) com.entity("Commit Version", other_attributes={"prov:type": "commit_resource_version"}) com.entity("Annotated Commit Version", other_attributes={"prov:type": "commit_resource_version"},) com.wasAssociatedWith("Commit Creation", "Creator") com.wasAttributedTo("Commit", "Creator") com.wasAttributedTo("Commit Version", "Creator") com.wasGeneratedBy("Commit", "Commit Creation") com.wasGeneratedBy("Commit Version", "Commit Creation") com.wasAttributedTo("Annotated Commit Version", "Annotator") com.wasAssociatedWith("Commit Annotation", "Annotator") com.used("Commit Annotation", "Commit Version") com.wasInformedBy("Commit Annotation", "Commit Creation") com.wasGeneratedBy("Annotated Commit Version", "Commit Annotation") com.specializationOf("Commit Version", "Commit") com.specializationOf("Annotated Commit Version", "Commit") com.wasDerivedFrom("Annotated Commit Version", "Commit Version") mr = ProvDocument() mr.set_default_namespace("gitlab2prov:") mr.agent("Creator", other_attributes={"prov:type": "user", "prov:role": "creator", "name": ""},) mr.agent("Annotator", other_attributes={"prov:type": "user", "prov:role": "initiator", "name": ""}) mr.activity("Merge Request Creation", other_attributes={"prov:type": "merge_request_creation", "prov:startedAt": "", "prov:endedAt": ""}) mr.activity("Merge Request Annotation", other_attributes={"prov:type": "event", "prov:startedAt": "", "prov:endedAt": "", "event": ""}) mr.entity("Merge Request", other_attributes={"prov:type": "merge_request_resource", "id": "", "iid": "", "title": "", "description": "", "web_url": "", "project_id": "", "source_branch": "", "target_branch": "", "source_project_url": "", "target_project_url": ""}) mr.entity("Merge Request Version", other_attributes={"prov:type": "merge_request_resource_version"},) mr.entity("Annotated Merge Request Version", other_attributes={"prov:type": "merge_request_resource_version"},) mr.wasInformedBy("Merge Request Annotation", "Merge Request Creation") mr.wasGeneratedBy("Merge Request", "Merge Request Creation") mr.wasGeneratedBy("Merge Request Version", "Merge Request Creation") mr.wasGeneratedBy("Annotated Merge Request Version", "Merge Request Annotation") mr.used("Merge Request Annotation", "Merge Request Version") mr.specializationOf("Merge Request Version", "Merge Request") mr.specializationOf("Annotated Merge Request Version", "Merge Request") mr.wasDerivedFrom("Annotated Merge Request Version", "Merge Request Version") mr.wasAttributedTo("Annotated Merge Request Version", "Annotator") mr.wasAttributedTo("Merge Request Version", "Creator") mr.wasAttributedTo("Merge Request", "Creator") mr.wasAssociatedWith("Merge Request Creation", "Creator") mr.wasAssociatedWith("Merge Request Annotation", "Annotator") iss = ProvDocument() iss.set_default_namespace("gitlab2prov:") iss.agent("Creator", other_attributes={"prov:type": "user", "prov:role": "creator", "name": ""}) iss.agent("Annotator", other_attributes={"prov:type": "user", "prov:role": "initiator", "name": ""}) iss.activity("Issue Creation", other_attributes={"prov:type": "issue_creation", "prov:startedAt": "", "prov:endedAt": ""}) iss.activity("Issue Annotation", other_attributes={"prov:type": "event", "prov:startedAt": "", "prov:endedAt": "", "event": ""}) iss.entity("Issue", other_attributes={"prov:type": "issue_resource", "id": "", "iid": "", "title": "", "description": "", "project_id": "", "web_url": ""}) iss.entity("Issue Version", other_attributes={"prov:type": "issue_resource_version"}) iss.entity("Annotated Issue Version", other_attributes={"prov:type": "issue_resource_version"}) iss.wasInformedBy("Issue Annotation", "Issue Creation") iss.wasGeneratedBy("Issue", "Issue Creation") iss.wasGeneratedBy("Issue Version", "Issue Creation") iss.wasGeneratedBy("Annotated Issue Version", "Issue Annotation") iss.used("Issue Annotation", "Issue Version") iss.specializationOf("Issue Version", "Issue") iss.specializationOf("Annotated Issue Version", "Issue") iss.wasDerivedFrom("Annotated Issue Version", "Issue Version") iss.wasAttributedTo("Annotated Issue Version", "Annotator") iss.wasAttributedTo("Issue Version", "Creator") iss.wasAttributedTo("Issue", "Creator") iss.wasAssociatedWith("Issue Creation", "Creator") iss.wasAssociatedWith("Issue Annotation", "Annotator") release_tag_model = ProvDocument() release_tag_model.set_default_namespace("gitlab2prov:") release_tag_model.agent("User", {"name": "", "email": ""}) release_tag_model.activity("Release_Event") release_tag_model.activity("Tag_Event") release_tag_model.activity("Commit_Event") release_tag_model.entity("Tag", {"prov:type": "prov:Collection", "name": "", "message": "", "commit": "", "target_commit": ""}) release_tag_model.entity("Release", {"prov:type": "prov:Collection", "name": "", "tag_name": "", "description": "", "created_at": "", "released_at": "", "commit_path": "", "tag_path": ""}) release_tag_model.entity("Commit", {"id": "", "short_id": "", "title": "", "message": "", "web_url": "", "created_at": ""}) release_tag_model.entity("Release_Evidence", {"sha": "", "filepath": "", "collected_at": ""}) release_tag_model.entity("Release_Asset", {"uri": "", "format": "", "filepath": ""}) release_tag_model.hadMember("Release_Asset", "Release") release_tag_model.hadMember("Release_Evidence", "Release") release_tag_model.hadMember("Tag", "Release") release_tag_model.hadMember("Commit", "Tag") release_tag_model.wasAssociatedWith("Commit_Event", "User") release_tag_model.wasAssociatedWith("Release_Event", "User") release_tag_model.wasAssociatedWith("Tag_Event", "User") release_tag_model.wasAttributedTo("Release", "User") release_tag_model.wasAttributedTo("Tag", "User") release_tag_model.wasAttributedTo("Commit", "User") release_tag_model.wasGeneratedBy("Release", "Release_Event") release_tag_model.wasGeneratedBy("Tag", "Tag_Event") release_tag_model.wasGeneratedBy("Commit", "Commit_Event") for title, doc in [ ("git_commit_model_add", add), ("git_commit_model_mod", mod), ("git_commit_model_del", rem), ("gitlab_commit_model", com), ("gitlab_issue_model", iss), ("gitlab_merge_request_model", mr), ("gitlab_release_tag_model", release_tag_model) ]: prov_to_dot(doc, show_nary=False, use_labels=False, direction="BT").write_pdf( f"pdfs/{title}.pdf" ) prov_to_dot(doc, show_nary=False, use_labels=False, direction="BT").write_svg( f"svgs/{title}.svg" )
[ 37811, 41283, 2746, 277, 1050, 15151, 17822, 17, 41283, 526, 15931, 198, 198, 834, 9800, 834, 796, 366, 47404, 292, 390, 3248, 263, 11, 33728, 3059, 260, 1856, 11, 24868, 18042, 509, 700, 265, 12079, 1, 198, 834, 22163, 4766, 834, 796...
2.971809
3,760
import json import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry from enum import Enum # This is a hard coded list of evidence, better organized for readability ev_all = ['EXP', 'IDA', 'IMP', 'IGI', 'IPI', 'IEP', 'IGC', 'RCA', 'IBA', 'IKR', 'IC', 'NAS', 'ND', 'TAS', 'HDA', 'HEP', 'HGI', 'HMP', 'ISA', 'ISM', 'ISO', 'ISS', 'IEA'] # This is a hard coded list of reference genomes that should always be present in a GO release REFERENCE_GENOME_IDS = [ "NCBITaxon:9606", "NCBITaxon:10116", "NCBITaxon:10090", "NCBITaxon:3702", "NCBITaxon:7955", "NCBITaxon:6239", "NCBITaxon:559292", "NCBITaxon:7227", "NCBITaxon:44689", "NCBITaxon:4896", "NCBITaxon:83333" ] BP_TERM_ID = "GO:0008150" MF_TERM_ID = "GO:0003674" CC_TERM_ID = "GO:0005575" # useful grouping of evidences as discussed with Pascale EVIDENCE_GROUPS = { "EXP": ["EXP", "IDA", "IEP", "IGI", "IMP", "IPI"], "HTP": ["HDA", "HEP", "HGI", "HMP", "HTP"], "PHYLO": ["IBA", "IRD", "IKR", "IMR"], "IEA": ["IEA"], "ND": ["ND"], "OTHER": ["IC", "IGC", "ISA", "ISM", "ISO", "ISS", "NAS", "RCA", "TAS"] } EVIDENCE_MIN_GROUPS = { "EXPERIMENTAL" : EVIDENCE_GROUPS["EXP"] + EVIDENCE_GROUPS["HTP"], "COMPUTATIONAL" : EVIDENCE_GROUPS["PHYLO"] + EVIDENCE_GROUPS["IEA"] + EVIDENCE_GROUPS["OTHER"] } global_session = None def fetch(url): """ Error proof method to get data from HTTP request If an error occured, return None """ global global_session # Ensure we are using the same session - creating too many sessions could crash this script if global_session is None: global_session = requests_retry(global_session) try: r = global_session.get(url) return r except Exception as x: print("Query GET " , url , " failed: ", x) return None def golr_fetch(golr_base_url, select_query): """ Error proof method to get data from GOLr If an HTTP error occurs, return None, otherwise return the json object """ r = fetch(golr_base_url + select_query) if r is None: return None response = r.json() return response # utility function to build a list from a solr/golr facet array # utility function to transform a list [A, 1, B, 2] into a map {A: 1, B: 2} # utility function to build a reverse map: { "a": 1, "b": 1, "c": 2 } -> {1: ["a", "b"], 2: ["c"]} # utility function to cluster elements of an input map based on another map of synonyms # similar as above but the value of each key is also a map # reorder map (python 3.6 keeps order in which items are inserted in map: https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) def bioentity_type(str_type): """ In a nutshell, collapse all RNA related types into RNA """ if "RNA" in str_type or "ribozyme" in str_type or "transcript" in str_type: return "RNA_cluster" return str_type def sum_map_values(map): """ Utility function to sum up the values of a map. Assume the map values are all numbers """ total = 0 for key, val in map.items(): total += val return total
[ 11748, 33918, 198, 11748, 7007, 198, 6738, 7007, 13, 324, 12126, 1330, 14626, 47307, 198, 6738, 2956, 297, 571, 18, 13, 22602, 13, 1186, 563, 1330, 4990, 563, 198, 6738, 33829, 1330, 2039, 388, 198, 198, 2, 770, 318, 257, 1327, 30817,...
2.47907
1,290
from django.urls import reverse
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 628 ]
3.666667
9
num_list = [1,2,3,4] months = ['Jan', 'Feb', 'Mar', 'Apr'] months_dict = dict(zip(months, num_list))
[ 22510, 62, 4868, 796, 685, 16, 11, 17, 11, 18, 11, 19, 60, 198, 198, 41537, 796, 37250, 12128, 3256, 705, 15146, 3256, 705, 7676, 3256, 705, 13680, 20520, 198, 198, 41537, 62, 11600, 796, 8633, 7, 13344, 7, 41537, 11, 997, 62, 486...
2.266667
45
# SPDX-License-Identifier: MIT """The application's interfaces that are used to connect the different components. Notes ----- This package's code is not really specific to the Django framework. It is an abstraction layer. Primary focus is the provision of a plugin API, that allows the app to be extendable with third-party applications. """
[ 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 17168, 198, 198, 37811, 464, 3586, 338, 20314, 326, 389, 973, 284, 2018, 262, 1180, 6805, 13, 198, 198, 16130, 198, 30934, 198, 1212, 5301, 338, 2438, 318, 407, 1107, 2176, 284, 262, 377...
4.058824
85
# =================================== # Name: Edward (Eddie) Guo # ID: 1576381 # Partner: Jason Kim # CMPUT 275, Fall 2020 # # Final Assignment: EEG Visualizer # =================================== """ Contains the QApplication which holds the PlotWindow QMainWindow object. The controller class is here for convenient additions of extra QMainWindows. """ import sys # for UI from PyQt5 import QtCore, QtWidgets from plot_window import PlotWindow class Controller: """Controller class for slave QMainWindows. Used for expandability in case the user wishes to create additional windows for the program (ex: home window). """ def show_plot_window(self): """Creates the main window (EEG and FFT plots) from plot_window.py. """ self.plot_window = QtWidgets.QMainWindow() self.ui = PlotWindow() self.ui.setup_ui(self.plot_window) self.plot_window.setWindowFlags(QtCore.Qt.Window) self.plot_window.show() app.aboutToQuit.connect(self.close_threads) def close_threads(self): """Helper function that closes all running threads when the application is about to quit. """ self.ui.close_threads() if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) controller = Controller() controller.show_plot_window() sys.exit(app.exec_())
[ 2, 46111, 855, 198, 2, 220, 220, 6530, 25, 10443, 357, 36, 1860, 494, 8, 1962, 78, 198, 2, 220, 220, 4522, 25, 1315, 4304, 36626, 198, 2, 220, 220, 35532, 25, 8982, 6502, 198, 2, 220, 220, 327, 7378, 3843, 25829, 11, 7218, 12131...
2.80202
495
# -*- coding: utf-8 -*- """Test Code in __init__.""" __all__ = [ "test_get_path_to_file", ] ############################################################################## # IMPORTS # BUILT-IN import os.path # PROJECT-SPECIFIC from utilipy.data_utils.utils import get_path_to_file ############################################################################## # PARAMETERS ############################################################################## # CODE ############################################################################## # /def # ------------------------------------------------------------------- ############################################################################## # END
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 14402, 6127, 287, 11593, 15003, 834, 526, 15931, 198, 198, 834, 439, 834, 796, 685, 198, 220, 220, 220, 366, 9288, 62, 1136, 62, 6978, 62, 1462, 62, 7753, ...
4.793333
150
# Generated by Django 3.1.7 on 2021-04-20 16:20 from django.db import migrations, models import django.db.models.deletion
[ 2, 2980, 515, 416, 37770, 513, 13, 16, 13, 22, 319, 33448, 12, 3023, 12, 1238, 1467, 25, 1238, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 9945, 13, 27530, 13, 2934, 1616, 295, ...
2.818182
44
# Copyright 2021 The Kubeflow Authors # # 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. """Classes and methods that supports argument for ParallelFor.""" import re from typing import Any, Dict, List, Optional, Tuple, Union, get_type_hints from kfp.v2.components.experimental import pipeline_channel ItemList = List[Union[int, float, str, Dict[str, Any]]] def _get_loop_item_type(type_name: str) -> Optional[str]: """Extracts the loop item type. This method is used for extract the item type from a collection type. For example: List[str] -> str typing.List[int] -> int typing.Sequence[str] -> str List -> None str -> None Args: type_name: The collection type name, like `List`, Sequence`, etc. Returns: The collection item type or None if no match found. """ match = re.match('(typing\.)?(?:\w+)(?:\[(?P<item_type>.+)\])', type_name) if match: return match.group('item_type').lstrip().rstrip() else: return None def _get_subvar_type(type_name: str) -> Optional[str]: """Extracts the subvar type. This method is used for extract the value type from a dictionary type. For example: Dict[str, int] -> int typing.Mapping[str, float] -> float Args: type_name: The dictionary type. Returns: The dictionary value type or None if no match found. """ match = re.match( '(typing\.)?(?:\w+)(?:\[\s*(?:\w+)\s*,\s*(?P<value_type>.+)\])', type_name) if match: return match.group('value_type').lstrip().rstrip() else: return None class LoopArgument(pipeline_channel.PipelineChannel): """Represents the argument that are looped over in a ParallelFor loop. The class shouldn't be instantiated by the end user, rather it is created automatically by a ParallelFor ops group. To create a LoopArgument instance, use one of its factory methods:: LoopArgument.from_pipeline_channel(...) LoopArgument.from_raw_items(...) Attributes: items_or_pipeline_channel: The raw items or the PipelineChannel object this LoopArgument is associated to. """ LOOP_ITEM_NAME_BASE = 'loop-item' LOOP_ITEM_PARAM_NAME_BASE = 'loop-item-param' def __init__( self, items: Union[ItemList, pipeline_channel.PipelineChannel], name_code: Optional[str] = None, name_override: Optional[str] = None, **kwargs, ): """Initializes a LoopArguments object. Args: items: List of items to loop over. If a list of dicts then, all dicts must have the same keys and every key must be a legal Python variable name. name_code: A unique code used to identify these loop arguments. Should match the code for the ParallelFor ops_group which created these LoopArguments. This prevents parameter name collisions. name_override: The override name for PipelineChannel. **kwargs: Any other keyword arguments passed down to PipelineChannel. """ if (name_code is None) == (name_override is None): raise ValueError( 'Expect one and only one of `name_code` and `name_override` to ' 'be specified.') if name_override is None: super().__init__(name=self._make_name(name_code), **kwargs) else: super().__init__(name=name_override, **kwargs) if not isinstance(items, (list, tuple, pipeline_channel.PipelineChannel)): raise TypeError( f'Expected list, tuple, or PipelineChannel, got {items}.') if isinstance(items, tuple): items = list(items) self.items_or_pipeline_channel = items self._referenced_subvars: Dict[str, LoopArgumentVariable] = {} if isinstance(items, list) and isinstance(items[0], dict): subvar_names = set(items[0].keys()) # then this block creates loop_arg.variable_a and loop_arg.variable_b for subvar_name in subvar_names: loop_arg_var = LoopArgumentVariable( loop_argument=self, subvar_name=subvar_name, ) self._referenced_subvars[subvar_name] = loop_arg_var setattr(self, subvar_name, loop_arg_var) def _make_name(self, code: str): """Makes a name for this loop argument from a unique code.""" return '{}-{}'.format(self.LOOP_ITEM_PARAM_NAME_BASE, code) @classmethod def from_pipeline_channel( cls, channel: pipeline_channel.PipelineChannel, ) -> 'LoopArgument': """Creates a LoopArgument object from a PipelineChannel object.""" return LoopArgument( items=channel, name_override=channel.name + '-' + cls.LOOP_ITEM_NAME_BASE, task_name=channel.task_name, channel_type=_get_loop_item_type(channel.channel_type), ) @classmethod def from_raw_items( cls, raw_items: ItemList, name_code: str, ) -> 'LoopArgument': """Creates a LoopArgument object from raw item list.""" if len(raw_items) == 0: raise ValueError('Got an empty item list for loop argument.') return LoopArgument( items=raw_items, name_code=name_code, channel_type=type(raw_items[0]).__name__, ) @classmethod def name_is_loop_argument(cls, name: str) -> bool: """Returns True if the given channel name looks like a loop argument. Either it came from a withItems loop item or withParams loop item. """ return ('-' + cls.LOOP_ITEM_NAME_BASE) in name \ or (cls.LOOP_ITEM_PARAM_NAME_BASE + '-') in name class LoopArgumentVariable(pipeline_channel.PipelineChannel): """Represents a subvariable for a loop argument. This is used for cases where we're looping over maps, each of which contains several variables. If the user ran: with dsl.ParallelFor([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]) as item: ... Then there's one LoopArgumentVariable for 'a' and another for 'b'. Attributes: loop_argument: The original LoopArgument object this subvariable is attached to. subvar_name: The subvariable name. """ SUBVAR_NAME_DELIMITER = '-subvar-' LEGAL_SUBVAR_NAME_REGEX = re.compile(r'^[a-zA-Z_][0-9a-zA-Z_]*$') def __init__( self, loop_argument: LoopArgument, subvar_name: str, ): """Initializes a LoopArgumentVariable instance. Args: loop_argument: The LoopArgument object this subvariable is based on a subvariable to. subvar_name: The name of this subvariable, which is the name of the dict key that spawned this subvariable. Raises: ValueError is subvar name is illegal. """ if not self._subvar_name_is_legal(subvar_name): raise ValueError( f'Tried to create subvariable named {subvar_name}, but that is ' 'not a legal Python variable name.') self.subvar_name = subvar_name self.loop_argument = loop_argument super().__init__( name=self._get_name_override( loop_arg_name=loop_argument.name, subvar_name=subvar_name, ), task_name=loop_argument.task_name, channel_type=_get_subvar_type(loop_argument.channel_type), ) def _subvar_name_is_legal(self, proposed_variable_name: str) -> bool: """Returns True if the subvar name is legal.""" return re.match(self.LEGAL_SUBVAR_NAME_REGEX, proposed_variable_name) is not None def _get_name_override(self, loop_arg_name: str, subvar_name: str) -> str: """Gets the name. Args: loop_arg_name: the name of the loop argument parameter that this LoopArgumentVariable is attached to. subvar_name: The name of this subvariable. Returns: The name of this loop arg variable. """ return f'{loop_arg_name}{self.SUBVAR_NAME_DELIMITER}{subvar_name}'
[ 2, 15069, 33448, 383, 24921, 891, 9319, 46665, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 198, ...
2.337441
3,814
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import datetime os.chdir(os.path.abspath(os.path.dirname(__file__))) LINUX_DISTROS = [ "almalinux-8", "amazon-2", "arch", "centos-7", "centos-8", "debian-10", "debian-11", "debian-9", "fedora-33", "fedora-34", "fedora-35", "gentoo", "gentoo-systemd", "opensuse-15", "opensuse-tumbleweed", "oraclelinux-7", "oraclelinux-8", "rockylinux-8", "ubuntu-1804", "ubuntu-2004", "ubuntu-2104", ] OSX = WINDOWS = [] STABLE_DISTROS = [ "amazon-2", "centos-7", "centos-8", "debian-10", "debian-11", "debian-9", "fedora-33", "fedora-34", "fedora-35", "gentoo", "gentoo-systemd", "oraclelinux-7", "oraclelinux-8", "ubuntu-1804", "ubuntu-2004", "ubuntu-2104", ] PY2_BLACKLIST = [ "almalinux-8", "centos-8", "debian-10", "debian-11", "fedora-33", "fedora-34", "fedora-35", "gentoo", "gentoo-systemd", "opensuse-15", "opensuse-tumbleweed", "oraclelinux-8", "rockylinux-8", "ubuntu-2004", "ubuntu-2104", ] BLACKLIST_3000 = [ "almalinux-8", "debian-11", "fedora-33", "fedora-34", "fedora-35", "opensuse-tumbleweed", "rockylinux-8", "ubuntu-2004", "ubuntu-2104", ] BLACKLIST_3001 = [ "almalinux-8", "debian-11", "rockylinux-8", "ubuntu-2104", ] BLACKLIST_3001_0 = [ "almalinux-8", "debian-11", "gentoo", "gentoo-systemd", "rockylinux-8", "ubuntu-2104", ] BLACKLIST_3002_0 = [ "almalinux-8", "debian-11", "gentoo", "gentoo-systemd", "rockylinux-8", "ubuntu-2104", ] SALT_BRANCHES = [ "3000", "3001", "3001-0", "3002", "3002-0", "master", "latest", ] BRANCH_DISPLAY_NAMES = { "3000": "v3000", "3001": "v3001", "3001-0": "v3001.0", "3002": "v3002", "3002-0": "v3002.0", "master": "Master", "latest": "Latest", } STABLE_BRANCH_BLACKLIST = [] LATEST_PKG_BLACKLIST = [] DISTRO_DISPLAY_NAMES = { "almalinux-8": "AlmaLinux 8", "amazon-2": "Amazon 2", "arch": "Arch", "centos-7": "CentOS 7", "centos-8": "CentOS 8", "debian-10": "Debian 10", "debian-11": "Debian 11", "debian-9": "Debian 9", "fedora-33": "Fedora 33", "fedora-34": "Fedora 34", "fedora-35": "Fedora 35", "gentoo": "Gentoo", "gentoo-systemd": "Gentoo (systemd)", "opensuse-15": "Opensuse 15", "opensuse-tumbleweed": "Opensuse Tumbleweed", "oraclelinux-7": "Oracle Linux 7", "oraclelinux-8": "Oracle Linux 8", "rockylinux-8": "Rocky Linux 8", "ubuntu-1804": "Ubuntu 18.04", "ubuntu-2004": "Ubuntu 20.04", "ubuntu-2104": "Ubuntu 21.04", } TIMEOUT_DEFAULT = 20 TIMEOUT_OVERRIDES = { "gentoo": 90, "gentoo-systemd": 90, } BRANCH_ONLY_OVERRIDES = [ "gentoo", "gentoo-systemd", ] if __name__ == "__main__": generate_test_jobs()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 28686, 198, 11748, 4818, 8079, 198, 198, 418, 13, 354, 15908, 7, 418, 13, 6978, 13, 397, 2777, 776, 7, 418, ...
1.901078
1,577
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM Corp. 2017 and later. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """ The Shor's Factoring algorithm. """ import math import array import fractions import logging import numpy as np from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister from qiskit.aqua.utils.arithmetic import is_power from qiskit.aqua import AquaError, Pluggable from qiskit.aqua.utils import get_subsystem_density_matrix from qiskit.aqua.algorithms import QuantumAlgorithm from qiskit.aqua.circuits import FourierTransformCircuits as ftc from qiskit.aqua.circuits.gates import mcu1 from qiskit.aqua.utils import summarize_circuits logger = logging.getLogger(__name__) class Shor(QuantumAlgorithm): """ The Shor's Factoring algorithm. Adapted from https://github.com/ttlion/ShorAlgQiskit """ PROP_N = 'N' PROP_A = 'a' CONFIGURATION = { 'name': 'Shor', 'description': "The Shor's Factoring Algorithm", 'input_schema': { '$schema': 'http://json-schema.org/schema#', 'id': 'shor_schema', 'type': 'object', 'properties': { PROP_N: { 'type': 'integer', 'default': 15, 'minimum': 3 }, PROP_A: { 'type': 'integer', 'default': 2, 'minimum': 2 }, }, 'additionalProperties': False }, 'problems': ['factoring'], } def __init__(self, N=15, a=2): """ Constructor. Args: N (int): The integer to be factored. a (int): A random integer a that satisfies a < N and gcd(a, N) = 1 """ self.validate(locals()) super().__init__() # check the input integer if N < 1 or N % 2 == 0: raise AquaError('The input needs to be an odd integer greater than 1.') self._N = N if a >= N or math.gcd(a, self._N) != 1: raise AquaError('The integer a needs to satisfy a < N and gcd(a, N) = 1.') self._a = a self._ret = {'factors': []} # check if the input integer is a power tf, b, p = is_power(N, return_decomposition=True) if tf: logger.info('The input integer is a power: {}={}^{}.'.format(N, b, p)) self._ret['factors'].append(b) @classmethod def init_params(cls, params, algo_input): """ Initialize via parameters dictionary and algorithm input instance. Args: params: parameters dictionary algo_input: input instance """ if algo_input is not None: raise AquaError("Input instance not supported.") shor_params = params.get(Pluggable.SECTION_KEY_ALGORITHM) N = shor_params.get(Shor.PROP_N) return cls(N) def _get_angles(self, a): """ Calculate the array of angles to be used in the addition in Fourier Space """ s = bin(int(a))[2:].zfill(self._n + 1) angles = np.zeros([self._n + 1]) for i in range(0, self._n + 1): for j in range(i, self._n + 1): if s[j] == '1': angles[self._n - i] += math.pow(2, -(j - i)) angles[self._n - i] *= np.pi return angles def _phi_add(self, circuit, q, inverse=False): """ Creation of the circuit that performs addition by a in Fourier Space Can also be used for subtraction by setting the parameter inverse=True """ angle = self._get_angles(self._N) for i in range(0, self._n + 1): circuit.u1(-angle[i] if inverse else angle[i], q[i]) def _controlled_phi_add(self, circuit, q, ctl, inverse=False): """ Single controlled version of the _phi_add circuit """ angles = self._get_angles(self._N) for i in range(0, self._n + 1): angle = (-angles[i] if inverse else angles[i]) / 2 circuit.u1(angle, ctl) circuit.cx(ctl, q[i]) circuit.u1(-angle, q[i]) circuit.cx(ctl, q[i]) circuit.u1(angle, q[i]) def _controlled_controlled_phi_add(self, circuit, q, ctl1, ctl2, a, inverse=False): """ Doubly controlled version of the _phi_add circuit """ angle = self._get_angles(a) for i in range(self._n + 1): # ccphase(circuit, -angle[i] if inverse else angle[i], ctl1, ctl2, q[i]) circuit.mcu1(-angle[i] if inverse else angle[i], [ctl1, ctl2], q[i]) def _controlled_controlled_phi_add_mod_N(self, circuit, q, ctl1, ctl2, aux, a): """ Circuit that implements doubly controlled modular addition by a """ self._controlled_controlled_phi_add(circuit, q, ctl1, ctl2, a) self._phi_add(circuit, q, inverse=True) ftc.construct_circuit( circuit=circuit, qubits=[q[i] for i in reversed(range(self._n + 1))], do_swaps=False, inverse=True ) circuit.cx(q[self._n], aux) ftc.construct_circuit( circuit=circuit, qubits=[q[i] for i in reversed(range(self._n + 1))], do_swaps=False ) self._controlled_phi_add(circuit, q, aux) self._controlled_controlled_phi_add(circuit, q, ctl1, ctl2, a, inverse=True) ftc.construct_circuit( circuit=circuit, qubits=[q[i] for i in reversed(range(self._n + 1))], do_swaps=False, inverse=True ) circuit.u3(np.pi, 0, np.pi, q[self._n]) circuit.cx(q[self._n], aux) circuit.u3(np.pi, 0, np.pi, q[self._n]) ftc.construct_circuit( circuit=circuit, qubits=[q[i] for i in reversed(range(self._n + 1))], do_swaps=False ) self._controlled_controlled_phi_add(circuit, q, ctl1, ctl2, a) def _controlled_controlled_phi_add_mod_N_inv(self, circuit, q, ctl1, ctl2, aux, a): """ Circuit that implements the inverse of doubly controlled modular addition by a """ self._controlled_controlled_phi_add(circuit, q, ctl1, ctl2, a, inverse=True) ftc.construct_circuit( circuit=circuit, qubits=[q[i] for i in reversed(range(self._n + 1))], do_swaps=False, inverse=True ) circuit.u3(np.pi, 0, np.pi, q[self._n]) circuit.cx(q[self._n], aux) circuit.u3(np.pi, 0, np.pi, q[self._n]) ftc.construct_circuit( circuit=circuit, qubits=[q[i] for i in reversed(range(self._n + 1))], do_swaps=False ) self._controlled_controlled_phi_add(circuit, q, ctl1, ctl2, a) self._controlled_phi_add(circuit, q, aux, inverse=True) ftc.construct_circuit( circuit=circuit, qubits=[q[i] for i in reversed(range(self._n + 1))], do_swaps=False, inverse=True ) circuit.cx(q[self._n], aux) ftc.construct_circuit( circuit=circuit, qubits=[q[i] for i in reversed(range(self._n + 1))], do_swaps=False ) self._phi_add(circuit, q) self._controlled_controlled_phi_add(circuit, q, ctl1, ctl2, a, inverse=True) def _controlled_multiple_mod_N(self, circuit, ctl, q, aux, a): """ Circuit that implements single controlled modular multiplication by a """ ftc.construct_circuit( circuit=circuit, qubits=[aux[i] for i in reversed(range(self._n + 1))], do_swaps=False ) for i in range(0, self._n): self._controlled_controlled_phi_add_mod_N( circuit, aux, q[i], ctl, aux[self._n + 1], (2 ** i) * a % self._N ) ftc.construct_circuit( circuit=circuit, qubits=[aux[i] for i in reversed(range(self._n + 1))], do_swaps=False, inverse=True ) for i in range(0, self._n): circuit.cswap(ctl, q[i], aux[i]) a_inv = modinv(a, self._N) ftc.construct_circuit( circuit=circuit, qubits=[aux[i] for i in reversed(range(self._n + 1))], do_swaps=False ) for i in reversed(range(self._n)): self._controlled_controlled_phi_add_mod_N_inv( circuit, aux, q[i], ctl, aux[self._n + 1], math.pow(2, i) * a_inv % self._N ) ftc.construct_circuit( circuit=circuit, qubits=[aux[i] for i in reversed(range(self._n + 1))], do_swaps=False, inverse=True ) def construct_circuit(self): """Construct circuit. Returns: QuantumCircuit: quantum circuit. """ # Get n value used in Shor's algorithm, to know how many qubits are used self._n = math.ceil(math.log(self._N, 2)) # quantum register where the sequential QFT is performed self._up_qreg = QuantumRegister(2 * self._n, name='up') # quantum register where the multiplications are made self._down_qreg = QuantumRegister(self._n, name='down') # auxilliary quantum register used in addition and multiplication self._aux_qreg = QuantumRegister(self._n + 2, name='aux') # Create Quantum Circuit circuit = QuantumCircuit(self._up_qreg, self._down_qreg, self._aux_qreg) # Initialize down register to 1 and create maximal superposition in top register circuit.u2(0, np.pi, self._up_qreg) circuit.u3(np.pi, 0, np.pi, self._down_qreg[0]) # Apply the multiplication gates as showed in the report in order to create the exponentiation for i in range(0, 2 * self._n): self._controlled_multiple_mod_N( circuit, self._up_qreg[i], self._down_qreg, self._aux_qreg, int(pow(self._a, pow(2, i))) ) # Apply inverse QFT ftc.construct_circuit(circuit=circuit, qubits=self._up_qreg, do_swaps=True, inverse=True) logger.info(summarize_circuits(circuit)) return circuit def _get_factors(self, output_desired, t_upper): """ Apply the continued fractions to find r and the gcd to find the desired factors. """ x_value = int(output_desired, 2) logger.info('In decimal, x_final value for this result is: {0}.'.format(x_value)) if x_value <= 0: self._ret['results'][output_desired] = 'x_value is <= 0, there are no continued fractions.' return False logger.debug('Running continued fractions for this case.') # Calculate T and x/T T = pow(2, t_upper) x_over_T = x_value / T # Cycle in which each iteration corresponds to putting one more term in the # calculation of the Continued Fraction (CF) of x/T # Initialize the first values according to CF rule i = 0 b = array.array('i') t = array.array('f') b.append(math.floor(x_over_T)) t.append(x_over_T - b[i]) while i >= 0: # From the 2nd iteration onwards, calculate the new terms of the CF based # on the previous terms as the rule suggests if i > 0: b.append(math.floor(1 / t[i - 1])) t.append((1 / t[i - 1]) - b[i]) # Calculate the CF using the known terms aux = 0 j = i while j > 0: aux = 1 / (b[j] + aux) j = j - 1 aux = aux + b[0] # Get the denominator from the value obtained frac = fractions.Fraction(aux).limit_denominator() denominator = frac.denominator logger.debug('Approximation number {0} of continued fractions:'.format(i + 1)) logger.debug("Numerator:{0} \t\t Denominator: {1}.".format(frac.numerator, frac.denominator)) # Increment i for next iteration i = i + 1 if denominator % 2 == 1: if i >= self._N: self._ret['results'][output_desired] = 'unable to find factors after too many attempts.' return False logger.debug('Odd denominator, will try next iteration of continued fractions.') continue # If denominator even, try to get factors of N # Get the exponential a^(r/2) exponential = 0 if denominator < 1000: exponential = pow(self._a, denominator / 2) # Check if the value is too big or not if math.isinf(exponential) or exponential > 1000000000: self._ret['results'][output_desired] = 'denominator of continued fraction is too big.' return False # If the value is not to big (infinity), then get the right values and do the proper gcd() putting_plus = int(exponential + 1) putting_minus = int(exponential - 1) one_factor = math.gcd(putting_plus, self._N) other_factor = math.gcd(putting_minus, self._N) # Check if the factors found are trivial factors or are the desired factors if one_factor == 1 or one_factor == self._N or other_factor == 1 or other_factor == self._N: logger.debug('Found just trivial factors, not good enough.') # Check if the number has already been found, use i-1 because i was already incremented if t[i - 1] == 0: self._ret['results'][output_desired] = 'the continued fractions found exactly x_final/(2^(2n)).' return False if i >= self._N: self._ret['results'][output_desired] = 'unable to find factors after too many attempts.' return False else: logger.debug('The factors of {0} are {1} and {2}.'.format(self._N, one_factor, other_factor)) logger.debug('Found the desired factors.') self._ret['results'][output_desired] = (one_factor, other_factor) factors = sorted((one_factor, other_factor)) if factors not in self._ret['factors']: self._ret['factors'].append(factors) return True
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 770, 2438, 318, 636, 286, 1195, 1984, 270, 13, 198, 2, 198, 2, 357, 34, 8, 15069, 19764, 11421, 13, 2177, 290, 1568, 13, 198, 2, 198, 2, 770, 2438, 318, ...
2.070417
7,342
import re import bz2 import pygame import public import sprites import functions import dictionaries import random # :^)
[ 11748, 302, 198, 11748, 275, 89, 17, 198, 11748, 12972, 6057, 198, 11748, 1171, 198, 11748, 42866, 198, 11748, 5499, 198, 11748, 48589, 3166, 198, 11748, 4738, 628, 628, 198, 2, 1058, 61, 8, 198 ]
3.571429
35
# -*- coding: utf-8 -*- """ Reads an `html` formatted table. """ import numpy as np from bs4 import BeautifulSoup import requests from selenium import webdriver from selenium.webdriver.firefox.options import Options as FirefoxOptions from selenium.webdriver.chrome.options import Options as ChromeOptions from selenium.webdriver.edge.options import Options as EdgeOptions from selenium.webdriver.ie.options import Options as IeOptions import copy import logging from tabledataextractor.exceptions import InputError log = logging.getLogger(__name__) def makearray(html_table): """ Creates a numpy array from an `.html` file, taking `rowspan` and `colspan` into account. Modified from: John Ricco, https://johnricco.github.io/2017/04/04/python-html/, *Using Python to scrape HTML tables with merged cells* Added functionality for duplicating cell content for cells with `rowspan`/`colspan`. The table has to be :math:`n*m`, rectangular, with the same number of columns in every row. """ n_cols = 0 n_rows = 0 for row in html_table.findAll("tr"): col_tags = row.find_all(["td", "th"]) if len(col_tags) > 0: n_rows += 1 if len(col_tags) > n_cols: n_cols = len(col_tags) # according to numpy documentation fill_value should be of type Union[int, float, complex] # however, 'str' works just fine array = np.full((n_rows, n_cols), fill_value="", dtype='<U60') # list to store rowspan values skip_index = [0 for i in range(0, n_cols)] # iterating over each row in the table row_counter = 0 for row in html_table.findAll("tr"): # skip row if it's empty if len(row.find_all(["td", "th"])) == 0: continue else: # get all the cells containing data in this row columns = row.find_all(["td", "th"]) col_dim = [] row_dim = [] col_dim_counter = -1 row_dim_counter = -1 col_counter = -1 this_skip_index = copy.deepcopy(skip_index) for col in columns: # determine all cell dimensions colspan = col.get("colspan") if not colspan: col_dim.append(1) else: col_dim.append(int(colspan)) col_dim_counter += 1 rowspan = col.get("rowspan") if not rowspan: row_dim.append(1) else: row_dim.append(int(rowspan)) row_dim_counter += 1 # adjust column counter if col_counter == -1: col_counter = 0 else: col_counter = col_counter + col_dim[col_dim_counter - 1] while skip_index[col_counter] > 0: col_counter += 1 # get cell contents cell_data = col.get_text() # insert data into cell array[row_counter, col_counter] = cell_data # Insert data into neighbouring rowspan/colspan cells if colspan: for spanned_col in range(col_counter+1, col_counter + int(colspan)): array[row_counter, spanned_col] = cell_data if rowspan: for spanned_row in range(row_counter+1, row_counter + int(rowspan)): array[spanned_row, col_counter] = cell_data #record column skipping index if row_dim[row_dim_counter] > 1: this_skip_index[col_counter] = row_dim[row_dim_counter] # adjust row counter row_counter += 1 # adjust column skipping index skip_index = [i - 1 if i > 0 else i for i in this_skip_index] return array def read_file(file_path, table_number=1): """Reads an .html file and returns a numpy array.""" file = open(file_path, encoding='UTF-8') html_soup = BeautifulSoup(file, features='lxml') file.close() html_table = html_soup.find_all("table")[table_number-1] array = makearray(html_table) return array def configure_selenium(browser='Firefox'): """ Configuration for `Selenium <https://selenium-python.readthedocs.io/>`_. Sets the path to ``geckodriver.exe`` :param browser: Which browser to use :type browser: str :return: Selenium driver """ if browser == 'Firefox': options = FirefoxOptions() options.headless = True driver = webdriver.Firefox(options=options, executable_path=r'C:\Users\juras\System\geckodriver\geckodriver.exe') return driver else: return None def read_url(url, table_number=1): """ Reads in a table from an URL and returns a numpy array. Will try `Requests <http://docs.python-requests.org/en/master/>`_ first. If it doesn't succeed, `Selenium <https://selenium-python.readthedocs.io/>`_ will be used. :param url: Url of the page where the table is located :type url: str :param table_number: Number of Table on the web page. :type table_number: int """ if not isinstance(table_number, int): msg = 'Table number is not valid.' log.critical(msg) raise TypeError(msg) # first try the requests package, if it fails do the selenium, which is much slower try: html_file = requests.get(url) html_soup = BeautifulSoup(html_file.text, features='lxml') html_table = html_soup.find_all("table")[table_number - 1] array = makearray(html_table) log.info("Package 'requests' was used.") return array except Exception: driver = configure_selenium() driver.get(url) html_file = driver.page_source html_soup = BeautifulSoup(html_file, features='lxml') try: html_table = html_soup.find_all("table")[table_number-1] except IndexError: raise InputError("table_number={} is out of range".format(table_number)) else: array = makearray(html_table) log.info("Package 'selenium' was used.") return array
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 5569, 82, 281, 4600, 6494, 63, 39559, 3084, 13, 198, 37811, 628, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198, 1...
2.246492
2,779
import numpy as np test_data = np.array([16, 1, 2, 0, 4, 2, 7, 1, 2, 14]) np_data = np.loadtxt("data.txt", delimiter=",", dtype=int) def one(data: np.ndarray) -> int: """ Determine the horizontal position that the crabs can align to using the least fuel possible. How much fuel must they spend to align to that position? """ median = np.median(data).astype(int) return np.absolute(data - median).sum() def two(data: np.ndarray) -> int: """ Determine the horizontal position that the crabs can align to using the least fuel possible so they can make you an escape route! How much fuel must they spend to align to that position? """ mean = np.mean(data).astype(int) diff = np.absolute(data - mean) # 'Factorial for addition' is the same as (X^2 + X) / 2 return ((diff * diff + diff) / 2).astype(int).sum() print(f"1. {one(np_data)}") print(f"2. {two(np_data)}")
[ 11748, 299, 32152, 355, 45941, 198, 198, 9288, 62, 7890, 796, 45941, 13, 18747, 26933, 1433, 11, 352, 11, 362, 11, 657, 11, 604, 11, 362, 11, 767, 11, 352, 11, 362, 11, 1478, 12962, 198, 37659, 62, 7890, 796, 45941, 13, 2220, 1411...
2.774775
333
# Copyright (c) 2018 Arista Networks, Inc. All rights reserved. # Arista Networks, Inc. Confidential and Proprietary. # # DON'T EDIT THIS FILE. It was generated by # /usr/local/lib/python2.7/dist-packages/CTypeGen.py # Please see AID/3558 for details on the contents of this file # from ctypes import * # pylint: disable=wildcard-import from CTypeGenRun import * # pylint: disable=wildcard-import # pylint: disable=unnecessary-pass,protected-access Callback = CFUNCTYPE( c_int, c_int , c_int ) functionTypes = { 'callme': CFUNCTYPE( c_int, c_int , c_int , Callback ), } if __name__ == "__main__": test_classes()
[ 2, 15069, 357, 66, 8, 2864, 943, 12523, 27862, 11, 3457, 13, 220, 1439, 2489, 10395, 13, 198, 2, 943, 12523, 27862, 11, 3457, 13, 7326, 35599, 290, 1041, 3448, 8527, 13, 198, 2, 198, 2, 23917, 6, 51, 48483, 12680, 45811, 13, 632, ...
2.624
250
from netapp.connection import NaErrorResponse, NaPagedResponse from netapp.net import NetConnection from netapp.net.net_port_info import NetPortInfo conn = NetConnection("192.168.135.100", "admin", "mehmeh123") print "LISTING ALL PORTS:" print "-----------------------------------------------" query = NetPortInfo(node="radontap-02") response = conn.net_port_get_iter( desired_attributes="node,port".split(","), query=query ) if isinstance(response, NaPagedResponse): for npi in response.output: print "{}: {}".format( npi.port, npi ) while response.has_more(): next = response.next() if isinstance(next.result, NaErrorResponse): print "There was an error: {} : {}".format( next.result.error_code, next.result.reason ) else: for npi in next.output: print "{}: {}".format( npi.port, npi ) elif isinstance(response, NaErrorResponse): print "There was an error: {} : {}".format( response.error_code, response.reason ) else: for npi in response: print "{}: {}".format( npi.port, npi ) print "GET A SINGLE PORT:" print "-----------------------------------------------" port_info = conn.net_port_get( node="radontap-02", port="e0c", desired_attributes="node,port".split(",") ) print port_info
[ 6738, 2010, 1324, 13, 38659, 1330, 11013, 12331, 31077, 11, 11013, 47, 1886, 31077, 198, 6738, 2010, 1324, 13, 3262, 1330, 3433, 32048, 198, 6738, 2010, 1324, 13, 3262, 13, 3262, 62, 634, 62, 10951, 1330, 3433, 13924, 12360, 198, 198, ...
2.781116
466
# type: ignore[attr-defined] from .core import unify, reify # noqa: F403 from .more import unifiable # noqa: F403 from .variable import var, isvar, vars, variables, Var # noqa: F403
[ 2, 2099, 25, 8856, 58, 35226, 12, 23211, 60, 198, 6738, 764, 7295, 1330, 555, 1958, 11, 302, 1958, 220, 1303, 645, 20402, 25, 376, 31552, 198, 6738, 764, 3549, 1330, 555, 16823, 220, 1303, 645, 20402, 25, 376, 31552, 198, 6738, 764,...
2.890625
64
############################################################################### # Copyright 2012 FastSoft Inc. # Copyright 2012 Devin Anderson <danderson (at) fastsoft (dot) com> # # 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 psinsights.rule import Rule as _Rule
[ 29113, 29113, 7804, 4242, 21017, 198, 2, 15069, 2321, 12549, 18380, 3457, 13, 198, 2, 15069, 2321, 37081, 9918, 1279, 67, 392, 882, 357, 265, 8, 3049, 4215, 357, 26518, 8, 401, 29, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, ...
4.314721
197
''' Faça um programa que leia o salário de um trabalhador e o valor da prestação de um empréstimo. Se a prestação for maior que 20% do salário imprima: “Empréstimo não concedido”; caso contrário imprima: “Empréstimo concedido”. ''' # entrada de dados salarao = float(input('Digite o valor do salario: ')) prestacao = float(input('Digite o valor da prestacao: ')) # condicional if (prestacao > 0.2*salarao): print('Emprestimo nao concedido!') else: print('Emprestimo concedido!') # mensagem de término de algoritmo print('Fim do algoritmo!')
[ 7061, 6, 198, 50110, 50041, 23781, 1430, 64, 8358, 443, 544, 267, 3664, 6557, 27250, 390, 23781, 491, 44349, 71, 7079, 304, 267, 1188, 273, 198, 6814, 16153, 64, 16175, 28749, 390, 23781, 795, 1050, 2634, 301, 25147, 13, 1001, 257, 16...
2.369099
233
""" Firefly Security and Monitoring This is the core Firefly Security and Monitoring Service. There should be almost zero config to the user and firefly will monitor the entire house. - Alarm System (Away) - Alarm System (Night) - Vacation Lighting - Battery Monitor - Smoke Alerts - Flooding Alerts """ from Firefly import logging, scheduler, aliases from Firefly.const import COMMAND_NOTIFY, EVENT_TYPE_BROADCAST, FIREFLY_SECURITY_MONITORING, SERVICE_NOTIFICATION, SOURCE_LOCATION, TYPE_DEVICE, WATER, SENSOR_DRY, SENSOR_WET from Firefly.helpers.device import BATTERY, CONTACT, CONTACT_CLOSE, CONTACT_OPEN, MOTION, MOTION_ACTIVE, MOTION_INACTIVE from Firefly.helpers.events import Command, Event from Firefly.services.firefly_security_and_monitoring.battery_monitor import check_battery_from_event, generate_battery_notification_message from Firefly.services.firefly_security_and_monitoring.secueity_settings import FireflySecuritySettings from Firefly.services.firefly_security_and_monitoring.security_monitor import (check_all_security_contact_sensors, check_all_security_motion_sensors, generate_contact_warning_message, process_contact_change, process_motion_change) from Firefly.util.firefly_util import command_from_dict from .const import ALARM_ARMED_MESSAGE_MOTION, ALARM_ARMED_MESSAGE_NO_MOTION, BATTERY_LOW, BATTERY_NO_NOTIFY_STATES, STATUS_TEMPLATE ALARM_DISARMED = 'disarmed' ALARM_ARMED = 'armed' ALARM_ARMED_MOTION = 'armed_motion' ALARM_ARMED_NO_MOTION = 'armed_no_motion' ALARM_TRIGGERED = 'triggered' SYSTEM_DISABLED = 'system_diabled'
[ 37811, 198, 13543, 12254, 4765, 290, 37484, 198, 198, 1212, 318, 262, 4755, 40374, 4765, 290, 37484, 4809, 13, 1318, 815, 307, 2048, 6632, 4566, 284, 262, 2836, 290, 2046, 12254, 481, 5671, 262, 2104, 2156, 13, 198, 12, 978, 1670, 448...
2.804795
584
# standard gravitational parameter for Earth = G*M EARTH_GRAV_CONST = 3.986005e5 # (km^3/s^2) # Earth Radius EARTH_RADIUS = 6378.137 # (km) # Earth rotation speed (calculated from sideral period) EARTH_ROT_RATE = 6.300387486749 / 86164 # (rad/s) # Earth gravitation at sea leve EARTH_GRAV_SEA_LVL = 9.80665 # (m^2/s)
[ 2, 3210, 29973, 11507, 329, 3668, 796, 402, 9, 44, 198, 17133, 4221, 62, 38, 3861, 53, 62, 10943, 2257, 796, 513, 13, 4089, 8054, 20, 68, 20, 220, 1303, 357, 13276, 61, 18, 14, 82, 61, 17, 8, 198, 198, 2, 3668, 48838, 198, 171...
2.314286
140
'''Some helper functions for PyTorch, including: - get_mean_and_std: calculate the mean and std value of dataset. - msr_init: net parameter initialization. - progress_bar: progress bar mimic xlua.progress. ''' import errno import os import sys import time import math import torch.nn as nn import torch.nn.init as init from torch.autograd import Variable import numpy as np import pdb import torch __all__ = ['get_mean_and_std', 'init_params', 'mkdir_p', 'AverageMeter', 'MovingAverage', 'AverageMeter_Mat', 'Timer'] def get_mean_and_std(dataset): '''Compute the mean and std value of dataset.''' dataloader = trainloader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=True, num_workers=2) mean = torch.zeros(3) std = torch.zeros(3) print('==> Computing mean and std..') for inputs, targets in dataloader: for i in range(3): mean[i] += inputs[:,i,:,:].mean() std[i] += inputs[:,i,:,:].std() mean.div_(len(dataset)) std.div_(len(dataset)) return mean, std def init_params(net): '''Init layer parameters.''' for m in net.modules(): if isinstance(m, nn.Conv2d): init.kaiming_normal(m.weight, mode='fan_out') if m.bias: init.constant(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): init.constant(m.weight, 1) init.constant(m.bias, 0) elif isinstance(m, nn.Linear): init.normal(m.weight, std=1e-3) if m.bias: init.constant(m.bias, 0) def mkdir_p(path): '''make dir if not exist''' try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise class AverageMeter(object): """Computes and stores the average and current value Imported from https://github.com/pytorch/examples/blob/master/imagenet/main.py#L247-L262 """
[ 7061, 6, 4366, 31904, 5499, 329, 9485, 15884, 354, 11, 1390, 25, 198, 220, 220, 220, 532, 651, 62, 32604, 62, 392, 62, 19282, 25, 15284, 262, 1612, 290, 14367, 1988, 286, 27039, 13, 198, 220, 220, 220, 532, 13845, 81, 62, 15003, 2...
2.227933
895
import numpy as np np.random.seed(111) ''' The data is generated adding noise to the values from y = 0.8x + 2 equation Therefore the expectation of the auto encoder is to get the values w and b closer to 0.8 and 2 respectively ''' '''generate random x values''' X_train = np.random.random((1, 50))[0] '''get the reference y value''' y_reference = 0.8*X_train + 2 '''add noise to the reference y value''' y_train = y_reference + np.sqrt(0.01)*np.random.random((1, 50))[0] W = np.random.random() b = np.random.random() '''number of training examples''' m = len(X_train) '''parameters''' learning_rate = 0.01 epochs = 5000 '''send data to the gradient optimizer to optimize values for W and b''' gradient_descent(X_train, y_train) print('\nGradient optimization completed') print('W Expected : 0.8' + ' Learned : ' + str(W)) print('b Expected : 2.0' + ' Learned : ' + str(b))
[ 11748, 299, 32152, 355, 45941, 198, 198, 37659, 13, 25120, 13, 28826, 7, 16243, 8, 198, 198, 7061, 6, 198, 464, 1366, 318, 7560, 4375, 7838, 284, 262, 3815, 422, 220, 331, 796, 657, 13, 23, 87, 1343, 362, 16022, 198, 26583, 262, 1...
2.812698
315
#Faça um programa que leia um ângulo qualquer e mostre na tela #o valor do seno,cosseno e tangente desse ângulo. from math import radians, sin, cos, tan angulo = int(input('Digite um ângulo: ')) sen = sin(radians(angulo)) cos = cos(radians(angulo)) tan = tan(radians(angulo)) print('O seno do ângulo {} é {:.2f}'.format(angulo, sen)) print('O Cosseno do ângulo {} é {:.2f}'.format(angulo, cos)) print('A tangente do ângulo {} é {:.2f}'.format(angulo, tan))
[ 2, 50110, 50041, 23781, 1430, 64, 8358, 443, 544, 23781, 6184, 95, 782, 43348, 4140, 10819, 304, 749, 260, 12385, 256, 10304, 198, 2, 78, 1188, 273, 466, 3308, 78, 11, 66, 793, 23397, 304, 13875, 21872, 748, 325, 6184, 95, 782, 4334...
2.43617
188
#!/usr/bin/env python """stereograph.py: Compute length of a geodesic in the unit sphere. """ from sympy import (symbols, Function, Matrix, factor, simplify, latex, sqrt) from sympy.abc import (t, xi, eta) from sympy.printing import print_latex if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 37811, 301, 567, 2384, 13, 9078, 25, 3082, 1133, 4129, 286, 257, 4903, 4147, 291, 287, 262, 4326, 16558, 13, 198, 37811, 198, 198, 6738, 10558, 88, 1330, 357, 1837, 2022, 10220, 11, ...
2.794118
102
# from visdialch.decoders.gen import GenerativeDecoder #from visdialch.decoders.disc import DiscriminativeDecoder from visdialch.decoders.decoder import DiscriminativeDecoder
[ 2, 422, 1490, 38969, 354, 13, 12501, 375, 364, 13, 5235, 1330, 2980, 876, 10707, 12342, 198, 2, 6738, 1490, 38969, 354, 13, 12501, 375, 364, 13, 15410, 1330, 8444, 3036, 259, 876, 10707, 12342, 198, 6738, 1490, 38969, 354, 13, 12501, ...
3.181818
55
import pytest from ansiblediscover.graph.node import Node @pytest.mark.parametrize('this, other, equal', [ (('myname', 'mytype', 'mypath'), ('myname', 'mytype', 'mypath'), True), (('myname', 'mytype', 'mypath'), ('othername', 'mytype', 'mypath'), False), (('myname', 'mytype', 'mypath'), ('myname', 'othertype', 'mypath'), False), (('myname', 'mytype', 'mypath'), ('myname', 'othertype', 'otherpath'), False), ]) @pytest.mark.parametrize('other', [ None, [], ('myname', 'mytype', 'mypath'), ])
[ 11748, 12972, 9288, 198, 198, 6738, 9093, 571, 992, 29392, 13, 34960, 13, 17440, 1330, 19081, 628, 628, 628, 198, 198, 31, 9078, 9288, 13, 4102, 13, 17143, 316, 380, 2736, 10786, 5661, 11, 584, 11, 4961, 3256, 685, 198, 220, 220, 22...
2.509434
212
import datetime from Models.Submission import Submission from Core.Database import Database from Core.Scorer import Scorer from Core.Executer import Executer from Core.Parser import Parser
[ 11748, 4818, 8079, 198, 6738, 32329, 13, 7004, 3411, 1330, 42641, 198, 6738, 7231, 13, 38105, 1330, 24047, 198, 6738, 7231, 13, 3351, 11934, 1330, 1446, 11934, 198, 6738, 7231, 13, 23002, 11894, 1330, 8393, 11894, 198, 6738, 7231, 13, 4...
4.222222
45
from copy import copy import torch from nitorch.core.py import make_list from nitorch.core import dtypes from nitorch.spatial import affine_sub, affine_permute, voxel_size as affvx from nitorch.io.utils.indexing import (expand_index, guess_shape, compose_index, neg2pos, is_droppedaxis, is_newaxis, is_sliceaxis, invert_permutation, invert_slice, slice_navigator) from ..utils import volutils from ..mapping import MappedFile class MappedArray(MappedFile): """Base class for mapped arrays. Mapped arrays are usually stored on-disk, along with (diverse) metadata. They can be symbolically sliced, allowing for partial reading and (sometimes) writing of data from/to disk. Chaining of symbolic slicing operations is implemented in this base class. The actual io must be implemented by the child class. Abstract Methods ---------------- Child classes MUST implement: * self.data(...) Child classes SHOULD implement: * self.metadata(...) default -> returns empty dict Child classes MAY implement: * self.set_data(...) default -> raises cls.FailedWriteError * self.set_metadata(...) default -> raises cls.FailedWriteError * cls.save_new(...) default -> raises cls.FailedWriteError * cls.savef_new(...) default -> raises cls.FailedWriteError Child classes SHOULD register themselves in `readers.reader_classes`. If they implement `save_new`, child classes SHOULD register themselves in `writers.writer_classes`. Properties ---------- dtype : np.dtype On-disk data type slope : float Intensity slope from on-disk to unit inter : float Intensity shift from on-disk to unit affine : tensor Orientation matrix: maps spatial axes to 'world' spatial : tuple[bool] Mask of 'spatial' axes (x, y, z, ...) slicer : tuple[index_like] Indexing into the full on-disk array permutation : tuple[int] Permutation of the original in-disk axes. dim : int Number of axes voxel_size : tuple[float] World size of the spatial dimensions readable : AccessType See `AccessType` writable : AccessType See `AccessType` Types ----- FailedReadError Error raised when failing to load FailedWriteError Error raised when failing to save Methods ------- slice(tuple[index_like]) Subslice the array permute(tuple[int]) Permute axes transpose(int, int) Permute two axes unsqueeze(int) Insert singleton dimension squeeze(int) Remove singleton dimension unbind -> tuple Unstack arrays along a dimension chunk -> tuple Unstack arrays along a dimension by chunks split -> tuple Unstack arrays along a dimension by chunks data(...) -> tensor Load raw data to memory fdata(...) -> tensor Load scaled floating-point data to memory metadata(...) -> dict Load metadata to memory set_data(dat, ...) Write raw data to disk set_fdata(dat, ...) Write scaled floating-point data to disk set_metadata(**meta) Write metadata to disk Class methods ------------- save_new(dat, file_like) Write new file populated with `dat` savef_new(dat, file_like) Write new file populated with (scaled) `dat` External functions ------------------ map(file_like) -> MappedArray Build a MappedArray load(file_like) -> tensor Load raw data to memory from a file loadf(file_like) -> tensor Load scaled data to memory from a file save(dat, file_like) -> Save raw data into a new file savef(dat, file_like) -> Save scaled data into a new file cat(tuple[MappedArray]) Concatenate arrays along a dimension Syntaxic sugar -------------- __call__ -> fdata Load scaled floating-point data to memory __array__ -> fdata Load scaled floating-point data to memory __getitem__ -> slice Subslice the array __setitem__ -> set_fdata Write scaled floating-point data to disk __len__ Size of the first dimension (or 0 if scalar) """ fname: str = None # filename (can be None if in-memory proxy) fileobj = None # file-like object (`write`, `seek`, etc) is_compressed: bool = None # is compressed dtype: torch.dtype = None # on-disk data type slope: float = 1 # intensity slope inter: float = 0 # intensity shift affine = None # sliced voxel-to-world _affine = None # original voxel-to-world spatial: tuple = None # sliced spatial mask (len -> dim) _spatial: tuple = None # original spatial mask (len -> _dim) shape: tuple = None # sliced shape (len -> dim) _shape: tuple = None # original shape (len -> _dim) slicer: tuple = None # indexing into the parent permutation: tuple = None # permutation of original dim (len -> _dim) dim = property(lambda self: len(self.shape)) # Nb of sliced dimensions _dim = property(lambda self: len(self._shape)) # Nb of original dimensions voxel_size = property(lambda self: affvx(self.affine)) __repr__ = __str__ @classmethod def possible_extensions(cls): """List all possible extensions""" return tuple() def __getitem__(self, index): """Extract a sub-part of the array. Indices can only be slices, ellipses, integers or None. Parameters ---------- index : tuple[slice or ellipsis or int or None] Returns ------- subarray : type(self) MappedArray object, with the indexing operations and affine matrix relating to the new sub-array. """ return self.slice(index) def slice(self, index, new_shape=None, _pre_expanded=False): """Extract a sub-part of the array. Indices can only be slices, ellipses, integers or None. Parameters ---------- index : tuple[slice or ellipsis or int or None] Other Parameters ---------------- new_shape : sequence[int], optional Output shape of the sliced object _pre_expanded : bool, default=False Set to True of `expand_index` has already been called on `index` Returns ------- subarray : type(self) MappedArray object, with the indexing operations and affine matrix relating to the new sub-array. """ index = expand_index(index, self.shape) new_shape = guess_shape(index, self.shape) if any(isinstance(idx, list) for idx in index) > 1: raise ValueError('List indices not currently supported ' '(otherwise we enter advanced indexing ' 'territory and it becomes too complicated).') new = copy(self) new.shape = new_shape # compute new affine if self.affine is not None: spatial_shape = [sz for sz, msk in zip(self.shape, self.spatial) if msk] spatial_index = [idx for idx in index if not is_newaxis(idx)] spatial_index = [idx for idx, msk in zip(spatial_index, self.spatial) if msk] affine, _ = affine_sub(self.affine, spatial_shape, tuple(spatial_index)) else: affine = None new.affine = affine # compute new slicer perm_shape = [self._shape[d] for d in self.permutation] new.slicer = compose_index(self.slicer, index, perm_shape) # compute new spatial mask spatial = [] i = 0 for idx in new.slicer: if is_newaxis(idx): spatial.append(False) else: # original axis if not is_droppedaxis(idx): spatial.append(self._spatial[self.permutation[i]]) i += 1 new.spatial = tuple(spatial) return new def __setitem__(self, index, value): """Write scaled data to disk. Parameters ---------- index : tuple Tuple of indices (see `__getitem__`) value : array or tensor Array-like with shape `self[index].shape` Returns ------- self : type(self) """ if isinstance(value, MappedArray): raise NotImplementedError else: self.__getitem__(index).set_fdata(value) return self def __call__(self, *args, **kwargs): """Get floating point data. See `fdata()`""" return self.fdata(*args, **kwargs) def __array__(self, dtype=None): """Convert to numpy array""" return self.fdata(dtype=dtype, numpy=True) def permute(self, dims): """Permute dimensions Parameters ---------- dims : sequence[int] A permutation of `range(self.dim)` Returns ------- permarray : type(self) MappedArray object, with the indexing operations and affine matrix reflecting the permutation. """ dims = list(dims) if len(dims) != self.dim or len(dims) != len(set(dims)): raise ValueError('there should be as many (unique) dimensions ' 'as the array\'s dimension. Got {} and {}.' .format(len(set(dims)), self.dim)) # permute tuples that relate to the current spatial dimensions # (that part is easy) shape = tuple(self.shape[d] for d in dims) spatial = tuple(self.spatial[d] for d in dims) # permute slicer # 1) permute non-dropped dimensions slicer_nodrop = list(filter(lambda x: not is_droppedaxis(x), self.slicer)) slicer_nodrop = [slicer_nodrop[d] for d in dims] # 2) insert dropped dimensions slicer = [] for idx in self.slicer: if is_droppedaxis(idx): slicer.append(idx) else: new_idx, *slicer_nodrop = slicer_nodrop slicer.append(new_idx) # permute permutation # 1) insert None where new axes and remove dropped axes old_perm = self.permutation new_perm = [] drop_perm = [] for idx in self.slicer: if is_newaxis(idx): new_perm.append(None) continue p, *old_perm = old_perm if not is_droppedaxis(idx): new_perm.append(p) else: drop_perm.append(p) # 2) permute new_perm = [new_perm[d] for d in dims] # 3) insert back dropped axes and remove new axes perm = [] for idx in self.slicer: if is_droppedaxis(idx): p, *drop_perm = drop_perm perm.append(p) continue p, *new_perm = new_perm if not is_newaxis(p): perm.append(p) # permute affine # (it's a bit more complicated: we need to find the # permutation of the *current* *spatial* dimensions) perm_spatial = [p for p in dims if self.spatial[p]] perm_spatial = sorted(range(len(perm_spatial)), key=lambda k: perm_spatial[k]) affine, _ = affine_permute(self.affine, perm_spatial, self.shape) # create new object new = copy(self) new.shape = shape new.spatial = spatial new.permutation = tuple(perm) new.slicer = tuple(slicer) new.affine = affine return new def transpose(self, dim0, dim1): """Transpose two dimensions Parameters ---------- dim0 : int First dimension dim1 : int Second dimension Returns ------- permarray : type(self) MappedArray object, with the indexing operations and affine matrix reflecting the transposition. """ permutation = list(range(self.dim)) permutation[dim0] = dim1 permutation[dim1] = dim0 return self.permute(permutation) def data(self, dtype=None, device=None, casting='unsafe', rand=True, cutoff=None, dim=None, numpy=False): """Load the array in memory Parameters ---------- dtype : type or torch.dtype or np.dtype, optional Output data type. By default, keep the on-disk data type. device : torch.device, default='cpu' Output device. rand : bool, default=False If the on-disk dtype is not floating point, sample noise in the uncertainty interval. cutoff : float or (float, float), default=(0, 1) Percentile cutoff. If only one value is provided, it is assumed to relate to the upper percentile. dim : int or list[int], optional Dimensions along which to compute percentiles. By default, they are computed on the flattened array. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe', 'rescale'}, default='unsafe' Controls what kind of data casting may occur: * 'no': the data types should not be cast at all. * 'equiv': only byte-order changes are allowed. * 'safe': only casts which can preserve values are allowed. * 'same_kind': only safe casts or casts within a kind, like float64 to float32, are allowed. * 'unsafe': any data conversions may be done. * 'rescale': the input data is rescaled to match the dynamic range of the output type. The minimum value in the data is mapped to the minimum value of the data type and the maximum value in the data is mapped to the maximum value of the data type. * 'rescale_zero': the input data is rescaled to match the dynamic range of the output type, but ensuring that zero maps to zero. > If the data is signed and cast to a signed datatype, zero maps to zero, and the scaling is chosen so that both the maximum and minimum value in the data fit in the output dynamic range. > If the data is signed and cast to an unsigned datatype, negative values "wrap around" (as with an unsafe cast). > If the data is unsigned and cast to a signed datatype, values are kept positive (the negative range is unused). numpy : bool, default=False Return a numpy array rather than a torch tensor. Returns ------- dat : tensor[dtype] """ pass def fdata(self, dtype=None, device=None, rand=False, cutoff=None, dim=None, numpy=False): """Load the scaled array in memory This function differs from `data` in several ways: * The output data type should be a floating point type. * If an affine scaling (slope, intercept) is defined in the file, it is applied to the data. * the default output data type is `torch.get_default_dtype()`. Parameters ---------- dtype : dtype_like, optional Output data type. By default, use `torch.get_default_dtype()`. Should be a floating point type. device : torch.device, default='cpu' Output device. rand : bool, default=False If the on-disk dtype is not floating point, sample noise in the uncertainty interval. cutoff : float or (float, float), default=(0, 1) Percentile cutoff. If only one value is provided, it is assumed to relate to the upper percentile. dim : int or list[int], optional Dimensions along which to compute percentiles. By default, they are computed on the flattened array. numpy : bool, default=False Return a numpy array rather than a torch tensor. Returns ------- dat : tensor[dtype] """ # --- sanity check --- dtype = torch.get_default_dtype() if dtype is None else dtype info = dtypes.dtype(dtype) if not info.is_floating_point: raise TypeError('Output data type should be a floating point ' 'type but got {}.'.format(dtype)) # --- get unscaled data --- dat = self.data(dtype=dtype, device=device, rand=rand, cutoff=cutoff, dim=dim, numpy=numpy) # --- scale --- if self.slope != 1: dat *= float(self.slope) if self.inter != 0: dat += float(self.inter) return dat def set_data(self, dat, casting='unsafe'): """Write (partial) data to disk. Parameters ---------- dat : tensor Tensor to write on disk. It should have shape `self.shape`. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe', 'rescale'}, default='unsafe' Controls what kind of data casting may occur: * 'no': the data types should not be cast at all. * 'equiv': only byte-order changes are allowed. * 'safe': only casts which can preserve values are allowed. * 'same_kind': only safe casts or casts within a kind, like float64 to float32, are allowed. * 'unsafe': any data conversions may be done. * 'rescale': the input data is rescaled to match the dynamic range of the output type. The minimum value in the data is mapped to the minimum value of the data type and the maximum value in the data is mapped to the maximum value of the data type. * 'rescale_zero': the input data is rescaled to match the dynamic range of the output type, but ensuring that zero maps to zero. > If the data is signed and cast to a signed datatype, zero maps to zero, and the scaling is chosen so that both the maximum and minimum value in the data fit in the output dynamic range. > If the data is signed and cast to an unsigned datatype, negative values "wrap around" (as with an unsafe cast). > If the data is unsigned and cast to a signed datatype, values are kept positive (the negative range is unused). Returns ------- self : type(self) """ raise self.FailedWriteError("Method not implemented in class {}." .format(type(self).__name__)) def set_fdata(self, dat): """Write (partial) scaled data to disk. Parameters ---------- dat : tensor Tensor to write on disk. It should have shape `self.shape` and a floating point data type. Returns ------- self : type(self) """ # --- sanity check --- info = dtypes.dtype(dat.dtype) if not info.is_floating_point: raise TypeError('Input data type should be a floating point ' 'type but got {}.'.format(dat.dtype)) if dat.shape != self.shape: raise TypeError('Expected input shape {} but got {}.' .format(self.shape, dat.shape)) # --- detach --- if torch.is_tensor(dat): dat = dat.detach() # --- unscale --- if self.inter != 0 or self.slope != 1: dat = dat.clone() if torch.is_tensor(dat) else dat.copy() if self.inter != 0: dat -= float(self.inter) if self.slope != 1: dat /= float(self.slope) # --- set unscaled data --- self.set_data(dat) return self def metadata(self, keys=None): """Read metadata .. note:: The values returned by this function always relate to the full volume, even if we're inside a view. That is, we always return the affine of the original volume. To get an affine matrix that relates to the view, use `self.affine`. Parameters ---------- keys : sequence[str], optional List of metadata to load. They can either be one of the generic metadata keys define in `io.metadata`, or a format-specific metadata key. By default, all generic keys that are found in the file are returned. Returns ------- metadata : dict A dictionary of metadata """ return dict() def set_metadata(self, **meta): """Write metadata Parameters ---------- meta : dict, optional Dictionary of metadata. Fields that are absent from the dictionary or that have value `None` are kept untouched. Returns ------- self : type(self) """ raise NotImplementedError("Method not implemented in class {}." .format(type(self).__name__)) @classmethod def save_new(cls, dat, file_like, like=None, casting='unsafe', **metadata): """Write an array to disk. This function makes educated choices for the file format and its metadata based on the file extension, the data type and the other options provided. Parameters ---------- dat : tensor or array or MappedArray Data to write file_like : str or file object Path to file or file object (with methods `seek`, `read`). If the extension is known, it gets priority over `like` when choosing the output format. like : file or MappedArray An array on-disk that should be used as a template for the new file. Its metadata/layout/etc will be mimicked as much as possible. casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe', 'rescale'}, default='unsafe' Controls what kind of data casting may occur. See `MappedArray.set_data` metadata : dict Metadata to store on disk. Values provided there will have priority over `like`. Returns ------- dat : array or tensor The array loaded in memory attributes : dict, if attributes is not None Dictionary of attributes loaded as well """ raise cls.FailedWriteError("Method not implemented in class {}." .format(cls.__name__)) @classmethod def savef_new(cls, dat, file_like, like=None, **metadata): """Write a scaled array to disk. This function makes educated choices for the file format and its metadata based on the file extension, the data type and the other options provided. The input data type must be a floating point type. Parameters ---------- dat : tensor or array or MappedArray Data to write file_like : str or file object Path to file or file object (with methods `seek`, `read`). If the extension is known, it gets priority over `like` when choosing the output format. like : file or MappedArray An array on-disk that should be used as a template for the new file. Its metadata/layout/etc will be mimicked as much as possible. metadata : dict Metadata to store on disk. Values provided there will have priority over `like`. Returns ------- dat : array or tensor The array loaded in memory attributes : dict, if attributes is not None Dictionary of attributes loaded as well """ raise cls.FailedWriteError("Method not implemented in class {}." .format(cls.__name__)) def unsqueeze(self, dim, ndim=1): """Add a dimension of size 1 in position `dim`. Parameters ---------- dim : int The dimension is added to the right of `dim` if `dim < 0` else it is added to the left of `dim`. Returns ------- MappedArray """ index = [slice(None)] * self.dim if dim < 0: dim = self.dim + dim + 1 index = index[:dim] + ([None] * ndim) + index[dim:] return self[tuple(index)] def squeeze(self, dim): """Remove all dimensions of size 1. Parameters ---------- dim : int or sequence[int], optional If provided, only this dimension is squeezed. It *must* be a dimension of size 1. Returns ------- MappedArray """ if dim is None: dim = [d for d in range(self.dim) if self.shape[d] == 1] dim = make_list(dim) ndim = len(self.shape) dim = [ndim + d if d < 0 else d for d in dim] if any(self.shape[d] != 1 for d in dim): raise ValueError('Impossible to squeeze non-singleton dimensions.') index = [slice(None) if d not in dim else 0 for d in range(self.dim)] return self[tuple(index)] def unbind(self, dim=0, keepdim=False): """Extract all arrays along dimension `dim` and drop that dimension. Parameters ---------- dim : int, default=0 Dimension along which to unstack. keepdim : bool, default=False Do not drop the unstacked dimension. Returns ------- list[MappedArray] """ index = [slice(None)] * self.dim if keepdim: index = index[:dim+1] + [None] + index[dim+1:] out = [] for i in range(self.shape[dim]): index[dim] = i out.append(self[tuple(index)]) return out def chunk(self, chunks, dim=0): """Split the array into smaller arrays of size `chunk` along `dim`. Parameters ---------- chunks : int Number of chunks. dim : int, default=0 Dimensions along which to split. Returns ------- list[MappedArray] """ index = [slice(None)] * self.dim out = [] for i in range(self.shape[dim]): index[dim] = slice(i*chunks, (i+1)*chunks) out.append(self[tuple(index)]) return out def split(self, chunks, dim=0): """Split the array into smaller arrays along `dim`. Parameters ---------- chunks : int or list[int] If `int`: Number of chunks (see `self.chunk`) Else: Size of each chunk. Must sum to `self.shape[dim]`. dim : int, default=0 Dimensions along which to split. Returns ------- list[MappedArray] """ if isinstance(chunks, int): return self.chunk(chunks, dim) chunks = make_list(chunks) if sum(chunks) != self.shape[dim]: raise ValueError('Chunks must cover the full dimension. ' 'Got {} and {}.' .format(sum(chunks), self.shape[dim])) index = [slice(None)] * self.dim previous_chunks = 0 out = [] for chunk in chunks: index[dim] = slice(previous_chunks, previous_chunks+chunk) out.append(self[tuple(index)]) previous_chunks += chunk return out def channel_first(self, atleast=0): """Permute the dimensions such that all spatial axes are on the right. Parameters ---------- atleast : int, default=0 Make sure that at least this number of non-spatial dimensions exist (new axes are inserted accordingly). Returns ------- MappedArray """ # 1) move spatial dimensions to the right perm = [] spatial = [] for d, is_spatial in enumerate(self.spatial): if is_spatial: spatial.append(d) else: perm.append(d) nb_channels = len(perm) perm = perm + spatial new = self.permute(perm) # 2) add channel axes add_channels = max(0, atleast - nb_channels) if add_channels: index = [slice(None)] * nb_channels \ + [None] * add_channels \ + [Ellipsis] new = new.slice(tuple(index)) return new def channel_last(self, atleast=0): """Permute the dimensions such that all spatial axes are on the left. Parameters ---------- atleast : int, default=0 Make sure that at least this number of non-spatial dimensions exist (new axes are inserted accordingly). Returns ------- MappedArray """ # 1) move spatial dimensions to the right perm = [] spatial = [] for d, is_spatial in enumerate(self.spatial): if is_spatial: spatial.append(d) else: perm.append(d) nb_channels = len(perm) perm = spatial + perm new = self.permute(perm) # 2) add channel axes add_channels = max(0, atleast - nb_channels) if add_channels: index = [Ellipsis] + [None] * add_channels new = new.slice(tuple(index)) return new class CatArray(MappedArray): """A concatenation of mapped arrays. This is largely inspired by virtual concatenation of file_array in SPM: https://github.com/spm/spm12/blob/master/@file_array/cat.m """ _arrays: tuple = [] _dim_cat: int = None # defer attributes fname = property(lambda self: tuple(a.fname for a in self._arrays)) fileobj = property(lambda self: tuple(a.fileobj for a in self._arrays)) is_compressed = property(lambda self: tuple(a.is_compressed for a in self._arrays)) dtype = property(lambda self: tuple(a.dtype for a in self._arrays)) slope = property(lambda self: tuple(a.slope for a in self._arrays)) inter = property(lambda self: tuple(a.inter for a in self._arrays)) _shape = property(lambda self: tuple(a._shape for a in self._arrays)) _dim = property(lambda self: tuple(a._dim for a in self._arrays)) affine = property(lambda self: tuple(a.affine for a in self._arrays)) _affine = property(lambda self: tuple(a._affine for a in self._arrays)) spatial = property(lambda self: tuple(a.spatial for a in self._arrays)) _spatial = property(lambda self: tuple(a._spatial for a in self._arrays)) slicer = property(lambda self: tuple(a.slicer for a in self._arrays)) permutation = property(lambda self: tuple(a.permutation for a in self._arrays)) voxel_size = property(lambda self: tuple(a.voxel_size for a in self._arrays)) def __init__(self, arrays, dim=0): """ Parameters ---------- arrays : sequence[MappedArray] Arrays to concatenate. Their shapes should be identical except along dimension `dim`. dim : int, default=0 Dimension along white to concatenate the arrays """ super().__init__() arrays = list(arrays) dim = dim or 0 self._dim_cat = dim # sanity checks shapes = [] for i, array in enumerate(arrays): if not isinstance(array, MappedArray): raise TypeError('Input arrays should be `MappedArray` ' 'instances. Got {}.',format(type(array))) shape = list(array.shape) del shape[dim] shapes.append(shape) shape0, *shapes = shapes if not all(shape == shape0 for shape in shapes): raise ValueError('Shapes of all concatenated arrays should ' 'be equal except in the concatenation dimension.') # compute output shape shape = list(arrays[0].shape) dims = [array.shape[dim] for array in arrays] shape[dim] = sum(dims) self.shape = tuple(shape) # concatenate self._arrays = tuple(arrays) __repr__ = __str__ def cat(arrays, dim=0): """Concatenate mapped arrays along a dimension. Parameters ---------- arrays : sequence[MappedArray] Arrays to concatenate. Their shapes should be identical except along dimension `dim`. dim : int, default=0 Dimension along white to concatenate the arrays Returns ------- CatArray A symbolic concatenation of all input arrays. Its shape along dimension `dim` is the sum of all input shapes along dimension `dim`. """ return CatArray(arrays, dim) def stack(arrays, dim=0): """Stack mapped arrays along a dimension. Parameters ---------- arrays : sequence[MappedArray] Arrays to concatenate. Their shapes should be identical except along dimension `dim`. dim : int, default=0 Dimension along white to concatenate the arrays Returns ------- CatArray A symbolic stack of all input arrays. """ arrays = [array.unsqueeze(dim=dim) for array in arrays] return cat(arrays, dim=dim)
[ 6738, 4866, 1330, 4866, 198, 11748, 28034, 198, 6738, 299, 2072, 354, 13, 7295, 13, 9078, 1330, 787, 62, 4868, 198, 6738, 299, 2072, 354, 13, 7295, 1330, 288, 19199, 198, 6738, 299, 2072, 354, 13, 2777, 34961, 1330, 1527, 500, 62, 7...
2.262884
15,155
""" blit.py Call if you want to run everything """ import json import os import sys import integrate if __name__ == '__main__': sys.exit(main(sys.argv))
[ 37811, 198, 2436, 270, 13, 9078, 198, 198, 14134, 611, 345, 765, 284, 1057, 2279, 198, 37811, 628, 198, 11748, 33918, 198, 11748, 28686, 198, 11748, 25064, 628, 198, 11748, 19386, 628, 628, 198, 198, 361, 11593, 3672, 834, 6624, 705, ...
2.737705
61
from random import randint numeros = [] # programa principal sorteia() somapar()
[ 6738, 4738, 1330, 43720, 600, 198, 77, 6975, 418, 796, 17635, 198, 2, 1430, 64, 10033, 198, 30619, 68, 544, 3419, 198, 82, 296, 499, 283, 3419 ]
2.962963
27
import pickle import numpy as np #비선형 퍼셉트론 import matplotlib.pylab as plt import sys, os sys.path.append(os.pardir) from dataset.mnist import load_mnist from PIL import Image def step_function(x): ''' y = x > 0 return y.astype(np.int) #np.int와 dtype=int의 역할은 같다. ''' return np.array(x>0, dtype=int) #dtype의 역할은 출력 결과를 dtype=int등으로 통해 원하는 자료형으로 변형하는 것 ''' network=init_network() x=np.array([100,40]) y=forward(network, x) print(y) #print(y) #plt.plot(x,y) #plt.ylim(-0.1,1.1) #plt.show() ''' x_test,t_test = get_data() network=init_networrk_mnist() batch_size=100 accuracy_ct=0 for i in range(0, len(x_test), batch_size):#x_train의 실제 개수 몰라도 len함수 쓰면 된다 x_batch = x_test[i:i+batch_size] y_batch = predict(network, x_batch) p = np.argmax(y_batch, axis=1) #가장 확률이 높은 원소 가져오기? print(np.sum(p == t_test[i:i+batch_size])) accuracy_ct += np.sum(p == t_test[i:i+batch_size]) ''' y=predict(network, x_test[i]) p=np.argmax(y) if p==t_test[i] : accuracy_ct+=1 ''' print("Accuracy:",str(float(accuracy_ct)/len(x_test))) print(accuracy_ct) ''' img = x_train[0] label = t_train[0] print(label) print(img.shape) img = img.reshape(28,28) #이거 패턴화 28,28로 안하면 원하는 이미지 안나온다.-> 이거 이용해서 암호화나 용량 줄이기도 가능? print(img.shape) img_show(img) '''
[ 11748, 2298, 293, 198, 198, 11748, 299, 32152, 355, 45941, 220, 220, 220, 220, 220, 220, 220, 220, 220, 1303, 167, 117, 226, 168, 226, 254, 169, 246, 243, 220, 169, 235, 120, 168, 227, 231, 169, 232, 116, 167, 94, 254, 198, 11748,...
1.481768
905
# coding=utf-8 import copy from flask import Markup, url_for from flask.ext.security import Security, MongoEngineUserDatastore, user_registered from flask.ext.security.core import _SecurityState from flask.ext.security.core import _context_processor as security_default_context_processor from flask.ext.security.views import create_blueprint as security_create_blueprint from flask.ext.security.views import send_confirmation as security_send_confirmation from flask.ext.security.utils import send_mail from slideatlas import models from . import forms, views, login_provider from .principal import register_principal ################################################################################ __all__ = ('blueprint', 'register_with_app') ################################################################################ ################################################################################ # TODO: find a way of automatically registering Shibboleth users with the # appropriate group, similar to facebook_id ################################################################################ def add_config(app): """ Set Flask application configuration options. These are options that should never change. """ # Flask-Security configuration app.config.update( ### Frontend ### SECURITY_FLASH_MESSAGES=True, SECURITY_LOGIN_URL='/login', SECURITY_LOGIN_USER_TEMPLATE='security/login.html', SECURITY_MSG_DISABLED_ACCOUNT=('Password login is disabled for this account.', 'error'), SECURITY_LOGOUT_URL='/logout', # TODO: change '/sessions' to an endpoint name SECURITY_POST_LOGIN_VIEW='/sessions', SECURITY_POST_LOGOUT_VIEW='home', ### Password login options ### SECURITY_DEFAULT_REMEMBER_ME=False, ## New account registration SECURITY_REGISTERABLE=True, SECURITY_REGISTER_URL='/login/password/register', SECURITY_REGISTER_USER_TEMPLATE='security/register.html', SECURITY_SEND_REGISTER_EMAIL=True, SECURITY_EMAIL_SUBJECT_REGISTER='SlideAtlas: Account Created', # uses 'welcome' email body template # TODO: change the email body template, as the default contains a password confirmation link, and we want non-password users to receive a welcome email too ## Confirmation of user's email address SECURITY_CONFIRMABLE=True, SECURITY_CONFIRM_URL='/login/password/confirm', SECURITY_SEND_CONFIRMATION_TEMPLATE='security/resend_confirmation.html', SECURITY_EMAIL_SUBJECT_CONFIRM='SlideAtlas: Account Confirmation', # uses 'confirmation_instructions' email body template SECURITY_CONFIRM_EMAIL_WITHIN='5 days', SECURITY_LOGIN_WITHOUT_CONFIRMATION=False, SECURITY_MSG_EMAIL_CONFIRMED=( Markup( 'Welcome to SlideAtlas! Your account has been confirmed.<br>' '<br>' 'Site administrators may now grant you access to additional content. ' 'You can also contact <a href="mailto:%(email)s">%(email)s</a> with any requests.' % {'email': app.config['SLIDEATLAS_ADMIN_EMAIL']} ), 'success'), ## Recover / reset a lost password SECURITY_RECOVERABLE=True, SECURITY_RESET_URL='/login/password/reset', SECURITY_FORGOT_PASSWORD_TEMPLATE='security/password_reset_1.html', # step 1 SECURITY_RESET_PASSWORD_TEMPLATE='security/password_reset_2.html', # step 2 SECURITY_EMAIL_SUBJECT_PASSWORD_RESET='SlideAtlas: Password Reset Instructions', # uses 'reset_instructions' email body template SECURITY_RESET_PASSWORD_WITHIN='5 days', SECURITY_SEND_PASSWORD_RESET_NOTICE_EMAIL=False, # TODO: do we want to send a confirmation email? SECURITY_EMAIL_SUBJECT_PASSWORD_NOTICE='SlideAtlas: Password Reset Successful', # uses 'reset_notice' email body template ## Change a password SECURITY_CHANGEABLE=True, SECURITY_CHANGE_URL='/login/password/change', SECURITY_CHANGE_PASSWORD_TEMPLATE='security/password_change.html', SECURITY_SEND_PASSWORD_CHANGE_EMAIL=False, # TODO: do we want to send a confirmation email? SECURITY_EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE='SlideAtlas: Password Change Successful', # uses 'change notice' email body template ### Other options ### SECURITY_TRACKABLE=True, # record login statistics in User model SECURITY_PASSWORDLESS=False, # an experimental feature # custom salts can also be set for several other tokens, but this shouldn't be necessary # TODO: there are a few other undocumented config settings in Flask-Security, explore them ) # Flask-Login configuration app.config.update( SESSION_PROTECTION='basic', # some extra security for cookies, see documentation for details REMEMBER_COOKIE_DOMAIN=app.session_interface.get_cookie_domain(app), REMEMBER_COOKIE_HTTPONLY=True, REMEMBER_COOKIE_SECURE=app.config['SLIDEATLAS_HTTPS'], ) ################################################################################ ################################################################################
[ 2, 19617, 28, 40477, 12, 23, 198, 198, 11748, 4866, 198, 198, 6738, 42903, 1330, 2940, 929, 11, 19016, 62, 1640, 198, 6738, 42903, 13, 2302, 13, 12961, 1330, 4765, 11, 42591, 13798, 12982, 27354, 459, 382, 11, 2836, 62, 33736, 198, ...
2.77853
1,919
from django.shortcuts import render from django.urls import reverse from django.http import Http404, HttpResponseRedirect from flight.models import Flight, Passenger def index(request): ''' display all flights ''' context = { 'main_header': 'Flights', 'title': 'Flights', 'flights': Flight.objects.all() } return render(request, 'flight/index.html', context) def flight(request, flight_id): ''' return individual flight details and passengers on this flight''' try: flight = Flight.objects.get(pk=flight_id) except Flight.DoesNotExist: raise Http404(f'Flight {flight} does not exist.') context = { 'flight': flight, 'passengers': flight.passengers.all(), 'non_passengers': Passenger.objects.exclude(flight=flight).all(), 'number_of_passengers': flight.passengers.count() } return render(request, 'flight/flight.html', context)
[ 6738, 42625, 14208, 13, 19509, 23779, 1330, 8543, 198, 6738, 42625, 14208, 13, 6371, 82, 1330, 9575, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 26429, 11, 367, 29281, 31077, 7738, 1060, 198, 6738, 5474, 13, 27530, 1330, 13365, ...
2.722543
346
from setuptools import setup, find_packages, Extension from torch.utils import cpp_extension setup( name='my_lib', version='0.0', description='Learning setup', packages=find_packages(), ext_package='trt_pose', ext_modules=[cpp_extension.CppExtension('plugins', [ 'Learn_cpp/learn.cpp', ])], cmdclass={'build_ext': cpp_extension.BuildExtension}, install_requires=[ ], )
[ 6738, 900, 37623, 10141, 1330, 9058, 11, 1064, 62, 43789, 11, 27995, 198, 6738, 28034, 13, 26791, 1330, 269, 381, 62, 2302, 3004, 628, 198, 40406, 7, 198, 220, 220, 220, 1438, 11639, 1820, 62, 8019, 3256, 198, 220, 220, 220, 2196, 1...
2.602484
161
# -*- coding: utf-8 -*- from typing import Optional from pymarc import Field from unidecode import unidecode, UnidecodeError from bookops_callno.errors import CallNoConstructorError def remove_trailing_punctuation(value: str) -> str: """ Removes any trailing periods, commas, etc. Args: value: string to be processed Returns: value """ if not isinstance(value, str): raise CallNoConstructorError( "Invalid 'value' type used in argument. Must be a string." ) while value[-1] in ".,:;-() ": value = value[:-1] return value def normalize_value(value: str) -> str: """ Removes diacritics from string and changes to uppercase """ if not value: return "" elif not isinstance(value, str): raise CallNoConstructorError( "Invalid 'value' type used in argument. Must be a string." ) try: value = value.replace("\u02b9", "") # Russian: modifier letter prime value = value.replace("\u02bb", "") # Arabic modifier letter turned comma value = value.replace("'", "") value = unidecode(value, errors="strict") value = remove_trailing_punctuation(value).upper() return value except UnidecodeError as exc: raise CallNoConstructorError( f"Unsupported character encountered. Error: '{exc}'." ) def corporate_name_first_word(field: Field = None) -> Optional[str]: """ Returns the uppdercase first word of the corporate entity from the 110 MARC tag Args: field: pymarc.Field instance Returns: name """ if field is None: return None elif not isinstance(field, Field): raise CallNoConstructorError( "Invalid 'field' argument type. Must be pymarc.Field instance." ) if field.tag != "110": return None words = field["a"].strip().split(" ") name = normalize_value(words[0]) return name def corporate_name_full(field: Field = None) -> Optional[str]: """ Returns an uppercase full name of corporate entity. Uses the 110 MARC tag Args: field: pymarc.Field instance Returns: name """ if field is None: return None elif not isinstance(field, Field): raise CallNoConstructorError( "Invalid 'field' argument type. Must be pymarc.Field instance." ) if field.tag not in ("110", "610"): return None phrases = field["a"].strip().split("(") name = normalize_value(phrases[0]) return name def corporate_name_initial(field: Field = None) -> Optional[str]: """ Returns the uppercase first letter of the corporate entity based on the 110 MARC tag Args: field: pymarc.Field instance Returns: initial """ if field is None: return None elif not isinstance(field, Field): raise CallNoConstructorError( "Invalid 'field' argument type. Must be pymarc.Field instance." ) if field.tag != "110": return None name = field["a"] name = normalize_value(name) initial = name[0] return initial def personal_name_initial(field: Field = None) -> Optional[str]: """ Returns the first letter of the last name of a personal author Args: field: pymarc.Field instance Returns initial """ if field is None: return None elif not isinstance(field, Field): raise CallNoConstructorError( "Invalid 'field' argument type. Must be pymarc.Field instance." ) if field.tag != "100": return None name = field["a"].strip() name = normalize_value(name) initial = name[0] return initial def personal_name_surname(field: Field = None) -> Optional[str]: """ Returns an uppercase surname of personal author. Includes any numeration from the subield $b of 100 or 600 MARC tag. Args: field: pymarc.Field instance Returns: name """ if field is None: return None elif not isinstance(field, Field): raise CallNoConstructorError( "Invalid 'field' argument type. Must be pymarc.Field instance." ) if field.tag not in ("100", "600"): return None elif field.indicator1 not in ("0", "1"): return None sub_a = field["a"].strip() # include subfield $b if present try: sub_b = field["b"].strip() name = f"{sub_a} {sub_b}" except AttributeError: name = sub_a name = normalize_value(name) # stop at comma to select surname try: stop = name.index(",") name = name[:stop] except ValueError: pass return name def subject_corporate_name(field: Field = None) -> Optional[str]: """ Returns an uppercase corporate name to be used in subject segment of the call number based on MARC tag 610 Args: field: pymarc.Field instance Returns: name """ if field is None: return None elif not isinstance(field, Field): raise CallNoConstructorError( "Invalid 'field' argument type. Must be pymarc.Field instance." ) if field.tag != "610": return None name = corporate_name_full(field) return name def subject_family_name(field: Field = None) -> Optional[str]: """ Returns an uppercase family name based on the 600 MARC tag Args: field: pymarc.Field instance Returns: name """ if field is None: return None elif not isinstance(field, Field): raise CallNoConstructorError( "Invalid 'field' argument type. Must be pymarc.Field instance." ) if field.tag != "600": return None elif field.indicator1 != "3": return None try: stop = field["a"].index("family") name = field["a"][:stop] except ValueError: return None name = normalize_value(name) return name def subject_personal_name(field: Field = None) -> Optional[str]: """ Returns personal name to be used in subject segment of the call number. Use for biography or Dewey + Name patters, examples: biography: B LOUIS XIV C criticizm of works of an author: 813 ADAMS C Args: field: pymarc.Field instance Returns: name """ if field is None: return None elif not isinstance(field, Field): raise CallNoConstructorError( "Invalid 'field' argument type. Must be pymarc.Field instance." ) if field.tag != "600": return None name = personal_name_surname(field) return name def subject_topic(field: Field = None) -> Optional[str]: """ Returns an uppercase topic to be used in the subject segment of the call number based on MARC tag 650. Valid only for BPL call numbers. Examples: programming language, name of operating system, etc. Args: field: pymarc.Field instance Returns: topic """ pass def title_first_word(field: Field = None) -> Optional[str]: """ Returns an uppercase first word (skipping any articles) of the title field (245 MARC tag subfield $a). Args: field: pymarc.Field instance Returns: word """ pass def title_initial(field: Field = None) -> Optional[str]: """ Returns an uppercase initial (skipping any articles) of the title field (245 MARC tag subfield $a). Args: field: pymarc.Field instance Returns: initial """ if field is None: return None elif not isinstance(field, Field): raise CallNoConstructorError( "Invalid 'field' argument type. Must be pymarc.Field instance." ) if field.tag != "245": return None try: ind2 = int(field.indicator2) except ValueError: return None title = field["a"][ind2:] title = normalize_value(title) initial = title[0] return initial
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 19720, 1330, 32233, 198, 198, 6738, 12972, 3876, 66, 1330, 7663, 198, 6738, 555, 485, 8189, 1330, 555, 485, 8189, 11, 791, 485, 8189, 12331, 628, 198, 6738, ...
2.391628
3,488
'''O Sr. Manoel Joaquim expandiu seus negócios para além dos negócios de 1,99 e agora possui uma loja de conveniências. Faça um programa que implemente uma caixa registradora rudimentar. O programa deverá receber um número desconhecido de valores referentes aos preços das mercadorias. Um valor zero deve ser informado pelo operador para indicar o final da compra. O programa deve então mostrar o total da compra e perguntar o valor em dinheiro que o cliente forneceu, para então calcular e mostrar o valor do troco. Após esta operação, o programa deverá voltar ao ponto inicial, para registrar a próxima compra. A saída deve ser conforme o exemplo abaixo: ''' from time import sleep start = 1 while start == 1: #Reinicia o programa quando chega ao final. print('LOJAS TABAJARA') cont = 1 valor_produto = '' total_compra = 0 while valor_produto != 0: #Recebe valor dos produtos comprados. valor_produto = float(input(f'Produto {cont}: R$ ')) total_compra += valor_produto cont += 1 if valor_produto == 0: #Finaliza o programa. print(f'Total: R$ {total_compra:.2f}') dinheiro_cliente = float(input('Dinheiro: R$ ')) troco = dinheiro_cliente - total_compra print(f'Troco: R$ {troco:.2f}') sleep(3)
[ 7061, 6, 46, 21714, 13, 1869, 78, 417, 5302, 36129, 320, 4292, 16115, 384, 385, 2469, 10205, 979, 418, 31215, 435, 2634, 76, 23430, 2469, 10205, 979, 418, 390, 352, 11, 2079, 304, 556, 5799, 1184, 9019, 334, 2611, 2376, 6592, 390, 7...
2.36036
555
from schnetkit.engine import Stateful models = [Dummy]
[ 6738, 264, 1349, 316, 15813, 13, 18392, 1330, 1812, 913, 628, 198, 198, 27530, 796, 685, 35, 13513, 60, 198 ]
2.9
20
import secrets from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.ciphers.aead import AESGCM from cryptography.hazmat.primitives.kdf.hkdf import HKDF from zigbear.custom_protocol.scapy_layers import ZigbearSecurityLayer
[ 11748, 13141, 198, 198, 6738, 45898, 13, 71, 1031, 6759, 13, 1891, 2412, 1330, 4277, 62, 1891, 437, 198, 6738, 45898, 13, 71, 1031, 6759, 13, 19795, 20288, 1330, 46621, 198, 6738, 45898, 13, 71, 1031, 6759, 13, 19795, 20288, 1330, 113...
3.487805
123
#!/usr/bin/env python2 import os import json import logging from TrackDb import TrackDb from util import subtools from util import santitizer
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 17, 198, 11748, 28686, 198, 11748, 33918, 198, 11748, 18931, 198, 198, 6738, 17762, 43832, 1330, 17762, 43832, 198, 6738, 7736, 1330, 13284, 10141, 198, 6738, 7736, 1330, 264, 415, 3029, 263, ...
3.23913
46
# coding=UTF-8 from __future__ import absolute_import, division, print_function """ Provides reactors that can authenticate an AQMP session """ import six import typing as tp import copy import logging from coolamqp.framing.definitions import ConnectionStart, ConnectionStartOk, \ ConnectionTune, ConnectionTuneOk, ConnectionOpen, ConnectionOpenOk from coolamqp.framing.frames import AMQPMethodFrame from coolamqp.uplink.connection.states import ST_ONLINE from coolamqp.uplink.heartbeat import Heartbeater from coolamqp import __version__ PUBLISHER_CONFIRMS = b'publisher_confirms' CONSUMER_CANCEL_NOTIFY = b'consumer_cancel_notify' CONNECTION_BLOCKED = b'connection.blocked' SUPPORTED_EXTENSIONS = [ PUBLISHER_CONFIRMS, CONSUMER_CANCEL_NOTIFY, # half assed support - we just .cancel the consumer, see #12 CONNECTION_BLOCKED ] CLIENT_DATA = [ # because RabbitMQ is some kind of a fascist and does not allow # these fields to be of type short-string (b'product', (b'CoolAMQP', 'S')), (b'version', (__version__.encode('utf8'), 'S')), (b'copyright', (b'Copyright (C) 2016-2021 SMOK sp. z o.o.', 'S')), ( b'information', ( b'Licensed under the MIT License.\nSee https://github.com/smok-serwis/coolamqp for details', 'S')), (b'capabilities', ([(capa, (True, 't')) for capa in SUPPORTED_EXTENSIONS], 'F')), ] WATCHDOG_TIMEOUT = 10 logger = logging.getLogger(__name__) class Handshaker(object): """ Object that given a connection rolls the handshake. """ def __init__(self, connection, # type: coolamqp.uplink.connection.Connection node_definition, # type: coolamqp.objects.NodeDefinition on_success, # type: tp.Callable[[], None] extra_properties=None # type: tp.Dict[bytes, tp.Tuple[tp.Any, str]] ): """ :param connection: Connection instance to use :type node_definition: NodeDefinition :param on_success: callable/0, on success """ self.connection = connection self.login = node_definition.user.encode('utf8') self.password = node_definition.password.encode('utf8') self.virtual_host = node_definition.virtual_host.encode('utf8') self.heartbeat = node_definition.heartbeat or 0 self.connection.watch_for_method(0, ConnectionStart, self.on_connection_start) # Callbacks self.on_success = on_success self.EXTRA_PROPERTIES = extra_properties or [] # Called by internal setup def on_watchdog(self): """ Called WATCHDOG_TIMEOUT seconds after setup begins If we are not ST_ONLINE after that much, something is wrong and pwn this connection. """ # Not connected in 20 seconds - abort if self.connection.state != ST_ONLINE: # closing the connection this way will get to Connection by channels of ListenerThread self.connection.send(None)
[ 2, 19617, 28, 48504, 12, 23, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 198, 198, 37811, 198, 15946, 1460, 28502, 326, 460, 8323, 5344, 281, 39514, 7378, 6246, 198, 37811, 198, 11748, 2237, 198,...
2.481663
1,227
# Copyright 2008 the V8 project authors. 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 Google Inc. 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. import test import os from os.path import join, dirname, exists, splitext, isdir, basename import re import ast FLAGS_PATTERN = re.compile(r"//\s+Flags:(.*)") FILES_PATTERN = re.compile(r"//\s+Files:(.*)") chakraBannedFlags = ["--expose_externalize_string"]
[ 2, 15069, 3648, 262, 569, 23, 1628, 7035, 13, 1439, 2489, 10395, 13, 198, 2, 2297, 396, 3890, 290, 779, 287, 2723, 290, 13934, 5107, 11, 351, 393, 1231, 198, 2, 17613, 11, 389, 10431, 2810, 326, 262, 1708, 3403, 389, 198, 2, 1138,...
3.26738
561
""" 抽象工厂方法--对象创建型模式 1. 目标 定义一个用于创建对象的接口, 让子类决定实例化哪一个类, 使一个类的实例化延迟到子类。 """ if __name__ == '__main__': cream_cake_factory = CreamCakeFactory() cream_cake = cream_cake_factory.make_cake() print(cream_cake) fruit_cake_factory = FruitCakeFactory() fruit_cake = fruit_cake_factory.make_cake() print(fruit_cake)
[ 37811, 198, 162, 232, 121, 164, 109, 94, 32432, 98, 43889, 224, 43095, 37345, 243, 438, 43380, 117, 164, 109, 94, 26344, 249, 161, 119, 118, 161, 252, 233, 162, 101, 94, 28156, 237, 198, 198, 16, 13, 13328, 249, 106, 43718, 229, 1...
1.408333
240
from django.db import models from django.contrib.auth.models import User # Create your models here.
[ 6738, 42625, 14208, 13, 9945, 1330, 4981, 198, 6738, 42625, 14208, 13, 3642, 822, 13, 18439, 13, 27530, 1330, 11787, 198, 2, 13610, 534, 4981, 994, 13, 628 ]
3.607143
28
#!/usr/bin/env python # Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Concatenates D-Bus busconfig files.""" import sys import xml.etree.ElementTree _BUSCONFIG_FILE_HEADER = b"""<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd"> """ if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 15069, 13130, 383, 18255, 1505, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 5765, 286, 428, 2723, 2438, 318, 21825, 416, 257, 347, 10305, 12, 7635, 5964, 326, 460, 307, 198, 2, 1043...
2.859649
171
import sys; import numpy as np; import pandas as pd; np.set_printoptions(threshold=sys.maxsize) # replace the range, sample size with your custom numbers arr = np.array(np.random.choice(range(10000), 10000, replace=False)) print(arr) DF = pd.DataFrame(arr) DF.to_csv("temp.csv")
[ 11748, 25064, 26, 198, 11748, 299, 32152, 355, 45941, 26, 198, 11748, 19798, 292, 355, 279, 67, 26, 198, 198, 37659, 13, 2617, 62, 4798, 25811, 7, 400, 10126, 28, 17597, 13, 9806, 7857, 8, 198, 2, 6330, 262, 2837, 11, 6291, 2546, ...
2.82
100
import torch from sklearn.preprocessing import LabelEncoder from torch.utils.data import Dataset, DataLoader
[ 11748, 28034, 198, 6738, 1341, 35720, 13, 3866, 36948, 1330, 36052, 27195, 12342, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 16092, 292, 316, 11, 6060, 17401, 628, 198 ]
3.827586
29