Dataset Viewer
hexsha
string | size
int64 | ext
string | lang
string | max_stars_repo_path
string | max_stars_repo_name
string | max_stars_repo_head_hexsha
string | max_stars_repo_licenses
list | max_stars_count
int64 | max_stars_repo_stars_event_min_datetime
string | max_stars_repo_stars_event_max_datetime
string | max_issues_repo_path
string | max_issues_repo_name
string | max_issues_repo_head_hexsha
string | max_issues_repo_licenses
list | max_issues_count
int64 | max_issues_repo_issues_event_min_datetime
string | max_issues_repo_issues_event_max_datetime
string | max_forks_repo_path
string | max_forks_repo_name
string | max_forks_repo_head_hexsha
string | max_forks_repo_licenses
list | max_forks_count
int64 | max_forks_repo_forks_event_min_datetime
string | max_forks_repo_forks_event_max_datetime
string | content
string | avg_line_length
float64 | max_line_length
int64 | alphanum_fraction
float64 | qsc_code_num_words_quality_signal
int64 | qsc_code_num_chars_quality_signal
float64 | qsc_code_mean_word_length_quality_signal
float64 | qsc_code_frac_words_unique_quality_signal
float64 | qsc_code_frac_chars_top_2grams_quality_signal
float64 | qsc_code_frac_chars_top_3grams_quality_signal
float64 | qsc_code_frac_chars_top_4grams_quality_signal
float64 | qsc_code_frac_chars_dupe_5grams_quality_signal
float64 | qsc_code_frac_chars_dupe_6grams_quality_signal
float64 | qsc_code_frac_chars_dupe_7grams_quality_signal
float64 | qsc_code_frac_chars_dupe_8grams_quality_signal
float64 | qsc_code_frac_chars_dupe_9grams_quality_signal
float64 | qsc_code_frac_chars_dupe_10grams_quality_signal
float64 | qsc_code_frac_chars_replacement_symbols_quality_signal
float64 | qsc_code_frac_chars_digital_quality_signal
float64 | qsc_code_frac_chars_whitespace_quality_signal
float64 | qsc_code_size_file_byte_quality_signal
float64 | qsc_code_num_lines_quality_signal
float64 | qsc_code_num_chars_line_max_quality_signal
float64 | qsc_code_num_chars_line_mean_quality_signal
float64 | qsc_code_frac_chars_alphabet_quality_signal
float64 | qsc_code_frac_chars_comments_quality_signal
float64 | qsc_code_cate_xml_start_quality_signal
float64 | qsc_code_frac_lines_dupe_lines_quality_signal
float64 | qsc_code_cate_autogen_quality_signal
float64 | qsc_code_frac_lines_long_string_quality_signal
float64 | qsc_code_frac_chars_string_length_quality_signal
float64 | qsc_code_frac_chars_long_word_length_quality_signal
float64 | qsc_code_frac_lines_string_concat_quality_signal
float64 | qsc_code_cate_encoded_data_quality_signal
float64 | qsc_code_frac_chars_hex_words_quality_signal
float64 | qsc_code_frac_lines_prompt_comments_quality_signal
float64 | qsc_code_frac_lines_assert_quality_signal
float64 | qsc_codepython_cate_ast_quality_signal
float64 | qsc_codepython_frac_lines_func_ratio_quality_signal
float64 | qsc_codepython_cate_var_zero_quality_signal
bool | qsc_codepython_frac_lines_pass_quality_signal
float64 | qsc_codepython_frac_lines_import_quality_signal
float64 | qsc_codepython_frac_lines_simplefunc_quality_signal
float64 | qsc_codepython_score_lines_no_logic_quality_signal
float64 | qsc_codepython_frac_lines_print_quality_signal
float64 | qsc_code_num_words
int64 | qsc_code_num_chars
int64 | qsc_code_mean_word_length
int64 | qsc_code_frac_words_unique
null | qsc_code_frac_chars_top_2grams
int64 | qsc_code_frac_chars_top_3grams
int64 | qsc_code_frac_chars_top_4grams
int64 | qsc_code_frac_chars_dupe_5grams
int64 | qsc_code_frac_chars_dupe_6grams
int64 | qsc_code_frac_chars_dupe_7grams
int64 | qsc_code_frac_chars_dupe_8grams
int64 | qsc_code_frac_chars_dupe_9grams
int64 | qsc_code_frac_chars_dupe_10grams
int64 | qsc_code_frac_chars_replacement_symbols
int64 | qsc_code_frac_chars_digital
int64 | qsc_code_frac_chars_whitespace
int64 | qsc_code_size_file_byte
int64 | qsc_code_num_lines
int64 | qsc_code_num_chars_line_max
int64 | qsc_code_num_chars_line_mean
int64 | qsc_code_frac_chars_alphabet
int64 | qsc_code_frac_chars_comments
int64 | qsc_code_cate_xml_start
int64 | qsc_code_frac_lines_dupe_lines
int64 | qsc_code_cate_autogen
int64 | qsc_code_frac_lines_long_string
int64 | qsc_code_frac_chars_string_length
int64 | qsc_code_frac_chars_long_word_length
int64 | qsc_code_frac_lines_string_concat
null | qsc_code_cate_encoded_data
int64 | qsc_code_frac_chars_hex_words
int64 | qsc_code_frac_lines_prompt_comments
int64 | qsc_code_frac_lines_assert
int64 | qsc_codepython_cate_ast
int64 | qsc_codepython_frac_lines_func_ratio
int64 | qsc_codepython_cate_var_zero
int64 | qsc_codepython_frac_lines_pass
int64 | qsc_codepython_frac_lines_import
int64 | qsc_codepython_frac_lines_simplefunc
int64 | qsc_codepython_score_lines_no_logic
int64 | qsc_codepython_frac_lines_print
int64 | effective
string | hits
int64 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d9a00b2c6f1a0e88ad5b4a7def2a45bd074f417f
| 3,880 |
py
|
Python
|
pypagai/models/model_lstm.py
|
gcouti/pypagAI
|
d08fac95361dcc036d890a88cb86ce090322a612
|
[
"Apache-2.0"
] | 1 |
2018-07-24T18:53:26.000Z
|
2018-07-24T18:53:26.000Z
|
pypagai/models/model_lstm.py
|
gcouti/pypagAI
|
d08fac95361dcc036d890a88cb86ce090322a612
|
[
"Apache-2.0"
] | 7 |
2020-01-28T21:45:14.000Z
|
2022-03-11T23:20:53.000Z
|
pypagai/models/model_lstm.py
|
gcouti/pypagAI
|
d08fac95361dcc036d890a88cb86ce090322a612
|
[
"Apache-2.0"
] | null | null | null |
from keras import Model, Input
from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten
from keras.optimizers import Adam
from pypagai.models.base import KerasModel
class SimpleLSTM(KerasModel):
"""
Use a simple lstm neural network
"""
@staticmethod
def default_config():
config = KerasModel.default_config()
config['hidden'] = 32
return config
def __init__(self, cfg):
super().__init__(cfg)
self._cfg_ = cfg
def _create_network_(self):
hidden = self._cfg_['hidden']
story = Input((self._story_maxlen, ), name='story')
question = Input((self._query_maxlen, ), name='question')
conc = concatenate([story, question],)
conc = Reshape((1, int(conc.shape[1])))(conc)
conc = Permute((2, 1))(conc)
response = LSTM(hidden, dropout=0.2, recurrent_dropout=0.2)(conc)
response = Dense(self._vocab_size, activation='softmax')(response)
self._model = Model(inputs=[story, question], outputs=response)
self._model.compile(optimizer=Adam(lr=2e-4), loss='sparse_categorical_crossentropy', metrics=['accuracy'])
class EmbedLSTM(KerasModel):
"""
Use a simple lstm neural network
"""
@staticmethod
def default_config():
config = KerasModel.default_config()
config['hidden'] = 32
return config
def __init__(self, cfg):
super().__init__(cfg)
self._cfg_ = cfg
def _create_network_(self):
hidden = self._cfg_['hidden']
story = Input((self._story_maxlen, ), name='story')
question = Input((self._query_maxlen, ), name='question')
eb_story = Embedding(self._vocab_size, 64)(story)
eb_story = Dropout(0.3)(eb_story)
eb_question = Embedding(self._vocab_size, 64)(question)
eb_question = Dropout(0.3)(eb_question)
conc = concatenate([eb_story, eb_question], axis=1)
response = LSTM(hidden, dropout=0.2, recurrent_dropout=0.2)(conc)
response = Dense(self._vocab_size, activation='softmax')(response)
self._model = Model(inputs=[story, question], outputs=response)
self._model.compile(optimizer=Adam(lr=2e-4), loss='sparse_categorical_crossentropy', metrics=['accuracy'])
class ConvLSTM(KerasModel):
"""
Use a simple lstm neural network
"""
@staticmethod
def default_config():
config = KerasModel.default_config()
config['hidden'] = 32
return config
def __init__(self, model_cfg):
super().__init__(model_cfg)
self._cfg = model_cfg
def _create_network_(self):
hidden = self._cfg['hidden']
story = Input((self._story_maxlen, ), name='story')
question = Input((self._query_maxlen, ), name='question')
eb_story = Embedding(self._vocab_size, 64)(story)
eb_story = Convolution1D(64, 3, padding='same')(eb_story)
eb_story = Convolution1D(32, 3, padding='same')(eb_story)
eb_story = Convolution1D(16, 3, padding='same')(eb_story)
# eb_story = Flatten()(eb_story)
eb_question = Embedding(self._vocab_size, 64)(question)
eb_question = Convolution1D(64, 3, padding='same')(eb_question)
eb_question = Convolution1D(32, 3, padding='same')(eb_question)
eb_question = Convolution1D(16, 3, padding='same')(eb_question)
# eb_question = Flatten()(eb_question)
conc = concatenate([eb_story, eb_question], axis=1)
response = LSTM(hidden, dropout=0.2, recurrent_dropout=0.2)(conc)
response = Dense(self._vocab_size, activation='softmax')(response)
self._model = Model(inputs=[story, question], outputs=response)
self._model.compile(optimizer=Adam(lr=2e-4), loss='sparse_categorical_crossentropy', metrics=['accuracy'])
| 33.162393 | 114 | 0.650773 | 460 | 3,880 | 5.226087 | 0.171739 | 0.040765 | 0.037854 | 0.034942 | 0.851498 | 0.851498 | 0.835691 | 0.811564 | 0.741681 | 0.741681 | 0 | 0.022069 | 0.217526 | 3,880 | 116 | 115 | 33.448276 | 0.769763 | 0.043041 | 0 | 0.694444 | 0 | 0 | 0.064648 | 0.025368 | 0 | 0 | 0 | 0 | 0 | 1 | 0.125 | false | 0 | 0.055556 | 0 | 0.263889 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
0
| 6 |
d9fe73cee8f0ad5d98f81eb365b256cba7970cbe
| 13,093 |
gyp
|
Python
|
third_party/protobuf/protobuf.gyp
|
meego-tablet-ux/meego-app-browser
|
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
|
[
"BSD-3-Clause"
] | 1 |
2015-10-12T09:14:22.000Z
|
2015-10-12T09:14:22.000Z
|
third_party/protobuf/protobuf.gyp
|
meego-tablet-ux/meego-app-browser
|
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
|
[
"BSD-3-Clause"
] | null | null | null |
third_party/protobuf/protobuf.gyp
|
meego-tablet-ux/meego-app-browser
|
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
|
[
"BSD-3-Clause"
] | 1 |
2020-11-04T07:22:28.000Z
|
2020-11-04T07:22:28.000Z
|
# Copyright (c) 2009 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.
{
'conditions': [
['OS!="win"', {
'variables': {
'config_h_dir':
'.', # crafted for gcc/linux.
},
}, { # else, OS=="win"
'variables': {
'config_h_dir':
'vsprojects', # crafted for msvc.
},
'target_defaults': {
'msvs_disabled_warnings': [
4018, # signed/unsigned mismatch in comparison
4244, # implicit conversion, possible loss of data
4355, # 'this' used in base member initializer list
],
'defines!': [
'WIN32_LEAN_AND_MEAN', # Protobuf defines this itself.
],
},
}]
],
'targets': [
# The "lite" lib is about 1/7th the size of the heavy lib,
# but it doesn't support some of the more exotic features of
# protobufs, like reflection. To generate C++ code that can link
# against the lite version of the library, add the option line:
#
# option optimize_for = LITE_RUNTIME;
#
# to your .proto file.
{
'target_name': 'protobuf_lite',
'type': '<(library)',
'toolsets': ['host', 'target'],
'sources': [
'src/google/protobuf/stubs/common.h',
'src/google/protobuf/stubs/once.h',
'src/google/protobuf/extension_set.h',
'src/google/protobuf/generated_message_util.h',
'src/google/protobuf/message_lite.h',
'src/google/protobuf/repeated_field.h',
'src/google/protobuf/unknown_field_set.cc',
'src/google/protobuf/unknown_field_set.h',
'src/google/protobuf/wire_format_lite.h',
'src/google/protobuf/wire_format_lite_inl.h',
'src/google/protobuf/io/coded_stream.h',
'src/google/protobuf/io/zero_copy_stream.h',
'src/google/protobuf/io/zero_copy_stream_impl_lite.h',
'src/google/protobuf/stubs/common.cc',
'src/google/protobuf/stubs/once.cc',
'src/google/protobuf/stubs/hash.h',
'src/google/protobuf/stubs/map-util.h',
'src/google/protobuf/stubs/stl_util-inl.h',
'src/google/protobuf/extension_set.cc',
'src/google/protobuf/generated_message_util.cc',
'src/google/protobuf/message_lite.cc',
'src/google/protobuf/repeated_field.cc',
'src/google/protobuf/wire_format_lite.cc',
'src/google/protobuf/io/coded_stream.cc',
'src/google/protobuf/io/coded_stream_inl.h',
'src/google/protobuf/io/zero_copy_stream.cc',
'src/google/protobuf/io/zero_copy_stream_impl_lite.cc',
'<(config_h_dir)/config.h',
],
'include_dirs': [
'<(config_h_dir)',
'src',
],
# This macro must be defined to suppress the use of dynamic_cast<>,
# which requires RTTI.
'defines': [
'GOOGLE_PROTOBUF_NO_RTTI',
],
'direct_dependent_settings': {
'include_dirs': [
'<(config_h_dir)',
'src',
],
'defines': [
'GOOGLE_PROTOBUF_NO_RTTI',
],
},
},
# This is the full, heavy protobuf lib that's needed for c++ .proto's
# that don't specify the LITE_RUNTIME option. The protocol
# compiler itself (protoc) falls into that category.
#
# DO NOT LINK AGAINST THIS TARGET IN CHROME CODE --agl
{
'target_name': 'protobuf_full_do_not_use',
'type': '<(library)',
'toolsets': ['host','target'],
'sources': [
'src/google/protobuf/descriptor.h',
'src/google/protobuf/descriptor.pb.h',
'src/google/protobuf/descriptor_database.h',
'src/google/protobuf/dynamic_message.h',
'src/google/protobuf/generated_message_reflection.h',
'src/google/protobuf/message.h',
'src/google/protobuf/reflection_ops.h',
'src/google/protobuf/service.h',
'src/google/protobuf/text_format.h',
'src/google/protobuf/unknown_field_set.h',
'src/google/protobuf/wire_format.h',
'src/google/protobuf/io/gzip_stream.h',
'src/google/protobuf/io/printer.h',
'src/google/protobuf/io/tokenizer.h',
'src/google/protobuf/io/zero_copy_stream_impl.h',
'src/google/protobuf/compiler/code_generator.h',
'src/google/protobuf/compiler/command_line_interface.h',
'src/google/protobuf/compiler/importer.h',
'src/google/protobuf/compiler/parser.h',
'src/google/protobuf/stubs/strutil.cc',
'src/google/protobuf/stubs/strutil.h',
'src/google/protobuf/stubs/substitute.cc',
'src/google/protobuf/stubs/substitute.h',
'src/google/protobuf/stubs/structurally_valid.cc',
'src/google/protobuf/descriptor.cc',
'src/google/protobuf/descriptor.pb.cc',
'src/google/protobuf/descriptor_database.cc',
'src/google/protobuf/dynamic_message.cc',
'src/google/protobuf/extension_set_heavy.cc',
'src/google/protobuf/generated_message_reflection.cc',
'src/google/protobuf/message.cc',
'src/google/protobuf/reflection_ops.cc',
'src/google/protobuf/service.cc',
'src/google/protobuf/text_format.cc',
'src/google/protobuf/unknown_field_set.cc',
'src/google/protobuf/wire_format.cc',
# This file pulls in zlib, but it's not actually used by protoc, so
# instead of compiling zlib for the host, let's just exclude this.
# 'src/src/google/protobuf/io/gzip_stream.cc',
'src/google/protobuf/io/printer.cc',
'src/google/protobuf/io/tokenizer.cc',
'src/google/protobuf/io/zero_copy_stream_impl.cc',
'src/google/protobuf/compiler/importer.cc',
'src/google/protobuf/compiler/parser.cc',
],
'dependencies': [
'protobuf_lite',
],
'export_dependent_settings': [
'protobuf_lite',
],
},
{
'target_name': 'protoc',
'type': 'executable',
'toolsets': ['host'],
'sources': [
'src/google/protobuf/compiler/code_generator.cc',
'src/google/protobuf/compiler/command_line_interface.cc',
'src/google/protobuf/compiler/plugin.cc',
'src/google/protobuf/compiler/plugin.pb.cc',
'src/google/protobuf/compiler/subprocess.cc',
'src/google/protobuf/compiler/subprocess.h',
'src/google/protobuf/compiler/zip_writer.cc',
'src/google/protobuf/compiler/zip_writer.h',
'src/google/protobuf/compiler/cpp/cpp_enum.cc',
'src/google/protobuf/compiler/cpp/cpp_enum.h',
'src/google/protobuf/compiler/cpp/cpp_enum_field.cc',
'src/google/protobuf/compiler/cpp/cpp_enum_field.h',
'src/google/protobuf/compiler/cpp/cpp_extension.cc',
'src/google/protobuf/compiler/cpp/cpp_extension.h',
'src/google/protobuf/compiler/cpp/cpp_field.cc',
'src/google/protobuf/compiler/cpp/cpp_field.h',
'src/google/protobuf/compiler/cpp/cpp_file.cc',
'src/google/protobuf/compiler/cpp/cpp_file.h',
'src/google/protobuf/compiler/cpp/cpp_generator.cc',
'src/google/protobuf/compiler/cpp/cpp_helpers.cc',
'src/google/protobuf/compiler/cpp/cpp_helpers.h',
'src/google/protobuf/compiler/cpp/cpp_message.cc',
'src/google/protobuf/compiler/cpp/cpp_message.h',
'src/google/protobuf/compiler/cpp/cpp_message_field.cc',
'src/google/protobuf/compiler/cpp/cpp_message_field.h',
'src/google/protobuf/compiler/cpp/cpp_primitive_field.cc',
'src/google/protobuf/compiler/cpp/cpp_primitive_field.h',
'src/google/protobuf/compiler/cpp/cpp_service.cc',
'src/google/protobuf/compiler/cpp/cpp_service.h',
'src/google/protobuf/compiler/cpp/cpp_string_field.cc',
'src/google/protobuf/compiler/cpp/cpp_string_field.h',
'src/google/protobuf/compiler/java/java_enum.cc',
'src/google/protobuf/compiler/java/java_enum.h',
'src/google/protobuf/compiler/java/java_enum_field.cc',
'src/google/protobuf/compiler/java/java_enum_field.h',
'src/google/protobuf/compiler/java/java_extension.cc',
'src/google/protobuf/compiler/java/java_extension.h',
'src/google/protobuf/compiler/java/java_field.cc',
'src/google/protobuf/compiler/java/java_field.h',
'src/google/protobuf/compiler/java/java_file.cc',
'src/google/protobuf/compiler/java/java_file.h',
'src/google/protobuf/compiler/java/java_generator.cc',
'src/google/protobuf/compiler/java/java_helpers.cc',
'src/google/protobuf/compiler/java/java_helpers.h',
'src/google/protobuf/compiler/java/java_message.cc',
'src/google/protobuf/compiler/java/java_message.h',
'src/google/protobuf/compiler/java/java_message_field.cc',
'src/google/protobuf/compiler/java/java_message_field.h',
'src/google/protobuf/compiler/java/java_primitive_field.cc',
'src/google/protobuf/compiler/java/java_primitive_field.h',
'src/google/protobuf/compiler/java/java_service.cc',
'src/google/protobuf/compiler/java/java_service.h',
'src/google/protobuf/compiler/java/java_string_field.cc',
'src/google/protobuf/compiler/java/java_string_field.h',
'src/google/protobuf/compiler/python/python_generator.cc',
'src/google/protobuf/compiler/main.cc',
],
'dependencies': [
'protobuf_full_do_not_use',
],
'include_dirs': [
'<(config_h_dir)',
'src/src',
],
},
{
# Generate the python module needed by all protoc-generated Python code.
'target_name': 'py_proto',
'type': 'none',
'copies': [
{
'destination': '<(PRODUCT_DIR)/pyproto/google/',
'files': [
# google/ module gets an empty __init__.py.
'__init__.py',
],
},
{
'destination': '<(PRODUCT_DIR)/pyproto/google/protobuf',
'files': [
'python/google/protobuf/__init__.py',
'python/google/protobuf/descriptor.py',
'python/google/protobuf/message.py',
'python/google/protobuf/reflection.py',
'python/google/protobuf/service.py',
'python/google/protobuf/service_reflection.py',
'python/google/protobuf/text_format.py',
# TODO(ncarter): protoc's python generator treats descriptor.proto
# specially, but it's not possible to trigger the special treatment
# unless you run protoc from ./src/src (the treatment is based
# on the path to the .proto file matching a constant exactly).
# I'm not sure how to convince gyp to execute a rule from a
# different directory. Until this is resolved, use a copy of
# descriptor_pb2.py that I manually generated.
'descriptor_pb2.py',
],
},
{
'destination': '<(PRODUCT_DIR)/pyproto/google/protobuf/internal',
'files': [
'python/google/protobuf/internal/__init__.py',
'python/google/protobuf/internal/api_implementation.py',
'python/google/protobuf/internal/containers.py',
'python/google/protobuf/internal/cpp_message.py',
'python/google/protobuf/internal/decoder.py',
'python/google/protobuf/internal/encoder.py',
'python/google/protobuf/internal/generator_test.py',
'python/google/protobuf/internal/message_listener.py',
'python/google/protobuf/internal/python_message.py',
'python/google/protobuf/internal/type_checkers.py',
'python/google/protobuf/internal/wire_format.py',
],
},
],
# # We can't generate a proper descriptor_pb2.py -- see earlier comment.
# 'rules': [
# {
# 'rule_name': 'genproto',
# 'extension': 'proto',
# 'inputs': [
# '<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)protoc<(EXECUTABLE_SUFFIX)',
# ],
# 'variables': {
# # The protoc compiler requires a proto_path argument with the
# # directory containing the .proto file.
# 'rule_input_relpath': 'src/google/protobuf',
# },
# 'outputs': [
# '<(PRODUCT_DIR)/pyproto/google/protobuf/<(RULE_INPUT_ROOT)_pb2.py',
# ],
# 'action': [
# '<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)protoc<(EXECUTABLE_SUFFIX)',
# '-I./src',
# '-I.',
# '--python_out=<(PRODUCT_DIR)/pyproto/google/protobuf',
# 'google/protobuf/descriptor.proto',
# ],
# 'message': 'Generating Python code from <(RULE_INPUT_PATH)',
# },
# ],
# 'dependencies': [
# 'protoc#host',
# ],
# 'sources': [
# 'src/google/protobuf/descriptor.proto',
# ],
},
],
}
# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
| 41.302839 | 81 | 0.621554 | 1,560 | 13,093 | 5.064103 | 0.186538 | 0.269367 | 0.273291 | 0.196203 | 0.700127 | 0.478734 | 0.360633 | 0.256582 | 0.064937 | 0.025949 | 0 | 0.002701 | 0.236462 | 13,093 | 316 | 82 | 41.433544 | 0.787536 | 0.21523 | 0 | 0.218107 | 0 | 0 | 0.677521 | 0.62348 | 0 | 0 | 0 | 0.003165 | 0 | 1 | 0 | true | 0 | 0.00823 | 0 | 0.00823 | 0.00823 | 0 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 |
0
| 6 |
8a04ff873e3cd041bc9cad7f7fc7707f7c185cce
| 6,652 |
py
|
Python
|
invera/api/tests.py
|
LeoLeiva/todo-challenge
|
f6f24f53758eb4e425c91516bcab7af8cad66814
|
[
"MIT"
] | null | null | null |
invera/api/tests.py
|
LeoLeiva/todo-challenge
|
f6f24f53758eb4e425c91516bcab7af8cad66814
|
[
"MIT"
] | null | null | null |
invera/api/tests.py
|
LeoLeiva/todo-challenge
|
f6f24f53758eb4e425c91516bcab7af8cad66814
|
[
"MIT"
] | 1 |
2021-01-10T20:19:42.000Z
|
2021-01-10T20:19:42.000Z
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import inspect
from task.models import InveraTask
from api.utils import send_test_csv_report
from django.contrib.auth.models import User
from rest_framework.test import APIClient, APITestCase
from rest_framework.reverse import reverse
from rest_framework import status
TEST_RESULTS = []
RECIPIENTS = ['email@destino.com']
class TaskListTestCase(APITestCase):
def setUp(self) -> None:
self.user = User.objects.create_user(
username='test_user', password='adminpass')
self.other_user = User.objects.create_user(
username='other_user', password='adminpass')
self.task = InveraTask.objects.create(
userTask=self.user, title='My Initial Task')
self.client = APIClient()
@classmethod
def tearDownClass(cls):
User.objects.filter(username__in=['test_user', 'other_user']).delete()
def test_create_task_with_un_authenticate_user(self):
"""
En este caso de prueba, estamos probando la API Task Create utilizando un usuario no autenticado.
"""
response = self.client.post(
reverse('api-task'), {'title': 'My Task 1'}, format='json')
is_passed = response.status_code == status.HTTP_403_FORBIDDEN
TEST_RESULTS.append({
"result": "Passed" if is_passed else "Failed",
"test_name": inspect.currentframe().f_code.co_name,
"test_description": "El usuario no autenticado no puede agregar una tarea a la lista"
})
if is_passed:
print("Resultado: Aprobado")
else:
print("Resultado: Fallido")
print("Nombre del test: " + inspect.currentframe().f_code.co_name)
print("Descripcion: El usuario no autenticado no puede agregar una tarea a la lista")
print("-----------")
def test_put_task_with_un_authenticate_user(self):
"""
En este caso de prueba, estamos probando la API Task PUT utilizando un usuario no autenticado.
"""
response = self.client.put(
reverse('api-task'), {'title': 'My Task'}, format='json')
is_passed = response.status_code == status.HTTP_403_FORBIDDEN
TEST_RESULTS.append({
"result": "Passed" if is_passed else "Failed",
"test_name": inspect.currentframe().f_code.co_name,
"test_description": "El usuario no autenticado no puede modificar una tarea"
})
if is_passed:
print("Resultado: Aprobado")
else:
print("Resultado: Fallido")
print("Nombre del test: " + inspect.currentframe().f_code.co_name)
print("Descripcion: El usuario no autenticado no puede modificar una tarea")
print("-----------")
def test_put_task_with_authenticated_user(self):
self.client.login(username='test_user', password='adminpass')
response = self.client.put(reverse('api-task-detail', args=[str(self.task.idTask)]), {'title': 'My Task 2'}, format='json')
is_passed = response.status_code == status.HTTP_200_OK
TEST_RESULTS.append({
"result": "Passed" if is_passed else "Failed",
"test_name": inspect.currentframe().f_code.co_name,
"test_description": "Usuario autenticado puede modificar una tarea suya"
})
if is_passed:
print("Resultado: Aprobado")
else:
print("Resultado: Fallido")
print("Nombre del test: " + inspect.currentframe().f_code.co_name)
print("Descripcion: Usuario autenticado puede modificar una tarea suya")
print("-----------")
def test_get_other_user_task_detail(self):
"""
En este caso de prueba, estamos probando la API Task GET y tratando de obtener detalles de la tarea de un usuario que usa credenciales de usuario diferentes.
"""
self.client.login(username='other_user', password='adminpass')
response = self.client.get(reverse('api-task-detail', args=[str(self.task.idTask)]))
is_passed = response.status_code == status.HTTP_404_NOT_FOUND
# is_passed = response.status_code == status.HTTP_403_FORBIDDEN
TEST_RESULTS.append({
"result": "Passed" if is_passed else "Failed",
"test_name": inspect.currentframe().f_code.co_name,
"test_description": "Solo el propietario puede ver el detalle de la tarea"
})
if is_passed:
print("Resultado: Aprobado")
else:
print("Resultado: Fallido")
print("Nombre del test: " + inspect.currentframe().f_code.co_name)
print("Descripcion: Solo el propietario puede ver el detalle de la tarea")
print("-----------")
def test_create_task_with_authenticated_user(self):
self.client.login(username='test_user', password='adminpass')
response = self.client.post(reverse('api-task'), {'title': 'My Task'}, format='json')
is_passed = response.status_code == status.HTTP_201_CREATED
TEST_RESULTS.append({
"result": "Passed" if is_passed else "Failed",
"test_name": inspect.currentframe().f_code.co_name,
"test_description": "Usuario autenticado agrega tarea a la lista"
})
if is_passed:
print("Resultado: Aprobado")
else:
print("Resultado: Fallido")
print("Nombre del test: " + inspect.currentframe().f_code.co_name)
print("Descripcion: Usuario autenticado agrega tarea a la lista")
print("-----------")
def test_get_task_detail(self):
self.client.login(username='test_user', password='adminpass')
response = self.client.get(reverse('api-task-detail', args=[str(self.task.idTask)]))
is_passed = response.status_code == status.HTTP_200_OK
TEST_RESULTS.append({
"result": "Passed" if is_passed else "Failed",
"test_name": inspect.currentframe().f_code.co_name,
"test_description": "Usuario autenticado puede ver detalles de la tarea correctamente"
})
if is_passed:
print("Resultado: Aprobado")
else:
print("Resultado: Fallido")
print("Nombre del test: " + inspect.currentframe().f_code.co_name)
print("Descripcion: Usuario autenticado puede ver detalles de la tarea correctamente")
print("-----------")
class CSVReportTest(APITestCase):
def test_send_csv(self):
send_test_csv_report(
test_results=TEST_RESULTS,
recipients=RECIPIENTS
)
| 37.370787 | 165 | 0.634245 | 783 | 6,652 | 5.203065 | 0.177522 | 0.03731 | 0.029455 | 0.070692 | 0.794551 | 0.77246 | 0.751841 | 0.728031 | 0.707904 | 0.672067 | 0 | 0.004797 | 0.247895 | 6,652 | 177 | 166 | 37.581921 | 0.809514 | 0.065394 | 0 | 0.556452 | 0 | 0 | 0.272831 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.072581 | false | 0.193548 | 0.064516 | 0 | 0.153226 | 0.241935 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 |
0
| 6 |
8a45f1c6e8e51b93e9ab54060af5d33d536b2abf
| 75 |
py
|
Python
|
logger/__init__.py
|
remmyzen/nqs-tensorflow2
|
2af5d5ebb108eac4d2daa5082bdef11c8107bd1b
|
[
"MIT"
] | 4 |
2021-07-29T17:52:54.000Z
|
2022-02-15T06:32:15.000Z
|
logger/__init__.py
|
remmyzen/nqs-tensorflow2
|
2af5d5ebb108eac4d2daa5082bdef11c8107bd1b
|
[
"MIT"
] | null | null | null |
logger/__init__.py
|
remmyzen/nqs-tensorflow2
|
2af5d5ebb108eac4d2daa5082bdef11c8107bd1b
|
[
"MIT"
] | null | null | null |
from .logger import Logger
from .logger_supervised import LoggerSupervised
| 25 | 47 | 0.866667 | 9 | 75 | 7.111111 | 0.555556 | 0.3125 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.106667 | 75 | 2 | 48 | 37.5 | 0.955224 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 |
0
| 6 |
8a50b1905c10bef14015d0bd1e4794d8d3018140
| 38,121 |
py
|
Python
|
circuitry/circuitry.py
|
nthparty/circuitry
|
e8bc8bde93cf5056368a14a21086f18f1bcd934f
|
[
"MIT"
] | 3 |
2020-06-23T19:11:53.000Z
|
2021-01-06T16:42:56.000Z
|
circuitry/circuitry.py
|
nthparty/circuitry
|
e8bc8bde93cf5056368a14a21086f18f1bcd934f
|
[
"MIT"
] | 4 |
2020-07-28T03:14:59.000Z
|
2020-07-28T17:44:25.000Z
|
circuitry/circuitry.py
|
nthparty/circuitry
|
e8bc8bde93cf5056368a14a21086f18f1bcd934f
|
[
"MIT"
] | 1 |
2020-06-23T19:07:59.000Z
|
2020-06-23T19:07:59.000Z
|
"""Embedded DSL for assembling logic circuits.
Embedded domain-specific combinator library for
assembling abstract definitions of logic circuits
and synthesizing circuits from those definitions.
"""
from __future__ import annotations
from typing import Sequence
import doctest
from parts import parts
from circuit import op, gate, circuit, signature
class bit():
"""
Class for representing an abstract bit. Such a bit
can be interpreted concretely as a value, but it is
also used to keep track of relationships between
operators and to represent the wires within a
circuit built up out of those operators.
>>> bit.hook_operation(lambda o, v, *args: None)
>>> bit.circuit(circuit())
>>> b = output(input(1).and_(input(1)))
>>> b.value == bit.circuit().evaluate([1,1])[0]
True
>>> def make_hook(bit_):
... def hook(o, v, *args):
... return bit_.constructor(*args)(v, bit_.gate(o, [a.gate for a in args]))
... return hook
>>> bit.hook_operation(make_hook(bit))
>>> bit.circuit(circuit())
>>> b = output(input(0).and_(input(0)))
>>> b.value == bit.circuit().evaluate([0,0])[0]
True
"""
_circuit = None
_hook_operation = None
@staticmethod
def circuit(circuit_=None):
if circuit_ is not None:
bit._circuit = circuit_
return None
else:
bit._circuit.prune_and_topological_sort_stable()
return bit._circuit
@staticmethod
def hook_operation(hook=None):
bit._hook_operation = hook
@staticmethod
def operation(o, *args):
# Ensure second argument is a `bit`.
args = list(args)
if len(args) == 2:
args[1] = constant(args[1]) if isinstance(args[1], int) else args[1]
# Compute the value of the result of the operation on the arguments.
v = o(*[a.value for a in args])
# Return output from hook if it exists and if
# it returns an output.
if bit._hook_operation is not None:
r = bit._hook_operation(o, v, *args)
if r is not None:
return r
return bit.constructor(*args)(v, bit.gate(o, [a.gate for a in args]))
@staticmethod
def constructor(b1, b2=None):
# The inference code below is not currently in use.
"""
if isinstance(b1, input_one) and isinstance(b2, input_one):
return input_one
elif isinstance(b1, input_two) and isinstance(b2, input_two):
return input_two
elif isinstance(b1, (input_one, input_two)) and b2 is None:
return type(b1)
else:
return bit
"""
return bit
@staticmethod
def gate(operation, igs):
return bit._circuit.gate(operation, igs)
def __init__(self, value, gate_=None):
self.value = value
self.gate = bit._circuit.gate() if gate_ is None else gate_
def __int__(self):
return self.value
def not_(self):
"""
>>> results = []
>>> for x in [0, 1]:
... bit.circuit(circuit())
... b = output(input(x).not_())
... results.append(int(b) == bit.circuit().evaluate([x])[0])
>>> all(results)
True
"""
return bit.operation(op.not_, self)
def __invert__(self):
"""
>>> results = []
>>> for x in [0, 1]:
... bit.circuit(circuit())
... b = output(~input(x))
... results.append(int(b) == bit.circuit().evaluate([x])[0])
>>> all(results)
True
"""
return bit.operation(op.not_, self)
def __rsub__(self, other):
"""
>>> results = []
>>> for x in [0, 1]:
... bit.circuit(circuit())
... b = output(1 - input(x))
... results.append(int(b) == bit.circuit().evaluate([x])[0])
>>> all(results)
True
>>> bit.circuit(circuit())
>>> 2 - input(0)
Traceback (most recent call last):
...
ValueError: can only subtract a bit from the integer 1
"""
if other == 1:
return bit.operation(op.not_, self)
raise ValueError('can only subtract a bit from the integer 1')
def and_(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x).and_(input(y)))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.and_, self, other)
def __and__(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x) & input(y))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.and_, self, other)
def __rand__(self, other):
"""
>>> bit.circuit(circuit())
>>> b = 0 & constant(1)
>>> b.value
0
"""
return self & (constant(other) if isinstance(other, int) else other)
def nimp(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x).nimp(input(y)))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.nimp_, self, other)
def nimp_(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x).nimp_(input(y)))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.nimp_, self, other)
def __gt__(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x) > input(y))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return self.nimp(other)
def nif(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x).nif(input(y)))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.nif_, self, other)
def nif_(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x).nif_(input(y)))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.nif_, self, other)
def __lt__(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x) < input(y))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return self.nif(other)
def xor(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x).xor(input(y)))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.xor_, self, other)
def xor_(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x).xor_(input(y)))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.xor_, self, other)
def __xor__(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x) ^ input(y))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.xor_, self, other)
def __rxor__(self, other):
"""
>>> bit.circuit(circuit())
>>> b = 1 ^ constant(0)
>>> b.value
1
"""
return self ^ (constant(other) if isinstance(other, int) else other)
def or_(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x).or_(input(y)))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.or_, self, other)
def __or__(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x) | input(y))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.or_, self, other)
def __ror__(self, other):
"""
>>> bit.circuit(circuit())
>>> b = 1 | constant(0)
>>> b.value
1
"""
return self | (constant(other) if isinstance(other, int) else other)
def nor(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x).nor(input(y)))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.nor_, self, other)
def nor_(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x).nor_(input(y)))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.nor_, self, other)
def __mod__(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x) % input(y))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.nor_, self, other)
def xnor(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x).xnor(input(y)))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.xnor_, self, other)
def xnor_(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x).xnor_(input(y)))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.xnor_, self, other)
def __eq__(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x) == input(y))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.xnor_, self, other)
def if_(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x).if_(input(y)))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.if_, self, other)
def __ge__(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x) >= input(y))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.if_, self, other)
def imp(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x).imp(input(y)))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.imp_, self, other)
def imp_(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x).imp_(input(y)))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.imp_, self, other)
def __le__(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x) <= input(y))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.imp_, self, other)
def nand(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x).nand(input(y)))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.nand_, self, other)
def nand_(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x).nand_(input(y)))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.nand_, self, other)
def __matmul__(self, other):
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... b = output(input(x) @ input(y))
... results.append(int(b) == bit.circuit().evaluate([x,y])[0])
>>> all(results)
True
"""
return bit.operation(op.nand_, self, other)
class constant(bit):
"""Bit that is designated as a constant input."""
class input(bit):
"""Bit that is designated as a variable input."""
def __init__(self: bit, value: int):
self.value = value
self.gate = bit._circuit.gate(op.id_, is_input=True)
class input_one(input):
"""Bit that is designated as a variable input from one source."""
class input_two(input):
"""Bit that is designated as a variable input from a second source."""
class output(bit):
"""
Bit that is designated an output.
>>> bit.circuit(circuit())
>>> b0 = output(input(1).not_())
>>> b1 = output(b0.not_())
>>> b2 = output(b0)
>>> [b0.value, b1.value, b2.value]
[0, 1, 0]
"""
def __init__(self: bit, b: bit):
# Check if bit is ready as final output or whether there are others dependent on it.
if len(b.gate.outputs) > 0:
b = ~(~b) # Preserve the bit by copying it to a new wire.
self.value = b.value
self.gate = bit._circuit.gate(op.id_, [b.gate], is_output=True)
class bits_type(int): # pylint: disable=R0903
"""
Class for representing an input or output type of a
function decorated for automated synthesis.
"""
class bits(list):
"""
Class for representing a vector of abstract bits.
"""
@staticmethod
def from_byte(byte_: int, constructor=bit) -> bits:
return bits([
constructor(bit_)
for bit_ in reversed([(byte_>>i)%2 for i in range(8)])
])
@staticmethod
def from_bytes(bytes_, constructor=bit) -> bits:
"""
>>> bit.circuit(circuit())
>>> [b.value for b in bits.from_bytes(bytes([255]))]
[1, 1, 1, 1, 1, 1, 1, 1]
>>> bit.circuit(circuit())
>>> [b.value for b in bits.from_bytes(bytes([11, 0]))]
[0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]
"""
return bits([
bit_
for byte_ in bytes_
for bit_ in bits.from_byte(byte_, constructor)
])
@staticmethod
def zeros(n: int) -> bits:
"""
>>> bit.circuit(circuit())
>>> xs = bits.zeros(3)
>>> ys = outputs(xs.not_())
>>> [y.value for y in ys]
[1, 1, 1]
"""
return bits([constant(0)]*n)
def __new__(cls, argument = None) -> bits:
"""
Return bits object given the supplied argument.
"""
return bits_type(argument)\
if isinstance(argument, int) else\
list.__new__(cls, argument)
def __int__(self: bits) -> int:
"""
>>> bit.circuit(circuit())
>>> xs = constants([0, 0, 0])
>>> ys = outputs(xs.not_())
>>> int(ys)
7
"""
return sum(int(b)*(2**i) for (i, b) in zip(range(len(self)), reversed(self)))
def not_(self: bits) -> bits:
"""
>>> results = []
>>> for x in [0, 1]:
... bit.circuit(circuit())
... xs = inputs([x, x, x])
... ys = outputs(xs.not_())
... ns = [int(y) for y in ys]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x]))
>>> all(results)
True
"""
return bits([x.not_() for x in self])
def __invert__(self: bits) -> bits:
"""
>>> results = []
>>> for x in [0, 1]:
... bit.circuit(circuit())
... xs = inputs([x, x, x])
... ys = outputs(~xs)
... ns = [int(y) for y in ys]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x]))
>>> all(results)
True
"""
return bits([x.not_() for x in self])
def and_(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs.and_(ys))
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.and_(y) for (x, y) in zip(self, other)])
def __and__(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs & ys)
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.and_(y) for (x, y) in zip(self, other)])
def nimp(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs.nimp(ys))
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.nimp_(y) for (x, y) in zip(self, other)])
def nimp_(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs.nimp_(ys))
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.nimp_(y) for (x, y) in zip(self, other)])
def __gt__(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs > ys)
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.nimp_(y) for (x, y) in zip(self, other)])
def nif(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs.nif(ys))
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.nif_(y) for (x, y) in zip(self, other)])
def nif_(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs.nif_(ys))
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.nif_(y) for (x, y) in zip(self, other)])
def __lt__(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs < ys)
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.nif_(y) for (x, y) in zip(self, other)])
def xor(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs.xor(ys))
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.xor_(y) for (x, y) in zip(self, other)])
def xor_(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs.xor_(ys))
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.xor_(y) for (x, y) in zip(self, other)])
def __xor__(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs ^ ys)
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.xor_(y) for (x, y) in zip(self, other)])
def or_(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs.or_(ys))
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.or_(y) for (x, y) in zip(self, other)])
def __or__(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs | ys)
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.or_(y) for (x, y) in zip(self, other)])
def nor(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs.nor(ys))
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.nor_(y) for (x, y) in zip(self, other)])
def nor_(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs.nor_(ys))
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.nor_(y) for (x, y) in zip(self, other)])
def __mod__(self, other) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs % ys)
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.nor_(y) for (x, y) in zip(self, other)])
def xnor(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs.xnor(ys))
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.xnor_(y) for (x, y) in zip(self, other)])
def xnor_(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs.xnor_(ys))
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.xnor_(y) for (x, y) in zip(self, other)])
def __eq__(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs == ys)
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.xnor_(y) for (x, y) in zip(self, other)])
def if_(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs.if_(ys))
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.if_(y) for (x, y) in zip(self, other)])
def __ge__(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs >= ys)
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.if_(y) for (x, y) in zip(self, other)])
def imp(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs.imp(ys))
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.imp_(y) for (x, y) in zip(self, other)])
def imp_(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs.imp_(ys))
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.imp_(y) for (x, y) in zip(self, other)])
def __le__(self: bits, other: bits) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs <= ys)
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.imp_(y) for (x, y) in zip(self, other)])
def nand(self: bits, other) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs.nand(ys))
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.nand_(y) for (x, y) in zip(self, other)])
def nand_(self: bits, other) -> bits:
"""
>>> results = []
>>> for (x, y) in [(0, 0), (0, 1), (1, 0), (1, 1)]:
... bit.circuit(circuit())
... (xs, ys) = (inputs([x, x, x]), inputs([y, y, y]))
... zs = outputs(xs.nand_(ys))
... ns = [int(z) for z in zs]
... c = bit.circuit()
... results.append(ns == c.evaluate([x, x, x, y, y, y]))
>>> all(results)
True
"""
return bits([x.nand_(y) for (x, y) in zip(self, other)])
def __rshift__(self: bits, other) -> bits:
"""
Overloaded operator: rotation and shift operations.
>>> bit.circuit(circuit())
>>> bs = bits(map(bit, [1,1,1,1,0,0,0,0]))
>>> bs = bs >> 3
>>> [b.value for b in bs]
[0, 0, 0, 1, 1, 1, 1, 0]
>>> bit.circuit(circuit())
>>> bs = bits(map(bit, [0,0,0,0,1,1,1,1]))
>>> bs = bs >> {3}
>>> [b.value for b in bs]
[1, 1, 1, 0, 0, 0, 0, 1]
"""
if isinstance(other, set) and isinstance(list(other)[0], int): # Rotation.
quantity = list(other)[0]
return bits(self[len(self)-quantity:]) ** bits(self[0:len(self)-quantity])
else: # Shift
return bits([constant(0)]*other) ** bits(self[0:len(self)-other])
def __lshift__(self: bits, other) -> bits:
"""
>>> bit.circuit(circuit())
>>> bs = bits(map(bit, [1,1,1,1,0,0,0,0]))
>>> bs = bs << 3
>>> [b.value for b in bs]
[1, 0, 0, 0, 0, 0, 0, 0]
"""
return bits(self[other:]) ** bits([constant(0) for _ in range(other)])
def __truediv__(self: bits, other) -> Sequence[bits]:
"""
>>> bit.circuit(circuit())
>>> bs = bits(map(bit, [1,1,1,1,0,0,0,0]))
>>> bss = list(bs / 2)
>>> ([b.value for b in bss[0]], [b.value for b in bss[1]])
([1, 1, 1, 1], [0, 0, 0, 0])
>>> bit.circuit(circuit())
>>> bs = bits(map(bit, [1,1,1,1,0,0,0,0]))
>>> bss = list(bs / {2})
>>> [[b.value for b in bs] for bs in bss]
[[1, 1], [1, 1], [0, 0], [0, 0]]
>>> bit.circuit(circuit())
>>> bs = bits(map(bit, [1,1,1,1,0,0,0,0]))
>>> bss = list(bs / [1, 3, 4])
>>> [[b.value for b in bs] for bs in bss]
[[1], [1, 1, 1], [0, 0, 0, 0]]
"""
if isinstance(other, list) and len(other) > 0 and isinstance(other[0], int):
return map(bits, parts(self, length=other)) # Sequence of lengths.
elif isinstance(other, set) and len(other) == 1 and isinstance(list(other)[0], int):
return self / (len(self)//list(other)[0]) # Parts of length `other`.
else:
return map(bits, parts(self, other)) # Number of parts is `other`.
def __add__(self: bits, other) -> bits:
"""Concatenation of bit vectors."""
result = list(self)
result.extend(list(other))
return bits(result)
def __pow__(self: bits, other) -> bits:
"""Concatenation of bit vectors."""
return self + other
def constants(l):
return bits(map(constant, l))
def inputs(l):
return bits(map(input, l))
def outputs(l):
return bits(map(output, l))
def synthesize(f):
"""
Decorator for automatically synthesizing a circuit from a
function that takes only `bit` and/or `bits` objects as its
arguments and returns an output of type `bit` or `bits`.
>>> @synthesize
... def equal(x: bit, y: bit) -> bit:
... return (x & y) | ((1 - x) & (1 - y))
>>> xys = [bits([x, y]) for x in (0, 1) for y in (0, 1)]
>>> [equal.circuit.evaluate(xy) for xy in xys]
[[1], [0], [0], [1]]
>>> @synthesize
... def conjunction(xy: bits(2)) -> bits(2):
... return (xy[0], xy[0] & xy[1])
>>> xys = [bits([x, y]) for x in (0, 1) for y in (0, 1)]
>>> [conjunction.circuit.evaluate(xy) for xy in xys]
[[0, 0], [0, 0], [1, 0], [1, 1]]
>>> @synthesize
... def equal(x, y):
... return x & y
Traceback (most recent call last):
...
RuntimeError: automated circuit synthesis failed
"""
# Functions for determining types/signature from
# the type annotation of the decorated function.
type_in = lambda a: input(0) if a is bit else inputs([0] * a)
type_out = lambda a: output if a is bit else outputs
# For forward-compatibility with PEP 563.
eval_ = lambda a: eval(a) if isinstance(a, str) else a # pylint: disable=W0123
try:
# Construct the circuit and add it to the function as an attribute.
bit.circuit(circuit())
args_in = {
k: type_in(eval_(a))
for (k, a) in f.__annotations__.items() if k != 'return'
}
type_out(eval_(f.__annotations__['return']))(f(**args_in))
f.circuit = bit.circuit()
except:
raise RuntimeError('automated circuit synthesis failed') from None
# Return the original function.
return f
if __name__ == "__main__":
doctest.testmod() # pragma: no cover
| 33.557218 | 92 | 0.440728 | 4,937 | 38,121 | 3.332388 | 0.054081 | 0.019815 | 0.020058 | 0.033613 | 0.744104 | 0.721736 | 0.710005 | 0.703319 | 0.686725 | 0.684658 | 0 | 0.028745 | 0.347499 | 38,121 | 1,135 | 93 | 33.586784 | 0.632669 | 0.554943 | 0 | 0.296748 | 0 | 0 | 0.008636 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.341463 | false | 0 | 0.020325 | 0.02439 | 0.747967 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 |
0
| 6 |
8a54efc9a7ad3665cabc7b4468043314dcb3122b
| 3,743 |
py
|
Python
|
test/test_downloadfile.py
|
foliant-docs/foliantcontrib.downloadfile
|
1af9481f9bc9142d8b1ac1eff93fa0c5577ccaec
|
[
"MIT"
] | null | null | null |
test/test_downloadfile.py
|
foliant-docs/foliantcontrib.downloadfile
|
1af9481f9bc9142d8b1ac1eff93fa0c5577ccaec
|
[
"MIT"
] | null | null | null |
test/test_downloadfile.py
|
foliant-docs/foliantcontrib.downloadfile
|
1af9481f9bc9142d8b1ac1eff93fa0c5577ccaec
|
[
"MIT"
] | null | null | null |
import shutil
from pathlib import Path
from unittest import TestCase
from unittest.mock import Mock
from unittest.mock import patch
from foliant.config.downloadfile import download_file
from foliant.config.downloadfile import get_file_ext_from_url
from foliant.config.downloadfile import get_file_name_from_url
class TestDownloadFile(TestCase):
def setUp(self):
self.project_dir = (Path(__file__).parent / 'project_dir').resolve()
self.project_dir.mkdir(exist_ok=True)
def tearDown(self):
shutil.rmtree(self.project_dir, ignore_errors=True)
@patch('foliant.config.downloadfile.urlopen', autospec=True)
def test_only_url(self, urlopen):
mock_response = Mock()
mock_response.read.return_value = b'File content'
urlopen.return_value = mock_response
url = 'http://example.com/myfile.txt'
download_file(root_dir=self.project_dir, url=url)
request = urlopen.call_args.args[0]
context = urlopen.call_args.kwargs['context']
self.assertEqual(request.headers, {})
self.assertIsNone(context)
with open(self.project_dir / 'myfile.txt') as f:
self.assertEqual(f.read(), 'File content')
@patch('foliant.config.downloadfile.urlopen', autospec=True)
def test_save_to(self, urlopen):
mock_response = Mock()
mock_response.read.return_value = b'File content'
urlopen.return_value = mock_response
url = 'http://example.com/myfile.txt'
save_to = 'subdir1/subdir2/downloaded.txt'
download_file(root_dir=self.project_dir, url=url, save_to=save_to)
request = urlopen.call_args.args[0]
context = urlopen.call_args.kwargs['context']
self.assertEqual(request.headers, {})
self.assertIsNone(context)
with open(self.project_dir / save_to) as f:
self.assertEqual(f.read(), 'File content')
@patch('foliant.config.downloadfile.urlopen', autospec=True)
def test_with_auth(self, urlopen):
mock_response = Mock()
mock_response.read.return_value = b'File content'
urlopen.return_value = mock_response
url = 'http://example.com/myfile.txt'
download_file(
root_dir=self.project_dir,
url=url,
login='john',
password='qwerty1234'
)
request = urlopen.call_args.args[0]
context = urlopen.call_args.kwargs['context']
self.assertIn('Authorization', request.headers)
self.assertIsNone(context)
with open(self.project_dir / 'myfile.txt') as f:
self.assertEqual(f.read(), 'File content')
class TestGetFileNameFromURL(TestCase):
def test_with_ext(self):
url = 'http://example.com/sub/myfile.txt'
name = get_file_name_from_url(url)
self.assertEqual(name, 'myfile.txt')
def test_no_ext(self):
url = 'http://example.com/sub/myfile'
name = get_file_name_from_url(url)
self.assertEqual(name, 'myfile')
def test_with_clutter(self):
url = 'http://example.com/sub/myfile.txt?param=val&foo=bar'
name = get_file_name_from_url(url)
self.assertEqual(name, 'myfile.txt')
class TestGetFileExtFromURL(TestCase):
def test_with_ext(self):
url = 'http://example.com/sub/myfile.txt'
ext = get_file_ext_from_url(url)
self.assertEqual(ext, '.txt')
def test_no_ext(self):
url = 'http://example.com/sub/myfile'
ext = get_file_ext_from_url(url)
self.assertEqual(ext, '')
def test_with_clutter(self):
url = 'http://example.com/sub/myfile.txt?param=val&foo=bar'
ext = get_file_ext_from_url(url)
self.assertEqual(ext, '.txt')
| 32.833333 | 76 | 0.663906 | 480 | 3,743 | 4.972917 | 0.177083 | 0.041475 | 0.052786 | 0.064097 | 0.804357 | 0.780897 | 0.780897 | 0.745706 | 0.745706 | 0.722246 | 0 | 0.003081 | 0.21961 | 3,743 | 113 | 77 | 33.123894 | 0.814105 | 0 | 0 | 0.623529 | 0 | 0 | 0.169116 | 0.036067 | 0 | 0 | 0 | 0 | 0.176471 | 1 | 0.129412 | false | 0.011765 | 0.094118 | 0 | 0.258824 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
0
| 6 |
8a7777964dadf66bcb5c8207f5f26c1301e49cee
| 3,977 |
py
|
Python
|
libsaas/services/twilio/applications.py
|
MidtownFellowship/libsaas
|
541bb731b996b08ede1d91a235cb82895765c38a
|
[
"MIT"
] | 155 |
2015-01-27T15:17:59.000Z
|
2022-02-20T00:14:08.000Z
|
libsaas/services/twilio/applications.py
|
MidtownFellowship/libsaas
|
541bb731b996b08ede1d91a235cb82895765c38a
|
[
"MIT"
] | 14 |
2015-01-12T08:22:37.000Z
|
2021-06-16T19:49:31.000Z
|
libsaas/services/twilio/applications.py
|
MidtownFellowship/libsaas
|
541bb731b996b08ede1d91a235cb82895765c38a
|
[
"MIT"
] | 43 |
2015-01-28T22:41:45.000Z
|
2021-09-21T04:44:26.000Z
|
from libsaas import http, parsers
from libsaas.services import base
from libsaas.services.twilio import resource
class ApplicationsBase(resource.TwilioResource):
path = 'Applications'
class Application(ApplicationsBase):
def create(self, *args, **kwargs):
raise base.MethodNotSupported()
class Applications(ApplicationsBase):
@base.apimethod
def get(self, FriendlyName=None, Page=None, PageSize=None, AfterSid=None):
"""
Fetch the Applications belonging to an account.
:var FriendlyName: Only return the Account resources with friendly
names that exactly match this name.
:vartype FriendlyName: str
:var Page: The current page number. Zero-indexed, so the first page
is 0.
:vartype Page: int
:var PageSize: How many resources to return in each list page.
The default is 50, and the maximum is 1000.
:vartype PageSize: int
:var AfterSid: The last Sid returned in the previous page, used to
avoid listing duplicated resources if new ones are created while
paging.
:vartype AfterSid: str
"""
params = resource.get_params(None, locals())
request = http.Request('GET', self.get_url(), params)
return request, parsers.parse_json
def update(self, *args, **kwargs):
raise base.MethodNotSupported()
def delete(self, *args, **kwargs):
raise base.MethodNotSupported()
class ConnectAppsBase(resource.TwilioResource):
path = 'ConnectApps'
def create(self, *args, **kwargs):
raise base.MethodNotSupported()
def delete(self, *args, **kwargs):
raise base.MethodNotSupported()
class ConnectApp(ConnectAppsBase):
pass
class ConnectApps(ConnectAppsBase):
@base.apimethod
def get(self, Page=None, PageSize=None, AfterSid=None):
"""
Fetch the Connect Apps belonging to an account.
:var Page: The current page number. Zero-indexed, so the first page
is 0.
:vartype Page: int
:var PageSize: How many resources to return in each list page.
The default is 50, and the maximum is 1000.
:vartype PageSize: int
:var AfterSid: The last Sid returned in the previous page, used to
avoid listing duplicated resources if new ones are created while
paging.
:vartype AfterSid: str
"""
params = resource.get_params(None, locals())
request = http.Request('GET', self.get_url(), params)
return request, parsers.parse_json
def update(self, *args, **kwargs):
raise base.MethodNotSupported()
class AuthorizedConnectAppsBase(resource.TwilioResource):
path = 'AuthorizedConnectApps'
def create(self, *args, **kwargs):
raise base.MethodNotSupported()
def update(self, *args, **kwargs):
raise base.MethodNotSupported()
def delete(self, *args, **kwargs):
raise base.MethodNotSupported()
class AuthorizedConnectApp(AuthorizedConnectAppsBase):
pass
class AuthorizedConnectApps(AuthorizedConnectAppsBase):
@base.apimethod
def get(self, Page=None, PageSize=None, AfterSid=None):
"""
Fetch the Authorized Connect Apps belonging to an account.
:var Page: The current page number. Zero-indexed, so the first page
is 0.
:vartype Page: int
:var PageSize: How many resources to return in each list page.
The default is 50, and the maximum is 1000.
:vartype PageSize: int
:var AfterSid: The last Sid returned in the previous page, used to
avoid listing duplicated resources if new ones are created while
paging.
:vartype AfterSid: str
"""
params = resource.get_params(None, locals())
request = http.Request('GET', self.get_url(), params)
return request, parsers.parse_json
| 28.007042 | 78 | 0.652753 | 458 | 3,977 | 5.648472 | 0.220524 | 0.027831 | 0.048705 | 0.0661 | 0.752223 | 0.734441 | 0.734441 | 0.730576 | 0.695787 | 0.67298 | 0 | 0.007187 | 0.265275 | 3,977 | 141 | 79 | 28.205674 | 0.878166 | 0.378175 | 0 | 0.68 | 0 | 0 | 0.024778 | 0.009818 | 0 | 0 | 0 | 0 | 0 | 1 | 0.24 | false | 0.04 | 0.06 | 0 | 0.6 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 |
0
| 6 |
8a8c957af09c1662e1613d8819301ef9871bcd5c
| 5,914 |
py
|
Python
|
tensorflow/python/ops/standard_ops.py
|
ashutom/tensorflow-upstream
|
c16069c19de9e286dd664abb78d0ea421e9f32d4
|
[
"Apache-2.0"
] | 8 |
2021-08-03T03:57:10.000Z
|
2021-12-13T01:19:02.000Z
|
tensorflow/python/ops/standard_ops.py
|
CaptainGizzy21/tensorflow
|
3457a2b122e50b4d44ceaaed5a663d635e5c22df
|
[
"Apache-2.0"
] | 17 |
2021-08-12T19:38:42.000Z
|
2022-01-27T14:39:35.000Z
|
tensorflow/python/ops/standard_ops.py
|
CaptainGizzy21/tensorflow
|
3457a2b122e50b4d44ceaaed5a663d635e5c22df
|
[
"Apache-2.0"
] | 4 |
2022-01-13T11:23:44.000Z
|
2022-03-02T11:11:42.000Z
|
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
# pylint: disable=unused-import
"""Import names of Tensor Flow standard Ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import platform as _platform
import sys as _sys
from tensorflow.python import autograph
from tensorflow.python.training.experimental import loss_scaling_gradient_tape
# pylint: disable=g-bad-import-order
# Imports the following modules so that @RegisterGradient get executed.
from tensorflow.python.ops import array_grad
from tensorflow.python.ops import cudnn_rnn_grad
from tensorflow.python.ops import data_flow_grad
from tensorflow.python.ops import manip_grad
from tensorflow.python.ops import math_grad
from tensorflow.python.ops import random_grad
from tensorflow.python.ops import rnn_grad
from tensorflow.python.ops import sparse_grad
from tensorflow.python.ops import state_grad
from tensorflow.python.ops import tensor_array_grad
# go/tf-wildcard-import
# pylint: disable=wildcard-import
from tensorflow.python.ops.array_ops import * # pylint: disable=redefined-builtin
from tensorflow.python.ops.check_ops import *
from tensorflow.python.ops.clip_ops import *
from tensorflow.python.ops.special_math_ops import *
# TODO(vrv): Switch to import * once we're okay with exposing the module.
from tensorflow.python.ops.confusion_matrix import confusion_matrix
from tensorflow.python.ops.control_flow_ops import Assert
from tensorflow.python.ops.control_flow_ops import case
from tensorflow.python.ops.control_flow_ops import cond
from tensorflow.python.ops.control_flow_ops import group
from tensorflow.python.ops.control_flow_ops import no_op
from tensorflow.python.ops.control_flow_ops import tuple # pylint: disable=redefined-builtin
# pylint: enable=redefined-builtin
from tensorflow.python.eager import wrap_function
from tensorflow.python.ops.control_flow_ops import while_loop
from tensorflow.python.ops.batch_ops import *
from tensorflow.python.ops.critical_section_ops import *
from tensorflow.python.ops.data_flow_ops import *
from tensorflow.python.ops.functional_ops import *
from tensorflow.python.ops.gradients import *
from tensorflow.python.ops.histogram_ops import *
from tensorflow.python.ops.init_ops import *
from tensorflow.python.ops.io_ops import *
from tensorflow.python.ops.linalg_ops import *
from tensorflow.python.ops.logging_ops import Print
from tensorflow.python.ops.logging_ops import get_summary_op
from tensorflow.python.ops.logging_ops import timestamp
from tensorflow.python.ops.lookup_ops import initialize_all_tables
from tensorflow.python.ops.lookup_ops import tables_initializer
from tensorflow.python.ops.manip_ops import *
from tensorflow.python.ops.math_ops import * # pylint: disable=redefined-builtin
from tensorflow.python.ops.numerics import *
from tensorflow.python.ops.parsing_ops import *
from tensorflow.python.ops.partitioned_variables import *
from tensorflow.python.ops.proto_ops import *
from tensorflow.python.ops.ragged import ragged_dispatch as _ragged_dispatch
from tensorflow.python.ops.ragged import ragged_operators as _ragged_operators
from tensorflow.python.ops.random_ops import *
from tensorflow.python.ops.script_ops import py_func
from tensorflow.python.ops.session_ops import *
from tensorflow.python.ops.sort_ops import *
from tensorflow.python.ops.sparse_ops import *
from tensorflow.python.ops.state_ops import assign
from tensorflow.python.ops.state_ops import assign_add
from tensorflow.python.ops.state_ops import assign_sub
from tensorflow.python.ops.state_ops import count_up_to
from tensorflow.python.ops.state_ops import scatter_add
from tensorflow.python.ops.state_ops import scatter_div
from tensorflow.python.ops.state_ops import scatter_mul
from tensorflow.python.ops.state_ops import scatter_sub
from tensorflow.python.ops.state_ops import scatter_min
from tensorflow.python.ops.state_ops import scatter_max
from tensorflow.python.ops.state_ops import scatter_update
from tensorflow.python.ops.state_ops import scatter_nd_add
from tensorflow.python.ops.state_ops import scatter_nd_sub
# TODO(simister): Re-enable once binary size increase due to scatter_nd
# ops is under control.
# from tensorflow.python.ops.state_ops import scatter_nd_mul
# from tensorflow.python.ops.state_ops import scatter_nd_div
from tensorflow.python.ops.state_ops import scatter_nd_update
from tensorflow.python.ops.stateless_random_ops import *
from tensorflow.python.ops.string_ops import *
from tensorflow.python.ops.template import *
from tensorflow.python.ops.tensor_array_ops import *
from tensorflow.python.ops.variable_scope import * # pylint: disable=redefined-builtin
from tensorflow.python.ops.variables import *
from tensorflow.python.ops.parallel_for.control_flow_ops import vectorized_map
# pylint: disable=g-import-not-at-top
if _platform.system() == "Windows":
from tensorflow.python.compiler.tensorrt import trt_convert_windows as trt
else:
from tensorflow.python.compiler.tensorrt import trt_convert as trt
# pylint: enable=g-import-not-at-top
# pylint: enable=wildcard-import
# pylint: enable=g-bad-import-order
# These modules were imported to set up RaggedTensor operators and dispatchers:
del _ragged_dispatch, _ragged_operators
| 46.936508 | 93 | 0.825668 | 875 | 5,914 | 5.410286 | 0.244571 | 0.227714 | 0.325306 | 0.34981 | 0.5921 | 0.53929 | 0.367343 | 0.277989 | 0.118293 | 0.025771 | 0 | 0.001496 | 0.095536 | 5,914 | 125 | 94 | 47.312 | 0.88353 | 0.263274 | 0 | 0 | 0 | 0 | 0.001621 | 0 | 0 | 0 | 0 | 0.008 | 0.012048 | 1 | 0 | true | 0 | 0.963855 | 0 | 0.963855 | 0.012048 | 0 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 |
0
| 6 |
0a06508cf532e568943c2d6f9f6d327c4504fc73
| 56 |
py
|
Python
|
starry/_core/ops/lib/include/oblate/tests/test_derivs.py
|
rodluger/starry
|
da7fee48c5ef94278f0047be0579e2f13492cdd5
|
[
"MIT"
] | 116 |
2018-02-23T19:47:15.000Z
|
2022-02-21T04:43:46.000Z
|
starry/_core/ops/lib/include/oblate/tests/test_derivs.py
|
rodluger/starry
|
da7fee48c5ef94278f0047be0579e2f13492cdd5
|
[
"MIT"
] | 224 |
2018-02-26T00:41:51.000Z
|
2022-03-29T10:38:16.000Z
|
starry/_core/ops/lib/include/oblate/tests/test_derivs.py
|
rodluger/starry
|
da7fee48c5ef94278f0047be0579e2f13492cdd5
|
[
"MIT"
] | 25 |
2018-02-26T18:14:36.000Z
|
2021-11-30T01:00:56.000Z
|
import oblate
import numpy as np
import pytest
# TODO!
| 9.333333 | 18 | 0.767857 | 9 | 56 | 4.777778 | 0.777778 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.196429 | 56 | 5 | 19 | 11.2 | 0.955556 | 0.089286 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 |
0
| 6 |
0a33cb634cfe076d601a3145a01487981499f068
| 22,712 |
py
|
Python
|
Scripts/calc_Utilities.py
|
zmlabe/ThicknessSensitivity
|
6defdd897a61d7d1a02f34a9f4ec92b2b17b3075
|
[
"MIT"
] | 1 |
2017-10-22T02:22:14.000Z
|
2017-10-22T02:22:14.000Z
|
Scripts/calc_Utilities.py
|
zmlabe/ThicknessSensitivity
|
6defdd897a61d7d1a02f34a9f4ec92b2b17b3075
|
[
"MIT"
] | null | null | null |
Scripts/calc_Utilities.py
|
zmlabe/ThicknessSensitivity
|
6defdd897a61d7d1a02f34a9f4ec92b2b17b3075
|
[
"MIT"
] | 4 |
2018-04-05T17:55:36.000Z
|
2022-03-31T07:05:01.000Z
|
"""
Functions are useful untilities for SITperturb experiments
Notes
-----
Author : Zachary Labe
Date : 13 August 2017
Usage
-----
[1] calcDecJan(varx,vary,lat,lon,level,levsq)
[2] calcDecJanFeb(varx,vary,lat,lon,level,levsq)
[3] calc_indttest(varx,vary)
[4] calc_weightedAve(var,lats)
[5] calc_spatialCorr(varx,vary,lats,lons,weight)
[6] calc_RMSE(varx,vary,lats,lons,weight)
[7] calc_spatialCorrHeight(varx,vary,lats,lons,weight)
[8] calc_spatialCorrHeightLev(varx,vary,lats,lons,weight,levelq)
"""
def calcDecJan(varx,vary,lat,lon,level,levsq):
"""
Function calculates average for December-January
Parameters
----------
varx : 4d array or 5d array
[year,month,lat,lon] or [year,month,lev,lat,lon]
vary : 4d array or 5d array
[year,month,lat,lon] or [year,month,lev,lat,lon]
lat : 1d numpy array
latitudes
lon : 1d numpy array
longitudes
level : string
Height of variable (surface or profile)
levsq : integer
number of levels
Returns
-------
varx_dj : 3d array or 4d array
[year,lat,lon] or [year,lev,lat,lon]
vary_dj : 3d array
[year,lat,lon] or [year,lev,lat,lon]
Usage
-----
varx_dj,vary_dj = calcDecJan(varx,vary,lat,lon,level,levsq)
"""
print('\n>>> Using calcDecJan function!')
### Import modules
import numpy as np
### Reshape for 3d variables
if level == 'surface':
varxravel = np.reshape(varx.copy(),
(int(varx.shape[0]*12),
int(lat.shape[0]),int(lon.shape[0])))
varyravel = np.reshape(vary.copy(),
(int(vary.shape[0]*12),
int(lat.shape[0]),int(lon.shape[0])))
varx_dj = np.empty((varx.shape[0]-1,lat.shape[0],lon.shape[0]))
vary_dj = np.empty((vary.shape[0]-1,lat.shape[0],lon.shape[0]) )
for i in range(0,varxravel.shape[0]-12,12):
counter = 0
if i >= 12:
counter = i//12
djappendh = np.append(varxravel[11+i,:,:],varxravel[12+i,:,:])
djappendf = np.append(varyravel[11+i,:,:],varyravel[12+i,:,:])
varx_dj[counter,:,:] = np.nanmean(np.reshape(djappendh,
(2,int(lat.shape[0]),int(lon.shape[0]))),
axis=0)
vary_dj[counter,:,:] = np.nanmean(np.reshape(djappendf,
(2,int(lat.shape[0]),int(lon.shape[0]))),
axis=0)
### Reshape for 4d variables
elif level == 'profile':
varxravel = np.reshape(varx.copy(),
(int(varx.shape[0]*12.),levsq,
int(lat.shape[0]),int(lon.shape[0])))
varyravel = np.reshape(vary.copy(),
(int(vary.shape[0]*12.),levsq,
int(lat.shape[0]),int(lon.shape[0])))
varx_dj = np.empty((int(varx.shape[0]-1),levsq,
int(lat.shape[0]),int(lon.shape[0])))
vary_dj = np.empty((int(vary.shape[0]-1),levsq,
int(lat.shape[0]),int(lon.shape[0])) )
for i in range(0,varxravel.shape[0]-12,12):
counter = 0
if i >= 12:
counter = i//12
djappendh = np.append(varxravel[11+i,:,:,:],
varxravel[12+i,:,:,:])
djappendf = np.append(varyravel[11+i,:,:,:],
varyravel[12+i,:,:,:])
varx_dj[counter,:,:] = np.nanmean(np.reshape(djappendh,
(2,levsq,int(lat.shape[0]),
int(lon.shape[0]))),axis=0)
vary_dj[counter,:,:] = np.nanmean(np.reshape(djappendf,
(2,levsq,int(lat.shape[0]),
int(lon.shape[0]))),axis=0)
else:
print(ValueError('Selected wrong height - (surface or profile!)!'))
print('Completed: Organized data by months (ON,DJ,FM)!')
print('*Completed: Finished calcDecJan function!')
return varx_dj,vary_dj
###############################################################################
###############################################################################
###############################################################################
def calcDecJanFeb(varx,vary,lat,lon,level,levsq):
"""
Function calculates average for December-January-February
Parameters
----------
varx : 4d array or 5d array
[year,month,lat,lon] or [year,month,lev,lat,lon]
vary : 4d array or 5d array
[year,month,lat,lon] or [year,month,lev,lat,lon]
lat : 1d numpy array
latitudes
lon : 1d numpy array
longitudes
level : string
Height of variable (surface or profile)
levsq : integer
number of levels
Returns
-------
varx_djf : 3d array or 4d array
[year,lat,lon] or [year,lev,lat,lon]
vary_djf : 3d array
[year,lat,lon] or [year,lev,lat,lon]
Usage
-----
varx_djf,vary_djf = calcDecJanFeb(varx,vary,lat,lon,level,levsq)
"""
print('\n>>> Using calcDecJan function!')
### Import modules
import numpy as np
### Reshape for 3d variables
if level == 'surface':
varxravel = np.reshape(varx.copy(),
(int(varx.shape[0]*12),
int(lat.shape[0]),int(lon.shape[0])))
varyravel = np.reshape(vary.copy(),
(int(vary.shape[0]*12),
int(lat.shape[0]),int(lon.shape[0])))
varx_djf = np.empty((varx.shape[0]-1,lat.shape[0],lon.shape[0]))
vary_djf = np.empty((vary.shape[0]-1,lat.shape[0],lon.shape[0]) )
for i in range(0,varxravel.shape[0]-12,12):
counter = 0
if i >= 12:
counter = i//12
djfappendh1 = np.append(varxravel[11+i,:,:],varxravel[12+i,:,:])
djfappendf1 = np.append(varyravel[11+i,:,:],varyravel[12+i,:,:])
djfappendh = np.append(djfappendh1,varxravel[13+i,:,:])
djfappendf = np.append(djfappendf1,varyravel[13+i,:,:])
varx_djf[counter,:,:] = np.nanmean(np.reshape(djfappendh,
(3,int(lat.shape[0]),int(lon.shape[0]))),
axis=0)
vary_djf[counter,:,:] = np.nanmean(np.reshape(djfappendf,
(3,int(lat.shape[0]),int(lon.shape[0]))),
axis=0)
### Reshape for 4d variables
elif level == 'profile':
varxravel = np.reshape(varx.copy(),
(int(varx.shape[0]*12.),levsq,
int(lat.shape[0]),int(lon.shape[0])))
varyravel = np.reshape(vary.copy(),
(int(vary.shape[0]*12.),levsq,
int(lat.shape[0]),int(lon.shape[0])))
varx_djf = np.empty((int(varx.shape[0]-1),levsq,
int(lat.shape[0]),int(lon.shape[0])))
vary_djf = np.empty((int(vary.shape[0]-1),levsq,
int(lat.shape[0]),int(lon.shape[0])) )
for i in range(0,varxravel.shape[0]-12,12):
counter = 0
if i >= 12:
counter = i//12
djfappendh1 = np.append(varxravel[11+i,:,:,:],
varxravel[12+i,:,:,:])
djfappendf1 = np.append(varyravel[11+i,:,:,:],
varyravel[12+i,:,:,:])
djfappendh = np.append(djfappendh1,
varxravel[13+i,:,:,:])
djfappendf = np.append(djfappendf1,
varyravel[13+i,:,:,:])
varx_djf[counter,:,:] = np.nanmean(np.reshape(djfappendh,
(3,levsq,int(lat.shape[0]),
int(lon.shape[0]))),axis=0)
vary_djf[counter,:,:] = np.nanmean(np.reshape(djfappendf,
(3,levsq,int(lat.shape[0]),
int(lon.shape[0]))),axis=0)
else:
print(ValueError('Selected wrong height - (surface or profile!)!'))
print('Completed: Organized data by months (DJF)!')
print('*Completed: Finished calcDecJanFeb function!')
return varx_djf,vary_djf
###############################################################################
###############################################################################
###############################################################################
def calc_indttest(varx,vary):
"""
Function calculates statistical difference for 2 independent
sample t-test
Parameters
----------
varx : 3d array
vary : 3d array
Returns
-------
stat = calculated t-statistic
pvalue = two-tailed p-value
Usage
-----
stat,pvalue = calc_ttest(varx,vary)
"""
print('\n>>> Using calc_ttest function!')
### Import modules
import numpy as np
import scipy.stats as sts
### 2-independent sample t-test
stat,pvalue = sts.ttest_ind(varx,vary,nan_policy='omit')
### Significant at 95% confidence level
pvalue[np.where(pvalue >= 0.05)] = np.nan
pvalue[np.where(pvalue < 0.05)] = 1.
print('*Completed: Finished calc_ttest function!')
return stat,pvalue
###############################################################################
###############################################################################
###############################################################################
def calc_weightedAve(var,lats):
"""
Area weights sit array 5d [ens,year,month,lat,lon] into [ens,year,month]
Parameters
----------
var : 5d,4d,3d array of a gridded variable
lats : 2d array of latitudes
Returns
-------
meanvar : weighted average for 3d,2d,1d array
Usage
-----
meanvar = calc_weightedAve(var,lats)
"""
print('\n>>> Using calc_weightedAve function!')
### Import modules
import numpy as np
### Calculate weighted average for various dimensional arrays
if var.ndim == 5:
meanvar = np.empty((var.shape[0],var.shape[1],var.shape[2]))
for ens in range(var.shape[0]):
for i in range(var.shape[1]):
for j in range(var.shape[2]):
varq = var[ens,i,j,:,:]
mask = np.isfinite(varq) & np.isfinite(lats)
varmask = varq[mask]
areamask = np.cos(np.deg2rad(lats[mask]))
meanvar[ens,i,j] = np.nansum(varmask*areamask) \
/np.sum(areamask)
elif var.ndim == 4:
meanvar = np.empty((var.shape[0],var.shape[1]))
for i in range(var.shape[0]):
for j in range(var.shape[1]):
varq = var[i,j,:,:]
mask = np.isfinite(varq) & np.isfinite(lats)
varmask = varq[mask]
areamask = np.cos(np.deg2rad(lats[mask]))
meanvar[i,j] = np.nansum(varmask*areamask)/np.sum(areamask)
elif var.ndim == 3:
meanvar = np.empty((var.shape[0]))
for i in range(var.shape[0]):
varq = var[i,:,:]
mask = np.isfinite(varq) & np.isfinite(lats)
varmask = varq[mask]
areamask = np.cos(np.deg2rad(lats[mask]))
meanvar[i] = np.nansum(varmask*areamask)/np.sum(areamask)
elif var.ndim == 2:
meanvar = np.empty((var.shape[0]))
varq = var[:,:]
mask = np.isfinite(varq) & np.isfinite(lats)
varmask = varq[mask]
areamask = np.cos(np.deg2rad(lats[mask]))
meanvar = np.nansum(varmask*areamask)/np.sum(areamask)
else:
print(ValueError('Variable has the wrong dimensions!'))
print('Completed: Weighted variable average!')
print('*Completed: Finished calc_weightedAve function!')
return meanvar
###############################################################################
###############################################################################
###############################################################################
def calc_spatialCorr(varx,vary,lats,lons,weight):
"""
Calculates spatial correlation from pearson correlation coefficient
Parameters
----------
varx : 2d array
vary : 2d array
lats : 1d array
lons : 1d array of latitude
weight : string (yes or no)
Returns
-------
corrcoef : 1d array of correlation coefficient (pearson r)
Usage
-----
corrcoef = calc_spatialCorr(varx,vary,lats,lons)
"""
print('\n>>> Using calc_spatialCorr function!')
### Import modules
import numpy as np
if weight == 'yes': # Computed weighted correlation coefficient
### mask
mask = 'yes'
if mask == 'yes':
latq = np.where(lats > 40)[0]
lats = lats[latq]
varx = varx[latq,:]
vary = vary[latq,:]
print('MASKING LATITUDES!')
### Create 2d meshgrid for weights
lon2,lat2 = np.meshgrid(lons,lats)
### Create 2d array of weights based on latitude
gw = np.cos(np.deg2rad(lat2))
def m(x, w):
"""Weighted Mean"""
wave = np.sum(x * w) / np.sum(w)
print('Completed: Computed weighted average!')
return wave
def cov(x, y, w):
"""Weighted Covariance"""
wcov = np.sum(w * (x - m(x, w)) * (y - m(y, w))) / np.sum(w)
print('Completed: Computed weighted covariance!')
return wcov
def corr(x, y, w):
"""Weighted Correlation"""
wcor = cov(x, y, w) / np.sqrt(cov(x, x, w) * cov(y, y, w))
print('Completed: Computed weighted correlation!')
return wcor
corrcoef = corr(varx,vary,gw)
elif weight == 'no':
### Correlation coefficient from numpy function (not weighted)
corrcoef= np.corrcoef(varx.ravel(),vary.ravel())[0][1]
print('Completed: Computed NON-weighted correlation!')
else:
ValueError('Wrong weighted arguement in function!')
print('*Completed: Finished calc_SpatialCorr function!')
return corrcoef
###############################################################################
###############################################################################
###############################################################################
def calc_RMSE(varx,vary,lats,lons,weight):
"""
Calculates root mean square weighted average
Parameters
----------
varx : 2d array
vary : 2d array
lons : 1d array of latitude
weight : string (yes or no)
Returns
-------
rmse : 1d array
Usage
-----
rmse = calc_RMSE(varx,vary,lats,lons)
"""
print('\n>>> Using calc_RMSE function!')
### Import modules
import numpy as np
from sklearn.metrics import mean_squared_error
if weight == 'yes': # Computed weighted correlation coefficient
### mask
mask = 'yes'
if mask == 'yes':
latq = np.where(lats > 40)[0]
lats = lats[latq]
varx = varx[latq,:]
vary = vary[latq,:]
print('MASKING LATITUDES!')
### Create 2d meshgrid for weights
lon2,lat2 = np.meshgrid(lons,lats)
### Create 2d array of weights based on latitude
gw = np.cos(np.deg2rad(lat2))
### Calculate rmse
sq_err = (varx - vary)**2
rmse = np.sqrt((np.sum(sq_err*gw))/np.sum(gw))
elif weight == 'no':
### Root mean square error from sklearn (not weighted)
rmse = np.sqrt(mean_squared_error(varx.ravel(),vary.ravel()))
print('Completed: Computed NON-weighted correlation!')
else:
ValueError('Wrong weighted arguement in function!')
print('*Completed: Finished calc_RMSE function!')
return rmse
###############################################################################
###############################################################################
###############################################################################
def calc_spatialCorrHeight(varx,vary,levs,lons,weight):
"""
Calculates spatial correlation from pearson correlation coefficient for
grids over vertical height (17 pressure coordinate levels)
Parameters
----------
varx : 2d array
vary : 2d array
levs : 1d array of levels
lons : 1d array of latitude
weight : string (yes or no)
Returns
-------
corrcoef : 1d array of correlation coefficient (pearson r)
Usage
-----
corrcoef = calc_spatialCorrHeight(varx,vary,lats,lons)
"""
print('\n>>> Using calc_spatialCorrHeight function!')
### Import modules
import numpy as np
if weight == 'yes': # Computed weighted correlation coefficient
### Create 2d meshgrid for weights
lon2,lev2 = np.meshgrid(lons,levs)
### Create 2d array of weights based on latitude
gwq = np.array([0.25,0.25,0.25,0.25,0.25,0.25,0.4,0.5,0.5,0.5,
0.5,0.5,0.5,0.7,0.7,0.7,1.])
gw,gw2 = np.meshgrid(lons,gwq)
def m(x, w):
"""Weighted Mean"""
wave = np.sum(x * w) / np.sum(w)
print('Completed: Computed weighted average (17 P Levels)!')
return wave
def cov(x, y, w):
"""Weighted Covariance"""
wcov = np.sum(w * (x - m(x, w)) * (y - m(y, w))) / np.sum(w)
print('Completed: Computed weighted covariance (17 P Levels)!')
return wcov
def corr(x, y, w):
"""Weighted Correlation"""
wcor = cov(x, y, w) / np.sqrt(cov(x, x, w) * cov(y, y, w))
print('Completed: Computed weighted correlation (17 P Levels)!')
return wcor
corrcoef = corr(varx,vary,gw)
elif weight == 'no':
### Correlation coefficient from numpy function (not weighted)
corrcoef= np.corrcoef(varx.ravel(),vary.ravel())[0][1]
print('Completed: Computed NON-weighted correlation!')
else:
ValueError('Wrong weighted argument in function!')
print('*Completed: Finished calc_SpatialCorrHeight function!')
return corrcoef
###############################################################################
###############################################################################
###############################################################################
def calc_spatialCorrHeightLev(varx,vary,levs,lons,weight,levelq):
"""
Calculates spatial correlation from pearson correlation coefficient for
grids over vertical height (17 pressure coordinate levels). Change the
weighting for different level correlations
Parameters
----------
varx : 2d array
vary : 2d array
levs : 1d array of levels
lons : 1d array of latitude
weight : string (yes or no)
levelq : string (all, tropo, strato)
Returns
-------
corrcoef : 1d array of correlation coefficient (pearson r)
Usage
-----
corrcoef = calc_spatialCorrHeight(varx,vary,lats,lons,levels)
"""
print('\n>>> Using calc_spatialCorrHeightLev function!')
### Import modules
import numpy as np
if weight == 'yes': # Computed weighted correlation coefficient
### Create 2d meshgrid for weights
lon2,lev2 = np.meshgrid(lons,levs)
if levelq == 'all':
### Create 2d array of weights based on latitude
gwq = np.array([0.25,0.25,0.25,0.25,0.25,0.25,0.4,0.5,0.5,0.5,
0.5,0.5,0.5,0.7,0.7,0.7,1.])
gw,gw2 = np.meshgrid(lons,gwq)
elif levelq == 'tropo':
gwq = np.array([1.0,1.0,1.0,1.0,0.5,0.5,0.5,0.2,0.2,0.,0.,0.,
0.,0.,0.,0.,0.])
gw,gw2 = np.meshgrid(lons,gwq)
elif levelq == 'strato':
gwq = np.array([0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.5,1.,1.,1.,1.
,1.,1.])
gw,gw2 = np.meshgrid(lons,gwq)
def m(x, w):
"""Weighted Mean"""
wave = np.sum(x * w) / np.sum(w)
print('Completed: Computed weighted average (17 P Levels)!')
return wave
def cov(x, y, w):
"""Weighted Covariance"""
wcov = np.sum(w * (x - m(x, w)) * (y - m(y, w))) / np.sum(w)
print('Completed: Computed weighted covariance (17 P Levels)!')
return wcov
def corr(x, y, w):
"""Weighted Correlation"""
wcor = cov(x, y, w) / np.sqrt(cov(x, x, w) * cov(y, y, w))
print('Completed: Computed weighted correlation (17 P Levels)!')
return wcor
corrcoef = corr(varx,vary,gw)
elif weight == 'no':
### Correlation coefficient from numpy function (not weighted)
corrcoef= np.corrcoef(varx.ravel(),vary.ravel())[0][1]
print('Completed: Computed NON-weighted correlation!')
else:
ValueError('Wrong weighted argument in function!')
print('*Completed: Finished calc_SpatialCorrHeightLev function!')
return corrcoef
| 36.514469 | 95 | 0.468739 | 2,463 | 22,712 | 4.295575 | 0.097848 | 0.042533 | 0.020416 | 0.022684 | 0.831947 | 0.81465 | 0.795747 | 0.750189 | 0.738185 | 0.719187 | 0 | 0.030765 | 0.330222 | 22,712 | 622 | 96 | 36.514469 | 0.664738 | 0.224287 | 0 | 0.686411 | 0 | 0 | 0.11901 | 0.006239 | 0 | 0 | 0 | 0 | 0 | 1 | 0.059233 | false | 0 | 0.034843 | 0 | 0.15331 | 0.12892 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
0
| 6 |
0a3472688b742e51fb849821bffb5408a0c299f0
| 5,306 |
py
|
Python
|
cs15211/ReverseBits.py
|
JulyKikuAkita/PythonPrac
|
0ba027d9b8bc7c80bc89ce2da3543ce7a49a403c
|
[
"Apache-2.0"
] | 1 |
2021-07-05T01:53:30.000Z
|
2021-07-05T01:53:30.000Z
|
cs15211/ReverseBits.py
|
JulyKikuAkita/PythonPrac
|
0ba027d9b8bc7c80bc89ce2da3543ce7a49a403c
|
[
"Apache-2.0"
] | null | null | null |
cs15211/ReverseBits.py
|
JulyKikuAkita/PythonPrac
|
0ba027d9b8bc7c80bc89ce2da3543ce7a49a403c
|
[
"Apache-2.0"
] | 1 |
2018-01-08T07:14:08.000Z
|
2018-01-08T07:14:08.000Z
|
__source__ = 'https://leetcode.com/problems/reverse-bits/description/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/reverse-bits.py
# Time : O(n)
# Space: O(1)
# Bit Manipulation
#
# Description: Leetcode # 190. Reverse Bits
#
# Reverse bits of a given 32 bits unsigned integer.
#
# For example, given input 43261596 (represented in binary as 00000010100101000001111010011100),
# return 964176192 (represented in binary as 00111001011110000010100101000000).
#
# Follow up:
# If this function is called many times, how would you optimize it?
#
# Companies
# Apple Airbnb
# Related Topics
# Bit Manipulation
# Similar Questions
# Number of 1 Bits
#
import unittest
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
result = 0
for i in xrange(32):
result <<= 1
result |= n & 1
n >>= 1
return result
class TestMethods(unittest.TestCase):
def test_Local(self):
self.assertEqual(1, 1)
print Solution().reverseBits(1)
if __name__ == '__main__':
unittest.main()
Java = '''
# Thought:
# 1ms 100%
class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int ret = 0;
for (int i = 0; i < 32; i++) {
if ((n & 1) != 0) {
ret |= 1; //same as // res += n & 1
}
n >>>= 1; // padding 0 on the left side
if (i < 31) { // CATCH: for last digit, don't shift!
ret <<= 1;
}
}
return ret;
}
}
We first intitialize result to 0. We then iterate from 0 to 31 (an integer has 32 bits).
In each iteration: We first shift result to the left by 1 bit.
Then, if the last digit of input n is 1, we add 1 to result.
To find the last digit of n, we just do: (n & 1)
Example, if n=5 (101), n&1 = 101 & 001 = 001 = 1; however, if n = 2 (10), n&1 = 10 & 01 = 0).
Finally, we update n by shifting it to the right by 1 (n >>= 1)
At the end of the iteration, we return result.
Example, if input n = 13 (represented in binary as
0000_0000_0000_0000_0000_0000_0000_1101, the "_" is for readability),
calling reverseBits(13) should return:
1011_0000_0000_0000_0000_0000_0000_0000
Here is how our algorithm would work for input n = 13:
Initially, result = 0 = 0000_0000_0000_0000_0000_0000_0000_0000,
n = 13 = 0000_0000_0000_0000_0000_0000_0000_1101
Starting for loop:
i = 0:
result = result << 1 = 0000_0000_0000_0000_0000_0000_0000_0000.
n&1 = 0000_0000_0000_0000_0000_0000_0000_1101 &
0000_0000_0000_0000_0000_0000_0000_0001 =
0000_0000_0000_0000_0000_0000_0000_0001 = 1
therefore result = result + 1 =
0000_0000_0000_0000_0000_0000_0000_0000 +
0000_0000_0000_0000_0000_0000_0000_0001 =
0000_0000_0000_0000_0000_0000_0000_0001 = 1
We right shift n by 1 (n >>= 1) to get:
n = 0000_0000_0000_0000_0000_0000_0000_0110.
We then go to the next iteration.
i = 1:
result = result << 1 = 0000_0000_0000_0000_0000_0000_0000_0010;
n&1 = 0000_0000_0000_0000_0000_0000_0000_0110 &
0000_0000_0000_0000_0000_0000_0000_0001
= 0000_0000_0000_0000_0000_0000_0000_0000 = 0;
therefore we don't increment result.
We right shift n by 1 (n >>= 1) to get:
n = 0000_0000_0000_0000_0000_0000_0000_0011.
We then go to the next iteration.
i = 2:
result = result << 1 = 0000_0000_0000_0000_0000_0000_0000_0100.
n&1 = 0000_0000_0000_0000_0000_0000_0000_0011 &
0000_0000_0000_0000_0000_0000_0000_0001 =
0000_0000_0000_0000_0000_0000_0000_0001 = 1
therefore result = result + 1 =
0000_0000_0000_0000_0000_0000_0000_0100 +
0000_0000_0000_0000_0000_0000_0000_0001 =
result = 0000_0000_0000_0000_0000_0000_0000_0101
We right shift n by 1 to get:
n = 0000_0000_0000_0000_0000_0000_0000_0001.
We then go to the next iteration.
i = 3:
result = result << 1 = 0000_0000_0000_0000_0000_0000_0000_1010.
n&1 = 0000_0000_0000_0000_0000_0000_0000_0001 &
0000_0000_0000_0000_0000_0000_0000_0001 =
0000_0000_0000_0000_0000_0000_0000_0001 = 1
therefore result = result + 1 =
= 0000_0000_0000_0000_0000_0000_0000_1011
We right shift n by 1 to get:
n = 0000_0000_0000_0000_0000_0000_0000_0000 = 0.
Now, from here to the end of the iteration, n is 0,
so (n&1) will always be 0 and n >>=1 will not change n.
The only change will be for result <<=1, i.e. shifting result to the left by 1 digit.
Since there we have i=4 to i = 31 iterations left, this will result
in padding 28 0's to the right of result. i.e at the end,
we get result = 1011_0000_0000_0000_0000_0000_0000_0000
This is exactly what we expected to get
# 1ms 100%
class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
if (n == 0) return 0;
int result = 0;
for (int i = 0; i < 32; i++) {
result <<= 1;
if ((n & 1) == 1) result++;
n >>= 1;
}
return result;
}
}
# 1ms 100%
class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
n = ((n & 0x55555555) << 1) | ((n & 0xAAAAAAAA) >>> 1);
n = ((n & 0x33333333) << 2) | ((n & 0xCCCCCCCC) >>> 2);
n = ((n & 0x0F0F0F0F) << 4) | ((n & 0xF0F0F0F0) >>> 4);
n = ((n & 0x00FF00FF) << 8) | ((n & 0xFF00FF00) >>> 8);
return (n >>> 16) | (n << 16);
}
}
'''
| 31.963855 | 96 | 0.67942 | 885 | 5,306 | 3.80452 | 0.216949 | 0.470448 | 0.595189 | 0.646273 | 0.485595 | 0.473715 | 0.463023 | 0.454707 | 0.36828 | 0.328185 | 0 | 0.314932 | 0.225028 | 5,306 | 165 | 97 | 32.157576 | 0.503891 | 0.109876 | 0 | 0.264 | 0 | 0.024 | 0.905472 | 0.267618 | 0 | 0 | 0.017032 | 0 | 0.008 | 0 | null | null | 0 | 0.008 | null | null | 0.008 | 0 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
0
| 6 |
0a444a2a9b00c93ede978edd61b59c20a6608e93
| 5,351 |
py
|
Python
|
testing/scripts/test_ksonnet_single_namespace.py
|
dtrawins/seldon-core
|
3d8b3791b343118953757a1e787e5919cc64e697
|
[
"Apache-2.0"
] | null | null | null |
testing/scripts/test_ksonnet_single_namespace.py
|
dtrawins/seldon-core
|
3d8b3791b343118953757a1e787e5919cc64e697
|
[
"Apache-2.0"
] | null | null | null |
testing/scripts/test_ksonnet_single_namespace.py
|
dtrawins/seldon-core
|
3d8b3791b343118953757a1e787e5919cc64e697
|
[
"Apache-2.0"
] | null | null | null |
import pytest
import time
import subprocess
from subprocess import run,Popen
from seldon_utils import *
from k8s_utils import *
def wait_for_shutdown(deploymentName):
ret = run("kubectl get deploy/"+deploymentName, shell=True)
while ret.returncode == 0:
time.sleep(1)
ret = run("kubectl get deploy/"+deploymentName, shell=True)
def wait_for_rollout(deploymentName):
ret = run("kubectl rollout status deploy/"+deploymentName, shell=True)
while ret.returncode > 0:
time.sleep(1)
ret = run("kubectl rollout status deploy/"+deploymentName, shell=True)
def initial_rest_request():
r = rest_request_api_gateway("oauth-key","oauth-secret",None,API_GATEWAY_REST)
if not r.status_code == 200:
time.sleep(1)
r = rest_request_api_gateway("oauth-key","oauth-secret",None,API_GATEWAY_REST)
if not r.status_code == 200:
time.sleep(5)
r = rest_request_api_gateway("oauth-key","oauth-secret",None,API_GATEWAY_REST)
return r
@pytest.mark.usefixtures("seldon_java_images")
@pytest.mark.usefixtures("single_namespace_seldon_ksonnet")
class TestSingleNamespace(object):
# Test singe model helm script with 4 API methods
def test_single_model(self):
run('cd my-model && ks delete default && ks component rm mymodel', shell=True)
run('kubectl delete sdep --all', shell=True)
run('cd my-model && ks generate seldon-serve-simple-v1alpha2 mymodel --image seldonio/mock_classifier:1.0 --oauthKey=oauth-key --oauthSecret=oauth-secret && ks apply default -c mymodel', shell=True, check=True)
wait_for_rollout("mymodel-mymodel-025d03d")
r = initial_rest_request()
r = rest_request_api_gateway("oauth-key","oauth-secret",None,API_GATEWAY_REST)
res = r.json()
print(res)
assert r.status_code == 200
assert len(r.json()["data"]["tensor"]["values"]) == 1
r = rest_request_ambassador("mymodel",None,API_AMBASSADOR)
res = r.json()
print(res)
assert r.status_code == 200
assert len(r.json()["data"]["tensor"]["values"]) == 1
r = grpc_request_ambassador2("mymodel",None,API_AMBASSADOR)
print(r)
r = grpc_request_api_gateway2("oauth-key","oauth-secret",None,rest_endpoint=API_GATEWAY_REST,grpc_endpoint=API_GATEWAY_GRPC)
print(r)
run('cd my-model && ks delete default -c mymodel && ks component rm mymodel', shell=True)
# Test AB Test model helm script with 4 API methods
def test_abtest_model(self):
run('cd my-model && ks delete default && ks component rm mymodel', shell=True)
run('kubectl delete sdep --all', shell=True)
run('cd my-model && ks generate seldon-abtest-v1alpha2 myabtest --imageA seldonio/mock_classifier:1.0 --imageB seldonio/mock_classifier:1.0 --oauthKey=oauth-key --oauthSecret=oauth-secret && ks apply default -c myabtest', shell=True)
wait_for_rollout("myabtest-myabtest-41de5b8")
wait_for_rollout("myabtest-myabtest-df66c5c")
r = initial_rest_request()
r = rest_request_api_gateway("oauth-key","oauth-secret",None,API_GATEWAY_REST)
res = r.json()
print(res)
assert r.status_code == 200
assert len(r.json()["data"]["tensor"]["values"]) == 1
r = rest_request_ambassador("myabtest",None,API_AMBASSADOR)
res = r.json()
print(res)
assert r.status_code == 200
assert len(r.json()["data"]["tensor"]["values"]) == 1
r = grpc_request_ambassador2("myabtest",None,API_AMBASSADOR)
print(r)
r = grpc_request_api_gateway2("oauth-key","oauth-secret",None,rest_endpoint=API_GATEWAY_REST,grpc_endpoint=API_GATEWAY_GRPC)
print(r)
run('cd my-model && ks delete default -c myabtest && ks component rm myabtest', shell=True)
# Test MAB Test model helm script with 4 API methods
def test_mab_model(self):
run('cd my-model && ks delete default && ks component rm mymab', shell=True)
run('kubectl delete sdep --all', shell=True)
run('cd my-model && ks generate seldon-mab-v1alpha2 mymab --imageA seldonio/mock_classifier:1.0 --imageB seldonio/mock_classifier:1.0 --oauthKey=oauth-key --oauthSecret=oauth-secret && ks apply default -c mymab', shell=True)
wait_for_rollout("mymab-mymab-41de5b8")
wait_for_rollout("mymab-mymab-b8038b2")
wait_for_rollout("mymab-mymab-df66c5c")
r = initial_rest_request()
r = rest_request_api_gateway("oauth-key","oauth-secret",None,API_GATEWAY_REST)
res = r.json()
print(res)
assert r.status_code == 200
assert len(r.json()["data"]["tensor"]["values"]) == 1
r = rest_request_ambassador("mymab",None,API_AMBASSADOR)
res = r.json()
print(res)
assert r.status_code == 200
assert len(r.json()["data"]["tensor"]["values"]) == 1
r = grpc_request_ambassador2("mymab",None,API_AMBASSADOR)
print(r)
r = grpc_request_api_gateway2("oauth-key","oauth-secret",None,rest_endpoint=API_GATEWAY_REST,grpc_endpoint=API_GATEWAY_GRPC)
print(r)
run('cd my-model && ks delete default && ks component rm mymab', shell=True)
| 50.481132 | 245 | 0.657073 | 720 | 5,351 | 4.709722 | 0.152778 | 0.053082 | 0.031849 | 0.050428 | 0.830434 | 0.784429 | 0.775877 | 0.775877 | 0.761722 | 0.730758 | 0 | 0.020525 | 0.216969 | 5,351 | 105 | 246 | 50.961905 | 0.788783 | 0.027658 | 0 | 0.617021 | 0 | 0.031915 | 0.320446 | 0.071552 | 0 | 0 | 0 | 0 | 0.12766 | 1 | 0.06383 | false | 0 | 0.06383 | 0 | 0.148936 | 0.12766 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
0
| 6 |
6a94a7cd3e89c26bee4c47c7741e5a37358da6ff
| 46 |
py
|
Python
|
Fundamentals/Reversed Strings.py
|
gnvidal/Codewars
|
117a83bd949a1503f31f1f915641e96e7bf7a04c
|
[
"MIT"
] | 49 |
2018-04-30T06:42:45.000Z
|
2021-07-22T16:39:02.000Z
|
Fundamentals/Reversed Strings.py
|
gnvidal/Codewars
|
117a83bd949a1503f31f1f915641e96e7bf7a04c
|
[
"MIT"
] | 1 |
2020-08-31T02:36:53.000Z
|
2020-08-31T10:14:00.000Z
|
Fundamentals/Reversed Strings.py
|
gnvidal/Codewars
|
117a83bd949a1503f31f1f915641e96e7bf7a04c
|
[
"MIT"
] | 36 |
2016-11-07T19:59:58.000Z
|
2022-03-31T11:18:27.000Z
|
def solution(string):
return string[::-1]
| 15.333333 | 23 | 0.652174 | 6 | 46 | 5 | 0.833333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.026316 | 0.173913 | 46 | 2 | 24 | 23 | 0.763158 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.5 | false | 0 | 0 | 0.5 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 0 |
0
| 6 |
0a8d1e23712a4b58170f56ad1d0354b9b57142a5
| 45 |
py
|
Python
|
AudioLib/__init__.py
|
yNeshy/voice-change
|
2535351bcd8a9f2d58fcbff81a2051c4f6ac6ab4
|
[
"MIT"
] | 11 |
2021-02-04T11:35:37.000Z
|
2022-03-26T10:32:00.000Z
|
AudioLib/__init__.py
|
yNeshy/voice-change
|
2535351bcd8a9f2d58fcbff81a2051c4f6ac6ab4
|
[
"MIT"
] | 4 |
2021-03-22T09:36:54.000Z
|
2021-03-26T09:10:51.000Z
|
AudioLib/__init__.py
|
yNeshy/voice-change
|
2535351bcd8a9f2d58fcbff81a2051c4f6ac6ab4
|
[
"MIT"
] | 6 |
2021-02-24T09:03:35.000Z
|
2021-11-16T02:00:53.000Z
|
from AudioLib.AudioEffect import AudioEffect
| 22.5 | 44 | 0.888889 | 5 | 45 | 8 | 0.8 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.088889 | 45 | 1 | 45 | 45 | 0.97561 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 |
0
| 6 |
0aab7620f824873c7b572e13e03aa334f91e254d
| 143 |
py
|
Python
|
axju/generic/__init__.py
|
axju/axju
|
de0b3d9c63b7cca4ed16fb50e865c159b4377953
|
[
"MIT"
] | null | null | null |
axju/generic/__init__.py
|
axju/axju
|
de0b3d9c63b7cca4ed16fb50e865c159b4377953
|
[
"MIT"
] | null | null | null |
axju/generic/__init__.py
|
axju/axju
|
de0b3d9c63b7cca4ed16fb50e865c159b4377953
|
[
"MIT"
] | null | null | null |
from axju.generic.basic import BasicWorker
from axju.generic.execution import ExecutionWorker
from axju.generic.template import TemplateWorker
| 35.75 | 50 | 0.874126 | 18 | 143 | 6.944444 | 0.555556 | 0.192 | 0.36 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.083916 | 143 | 3 | 51 | 47.666667 | 0.954198 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 |
0
| 6 |
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- 18