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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a3f2f1511ee20e3de14fce88861b2e0da7e98c47 | 3,965 | py | Python | appengine/monorail/framework/test/timestr_test.py | xinghun61/infra | b5d4783f99461438ca9e6a477535617fadab6ba3 | [
"BSD-3-Clause"
] | 2 | 2021-04-13T21:22:18.000Z | 2021-09-07T02:11:57.000Z | appengine/monorail/framework/test/timestr_test.py | asdfghjjklllllaaa/infra | 8f63af54e46194cd29291813f2790ff6e986804d | [
"BSD-3-Clause"
] | 21 | 2020-09-06T02:41:05.000Z | 2022-03-02T04:40:01.000Z | appengine/monorail/framework/test/timestr_test.py | xinghun61/infra | b5d4783f99461438ca9e6a477535617fadab6ba3 | [
"BSD-3-Clause"
] | null | null | null | # Copyright 2016 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 or at
# https://developers.google.com/open-source/licenses/bsd
"""Unittest for timestr module."""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import calendar
import datetime
import time
import unittest
from framework import timestr
class TimeStrTest(unittest.TestCase):
"""Unit tests for timestr routines."""
def testFormatAbsoluteDate(self):
now = datetime.datetime(2008, 1, 1)
def GetDate(*args):
date = datetime.datetime(*args)
return timestr.FormatAbsoluteDate(
calendar.timegm(date.utctimetuple()), clock=lambda: now)
self.assertEquals(GetDate(2008, 1, 1), 'Today')
self.assertEquals(GetDate(2007, 12, 31), 'Yesterday')
self.assertEquals(GetDate(2007, 12, 30), 'Dec 30')
self.assertEquals(GetDate(2007, 1, 1), 'Jan 2007')
self.assertEquals(GetDate(2007, 1, 2), 'Jan 2007')
self.assertEquals(GetDate(2007, 12, 31), 'Yesterday')
self.assertEquals(GetDate(2006, 12, 31), 'Dec 2006')
self.assertEquals(GetDate(2007, 7, 1), 'Jul 1')
self.assertEquals(GetDate(2007, 6, 30), 'Jun 2007')
self.assertEquals(GetDate(2008, 1, 3), 'Jan 2008')
# Leap year fun
now = datetime.datetime(2008, 3, 1)
self.assertEquals(GetDate(2008, 2, 29), 'Yesterday')
# Clock skew
now = datetime.datetime(2008, 1, 1, 23, 59, 59)
self.assertEquals(GetDate(2008, 1, 2), 'Today')
now = datetime.datetime(2007, 12, 31, 23, 59, 59)
self.assertEquals(GetDate(2008, 1, 1), 'Today')
self.assertEquals(GetDate(2008, 1, 2), 'Jan 2008')
def testFormatRelativeDate(self):
now = time.mktime(datetime.datetime(2008, 1, 1).timetuple())
def TestSecsAgo(secs_ago, expected, expected_days_only):
test_time = now - secs_ago
actual = timestr.FormatRelativeDate(
test_time, clock=lambda: now)
self.assertEquals(actual, expected)
actual_days_only = timestr.FormatRelativeDate(
test_time, clock=lambda: now, days_only=True)
self.assertEquals(actual_days_only, expected_days_only)
TestSecsAgo(10 * 24 * 60 * 60, '', '10 days ago')
TestSecsAgo(5 * 24 * 60 * 60 - 1, '4 days ago', '4 days ago')
TestSecsAgo(5 * 60 * 60 - 1, '4 hours ago', '')
TestSecsAgo(5 * 60 - 1, '4 minutes ago', '')
TestSecsAgo(2 * 60 - 1, '1 minute ago', '')
TestSecsAgo(60 - 1, 'moments ago', '')
TestSecsAgo(0, 'moments ago', '')
TestSecsAgo(-10, 'moments ago', '')
TestSecsAgo(-100, '', '')
def testGetHumanScaleDate(self):
"""Tests GetHumanScaleDate()."""
now = time.mktime(datetime.datetime(2008, 4, 10, 20, 50, 30).timetuple())
def GetDate(*args):
date = datetime.datetime(*args)
timestamp = time.mktime(date.timetuple())
return timestr.GetHumanScaleDate(timestamp, now=now)
self.assertEquals(
GetDate(2008, 4, 10, 15), ('Today', '5 hours ago'))
self.assertEquals(
GetDate(2008, 4, 10, 19, 55), ('Today', '55 min ago'))
self.assertEquals(
GetDate(2008, 4, 10, 20, 48, 35), ('Today', '1 min ago'))
self.assertEquals(
GetDate(2008, 4, 10, 20, 49, 35), ('Today', 'moments ago'))
self.assertEquals(
GetDate(2008, 4, 10, 20, 50, 55), ('Today', 'moments ago'))
self.assertEquals(
GetDate(2008, 4, 9, 15), ('Yesterday', '29 hours ago'))
self.assertEquals(
GetDate(2008, 4, 5, 15), ('Last 7 days', 'Apr 05, 2008'))
self.assertEquals(
GetDate(2008, 3, 22, 15), ('Last 30 days', 'Mar 22, 2008'))
self.assertEquals(
GetDate(2008, 1, 2, 15), ('Earlier this year', 'Jan 02, 2008'))
self.assertEquals(
GetDate(2007, 12, 31, 15), ('Before this year', 'Dec 31, 2007'))
self.assertEquals(
GetDate(2008, 4, 11, 20, 49, 35), ('Future', 'Later'))
| 37.761905 | 77 | 0.645397 | 522 | 3,965 | 4.848659 | 0.268199 | 0.170684 | 0.227183 | 0.170684 | 0.434216 | 0.363888 | 0.263532 | 0.167128 | 0.115765 | 0.085737 | 0 | 0.11895 | 0.202774 | 3,965 | 104 | 78 | 38.125 | 0.681746 | 0.083228 | 0 | 0.240506 | 0 | 0 | 0.114555 | 0 | 0 | 0 | 0 | 0 | 0.341772 | 1 | 0.075949 | false | 0 | 0.101266 | 0 | 0.21519 | 0.012658 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
a3f510544942695364cd0424dc68903d43497da6 | 10,199 | py | Python | main code.py | jsheng0901/Humpback-Whale-Identification | df8db4002b95014e0c0d277ddb0dfd9e47b56066 | [
"MIT"
] | null | null | null | main code.py | jsheng0901/Humpback-Whale-Identification | df8db4002b95014e0c0d277ddb0dfd9e47b56066 | [
"MIT"
] | null | null | null | main code.py | jsheng0901/Humpback-Whale-Identification | df8db4002b95014e0c0d277ddb0dfd9e47b56066 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""kernel8b79eadbd5.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1RjLxCLD-ueP9Eju9lPSNdoRyGE_TTJAK
"""
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
# Input data files are available in the "../input/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory
import os
print(os.listdir("../input"))
import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
import matplotlib.image as mplimg
from matplotlib.pyplot import imshow
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from keras import layers
from keras.preprocessing import image
from keras.applications.imagenet_utils import preprocess_input
from keras.layers import Input, Dense, Activation, BatchNormalization, Flatten, Conv2D,GlobalAveragePooling2D
from keras.layers import AveragePooling2D, MaxPooling2D, Dropout
from keras.models import Model
import keras.backend as K
from keras.models import Sequential
import warnings
warnings.simplefilter("ignore", category=DeprecationWarning)
number_train = len(os.listdir("../input/train"))
train_df = pd.read_csv("../input/train.csv")
print('The shape of trainning csv is ' + str(train_df.shape))
print('The number of trainning image is ' + str(number_train))
train_df.head()
class_size = train_df['Id'].value_counts()
class_size[1:15].plot(kind='bar')
def prepareImages(data, m, dataset):
print("Preparing images")
X_train = np.zeros((m, 100, 100, 3))
count = 0
for fig in data['Image']:
#load images into images of size 100x100x3
img = image.load_img("../input/"+dataset+"/"+fig, target_size=(100, 100, 3)) # show the image as PIL
x = image.img_to_array(img) # convert image to pixal values and shapes as target_size which defined above
x = preprocess_input(x) # center the image pixal value because Resnet model train on pixal values in (-1,1)
X_train[count] = x
if (count%500 == 0):
print("Processing image: ", count+1, ", ", fig)
count += 1
return X_train
X = prepareImages(train_df, train_df.shape[0], "train")
X /= 255 # normalized the image pixal values
X.shape # just check the above model
def prepare_labels(y):
values = np.array(y)
label_encoder = LabelEncoder()
integer_encoded = label_encoder.fit_transform(values)
# print(integer_encoded) this change 5005 classes as lable class as a np.array
onehot_encoder = OneHotEncoder(sparse=False)
integer_encoded = integer_encoded.reshape(len(integer_encoded), 1) # change integer_encoded to (25361, 1)
onehot_encoded = onehot_encoder.fit_transform(integer_encoded)
# print(onehot_encoded)
y = onehot_encoded # change all sample as (25361, 5005) and each row is one sample one-encoding class
# print(y.shape)
return y, label_encoder
# Another way to get lable in one-hot encoding
yy = pd.get_dummies(train_df['Id']).values # try another way to change one-encoding
# try to split the train and val
from sklearn.model_selection import train_test_split
train_x, val_x, train_y, val_y = train_test_split(X, yy, test_size = 0.2, random_state = 0)
# check the train and val
print(train_x.shape, val_x.shape)
print(train_y.shape, val_y.shape)
y, label_encoder = prepare_labels(train_df['Id'])
y.shape
# The first CNN model
model = Sequential()
model.add(Conv2D(32, (7, 7), strides = (1, 1), name = 'conv0', input_shape = (100, 100, 3)))
model.add(BatchNormalization(axis = 3, name = 'bn0'))
model.add(Activation('relu'))
model.add(MaxPooling2D((2, 2), name='max_pool'))
model.add(Conv2D(64, (3, 3), strides = (1,1), name="conv1"))
model.add(Activation('relu'))
model.add(AveragePooling2D((3, 3), name='avg_pool'))
model.add(Flatten())
model.add(Dense(500, activation="relu", name='rl'))
model.add(Dropout(0.5))
model.add(Dense(yy.shape[1], activation='softmax', name='sm'))
model.compile(loss='categorical_crossentropy', optimizer="adam", metrics=['accuracy'])
model.summary()
# Try another CNN model
model = Sequential()
model.add(Conv2D(filters = 16, kernel_size = (5,5), padding = 'Same', activation = 'relu', input_shape = (100,100,3)))
model.add(Conv2D(filters = 16, kernel_size = (5,5), padding = 'Same', activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(filters = 32, kernel_size = (3,3), padding = 'Same', activation = 'relu'))
model.add(Conv2D(filters = 32, kernel_size = (3,3), padding = 'Same', activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2,2), strides=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(filters = 64, kernel_size = (3,3), padding = 'Same', activation = 'relu'))
model.add(Conv2D(filters = 64, kernel_size = (3,3), padding = 'Same', activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2,2), strides=(2,2)))
model.add(Dropout(0.25))
# fully connected
model.add(Flatten())
model.add(Dense(256, activation = 'relu'))
model.add(BatchNormalization())
model.add(Dense(yy.shape[1], activation = "softmax"))
model.compile(loss='categorical_crossentropy', optimizer="adam", metrics=['accuracy'])
model.summary()
history = model.fit(X, yy, epochs=1, batch_size=100, verbose=1)
plt.plot(history.history['acc'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.show()
# try fit_generator funtion for data augmentation avoiding overfiting
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rotation_range = 40,
width_shift_range = 0.2,
height_shift_range = 0.2,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
validation_datagen = ImageDataGenerator(rotation_range = 40,
width_shift_range = 0.2,
height_shift_range = 0.2,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
history_1 = model.fit_generator(train_datagen.flow(train_x, train_y, batch_size=32),
steps_per_epoch=len(train_x) / 32,
epochs=10,
validation_data=validation_datagen.flow(val_x, val_y, batch_size=32),
validation_steps=len(val_x) / 32)
plt.plot(history_1.history['acc'])
plt.plot(history_1.history['val_acc'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.show()
# try transfer learning Inceptionv3
from tensorflow.keras.applications.inception_v3 import InceptionV3
from tensorflow.keras import Model
pre_trained_model = InceptionV3(input_shape = (100, 100, 3),
include_top = False,weights=None, classes=5005)
#pre_trained_model.load_weights(local_weights_file)
#for layer in pre_trained_model.layers:
# layer.trainable = False
# pre_trained_model.summary()
last_layer = pre_trained_model.get_layer('mixed7')
print('last layer output shape: ', last_layer.output_shape)
last_output = last_layer.output
x = Flatten()(last_output)
# Add a fully connected layer with 1,024 hidden units and ReLU activation
x = Dense(1024, activation='relu')(x)
# Add a dropout rate of 0.2
x = Dropout(0.2)(x)
# Add a final sigmoid layer for classification
x = Dense(5005, activation='softmax')(x)
model_1 = Model(pre_trained_model.input, x)
# try transfer learning ResNet50
from keras.applications.resnet50 import ResNet50
from tensorflow.keras import Model
pre_trained_model_1 = ResNet50(input_shape = (100, 100, 3),
include_top = False,weights=None, classes=5005)
x = pre_trained_model_1.output
x = GlobalAveragePooling2D()(x)
# let's add a fully-connected layer
x = Dense(1024, activation='relu')(x)
x = Dense(5005, activation='softmax')(x)
model_2 = Model(inputs=pre_trained_model_1.input, outputs=x)
model_2.compile(loss='categorical_crossentropy', optimizer="adam", metrics=['accuracy'])
pre_trained_model_1.summary()
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen_1 = ImageDataGenerator(rotation_range = 40,
width_shift_range = 0.2,
height_shift_range = 0.2,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
validation_datagen_1 = ImageDataGenerator()
history_2 = pre_trained_model_1.fit_generator(train_datagen_1.flow(train_x, train_y, batch_size=32),
steps_per_epoch=len(train_x) / 32,
epochs=10,
validation_data=validation_datagen_1.flow(val_x, val_y, batch_size=32),
validation_steps=len(val_x) / 32)X
# Try MobileNet transfer learning
from keras.applications import MobileNet
from keras.applications.mobilenet import preprocess_input
model_3 = MobileNet(input_shape=(100, 100, 3), alpha=1., weights=None, classes=5005)
model_3.compile(loss='categorical_crossentropy', optimizer="adam", metrics=['accuracy'])
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen_2 = ImageDataGenerator(rotation_range = 40,
width_shift_range = 0.2,
height_shift_range = 0.2,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
validation_datagen_2 = ImageDataGenerator()
history_3 =model_3.fit_generator(train_datagen_2.flow(X, yy, batch_size=32),
steps_per_epoch=len(X) / 32,
epochs=10) | 38.05597 | 118 | 0.668595 | 1,365 | 10,199 | 4.835897 | 0.219048 | 0.032722 | 0.016967 | 0.026663 | 0.410847 | 0.386154 | 0.361006 | 0.331465 | 0.287532 | 0.255416 | 0 | 0.042393 | 0.218257 | 10,199 | 268 | 119 | 38.05597 | 0.785526 | 0.143249 | 0 | 0.388571 | 1 | 0 | 0.064406 | 0.011262 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.171429 | null | null | 0.045714 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
a3f868cfe72c862735c32d4072e13856c6529e01 | 442 | py | Python | Python/Tests/TestData/WFastCgi/DjangoSimpleAppUrlRewrite/DjangoApplication/TestApp/views.py | techkey/PTVS | 8355e67eedd8e915ca49bd38a2f36172696fd903 | [
"Apache-2.0"
] | 404 | 2019-05-07T02:21:57.000Z | 2022-03-31T17:03:04.000Z | Python/Tests/TestData/WFastCgi/DjangoSimpleAppUrlRewrite/DjangoApplication/TestApp/views.py | techkey/PTVS | 8355e67eedd8e915ca49bd38a2f36172696fd903 | [
"Apache-2.0"
] | 1,672 | 2019-05-06T21:09:38.000Z | 2022-03-31T23:16:04.000Z | Python/Tests/TestData/WFastCgi/DjangoSimpleAppUrlRewrite/DjangoApplication/TestApp/views.py | techkey/PTVS | 8355e67eedd8e915ca49bd38a2f36172696fd903 | [
"Apache-2.0"
] | 186 | 2019-05-13T03:17:37.000Z | 2022-03-31T16:24:05.000Z | import sys
from django.http import HttpResponse, HttpRequest
if sys.version_info >= (3,):
def encode(x):
return x.encode('ascii')
else:
def encode(x):
return x
def home(request):
assert isinstance(request, HttpRequest)
result = '''path: {0}
path_info: {1}
GET: {2}
POST: {3}'''.format(request.path, request.path_info, request.GET.urlencode(), request.POST.urlencode())
return HttpResponse(encode(result)) | 26 | 103 | 0.676471 | 59 | 442 | 5.016949 | 0.508475 | 0.060811 | 0.067568 | 0.108108 | 0.114865 | 0 | 0 | 0 | 0 | 0 | 0 | 0.013699 | 0.174208 | 442 | 17 | 104 | 26 | 0.79726 | 0 | 0 | 0.133333 | 0 | 0 | 0.108352 | 0 | 0 | 0 | 0 | 0 | 0.066667 | 1 | 0.2 | false | 0 | 0.133333 | 0.133333 | 0.533333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 2 |
a3fade465cb383861dbf4d57722d386aa8d9556a | 11,798 | py | Python | PyViCare/PyViCareDevice.py | bacobaco/PyViCare | e8d49e7148acf247ddba92eb104de160fe1f8f69 | [
"Apache-2.0"
] | null | null | null | PyViCare/PyViCareDevice.py | bacobaco/PyViCare | e8d49e7148acf247ddba92eb104de160fe1f8f69 | [
"Apache-2.0"
] | null | null | null | PyViCare/PyViCareDevice.py | bacobaco/PyViCare | e8d49e7148acf247ddba92eb104de160fe1f8f69 | [
"Apache-2.0"
] | null | null | null | import re
import json
import os
import logging
from PyViCare.PyViCareService import ViCareService
logger = logging.getLogger('ViCare')
logger.addHandler(logging.NullHandler())
# TODO Holiday program can still be used (parameters are there) heating.circuits." + str(self.service.circuit) + ".operating.programs.holiday
# TODO heating.dhw.schedule/setSchedule
# https://api.viessmann-platform.io/operational-data/installations/16011/gateways/7571381681420106/devices/0/features
# could be used for auto-generation
# a method to list all features
# another one to use them
# this can tell me if it's heating pump or gaz
""""Viessmann ViCare API Python tools"""
class Device:
"""This class connects to the Viesmann ViCare API.
The authentication is done through OAuth2.
Note that currently, a new token is generate for each run.
"""
# TODO cirtcuit management should move at method level
def __init__(self, username, password,token_file=None,circuit=0):
"""Init function. Create the necessary oAuth2 sessions
Parameters
----------
username : str
e-mail address
password : str
password
Returns
-------
"""
self.service = ViCareService(username, password, token_file, circuit)
""" Set the active mode
Parameters
----------
mode : str
Valid mode can be obtained using getModes()
Returns
-------
result: json
json representation of the answer
"""
def setMode(self,mode):
r=self.service.setProperty("heating.circuits." + str(self.service.circuit) + ".operating.modes.active","setMode","{\"mode\":\""+mode+"\"}")
return r
# Works for normal, reduced, comfort
# active has no action
# exetenral , standby no action
# holiday, sheculde and unscheduled
# activate, decativate comfort,eco
""" Set the target temperature for the target program
Parameters
----------
program : str
Can be normal, reduced or comfort
temperature: int
target temperature
Returns
-------
result: json
json representation of the answer
"""
def setProgramTemperature(self,program: str,temperature :int):
return self.service.setProperty("heating.circuits." + str(self.service.circuit) + ".operating.programs."+program,"setTemperature","{\"targetTemperature\":"+str(temperature)+"}")
def setReducedTemperature(self,temperature):
return self.setProgramTemperature("reduced",temperature)
def setComfortTemperature(self,temperature):
return self.setProgramTemperature("comfort",temperature)
def setNormalTemperature(self,temperature):
return self.setProgramTemperature("normal",temperature)
""" Activate a program
NOTE
DEVICE_COMMUNICATION_ERROR can just mean that the program is already on
Parameters
----------
program : str
Appears to work only for comfort
Returns
-------
result: json
json representation of the answer
"""
# optional temperature parameter could be passed (but not done)
def activateProgram(self,program):
return self.service.setProperty("heating.circuits." + str(self.service.circuit) + ".operating.programs."+program,"activate","{}")
def activateComfort(self):
return self.activateProgram("comfort")
""" Deactivate a program
Parameters
----------
program : str
Appears to work only for comfort and eco (coming from normal, can be reached only by deactivating another state)
Returns
-------
result: json
json representation of the answer
"""
def deactivateProgram(self,program):
return self.service.setProperty("heating.circuits." + str(self.service.circuit) + ".operating.programs."+program,"deactivate","{}")
def deactivateComfort(self):
return self.deactivateProgram("comfort")
def getMonthSinceLastService(self):
try:
return self.service.getProperty("heating.service.timeBased")["properties"]["activeMonthSinceLastService"]["value"]
except KeyError:
return "error"
def getLastServiceDate(self):
try:
return self.service.getProperty("heating.service.timeBased")["properties"]["lastService"]["value"]
except KeyError:
return "error"
def getOutsideTemperature(self):
try:
return self.service.getProperty("heating.sensors.temperature.outside")["properties"]["value"]["value"]
except KeyError:
return "error"
def getSupplyTemperature(self):
try:
return self.service.getProperty("heating.circuits." + str(self.service.circuit) + ".sensors.temperature.supply")["properties"]["value"]["value"]
except KeyError:
return "error"
def getRoomTemperature(self):
try:
return self.service.getProperty("heating.circuits." + str(self.service.circuit) + ".sensors.temperature.room")["properties"]["value"]["value"]
except KeyError:
return "error"
def getModes(self):
try:
return self.service.getProperty("heating.circuits." + str(self.service.circuit) + ".operating.modes.active")["actions"][0]["fields"][0]["enum"]
except KeyError:
return "error"
def getActiveMode(self):
try:
return self.service.getProperty("heating.circuits." + str(self.service.circuit) + ".operating.modes.active")["properties"]["value"]["value"]
except KeyError:
return "error"
def getHeatingCurveShift(self):
try:
return self.service.getProperty("heating.circuits." + str(self.service.circuit) + ".heating.curve")["properties"]["shift"]["value"]
except KeyError:
return "error"
#################################################################################################################################################################################
#baco hack add
def setHeatingCurve(self,shift,slope):
try:
#return self.service.setProperty("heating.dhw.temperature","setTargetTemperature","{\"temperature\":"+str(temperature)+"}")
return self.service.setProperty("heating.circuits." + str(self.service.circuit) + ".heating.curve","setCurve","{\"shift\":" +str(shift)+",\"slope\":"+str(slope)+"}")
except KeyError:
return "error"
#end hack baco
#################################################################################################################################################################################
def getHeatingCurveSlope(self):
try:
return self.service.getProperty("heating.circuits." + str(self.service.circuit) + ".heating.curve")["properties"]["slope"]["value"]
except KeyError:
return "error"
def getActiveProgram(self):
try:
return self.service.getProperty("heating.circuits." + str(self.service.circuit) + ".operating.programs.active")["properties"]["value"]["value"]
except KeyError:
return "error"
def getPrograms(self):
try:
return self.service.getProperty("heating.circuits." + str(self.service.circuit) + ".operating.programs")["entities"][9]["properties"]["components"]
except KeyError:
return "error"
def getDesiredTemperatureForProgram(self , program):
try:
return self.service.getProperty("heating.circuits." + str(self.service.circuit) + ".operating.programs."+program)["properties"]["temperature"]["value"]
except KeyError:
return "error"
def getCurrentDesiredTemperature(self):
try:
return self.service.getProperty("heating.circuits." + str(self.service.circuit) + ".operating.programs."+self.getActiveProgram())["properties"]["temperature"]["value"]
except KeyError:
return "error"
def getErrorHistory(self):
try:
return self.service.getProperty("heating.errors.history")["properties"]["entries"]["value"]
except KeyError:
return "error"
def getActiveError(self):
try:
return self.service.getProperty("heating.errors.active")["properties"]["entries"]["value"]
except KeyError:
return "error"
def getDomesticHotWaterConfiguredTemperature(self):
try:
return self.service.getProperty("heating.dhw.temperature")["properties"]["value"]["value"]
except KeyError:
return "error"
def getDomesticHotWaterStorageTemperature(self):
try:
return self.service.getProperty("heating.dhw.sensors.temperature.hotWaterStorage")["properties"]["value"]["value"]
except KeyError:
return "error"
def getDomesticHotWaterPumpActive(self):
try:
status = self.service.getProperty("heating.dhw.pumps.primary")["properties"]["status"]["value"]
return status == 'on'
except KeyError:
return "error"
def getDomesticHotWaterMaxTemperature(self):
try:
return self.service.getProperty("heating.dhw.temperature")["actions"][0]["fields"][0]["max"]
except KeyError:
return "error"
def getDomesticHotWaterMinTemperature(self):
try:
return self.service.getProperty("heating.dhw.temperature")["actions"][0]["fields"][0]["min"]
except KeyError:
return "error"
""" Set the target temperature for domestic host water
Parameters
----------
temperature : int
Target temperature
Returns
-------
result: json
json representation of the answer
"""
def setDomesticHotWaterTemperature(self,temperature):
return self.service.setProperty("heating.dhw.temperature","setTargetTemperature","{\"temperature\":"+str(temperature)+"}")
def getCirculationPumpActive(self):
try:
status = self.service.getProperty("heating.circuits." + str(self.service.circuit) + ".circulation.pump")["properties"]["status"]["value"]
return status == 'on'
except KeyError:
return "error"
def getHeatingSchedule(self):
try:
properties = self.service.getProperty("heating.circuits." + str(self.service.circuit) + ".heating.schedule")["properties"]
return {
"active": properties["active"]["value"],
"mon": properties["entries"]["value"]["mon"],
"tue": properties["entries"]["value"]["tue"],
"wed": properties["entries"]["value"]["wed"],
"thu": properties["entries"]["value"]["thu"],
"fri": properties["entries"]["value"]["fri"],
"sat": properties["entries"]["value"]["sat"],
"sun": properties["entries"]["value"]["sun"]
}
except KeyError:
return "error"
def getDomesticHotWaterSchedule(self):
try:
properties = self.service.getProperty("heating.dhw.schedule")["properties"]
return {
"active": properties["active"]["value"],
"mon": properties["entries"]["value"]["mon"],
"tue": properties["entries"]["value"]["tue"],
"wed": properties["entries"]["value"]["wed"],
"thu": properties["entries"]["value"]["thu"],
"fri": properties["entries"]["value"]["fri"],
"sat": properties["entries"]["value"]["sat"],
"sun": properties["entries"]["value"]["sun"]
}
except KeyError:
return "error"
| 38.809211 | 185 | 0.602221 | 1,090 | 11,798 | 6.511009 | 0.226606 | 0.075948 | 0.059884 | 0.084543 | 0.617303 | 0.5732 | 0.5577 | 0.535156 | 0.436522 | 0.376497 | 0 | 0.003532 | 0.232073 | 11,798 | 303 | 186 | 38.937294 | 0.779801 | 0.098746 | 0 | 0.531792 | 0 | 0 | 0.223569 | 0.052805 | 0 | 0 | 0 | 0.006601 | 0 | 1 | 0.202312 | false | 0.011561 | 0.028902 | 0.052023 | 0.572254 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
430b13de22657e77fc70e77b88bddf1c2687adfb | 623 | py | Python | src/app1/migrations/0002_auto_20200313_1714.py | SheelSanghvi/inventory-management-web | 1e848aa833e2418c588e8d2eaa98782e89ed3952 | [
"MIT"
] | 3 | 2020-06-12T18:29:21.000Z | 2021-12-26T21:14:59.000Z | src/app1/migrations/0002_auto_20200313_1714.py | Preet538-neitzen/inventory-management-web | 1e848aa833e2418c588e8d2eaa98782e89ed3952 | [
"MIT"
] | 9 | 2020-02-29T04:04:42.000Z | 2022-02-26T23:26:17.000Z | src/app1/migrations/0002_auto_20200313_1714.py | Preet538-neitzen/inventory-management-web | 1e848aa833e2418c588e8d2eaa98782e89ed3952 | [
"MIT"
] | 17 | 2020-02-24T17:18:44.000Z | 2021-04-08T08:37:30.000Z | # Generated by Django 2.1.4 on 2020-03-13 11:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("app1", "0001_initial"),
]
operations = [
migrations.AlterField(
model_name="user", name="age", field=models.IntegerField(default=0),
),
migrations.AlterField(
model_name="user",
name="gender",
field=models.CharField(
choices=[("M", "M"), ("F", "F"), ("Other", "Other")],
default="M",
max_length=15,
),
),
]
| 23.961538 | 80 | 0.507223 | 61 | 623 | 5.114754 | 0.688525 | 0.128205 | 0.160256 | 0.185897 | 0.237179 | 0.237179 | 0 | 0 | 0 | 0 | 0 | 0.056098 | 0.341894 | 623 | 25 | 81 | 24.92 | 0.704878 | 0.072231 | 0 | 0.263158 | 1 | 0 | 0.083333 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.052632 | 0 | 0.210526 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
430c2b1cc629a44315689794b4f3601fa2fc266c | 476 | py | Python | quiz/forms/quiz_settings_form.py | manikagarg/iQuiz | 99b2550eeedb92134a631d71fdb017844f81ef78 | [
"MIT"
] | null | null | null | quiz/forms/quiz_settings_form.py | manikagarg/iQuiz | 99b2550eeedb92134a631d71fdb017844f81ef78 | [
"MIT"
] | null | null | null | quiz/forms/quiz_settings_form.py | manikagarg/iQuiz | 99b2550eeedb92134a631d71fdb017844f81ef78 | [
"MIT"
] | 1 | 2021-09-26T14:10:28.000Z | 2021-09-26T14:10:28.000Z | from django.forms import *
from pagedown.widgets import PagedownWidget
from ..models import QuizSettings
class QuizSettingsForm(ModelForm):
information = CharField(widget=PagedownWidget(), strip=False, required=False)
deadline = DateField(widget = DateInput(attrs={'placeholder': 'YYYY-MM-DD [HH:MM:SS]',}), required = False)
class Meta:
model = QuizSettings
fields = ['deadline', 'duration', 'timeBetweenAttempt', 'maxAttempts' , 'information'] | 39.666667 | 111 | 0.722689 | 48 | 476 | 7.166667 | 0.708333 | 0.075581 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.151261 | 476 | 12 | 112 | 39.666667 | 0.851485 | 0 | 0 | 0 | 0 | 0 | 0.184486 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.333333 | 0 | 0.777778 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
430ceee7108841e6acffeede336999382c1ab4c4 | 2,452 | py | Python | datalidator/DatalidatorObjectIface.py | vitlabuda/datalidator | 539063a98990c6be165baeff6c2a74ac2fd7a130 | [
"BSD-3-Clause"
] | null | null | null | datalidator/DatalidatorObjectIface.py | vitlabuda/datalidator | 539063a98990c6be165baeff6c2a74ac2fd7a130 | [
"BSD-3-Clause"
] | null | null | null | datalidator/DatalidatorObjectIface.py | vitlabuda/datalidator | 539063a98990c6be165baeff6c2a74ac2fd7a130 | [
"BSD-3-Clause"
] | null | null | null | #!/bin/false
# Copyright (c) 2022 Vít Labuda. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
# following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
# disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
# following disclaimer in the documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
# products derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import abc
__all__ = "DatalidatorObjectIface",
class DatalidatorObjectIface(metaclass=abc.ABCMeta):
"""
The interface of all blueprints, filters and validators.
"""
__slots__ = ()
@abc.abstractmethod
def get_tag(self) -> str:
"""
Returns the tag of the Datalidator object.
A tag is a string that might be provided by the user when instantiating a Datalidator object. It might be used
to identify the instance later, and it is also passed to all Datalidator exceptions and errors raised by
Datalidator objects (which makes it simple for the user to identify where exactly did the problem occur when,
for example, using nested blueprints - see the 'OriginatorTagCarrierMixin' class).
:return: The tag of the Datalidator object.
"""
raise NotImplementedError(DatalidatorObjectIface.get_tag.__qualname__)
| 49.04 | 118 | 0.757749 | 338 | 2,452 | 5.455621 | 0.532544 | 0.013557 | 0.018438 | 0.024946 | 0.130152 | 0.104121 | 0.073753 | 0.073753 | 0.073753 | 0.073753 | 0 | 0.003548 | 0.195351 | 2,452 | 49 | 119 | 50.040816 | 0.931069 | 0.840131 | 0 | 0 | 0 | 0 | 0.074576 | 0.074576 | 0 | 0 | 0 | 0 | 0 | 1 | 0.142857 | false | 0 | 0.142857 | 0 | 0.571429 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
4315b82fd67b35f3276f41c2f2b702f58e257be4 | 119 | py | Python | guppe/atividades/secao_4/ex004.py | WesleyLucas97/cursos_python | b2cbd393e8fed6e36b84253f7934766f2b4f1de8 | [
"MIT"
] | null | null | null | guppe/atividades/secao_4/ex004.py | WesleyLucas97/cursos_python | b2cbd393e8fed6e36b84253f7934766f2b4f1de8 | [
"MIT"
] | null | null | null | guppe/atividades/secao_4/ex004.py | WesleyLucas97/cursos_python | b2cbd393e8fed6e36b84253f7934766f2b4f1de8 | [
"MIT"
] | null | null | null | numero = float(input('Digite um número real: '))
numero = numero**2
print(f'O quadrado do número digitado é {numero}.') | 39.666667 | 51 | 0.714286 | 19 | 119 | 4.473684 | 0.789474 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.009709 | 0.134454 | 119 | 3 | 51 | 39.666667 | 0.815534 | 0 | 0 | 0 | 0 | 0 | 0.533333 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.333333 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
4316cf7086b7fe11c9ca0356776b7ffdac197c0b | 216 | py | Python | cosmic-core/systemvm/patches/centos7/opt/cosmic/router/bin/databag/cs_loadbalancer.py | sanderv32/cosmic | 9a9d86500b67255a1c743a9438a05c0d969fd210 | [
"Apache-2.0"
] | 64 | 2016-01-30T13:31:00.000Z | 2022-02-21T02:13:25.000Z | cosmic-core/systemvm/patches/centos7/opt/cosmic/router/bin/databag/cs_loadbalancer.py | sanderv32/cosmic | 9a9d86500b67255a1c743a9438a05c0d969fd210 | [
"Apache-2.0"
] | 525 | 2016-01-22T10:46:31.000Z | 2022-02-23T11:08:01.000Z | cosmic-core/systemvm/patches/centos7/opt/cosmic/router/bin/databag/cs_loadbalancer.py | sanderv32/cosmic | 9a9d86500b67255a1c743a9438a05c0d969fd210 | [
"Apache-2.0"
] | 25 | 2016-01-13T16:46:46.000Z | 2021-07-23T15:22:27.000Z | def merge(dbag, data):
""" Simply overwrite the existsing bag as, the whole configuration is sent every time """
if "rules" not in data:
return dbag
dbag['config'] = data['rules']
return dbag
| 30.857143 | 93 | 0.643519 | 30 | 216 | 4.633333 | 0.733333 | 0.143885 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | 216 | 6 | 94 | 36 | 0.858025 | 0.375 | 0 | 0.4 | 0 | 0 | 0.125984 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.2 | false | 0 | 0 | 0 | 0.6 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
4319d23620170cf888545186dea35e0eaf8eb3fe | 220 | py | Python | fastgplearn/__init__.py | boliqq07/fastgplearn | a740d1ea61823e53cd0aca360bac1758be115f96 | [
"MIT"
] | 1 | 2021-11-13T20:24:03.000Z | 2021-11-13T20:24:03.000Z | fastgplearn/__init__.py | boliqq07/fastgplearn | a740d1ea61823e53cd0aca360bac1758be115f96 | [
"MIT"
] | null | null | null | fastgplearn/__init__.py | boliqq07/fastgplearn | a740d1ea61823e53cd0aca360bac1758be115f96 | [
"MIT"
] | 1 | 2021-12-28T09:25:26.000Z | 2021-12-28T09:25:26.000Z | # -*- coding: utf-8 -*-
# @Time : 2021/11/1 9:19
# @Software : PyCharm
# @License : GNU General Public License v3.0
# @Author : xxx
__all__ = ["tools", "skflow", "sci_formula", "gp", "cli", "backend", "source"]
| 24.444444 | 78 | 0.581818 | 29 | 220 | 4.241379 | 0.965517 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.073864 | 0.2 | 220 | 8 | 79 | 27.5 | 0.625 | 0.581818 | 0 | 0 | 0 | 0 | 0.465116 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
43204b474684d8a07df003fb8370f84ddfc3d054 | 312 | py | Python | midca/modules/_adist/TestInterval.py | Heider1632/midca | ff61e1b291ae9a3aa784c75b4069f91884e26b2c | [
"MIT"
] | null | null | null | midca/modules/_adist/TestInterval.py | Heider1632/midca | ff61e1b291ae9a3aa784c75b4069f91884e26b2c | [
"MIT"
] | null | null | null | midca/modules/_adist/TestInterval.py | Heider1632/midca | ff61e1b291ae9a3aa784c75b4069f91884e26b2c | [
"MIT"
] | null | null | null | #!/usr/bin/python
from Interval import Interval
import random
#
# Simple code for testing the Interval module, and showing how it is used
#
interval = Interval(1.5, 2.5)
for i in range(1, 100):
interval.add(random.random() * 10)
print interval.getCount()
interval.clear()
print interval.getCount()
| 13.565217 | 73 | 0.714744 | 47 | 312 | 4.744681 | 0.659574 | 0.125561 | 0.188341 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.03876 | 0.173077 | 312 | 22 | 74 | 14.181818 | 0.825581 | 0.282051 | 0 | 0.25 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.25 | null | null | 0.25 | 0 | 0 | 0 | null | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
43222adcbb5c09e265de904b25ad733c3752fb9a | 190 | py | Python | evaluations/model/SFNDelay/functions/f2/lambda_function.py | pacslab/SLApp-PerfCost-MdlOpt | 9b9fb13b9e914a7fe5c89da570bd95baff73276e | [
"MIT"
] | 8 | 2020-08-07T02:03:02.000Z | 2022-03-02T10:27:14.000Z | evaluations/model/SFNDelay/functions/f2/lambda_function.py | pacslab/SLApp-PerfCost-MdlOpt | 9b9fb13b9e914a7fe5c89da570bd95baff73276e | [
"MIT"
] | null | null | null | evaluations/model/SFNDelay/functions/f2/lambda_function.py | pacslab/SLApp-PerfCost-MdlOpt | 9b9fb13b9e914a7fe5c89da570bd95baff73276e | [
"MIT"
] | 4 | 2020-08-24T14:35:41.000Z | 2021-04-23T18:57:45.000Z | import json
import time
def lambda_handler(event, context):
time.sleep(0.2)
return {
'statusCode': 200,
'body': json.dumps({'msg':'f2 sleep 200ms completed'})
}
| 19 | 62 | 0.610526 | 24 | 190 | 4.791667 | 0.833333 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.062937 | 0.247368 | 190 | 9 | 63 | 21.111111 | 0.741259 | 0 | 0 | 0 | 0 | 0 | 0.215789 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.125 | false | 0 | 0.25 | 0 | 0.5 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
432b5ef522608a47eeef5d3511a4f6936bcf0589 | 448 | py | Python | exam/notes/models.py | borko81/simple_django | b4faafe939e30998b1bd96aee1d0c83b242efc00 | [
"MIT"
] | 1 | 2021-08-04T19:44:20.000Z | 2021-08-04T19:44:20.000Z | exam/notes/models.py | borko81/simple_django | b4faafe939e30998b1bd96aee1d0c83b242efc00 | [
"MIT"
] | null | null | null | exam/notes/models.py | borko81/simple_django | b4faafe939e30998b1bd96aee1d0c83b242efc00 | [
"MIT"
] | null | null | null | from django.db import models
class Profile(models.Model):
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
age = models.PositiveIntegerField()
image_url = models.URLField()
def __str__(self):
return self.first_name + ' ' + self.last_name
class Note(models.Model):
title = models.CharField(max_length=30)
image_url = models.URLField()
content = models.TextField()
| 24.888889 | 53 | 0.705357 | 57 | 448 | 5.315789 | 0.508772 | 0.148515 | 0.178218 | 0.237624 | 0.19802 | 0.19802 | 0 | 0 | 0 | 0 | 0 | 0.016438 | 0.185268 | 448 | 17 | 54 | 26.352941 | 0.813699 | 0 | 0 | 0.166667 | 0 | 0 | 0.002232 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.083333 | false | 0 | 0.083333 | 0.083333 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
433a3dfc3d3a3724fca77ce59d7d10edf3e2958c | 826 | py | Python | apps/common/auth.py | gureuso/flask-movie | d06ca778f7bdb7eed53091aa4d09bad061829326 | [
"Apache-2.0"
] | null | null | null | apps/common/auth.py | gureuso/flask-movie | d06ca778f7bdb7eed53091aa4d09bad061829326 | [
"Apache-2.0"
] | null | null | null | apps/common/auth.py | gureuso/flask-movie | d06ca778f7bdb7eed53091aa4d09bad061829326 | [
"Apache-2.0"
] | 1 | 2021-11-15T05:26:44.000Z | 2021-11-15T05:26:44.000Z | # -*- coding: utf-8 -*-
import hashlib
from functools import wraps
from flask import redirect, url_for
from flask_login import current_user
class SHA256:
@staticmethod
def encrypt(value):
return hashlib.sha256(value.encode()).hexdigest()
@staticmethod
def compare_with(a, b):
return SHA256.encrypt(a) == SHA256.encrypt(b)
def already_signin(func):
@wraps(func)
def wrapper(*args, **kwargs):
if current_user.is_authenticated:
return redirect(url_for('showtimes.index'))
return func(*args, **kwargs)
return wrapper
def signin_required(func):
@wraps(func)
def wrapper(*args, **kwargs):
if not current_user.is_authenticated:
return redirect(url_for('users.signin'))
return func(*args, **kwargs)
return wrapper
| 23.6 | 57 | 0.662228 | 101 | 826 | 5.29703 | 0.415842 | 0.074766 | 0.078505 | 0.059813 | 0.426168 | 0.426168 | 0.302804 | 0.302804 | 0 | 0 | 0 | 0.020313 | 0.225182 | 826 | 34 | 58 | 24.294118 | 0.815625 | 0.025424 | 0 | 0.4 | 0 | 0 | 0.033624 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.24 | false | 0 | 0.16 | 0.08 | 0.76 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
433d7a6e218d4bf1bab7a0f231fcaf377964b596 | 885 | py | Python | documentation/models/parsers.py | rjvanvoorhis/photomosaic-api-v2 | 5da432e911c02f17f595ef056c45a5f4fd717738 | [
"MIT"
] | null | null | null | documentation/models/parsers.py | rjvanvoorhis/photomosaic-api-v2 | 5da432e911c02f17f595ef056c45a5f4fd717738 | [
"MIT"
] | null | null | null | documentation/models/parsers.py | rjvanvoorhis/photomosaic-api-v2 | 5da432e911c02f17f595ef056c45a5f4fd717738 | [
"MIT"
] | null | null | null | __all__ = ['upload_parser', 'paging_parser', 'gallery_parser', 'pending_parser']
from flask_restplus import reqparse
from werkzeug.datastructures import FileStorage
upload_parser = reqparse.RequestParser()
upload_parser.add_argument('file', location='files', type=FileStorage, required=True)
paging_parser = reqparse.RequestParser()
paging_parser.add_argument('skip', type=int)
paging_parser.add_argument('limit', type=int)
gallery_parser = reqparse.RequestParser()
gallery_parser.add_argument('mosaic_file', location='files', type=FileStorage, required=True)
gallery_parser.add_argument('alternate_file', location='files', type=FileStorage)
pending_parser = reqparse.RequestParser()
pending_parser.add_argument('frame', location='files', type=FileStorage, required=True)
pending_parser.add_argument('total_frames', type=int)
pending_parser.add_argument('progress', type=float)
| 38.478261 | 93 | 0.813559 | 108 | 885 | 6.37037 | 0.305556 | 0.104651 | 0.197674 | 0.162791 | 0.232558 | 0.186047 | 0.127907 | 0 | 0 | 0 | 0 | 0 | 0.063277 | 885 | 22 | 94 | 40.227273 | 0.829916 | 0 | 0 | 0 | 0 | 0 | 0.154802 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.133333 | 0 | 0.133333 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
4a33dfbd95b92d5dea832d1b9571ce2619cb2933 | 1,126 | py | Python | mr-owlf-dss/mr_owlf_dss/repository/domain.py | avcaliani/mr-owlf | 19eefb4a1535f64bee3347af0ea1a3ad84b036fd | [
"MIT"
] | 2 | 2021-02-15T14:02:56.000Z | 2021-03-14T15:07:11.000Z | mr-owlf-dss/mr_owlf_dss/repository/domain.py | avcaliani/mr-owlf | 19eefb4a1535f64bee3347af0ea1a3ad84b036fd | [
"MIT"
] | null | null | null | mr-owlf-dss/mr_owlf_dss/repository/domain.py | avcaliani/mr-owlf | 19eefb4a1535f64bee3347af0ea1a3ad84b036fd | [
"MIT"
] | null | null | null | from logging import getLogger
from bson.objectid import ObjectId
from pymongo.collection import Collection
from pymongo.database import Database
from pymongo.results import InsertOneResult, UpdateResult
class DomainRepository:
def __init__(self, db: Database):
self.log = getLogger('root')
self.collection: Collection = db['domains']
def find(self, name: str) -> any:
return self.collection.find_one({'domain': name})
def add(self, name: any, classification: str) -> None:
result: InsertOneResult = self.collection.insert_one({
'domain': name,
'classification': {classification: 1}
})
self.log.debug('Inserted domain: {0}'.format(result.inserted_id))
def update(self, _id: ObjectId, classification: str, count: int) -> None:
result: UpdateResult = self.collection.update_one(
{'_id': _id}, {"$set": {f"classification.{classification}": count}}
)
self.log.debug('Updated domains: {0}'.format(result.modified_count))
def count(self) -> int:
return self.collection.count_documents({})
| 34.121212 | 79 | 0.664298 | 125 | 1,126 | 5.88 | 0.376 | 0.095238 | 0.054422 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.003375 | 0.21048 | 1,126 | 32 | 80 | 35.1875 | 0.823397 | 0 | 0 | 0 | 0 | 0 | 0.102131 | 0.027531 | 0 | 0 | 0 | 0 | 0 | 1 | 0.208333 | false | 0 | 0.208333 | 0.083333 | 0.541667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
4a340a28de20b1f6c2fdb116c85d57b10729bb72 | 2,146 | py | Python | openpnm/topotools/generators/_delaunay.py | lixuekai2001/OpenPNM | 9026f0fed427d37f4caf1a79e4a7684490d52cf6 | [
"MIT"
] | 1 | 2021-12-06T03:20:55.000Z | 2021-12-06T03:20:55.000Z | openpnm/topotools/generators/_delaunay.py | lixuekai2001/OpenPNM | 9026f0fed427d37f4caf1a79e4a7684490d52cf6 | [
"MIT"
] | 2 | 2020-06-26T19:58:23.000Z | 2021-12-14T07:16:41.000Z | openpnm/topotools/generators/_delaunay.py | lixuekai2001/OpenPNM | 9026f0fed427d37f4caf1a79e4a7684490d52cf6 | [
"MIT"
] | null | null | null | import numpy as np
import scipy.spatial as sptl
from openpnm.topotools import tri_to_am
from openpnm.topotools.generators import tools
def delaunay(points, shape=[1, 1, 1]):
r"""
Generate a network based on Delaunay triangulation of random points
Parameters
----------
points : array_like or int
Can either be an N-by-3 array of point coordinates which will be used,
or a scalar value indicating the number of points to generate
shape : array_like
Indicates the size and shape of the domain
Returns
-------
network : dict
A dictionary containing 'vert.coords' and 'edge.conns'
tri : Delaunay tessellation object
The Delaunay tessellation object produced by ``scipy.spatial.Delaunay``
"""
points = tools.parse_points(points=points, shape=shape)
mask = ~np.all(points == 0, axis=0)
tri = sptl.Delaunay(points=points[:, mask])
coo = tri_to_am(tri)
d = {}
d['vert.coords'] = points
d['edge.conns'] = np.vstack((coo.row, coo.col)).T
return d, tri
if __name__ == "__main__":
# Make a 2D network based on number of points
dn, tri = delaunay(points=50, shape=[1, 1, 0])
print(dn.keys())
print(dn['vert.coords'].shape)
print(dn['edge.conns'].shape)
# Make a 2D network based on number of points
dn, tri = delaunay(points=50, shape=[1, 0, 1])
print(dn.keys())
print(dn['vert.coords'].shape)
print(dn['edge.conns'].shape)
# Make a 3D network based on number of points
dn, tri = delaunay(points=50, shape=[1, 1, 1])
print(dn.keys())
print(dn['vert.coords'].shape)
print(dn['edge.conns'].shape)
# Make a 3D cylinder
dn, tri = delaunay(points=50, shape=[1, 1])
print(dn.keys())
print(dn['vert.coords'].shape)
print(dn['edge.conns'].shape)
# Make a 2D circle
dn, tri = delaunay(points=50, shape=[1, 0])
print(dn.keys())
print(dn['vert.coords'].shape)
print(dn['edge.conns'].shape)
# Make a 3D sphere
dn, tri = delaunay(points=50, shape=[1])
print(dn.keys())
print(dn['vert.coords'].shape)
print(dn['edge.conns'].shape)
| 32.029851 | 79 | 0.635601 | 321 | 2,146 | 4.202492 | 0.283489 | 0.093403 | 0.057821 | 0.084507 | 0.4596 | 0.4596 | 0.4596 | 0.440326 | 0.401038 | 0.401038 | 0 | 0.022741 | 0.221342 | 2,146 | 66 | 80 | 32.515152 | 0.78456 | 0.33178 | 0 | 0.461538 | 1 | 0 | 0.113887 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.025641 | false | 0 | 0.102564 | 0 | 0.153846 | 0.461538 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 |
4a4ecaeb1dee9f5af8f289869ca470fd6ab2d25e | 73 | py | Python | config.py | QwertygidQ/phystech-backend | 657a5862d3bab91623551c7f4f6868cfdb1df4b8 | [
"MIT"
] | null | null | null | config.py | QwertygidQ/phystech-backend | 657a5862d3bab91623551c7f4f6868cfdb1df4b8 | [
"MIT"
] | null | null | null | config.py | QwertygidQ/phystech-backend | 657a5862d3bab91623551c7f4f6868cfdb1df4b8 | [
"MIT"
] | null | null | null | host = '0.0.0.0'
port = 8080
debug = True
CORS_HEADERS = 'Content-Type'
| 12.166667 | 29 | 0.657534 | 13 | 73 | 3.615385 | 0.769231 | 0.12766 | 0.12766 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.133333 | 0.178082 | 73 | 5 | 30 | 14.6 | 0.65 | 0 | 0 | 0 | 0 | 0 | 0.260274 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
4a4f3bcff96565505ef659d8630be28ec93fe4c7 | 4,660 | gyp | Python | build/system.gyp | rzr/crosswalk | 5bca7eba8898415cecfd7002c30f31ac1f51f8a2 | [
"BSD-3-Clause"
] | null | null | null | build/system.gyp | rzr/crosswalk | 5bca7eba8898415cecfd7002c30f31ac1f51f8a2 | [
"BSD-3-Clause"
] | null | null | null | build/system.gyp | rzr/crosswalk | 5bca7eba8898415cecfd7002c30f31ac1f51f8a2 | [
"BSD-3-Clause"
] | null | null | null | # Copyright (c) 2013 Intel Corporation. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets' : [
{
'target_name': 'gio',
'type': 'none',
'variables': {
'glib_packages': 'glib-2.0 gio-unix-2.0',
},
'direct_dependent_settings': {
'cflags': [
'<!@(pkg-config --cflags <(glib_packages))',
],
},
'link_settings': {
'ldflags': [
'<!@(pkg-config --libs-only-L --libs-only-other <(glib_packages))',
],
'libraries': [
'<!@(pkg-config --libs-only-l <(glib_packages))',
],
},
},
], # targets
'conditions': [
['tizen==1', {
'targets': [
{
'target_name': 'tizen_geolocation',
'type': 'none',
'variables': {
'packages': [
'capi-location-manager',
'vconf',
],
},
'direct_dependent_settings': {
'cflags': [
'<!@(pkg-config --cflags <@(packages))',
],
},
'link_settings': {
'ldflags': [
'<!@(pkg-config --libs-only-L --libs-only-other <@(packages))',
],
'libraries': [
'<!@(pkg-config --libs-only-l <@(packages))',
],
},
},
{
'target_name': 'tizen',
'type': 'none',
'variables': {
'packages': [
'ail',
'dlog',
'pkgmgr-parser',
'pkgmgr-info',
'pkgmgr-installer',
'pkgmgr',
'vconf',
],
},
'direct_dependent_settings': {
'cflags': [
'<!@(pkg-config --cflags <@(packages))',
],
},
'link_settings': {
'ldflags': [
'<!@(pkg-config --libs-only-L --libs-only-other <@(packages))',
],
'libraries': [
'<!@(pkg-config --libs-only-l <@(packages))',
],
},
},
{
'target_name': 'tizen_sensor',
'type': 'none',
'variables': {
'packages': [
'sensor',
'vconf',
],
},
'direct_dependent_settings': {
'cflags': [
'<!@(pkg-config --cflags <@(packages))',
],
},
'link_settings': {
'ldflags': [
'<!@(pkg-config --libs-only-L --libs-only-other <@(packages))',
],
'libraries': [
'<!@(pkg-config --libs-only-l <@(packages))',
],
},
},
{
'target_name': 'tizen_sysapps',
'type': 'none',
'variables': {
'packages': [
'vconf',
],
},
'direct_dependent_settings': {
'cflags': [
'<!@(pkg-config --cflags <@(packages))',
],
},
'link_settings': {
'ldflags': [
'<!@(pkg-config --libs-only-L --libs-only-other <@(packages))',
],
'libraries': [
'<!@(pkg-config --libs-only-l <@(packages))',
],
},
},
{
'target_name': 'tizen_appcore_common',
'type': 'none',
'variables': {
'packages': [
'appcore-common',
],
},
'direct_dependent_settings': {
'cflags': [
'<!@(pkg-config --cflags <@(packages))',
],
},
'link_settings': {
'ldflags': [
'<!@(pkg-config --libs-only-L --libs-only-other <@(packages))',
],
'libraries': [
'<!@(pkg-config --libs-only-l <@(packages))',
],
},
},
{
'target_name': 'tizen_vibration',
'type': 'none',
'variables': {
'packages': [
'haptic',
],
},
'direct_dependent_settings': {
'cflags': [
'<!@(pkg-config --cflags <@(packages))',
],
},
'link_settings': {
'ldflags': [
'<!@(pkg-config --libs-only-L --libs-only-other <@(packages))',
],
'libraries': [
'<!@(pkg-config --libs-only-l <@(packages))',
],
},
},
], # targets
}],
], # conditions
}
| 26.628571 | 77 | 0.364807 | 311 | 4,660 | 5.344051 | 0.231511 | 0.113718 | 0.109507 | 0.143201 | 0.663057 | 0.663057 | 0.663057 | 0.615523 | 0.615523 | 0.615523 | 0 | 0.003513 | 0.450215 | 4,660 | 174 | 78 | 26.781609 | 0.645199 | 0.03927 | 0 | 0.641176 | 0 | 0 | 0.42953 | 0.043848 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
4a51d0d8ecc14f97c7edc41489c955845b57117a | 553 | py | Python | app/active_learning/base_estimator.py | LennartKeller/datenbanken_app | 80675a78435f5d8d8f42da7e50ef761077c3db28 | [
"MIT"
] | null | null | null | app/active_learning/base_estimator.py | LennartKeller/datenbanken_app | 80675a78435f5d8d8f42da7e50ef761077c3db28 | [
"MIT"
] | null | null | null | app/active_learning/base_estimator.py | LennartKeller/datenbanken_app | 80675a78435f5d8d8f42da7e50ef761077c3db28 | [
"MIT"
] | null | null | null | class BaseActiveLearningComponent:
def fit(self, X, y):
"""
Fits the estimator and returns a reference to itself.
"""
return self
def partial_fit(self, X, y):
"""
Updates the estimator given the data X, y.
Returns a reference to itself.
"""
return self
def rank(self, X):
"""
Ranks the instances in X.
Returns a list of indices, sorted by relevance.
The first index points to the most useful instance.
"""
return None
| 24.043478 | 61 | 0.556962 | 67 | 553 | 4.58209 | 0.567164 | 0.04886 | 0.052117 | 0.058632 | 0.247557 | 0.247557 | 0.247557 | 0.247557 | 0 | 0 | 0 | 0 | 0.368897 | 553 | 22 | 62 | 25.136364 | 0.879656 | 0.457505 | 0 | 0.285714 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.428571 | false | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
4a558102f371ec020eecf3488805678518451ec7 | 161 | py | Python | Python Fundamentals/Functions/Lab/Task07.py | DonikaChervenkova/SoftUni | bff579c037ec48f39ed193b34bc3502a32e90732 | [
"MIT"
] | null | null | null | Python Fundamentals/Functions/Lab/Task07.py | DonikaChervenkova/SoftUni | bff579c037ec48f39ed193b34bc3502a32e90732 | [
"MIT"
] | null | null | null | Python Fundamentals/Functions/Lab/Task07.py | DonikaChervenkova/SoftUni | bff579c037ec48f39ed193b34bc3502a32e90732 | [
"MIT"
] | 1 | 2021-12-04T12:30:57.000Z | 2021-12-04T12:30:57.000Z | nums = [float(i) for i in input().split(" ")]
def rounding(numbers):
round_nums = [round(i) for i in numbers]
return round_nums
print(rounding(nums)) | 17.888889 | 45 | 0.658385 | 25 | 161 | 4.16 | 0.52 | 0.076923 | 0.096154 | 0.134615 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.192547 | 161 | 9 | 46 | 17.888889 | 0.8 | 0 | 0 | 0 | 0 | 0 | 0.006173 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.2 | false | 0 | 0 | 0 | 0.4 | 0.2 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
4a566acd2464623ce5800e576f2e16459bdbf955 | 1,244 | py | Python | flaskbb/utils/datastructures.py | chaomei412/flaskbb | 3e20b4fa24a7e03c935e6c90b17b5462765b734d | [
"BSD-3-Clause"
] | 8 | 2015-08-08T00:19:34.000Z | 2019-08-28T16:20:19.000Z | flaskbb/utils/datastructures.py | chaomei412/flaskbb | 3e20b4fa24a7e03c935e6c90b17b5462765b734d | [
"BSD-3-Clause"
] | 45 | 2021-03-22T07:15:27.000Z | 2021-12-23T21:07:10.000Z | flaskbb/utils/datastructures.py | chaomei412/flaskbb | 3e20b4fa24a7e03c935e6c90b17b5462765b734d | [
"BSD-3-Clause"
] | 6 | 2021-03-26T18:30:56.000Z | 2022-03-27T10:58:53.000Z | # -*- coding: utf-8 -*-
"""
flaskbb.utils.datastructures
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A few helpers that are used by flaskbb
:copyright: (c) 2014 by the FlaskBB Team.
:license: BSD, see LICENSE for more details.
"""
import sys
try:
from types import SimpleNamespace
except ImportError:
class SimpleNamespace(dict):
def __getattr__(self, name):
try:
return super(SimpleNamespace, self).__getitem__(name)
except KeyError:
raise AttributeError('{0} has no attribute {1}'
.format(self.__class__.__name__, name))
def __setattr__(self, name, value):
super(SimpleNamespace, self).__setitem__(name, value)
class TemplateEventResult(list):
"""A list subclass for results returned by the hook that
concatenates the results if converted to string, otherwise it works
exactly like any other list.
"""
def __init__(self, items):
list.__init__(self, items)
def __unicode__(self):
return u"".join(map(str, self))
def __str__(self):
if sys.version_info[0] >= 3:
return self.__unicode__()
return self.__unicode__().encode("utf-8")
| 28.272727 | 76 | 0.604502 | 139 | 1,244 | 5.057554 | 0.589928 | 0.01138 | 0.068279 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.011111 | 0.276527 | 1,244 | 43 | 77 | 28.930233 | 0.77 | 0.288585 | 0 | 0.090909 | 0 | 0 | 0.034565 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.227273 | false | 0 | 0.136364 | 0.045455 | 0.636364 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
4a8054488c75919f0b06e907a98f171049b95615 | 539 | py | Python | scale/diagnostic/apps.py | kaydoh/scale | 1b6a3b879ffe83e10d3b9d9074835a4c3bf476ee | [
"Apache-2.0"
] | 121 | 2015-11-18T18:15:33.000Z | 2022-03-10T01:55:00.000Z | scale/diagnostic/apps.py | kaydoh/scale | 1b6a3b879ffe83e10d3b9d9074835a4c3bf476ee | [
"Apache-2.0"
] | 1,415 | 2015-12-23T23:36:04.000Z | 2022-01-07T14:10:09.000Z | scale/diagnostic/apps.py | kaydoh/scale | 1b6a3b879ffe83e10d3b9d9074835a4c3bf476ee | [
"Apache-2.0"
] | 66 | 2015-12-03T20:38:56.000Z | 2020-07-27T15:28:11.000Z | """Defines the application configuration for the diagnostic application"""
from __future__ import unicode_literals
from django.apps import AppConfig
class DiagnosticConfig(AppConfig):
"""Configuration for the diagnostic app
"""
name = 'diagnostic'
label = 'diagnostic'
verbose_name = 'Diagnostic'
def ready(self):
"""Registers the diagnostic errors"""
from diagnostic.exceptions import TestException
from error.exceptions import register_error
register_error(TestException())
| 24.5 | 74 | 0.719852 | 54 | 539 | 7.037037 | 0.537037 | 0.102632 | 0.1 | 0.152632 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.205937 | 539 | 21 | 75 | 25.666667 | 0.88785 | 0.263451 | 0 | 0 | 0 | 0 | 0.07874 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.1 | false | 0 | 0.4 | 0 | 0.9 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
4a874f334b6bac75efb7df1d5596033502dbb47a | 1,177 | py | Python | src/bot_configuration.py | haejung83/slack-training-monitor-bot | 9259cfadb98e309f32756e459142fb07d8049ed3 | [
"Apache-2.0"
] | null | null | null | src/bot_configuration.py | haejung83/slack-training-monitor-bot | 9259cfadb98e309f32756e459142fb07d8049ed3 | [
"Apache-2.0"
] | null | null | null | src/bot_configuration.py | haejung83/slack-training-monitor-bot | 9259cfadb98e309f32756e459142fb07d8049ed3 | [
"Apache-2.0"
] | null | null | null | import json
import os
_CONSTANT_CONFIG_TOKEN = 'token'
_CONSTANT_CONFIG_GROUP_ID = 'group_id'
_CONSTANT_CONFIG_CHANNEL_NAME = 'channel_name'
class BotConfiguration:
def __init__(self):
self._config = None
def load(self, file):
file_path = os.path.dirname(__file__) + '/'+ file
print("[%s] Open file path: %s" %(__name__, file_path))
with open(file_path) as fd:
try:
read_data = fd.read()
loaded_dict = json.loads(read_data)
if loaded_dict is not None:
self._config = loaded_dict.copy()
except Exception as e:
print("[%s] %s" % (__name__, e))
def get_token(self):
return self._config[_CONSTANT_CONFIG_TOKEN]
def get_group_id(self):
return self._config[_CONSTANT_CONFIG_GROUP_ID]
def get_channel_name(self):
return self._config[_CONSTANT_CONFIG_CHANNEL_NAME]
def info(self):
print("[%s] Token: %s" %(__name__, self.get_token()))
print("[%s] Group ID: %s" %(__name__, self.get_group_id()))
print("[%s] Channel Name: %s" %(__name__, self.get_channel_name()))
| 29.425 | 75 | 0.610025 | 150 | 1,177 | 4.286667 | 0.28 | 0.130638 | 0.065319 | 0.093313 | 0.158631 | 0.158631 | 0 | 0 | 0 | 0 | 0 | 0 | 0.269329 | 1,177 | 39 | 76 | 30.179487 | 0.747674 | 0 | 0 | 0 | 0 | 0 | 0.091915 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.206897 | false | 0 | 0.068966 | 0.103448 | 0.413793 | 0.172414 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 2 |
4a88e86f1fd362d2e75c42ec3ad1d8ab2869d8ba | 2,369 | py | Python | us_congress/congress.py | drawjk705/us-congress | dedae9171953f770d9b6efe4f1e4db83f60dd4b4 | [
"MIT"
] | 1 | 2021-09-10T21:06:40.000Z | 2021-09-10T21:06:40.000Z | us_congress/congress.py | drawjk705/us-congress | dedae9171953f770d9b6efe4f1e4db83f60dd4b4 | [
"MIT"
] | null | null | null | us_congress/congress.py | drawjk705/us-congress | dedae9171953f770d9b6efe4f1e4db83f60dd4b4 | [
"MIT"
] | null | null | null | # pyright: reportUnknownMemberType=false
import os
from typing import cast
import dotenv
import pandas
import punq
from us_congress._api.fetch import CongressApiFetchService
from us_congress._api.interface import ICongressApiFetchService
from us_congress._client import CongressClient
from us_congress._config import CongressConfig
from us_congress._exceptions import NoCongressApiKeyException
from us_congress._members.interface import ICongressMemberRepository
from us_congress._members.service import CongressMemberRepository
from us_congress._transformation.interface import ICongressDataTransformationService
from us_congress._transformation.service import CongressDataTransformationService
from us_congress._utils.log.configureLogger import DEFAULT_LOGFILE, configureLogger
from us_congress._utils.log.factory import ILoggerFactory, LoggerFactory
_transformer = CongressDataTransformationService()
_loggerFactory = LoggerFactory()
class Congress:
_client: CongressClient
_config: CongressConfig
def __init__(self, congressNumber: int, logFile: str = DEFAULT_LOGFILE) -> None:
dotenvPath = dotenv.find_dotenv()
dotenv.load_dotenv(dotenvPath) # type: ignore
apiKey = os.getenv("PROPUBLICA_CONG_KEY")
if apiKey is None:
raise NoCongressApiKeyException(
"Could not find `PROPUBLICA_CONG_KEY in .env"
)
self._config = CongressConfig(congressNumber, apiKey)
container = punq.Container()
# singletons
container.register(ICongressDataTransformationService, instance=_transformer)
container.register(CongressConfig, instance=self._config)
container.register(ILoggerFactory, instance=_loggerFactory)
container.register(ICongressApiFetchService, CongressApiFetchService)
container.register(ICongressMemberRepository, CongressMemberRepository)
container.register(CongressClient)
configureLogger(logFile)
self._client = cast(CongressClient, container.resolve(CongressClient))
def getSenators(self) -> pandas.DataFrame:
return self._client.getSenators().copy(deep=True)
def getRepresentatives(self) -> pandas.DataFrame:
return self._client.getRepresentatives().copy(deep=True)
def __repr__(self) -> str:
return f"<Congress {self._config.congress}>"
| 35.358209 | 85 | 0.775011 | 223 | 2,369 | 8.008969 | 0.35426 | 0.036954 | 0.086226 | 0.019037 | 0.06383 | 0.039194 | 0 | 0 | 0 | 0 | 0 | 0 | 0.159561 | 2,369 | 66 | 86 | 35.893939 | 0.897037 | 0.026171 | 0 | 0 | 0 | 0 | 0.041685 | 0.010421 | 0 | 0 | 0 | 0 | 0 | 1 | 0.088889 | false | 0 | 0.355556 | 0.066667 | 0.577778 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
4aa6b3fe1216816de8f8229eb5fce883b3db50f2 | 45,030 | py | Python | svload/views.py | singleview-co-kr/django_etl | ba80e6bedf831c2b9519a9bfb8c29113bae95c22 | [
"BSD-3-Clause"
] | null | null | null | svload/views.py | singleview-co-kr/django_etl | ba80e6bedf831c2b9519a9bfb8c29113bae95c22 | [
"BSD-3-Clause"
] | 31 | 2021-09-06T05:27:43.000Z | 2022-02-17T05:05:01.000Z | svload/views.py | singleview-co-kr/django_etl | ba80e6bedf831c2b9519a9bfb8c29113bae95c22 | [
"BSD-3-Clause"
] | null | null | null | # import os.path
# begin - django related
from django.shortcuts import render, redirect
from django.views.generic import TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.conf import settings
# end - django related
# begin - bokeh related
from bokeh.embed import components
# end - bokeh related
from svcommon.sv_sql_raw import SvSqlAccess
from svtransform.models import BranchType
from svacct.models import DataSource
from svacct.models import DataSourceDetail
from svacct.models import DataSourceType
from svacct.ownership import get_owned_brand_list
from .pandas_plugins.period_window import PeriodWindow
from .pandas_plugins.edi_raw import EdiRaw
from .pandas_plugins.edi_filter import EdiFilter
from .pandas_plugins.budget import Budget
from .visualizer import Visualizer
# dash plotly visualiztion with AI ML
# https://www.youtube.com/watch?v=hSPmj7mK6ng
# python visualization with bokeh
# https://www.youtube.com/watch?v=2TR_6VaVSOs
# data visualization with D3.js
# https://www.youtube.com/watch?v=_8V5o2UHG0E
# Create your views here.
# https://hackernoon.com/integrating-bokeh-visualisations-into-django-projects-a1c01a16b67a
# bokeh server jinja example
# https://stackoverflow.com/questions/44878976/curdoc-add-root-causes-bokeh-plot-rendering-to-fail-silently
# jinja template tutorial
# https://www.webforefront.com/django/jinjaconfiguration.html
# for logger
import logging
logger = logging.getLogger(__name__)
AppVersion = '0.2.2'
LastModifiedDate = '1st, Aug 2021'
class FocusTodayGaMedia(LoginRequiredMixin, TemplateView):
# template_name = 'analyze/index.html'
__g_nCntToVisitorNounRank = 100 # 추출할 순위 수
__g_nCntToInboundKeywordRank = 10 # 추출할 순위 수
__g_nCntToSourceMediumRank = 10 # 추출할 순위 수
def __init__(self):
return
def get(self, request, *args, **kwargs):
o_window = PeriodWindow()
# o_window.activate_debug()
dict_period = o_window.get_period_range(request, s_freq_mode='day')
dict_sampling_freq_mode = o_window.get_sampling_freq_ui() # sampling freq btn UI
del o_window
o_sv_db = SvSqlAccess()
if not o_sv_db:
raise Exception('invalid db handler')
dict_rst = get_brand_info(o_sv_db, request, kwargs)
if dict_rst['b_error']:
dict_context = {'err_msg': dict_rst['s_msg']}
return render(request, "svload/analyze_deny.html", context=dict_context)
s_brand_name = dict_rst['dict_ret']['s_brand_name']
lst_owned_brand = dict_rst['dict_ret']['lst_owned_brand'] # for global navigation
from .pandas_plugins.ga_media import GmMainVisual
lst_retrieve_attrs = ['media_ua', 'media_rst_type', 'media_source', 'media_media', 'media_imp', 'media_click',
'media_term', 'media_brd', 'in_site_tot_session', 'in_site_tot_bounce',
'in_site_tot_duration_sec', 'in_site_tot_pvs', 'in_site_tot_new',
'media_gross_cost_inc_vat']
o_visualize = GmMainVisual(o_sv_db)
o_visualize.set_period_dict(dict_period, ['tm', 'lm'])
n_brand_id = dict_rst['dict_ret']['n_brand_id']
o_visualize.set_brand_id(n_brand_id)
o_visualize.load_df(lst_retrieve_attrs)
# get this month
s_sort_column = 'media_gross_cost_inc_vat' # 'gross_cpc_inc_vat'
dict_gross_tm = o_visualize.load_source_medium_ps_only('tm', s_sort_column=s_sort_column)
dict_mtd_tm = o_visualize.retrieve_mtd_by_column('tm')
dict_est_tm = o_visualize.retrieve_full_by_column('tm')
dict_mtd_by_mob, dict_mtd_by_pc = o_visualize.retrieve_period_by_ua_column('tm')
dict_top_kws, n_other_kws_cnt = o_visualize.retrieve_gross_term(s_period_window='tm',
s_sort_column='in_site_tot_session',
n_th_rank=self.__g_nCntToInboundKeywordRank)
dict_top_sources, n_other_source_cnt = \
o_visualize.retrieve_gross_source_medium(s_period_window='tm', s_sort_column='in_site_tot_session',
n_th_rank=self.__g_nCntToSourceMediumRank)
# plots can be a single Bokeh Model, a list/tuple, or even a dictionary
lst_graph_to_draw = o_visualize.get_graph_data()
dict_plots = {}
for lst_graph in lst_graph_to_draw:
o_graph = Visualizer()
o_graph.set_title(lst_graph[5])
o_graph.set_height(lst_graph[6])
o_graph.set_x_labels(lst_graph[2])
for s_source_medium_name, lst_series_val in lst_graph[1].items():
s_series_color = lst_graph[4].pop(0)
o_graph.append_series(s_source_medium_name, s_series_color, lst_series_val)
dict_plots[lst_graph[0]] = o_graph.draw_vertical_bar(n_max_y_axis=lst_graph[3])
del o_graph
# get last month
dict_mtd_lm = o_visualize.retrieve_mtd_by_column('lm')
script, div = components(dict(dict_plots))
return render(request, 'svload/ga_media_main.html',
{'script': script, 'div': div,
'dict_sampling_freq_mode': dict_sampling_freq_mode,
's_cur_period_window': dict_period['s_cur_period_window'],
'dict_period_date': {'from': dict_period['dt_first_day_this_month'].strftime("%Y%m%d"),
'to': dict_period['dt_today'].strftime("%Y%m%d")},
's_brand_name': s_brand_name,
'lst_owned_brand': lst_owned_brand, # for global navigation
'n_target_budget': dict_gross_tm['n_gross_budget_inc_vat'],
'dict_gross_tm': dict_gross_tm['dict_ps_source_medium_gross'],
'dict_mtd_tm': dict_mtd_tm,
'dict_est_tm': dict_est_tm,
'dict_mtd_lm': dict_mtd_lm,
'dict_mtd_by_mob': dict_mtd_by_mob,
'dict_mtd_by_pc': dict_mtd_by_pc,
'dict_top_kws': dict_top_kws,
'n_other_kws_cnt': n_other_kws_cnt,
'dict_top_sources': dict_top_sources,
'n_other_source_cnt': n_other_source_cnt,
'visitor_noun_n_th_rank': self.__g_nCntToVisitorNounRank,
'inbound_noun_n_th_rank': self.__g_nCntToInboundKeywordRank,
})
class BySourceMediumView(LoginRequiredMixin, TemplateView):
# template_name = 'analyze/index.html'
def __init__(self):
return
def get(self, request, *args, **kwargs):
o_window = PeriodWindow()
# o_window.activate_debug()
dict_period = o_window.get_period_range(request)
dict_sampling_freq_mode = o_window.get_sampling_freq_ui() # sampling freq btn UI
del o_window
o_sv_db = SvSqlAccess()
if not o_sv_db:
raise Exception('invalid db handler')
dict_rst = get_brand_info(o_sv_db, request, kwargs)
if dict_rst['b_error']:
dict_context = {'err_msg': dict_rst['s_msg']}
return render(request, "svload/analyze_deny.html", context=dict_context)
s_brand_name = dict_rst['dict_ret']['s_brand_name']
lst_owned_brand = dict_rst['dict_ret']['lst_owned_brand'] # for global navigation
# from .pandas_plugins.ga_media_source_medium import Performance
from .pandas_plugins.ga_media import SourceMediumVisual
lst_retrieve_attrs = ['media_ua', 'media_rst_type', 'media_source', 'media_media', 'media_imp', 'media_click',
'media_term', 'media_brd', 'in_site_tot_session', 'in_site_tot_bounce',
'in_site_tot_duration_sec', 'in_site_tot_pvs', 'in_site_tot_new',
'media_gross_cost_inc_vat']
o_visualize = SourceMediumVisual(o_sv_db)
o_visualize.set_period_dict(dict_period, ['tm', 'lm', 'ly'])
o_visualize.load_df(lst_retrieve_attrs)
s_sort_column = 'media_gross_cost_inc_vat' # 'gross_cpc_inc_vat'
dict_gross_tm = o_visualize.load_source_medium_ps_only('tm', s_sort_column=s_sort_column)
dict_gross_lm = o_visualize.load_source_medium_ps_only('lm', s_sort_column=s_sort_column)
dict_gross_ly = o_visualize.load_source_medium_ps_only('ly', s_sort_column=s_sort_column)
# if not b_rst_tm and not b_rst_lm and not b_rst_ly:
# dict_context = {'err_msg': 'period without data'}
# return render(request, "svload/analyze_deny.html", context=dict_context)
lst_graph_to_draw = o_visualize.get_graph_data()
# plots can be a single Bokeh Model, a list/tuple, or even a dictionary
dict_plots = {}
for lst_graph in lst_graph_to_draw:
o_graph = Visualizer()
o_graph.set_title(lst_graph[5])
o_graph.set_height(lst_graph[6])
o_graph.set_x_labels(lst_graph[2])
for s_source_medium_name, lst_series_val in lst_graph[1].items():
s_series_color = lst_graph[4].pop(0)
o_graph.append_series(s_source_medium_name, s_series_color, lst_series_val)
dict_plots[lst_graph[0]] = o_graph.draw_vertical_bar(n_max_y_axis=lst_graph[3])
del o_graph
script, graph = components(dict(dict_plots))
return render(request, 'svload/ga_media_by_source_medium.html',
{'script': script, 'graph': graph,
'dict_sampling_freq_mode': dict_sampling_freq_mode,
's_cur_period_window': dict_period['s_cur_period_window'],
'dict_period_date': {'from': dict_period['dt_first_day_this_month'].strftime("%Y%m%d"),
'to': dict_period['dt_today'].strftime("%Y%m%d")},
's_brand_name': s_brand_name,
'lst_owned_brand': lst_owned_brand, # for global navigation
'dict_gross_tm': dict_gross_tm['dict_ps_source_medium_gross'],
'dict_gross_lm': dict_gross_lm['dict_ps_source_medium_gross'],
'dict_gross_ly': dict_gross_ly['dict_ps_source_medium_gross']
})
class FocusTodayEdi(LoginRequiredMixin, TemplateView):
# template_name = 'analyze/index.html'
def __init__(self):
return
def get(self, request, *args, **kwargs):
o_window = PeriodWindow()
dict_period = o_window.get_period_range(request)
dict_sampling_freq_mode = o_window.get_sampling_freq_ui() # sampling freq btn UI
del o_window
o_sv_db = SvSqlAccess()
if not o_sv_db:
raise Exception('invalid db handler')
dict_rst = get_brand_info(o_sv_db, request, kwargs)
if dict_rst['b_error']:
dict_context = {'err_msg': dict_rst['s_msg']}
return render(request, "svload/analyze_deny.html", context=dict_context)
n_brand_id = dict_rst['dict_ret']['n_brand_id']
s_brand_name = dict_rst['dict_ret']['s_brand_name']
lst_owned_brand = dict_rst['dict_ret']['lst_owned_brand'] # for global navigation
# begin - retrieve emart sku info
o_filter = EdiFilter(request)
dict_sales_ch_info = o_filter.get_sales_ch()
dict_branch_info = o_filter.get_branch()
dict_sku_info = o_filter.get_sku_by_brand_id(o_sv_db, n_brand_id)
# print(dict_sku_info_by_id)
del o_filter
# end - retrieve emart sku info
o_edi_raw = EdiRaw()
o_edi_raw.set_period_dict(dt_start=dict_period['dt_first_day_2year_ago'], dt_end=dict_period['dt_today'])
o_edi_raw.set_freq(dict_sampling_freq_mode)
o_edi_raw.set_sku_dict(dict_sku_info['dict_sku_info_by_id'])
o_edi_raw.set_branch_info(dict_branch_info)
df_edi_raw = o_edi_raw.load_national(o_sv_db)
del o_edi_raw
del o_sv_db
from .pandas_plugins.edi_national import Performance
o_perf_to_visualize = Performance()
o_perf_to_visualize.set_period_dict(dict_period)
o_perf_to_visualize.set_sku_dict(dict_sku_info['dict_sku_info_by_id'])
o_perf_to_visualize.set_all_branches(dict_branch_info) # ['dict_branch_info_for_dataframe'])
o_perf_to_visualize.load_df(df_edi_raw)
dict_branch_gross = o_perf_to_visualize.retrieve_branch_gross_in_period() # arrange branches by tm amnt
lst_branch_data_table = o_perf_to_visualize.retrieve_branch_rank_in_period() # arrange branches by tm amnt
# begin - 당월 공급액 순위 & 당월 출고량 비교
dict_4_h_bar_graph = o_perf_to_visualize.retrieve_sku_rank_in_period()
dict_plots = {}
o_graph = Visualizer()
o_graph.set_title('품목별 총 공급액')
o_graph.set_height(400)
o_graph.set_x_labels(dict_4_h_bar_graph['lst_sku_name_by_tm_amnt'])
o_graph.append_series('2LY', dict_4_h_bar_graph['lst_bar_color'][0],
dict_4_h_bar_graph['lst_2ly_sku_by_tm_amnt'])
o_graph.append_series('LY', dict_4_h_bar_graph['lst_bar_color'][1], dict_4_h_bar_graph['lst_ly_sku_by_tm_amnt'])
o_graph.append_series('LM', dict_4_h_bar_graph['lst_bar_color'][2], dict_4_h_bar_graph['lst_lm_sku_by_tm_amnt'])
o_graph.append_series('TM', dict_4_h_bar_graph['lst_bar_color'][3], dict_4_h_bar_graph['lst_tm_sku_by_tm_amnt'])
dict_plots['sell_in_amnt'] = o_graph.draw_horizontal_bar()
# del dict_data
del o_graph
o_graph = Visualizer()
o_graph.set_title('품목별 총 출고량')
o_graph.set_height(400)
o_graph.set_x_labels(dict_4_h_bar_graph['lst_sku_name_by_tm_amnt'])
o_graph.append_series('2LY', dict_4_h_bar_graph['lst_bar_color'][0],
dict_4_h_bar_graph['lst_2ly_sku_by_tm_qty'])
o_graph.append_series('LY', dict_4_h_bar_graph['lst_bar_color'][1], dict_4_h_bar_graph['lst_ly_sku_by_tm_qty'])
o_graph.append_series('LM', dict_4_h_bar_graph['lst_bar_color'][2], dict_4_h_bar_graph['lst_lm_sku_by_tm_qty'])
o_graph.append_series('TM', dict_4_h_bar_graph['lst_bar_color'][3], dict_4_h_bar_graph['lst_tm_sku_by_tm_qty'])
dict_plots['sell_out_qty'] = o_graph.draw_horizontal_bar()
# del dict_data
del o_graph
# end - 당월 공급액 순위 & 당월 출고량 비교
# 퓸목별 현황 - top 10
dict_top_5_sku_table, n_sku_dashboard_div_height_px = o_perf_to_visualize.retrieve_top_sku_chronicle(20)
del o_perf_to_visualize
script, div = components(dict(dict_plots))
return render(request, 'svload/edi_main.html',
{'script': script, 'div': div,
'dict_sampling_freq_mode': dict_sampling_freq_mode,
's_cur_period_window': dict_period['s_cur_period_window'],
'dict_period_date': {'from': dict_period['dt_first_day_this_month'].strftime("%Y%m%d"),
'to': dict_period['dt_today'].strftime("%Y%m%d")},
's_brand_name': s_brand_name,
'lst_owned_brand': lst_owned_brand, # for global navigation
'dict_sales_ch_info_by_id': dict_sales_ch_info['dict_sales_ch_info_for_ui'],
's_sales_ch_filter_mode': dict_sales_ch_info['s_sales_ch_filter_mode'],
'dict_branch_info_by_id': dict_branch_info['dict_branch_info_for_ui'],
's_branch_filter_mode': dict_branch_info['s_branch_filter_mode'],
'dict_sku_info_by_id': dict_sku_info['dict_sku_info_for_ui'],
's_sku_filter_mode': dict_sku_info['s_sku_filter_mode'],
'dict_branch_gross': dict_branch_gross,
'lst_branch_data_table': lst_branch_data_table,
'dict_top_5_sku_table': dict_top_5_sku_table,
'n_sku_dashboard_div_height_px': n_sku_dashboard_div_height_px
})
class ByBranchEdi(LoginRequiredMixin, TemplateView):
# template_name = 'analyze/index.html'
def __init__(self):
return
def get(self, request, *args, **kwargs):
o_window = PeriodWindow()
dict_period = o_window.get_period_range(request)
dict_sampling_freq_mode = o_window.get_sampling_freq_ui() # sampling freq btn UI
del o_window
o_sv_db = SvSqlAccess()
if not o_sv_db:
raise Exception('invalid db handler')
dict_rst = get_brand_info(o_sv_db, request, kwargs)
if dict_rst['b_error']:
dict_context = {'err_msg': dict_rst['s_msg']}
return render(request, "svload/analyze_deny.html", context=dict_context)
n_brand_id = dict_rst['dict_ret']['n_brand_id']
s_brand_name = dict_rst['dict_ret']['s_brand_name']
n_branch_id = kwargs['branch_id']
lst_owned_brand = dict_rst['dict_ret']['lst_owned_brand'] # for global navigation
# begin - retrieve emart sku info
o_filter = EdiFilter(request)
dict_branch_info = o_filter.get_branch(n_branch_id)
dict_sku_info = o_filter.get_sku_by_brand_id(o_sv_db, n_brand_id)
del o_filter
# end - retrieve emart sku info
# begin - set branch name for template
dict_single_branch_info = list(dict_branch_info['dict_branch_info_for_ui'].values())[0]
s_sch_name = dict_single_branch_info['hypermart_name']
s_branch_name = dict_single_branch_info['name']
# end - set branch name for template
o_edi_raw = EdiRaw()
o_edi_raw.set_period_dict(dt_start=dict_period['dt_first_day_2year_ago'], dt_end=dict_period['dt_today'])
o_edi_raw.set_freq(dict_sampling_freq_mode)
o_edi_raw.set_sku_dict(dict_sku_info['dict_sku_info_by_id'])
o_edi_raw.set_branch_info(dict_branch_info)
df_edi_raw = o_edi_raw.load_branch(o_sv_db)
del o_edi_raw
from .pandas_plugins.edi_by_branch import Performance
# get whole period
o_whole_perf_summary = Performance()
o_whole_perf_summary.set_period_dict(dict_period)
o_whole_perf_summary.set_sku_dict(dict_sku_info['dict_sku_info_by_id'])
o_whole_perf_summary.set_single_branch_info(dict_branch_info)
o_whole_perf_summary.load_df(df_edi_raw)
dict_plots = {} # defaultdict() # graph dict to draw
# begin - 당월 품목별 공급액 순위, 당월 품목별 출고량 비교
dict_4_h_bar_graph = o_whole_perf_summary.retrieve_sku_rank_in_period('amount')
# plots can be a single Bokeh Model, a list/tuple, or even a dictionary
o_graph = Visualizer()
o_graph.set_title('품목별 총 공급액')
o_graph.set_height(380)
o_graph.set_x_labels(dict_4_h_bar_graph['lst_sku_name_by_tm_amnt'])
o_graph.append_series('2LY', '#D6E2DF', dict_4_h_bar_graph['dict_amnt_by_sku']['2ly'])
o_graph.append_series('LY', '#A4C8C1', dict_4_h_bar_graph['dict_amnt_by_sku']['ly'])
o_graph.append_series('LM', '#6CBDAC', dict_4_h_bar_graph['dict_amnt_by_sku']['lm'])
o_graph.append_series('TM', '#079476', dict_4_h_bar_graph['dict_amnt_by_sku']['tm'])
dict_plots['sell_in_amnt'] = o_graph.draw_horizontal_bar()
# del dict_data
del o_graph
o_graph = Visualizer()
o_graph.set_title('품목별 총 출고량')
o_graph.set_height(380)
o_graph.set_x_labels(dict_4_h_bar_graph['lst_sku_name_by_tm_amnt'])
o_graph.append_series('2LY', '#D6E2DF', dict_4_h_bar_graph['dict_qty_by_sku']['2ly'])
o_graph.append_series('LY', '#A4C8C1', dict_4_h_bar_graph['dict_qty_by_sku']['ly'])
o_graph.append_series('LM', '#6CBDAC', dict_4_h_bar_graph['dict_qty_by_sku']['lm'])
o_graph.append_series('TM', '#079476', dict_4_h_bar_graph['dict_qty_by_sku']['tm'])
dict_plots['sell_out_qty'] = o_graph.draw_horizontal_bar()
# del dict_data
del o_graph
# end - 당월 품목별 공급액 순위, 당월 품목별 출고량 비교
# begin - Top 4 공급액 추이 2년간
lst_item_line_color = ['#D6E2DF', '#A4C8C1', '#6CBDAC', '#079476'] # last one is larger one
dict_4_multi_line = o_whole_perf_summary.retrieve_monthly_chronicle_by_sku_ml(lst_item_line_color)
# dict_plots['monthly'] = draw_multi_line_graph(lst_line_data=dict_4_multi_line['lst_series_amnt'],
o_graph = Visualizer()
o_graph.set_title('Top4 품목의 공급액 추이')
o_graph.set_height(380)
o_graph.set_x_labels(dict_4_multi_line['lst_x_label'])
o_graph.append_series(dict_4_multi_line['lst_line_label'][0], dict_4_multi_line['lst_line_color'][0],
dict_4_multi_line['lst_series_amnt'][0])
o_graph.append_series(dict_4_multi_line['lst_line_label'][1], dict_4_multi_line['lst_line_color'][1],
dict_4_multi_line['lst_series_amnt'][1])
o_graph.append_series(dict_4_multi_line['lst_line_label'][2], dict_4_multi_line['lst_line_color'][2],
dict_4_multi_line['lst_series_amnt'][2])
o_graph.append_series(dict_4_multi_line['lst_line_label'][3], dict_4_multi_line['lst_line_color'][3],
dict_4_multi_line['lst_series_amnt'][3])
dict_plots['monthly'] = o_graph.draw_multi_line()
del o_graph
# end - Top 4 공급액 추이 2년간
# begin - 매장 공급액, 전국 공급액, 매장 출고량, 전국 출고량
dict_national_overview, dict_branch_overview = o_whole_perf_summary.retrieve_branch_level_overview(o_sv_db)
# end - 매장 공급액, 전국 공급액, 매장 출고량, 전국 출고량
del o_sv_db
# begin - 퓸목별 현황
dict_sku_perf_table = o_whole_perf_summary.retrieve_sku_chronicle()
# end - 퓸목별 현황
del o_whole_perf_summary
script, div = components(dict(dict_plots))
return render(request, 'svload/edi_by_branch.html',
{'script': script, 'div': div,
'dict_sampling_freq_mode': dict_sampling_freq_mode,
's_cur_period_window': dict_period['s_cur_period_window'],
'dict_period_date': {'from': dict_period['dt_first_day_this_month'].strftime("%Y%m%d"),
'to': dict_period['dt_today'].strftime("%Y%m%d")},
's_brand_name': s_brand_name,
's_sch_name': s_sch_name,
's_branch_name': s_branch_name,
'lst_owned_brand': lst_owned_brand, # for global navigation
'dict_branch_info': dict_single_branch_info,
'dict_national_overview': dict_national_overview,
'dict_branch_overview': dict_branch_overview,
'dict_all_sku_table': dict_sku_perf_table,
'BranchType': BranchType, # for naver map api permission
'ALLOWED_HOSTS': settings.ALLOWED_HOSTS # for naver map api permission
})
def post(self, request, *args, **kwargs):
o_sv_db = SvSqlAccess()
if not o_sv_db:
raise Exception('invalid db handler')
dict_rst = get_brand_info(o_sv_db, request, kwargs)
if dict_rst['b_error']:
dict_context = {'err_msg': dict_rst['s_msg']}
return render(request, "svload/analyze_deny.html", context=dict_context)
n_brand_id = dict_rst['dict_ret']['n_brand_id']
from .pandas_plugins.edi_by_branch import Performance
o_branch = Performance()
dict_rst = o_branch.add_memo(o_sv_db, int(kwargs['branch_id']), n_brand_id, request)
del o_branch
del o_sv_db
return
return redirect('svload:edi_branch', owner_id=kwargs['owner_id'], ga_view_id=kwargs['ga_view_id'],
branch_id=kwargs['branch_id'])
class BySkuEdi(LoginRequiredMixin, TemplateView):
# template_name = 'analyze/index.html'
def __init__(self):
return
def get(self, request, *args, **kwargs):
o_window = PeriodWindow()
dict_period = o_window.get_period_range(request)
dict_sampling_freq_mode = o_window.get_sampling_freq_ui() # sampling freq btn UI
del o_window
o_sv_db = SvSqlAccess()
if not o_sv_db:
raise Exception('invalid db handler')
dict_rst = get_brand_info(o_sv_db, request, kwargs)
if dict_rst['b_error']:
dict_context = {'err_msg': dict_rst['s_msg']}
return render(request, "svload/analyze_deny.html", context=dict_context)
n_brand_id = dict_rst['dict_ret']['n_brand_id']
s_brand_name = dict_rst['dict_ret']['s_brand_name']
lst_owned_brand = dict_rst['dict_ret']['lst_owned_brand'] # for global navigation
# begin - retrieve emart sku info
o_filter = EdiFilter(request)
dict_branch_info = o_filter.get_branch()
dict_sku_info = o_filter.get_sku_by_brand_id(o_sv_db, n_brand_id, n_sku_id=kwargs['item_id'])
del o_filter
# end - retrieve emart sku info
# set item name for template
s_item_name = dict_sku_info['dict_sku_info_by_id'][kwargs['item_id']]['mart_name'] + ' ' + \
dict_sku_info['dict_sku_info_by_id'][kwargs['item_id']]['name']
o_edi_raw = EdiRaw()
o_edi_raw.set_period_dict(dt_start=dict_period['dt_first_day_2year_ago'], dt_end=dict_period['dt_today'])
o_edi_raw.set_freq(dict_sampling_freq_mode)
o_edi_raw.set_sku_dict(dict_sku_info['dict_sku_info_by_id'])
o_edi_raw.set_branch_info(dict_branch_info)
df_edi_raw = o_edi_raw.load_sku(o_sv_db)
del o_edi_raw
del o_sv_db
from .pandas_plugins.edi_by_sku import Performance
# get whole period
o_whole_perf_summary = Performance()
o_whole_perf_summary.set_period_dict(dict_period)
o_whole_perf_summary.set_sku_dict(dict_sku_info['dict_sku_info_by_id'])
o_whole_perf_summary.set_all_branches(dict_branch_info)
o_whole_perf_summary.load_df(df_edi_raw)
dict_plots = {} # graph dict to draw
# begin - 당월 품목별 공급액 순위, 당월 품목별 출고량 비교
# end - 당월 품목별 공급액 순위, 당월 품목별 출고량 비교
# begin - 전국 공급액 추이 2년간
dict_rst_tm = o_whole_perf_summary.retrieve_monthly_gross_vb()
o_graph = Visualizer()
o_graph.set_title('최근 2년간 공급액')
o_graph.set_height(170)
o_graph.set_x_labels(dict_rst_tm['lst_x_labels'])
# for s_scope_name in dict_rst_tm['lst_series_lbl']:
for s_scope_name, lst_series_val in dict_rst_tm['lst_series_info'].items():
s_series_color = dict_rst_tm['lst_palette'].pop(0)
# lst_series_val = dict_rst_tm['lst_series_val'].pop(0)
o_graph.append_series(s_scope_name, s_series_color, lst_series_val)
dict_plots['monthly_national'] = o_graph.draw_vertical_bar(n_max_y_axis=None)
del o_graph
# end - 전국 공급액 추이 2년간
# begin - 상위 매장 공급액 추이 2년간
lst_item_line_color = ['#D6E2DF', '#A4C8C1', '#6CBDAC', '#079476', '#097C63',
'#026E57'] # last one is larger one
s_top_branch_cnt = str(len(lst_item_line_color))
# s_graph_title = '당월 Top ' + s_top_branch_cnt + ' 매장의 최근 2년간 공급액'
dict_rst_tm = o_whole_perf_summary.retrieve_monthly_gross_by_branch_vb(lst_item_line_color)
o_graph = Visualizer()
o_graph.set_title('당월 Top ' + s_top_branch_cnt + ' 매장의 최근 2년간 공급액')
o_graph.set_height(170)
o_graph.set_x_labels(dict_rst_tm['lst_x_labels'])
for s_branch_name, lst_series_val in dict_rst_tm['lst_series_info'].items():
s_series_color = dict_rst_tm['lst_palette'].pop(0)
o_graph.append_series(s_branch_name, s_series_color, lst_series_val)
dict_plots['monthly_branch_top4'] = o_graph.draw_vertical_bar(n_max_y_axis=None)
del o_graph
# end - Top4 공급액 추이 2년간
# begin - 매장 공급액, 전국 공급액, 매장 출고량, 전국 출고량
lst_branch_data_table = o_whole_perf_summary.retrieve_branch_overview()
# end - 매장 공급액, 전국 공급액, 매장 출고량, 전국 출고량
script, div = components(dict(dict_plots))
return render(request, 'svload/edi_by_sku.html',
{'script': script, 'div': div,
'dict_sampling_freq_mode': dict_sampling_freq_mode,
's_cur_period_window': dict_period['s_cur_period_window'],
'dict_period_date': {'from': dict_period['dt_first_day_this_month'].strftime("%Y%m%d"),
'to': dict_period['dt_today'].strftime("%Y%m%d")},
's_brand_name': s_brand_name,
'lst_owned_brand': lst_owned_brand, # for global navigation
's_item_name': s_item_name,
's_top_branch_cnt': s_top_branch_cnt,
'lst_branch_data_table': lst_branch_data_table
})
class BudgetView(LoginRequiredMixin, TemplateView):
__g_oSvDb = None
__g_dictBrandInfo = {}
def __init__(self):
self.__g_oSvDb = SvSqlAccess()
if not self.__g_oSvDb:
raise Exception('invalid db handler')
return
def __del__(self):
del self.__g_oSvDb
pass
def get(self, request, *args, **kwargs):
self.__g_dictBrandInfo = get_brand_info(self.__g_oSvDb, request, kwargs)
if self.__g_dictBrandInfo['b_error']:
dict_context = {'err_msg': self.__g_dictBrandInfo['s_msg']}
return render(request, "svload/analyze_deny.html", context=dict_context)
if 'budget_id' in list(kwargs.keys()):
return self.__budget_detail(request, *args, **kwargs)
else:
return self.__budget_list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
o_sv_db = SvSqlAccess()
if not o_sv_db:
raise Exception('invalid db handler')
dict_rst = get_brand_info(o_sv_db, request, kwargs)
if dict_rst['b_error']:
dict_context = {'err_msg': dict_rst['s_msg']}
return render(request, "svload/analyze_deny.html", context=dict_context)
n_brand_id = dict_rst['dict_ret']['n_brand_id']
s_act = request.POST.get('act')
s_return_url = request.META.get('HTTP_REFERER')
if s_act == 'add_budget':
# n_brand_id = dict_rst['dict_ret']['n_brand_id']
from .pandas_plugins.budget import Budget
o_budget = Budget(o_sv_db)
dict_rst = o_budget.add_budget(n_brand_id, request)
del o_budget
if dict_rst['b_error']:
dict_context = {'err_msg': dict_rst['s_msg'], 's_return_url': s_return_url}
return render(request, "svload/deny.html", context=dict_context)
o_redirect = redirect('svload:budget_list', sv_brand_id=n_brand_id)
if s_act == 'update_budget':
if request.POST['budget_id'] == '':
dict_context = {'err_msg': dict_rst['s_msg'], 's_return_url': s_return_url}
return render(request, "svload/deny.html", context=dict_context)
n_budget_id = int(request.POST['budget_id'])
from .pandas_plugins.budget import Budget
o_budget = Budget(o_sv_db)
o_budget.update_budget(n_budget_id, request)
del o_budget
o_redirect = redirect('svload:budget_list', sv_brand_id=n_brand_id)
elif s_act == 'inquiry_budget':
s_period_from = request.POST.get('budget_period_from')
s_period_to = request.POST.get('budget_period_to')
o_redirect = redirect('svload:budget_period',
sv_brand_id=n_brand_id, period_from=s_period_from, period_to=s_period_to)
del o_sv_db
return o_redirect
def __budget_list(self, request, *args, **kwargs):
lst_kwargs = list(kwargs.keys())
if 'period_from' in lst_kwargs:
s_period_from = kwargs['period_from']
else:
s_period_from = None
if 'period_to' in lst_kwargs:
s_period_to = kwargs['period_to']
else:
s_period_to = None
del lst_kwargs
from .pandas_plugins.budget import Budget
n_brand_id = self.__g_dictBrandInfo['dict_ret']['n_brand_id']
o_budget = Budget(self.__g_oSvDb)
dict_budget_info = o_budget.get_list_by_period(n_brand_id, s_period_from, s_period_to)
lst_acct_list = o_budget.get_acct_list_for_ui()
del o_budget
s_brand_name = self.__g_dictBrandInfo['dict_ret']['s_brand_name']
lst_owned_brand = self.__g_dictBrandInfo['dict_ret']['lst_owned_brand'] # for global navigation
return render(request, 'svload/budget_list.html',
{'s_brand_name': s_brand_name,
'lst_owned_brand': lst_owned_brand, # for global navigation
'dict_budget_period': dict_budget_info['dict_budget_period'],
'lst_budget_table': dict_budget_info['lst_added_rst'],
'dict_budget_progress': dict_budget_info['dict_budget_progress'],
'lst_acct_list': lst_acct_list,
})
def __budget_detail(self, request, *args, **kwargs):
lst_kwargs = list(kwargs.keys())
if 'budget_id' not in lst_kwargs:
raise Exception('invalid budget id')
if 'period_from' in lst_kwargs:
s_period_from = kwargs['period_from']
else:
s_period_from = None
if 'period_to' in lst_kwargs:
s_period_to = kwargs['period_to']
else:
s_period_to = None
del lst_kwargs
n_budget_id = kwargs['budget_id']
n_brand_id = self.__g_dictBrandInfo['dict_ret']['n_brand_id']
o_budget = Budget(self.__g_oSvDb)
dict_budget_info = o_budget.get_detail_by_id(n_brand_id, n_budget_id)
dict_budget_info['n_budget_id'] = n_budget_id
dict_period_info = {'s_earliest_budget': s_period_from, 's_latest_budget': s_period_to}
lst_acct_list = o_budget.get_acct_list_for_ui()
del o_budget
s_brand_name = self.__g_dictBrandInfo['dict_ret']['s_brand_name']
lst_owned_brand = self.__g_dictBrandInfo['dict_ret']['lst_owned_brand'] # for global navigation
return render(request, 'svload/budget_detail.html',
{'s_brand_name': s_brand_name,
'lst_owned_brand': lst_owned_brand, # for global navigation
'dict_budget_info': dict_budget_info,
'dict_budget_period': dict_period_info,
'lst_acct_list': lst_acct_list,
})
class Morpheme(LoginRequiredMixin, TemplateView):
# template_name = 'analyze/index.html'
__g_nCntToVisitorNounRank = 100 # 추출할 순위 수
__g_nCntToInboundKeywordRank = 10 # 추출할 순위 수
__g_nCntToSourceMediumRank = 10 # 추출할 순위 수
def __init__(self):
return
def get(self, request, *args, **kwargs):
o_window = PeriodWindow()
dict_period = o_window.get_period_range(request)
dict_sampling_freq_mode = o_window.get_sampling_freq_ui() # sampling freq btn UI
del o_window
o_sv_db = SvSqlAccess()
if not o_sv_db:
raise Exception('invalid db handler')
dict_rst = get_brand_info(o_sv_db, request, kwargs)
if dict_rst['b_error']:
dict_context = {'err_msg': dict_rst['s_msg']}
return render(request, "svload/analyze_deny.html", context=dict_context)
s_brand_name = dict_rst['dict_ret']['s_brand_name']
lst_owned_brand = dict_rst['dict_ret']['lst_owned_brand'] # for global navigation
from .pandas_plugins.word_cloud import WcMainVisual
o_word_cloud = WcMainVisual(o_sv_db)
lst_period = ['ly', 'lm', 'tm']
o_word_cloud.set_period_dict(dict_period, lst_period)
o_word_cloud.load_df()
dict_config = {'n_brand_id': dict_rst['dict_ret']['n_brand_id'],
's_static_file_path': settings.STATICFILES_DIRS[0],
's_media_file_path': settings.MEDIA_ROOT,
's_media_url_root': settings.MEDIA_URL,
'lst_period': lst_period, 'n_th_rank': self.__g_nCntToVisitorNounRank}
dict_wc_rst = o_word_cloud.get_top_ranker(dict_config)
del o_word_cloud, dict_config
# script, div = components(dict(dict_plots))
return render(request, 'svload/morpheme.html',
{ # 'script': script, 'div': div,
'dict_sampling_freq_mode': dict_sampling_freq_mode,
's_cur_period_window': dict_period['s_cur_period_window'],
'dict_period_date': {'from': dict_period['dt_first_day_this_month'].strftime("%Y%m%d"),
'to': dict_period['dt_today'].strftime("%Y%m%d")},
's_brand_name': s_brand_name,
'lst_owned_brand': lst_owned_brand, # for global navigation
'lst_top_word_by_freq_trend': dict_wc_rst['lst_top_word_by_freq_trend'],
'visitor_noun_n_th_rank': self.__g_nCntToVisitorNounRank,
'dict_misc_word_cnt': dict_wc_rst['dict_misc_word_cnt'],
'dict_word_cloud_img_url': dict_wc_rst['dict_word_cloud_img_url']
})
def post(self, request, *args, **kwargs):
o_sv_db = SvSqlAccess()
if not o_sv_db:
raise Exception('invalid db handler')
dict_rst = get_brand_info(o_sv_db, request, kwargs)
if dict_rst['b_error']:
dict_context = {'err_msg': dict_rst['s_msg']}
return render(request, "svload/analyze_deny.html", context=dict_context)
dict_rst = get_brand_info(o_sv_db, request, kwargs)
if dict_rst['b_error']:
dict_context = {'err_msg': dict_rst['s_msg']}
return render(request, "svload/analyze_deny.html", context=dict_context)
s_brand_name = dict_rst['dict_ret']['s_brand_name']
lst_owned_brand = dict_rst['dict_ret']['lst_owned_brand'] # for global navigation
s_act = request.POST.get('act')
s_return_url = request.META.get('HTTP_REFERER')
if s_act == 'search_morpheme':
s_morpheme_query = request.POST.get('morpheme_query')
from .pandas_plugins.word_cloud import MorphemeVisual
o_morpheme = MorphemeVisual(o_sv_db)
dict_rst = o_morpheme.get_morpheme_id_by_morpheme(s_morpheme_query)
del o_morpheme
if dict_rst['b_error']:
dict_context = {'err_msg': dict_rst['s_msg'], 's_return_url': s_return_url}
return render(request, "svload/deny.html", context=dict_context)
return render(request, "svload/morpheme.html",
context={ # 'dict_sampling_freq_mode': dict_sampling_freq_mode,
's_brand_name': s_brand_name,
'lst_owned_brand': lst_owned_brand, # for global navigation
's_morpheme_query': s_morpheme_query,
'lst_relevant_morpheme': dict_rst['lst_morpheme'],
})
del o_sv_db
class MorphemeChronicle(LoginRequiredMixin, TemplateView):
# template_name = 'analyze/index.html'
def __init__(self):
return
def get(self, request, *args, **kwargs):
o_window = PeriodWindow()
dict_period = o_window.get_period_range(request)
dict_sampling_freq_mode = o_window.get_sampling_freq_ui() # sampling freq btn UI
del o_window
o_sv_db = SvSqlAccess()
if not o_sv_db:
raise Exception('invalid db handler')
dict_rst = get_brand_info(o_sv_db, request, kwargs)
if dict_rst['b_error']:
dict_context = {'err_msg': dict_rst['s_msg']}
return render(request, "svload/analyze_deny.html", context=dict_context)
s_brand_name = dict_rst['dict_ret']['s_brand_name']
lst_owned_brand = dict_rst['dict_ret']['lst_owned_brand'] # for global navigation
# if 'morpheme_id' in kwargs.keys(): # 7,21,758
from .pandas_plugins.word_cloud import MorphemeVisual
o_morpheme_chronicle = MorphemeVisual(o_sv_db)
lst_period = ['2ly', 'ly', 'lm', 'tm']
dict_url_rst = {'b_error': False, 's_msg': None}
if request.method == 'GET' and 'morpheme_id' in request.GET:
s_morpheme_ids = request.GET['morpheme_id']
lst_morpheme_id = s_morpheme_ids.split(',')
for x in lst_morpheme_id:
if not x.isdigit():
dict_url_rst['b_error'] = True
dict_url_rst['s_msg'] = 'invalid morpheme id'
break
else:
dict_url_rst['b_error'] = True
dict_url_rst['s_msg'] = 'invalid approach'
if dict_url_rst['b_error']:
dict_context = {'err_msg': dict_url_rst['s_msg']}
return render(request, "svload/analyze_deny.html", context=dict_context)
lst_morpheme_id = [int(x.strip()) for x in lst_morpheme_id] # ?morpheme_id=7,21,758
# begin -
lst_item_line_color = ['#D6E2DF', '#A4C8C1', '#6CBDAC', '#079476', '#960614', '#6b0000', '#205a86', '#140696',
'#4d6165', '#798984', '#8db670', '#ffad60'] # last one is the largest
n_max_morpheme_cnt = len(lst_item_line_color)
o_morpheme_chronicle.set_period_dict(dict_period, lst_period)
o_morpheme_chronicle.set_freq(dict_sampling_freq_mode)
o_morpheme_chronicle.set_morpheme_lst(lst_morpheme_id[:n_max_morpheme_cnt])
o_morpheme_chronicle.load_df()
dict_plots = {} # graph dict to draw
dict_4_multi_line = o_morpheme_chronicle.retrieve_daily_chronicle_by_morpheme_ml(lst_item_line_color)
o_graph = Visualizer()
o_graph.set_height(170)
o_graph.set_x_labels(dict_4_multi_line['lst_x_label'])
n_morpheme_cnt = len(dict_4_multi_line['lst_line_label'])
n_gross_freq = 0
for n_idx in range(0, n_morpheme_cnt):
o_graph.append_series(dict_4_multi_line['lst_line_label'][n_idx],
dict_4_multi_line['lst_line_color'][n_idx],
dict_4_multi_line['lst_series_cnt'][n_idx])
n_gross_freq = n_gross_freq + sum(dict_4_multi_line['lst_series_cnt'][n_idx])
o_graph.set_title('선택 단어는 총 ' + "{:,}".format(n_gross_freq) + '회 발생함')
dict_plots['morpheme_daily'] = o_graph.draw_multi_line()
del o_graph
# end -
script, div = components(dict(dict_plots))
return render(request, 'svload/morpheme_chronicle.html',
{'script': script, 'div': div,
'dict_sampling_freq_mode': dict_sampling_freq_mode,
's_brand_name': s_brand_name,
'lst_owned_brand': lst_owned_brand, # for global navigation
})
def get_brand_info(o_db, request, kwargs):
dict_rst = {'b_error': False, 's_msg': None, 'dict_ret': None}
dict_owned_brand = get_owned_brand_list(request, kwargs)
s_tbl_prefix = None
n_brand_id = None
s_brand_name = None
lst_owned_brand = []
for _, dict_single_acct in dict_owned_brand.items():
lst_owned_brand += dict_single_acct['lst_brand']
for dict_single_brand in dict_single_acct['lst_brand']:
if dict_single_brand['b_current_brand']:
s_tbl_prefix = str(dict_single_acct['n_acct_id'])
n_brand_id = dict_single_brand['n_brand_id']
s_brand_name = dict_single_brand['s_brand_ttl']
break
if not s_tbl_prefix or not n_brand_id:
dict_rst['b_error'] = True
dict_rst['s_msg'] = 'not allowed brand'
return dict_rst
o_db.set_tbl_prefix(s_tbl_prefix)
o_db.set_app_name(__name__)
o_db.initialize({'n_acct_id': s_tbl_prefix, 'n_brand_id': n_brand_id})
o_db.set_reserved_tag_value({'brand_id': n_brand_id})
dict_rst['s_msg'] = 'success'
dict_rst['dict_ret'] = {'n_brand_id': n_brand_id,
# 'n_owner_id': request.user.pk, 'n_ga_view_id': n_ga_view_id,
's_brand_name': s_brand_name, 'lst_owned_brand': lst_owned_brand}
return dict_rst
| 48.681081 | 120 | 0.640306 | 6,290 | 45,030 | 4.094754 | 0.071065 | 0.019801 | 0.010095 | 0.010483 | 0.793019 | 0.741381 | 0.691683 | 0.656041 | 0.633367 | 0.61442 | 0 | 0.009589 | 0.261226 | 45,030 | 924 | 121 | 48.733766 | 0.764632 | 0.087964 | 0 | 0.59691 | 0 | 0 | 0.172269 | 0.04336 | 0 | 0 | 0 | 0 | 0 | 1 | 0.032303 | false | 0.001404 | 0.04073 | 0.009831 | 0.151685 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
4aae0eb636c274804a52935a40f05fdafb9f4950 | 762 | py | Python | app/app.py | mtsulek/flask-project | 07ce98077cff52df0ac82e4ff337e3a135b82192 | [
"Apache-2.0"
] | null | null | null | app/app.py | mtsulek/flask-project | 07ce98077cff52df0ac82e4ff337e3a135b82192 | [
"Apache-2.0"
] | null | null | null | app/app.py | mtsulek/flask-project | 07ce98077cff52df0ac82e4ff337e3a135b82192 | [
"Apache-2.0"
] | null | null | null | """This module contains flask app and its routes"""
from flask import Flask, request
from app.settings import DevConfiguration, ProdConfiguration
def create_app(configuration_py_file) -> Flask:
"""This function is initiating flask application. Consists route paths"""
app = Flask(__name__)
app.config.from_object(configuration_py_file)
@app.route('/')
def hello() -> str:
"""Hello world method"""
return 'Hello, I am a simple flask app!'
@app.route('/register', methods=['POST'])
def register() -> dict:
"""Registering new users"""
json = request.get_json()
login = json['login']
password = json['password']
return {"login": login, "password": password}
return app
| 26.275862 | 77 | 0.645669 | 89 | 762 | 5.404494 | 0.550562 | 0.033264 | 0.079002 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.227034 | 762 | 28 | 78 | 27.214286 | 0.816638 | 0.2021 | 0 | 0 | 0 | 0 | 0.120954 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.2 | false | 0.133333 | 0.133333 | 0 | 0.533333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 2 |
4ab0520ab3fd527fa8373a63fc92bd1008aa0e0e | 190 | py | Python | Chapter02/requests/send_cookies.py | yangwawa0323/Learning-Python-Networking-Second-Edition | 5460fe4fb6acc5d0df19bf36e52ac09e9a11eb8b | [
"MIT"
] | 52 | 2018-12-17T19:33:06.000Z | 2022-03-25T18:14:02.000Z | Chapter02/requests/send_cookies.py | barretthugh/Learning-Python-Networking-Second-Edition | 0f00b8b20c1c85e76754e47113dff8ca9e99d5ca | [
"MIT"
] | null | null | null | Chapter02/requests/send_cookies.py | barretthugh/Learning-Python-Networking-Second-Edition | 0f00b8b20c1c85e76754e47113dff8ca9e99d5ca | [
"MIT"
] | 38 | 2018-12-18T09:08:43.000Z | 2022-02-06T02:53:05.000Z | #!/usr/bin/env python3
import requests
cookies = []
url = 'http://httpbin.org/cookies'
cookies = dict(admin='True')
cookie_req = requests.get(url, cookies=cookies)
print(cookie_req.text)
| 17.272727 | 47 | 0.726316 | 27 | 190 | 5.037037 | 0.703704 | 0.205882 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.005917 | 0.110526 | 190 | 10 | 48 | 19 | 0.798817 | 0.110526 | 0 | 0 | 0 | 0 | 0.178571 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.166667 | 0 | 0.166667 | 0.166667 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
4ab2db6ee68cdd823ea844a9ebd3854a73d44f4d | 2,187 | py | Python | 04. cmath module.py | ahammadshawki8/Standerd-Libraries-of-Python | cec8e21e5ac667b8a208c86709ee2ef783d28149 | [
"MIT"
] | null | null | null | 04. cmath module.py | ahammadshawki8/Standerd-Libraries-of-Python | cec8e21e5ac667b8a208c86709ee2ef783d28149 | [
"MIT"
] | null | null | null | 04. cmath module.py | ahammadshawki8/Standerd-Libraries-of-Python | cec8e21e5ac667b8a208c86709ee2ef783d28149 | [
"MIT"
] | null | null | null | # cmath module
# cmath stands for complex math
# it is simmilar as math module, but it has less functions and attributes compared to math module.
# the functions and attributes name are same as math module but they can work with complex number too.
# first we need to import the module
import cmath
# lets see the directory to find the name of functions and attributes.
print(dir(cmath))
# we can see that here we have:-
# ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh',
# 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'inf', 'infj', 'isclose', 'isfinite', 'isinf', 'isnan',
# 'log', 'log10', 'nan', 'nanj', 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau']
# first of all,
# NOTE that we can even create complex number without cmath module, we can do that by complex() method.
# then we can work with those numbers.
print(complex(2.5,4.5))
# it takes real part as the first arguement and imaginary part as the second arguement
# then it multiply the imaginary part with sqrt of -1 and create the complex number.
# we can see that we have trigonometeric functions.
# sin
# cos
# tan
# asin(arcsin)
# acos(arccos)
# atan(arctan)
# we also have hyperbolic functions.
# sinh
# cosh
# tanh
# asinh(arcsinh)
# acosh(arccosh)
# atanh(arctanh)
# we also have
# nan
# nanj
# nanj gives us Complex number with zero real part and NaN imaginary part.
# it is Equivalent to complex(0.0, float('nan')).
# isnan
# inf
# infj
# infj gives us Complex number with zero real part and positive infinity imaginary part
# it is Equivalent to complex(0.0, float('inf')).
# isinf
# isfinite
# we have logarithmic function
# log
# log10
# we have some constants
# e
# pie
# tau
# we also have
# sqrt
# exp
# we can print the phase angle of a complex by phase() function.
a=cmath.sqrt(-1)
print(cmath.phase(2+3*a))
# we can Convert a complex from rectangular coordinates to polar coordinatesn using polar() function.
print(cmath.polar(a))
# we can Convert a complex from polar coordinates to rectangular coordinatesn using rect() function.
print(cmath.rect(1.0, 1.5707963267948966)) | 28.776316 | 110 | 0.697759 | 337 | 2,187 | 4.468843 | 0.385757 | 0.02656 | 0.043825 | 0.01992 | 0.142098 | 0.142098 | 0.142098 | 0.108898 | 0.108898 | 0.057105 | 0 | 0.019685 | 0.187014 | 2,187 | 76 | 111 | 28.776316 | 0.827334 | 0.854595 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.142857 | 0 | 0.142857 | 0.714286 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 |
4ab840ba83a67bda050f8428998d6877ee60efdc | 2,601 | py | Python | bowling/game.py | pktippa/bowling_game | 2f4f7564c5c87b7331d3ee8552ad7a37d3f63805 | [
"MIT"
] | null | null | null | bowling/game.py | pktippa/bowling_game | 2f4f7564c5c87b7331d3ee8552ad7a37d3f63805 | [
"MIT"
] | null | null | null | bowling/game.py | pktippa/bowling_game | 2f4f7564c5c87b7331d3ee8552ad7a37d3f63805 | [
"MIT"
] | null | null | null | class Game(object):
def __init__(self, game_pairs=0):
self.throws = []
self.game_pairs = game_pairs
def __call__(self, game_pairs=0):
self.game_pairs = game_pairs
def add_throw(self, throw):
self.throws.append(throw)
def check_value_range(self, value):
if value < 0 or value > 10:
print('Exception Scenario')
raise Exception('Values not in range')
def get_total(self):
# initializing total score , throw index to 0
total_score = 0
throw_ind = 0
for pair in range(self.game_pairs):
#print('ind ', throw_ind, ' val ', self.throws[throw_ind], ' game pair ', self.game_pairs)
self.check_value_range(self.throws[throw_ind])
# Checking for strike
if self.throws[throw_ind] == 10:
# if it is last but one
if pair == self.game_pairs - 2:
self.check_value_range(self.throws[throw_ind] + 1)
if self.throws[throw_ind+1] == 10:
total_score += 30
else:
self.check_value_range(self.throws[throw_ind + 2])
total_score += 10 + self.throws[throw_ind+1] + self.throws[throw_ind + 2]
# checking for last one
elif pair == self.game_pairs - 1:
total_score += 30
else:
self.check_value_range(self.throws[throw_ind + 1])
self.check_value_range(self.throws[throw_ind + 2])
total_score += 10 + self.throws[throw_ind+1] + self.throws[throw_ind + 2]
throw_ind += 1
# checking for sparse
else:
self.check_value_range(self.throws[throw_ind + 1])
if self.throws[throw_ind] + self.throws[throw_ind + 1] == 10:
# if it is last one
#print('--- pair', pair)
if pair == self.game_pairs -1:
total_score += 10 + self.throws[throw_ind]
else:
self.check_value_range(self.throws[throw_ind + 2])
total_score += 10 + self.throws[throw_ind + 2]
throw_ind += 2
else:
total_score += self.throws[throw_ind] + self.throws[throw_ind + 1]
throw_ind += 2
print('Pair ', pair,'Score till now', total_score)
return total_score
def __main__():
pass | 41.951613 | 102 | 0.510188 | 309 | 2,601 | 4.048544 | 0.174757 | 0.159872 | 0.239808 | 0.28777 | 0.610711 | 0.534772 | 0.490807 | 0.42446 | 0.394884 | 0.35012 | 0 | 0.029206 | 0.394464 | 2,601 | 62 | 103 | 41.951613 | 0.765079 | 0.098808 | 0 | 0.375 | 0 | 0 | 0.023973 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.125 | false | 0.020833 | 0 | 0 | 0.166667 | 0.041667 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
4abf8cb61c41a275b78075582a14d3e5b796c342 | 3,858 | py | Python | misc/custom_fitter.py | joniumGit/moons | f5f8b7e23e707c8cf7e1081c4a1c0fcc22182d85 | [
"MIT"
] | 1 | 2021-07-16T06:30:37.000Z | 2021-07-16T06:30:37.000Z | misc/custom_fitter.py | joniumGit/moons | f5f8b7e23e707c8cf7e1081c4a1c0fcc22182d85 | [
"MIT"
] | null | null | null | misc/custom_fitter.py | joniumGit/moons | f5f8b7e23e707c8cf7e1081c4a1c0fcc22182d85 | [
"MIT"
] | 1 | 2021-05-26T03:53:41.000Z | 2021-05-26T03:53:41.000Z | from typing import Tuple
import numpy as np
from scipy.optimize import least_squares
from sklearn.base import BaseEstimator, RegressorMixin
from sklearn.utils.validation import check_X_y
from sklearn.utils.validation import check_array, check_is_fitted
class OnePerRegression(RegressorMixin, BaseEstimator):
"""
Regression model for k * x ** a + b
"""
def __init__(self, initial_guess: Tuple[float, float, float] = (1, -1, 0)):
"""
initial_guess:
- Tuple[float, float, float]
- k * x ^ a + b (k, a, b)
Constrained as follows:
- k[0,INF]
- a[-15,0]
- b[0,INF]
"""
super(OnePerRegression, self).__init__()
self.initial_guess = initial_guess
def _constraint(self):
# return np.asarray((
# [0, -15, 0],
# [np.inf, -1, np.inf]
# ))
return np.asarray((
[-np.inf, -np.inf, -np.inf],
[np.inf, np.inf, np.inf]
))
def _more_tags(self):
return {
"poor_score": True
}
def fun(self, guess):
k, a, b = guess[0:3]
return self.y_ - k * np.float_power(self.x_, a) + b
def fit(self, X, y):
if y is None:
raise ValueError()
x, y = check_X_y(X, y, y_numeric=True, force_all_finite=True, dtype='float64')
self.n_features_in_ = x.shape[1]
self.x_ = np.average(x, axis=1)
self.y_ = y
solution = least_squares(
self.fun,
np.asarray(self.initial_guess).astype('float64'),
bounds=self._constraint(),
loss='linear',
)
self.coef_ = [solution.x[0], solution.x[1]]
self.intercept_ = solution.x[2]
return self
def predict(self, X):
check_is_fitted(self, 'coef_')
x: np.ndarray = check_array(X, force_all_finite=True, dtype='float64')
if x.shape[1] != self.n_features_in_:
raise ValueError("Wrong number of features")
x = np.average(X, axis=1)
return self.coef_[0] * np.float_power(x, self.coef_[1]) + self.intercept_
class ReciprocalRegression(RegressorMixin, BaseEstimator):
"""
Regression model for k * 1 / x + b
"""
def __init__(self, initial_guess: Tuple[float, float, float] = (1, 0)):
"""
initial_guess:
- Tuple[float, float, float]
- k * 1 / x + b (k, a, b)
Constrained as follows:
- k[0,INF]
- b[0,INF]
"""
super(ReciprocalRegression, self).__init__()
self.initial_guess = initial_guess
def _constraint(self):
return np.asarray((
[0, 0],
[np.inf, np.inf]
))
def _more_tags(self):
return {
"poor_score": True
}
def fun(self, guess):
k, b = guess
return self.y_ - k * self.x_ + b
def fit(self, X, y):
if y is None:
raise ValueError()
x, y = check_X_y(X, y, y_numeric=True, force_all_finite=True, dtype='float64')
self.n_features_in_ = x.shape[1]
self.x_ = np.reciprocal(np.average(x, axis=1))
self.y_ = y
solution = least_squares(
self.fun,
np.asarray(self.initial_guess).astype('float64'),
bounds=self._constraint(),
loss='linear',
max_nfev=100
)
self.coef_ = [solution.x[0]]
self.intercept_ = solution.x[1]
return self
def predict(self, X):
check_is_fitted(self, 'coef_')
x: np.ndarray = check_array(X, force_all_finite=True, dtype='float64')
if x.shape[1] != self.n_features_in_:
raise ValueError("Wrong number of features")
x = np.average(X, axis=1)
return self.coef_[0] * np.reciprocal(x) + self.intercept_
| 27.557143 | 86 | 0.549767 | 498 | 3,858 | 4.062249 | 0.180723 | 0.059318 | 0.047454 | 0.029659 | 0.763717 | 0.745922 | 0.663866 | 0.663866 | 0.663866 | 0.629758 | 0 | 0.020611 | 0.320892 | 3,858 | 139 | 87 | 27.755396 | 0.751527 | 0.098756 | 0 | 0.611765 | 0 | 0 | 0.039891 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.141176 | false | 0 | 0.070588 | 0.047059 | 0.352941 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
4ac063629a09e212e534eba8cdcd6ecb42ef6164 | 15,814 | py | Python | symposion/reviews/migrations/0002_auto__add_index_proposalresult_status.py | pyconjp/pyconjp-website | c14b1412b70ad04d6c6e837cb0feaec17fd5cd36 | [
"BSD-3-Clause"
] | 6 | 2016-04-03T18:22:45.000Z | 2018-03-15T11:20:39.000Z | symposion/reviews/migrations/0002_auto__add_index_proposalresult_status.py | alex/pycon | d1437a9f2ac1ec4f4fd5ad41ef3a7fe06958b52b | [
"BSD-3-Clause"
] | 60 | 2016-04-14T12:16:06.000Z | 2017-08-15T06:15:50.000Z | symposion/reviews/migrations/0002_auto__add_index_proposalresult_status.py | alex/pycon | d1437a9f2ac1ec4f4fd5ad41ef3a7fe06958b52b | [
"BSD-3-Clause"
] | 7 | 2016-04-23T02:29:35.000Z | 2017-10-05T07:37:46.000Z | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding index on 'ProposalResult', fields ['status']
db.create_index(u'reviews_proposalresult', ['status'])
def backwards(self, orm):
# Removing index on 'ProposalResult', fields ['status']
db.delete_index(u'reviews_proposalresult', ['status'])
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'conference.conference': {
'Meta': {'object_name': 'Conference'},
'end_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'start_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'timezone': ('timezones.fields.TimeZoneField', [], {'default': "'US/Eastern'", 'max_length': '100', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'conference.section': {
'Meta': {'object_name': 'Section'},
'conference': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['conference.Conference']"}),
'end_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}),
'start_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'proposals.additionalspeaker': {
'Meta': {'unique_together': "(('speaker', 'proposalbase'),)", 'object_name': 'AdditionalSpeaker', 'db_table': "'proposals_proposalbase_additional_speakers'"},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'proposalbase': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['proposals.ProposalBase']"}),
'speaker': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['speakers.Speaker']"}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '1'})
},
u'proposals.proposalbase': {
'Meta': {'object_name': 'ProposalBase'},
'abstract': ('django.db.models.fields.TextField', [], {}),
'additional_notes': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'additional_speakers': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['speakers.Speaker']", 'symmetrical': 'False', 'through': u"orm['proposals.AdditionalSpeaker']", 'blank': 'True'}),
'cancelled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'description': ('django.db.models.fields.TextField', [], {'max_length': '400'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'kind': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['proposals.ProposalKind']"}),
'speaker': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'proposals'", 'to': u"orm['speakers.Speaker']"}),
'submitted': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'proposals.proposalkind': {
'Meta': {'object_name': 'ProposalKind'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'section': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'proposal_kinds'", 'to': u"orm['conference.Section']"}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'})
},
u'reviews.comment': {
'Meta': {'object_name': 'Comment'},
'commented_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'commenter': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'proposal': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'comments'", 'to': u"orm['proposals.ProposalBase']"}),
'public': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'text': ('django.db.models.fields.TextField', [], {})
},
u'reviews.latestvote': {
'Meta': {'unique_together': "[('proposal', 'user')]", 'object_name': 'LatestVote'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'proposal': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'votes'", 'to': u"orm['proposals.ProposalBase']"}),
'submitted_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
'vote': ('django.db.models.fields.CharField', [], {'max_length': '2'})
},
u'reviews.notificationtemplate': {
'Meta': {'object_name': 'NotificationTemplate'},
'body': ('django.db.models.fields.TextField', [], {}),
'from_address': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'subject': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'reviews.proposalmessage': {
'Meta': {'ordering': "['submitted_at']", 'object_name': 'ProposalMessage'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'message': ('django.db.models.fields.TextField', [], {}),
'proposal': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'messages'", 'to': u"orm['proposals.ProposalBase']"}),
'submitted_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"})
},
u'reviews.proposalresult': {
'Meta': {'object_name': 'ProposalResult'},
'accepted': ('django.db.models.fields.NullBooleanField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'comment_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'minus_one': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'minus_zero': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'plus_one': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'plus_zero': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'proposal': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'result'", 'unique': 'True', 'to': u"orm['proposals.ProposalBase']"}),
'score': ('django.db.models.fields.DecimalField', [], {'default': "'0.00'", 'max_digits': '5', 'decimal_places': '2'}),
'status': ('django.db.models.fields.CharField', [], {'default': "'undecided'", 'max_length': '20', 'db_index': 'True'}),
'vote_count': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'})
},
u'reviews.resultnotification': {
'Meta': {'object_name': 'ResultNotification'},
'body': ('django.db.models.fields.TextField', [], {}),
'from_address': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'proposal': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'notifications'", 'to': u"orm['proposals.ProposalBase']"}),
'subject': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'template': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['reviews.NotificationTemplate']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}),
'timestamp': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'to_address': ('django.db.models.fields.EmailField', [], {'max_length': '75'})
},
u'reviews.review': {
'Meta': {'object_name': 'Review'},
'comment': ('django.db.models.fields.TextField', [], {}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'proposal': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'reviews'", 'to': u"orm['proposals.ProposalBase']"}),
'submitted_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
'vote': ('django.db.models.fields.CharField', [], {'max_length': '2', 'blank': 'True'})
},
u'reviews.reviewassignment': {
'Meta': {'object_name': 'ReviewAssignment'},
'assigned_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'opted_out': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'origin': ('django.db.models.fields.IntegerField', [], {}),
'proposal': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['proposals.ProposalBase']"}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"})
},
u'speakers.speaker': {
'Meta': {'object_name': 'Speaker'},
'annotation': ('django.db.models.fields.TextField', [], {}),
'biography': ('django.db.models.fields.TextField', [], {}),
'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'invite_email': ('django.db.models.fields.CharField', [], {'max_length': '200', 'unique': 'True', 'null': 'True', 'db_index': 'True'}),
'invite_token': ('django.db.models.fields.CharField', [], {'max_length': '40', 'db_index': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'photo': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}),
'sessions_preference': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'twitter_username': ('django.db.models.fields.CharField', [], {'max_length': '15', 'blank': 'True'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'speaker_profile'", 'unique': 'True', 'null': 'True', 'to': u"orm['auth.User']"})
},
u'taggit.tag': {
'Meta': {'object_name': 'Tag'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100'})
},
u'taggit.taggeditem': {
'Meta': {'object_name': 'TaggedItem'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'taggit_taggeditem_tagged_items'", 'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'object_id': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'taggit_taggeditem_items'", 'to': u"orm['taggit.Tag']"})
}
}
complete_apps = ['reviews'] | 76.76699 | 218 | 0.567219 | 1,594 | 15,814 | 5.524467 | 0.122334 | 0.111742 | 0.193959 | 0.277084 | 0.723938 | 0.651942 | 0.627981 | 0.583239 | 0.519986 | 0.408926 | 0 | 0.007884 | 0.189895 | 15,814 | 206 | 219 | 76.76699 | 0.679494 | 0.008031 | 0 | 0.194872 | 0 | 0 | 0.599656 | 0.363938 | 0 | 0 | 0 | 0 | 0 | 1 | 0.010256 | false | 0.005128 | 0.020513 | 0 | 0.046154 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
434b2c70ffc8c6f833853c30b0457edc17344823 | 5,118 | py | Python | release/stubs.min/Autodesk/Revit/DB/__init___parts/LinearArray.py | YKato521/ironpython-stubs | b1f7c580de48528490b3ee5791b04898be95a9ae | [
"MIT"
] | null | null | null | release/stubs.min/Autodesk/Revit/DB/__init___parts/LinearArray.py | YKato521/ironpython-stubs | b1f7c580de48528490b3ee5791b04898be95a9ae | [
"MIT"
] | null | null | null | release/stubs.min/Autodesk/Revit/DB/__init___parts/LinearArray.py | YKato521/ironpython-stubs | b1f7c580de48528490b3ee5791b04898be95a9ae | [
"MIT"
] | null | null | null | class LinearArray(BaseArray, IDisposable):
""" An object that represents an Array created linearly within the Revit project. """
@staticmethod
def ArrayElementsWithoutAssociation(
aDoc, dBView, ids, count, translationToAnchorMember, anchorMember
):
""" ArrayElementsWithoutAssociation(aDoc: Document,dBView: View,ids: ICollection[ElementId],count: int,translationToAnchorMember: XYZ,anchorMember: ArrayAnchorMember) -> ICollection[ElementId] """
pass
@staticmethod
def ArrayElementWithoutAssociation(
aDoc, dBView, id, count, translationToAnchorMember, anchorMember
):
"""
ArrayElementWithoutAssociation(aDoc: Document,dBView: View,id: ElementId,count: int,translationToAnchorMember: XYZ,anchorMember: ArrayAnchorMember) -> ICollection[ElementId]
Creates a new linear array from a single element.
aDoc: The document.
dBView: The view. If it is a 2d view,translation vector must be in the view plane if
the element is a view-specific element.
id: The element to array.
count: The number of array members to create including the initial
element
grouping. Must between 2 and 200.
translationToAnchorMember: The translation vector for the array.
anchorMember: Indicates if the translation vector specifies the location of the second member
of the array,or the last member of the array.
Returns: The ids of the elements created during the operation.
"""
pass
@staticmethod
def Create(aDoc, dBView, *__args):
"""
Create(aDoc: Document,dBView: View,ids: ICollection[ElementId],count: int,translationToAnchorMember: XYZ,anchorMember: ArrayAnchorMember) -> LinearArray
Create(aDoc: Document,dBView: View,id: ElementId,count: int,translationToAnchorMember: XYZ,anchorMember: ArrayAnchorMember) -> LinearArray
Creates a new linear array element from a single element.
aDoc: The document.
dBView: The view. If it is a 2d view,translation vector must be in the view plane if
the element is a view-specific element.
id: The element to array.
count: The number of array members to create including the initial
element
grouping. Must between 2 and 200.
translationToAnchorMember: The translation vector for the array.
anchorMember: Indicates if the translation vector specifies the location of the second member
of the array,or the last member of the array.
Returns: The new linear array element.
"""
pass
def Dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def getBoundingBox(self, *args):
""" getBoundingBox(self: Element,view: View) -> BoundingBoxXYZ """
pass
def GetCopiedMemberIds(self):
"""
GetCopiedMemberIds(self: LinearArray) -> ICollection[ElementId]
Retrieves the copied member Ids of the Array.
Returns: The copied member Ids of the Array
"""
pass
def GetOriginalMemberIds(self):
"""
GetOriginalMemberIds(self: LinearArray) -> ICollection[ElementId]
Retrieves the original member Ids of the Array.
Returns: The original member Ids of the Array
"""
pass
@staticmethod
def IsElementArrayable(aDoc, id):
"""
IsElementArrayable(aDoc: Document,id: ElementId) -> bool
Indicates whether the input element is arrayable.
aDoc: The document.
id: The element id.
Returns: True if the input element is arrayable,false otherwise.
"""
pass
@staticmethod
def IsValidArraySize(count):
"""
IsValidArraySize(count: int) -> bool
This indicates whether the input count is valid.
count: The count.
Returns: True if the input count is between 2 and 200,false otherwise.
"""
pass
def ReleaseUnmanagedResources(self, *args):
""" ReleaseUnmanagedResources(self: Element,disposing: bool) """
pass
def setElementType(self, *args):
""" setElementType(self: Element,type: ElementType,incompatibleExceptionMessage: str) """
pass
def __enter__(self, *args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
NumMembers = property(
lambda self: object(), lambda self, v: None, lambda self: None
)
"""Retrieves or changes the number of the arrayed members.
Get: NumMembers(self: LinearArray) -> int
Set: NumMembers(self: LinearArray)=value
"""
| 25.211823 | 221 | 0.656702 | 552 | 5,118 | 5.976449 | 0.228261 | 0.018187 | 0.02425 | 0.026675 | 0.544104 | 0.501061 | 0.471961 | 0.432555 | 0.425887 | 0.413762 | 0 | 0.003974 | 0.262407 | 5,118 | 202 | 222 | 25.336634 | 0.869934 | 0.645369 | 0 | 0.512195 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.341463 | false | 0.341463 | 0 | 0 | 0.390244 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
434c9b87e7b1ea250e43662f5be5d9934c4e62ea | 137 | py | Python | cuttle/__init__.py | smitchell556/cuttle | f780114f2755bbfd0fcacabca429396312948885 | [
"MIT"
] | 2 | 2017-03-29T01:01:46.000Z | 2017-05-11T15:04:15.000Z | cuttle/__init__.py | smitchell556/cuttle | f780114f2755bbfd0fcacabca429396312948885 | [
"MIT"
] | 51 | 2017-02-10T23:56:34.000Z | 2017-05-17T18:07:38.000Z | cuttle/__init__.py | smitchell556/cuttle | f780114f2755bbfd0fcacabca429396312948885 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Cuttle, the simple, extendable ORM.
:license: MIT, see LICENSE for details.
"""
__version__ = '0.9.0.dev'
| 13.7 | 39 | 0.620438 | 19 | 137 | 4.263158 | 0.894737 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.035398 | 0.175182 | 137 | 9 | 40 | 15.222222 | 0.681416 | 0.722628 | 0 | 0 | 0 | 0 | 0.3 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
435314a80c9b1c92f094db131df4b4b5979b0a9f | 1,328 | py | Python | uitestcore/page_element.py | talawson05/ui-test-core | 6578398d6cfad97cee552f676a027b8b37755a73 | [
"MIT"
] | 8 | 2019-09-16T14:31:38.000Z | 2022-02-03T21:26:04.000Z | uitestcore/page_element.py | talawson05/ui-test-core | 6578398d6cfad97cee552f676a027b8b37755a73 | [
"MIT"
] | 12 | 2019-09-13T14:47:26.000Z | 2022-01-10T11:24:52.000Z | uitestcore/page_element.py | talawson05/ui-test-core | 6578398d6cfad97cee552f676a027b8b37755a73 | [
"MIT"
] | 4 | 2019-09-16T14:49:53.000Z | 2022-02-02T15:42:01.000Z | from enum import Enum
class PageElement:
"""
This represents an element on the page with information which can be used to locate it
"""
def __init__(self, locator_type, locator_value, element_type=""):
"""
Default constructor to create a PageElement
:param locator_type: the type of Selenium locator e.g. By.ID
:param locator_value: the locator string e.g. the ID of the element
:param element_type: additional information about an element e.g. "text" represents a text field
"""
self.locator_type = locator_type
self.locator_value = locator_value
self.field_type = element_type
def __add__(self, value):
"""
Overrides the "+" operator for this class to allow appending of locator value
:param value: the string to append to the locator value
:return: a new PageElement instance with the altered locator value
"""
return PageElement(self.locator_type, self.locator_value + value)
def __str__(self):
"""
Provides a string representation of the PageElement
:return: String
"""
return f"PageElement {self.locator_type}='{self.locator_value}'"
class FieldTypes(Enum):
text_box = "text"
radio_button = "radio"
check_box = "check"
| 33.2 | 104 | 0.659639 | 170 | 1,328 | 4.970588 | 0.370588 | 0.127811 | 0.071006 | 0.078107 | 0.131361 | 0.099408 | 0.099408 | 0 | 0 | 0 | 0 | 0 | 0.26506 | 1,328 | 39 | 105 | 34.051282 | 0.865779 | 0.470633 | 0 | 0 | 0 | 0 | 0.119298 | 0.073684 | 0 | 0 | 0 | 0 | 0 | 1 | 0.214286 | false | 0 | 0.071429 | 0 | 0.785714 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
43533250c5f5035bc92f8f54785847b328f1d8c3 | 2,827 | py | Python | pysnmp/CPQRECOV-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 11 | 2021-02-02T16:27:16.000Z | 2021-08-31T06:22:49.000Z | pysnmp/CPQRECOV-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 75 | 2021-02-24T17:30:31.000Z | 2021-12-08T00:01:18.000Z | pysnmp/CPQRECOV-MIB.py | agustinhenze/mibs.snmplabs.com | 1fc5c07860542b89212f4c8ab807057d9a9206c7 | [
"Apache-2.0"
] | 10 | 2019-04-30T05:51:36.000Z | 2022-02-16T03:33:41.000Z | #
# PySNMP MIB module CPQRECOV-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CPQRECOV-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:12:06 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection")
cpqHoTrapFlags, compaq = mibBuilder.importSymbols("CPQHOST-MIB", "cpqHoTrapFlags", "compaq")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
sysName, = mibBuilder.importSymbols("SNMPv2-MIB", "sysName")
Counter32, Gauge32, MibIdentifier, ModuleIdentity, TimeTicks, ObjectIdentity, iso, NotificationType, Counter64, enterprises, Unsigned32, IpAddress, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, Integer32, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "Gauge32", "MibIdentifier", "ModuleIdentity", "TimeTicks", "ObjectIdentity", "iso", "NotificationType", "Counter64", "enterprises", "Unsigned32", "IpAddress", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "Integer32", "Bits")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
cpqRecovery = MibIdentifier((1, 3, 6, 1, 4, 1, 232, 13))
cpqRsPartnerFailed = NotificationType((1, 3, 6, 1, 4, 1, 232) + (0,13001)).setObjects(("SNMPv2-MIB", "sysName"), ("CPQHOST-MIB", "cpqHoTrapFlags"))
cpqRsStandbyCableFailure = NotificationType((1, 3, 6, 1, 4, 1, 232) + (0,13002)).setObjects(("SNMPv2-MIB", "sysName"), ("CPQHOST-MIB", "cpqHoTrapFlags"))
cpqRsStandbyFailure = NotificationType((1, 3, 6, 1, 4, 1, 232) + (0,13003)).setObjects(("SNMPv2-MIB", "sysName"), ("CPQHOST-MIB", "cpqHoTrapFlags"))
cpqRsOnlineCableFailure = NotificationType((1, 3, 6, 1, 4, 1, 232) + (0,13004)).setObjects(("SNMPv2-MIB", "sysName"), ("CPQHOST-MIB", "cpqHoTrapFlags"))
cpqRsFailoverFailed = NotificationType((1, 3, 6, 1, 4, 1, 232) + (0,13005)).setObjects(("SNMPv2-MIB", "sysName"), ("CPQHOST-MIB", "cpqHoTrapFlags"))
mibBuilder.exportSymbols("CPQRECOV-MIB", cpqRsStandbyCableFailure=cpqRsStandbyCableFailure, cpqRsStandbyFailure=cpqRsStandbyFailure, cpqRsFailoverFailed=cpqRsFailoverFailed, cpqRecovery=cpqRecovery, cpqRsPartnerFailed=cpqRsPartnerFailed, cpqRsOnlineCableFailure=cpqRsOnlineCableFailure)
| 122.913043 | 543 | 0.767952 | 280 | 2,827 | 7.753571 | 0.382143 | 0.084754 | 0.066329 | 0.011055 | 0.450023 | 0.358821 | 0.358821 | 0.239521 | 0.239521 | 0.179641 | 0 | 0.061686 | 0.07676 | 2,827 | 22 | 544 | 128.5 | 0.770115 | 0.112487 | 0 | 0 | 0 | 0 | 0.2948 | 0.0176 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.533333 | 0 | 0.533333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
436fc8325ddc41845111b56ec90f842564daeabc | 191 | py | Python | game.py | johntelforduk/space-rocks-gamepi20 | b9450e8dad36e9e34b763585cf77cec231af6cc5 | [
"MIT"
] | null | null | null | game.py | johntelforduk/space-rocks-gamepi20 | b9450e8dad36e9e34b763585cf77cec231af6cc5 | [
"MIT"
] | null | null | null | game.py | johntelforduk/space-rocks-gamepi20 | b9450e8dad36e9e34b763585cf77cec231af6cc5 | [
"MIT"
] | null | null | null | # Run the game.
import space_rocks
this_config = space_rocks.Config(False, # Debug mode?
25) # Target FPS.
this_config.choose_options()
| 21.222222 | 61 | 0.549738 | 21 | 191 | 4.761905 | 0.761905 | 0.2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.016807 | 0.376963 | 191 | 8 | 62 | 23.875 | 0.823529 | 0.193717 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.25 | 0 | 0.25 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
43750e540ad444a0a3e540604dfec186001692cd | 2,941 | py | Python | nlcpy/linalg/__init__.py | SX-Aurora/nlcpy | 0a53eec8778073bc48b12687b7ce37ab2bf2b7e0 | [
"BSD-3-Clause"
] | 11 | 2020-07-31T02:21:55.000Z | 2022-03-10T03:12:11.000Z | nlcpy/linalg/__init__.py | SX-Aurora/nlcpy | 0a53eec8778073bc48b12687b7ce37ab2bf2b7e0 | [
"BSD-3-Clause"
] | null | null | null | nlcpy/linalg/__init__.py | SX-Aurora/nlcpy | 0a53eec8778073bc48b12687b7ce37ab2bf2b7e0 | [
"BSD-3-Clause"
] | null | null | null | #
# * The source code in this file is developed independently by NEC Corporation.
#
# # NLCPy License #
#
# Copyright (c) 2020-2021 NEC Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither NEC Corporation nor the names of its contributors may be
# used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
from numpy.linalg import LinAlgError # NOQA
# override numpy documentation
LinAlgError.__doc__ = '''
Generic Python-exception-derived object raised by linalg functions.
General purpose exception class, derived from Python's exception.
Exception class, programmatically raised in linalg functions when a
Linear Algebra-related condition would prevent further correct
execution of the function.
Parameters
----------
None
Examples
--------
>>> import nlcpy as vp
>>> vp.linalg.inv(vp.zeros((2,2))) # doctest: +SKIP
...
numpy.linalg.LinAlgError: Singular matrix
'''
from nlcpy.linalg import cblas_wrapper # NOQA
from nlcpy.linalg import products # NOQA
from nlcpy.linalg.solve import solve # NOQA
from nlcpy.linalg.solve import lstsq # NOQA
from nlcpy.linalg.solve import inv # NOQA
from nlcpy.linalg.eig import eig # NOQA
from nlcpy.linalg.eig import eigvals # NOQA
from nlcpy.linalg.eig import eigh # NOQA
from nlcpy.linalg.eig import eigvalsh # NOQA
from nlcpy.linalg.norm import norm # NOQA
from nlcpy.linalg.decomposition import svd # NOQA
from nlcpy.linalg.decomposition import cholesky # NOQA
from nlcpy.linalg.decomposition import qr # NOQA
| 43.25 | 88 | 0.740564 | 394 | 2,941 | 5.515228 | 0.456853 | 0.053843 | 0.089738 | 0.104924 | 0.230097 | 0.208007 | 0.062586 | 0.062586 | 0.062586 | 0.062586 | 0 | 0.004248 | 0.199592 | 2,941 | 67 | 89 | 43.895522 | 0.918862 | 0.596736 | 0 | 0 | 0 | 0 | 0.455185 | 0.06942 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.5 | 0 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
438886532404ee39a19ef3b7ec79f8ff950d49a1 | 131 | py | Python | 100 Days Python/day002/src/dataTypes.py | AiseKaise/100DaysPython | 6deba07b3b79bd4fbc11379878ba4f1c2887d315 | [
"MIT"
] | null | null | null | 100 Days Python/day002/src/dataTypes.py | AiseKaise/100DaysPython | 6deba07b3b79bd4fbc11379878ba4f1c2887d315 | [
"MIT"
] | null | null | null | 100 Days Python/day002/src/dataTypes.py | AiseKaise/100DaysPython | 6deba07b3b79bd4fbc11379878ba4f1c2887d315 | [
"MIT"
] | null | null | null | # Data Types
# Strings
print("Hello"[0])
# Integer
print(123 + 345)
# Float
3.14159
# Boolean
True
False | 7.277778 | 18 | 0.549618 | 16 | 131 | 4.5 | 0.9375 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.149425 | 0.335878 | 131 | 18 | 19 | 7.277778 | 0.678161 | 0.305344 | 0 | 0 | 0 | 0 | 0.072464 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0 | 0 | 0 | 0.4 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
4388d242f7b6becd6793f6a705cff5a74c9c02ed | 357 | py | Python | example/consumer.py | ybrs/pydisque | ea5ce1576b66398c1cce32cad0f15709b1ea8df8 | [
"MIT"
] | 92 | 2015-04-28T01:32:33.000Z | 2021-06-24T03:14:43.000Z | example/consumer.py | abdul-khalid/pydisque | a9b5caa6dac0621a0174d168f4a04c88d0e2f8b5 | [
"MIT"
] | 30 | 2015-04-28T01:39:55.000Z | 2019-02-28T15:18:45.000Z | example/consumer.py | abdul-khalid/pydisque | a9b5caa6dac0621a0174d168f4a04c88d0e2f8b5 | [
"MIT"
] | 20 | 2015-05-12T21:14:27.000Z | 2020-03-05T06:05:42.000Z | import json
import time
import logging
logging.basicConfig(level=logging.DEBUG)
from pydisque.client import Client
c = Client(['localhost:7712', 'localhost:7711'])
c.connect()
while True:
jobs = c.get_job(['test'])
for queue_name, job_id, job in jobs:
job = json.loads(job)
print ">>> received job:", job
c.ack_job(job_id) | 22.3125 | 48 | 0.672269 | 52 | 357 | 4.519231 | 0.576923 | 0.042553 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.027875 | 0.196078 | 357 | 16 | 49 | 22.3125 | 0.790941 | 0 | 0 | 0 | 0 | 0 | 0.136872 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.307692 | null | null | 0.076923 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
4389d93fcfede0064b9157caa93077d468bf7e7c | 2,325 | py | Python | django_project/blog/models.py | jsolly/blogthedata | 4f9ea581d0ddbcdefcf49b0911082b0b964fe594 | [
"MIT"
] | 1 | 2022-03-22T15:40:18.000Z | 2022-03-22T15:40:18.000Z | django_project/blog/models.py | jsolly/blogthedata | 4f9ea581d0ddbcdefcf49b0911082b0b964fe594 | [
"MIT"
] | 16 | 2022-03-22T15:35:35.000Z | 2022-03-30T00:55:14.000Z | django_project/blog/models.py | jsolly/blogthedata | 4f9ea581d0ddbcdefcf49b0911082b0b964fe594 | [
"MIT"
] | null | null | null | from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.contrib.auth.models import User
from django_ckeditor_5.fields import CKEditor5Field
import filetype
from .utils import slugify_instance_title
class PostManager(models.Manager):
def active(self, *args, **kwargs):
return super().filter(draft=False).order_by("-date_posted")
def all(self, *args, **kwargs):
return super().order_by("-date_posted")
class Category(models.Model):
"""A category contains a subset of posts that are associated with a single category"""
name = models.CharField(max_length=50)
description = models.CharField(max_length=140)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("blog-category", kwargs={"category": self.name})
class Post(models.Model):
"""Contains all the information that is relevant to a blog post"""
title = models.CharField(max_length=60)
slug = models.SlugField(unique=True, blank=True, null=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
metadesc = models.CharField(max_length=140, blank=True, null=True)
draft = models.BooleanField(default=False)
metaimg = models.ImageField(default="jsolly.jpeg", upload_to="post_metaimgs/")
metaimg_mimetype = models.CharField(max_length=20, default="image/jpeg")
metaimg_alt_txt = models.CharField(max_length=120, default="Meta Image")
content = CKEditor5Field(blank=True, null=True, config_name='extends')
snippet = CKEditor5Field(max_length=300, blank=True, null=True, config_name='extends')
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
objects = PostManager() # Make sure objects only include active (not draft) posts..
def __str__(self):
return self.title + " | " + str(self.author)
def get_absolute_url(self):
return reverse("post-detail", kwargs={"slug": self.slug})
def save(self, *args, **kwargs):
if not self.slug:
slugify_instance_title(self, save=False)
try:
self.metaimg_mimetype = filetype.guess(self.metaimg).MIME
except AttributeError:
pass
super().save(*args, **kwargs)
| 36.328125 | 90 | 0.707527 | 299 | 2,325 | 5.367893 | 0.394649 | 0.039252 | 0.06729 | 0.08972 | 0.174455 | 0.084735 | 0.084735 | 0 | 0 | 0 | 0 | 0.0115 | 0.177204 | 2,325 | 63 | 91 | 36.904762 | 0.827496 | 0.086022 | 0 | 0.088889 | 0 | 0 | 0.057711 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.155556 | false | 0.022222 | 0.155556 | 0.133333 | 0.844444 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 2 |
43902647dde76b6e4593edefa9eb7fed4641b0e2 | 1,514 | py | Python | src/users/views.py | kc97ble/icrew | 6a75848b9e9c38dda5b641b54298735d3a749454 | [
"MIT"
] | null | null | null | src/users/views.py | kc97ble/icrew | 6a75848b9e9c38dda5b641b54298735d3a749454 | [
"MIT"
] | 12 | 2019-12-31T13:18:24.000Z | 2021-09-22T18:21:50.000Z | src/users/views.py | kc97ble/icrew | 6a75848b9e9c38dda5b641b54298735d3a749454 | [
"MIT"
] | null | null | null | import django
from django.contrib import messages
from django.contrib.auth import login, authenticate, update_session_auth_hash
from django.contrib.auth.forms import UserCreationForm, PasswordChangeForm
from django.shortcuts import render, redirect
from django.http.response import HttpResponse
def change_password(request):
if request.method == "POST":
form = PasswordChangeForm(request.user, request.POST)
if form.is_valid():
user = form.save()
update_session_auth_hash(request, user) # Important!
messages.success(request, "Your password was successfully updated!")
return redirect("change_password")
else:
messages.error(request, "Please correct the error below.")
else:
form = PasswordChangeForm(request.user)
return render(request, "users/change_password.html", {"form": form})
def signup_view(request, *args, **kwargs):
return HttpResponse("Please contact admins to register")
'''
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get("username")
raw_password = form.cleaned_data.get("password1")
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect("home")
else:
form = UserCreationForm()
return render(request, "users/signup.html", {"form": form})
'''
| 37.85 | 80 | 0.669749 | 165 | 1,514 | 6.048485 | 0.375758 | 0.0501 | 0.051102 | 0.042084 | 0.094188 | 0.048096 | 0 | 0 | 0 | 0 | 0 | 0.000854 | 0.226552 | 1,514 | 39 | 81 | 38.820513 | 0.851409 | 0.006605 | 0 | 0.095238 | 0 | 0 | 0.153535 | 0.026263 | 0 | 0 | 0 | 0 | 0 | 1 | 0.095238 | false | 0.333333 | 0.285714 | 0 | 0.52381 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 2 |
43a191f4aeac6fad4c172255cc681ee596585129 | 1,817 | py | Python | edit/exportcontent.py | lokal-profil/isfdb_site | 0ce20d6347849926d4eda961ea9249c31519eea5 | [
"BSD-3-Clause"
] | null | null | null | edit/exportcontent.py | lokal-profil/isfdb_site | 0ce20d6347849926d4eda961ea9249c31519eea5 | [
"BSD-3-Clause"
] | null | null | null | edit/exportcontent.py | lokal-profil/isfdb_site | 0ce20d6347849926d4eda961ea9249c31519eea5 | [
"BSD-3-Clause"
] | null | null | null | #!_PYTHONLOC
#
# (C) COPYRIGHT 2008-2021 Al von Ruff and Ahasuerus
# ALL RIGHTS RESERVED
#
# The copyright notice above does not evidence any actual or
# intended publication of such source code.
#
# Version: $Revision$
# Date: $Date$
from isfdb import *
from isfdblib import *
from isfdblib_print import *
from library import *
if __name__ == '__main__':
pub_id = SESSION.Parameter(0, 'int')
pub_data = SQLGetPubById(pub_id)
if not pub_data:
SESSION.DisplayError('Record Does Not Exist')
PrintPreSearch('Export Content - %s' % pub_data[PUB_TITLE])
PrintNavBar('edit/exportcontent.cgi', pub_id)
print '<div id="HelpBox">'
print '<a href="%s://%s/index.php/Help:Screen:ExportContent">Help on exporting content</a><p>' % (PROTOCOL, WIKILOC)
print '</div>'
print 'Enter the publication ID/record number you would like to export into:'
print '<p>'
print '<form id="data" METHOD="POST" ACTION="/cgi-bin/edit/clonecontent.cgi">'
print '<table>'
printfield('Export Into', 'ExportTo')
print '<tr>'
print '<td><b>Include COVERART title(s)?</b></td>'
print '<td><input type="checkbox" NAME="IncludeCoverArt" value="on" checked></td>'
print '</tr>'
print '<tr>'
print '<td><b>Include INTERIORART titles?</b></td>'
print '<td><input type="checkbox" NAME="IncludeInteriorArt" value="on" checked></td>'
print '</tr>'
print '<tr>'
print '<td><b>Include page numbers?</b></td>'
print '<td><input type="checkbox" NAME="IncludePages" value="on" checked></td>'
print '</tr>'
print '</table>'
print '<p>'
print '<input NAME="ExportFrom" VALUE="%d" TYPE="HIDDEN">' % pub_id
print '<input TYPE="SUBMIT" VALUE="Export Content">'
print '</form>'
PrintPostSearch(tableclose=False)
| 29.786885 | 124 | 0.64557 | 237 | 1,817 | 4.873418 | 0.476793 | 0.036364 | 0.062338 | 0.036364 | 0.201732 | 0.201732 | 0.182684 | 0.158442 | 0.077922 | 0.077922 | 0 | 0.006106 | 0.188773 | 1,817 | 60 | 125 | 30.283333 | 0.777476 | 0.134838 | 0 | 0.216216 | 0 | 0.054054 | 0.533931 | 0.104994 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.108108 | null | null | 0.702703 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 |
43a41d321ff1602af5e59a6e97e8236998f8da72 | 446 | py | Python | complete-python/fundamentals/loops-exercise.py | alaindet/learn-python | 44d3b04188af19f4491a505a210b53cd67bae542 | [
"MIT"
] | null | null | null | complete-python/fundamentals/loops-exercise.py | alaindet/learn-python | 44d3b04188af19f4491a505a210b53cd67bae542 | [
"MIT"
] | null | null | null | complete-python/fundamentals/loops-exercise.py | alaindet/learn-python | 44d3b04188af19f4491a505a210b53cd67bae542 | [
"MIT"
] | null | null | null | # Print out numbers from 1 to 100 (including 100).
# But, instead of printing multiples of 3, print "Fizz"
# Instead of printing multiples of 5, print "Buzz"
# Instead of printing multiples of both 3 and 5, print "FizzBuzz".
for number in range(1, 101):
output = ''
if number % 3 == 0:
output += 'Fizz'
if number % 5 == 0:
output += 'Buzz'
if len(output):
print(output)
continue
print(number)
| 27.875 | 66 | 0.612108 | 64 | 446 | 4.265625 | 0.46875 | 0.098901 | 0.186813 | 0.285714 | 0.307692 | 0 | 0 | 0 | 0 | 0 | 0 | 0.05919 | 0.280269 | 446 | 15 | 67 | 29.733333 | 0.791277 | 0.484305 | 0 | 0 | 0 | 0 | 0.035556 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.2 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
43a89d65d1f432d87f5e412865f468f7d5f34306 | 2,765 | py | Python | parsers/utils/consoleCommands.py | mcellteam/bionetgen | def0c949b36c83b7848bbe33250ce81641d40e11 | [
"MIT"
] | 53 | 2015-03-15T20:33:36.000Z | 2022-02-25T12:07:26.000Z | parsers/utils/consoleCommands.py | mcellteam/bionetgen | def0c949b36c83b7848bbe33250ce81641d40e11 | [
"MIT"
] | 85 | 2015-03-19T19:58:19.000Z | 2022-02-28T20:38:17.000Z | parsers/utils/consoleCommands.py | mcellteam/bionetgen | def0c949b36c83b7848bbe33250ce81641d40e11 | [
"MIT"
] | 34 | 2015-05-02T23:46:57.000Z | 2021-12-22T19:35:58.000Z | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 2 18:11:35 2013
@author: proto
"""
import pexpect
import subprocess
import os
from os.path import expanduser,join
home = expanduser("~")
bngExecutable = join(home,'workspace','bionetgen','bng2','BNG2.pl')
def setBngExecutable(executable):
bngExecutable = executable
def getBngExecutable():
return bngExecutable
def bngl2xml(bnglFile,timeout=60):
try:
bngconsole = pexpect.spawn('{0} --console'.format(getBngExecutable()),timeout=timeout)
bngconsole.expect('BNG>')
bngconsole.sendline('load {0}'.format(bnglFile))
bngconsole.expect('BNG>')
bngconsole.sendline('action writeXML()')
bngconsole.expect('BNG>')
bngconsole.close()
except pexpect.TIMEOUT:
subprocess.call(['killall','bngdev'])
def bngl2sbml(bnglFile,timeout=60):
try:
bngconsole = pexpect.spawn('{0} --console'.format(getBngExecutable()),timeout=timeout)
bngconsole.expect('BNG>')
bngconsole.sendline('load {0}'.format(bnglFile))
bngconsole.expect('BNG>')
bngconsole.sendline('action generate_network()')
bngconsole.expect('BNG>')
bngconsole.sendline('action writeSBML()')
bngconsole.expect('BNG>')
bngconsole.close()
except pexpect.TIMEOUT:
subprocess.call(['killall','bngdev'])
def correctness(bnglFile):
bngconsole = pexpect.spawn('{0} --console'.format(getBngExecutable()))
bngconsole.expect('BNG>')
bngconsole.sendline('load {0}'.format(bnglFile))
bngconsole.expect('BNG>')
output= bngconsole.before
bngconsole.close()
if 'ERROR' in output in output:
return False
return True
def writeNetwork(bnglFile):
bngconsole = pexpect.spawn('{0} --console'.format(getBngExecutable()))
bngconsole.expect('BNG>')
bngconsole.sendline('load {0}'.format(bnglFile))
bngconsole.expect('BNG>')
bngconsole.sendline('action generate_network()')
bngconsole.expect('BNG>')
bngconsole.close()
def generateGraph(bnglFile,graphType):
directory = os.sep.join(bnglFile.split(os.sep)[:-1])
os.chdir(directory)
print directory
bngconsole = pexpect.spawn('{0} --console'.format(getBngExecutable()))
bngconsole.expect('BNG>')
bngconsole.sendline('load {0}'.format(bnglFile))
bngconsole.expect('BNG>')
if graphType == "regulatory":
bngconsole.sendline('action visualize()')
elif graphType == "contactmap":
bngconsole.sendline('action visualize({type=>"contactmap"})')
else:
return False
bngconsole.expect('BNG>')
bngconsole.close()
return True
if __name__ == "__main__":
print bngl2xml('output19.bngl') | 30.384615 | 94 | 0.652803 | 278 | 2,765 | 6.456835 | 0.302158 | 0.133705 | 0.158774 | 0.210028 | 0.612813 | 0.591086 | 0.583287 | 0.583287 | 0.583287 | 0.583287 | 0 | 0.015281 | 0.195298 | 2,765 | 91 | 95 | 30.384615 | 0.791461 | 0.007595 | 0 | 0.591549 | 0 | 0 | 0.152012 | 0.01155 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.056338 | null | null | 0.028169 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
43af66b47ec9a9039b20d0cd9f7e0eb42a06cd0b | 840 | py | Python | web/wefree/wefree/core/models.py | gerasdf/wefree | bc5a130861e960a6fc1178029e1066b094439d9a | [
"MIT"
] | 7 | 2015-11-05T09:05:04.000Z | 2021-01-03T01:57:02.000Z | web/wefree/wefree/core/models.py | gerasdf/wefree | bc5a130861e960a6fc1178029e1066b094439d9a | [
"MIT"
] | 1 | 2015-08-11T12:45:30.000Z | 2015-08-11T12:45:30.000Z | web/wefree/wefree/core/models.py | gerasdf/wefree | bc5a130861e960a6fc1178029e1066b094439d9a | [
"MIT"
] | null | null | null | from django.db import models
import json
class AP(models.Model):
bssid = models.CharField(max_length=25)
essid = models.CharField(max_length=128)
creation_date = models.DateTimeField(auto_now_add=True)
def to_json(self):
reports = self.report_set.filter(success=True)
data = {
"essid": self.essid, "bssid": self.bssid,
"passwords": [report.password for report in reports],
"positions": [(report.geo_lat, report.geo_long) for report in reports]
}
return json.dumps(data)
class Report(models.Model):
ap = models.ForeignKey(AP)
password = models.CharField(max_length=128)
date = models.DateTimeField(auto_now_add=True)
success = models.BooleanField()
geo_lat = models.FloatField(null=True)
geo_long = models.FloatField(null=True)
| 31.111111 | 82 | 0.67619 | 107 | 840 | 5.17757 | 0.429907 | 0.081227 | 0.097473 | 0.129964 | 0.231047 | 0.133574 | 0.133574 | 0 | 0 | 0 | 0 | 0.012085 | 0.211905 | 840 | 26 | 83 | 32.307692 | 0.824773 | 0 | 0 | 0 | 0 | 0 | 0.033333 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.047619 | false | 0.095238 | 0.095238 | 0 | 0.714286 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 2 |
43bde61abbb6c088ff9a1115d82c661ce4d74621 | 163 | py | Python | piper/main.py | eminentcodex/piper | e2cb4c04e9180fed38cbb001dffab977862b6bf2 | [
"MIT"
] | null | null | null | piper/main.py | eminentcodex/piper | e2cb4c04e9180fed38cbb001dffab977862b6bf2 | [
"MIT"
] | null | null | null | piper/main.py | eminentcodex/piper | e2cb4c04e9180fed38cbb001dffab977862b6bf2 | [
"MIT"
] | null | null | null | from termcolor import cprint
def main():
'''
Welcome to the Piper cli tool
'''
cprint(main.__doc__,"green")
if __name__=='__main__':
main() | 13.583333 | 33 | 0.613497 | 20 | 163 | 4.4 | 0.8 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.251534 | 163 | 12 | 34 | 13.583333 | 0.721311 | 0.177914 | 0 | 0 | 0 | 0 | 0.109244 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.2 | true | 0 | 0.2 | 0 | 0.4 | 0.4 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
43ccb0685cad45120eb2b07fa6e64a1773ae5e12 | 743 | py | Python | client.py | arondasamuel123/PasswordLocker | 9dfcda39faf2520949575787a3322509aebf29d0 | [
"MIT"
] | null | null | null | client.py | arondasamuel123/PasswordLocker | 9dfcda39faf2520949575787a3322509aebf29d0 | [
"MIT"
] | null | null | null | client.py | arondasamuel123/PasswordLocker | 9dfcda39faf2520949575787a3322509aebf29d0 | [
"MIT"
] | null | null | null | class Client:
"""
Class that creates new instances of client
"""
u_list = []
def __init__(self, fn, ln, email, password):
self.fn = fn
self.ln = ln
self.email = email
self.password = password
def save_client(self):
"""
Function to save client to list
"""
Client.u_list.append(self)
@classmethod
def find_client(cls, email, password):
"""
Function that takes in a password and the user
Args:
password ro search for
Returns :
Logins in user to application
"""
for client in cls.u_list:
if client.password == password:
return client
| 22.515152 | 55 | 0.526245 | 84 | 743 | 4.547619 | 0.452381 | 0.039267 | 0.057592 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.395693 | 743 | 33 | 56 | 22.515152 | 0.85078 | 0.271871 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.214286 | false | 0.285714 | 0 | 0 | 0.428571 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
43cdcce295e1406b31486d59aacb190531eb8f89 | 1,516 | py | Python | LeetCode/python/061-090/067-add-binary/plusbinary.py | shootsoft/practice | 49f28c2e0240de61d00e4e0291b3c5edd930e345 | [
"Apache-2.0"
] | null | null | null | LeetCode/python/061-090/067-add-binary/plusbinary.py | shootsoft/practice | 49f28c2e0240de61d00e4e0291b3c5edd930e345 | [
"Apache-2.0"
] | null | null | null | LeetCode/python/061-090/067-add-binary/plusbinary.py | shootsoft/practice | 49f28c2e0240de61d00e4e0291b3c5edd930e345 | [
"Apache-2.0"
] | null | null | null | class Solution:
# @param a, a string
# @param b, a string
# @return a string
def addBinary(self, num1, num2):
#print num1, num2
add = 0
pos1 = len(num1)-1
pos2 = len(num2)-1
pos = pos1 + 2
if(pos2>pos1):
pos = pos2 + 2
result = [''] * pos
pos = 0
while pos1 >=0 and pos2 >=0:
#print pos1, pos2
x = ord(num1[pos1]) + ord(num2[pos2]) - 96
if add> 0:
x += add
add = 0
if x >= 2 :
x -= 2
add = 1
result[pos] = chr(x+48)
pos += 1
pos1 -= 1
pos2 -= 1
#print result
while pos1 >=0:
x = ord(num1[pos1]) - 48
if add>0 :
x += add
add = 0
if x >= 2 :
x -= 2
add = 1
result[pos] = chr(x+48)
pos += 1
pos1 -= 1
# print result
while pos2 >=0:
x = ord(num2[pos2]) - 48
if add>0 :
x += 1
add = 0
if x >= 2 :
x -= 2
add = 1
result[pos] = chr(x+48)
pos += 1
pos2 -= 1
if add > 0:
result[pos] =chr(add+48)
result.reverse()
return ''.join(result)
s = Solution()
print s.addBinary('1111','1')
print s.addBinary('1111','1010')
| 21.657143 | 54 | 0.351583 | 177 | 1,516 | 3.011299 | 0.19774 | 0.060038 | 0.045028 | 0.0394 | 0.262664 | 0.242026 | 0.242026 | 0.242026 | 0.242026 | 0.242026 | 0 | 0.127989 | 0.531003 | 1,516 | 69 | 55 | 21.971014 | 0.62166 | 0.073219 | 0 | 0.568627 | 0 | 0 | 0.009306 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0 | null | null | 0.039216 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
43d12c235bee69b1956cea1a712503fda3712c4a | 576 | py | Python | predictor1.py | guezmike1/flyingflapjacks | 35741d4232cdea19bbaec9ec8dfc8bb2fa39d1f6 | [
"bzip2-1.0.6"
] | null | null | null | predictor1.py | guezmike1/flyingflapjacks | 35741d4232cdea19bbaec9ec8dfc8bb2fa39d1f6 | [
"bzip2-1.0.6"
] | null | null | null | predictor1.py | guezmike1/flyingflapjacks | 35741d4232cdea19bbaec9ec8dfc8bb2fa39d1f6 | [
"bzip2-1.0.6"
] | null | null | null | import requests
import math
import http.client
import json
from pprint import pprint
from firebase import firebase,FirebaseAuthentication
firebase_db = firebase.FirebaseApplication('https://nbasort.firebaseio.com/', authentication=None)
##GET TEAMS PLAYING
result = firebase_db.get('/Schedule/-KnFSyixTJlx59nX6C1C/games/0',None)
data_str = json.dumps(result)
current_game = json.loads(data_str)
away_team_alias = current_game['away']['alias']
home_team_alias = current_game['home']['alias']
print away_team_alias
print home_team_alias
| 19.862069 | 99 | 0.758681 | 73 | 576 | 5.780822 | 0.506849 | 0.085308 | 0.061611 | 0.094787 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.010142 | 0.144097 | 576 | 28 | 100 | 20.571429 | 0.845842 | 0.029514 | 0 | 0 | 0 | 0 | 0.165399 | 0.072243 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.428571 | null | null | 0.214286 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
43d76c31eaad704a25c843f15d817a73bdce7710 | 659 | py | Python | migrations/versions/0292_give_users_folder_perms.py | tlwr/notifications-api | 88a6b7729edb9be41ce3e7c027f1452b7b6d00d2 | [
"MIT"
] | 51 | 2016-04-03T23:36:17.000Z | 2022-03-21T20:04:52.000Z | migrations/versions/0292_give_users_folder_perms.py | tlwr/notifications-api | 88a6b7729edb9be41ce3e7c027f1452b7b6d00d2 | [
"MIT"
] | 1,335 | 2015-12-15T14:28:50.000Z | 2022-03-30T16:24:27.000Z | migrations/versions/0292_give_users_folder_perms.py | tlwr/notifications-api | 88a6b7729edb9be41ce3e7c027f1452b7b6d00d2 | [
"MIT"
] | 30 | 2016-01-08T19:05:32.000Z | 2021-12-20T16:37:23.000Z | """
Revision ID: 0292_give_users_folder_perms
Revises: 0291_remove_unused_index
Create Date: 2019-04-01 16:36:53.274394
"""
from alembic import op
from sqlalchemy.sql import text
revision = '0292_give_users_folder_perms'
down_revision = '0291_remove_unused_index'
def upgrade():
op.execute(text(
"""INSERT INTO user_folder_permissions (user_id, template_folder_id, service_id)
SELECT user_to_service.user_id, template_folder.id, user_to_service.service_id from user_to_service, template_folder
WHERE template_folder.service_id = user_to_service.service_id
ON CONFLICT do nothing"""
))
def downgrade():
pass
| 24.407407 | 124 | 0.763278 | 96 | 659 | 4.864583 | 0.489583 | 0.119914 | 0.111349 | 0.08137 | 0.295503 | 0.102784 | 0 | 0 | 0 | 0 | 0 | 0.064982 | 0.159332 | 659 | 26 | 125 | 25.346154 | 0.777978 | 0.174507 | 0 | 0 | 0 | 0 | 0.231111 | 0.231111 | 0 | 0 | 0 | 0 | 0 | 1 | 0.222222 | false | 0.111111 | 0.222222 | 0 | 0.444444 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
43de321014d05a58c1e7b0ef99220c4dfa9c4731 | 2,271 | py | Python | application/flicket/scripts/functions_login.py | juanvmarquezl/flicket | 0ed68d38b1f12e105436d8c51af163476b60a982 | [
"MIT"
] | 95 | 2017-10-31T21:25:11.000Z | 2022-03-07T05:46:12.000Z | application/flicket/scripts/functions_login.py | juanvmarquezl/flicket | 0ed68d38b1f12e105436d8c51af163476b60a982 | [
"MIT"
] | 47 | 2017-05-15T10:52:23.000Z | 2021-12-13T09:30:52.000Z | application/flicket/scripts/functions_login.py | juanvmarquezl/flicket | 0ed68d38b1f12e105436d8c51af163476b60a982 | [
"MIT"
] | 54 | 2017-07-13T03:38:47.000Z | 2022-02-12T20:10:02.000Z | #! usr/bin/python3
# -*- coding: utf-8 -*-
#
# Flicket - copyright Paul Bourne: evereux@gmail.com
import re
import bcrypt
from flask_babel import gettext
from application.flicket.models.flicket_user import FlicketUser
password_requirements = gettext('Passwords shall adhere to the following:<br>'
'1. Be a minimum of 8 characters.<br>'
'2. Contain at least one digit.<br>'
'3. Contain at least one upper and lower case character.<br>'
'4. Not contain your username.<br>')
def check_password_format(password, username, email):
"""
Checks that the password adheres to the rules defined by this function.
See `password_requirements`.
:param password:
:param username:
:param email:
:return: True if ok
"""
if not ((any(s.isupper() for s in password)) and (any(s.islower() for s in password))):
return False
if len(password) < 8:
return False
if not any([c.isdigit() for c in password]):
return False
if username in password:
return False
if email in password:
return False
return True
def check_email_format(email):
"""
Checks that the email adheres to the rules defined by this function
:param email:
:return: True if ok
"""
email_regex = re.compile(r'([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+(\.[a-zA-Z]{2,4}))')
if not email_regex.match(email):
return False
return True
def is_user_registered(username):
"""
is the entered user registered on website?
:param username:
:return: True if registered
"""
query = FlicketUser.query.filter_by(username=username)
if query.count() == 1:
return True
return False
def is_registered_password_correct(username, password):
"""
:param username:
:param password:
:return: True if password is correct
"""
user = FlicketUser.query.filter_by(username=username).first()
hashed = user.password
password = password.encode('utf-8')
if bcrypt.hashpw(password, hashed) == hashed:
return True
return False
| 27.695122 | 94 | 0.599736 | 281 | 2,271 | 4.782918 | 0.370107 | 0.059524 | 0.035714 | 0.0625 | 0.25 | 0.162946 | 0.056548 | 0.056548 | 0 | 0 | 0 | 0.01005 | 0.298987 | 2,271 | 81 | 95 | 28.037037 | 0.834171 | 0.228974 | 0 | 0.315789 | 0 | 0.026316 | 0.167734 | 0.03265 | 0 | 0 | 0 | 0 | 0 | 1 | 0.105263 | false | 0.289474 | 0.105263 | 0 | 0.526316 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 2 |
43e2fa425d59dc177a3eea083f4f4041affb0e4e | 2,702 | py | Python | import-automation/import-progress-dashboard-api/app/model/import_attempt_model.py | fpernice-google/data | 049b6c0c42364aa59af1966bc270521208cfdab7 | [
"Apache-2.0"
] | 25 | 2020-07-18T04:44:57.000Z | 2022-03-03T14:44:20.000Z | import-automation/import-progress-dashboard-api/app/model/import_attempt_model.py | fpernice-google/data | 049b6c0c42364aa59af1966bc270521208cfdab7 | [
"Apache-2.0"
] | 276 | 2020-05-09T00:57:50.000Z | 2022-03-29T23:27:38.000Z | import-automation/import-progress-dashboard-api/app/model/import_attempt_model.py | fpernice-google/data | 049b6c0c42364aa59af1966bc270521208cfdab7 | [
"Apache-2.0"
] | 59 | 2020-05-09T00:45:30.000Z | 2022-03-28T16:03:53.000Z | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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.
"""
Data model of an import attempt.
"""
import enum
class ImportAttempt:
"""Data model of an import attempt.
This class is not a data class. The class variables below are the fields
of an import attempt and their values are the field names. They are used
to index import attempt entities.
"""
# ID of the import attempt as a string. This is a UUID hex string.
attempt_id = 'attempt_id'
# ID of the system run as a string. This is a UUID hex string.
run_id = 'run_id'
# Relative import name as a string parsed from the manifest.
import_name = 'import_name'
# Absolute import name as a string of the form
# <path to the directory with the manifest>:<import_name>, e.g.,
# scripts/us_fed/treasury:US_FED_constant_maturity_rates
absolute_import_name = 'absolute_import_name'
# Provenance URL parsed from the manifest.
provenance_url = 'provenance_url'
# Provenance description parsed from the manifest.
provenance_description = 'provenance_description'
# Status of the import attempt, as a string.
# Must be one of the defined values by ImportAttemptStatus.
status = 'status'
# Creation time as a string of the import attempt.
# Must be in ISO 8601 format with UTC timezone of the form
# 'YYYY-MM-DDTHH:MM:SS.ffffff+00:00', e.g.,
# '2020-06-30T04:28:53.717569+00:00'.
time_created = 'time_created'
# Completion time as a string of the import attempt. See time_created for
# format.
time_completed = 'time_completed'
# List of IDs of progress logs attached to this import attempt, each
# as a string.
logs = 'logs'
# List of import inputs. Each import input is a dict with three fields:
# import_input_url, node_mcf_url, and csv_url.
import_inputs = 'import_inputs'
class ImportAttemptStatus(enum.Enum):
"""Allowed status of an import attempt.
The status of an import attempt can only be one of these.
"""
CREATED = 'created'
SUCCEEDED = 'succeeded'
FAILED = 'failed'
IMPORT_ATTEMPT_STATUS = frozenset(
status.value for status in ImportAttemptStatus)
| 37.527778 | 77 | 0.716876 | 405 | 2,702 | 4.698765 | 0.387654 | 0.081976 | 0.037835 | 0.044666 | 0.217551 | 0.11403 | 0.086705 | 0.063058 | 0.030478 | 0 | 0 | 0.018824 | 0.213546 | 2,702 | 71 | 78 | 38.056338 | 0.876706 | 0.699482 | 0 | 0 | 0 | 0 | 0.209239 | 0.029891 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.421053 | 0 | 1.263158 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
78e1e63ab26c5dfebb854c11ba70a443c2fbcc6f | 2,007 | py | Python | source/main/punctuation.py | SN-18/scrivener | 76ca835b47f84ad231a6b4bf6ab9e212fc6b8724 | [
"MIT"
] | null | null | null | source/main/punctuation.py | SN-18/scrivener | 76ca835b47f84ad231a6b4bf6ab9e212fc6b8724 | [
"MIT"
] | 27 | 2021-10-21T18:39:01.000Z | 2021-11-05T14:17:29.000Z | source/main/punctuation.py | SN-18/scrivener | 76ca835b47f84ad231a6b4bf6ab9e212fc6b8724 | [
"MIT"
] | 2 | 2021-10-30T03:51:33.000Z | 2021-11-30T02:10:49.000Z | import os
try:
# hack: Unfortunately Heroku uses below file and it conflicts with the Punctuator package
# as suggested here: https://github.com/chrisspen/punctuator2/issues/3
# removing the file
os.remove('.heroku/python/bin/punctuator.py')
except BaseException:
print("punctuator.py not found in: " + os.getcwd())
from punctuator import Punctuator
from pathlib import Path
class Punctuation:
"""
A class used to add punctuation to transcripts
...
Attributes
----------
punct_model: object
a ML model for adding puctuation to strings
Methods
-------
add_punctuation_transcript:
Adds punctuation to string
"""
def __init__(self):
"""
Parameters
----------
youtube_url : str
link of youtube video
"""
@staticmethod
def add_punctuation_transcript(transcription):
"""
Using the generated transcript, add punctuation
"""
# initialize the punctuator ML model
# cwd = Path.cwd()
# template = "./source/punct_model_full.pcl"
# file_path = (cwd / template).resolve()
# print(cwd, flush=True)
punct_model = Punctuator(
os.path.abspath("source/punct_model_full.pcl"))
# Add punctuation to text
punct_text = punct_model.punctuate(transcription)
# replace punctuation errors, sometimes ML model will double up on punctuation, replace it such that there is
# only one punctuation which is correct
punct_text = (
punct_text.replace(",,", ",")
.replace("!,", "!")
.replace(".,", ".")
.replace("?,", "?")
.replace(",.", ",")
.replace("!.", "!")
.replace("..", ".")
.replace("?.", "?")
.replace('",', ',"')
.replace('".', '."')
.replace('"!', '!"')
.replace('"?', '?"')
)
return punct_text
| 27.875 | 117 | 0.549078 | 193 | 2,007 | 5.601036 | 0.533679 | 0.142461 | 0.194265 | 0.233117 | 0.120259 | 0.077706 | 0.077706 | 0.077706 | 0.077706 | 0.077706 | 0 | 0.001446 | 0.310912 | 2,007 | 71 | 118 | 28.267606 | 0.780188 | 0.416044 | 0 | 0 | 0 | 0 | 0.122115 | 0.056731 | 0 | 0 | 0 | 0 | 0 | 1 | 0.068966 | false | 0 | 0.103448 | 0 | 0.241379 | 0.034483 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
78e5e83dc155d7a87bacca5f9a8b2e490405c5a2 | 3,892 | py | Python | report/models.py | zyzik1248/pola-backend | 56614e24518d4aeeedba9f8e6889ed93d1927892 | [
"BSD-3-Clause"
] | null | null | null | report/models.py | zyzik1248/pola-backend | 56614e24518d4aeeedba9f8e6889ed93d1927892 | [
"BSD-3-Clause"
] | null | null | null | report/models.py | zyzik1248/pola-backend | 56614e24518d4aeeedba9f8e6889ed93d1927892 | [
"BSD-3-Clause"
] | null | null | null | import re
from os.path import basename
from babel.dates import format_timedelta
from django.conf import settings
from django.contrib.postgres.indexes import BrinIndex
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from reversion.models import Revision
from product.models import Product
class ReportQuerySet(models.QuerySet):
def only_open(self):
return self.filter(resolved_at__isnull=True).filter(resolved_by__isnull=True)
def only_resolved(self):
return self.filter(resolved_at__isnull=False).filter(resolved_by__isnull=False)
def resolve(self, user):
return self.update(resolved_at=timezone.now(), resolved_by=user)
class Report(models.Model):
product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE)
client = models.CharField(max_length=40, blank=True, null=True, default=None, verbose_name=_('Zgłaszający'))
created_at = models.DateTimeField(auto_now_add=True, verbose_name=_('Utworzone'))
resolved_at = models.DateTimeField(null=True, blank=True, verbose_name=_('Rozpatrzone'))
resolved_by = models.ForeignKey(
settings.AUTH_USER_MODEL, null=True, blank=True, verbose_name=_('Rozpatrzone przez'), on_delete=models.CASCADE,
)
description = models.TextField(verbose_name=_('Opis'))
objects = ReportQuerySet.as_manager()
def status(self):
if self.resolved_at is not None:
return self.RESOLVED
if self.resolved_by is not None:
return self.RESOLVED
return self.OPEN
def resolve(self, user, commit=True):
self.resolved_at = timezone.now()
self.resolved_by = user
if commit:
self.save()
def get_absolute_url(self):
return reverse('report:detail', args=[self.pk])
def __str__(self):
return self.description[:40] or "None"
def get_timedelta(self):
return format_timedelta(timezone.now() - self.created_at, locale='pl_PL')
def attachment_count(self):
return self.attachment_set.count()
OPEN = 1
RESOLVED = 2
class Meta:
verbose_name = _("Report")
verbose_name_plural = _("Reports")
ordering = ['-created_at']
get_latest_by = 'created_at'
permissions = (
# ("view_report", "Can see all report"),
# ("add_report", "Can add a new report"),
# ("change_report", "Can edit the report"),
# ("delete_report", "Can delete the report"),
)
indexes = [BrinIndex(fields=['created_at'], pages_per_range=16)]
class Attachment(models.Model):
report = models.ForeignKey(Report, on_delete=models.CASCADE)
attachment = models.FileField(upload_to="reports/%Y/%m/%d", verbose_name=_("File"))
@property
def filename(self):
return basename(self.attachment.name)
def __str__(self):
return "%s" % (self.filename)
def get_absolute_url(self):
return self.attachment.url
class Meta:
verbose_name = _("Report's attachment")
verbose_name_plural = _("Report's attachments")
# Command in reversion description.
COMMAND_REGEXP = re.compile(r'(?P<command>\w+)\s?\#(?P<pk>[0-9]+)', re.I)
@receiver(post_save, sender=Revision)
def on_revision_commit(instance, *args, **kwargs):
comment = instance.comment
search = COMMAND_REGEXP.search(comment)
if not search:
return
command = search.group('command')
pk = search.group('pk')
if command.lower() == 'close':
handle_command_close(instance, command, pk)
def handle_command_close(revision, command, pk):
report = Report.objects.only_open().get(pk=pk)
if report:
report.resolve(revision.user)
| 30.888889 | 119 | 0.684224 | 492 | 3,892 | 5.213415 | 0.315041 | 0.042885 | 0.02729 | 0.024561 | 0.120858 | 0.100585 | 0.05848 | 0 | 0 | 0 | 0 | 0.003219 | 0.201696 | 3,892 | 125 | 120 | 31.136 | 0.822337 | 0.050874 | 0 | 0.091954 | 0 | 0 | 0.061822 | 0.00949 | 0 | 0 | 0 | 0 | 0 | 1 | 0.16092 | false | 0 | 0.149425 | 0.114943 | 0.655172 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 2 |
78f2f0ba9ac203f59c9f14acd9cc16a28cd517ff | 431 | py | Python | commands/pre_1_13/parser/primitives/coordinate.py | Red-Teapot/mc-commandblock-1.13-update | 64106e1ecb5adca2aff1eeb3a1fcc11486940000 | [
"MIT"
] | 1 | 2020-07-27T16:53:26.000Z | 2020-07-27T16:53:26.000Z | commands/pre_1_13/parser/primitives/coordinate.py | Red-Teapot/mc-commandblock-1.13-update | 64106e1ecb5adca2aff1eeb3a1fcc11486940000 | [
"MIT"
] | 5 | 2019-01-02T14:21:32.000Z | 2019-07-07T05:39:39.000Z | commands/pre_1_13/parser/primitives/coordinate.py | Red-Teapot/mc-commandblock-1.13-update | 64106e1ecb5adca2aff1eeb3a1fcc11486940000 | [
"MIT"
] | null | null | null | class Coordinate(object):
def __init__(self, prefix, value):
self.prefix = prefix
self.value = value
def __str__(self):
if self.prefix:
if self.value:
return self.prefix + str(self.value)
else:
return self.prefix
else:
if self.value:
return str(self.value)
else:
return '0' | 25.352941 | 52 | 0.477958 | 44 | 431 | 4.5 | 0.295455 | 0.252525 | 0.111111 | 0.171717 | 0.222222 | 0 | 0 | 0 | 0 | 0 | 0 | 0.004149 | 0.440835 | 431 | 17 | 53 | 25.352941 | 0.817427 | 0 | 0 | 0.333333 | 0 | 0 | 0.002315 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.133333 | false | 0 | 0 | 0 | 0.466667 | 0 | 0 | 0 | 0 | null | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
60046b0a774ee3c805e60b1863e3ab1b17662069 | 2,819 | py | Python | test/lmp/infer/_base/test_signature.py | ProFatXuanAll/char-RNN | 531f101b3d1ba20bafd28ca060aafe6f583d1efb | [
"Beerware"
] | null | null | null | test/lmp/infer/_base/test_signature.py | ProFatXuanAll/char-RNN | 531f101b3d1ba20bafd28ca060aafe6f583d1efb | [
"Beerware"
] | null | null | null | test/lmp/infer/_base/test_signature.py | ProFatXuanAll/char-RNN | 531f101b3d1ba20bafd28ca060aafe6f583d1efb | [
"Beerware"
] | null | null | null | """Test :py:mod:`lmp.infer._base` signatures."""
import argparse
import inspect
from inspect import Parameter, Signature
from typing import Any, ClassVar, get_type_hints
import lmp.infer._base
from lmp.model import BaseModel
from lmp.tknzr import BaseTknzr
def test_module_attribute() -> None:
"""Ensure module attributes' signatures."""
assert hasattr(lmp.infer._base, 'BaseInfer')
assert inspect.isclass(lmp.infer._base.BaseInfer)
assert inspect.isabstract(lmp.infer._base.BaseInfer)
def test_class_attribute() -> None:
"""Ensure class attributes' signatures."""
print(get_type_hints(lmp.infer._base.BaseInfer))
assert get_type_hints(lmp.infer._base.BaseInfer) == {
'infer_name': ClassVar[str],
}
assert lmp.infer._base.BaseInfer.infer_name == 'base'
def test_class_method() -> None:
"""Ensure class methods' signatures."""
assert hasattr(lmp.infer._base.BaseInfer, 'add_CLI_args')
assert inspect.ismethod(lmp.infer._base.BaseInfer.add_CLI_args)
assert lmp.infer._base.BaseInfer.add_CLI_args.__self__ == lmp.infer._base.BaseInfer
assert inspect.signature(lmp.infer._base.BaseInfer.add_CLI_args) == Signature(
parameters=[
Parameter(
name='parser',
kind=Parameter.POSITIONAL_OR_KEYWORD,
default=Parameter.empty,
annotation=argparse.ArgumentParser,
),
],
return_annotation=None,
)
def test_instance_method() -> None:
"""Ensure instance methods' signatures."""
assert hasattr(lmp.infer._base.BaseInfer, '__init__')
assert inspect.signature(lmp.infer._base.BaseInfer.__init__) == Signature(
parameters=[
Parameter(
name='self',
kind=Parameter.POSITIONAL_OR_KEYWORD,
default=Parameter.empty,
),
Parameter(
name='max_seq_len',
kind=Parameter.POSITIONAL_OR_KEYWORD,
default=Parameter.empty,
annotation=int,
),
Parameter(
name='kwargs',
kind=Parameter.VAR_KEYWORD,
annotation=Any,
),
],
return_annotation=Signature.empty,
)
assert hasattr(lmp.infer._base.BaseInfer, 'gen')
assert 'gen' in lmp.infer._base.BaseInfer.__abstractmethods__
assert inspect.signature(lmp.infer._base.BaseInfer.gen) == Signature(
parameters=[
Parameter(
name='self',
kind=Parameter.POSITIONAL_OR_KEYWORD,
default=Parameter.empty,
),
Parameter(
name='model',
kind=Parameter.POSITIONAL_OR_KEYWORD,
default=Parameter.empty,
annotation=BaseModel,
),
Parameter(
name='tknzr',
kind=Parameter.POSITIONAL_OR_KEYWORD,
annotation=BaseTknzr,
),
Parameter(
name='txt',
kind=Parameter.POSITIONAL_OR_KEYWORD,
annotation=str,
),
],
return_annotation=str,
)
| 28.474747 | 85 | 0.680028 | 311 | 2,819 | 5.913183 | 0.21865 | 0.078303 | 0.117455 | 0.182708 | 0.586732 | 0.572594 | 0.450245 | 0.297988 | 0.213703 | 0.11093 | 0 | 0 | 0.203264 | 2,819 | 98 | 86 | 28.765306 | 0.818789 | 0.06669 | 0 | 0.433735 | 0 | 0 | 0.035701 | 0 | 0 | 0 | 0 | 0 | 0.168675 | 1 | 0.048193 | true | 0 | 0.084337 | 0 | 0.13253 | 0.012048 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
6006443d4fc5ca7d4d5170088ef9fd921be617a5 | 265 | py | Python | numerapi/__init__.py | stoyandimov/numerapi | 5f18bbd12f1d8979adfdc2e6c8c3ddcaa41f3e11 | [
"MIT"
] | 71 | 2020-04-10T06:09:15.000Z | 2022-03-18T14:03:08.000Z | numerapi/__init__.py | stoyandimov/numerapi | 5f18bbd12f1d8979adfdc2e6c8c3ddcaa41f3e11 | [
"MIT"
] | 18 | 2017-08-14T19:48:25.000Z | 2019-06-03T07:41:20.000Z | numerapi/__init__.py | stoyandimov/numerapi | 5f18bbd12f1d8979adfdc2e6c8c3ddcaa41f3e11 | [
"MIT"
] | 18 | 2017-07-08T06:01:51.000Z | 2019-10-01T15:46:43.000Z | import pkg_resources
try:
__version__ = pkg_resources.get_distribution(__name__).version
except pkg_resources.DistributionNotFound:
__version__ = 'unknown'
from numerapi.numerapi import NumerAPI # noqa
from numerapi.signalsapi import SignalsAPI # noqa
| 24.090909 | 66 | 0.807547 | 29 | 265 | 6.827586 | 0.517241 | 0.181818 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.135849 | 265 | 10 | 67 | 26.5 | 0.864629 | 0.033962 | 0 | 0 | 0 | 0 | 0.027668 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.428571 | 0 | 0.428571 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
60079803dd2855bdafe88cb47b097aa954ab33a3 | 623 | py | Python | Application/tests/unit/test_all_units.py | GianC0/IST-SOE | 250786d12507298c0a7909ed2cc6be0e3249df02 | [
"MIT"
] | null | null | null | Application/tests/unit/test_all_units.py | GianC0/IST-SOE | 250786d12507298c0a7909ed2cc6be0e3249df02 | [
"MIT"
] | null | null | null | Application/tests/unit/test_all_units.py | GianC0/IST-SOE | 250786d12507298c0a7909ed2cc6be0e3249df02 | [
"MIT"
] | 1 | 2021-12-22T15:21:53.000Z | 2021-12-22T15:21:53.000Z | import unittest
from test_aggregator import TestAggregator
from test_evaluator import TestEvaluator
from test_gui import TestGUI
from tests.unit.test_utilities import TestUtilities
class runner():
def runner(self):
suite = unittest.TestSuite()
suite.addTest(TestUtilities())
suite.addTest(TestAggregator())
suite.addTest(TestEvaluator())
suite.addTest(TestGUI())
return suite
#System is a class that simply merges together different component
# such that is impossible to be tested in unit-mode
suite = runner().runner()
unittest.TextTestRunner(verbosity=2).run(suite) | 32.789474 | 67 | 0.747994 | 75 | 623 | 6.16 | 0.56 | 0.103896 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.001946 | 0.17496 | 623 | 19 | 68 | 32.789474 | 0.896887 | 0.186196 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.066667 | false | 0 | 0.333333 | 0 | 0.533333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 2 |
601646f304d62fb0394899a598360101b8f1d7c8 | 5,007 | py | Python | UA_process.py | Daon1109/BD-Data-Storage | 397491b7b034fd0b509093bd42f87532df4a0d00 | [
"MIT"
] | null | null | null | UA_process.py | Daon1109/BD-Data-Storage | 397491b7b034fd0b509093bd42f87532df4a0d00 | [
"MIT"
] | null | null | null | UA_process.py | Daon1109/BD-Data-Storage | 397491b7b034fd0b509093bd42f87532df4a0d00 | [
"MIT"
] | null | null | null | #!C:\Program Files\Python39\python.exe
import cgi
form = cgi.FieldStorage()
import os
name = form["name"].value
link = form["link"].value
input_password = form["input_pw"].value
#This file directory is not available in Pythonanywhere repository (available in local network)
#I should google it
opened_file = open('C:\SERVER\\apache2\htdocs\BD Data Storage\Data\\'+name,'r',encoding="UTF-8")
lists = opened_file.readlines()
opened_file.close()
#password = "{}".format(lists[1])
password = lists[1]
#Deleting escape string(\n)
password = password[0:(len(password) - 1)]
month = lists[2]
date = lists[3]
if link == "update":
if input_password == password:
# Deleting Process
#This file directory is not available in Pythonanywhere too
fileToDelete = open('C:\SERVER\\apache2\htdocs\BD Data Storage\Data\\'+name,'w',encoding="UTF-8")
fileToDelete.close()
os.remove("Data/"+name)
#HTML Code
print("Content-type: text/html")
print()
print('''<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Update Page</title>
<link rel="stylesheet" href="UA_style.css">
<script src="nightMODE.js"></script>
</head>
<body>
<h1 class="main_title"><a href="index.py">BD Data Storage</a> - Update</h1>
<div class="Tools">
<a href="index.py">
<p class="homeLink">Home</p>
</a>
<a href="countdown_pipeline.py?id={name}">
<p class="cntdn_button">Countdown</p>
</a>
<input class="nightmode" type="button" value="NightMode" onclick="
nightDay(this);
">
</div>
<form action="update_process.py" method="post">
<div class="update">
<div class="update_index">Name</div>
<input id="input_text" class="update_input" type="text" value="{name}" name="name">
<br>
<div class="update_index">Password</div>
<input id="input_text" class="update_input" type="text" value="{password}" name="password">
<br>
<div class="update_index">Month and Date of the Birthday</div>
<input id="input_text" class="update_input" type="text" value="{month}" name="month"><br>
<input id="input_text" class="update_input" type="text" value="{date}" name="date"><br>
<input class="update_submit" type="submit" value="Update">
</div>
</form>
</body>
</html>'''.format(name=name, password=password, month=month, date=date))
else:
# Redirecting
# HTML Code
print("Content-type: text/html")
print()
print('''
<title>Wrong Password!</title>
<form name="myForm" action="UA_page.py" method="post">
<input type="hidden" name="name" value="{name}">
<input type="hidden" name="link" value="{link}">
</form>
<script>
alert('WRONG Password! Try Again');
document.myForm.submit();
</script>'''.format(name=name, link=link))
elif link == "delete":
if input_password == password:
# Deleting Process
#This file directory is not available in Pythonanywhere too
fileToDelete = open('C:\SERVER\\apache2\htdocs\BD Data Storage\Data\\'+name,'w',encoding="UTF-8")
fileToDelete.close()
os.remove("Data/"+name)
#Redirection
print("Location: index.py")
print()
else:
# Redirecting
# HTML Code
print("Content-type: text/html")
print()
print('''
<title>Wrong Password!</title>
<form name="myForm" action="UA_page.py" method="post">
<input type="hidden" name="name" value="{name}">
<input type="hidden" name="link" value="{link}">
</form>
<script>
alert('WRONG Password! Try Again');
document.myForm.submit();
</script>'''.format(name=name, link=link))
else:
# ERROR MESSAGE
# HTML Code
print("Content-type: text/html")
print()
print('''
<title>Error Occured</title>
<form name="myForm" action="UA_page.py" method="post">
<input type="hidden" name="name" value="{name}">
<input type="hidden" name="link" value="{link}">
</form>
<script>
alert('Error Occured. Please report bug: mathuho1109@gmail.com');
document.myForm.submit();
</script>'''.format(name=name, link=link))
| 36.547445 | 116 | 0.521869 | 538 | 5,007 | 4.806691 | 0.256506 | 0.034803 | 0.034803 | 0.044084 | 0.5785 | 0.562258 | 0.562258 | 0.562258 | 0.544084 | 0.509281 | 0 | 0.006235 | 0.327342 | 5,007 | 136 | 117 | 36.816176 | 0.76158 | 0.089475 | 0 | 0.533981 | 0 | 0.048544 | 0.733999 | 0.106446 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.116505 | 0.019417 | 0 | 0.019417 | 0.135922 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
60191fbb741d753ac7e83f39a53049f4d1618bc7 | 633 | py | Python | lib/bes/fs/checksum.py | reconstruir/bes | 82ff54b2dadcaef6849d7de424787f1dedace85c | [
"Apache-2.0"
] | null | null | null | lib/bes/fs/checksum.py | reconstruir/bes | 82ff54b2dadcaef6849d7de424787f1dedace85c | [
"Apache-2.0"
] | null | null | null | lib/bes/fs/checksum.py | reconstruir/bes | 82ff54b2dadcaef6849d7de424787f1dedace85c | [
"Apache-2.0"
] | null | null | null | #-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
from collections import namedtuple
from bes.common.check import check
class checksum(namedtuple('checksum', 'algorithm, checksum')):
SHA256 = 'sha256'
SHA1 = 'sha1'
MD5 = 'md5'
def __new__(clazz, algorithm, checksum):
check.check_string(algorithm)
check.check_string(checksum)
return clazz.__bases__[0].__new__(clazz, algorithm, checksum)
def __str__(self):
return '{}:{}'.format(self.algorithm, self.checksum)
def __repr__(self):
return str(self)
check.register_class(checksum, include_seq = False)
| 25.32 | 90 | 0.707741 | 81 | 633 | 5.234568 | 0.518519 | 0.120283 | 0.080189 | 0.117925 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.026071 | 0.151659 | 633 | 24 | 91 | 26.375 | 0.763501 | 0.1406 | 0 | 0 | 0 | 0 | 0.082873 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.2 | false | 0 | 0.133333 | 0.133333 | 0.8 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 2 |
601cd7b9327b0a0f24656c4ded5fa9aebe8451de | 2,438 | py | Python | app/runstate.py | DSurguy/nuzlocker | 62dac0079d83cb62b381e09fa43a220b952eac83 | [
"MIT"
] | null | null | null | app/runstate.py | DSurguy/nuzlocker | 62dac0079d83cb62b381e09fa43a220b952eac83 | [
"MIT"
] | 1 | 2018-02-07T02:12:03.000Z | 2018-02-07T02:13:24.000Z | app/runstate.py | DSurguy/nuzlocker | 62dac0079d83cb62b381e09fa43a220b952eac83 | [
"MIT"
] | null | null | null | from app.models.pokemon import Pokemon
from app.models.outcome import OutcomeType
class RunState:
def __init__(self, party=None, box=None, seen=None, graveyard=None, events=None):
self.party = party or []
self.box = box or []
self.seen = seen or {}
self.graveyard = graveyard or []
self.events = events or []
self.event_index = len(self.events)
def apply_event(self, event):
if event.apply(self):
self.events.append((self.event_index, event))
self.event_index += 1
return True
return False
def to_dict(self):
return {'party': [x.to_dict() for x in self.party],
'box': [x.to_dict() for x in self.box],
'seen': self.seen,
'graveyard': [x.to_dict() for x in self.graveyard],
'events': [x[1].to_dict() for x in self.events]}
def party_size(self):
return len(self.party)
def box_size(self):
return len(self.box)
def seen_on_route(self, route_id):
return self.seen.get(route_id) or []
def add_new_pokemon(self, pokemon):
if self.party_size() <= 5:
self.party.append(pokemon)
else:
self.box.append(pokemon)
def pokemon_death(self, pokemon_id):
pokemon = self._remove_from_party(pokemon_id)
if pokemon is not None:
pokemon.alive = False
self.graveyard.append(pokemon)
return True
return False
def _remove_from_party(self, pokemon_id):
return self._safe_remove_from_list(pokemon_id, self.party)
def _remove_from_box(self, pokemon_id):
return self._safe_remove_from_list(pokemon_id, self.box)
def _safe_remove_from_list(self, obj_id, lst):
obj = next((x for x in lst if x.uid == obj_id), None)
if obj is not None:
lst.remove(obj)
return obj
return None
def add_encounter(self, encounter):
if encounter.route_id not in self.seen:
self.seen[encounter.route_id] = []
if encounter.get_pokemon_id() not in self.seen[encounter.route_id]:
self.seen[encounter.route_id].append(encounter.get_pokemon_id())
if encounter.outcome == OutcomeType.CAUGHT:
self.add_new_pokemon(Pokemon(encounter.pokemon_uid, encounter.get_pokemon_id(), encounter.nickname))
return True
| 31.662338 | 112 | 0.612797 | 330 | 2,438 | 4.327273 | 0.172727 | 0.056723 | 0.021008 | 0.028011 | 0.251401 | 0.122549 | 0.111345 | 0.07563 | 0.07563 | 0.07563 | 0 | 0.001716 | 0.283019 | 2,438 | 76 | 113 | 32.078947 | 0.815217 | 0 | 0 | 0.086207 | 0 | 0 | 0.011075 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.206897 | false | 0 | 0.034483 | 0.103448 | 0.482759 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 2 |
601e153612d230b19c5cb00bf10c82ee3b6c4cdc | 6,552 | py | Python | chainer/function_hook.py | Evanc123/chainer | 929af7189b1271683200aa9b0ba6da2dd3dee110 | [
"MIT"
] | null | null | null | chainer/function_hook.py | Evanc123/chainer | 929af7189b1271683200aa9b0ba6da2dd3dee110 | [
"MIT"
] | null | null | null | chainer/function_hook.py | Evanc123/chainer | 929af7189b1271683200aa9b0ba6da2dd3dee110 | [
"MIT"
] | null | null | null | import chainer
class FunctionHook(object):
"""Base class of hooks for Functions.
:class:`~chainer.FunctionHook` is a callback object
that is registered to :class:`~chainer.FunctionNode`.
Registered function hooks are invoked before and after
forward and backward operations of each function.
Function hooks that derive :class:`FunctionHook` are required
to implement four methods:
:meth:`~chainer.FunctionHook.forward_preprocess`,
:meth:`~chainer.FunctionHook.forward_postprocess`,
:meth:`~chainer.FunctionHook.backward_preprocess`, and
:meth:`~chainer.FunctionHook.backward_postprocess`.
By default, these methods do nothing.
Specifically, when :meth:`~chainer.FunctionNode.__call__`
method of some function is invoked,
:meth:`~chainer.FunctionHook.forward_preprocess`
(resp. :meth:`~chainer.FunctionHook.forward_postprocess`)
of all function hooks registered to this function are called before
(resp. after) forward propagation.
Likewise, when :meth:`~chainer.Variable.backward` of some
:class:`~chainer.Variable` is invoked,
:meth:`~chainer.FunctionHook.backward_preprocess`
(resp. :meth:`~chainer.FunctionHook.backward_postprocess`)
of all function hooks registered to the function which holds this variable
as a gradient are called before (resp. after) backward propagation.
There are two ways to register :class:`~chainer.FunctionHook`
objects to :class:`~chainer.FunctionNode` objects.
First one is to use ``with`` statement. Function hooks hooked
in this way are registered to all functions within ``with`` statement
and are unregistered at the end of ``with`` statement.
.. admonition:: Example
The following code is a simple example in which
we measure the elapsed time of a part of forward propagation procedure
with :class:`~chainer.function_hooks.TimerHook`, which is a subclass of
:class:`~chainer.FunctionHook`.
>>> from chainer import function_hooks
>>> class Model(chainer.Chain):
... def __init__(self):
... super(Model, self).__init__()
... with self.init_scope():
... self.l = L.Linear(10, 10)
... def __call__(self, x1):
... return F.exp(self.l(x1))
>>> model1 = Model()
>>> model2 = Model()
>>> x = chainer.Variable(np.zeros((1, 10), np.float32))
>>> with chainer.function_hooks.TimerHook() as m:
... _ = model1(x)
... y = model2(x)
... print("Total time : " + str(m.total_time()))
... model3 = Model()
... z = model3(y) # doctest:+ELLIPSIS
Total time : ...
In this example, we measure the elapsed times for each forward
propagation of all functions in ``model1`` and ``model2``.
Note that ``model3`` is not a target of measurement
as :class:`~chainer.function_hooks.TimerHook` is unregistered
before forward propagation of ``model3``.
.. note::
Chainer stores the dictionary of registered function hooks
as a thread local object. So, function hooks registered
are different depending on threads.
The other one is to register directly to
:class:`~chainer.FunctionNode` object with
:meth:`~chainer.Function.add_hook` method.
Function hooks registered in this way can be removed by
:meth:`~chainer.Function.delete_hook` method.
Contrary to former registration method, function hooks are registered
only to the function which :meth:`~chainer.FunctionNode.add_hook`
is called.
Args:
name(str): Name of this function hook.
"""
name = 'FunctionHook'
def __enter__(self):
function_hooks = chainer.get_function_hooks()
if self.name in function_hooks:
raise KeyError('hook %s already exists' % self.name)
function_hooks[self.name] = self
self.added()
return self
def __exit__(self, *_):
chainer.get_function_hooks()[self.name].deleted()
del chainer.get_function_hooks()[self.name]
def added(self, function=None):
"""Callback function invoked when a function hook is added
Args:
function(~chainer.FunctionNode): Function object to which
the function hook is added.
"""
pass
def deleted(self, function=None):
"""Callback function invoked when a function hook is deleted
Args:
function(~chainer.FunctionNode): Function object to which
the function hook is deleted.
"""
pass
# forward
def forward_preprocess(self, function, in_data):
"""Callback function invoked before forward propagation.
Args:
function(~chainer.FunctionNode): Function object to which
the function hook is registered.
in_data(tuple of numpy.ndarray or tuple of cupy.ndarray):
Input data of forward propagation.
"""
pass
def forward_postprocess(self, function, in_data):
"""Callback function invoked after forward propagation.
Args:
function(~chainer.FunctionNode): Function object to which
the function hook is registered.
in_data(tuple of numpy.ndarray or tuple of cupy.ndarray):
Input data of forward propagation.
"""
pass
# backward
def backward_preprocess(self, function, in_data, out_grad):
"""Callback function invoked before backward propagation.
Args:
function(~chainer.FunctionNode): Function object to which
the function hook is registered.
in_data(tuple of numpy.ndarray or tuple of cupy.ndarray):
Input data of forward propagation.
out_grad(tuple of numpy.ndarray or tuple of cupy.ndarray):
Gradient data of backward propagation.
"""
pass
def backward_postprocess(self, function, in_data, out_grad):
"""Callback function invoked after backward propagation.
Args:
function(~chainer.FunctionNode): Function object to which
the function hook is registered.
in_data(tuple of numpy.ndarray or tuple of cupy.ndarray):
Input of forward propagation.
out_grad(tuple of numpy.ndarray or tuple of cupy.ndarray):
Gradient data of backward propagation.
"""
pass
| 37.655172 | 79 | 0.646062 | 766 | 6,552 | 5.437337 | 0.220627 | 0.059304 | 0.044178 | 0.044658 | 0.461465 | 0.343818 | 0.328932 | 0.289556 | 0.289556 | 0.266507 | 0 | 0.004364 | 0.265568 | 6,552 | 173 | 80 | 37.872832 | 0.86118 | 0.76221 | 0 | 0.24 | 0 | 0 | 0.036093 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.32 | false | 0.24 | 0.04 | 0 | 0.48 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
602a27d0d12db1f59d48cfd5765a3b6d79fe607b | 753 | py | Python | main.py | Mukundan314/gci-file-upload | c2d41a501302496aaeb514c799beaeb9cf2bd1da | [
"MIT"
] | 1 | 2021-05-29T04:27:55.000Z | 2021-05-29T04:27:55.000Z | main.py | Mukundan314/gci-file-upload | c2d41a501302496aaeb514c799beaeb9cf2bd1da | [
"MIT"
] | null | null | null | main.py | Mukundan314/gci-file-upload | c2d41a501302496aaeb514c799beaeb9cf2bd1da | [
"MIT"
] | null | null | null | import os
from flask import Flask, redirect, request, render_template, send_from_directory
from werkzeug.utils import secure_filename
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html', files=os.listdir('uploads'))
@app.route('/upload', methods=["POST"])
def upload():
filename = secure_filename(request.form.get('filename'))
if os.path.exists(os.path.join('uploads', filename)):
return render_template('title_taken.html', title=filename)
request.files['file'].save(os.path.join('uploads', filename))
return redirect("/")
@app.route('/uploads/<path:path>')
def get_upload(path):
return send_from_directory('uploads', path)
if __name__ == "__main__":
app.run(debug=True)
| 24.290323 | 80 | 0.707835 | 99 | 753 | 5.151515 | 0.414141 | 0.082353 | 0.066667 | 0.066667 | 0.121569 | 0.121569 | 0 | 0 | 0 | 0 | 0 | 0 | 0.130146 | 753 | 30 | 81 | 25.1 | 0.778626 | 0 | 0 | 0 | 0 | 0 | 0.142098 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.157895 | false | 0 | 0.157895 | 0.105263 | 0.526316 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 2 |
602e676e21abf317f33a65827689253fc6b18ed0 | 9,646 | py | Python | tests/time_test.py | rhettg/dmc | 3f714167871c48870b745a3f28eba1f587f50a84 | [
"0BSD"
] | 17 | 2015-01-07T21:38:10.000Z | 2019-04-21T12:22:12.000Z | tests/time_test.py | rhettg/dmc | 3f714167871c48870b745a3f28eba1f587f50a84 | [
"0BSD"
] | 1 | 2015-03-30T20:03:09.000Z | 2017-02-12T18:07:16.000Z | tests/time_test.py | rhettg/dmc | 3f714167871c48870b745a3f28eba1f587f50a84 | [
"0BSD"
] | 2 | 2017-02-12T17:38:38.000Z | 2021-02-16T01:03:04.000Z | from testify import *
import datetime
import pytz
from dmc import (
Time,
TimeInterval,
TimeSpan,
TimeIterator,
TimeSpanIterator)
class InitTimeTestCase(TestCase):
def test_direct(self):
d = Time(2014, 4, 18, 17, 50, 21)
assert_equal(d.year, 2014)
assert_equal(d.month, 4)
assert_equal(d.day, 18)
assert_equal(d.hour, 17)
assert_equal(d.minute, 50)
assert_equal(d.second, 21)
def test_direct_tz(self):
d = Time(2014, 4, 18, 17, 50, 21, tz='US/Pacific')
assert_equal(d.year, 2014)
assert_equal(d.month, 4)
assert_equal(d.day, 19)
assert_equal(d.hour, 1)
assert_equal(d.minute, 50)
assert_equal(d.second, 21)
def test_direct_local(self):
d = Time(2014, 4, 18, 17, 50, 21, local=True)
assert_equal(d.year, 2014)
assert_equal(d.month, 4)
# can't really say for sure
assert d.day in [18, 19]
assert_equal(d.minute, 50)
assert_equal(d.second, 21)
def test_timestamp(self):
ts = 1398125982.036391
t = Time.from_timestamp(ts)
assert_equal(t.year, 2014)
assert_equal(t.month, 4)
assert_equal(t.day, 22)
assert_equal(t.hour, 0)
assert_equal(t.minute, 19)
assert_equal(t.second, 42)
assert_equal(t.microsecond, 36391)
def test_datetime_naive(self):
dt = datetime.datetime(2014, 4, 18, 17, 50, 21)
t = Time.from_datetime(dt)
assert_equal(t.day, 18)
assert_equal(t.hour, 17)
assert_equal(t.minute, 50)
assert_equal(t.second, 21)
def test_datetime_tz(self):
dt = datetime.datetime(2014, 4, 18, 17, 50, 21)
dt = pytz.timezone('US/Pacific').localize(dt)
t = Time.from_datetime(dt)
assert_equal(t.year, 2014)
assert_equal(t.month, 4)
assert_equal(t.day, 19)
assert_equal(t.hour, 0)
assert_equal(t.minute, 50)
assert_equal(t.second, 21)
def test_str(self):
t = Time.from_str("2014-04-18T17:50:21.036391")
assert_equal(t.year, 2014)
assert_equal(t.month, 4)
assert_equal(t.day, 18)
assert_equal(t.hour, 17)
assert_equal(t.minute, 50)
assert_equal(t.second, 21)
def test_str_tz(self):
t = Time.from_str("2014-04-18T17:50:21.036391-07:00")
assert_equal(t.year, 2014)
assert_equal(t.month, 4)
assert_equal(t.day, 19)
assert_equal(t.hour, 0)
assert_equal(t.minute, 50)
assert_equal(t.second, 21)
def test_str_specify_tz(self):
t = Time.from_str("2014-04-18T17:50:21.036391", tz='US/Pacific')
assert_equal(t.year, 2014)
assert_equal(t.month, 4)
assert_equal(t.day, 19)
assert_equal(t.hour, 0)
assert_equal(t.minute, 50)
assert_equal(t.second, 21)
class ConvertTimeTestCase(TestCase):
@setup
def create_time(self):
self.t = Time(2014, 4, 18, 17, 50, 21, 36391)
def test_str(self):
assert_equal(self.t.to_str(), "2014-04-18T17:50:21.036391+00:00")
def test_str_tz(self):
assert_equal(self.t.to_str(tz='US/Pacific'), "2014-04-18T10:50:21.036391-07:00")
def test_str_local(self):
# We don't really konw
assert self.t.to_str(local=True)
def test_str_format(self):
assert_equal(self.t.to_str(format="%m/%d/%Y %H:%M"), "04/18/2014 17:50")
def test_timestamp(self):
assert_equal(self.t.to_timestamp(), 1397872221.036391)
def test_datetime(self):
dt = self.t.to_datetime()
assert_equal(dt.year, 2014)
assert_equal(dt.month, 4)
assert_equal(dt.day, 18)
assert_equal(dt.hour, 17)
assert_equal(dt.minute, 50)
assert_equal(dt.second, 21)
assert_equal(dt.tzinfo, pytz.UTC)
def test_datetime_tz(self):
dt = self.t.to_datetime(tz='US/Pacific')
assert_equal(dt.year, 2014)
assert_equal(dt.month, 4)
assert_equal(dt.day, 18)
assert_equal(dt.hour, 10)
assert_equal(dt.minute, 50)
assert_equal(dt.second, 21)
assert_equal(str(dt.tzinfo), 'US/Pacific')
def test_datetime_local(self):
dt = self.t.to_datetime(local=True)
assert_equal(dt.year, 2014)
assert_equal(dt.month, 4)
assert_equal(dt.minute, 50)
assert_equal(dt.second, 21)
def test_human(self):
# Just make sure it doesn't crash
assert self.t.to_human()
class ArithmeticTimeTest(TestCase):
def test_time_add(self):
t1 = Time(2014, 4, 18, 17, 50, 21)
ti = TimeInterval(2.22)
t2 = t1 + ti
assert_equal(t2.second, 23)
assert_equal(t2.microsecond, 220000)
def test_time_sub(self):
t1 = Time(2014, 4, 18, 17, 50, 21)
ti = TimeInterval(2.22)
t2 = t1 - ti
assert_equal(t2.second, 18)
assert_equal(t2.microsecond, 780000)
class InitTimeIntervalTest(TestCase):
def test_seconds(self):
i = TimeInterval(21)
assert_equal(i.seconds, 21)
assert_equal(i.microseconds, 0)
def test_float_seconds(self):
i = TimeInterval(1.2)
assert_equal(i.seconds, 1)
assert_equal(i.microseconds, 200000)
def test_minutes(self):
i = TimeInterval(minutes=2)
assert_equal(i.seconds, 120)
assert_equal(i.microseconds, 0)
def test_hours(self):
i = TimeInterval(hours=1)
assert_equal(i.seconds, 3600)
assert_equal(i.microseconds, 0)
def test_microseconds(self):
i = TimeInterval(microseconds=10)
assert_equal(i.seconds, 0)
assert_equal(i.microseconds, 10)
def test_microsecond_overflow(self):
i = TimeInterval(seconds=1.9, microseconds=200000)
assert_equal(i.seconds, 2)
assert_equal(i.microseconds, 100000)
def test_timedelta(self):
td = datetime.timedelta(days=1, seconds=10, microseconds=1000)
i = TimeInterval.from_timedelta(td)
assert_equal(i.seconds, round(td.total_seconds()))
assert_equal(i.microseconds, td.microseconds)
assert_equal(float(i), td.total_seconds())
class ConvertTimeIntervalTest(TestCase):
def test_int(self):
i = TimeInterval(4)
assert_equal(int(i), 4)
def test_int_round(self):
i = TimeInterval(4, microseconds=600000)
assert_equal(int(i), 5)
def test_float(self):
i = TimeInterval(4, microseconds=600000)
assert_equal(float(i), 4.6)
def test_str(self):
i = TimeInterval(hours=1, minutes=45, seconds=21, microseconds=600000)
assert_equal(str(i), "+01:45:21.6")
class ArithmeticTimeIntervalTest(TestCase):
def test_add(self):
i1 = TimeInterval(1)
i2 = TimeInterval(1)
i3 = i1 + i2
assert_equal(i3.seconds, 2)
def test_add_int(self):
i1 = TimeInterval(1)
i2 = 1
i3 = i1 + i2
assert_equal(i3.seconds, 2)
i4 = i2 + i1
assert_equal(i4.seconds, 2)
def test_sub(self):
i1 = TimeInterval(2)
i2 = TimeInterval(1)
i3 = i1 - i2
assert_equal(i3.seconds, 1)
def test_sub_neg(self):
i1 = TimeInterval(1)
i2 = TimeInterval(2)
i3 = i1 - i2
assert_equal(i3.seconds, -1)
def test_sub_int(self):
i1 = TimeInterval(2)
i2 = 1
i3 = i1 - i2
assert_equal(i3.seconds, 1)
i4 = i2 - i1
assert_equal(i4, -1)
def test_mul(self):
i1 = TimeInterval(2)
i2 = i1 * 3
assert_equal(int(i2), 6)
def test_div(self):
i1 = TimeInterval(5)
i2 = i1 / 2
assert_equal(float(i2), 2.5)
def test_div_micro(self):
i1 = TimeInterval(2, microseconds=22)
i2 = i1 / 2
assert_equal(i2.seconds, 1)
assert_equal(i2.microseconds, 11)
def test_abs(self):
i1 = TimeInterval(-2.22)
i2 = abs(i1)
assert_equal(float(i1), 2.22)
def test_abs(self):
i1 = TimeInterval(2.22)
i2 = abs(i1)
assert_equal(float(i1), 2.22)
def test_cmp(self):
assert_equal(TimeInterval(2.22), TimeInterval(2, microseconds=220000))
assert_gt(TimeInterval(2.22), TimeInterval(2.20))
assert_gt(TimeInterval(3.22), TimeInterval(2.5))
assert_lt(TimeInterval(0), TimeInterval(microseconds=1))
assert_lt(TimeInterval(-3), TimeInterval(2.5))
class TimeSpanTest(TestCase):
def test_iter(self):
t1 = Time.now()
t2 = Time.now() + 30
ts = TimeSpan(t1, t2)
start_t, end_t = ts
assert_equal(start_t, t1)
assert_equal(end_t, t2)
def test_get(self):
t1 = Time.now()
t2 = Time.now() + 30
ts = TimeSpan(t1, t2)
assert_equal(ts[0], t1)
assert_equal(ts[1], t2)
class TimeIteratorTest(TestCase):
def test(self):
start_t = Time.now()
end_t = start_t + 5*60
times = list(TimeIterator(TimeSpan(start_t, end_t), TimeInterval(60)))
assert_equal(len(times), 6)
assert_equal(times[0], start_t)
assert_equal(times[-1], end_t)
class TimeSpanIteratorTest(TestCase):
def test(self):
start_t = Time.now()
end_t = start_t + 5*60
times = list(TimeSpanIterator(TimeSpan(start_t, end_t), TimeInterval(60)))
assert_equal(len(times), 5)
assert_equal(times[0].start, start_t)
assert_equal(times[-1].end, end_t)
| 25.317585 | 88 | 0.599108 | 1,357 | 9,646 | 4.092115 | 0.112749 | 0.237709 | 0.075635 | 0.037637 | 0.579146 | 0.515397 | 0.47902 | 0.432019 | 0.408248 | 0.379074 | 0 | 0.099856 | 0.278457 | 9,646 | 380 | 89 | 25.384211 | 0.697989 | 0.008086 | 0 | 0.440299 | 0 | 0 | 0.026035 | 0.015475 | 0 | 0 | 0 | 0 | 0.473881 | 1 | 0.175373 | false | 0 | 0.014925 | 0 | 0.223881 | 0 | 0 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
603f47071f1595b3f75d28d0eef46c1b21b6b9c1 | 254 | py | Python | sw_data_loader/test/test_bbk_swdata.py | stealthness/sklearn-examples | e755fd3804cc15dd28ff2a38e299e80c83565d0a | [
"BSD-3-Clause"
] | null | null | null | sw_data_loader/test/test_bbk_swdata.py | stealthness/sklearn-examples | e755fd3804cc15dd28ff2a38e299e80c83565d0a | [
"BSD-3-Clause"
] | null | null | null | sw_data_loader/test/test_bbk_swdata.py | stealthness/sklearn-examples | e755fd3804cc15dd28ff2a38e299e80c83565d0a | [
"BSD-3-Clause"
] | null | null | null | from sw_data_loader.SWDataClassFile import SWData
import sw_path
print("run test")
data = SWData()
data.load_img_datafiles(sw_path.WORK_ROOT + "RES/TestFolder")
print(data.base_path)
print((len(data.data_classes)))
print(data.is_datafiles_all_same_dim()) | 31.75 | 61 | 0.814961 | 41 | 254 | 4.731707 | 0.609756 | 0.061856 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.062992 | 254 | 8 | 62 | 31.75 | 0.815126 | 0 | 0 | 0 | 0 | 0 | 0.086275 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.25 | 0 | 0.25 | 0.5 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 2 |
60486f79a6057e65b0e6e6132c0fd255d546a1cc | 699 | py | Python | packages/pycopy/v2.11.0.1/esp32/stubs/onewire.py | TheVinhLuong102/micropy-stubs | 55ff1773008f7c4dfc3d70a403986486226eb6b3 | [
"MIT"
] | 18 | 2019-07-11T13:31:09.000Z | 2022-01-27T06:38:40.000Z | packages/pycopy/v2.11.0.1/esp32/stubs/onewire.py | TheVinhLuong102/micropy-stubs | 55ff1773008f7c4dfc3d70a403986486226eb6b3 | [
"MIT"
] | 9 | 2019-09-01T21:44:49.000Z | 2022-02-04T20:55:08.000Z | packages/pycopy/v2.11.0.1/esp32/stubs/onewire.py | TheVinhLuong102/micropy-stubs | 55ff1773008f7c4dfc3d70a403986486226eb6b3 | [
"MIT"
] | 6 | 2019-10-08T05:31:21.000Z | 2021-04-22T10:21:01.000Z | """
Module: 'onewire' on esp32 1.11.0
"""
# MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v2.11.0.1 on 2019-07-26', machine='ESP32 module with ESP32')
# Stubber: 1.2.0
class OneWire:
''
MATCH_ROM = 85
SEARCH_ROM = 240
SKIP_ROM = 204
def _search_rom():
pass
def crc8():
pass
def readbit():
pass
def readbyte():
pass
def readinto():
pass
def reset():
pass
def scan():
pass
def select_rom():
pass
def write():
pass
def writebit():
pass
def writebyte():
pass
class OneWireError:
''
_ow = None
def const():
pass
| 13.442308 | 130 | 0.517883 | 87 | 699 | 4.08046 | 0.505747 | 0.197183 | 0.022535 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.094923 | 0.351931 | 699 | 51 | 131 | 13.705882 | 0.688742 | 0.25465 | 0 | 0.4375 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.375 | false | 0.375 | 0 | 0 | 0.53125 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
6050bd46ad6212c73ec0151a683faaab1fa569e5 | 29,763 | py | Python | src/weblayer/tests/ftests/test_api.py | thruflo/weblayer | 24d74f71cedd3855911477ed4952a311c83b0b5f | [
"Unlicense"
] | 3 | 2016-07-04T15:27:12.000Z | 2021-04-30T22:46:13.000Z | src/weblayer/tests/ftests/test_api.py | thruflo/weblayer | 24d74f71cedd3855911477ed4952a311c83b0b5f | [
"Unlicense"
] | null | null | null | src/weblayer/tests/ftests/test_api.py | thruflo/weblayer | 24d74f71cedd3855911477ed4952a311c83b0b5f | [
"Unlicense"
] | 3 | 2015-09-16T08:55:30.000Z | 2018-09-23T11:06:01.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Functional tests for a :ref:`weblayer` application using the
:ref:`request handler api`.
"""
import unittest
class TestBasics(unittest.TestCase):
""" Sanity check the basics of hooking up a request handler and returning
a simple response.
"""
def make_app(self, mapping):
from webtest import TestApp
from weblayer import Bootstrapper, WSGIApplication
config = {
'check_xsrf': False,
'cookie_secret': '...',
'static_files_path': 'static',
'template_directories': ['templates']
}
bootstrapper = Bootstrapper(settings=config, url_mapping=mapping)
application = WSGIApplication(*bootstrapper())
return TestApp(application)
def test_hello_world(self):
""" Can we hook up a request handler with a positional argument
from the request path and return a simple response?
"""
from weblayer import RequestHandler
class Handler(RequestHandler):
def get(self, world):
return u'hello %s' % world
mapping = [(r'/(.*)', Handler)]
app = self.make_app(mapping)
res = app.get('/world')
self.assertTrue(res.body == 'hello world')
def test_unicode_response(self):
""" Can we return unicode characters?
"""
from weblayer import RequestHandler
class Handler(RequestHandler):
def get(self):
return u'hello Ð'
mapping = [(r'/', Handler)]
app = self.make_app(mapping)
res = app.get('/')
self.assertTrue(res.unicode_body == u'hello Ð')
def test_mapping(self):
""" Can we hook up multiple handlers?
"""
from weblayer import RequestHandler
class A(RequestHandler):
def get(self):
return 'a'
class B(RequestHandler):
def get(self):
return 'b'
mapping = [(
r'/a',
A
), (
r'/.*',
B
)
]
app = self.make_app(mapping)
res = app.get('/a')
self.assertTrue(res.body == 'a')
res = app.get('/foobar')
self.assertTrue(res.body == 'b')
def test_groups(self):
""" Each group in the request path should be passed as to the handler
method as a positional argument.
"""
from weblayer import RequestHandler
class Handler(RequestHandler):
def get(self, *args):
return ''.join(args)
mapping = [(r'/(.)/(.)/(.)', Handler)]
app = self.make_app(mapping)
res = app.get('/a/b/c')
self.assertTrue(res.body == 'abc')
def test_head_method(self):
""" HEAD requests should use ``Hander.get`` iff ``'head'`` is exposed,
``get()`` is defined and ``head()`` isn't.
"""
from weblayer import RequestHandler
class Handler(RequestHandler):
def get(self):
return 'hello'
mapping = [(r'/', Handler)]
app = self.make_app(mapping)
res = app.head('/')
self.assertTrue(res.headers['Content-Length'] == '5')
def test_form_post(self):
""" POST requests should call ``Hander.post``.
"""
from weblayer import RequestHandler
class Handler(RequestHandler):
__all__ = ('get', 'post')
def get(self):
form = u'<form method="post"><input name="name" /></form>'
return u'What is your name? %s' % form
def post(self):
return u'Hello %s!' % self.request.params.get('name')
mapping = [(r'/', Handler)]
app = self.make_app(mapping)
res = app.get('/')
form = res.form
form['name'] = 'Brian'
res = form.submit()
self.assertTrue(res.body == 'Hello Brian!')
class TestResponse(unittest.TestCase):
""" Sanity check response generation.
"""
def make_app(self, mapping):
from webtest import TestApp
from weblayer import Bootstrapper, WSGIApplication
config = {
'cookie_secret': '...',
'static_files_path': 'static',
'template_directories': ['templates']
}
bootstrapper = Bootstrapper(settings=config, url_mapping=mapping)
application = WSGIApplication(*bootstrapper())
return TestApp(application)
def test_return_basestring(self):
""" Returning a ``basestring`` from a request handler method should
update the ``response.body``.
"""
from weblayer import RequestHandler
class A(RequestHandler):
def get(self):
return 'hello'
class B(RequestHandler):
def get(self):
return u'hellö'
mapping = [(r'/a', A), (r'/b', B)]
app = self.make_app(mapping)
res = app.get('/a')
self.assertTrue(res.body == 'hello')
res = app.get('/b')
self.assertTrue(res.unicode_body == u'hellö')
def test_return_none(self):
""" Returning ``None`` should fallback on ``self.response``.
"""
from weblayer import RequestHandler
class A(RequestHandler):
def get(self):
self.response.body = 'elephants'
return None
mapping = [(r'/', A)]
app = self.make_app(mapping)
res = app.get('/')
self.assertTrue(res.body == 'elephants')
def test_return_response(self):
""" Returning an :py:class:`~weblayer.interfaces.IResponse` from a
request handler method should overwrite and use ``self.response``.
"""
from weblayer import RequestHandler
from weblayer.base import Response
class A(RequestHandler):
def get(self):
response = Response(body='fandango', request=self.request)
response.environ['weblayer.test_return_response'] = 1
return response
mapping = [(r'/', A)]
app = self.make_app(mapping)
res = app.get('/', extra_environ={'weblayer.test_return_response': 0})
self.assertTrue(res.body == 'fandango')
self.assertTrue(res.environ['weblayer.test_return_response'])
def test_return_data(self):
""" Returning something other than a ``basestring``, ``None`` or
:py:class:`~weblayer.interfaces.IResponse`` should JSON encode it.
"""
from weblayer import RequestHandler
class A(RequestHandler):
def get(self):
return {'a': 'b'}
class B(RequestHandler):
def get(self):
return {'a': u'ß'}
mapping = [(r'/a', A), (r'/b', B)]
app = self.make_app(mapping)
res = app.get('/a')
self.assertTrue(res.body == '{"a": "b"}')
res = app.get('/b')
self.assertTrue(res.unicode_body == u'{"a": "ß"}')
class TestSettings(unittest.TestCase):
""" Sanity check ``self.settings``.
"""
def make_app(self, config, mapping):
from webtest import TestApp
from weblayer import Bootstrapper, WSGIApplication
bootstrapper = Bootstrapper(settings=config, url_mapping=mapping)
application = WSGIApplication(*bootstrapper())
return TestApp(application)
def test_required_settings_misses_raises_error(self):
""" You must provide required settings by default.
"""
from weblayer import RequestHandler
config = {}
mapping = [(r'/', RequestHandler)]
self.assertRaises(
KeyError,
self.make_app,
config,
mapping
)
def test_settings_available(self):
""" Settings are available as self.settings.
"""
from weblayer import RequestHandler
class A(RequestHandler):
def get(self):
return '%s %s' % (
self.settings['cookie_secret'],
self.settings.get('not_present', None)
)
config = {
'cookie_secret': '...',
'static_files_path': 'static',
'template_directories': ['templates']
}
mapping = [(r'/', A)]
app = self.make_app(config, mapping)
res = app.get('/')
self.assertTrue(res.body == '... None')
class TestAuth(unittest.TestCase):
""" Sanity check ``self.auth``.
"""
def make_app(self, mapping):
from webtest import TestApp
from weblayer import Bootstrapper, WSGIApplication
config = {
'cookie_secret': '...',
'static_files_path': 'static',
'template_directories': ['templates']
}
bootstrapper = Bootstrapper(settings=config, url_mapping=mapping)
application = WSGIApplication(*bootstrapper())
return TestApp(application)
def test_unauthenticated(self):
""" If there's no ``environ['REMOTE_USER']``,
``self.auth.is_authenticated`` is ``False`` and
``self.auth.current_user`` is ``None``.
"""
from weblayer import RequestHandler
class A(RequestHandler):
def get(self):
return '%s %s' % (
self.auth.is_authenticated,
self.auth.current_user
)
mapping = [(r'/', A)]
app = self.make_app(mapping)
res = app.get('/')
self.assertTrue(res.body == 'False None')
def test_authenticated(self):
""" If there is a ``environ['REMOTE_USER']``,
``self.auth.is_authenticated`` is ``True`` and
``self.auth.current_user`` is ``environ['REMOTE_USER']``.
"""
from weblayer import RequestHandler
class A(RequestHandler):
def get(self):
return '%s %s' % (
self.auth.is_authenticated,
self.auth.current_user
)
mapping = [(r'/', A)]
app = self.make_app(mapping)
res = app.get('/', extra_environ={'REMOTE_USER': '123456'})
self.assertTrue(res.body == 'True 123456')
class TestCookies(unittest.TestCase):
""" Sanity check ``self.cookies``.
"""
def make_app(self, cookie_secret, mapping):
from webtest import TestApp
from weblayer import Bootstrapper, WSGIApplication
config = {
'cookie_secret': cookie_secret,
'static_files_path': 'static',
'template_directories': ['templates']
}
bootstrapper = Bootstrapper(settings=config, url_mapping=mapping)
application = WSGIApplication(*bootstrapper())
return TestApp(application)
def test_set_and_get(self):
""" We can set and get a cookie.
"""
from weblayer import RequestHandler
class SetCookie(RequestHandler):
def get(self):
self.cookies.set('name', 'value')
class GetCookie(RequestHandler):
def get(self):
return self.cookies.get('name')
mapping = [(r'/set', SetCookie), (r'/get', GetCookie)]
app = self.make_app('abc', mapping)
app.get('/set')
res = app.get('/get')
self.assertTrue(res.body == 'value')
def test_forged_returns_none(self):
""" If we set the value of the cookie without using
``self.cookies.set()``, ``self.cookies.get()`` returns None.
"""
from weblayer import RequestHandler
class SetCookie(RequestHandler):
def get(self):
self.response.set_cookie('name', value='value')
class GetCookie(RequestHandler):
def get(self):
return '%s' % self.cookies.get('name')
mapping = [(r'/set', SetCookie), (r'/get', GetCookie)]
app = self.make_app('abc', mapping)
app.get('/set')
res = app.get('/get')
self.assertTrue(res.body == 'None')
class TestStatic(unittest.TestCase):
""" Sanity check ``self.static``.
"""
def setUp(self):
""" Make sure ``./static/foo.js`` contains only::
var foo = {};
"""
from os.path import dirname, join as join_path
file_path = join_path(dirname(__file__), 'static', 'foo.js')
sock = open(file_path, 'w')
sock.write('var foo = {};')
sock.close()
def tearDown(self):
""" Make sure ``./static/foo.js`` contains only::
var foo = {};
"""
from os.path import dirname, join as join_path
file_path = join_path(dirname(__file__), 'static', 'foo.js')
sock = open(file_path, 'w')
sock.write('var foo = {};')
sock.close()
def make_app(self, mapping, **extra_config):
from os.path import dirname, join as join_path
from webtest import TestApp
from weblayer import Bootstrapper, WSGIApplication
config = {
'cookie_secret': '...',
'static_files_path': join_path(dirname(__file__), 'static'),
'template_directories': ['templates']
}
config.update(extra_config)
bootstrapper = Bootstrapper(settings=config, url_mapping=mapping)
application = WSGIApplication(*bootstrapper())
return TestApp(application)
def test_no_qs_if_file_doesnt_exist(self):
""" If the file doesn't exist, don't add a ``v=...`` part to the
query string.
"""
from weblayer import RequestHandler
class A(RequestHandler):
def get(self):
return self.static.get_url('not_there.js')
mapping = [(r'/', A)]
app = self.make_app(mapping)
res = app.get('/')
self.assertTrue(res.body == 'http://localhost/static/not_there.js')
def test_qs_if_file_exists(self):
""" If the file does exist, add the first few chars of a hash digest of
of the file contents to the query string.
"""
from weblayer import RequestHandler
class A(RequestHandler):
def get(self):
return self.static.get_url('foo.js')
mapping = [(r'/', A)]
app = self.make_app(mapping)
res = app.get('/')
self.assertTrue(res.body == 'http://localhost/static/foo.js?v=fc075b5')
def test_qs_cached_in_memory_despite_file_content_changing(self):
""" The hexdigest snippet is cached in memory and doesn't automatically
update when the underlying file changes.
"""
from os.path import dirname, join as join_path
from weblayer import RequestHandler
class A(RequestHandler):
def get(self):
return self.static.get_url('foo.js')
mapping = [(r'/', A)]
app = self.make_app(mapping)
res = app.get('/')
self.assertTrue(res.body == 'http://localhost/static/foo.js?v=fc075b5')
# change the file
file_path = join_path(dirname(__file__), 'static', 'foo.js')
sock = open(file_path, 'w')
sock.write('var foo = {\'changed\': true};')
sock.close()
# the qs *hasn't* changed
res = app.get('/')
self.assertTrue(res.body == 'http://localhost/static/foo.js?v=fc075b5')
def test_qs_changed_when_cache_cleared(self):
""" If we clear the cache, then the underlying file content change
is reflected in the query string.
"""
from os.path import dirname, join as join_path
from weblayer import RequestHandler
class A(RequestHandler):
def get(self):
return self.static.get_url('foo.js')
class B(RequestHandler):
def get(self):
""" n.b.: this hack only clears the cache for this process.
Don't do this in real code.
"""
static_files = self.settings['static_files_path']
file_path = join_path(static_files, 'foo.js')
del self.static._cache[file_path]
mapping = [(r'/a', A), (r'/b', B)]
app = self.make_app(mapping)
res = app.get('/a')
self.assertTrue(res.body == 'http://localhost/static/foo.js?v=fc075b5')
# change the file
file_path = join_path(dirname(__file__), 'static', 'foo.js')
sock = open(file_path, 'w')
sock.write('var foo = {\'changed\': true};')
sock.close()
# clear the cache
res = app.get('/b')
# the qs *has* changed
res = app.get('/a')
self.assertTrue(res.body == 'http://localhost/static/foo.js?v=114b07a')
# clear the cache
res = app.get('/b')
def test_host_url(self):
""" Uses the host url of the request.
"""
from weblayer import RequestHandler
class A(RequestHandler):
def get(self):
return self.static.get_url('foo.js')
mapping = [(r'/', A)]
app = self.make_app(mapping)
res = app.get('/', extra_environ={'HTTP_HOST': 'foo.com:1234'})
self.assertTrue(
res.body == 'http://foo.com:1234/static/foo.js?v=fc075b5'
)
def test_static_host_url(self):
""" Unless ``settings['static_host_url']`` is provided.
"""
from weblayer import RequestHandler
class A(RequestHandler):
def get(self):
return self.static.get_url('foo.js')
mapping = [(r'/', A)]
app = self.make_app(mapping, static_host_url='http://static.foo.com')
res = app.get('/')
self.assertTrue(
res.body == 'http://static.foo.com/static/foo.js?v=fc075b5'
)
res = app.get('/', extra_environ={'HTTP_HOST': 'foo.com:1234'})
self.assertTrue(
res.body == 'http://static.foo.com/static/foo.js?v=fc075b5'
)
class TestXSRF(unittest.TestCase):
""" Sanity check validating against XSRF attacks.
"""
def make_app(self, mapping):
from webtest import TestApp
from weblayer import Bootstrapper, WSGIApplication
config = {
'cookie_secret': '...',
'static_files_path': 'static',
'template_directories': ['templates']
}
bootstrapper = Bootstrapper(settings=config, url_mapping=mapping)
application = WSGIApplication(*bootstrapper())
return TestApp(application)
def test_form_post_using_xsrf_input(self):
""" If ``self.xsrf_input`` is included in the form POST it validates.
"""
from weblayer import RequestHandler
class Handler(RequestHandler):
__all__ = ('get', 'post')
def get(self):
inputs = u'%s<input name="name" />' % self.xsrf_input
form = u'<form method="post">%s</form>' % inputs
return u'What is your name? %s' % form
def post(self):
return u'Hello %s!' % self.request.params.get('name')
mapping = [(r'/', Handler)]
app = self.make_app(mapping)
res = app.get('/')
form = res.form
form['name'] = 'Brian'
res = form.submit()
self.assertTrue(res.body == 'Hello Brian!')
def test_form_post_without_xsrf_input(self):
""" If ``self.xsrf_input`` is not included in the form POST it,
fails to validate.
"""
from webtest import AppError
from weblayer import RequestHandler
class Handler(RequestHandler):
__all__ = ('get', 'post')
def get(self):
form = u'<form method="post"><input name="name" /></form>'
return u'What is your name? %s' % form
def post(self):
""" Never gets called
"""
mapping = [(r'/', Handler)]
app = self.make_app(mapping)
res = app.get('/')
form = res.form
form['name'] = 'Brian'
self.assertRaises(AppError, form.submit)
try:
result = form.submit()
except AppError, err:
self.assertTrue('403 Forbidden' in str(err))
class TestError(unittest.TestCase):
""" Sanity check ``self.error()``.
"""
def make_app(self, mapping):
from webtest import TestApp
from weblayer import Bootstrapper, WSGIApplication
config = {
'cookie_secret': '...',
'static_files_path': 'static',
'template_directories': ['templates']
}
bootstrapper = Bootstrapper(settings=config, url_mapping=mapping)
application = WSGIApplication(*bootstrapper())
return TestApp(application)
def test_return_vanilla_error(self):
""" Returning ``self.error()`` results in a 500 response.
"""
from webtest import AppError
from weblayer import RequestHandler
class A(RequestHandler):
def get(self):
return self.error()
mapping = [(r'/', A)]
app = self.make_app(mapping)
self.assertRaises(AppError, app.get, '/')
try:
result = app.get('/')
except AppError, err:
self.assertTrue('500 Internal Server Error' in str(err))
def test_return_specific_error(self):
""" Returning a specific error results in an appropriate response.
"""
from webtest import AppError
from weblayer import RequestHandler
class A(RequestHandler):
def get(self):
return self.error(status=501)
mapping = [(r'/', A)]
app = self.make_app(mapping)
self.assertRaises(AppError, app.get, '/')
try:
result = app.get('/')
except AppError, err:
self.assertTrue('501 Not Implemented' in str(err))
class TestRedirect(unittest.TestCase):
""" Sanity check ``self.redirect()``.
"""
def make_app(self, mapping):
from webtest import TestApp
from weblayer import Bootstrapper, WSGIApplication
config = {
'cookie_secret': '...',
'static_files_path': 'static',
'template_directories': ['templates']
}
bootstrapper = Bootstrapper(settings=config, url_mapping=mapping)
application = WSGIApplication(*bootstrapper())
return TestApp(application)
def test_redirect(self):
""" Returning ``self.redirect(url)`` results in a 302 response.
"""
from webtest import AppError
from weblayer import RequestHandler
class A(RequestHandler):
def get(self):
return self.redirect('/b')
mapping = [(r'/', A)]
app = self.make_app(mapping)
status = app.get('/').status
self.assertTrue(status == '302 Found')
def test_redirect_location(self):
""" Returning ``self.redirect(url)`` uses either the host url or full
url if provided.
"""
from webtest import AppError
from weblayer import RequestHandler
class A(RequestHandler):
def get(self):
return self.redirect('/b')
class B(RequestHandler):
def get(self):
return self.redirect('http://foo.com/c')
mapping = [(r'/a', A), (r'/b', B)]
app = self.make_app(mapping)
res = app.get('/a').follow()
self.assertTrue(res.headers['location'] == 'http://foo.com/c')
def test_permanent_redirect(self):
""" Returning ``self.redirect(url, permanent=True)`` returns a 301.
"""
from webtest import AppError
from weblayer import RequestHandler
class A(RequestHandler):
def get(self):
return self.redirect('/b', permanent=True)
mapping = [(r'/', A)]
app = self.make_app(mapping)
status = app.get('/').status
self.assertTrue(status == '301 Moved Permanently')
class TestRender(unittest.TestCase):
""" Sanity check ``self.render()``.
"""
def make_app(self, mapping):
from os.path import dirname, join as join_path
from webtest import TestApp
from weblayer import Bootstrapper, WSGIApplication
config = {
'cookie_secret': '...',
'static_files_path': join_path(dirname(__file__), 'static'),
'template_directories': [join_path(dirname(__file__), 'templates')]
}
bootstrapper = Bootstrapper(settings=config, url_mapping=mapping)
application = WSGIApplication(*bootstrapper())
return TestApp(application)
def test_builtins(self):
""" Returning ``self.render(tmpl_name)`` renders ``tmpl_name``, passing
through keyword arguments to the template's global namespace, along
with the builtins defined in :py:mod:`~weblayer.template`.
"""
import datetime
from weblayer import RequestHandler
class A(RequestHandler):
def get(self):
kwargs = {
'url': 'http://foo.com/b ar',
'data': {'a': u'b'},
}
return self.render('builtins.tmpl', **kwargs)
mapping = [(r'/', A)]
app = self.make_app(mapping)
res = app.get('/')
self.assertTrue('{"a": "b"}' in res)
self.assertTrue('http%3A%2F%2Ffoo.com%2Fb+ar' in res)
self.assertTrue(datetime.datetime.min in res)
def test_request_variables(self):
""" Returning ``self.render(tmpl_name)`` renders ``tmpl_name``, passing
through the ``request``, ``current_user``, ``get_static_url`` and
``xsrf_input``.
"""
from webtest import AppError
from weblayer import RequestHandler
class A(RequestHandler):
__all__ = ('get', 'post')
def get(self):
return self.render('request.tmpl')
def post(self):
return u'Hello %s!' % self.request.params.get('name')
mapping = [(r'/', A)]
app = self.make_app(mapping)
res = app.get('/?foo=bar', extra_environ={'REMOTE_USER': 'brian'})
self.assertTrue('foo: bar' in res)
self.assertTrue('user: brian' in res)
self.assertTrue(
'static url: http://localhost/static/not_present.js' in res
)
form = res.form
form['name'] = 'Brian'
res = form.submit()
self.assertTrue(res.body == 'Hello Brian!')
| 28.67341 | 79 | 0.50042 | 2,879 | 29,763 | 5.065648 | 0.113581 | 0.023999 | 0.050603 | 0.054306 | 0.722641 | 0.681912 | 0.651879 | 0.636999 | 0.612246 | 0.610464 | 0 | 0.005014 | 0.38353 | 29,763 | 1,037 | 80 | 28.701061 | 0.789841 | 0.005073 | 0 | 0.689781 | 0 | 0 | 0.098707 | 0.005416 | 0 | 0 | 0 | 0 | 0.083942 | 0 | null | null | 0 | 0.122263 | null | null | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
6058abb4e7ab2d17f992e6edaf1f2dd37e88ae0c | 12,125 | py | Python | python-siren/setup.py | zliobaite/teeth-redescription | e6f33aefbe693500c25062880fbdde73a75c1aba | [
"MIT"
] | null | null | null | python-siren/setup.py | zliobaite/teeth-redescription | e6f33aefbe693500c25062880fbdde73a75c1aba | [
"MIT"
] | null | null | null | python-siren/setup.py | zliobaite/teeth-redescription | e6f33aefbe693500c25062880fbdde73a75c1aba | [
"MIT"
] | null | null | null | """
This is a setup.py script generated by py2applet
Usage (OS X):
python setup.py py2app
Usage (Windows):
python setup.py py2exe
Edits by Pauli
"""
import sys
import os
import os.path
import re
import subprocess
import pdb
import glob
import time
from siren.common_details import common_variables
# Common info
APP = common_variables["MAIN_FILENAME"]
NAME = common_variables["PACKAGE_NAME"]
SHORT_NAME = common_variables["PROJECT_NAME"]
VERSION = common_variables["VERSION"]
DESCRIPTION = common_variables["PROJECT_DESCRIPTION"]
DESCRIPTION_LONG = common_variables["PROJECT_DESCRIPTION_LONG"]
AUTHOR = common_variables["PROJECT_AUTHORS"]
AUTHOR_EMAIL = common_variables["MAINTAINER_EMAIL"]
URL = common_variables["PROJECT_URL"]
LICENSE="Apache_2.0"
COPYRIGHT=u'\u00A9 '+common_variables["COPYRIGHT_YEAR_FROM"]+'-' \
+common_variables["COPYRIGHT_YEAR_FROM"]+' ' \
+common_variables["PROJECT_AUTHORS"]
HELP_PACKAGE_FILENAME = 'help.tar.gz'
HELP_PACKAGE_URL = URL+HELP_PACKAGE_FILENAME
HELP_UNPACK_CMD = 'tar xfz '+HELP_PACKAGE_FILENAME # command to unpack the help file to folder help/
extra_options = dict(
name=NAME,
version=VERSION,
description=(DESCRIPTION),
author=AUTHOR,
author_email=AUTHOR_EMAIL,
url=URL,
license=LICENSE,
)
##### helpers
def get_svnrevision():
svn_revision = '-1'
try:
p = subprocess.check_output(['svn', 'info'])
except (subprocess.CalledProcessError, OSError):
print "No SVN found, using default svn revision (-1) instead"
else:
for line in p.splitlines():
l = line.split()
if l[0] == 'Revision:':
svn_revision = l[1]
break
return svn_revision
def get_git_hash():
git_hash = '-1'
try:
git_hash = subprocess.check_output('git rev-parse HEAD', shell=True)
except (subprocess.CalledProcessError, OSError):
print "No GIT found, using default git revision (-1) instead"
return git_hash.strip()
def load_help_files():
try:
subprocess.check_call('curl "'+HELP_PACKAGE_URL+'" -o"'+HELP_PACKAGE_FILENAME+'"', shell=True)
except CalledProcessError as e:
sys.stderr.write('Downloading the help package failed, aborting:\n'+str(e))
sys.exit(e.returncode)
try:
subprocess.check_call(HELP_UNPACK_CMD, shell=True)
except CalledProcessError as e:
sys.stderr.write('Unpacking the help package failed, aborting:\n'+str(e))
sys.exit(e.returncode)
try:
subprocess.check_call('mv help/ siren/data/', shell=True);
except CalledProcessError as e:
sys.stderr.write('Moving the help files to siren/data/help/ failed:\n'+str(e))
sys.exit(e.returncode)
def clean_help_files():
subprocess.call('rm -rf help/', shell=True)
subprocess.call('rm -rf siren/data/help/', shell=True)
subprocess.call('rm -rf '+HELP_PACKAGE_FILENAME, shell=True)
#### platform specific
if sys.platform == 'darwin':
################ MAC SETUP
# Bootstrap
import ez_setup
ez_setup.use_setuptools()
from setuptools import setup
# Get help files
load_help_files()
# Rename exec_siren.py as Siren.py
subprocess.call('cp '+APP+' Siren.py', shell=True)
# A custom plist to associate with .siren -files
Plist = dict(CFBundleDocumentTypes = [dict(CFBundleTypeExtensions=['siren'],
CFBundleTypeName='Siren data file',
CFBundleTypeRole = 'Viewer',
CFBundleTypeIconFile = 'siren/data/icons/siren_file_icon.icns'),
dict(CFBundleTypeName = 'fi.helsinki.cs.siren.csv',
CFBundleTypeRole = 'Viewer',
LSHandlerRank = 'Alternate',
LSItemContentTypes = ['public.comma-separated-values-text'])
],
CFBundleShortVersionString = VERSION,
CFBundleVersion = get_git_hash(),
CFBundleName = SHORT_NAME,
CFBundleIdentifier = "fi.helsinki.cs.siren",
NSHumanReadableCopyright = COPYRIGHT
)
ST_PACKAGES = ['wx', 'sklearn', 'mpl_toolkits']
ST_RESOURCES=['siren/data/help', 'LICENSE', 'CHANGELOG',
'siren/interface/ui_confdef.xml','siren/views/views_confdef.xml', 'siren/reremi/miner_confdef.xml', 'siren/reremi/inout_confdef.xml']
ICONS = ['siren/data/icons/siren_icon.icns', 'siren/data/icons/siren_file_icon.icns', 'siren/data/icons/siren_icon32x32.png', 'siren/data/icons/siren_icon.ico', 'siren/data/icons/usiren_icon.ico']
LICENSES = ['siren/data/licenses'] #'LICENSE_basemap', 'LICENSE_matplotlib', 'LICENSE_python', 'LICENSE_wx', 'LICENSE_grako']
MATPLOTLIB_BACKENDS = ['wxagg']
OPTIONS = {'argv_emulation': True,
'iconfile': 'siren/data/icons/siren_icon.icns',
'packages': ST_PACKAGES,
#'matplotlib_backends': MATPLOTLIB_BACKENDS,
#'includes': ['ui_confdef.xml'],
#'includes': ['reremi'],
'resources': ST_RESOURCES+ICONS+LICENSES,
'site_packages': True,
'includes': ['server_siren.py'],
#'semi-standalone': True, # depends on local Python
'plist': Plist,
}
# Set extra options
extra_options.update(dict(
app=['Siren.py'],
#data_files=[APP],
options={'py2app': OPTIONS},
setup_requires=['py2app']
))
# Run setup
setup(**extra_options)
# Post setup
# Copy files
print "Copying files..."
subprocess.call('cp LICENSE dist/', shell=True)
subprocess.call('mkdir dist/third-party-licenses/', shell=True)
for f in LICENSES:
subprocess.call('cp '+f+'/LICENSE* dist/third-party-licenses/', shell=True)
subprocess.call('cp licenses/README_mac.rtf dist/README.rtf', shell=True)
subprocess.call('cp CHANGELOG dist/CHANGELOG', shell=True)
subprocess.call('cp help/Siren-UserGuide.pdf dist/UserGuide.pdf', shell=True)
subprocess.call('ln -s /Applications dist/', shell=True)
subprocess.call('cp siren/data/icons/siren_dmg_icon.icns dist/.VolumeIcon.icns', shell=True)
# Set VolumeIcon's creator
subprocess.call('SetFile -c icnC dist/.VolumeIcon.icns', shell=True)
# Make read/write tmp disk image
print "Creating initial disk image"
subprocess.call('hdiutil create -srcfolder dist/ -volname '+SHORT_NAME+' -format UDRW -ov raw-'+SHORT_NAME+'.dmg', shell=True)
# Attach the disk image
subprocess.call('mkdir tmp', shell=True)
subprocess.call('hdiutil attach raw-'+SHORT_NAME+'.dmg -mountpoint tmp', shell=True)
# Set custom icon
subprocess.call('SetFile -a C tmp', shell=True)
# Detach
print "Detaching"
time.sleep(2)
subprocess.call('hdiutil detach tmp', shell=True)
subprocess.call('rm -rf tmp', shell=True)
subprocess.call('rm -f '+SHORT_NAME+'.dmg', shell=True)
# Convert
print "Converting the disk image to the final one"
time.sleep(1)
subprocess.call('hdiutil convert raw-'+SHORT_NAME+'.dmg -format UDZO -o '+SHORT_NAME+'.dmg', shell=True)
# Clean
subprocess.call('rm -rf dist build', shell=True)
subprocess.call('rm -f raw-'+SHORT_NAME+'.dmg', shell=True)
# Clean help files
print "Cleaning help files"
clean_help_files()
elif sys.platform == 'win32':
################ WINDOWS SETUP
## Should this be 'win64'??
from distutils.core import setup
import py2exe
import matplotlib
ST_PACKAGES = ['wx', 'sklearn', 'mpl_toolkits']
DU_PACKAGES = ['siren', 'siren.reremi', 'siren.interface', 'siren.work', 'siren.views', 'siren.reremi.grako']
PACKAGE_DATA = {'data\\conf': ['siren\\reremi\\miner_confdef.xml', 'siren\\reremi\\inout_confdef.xml', 'siren\\views\\views_confdef.xml', 'siren\\interface\\ui_confdef.xml',],
'data\\icons': glob.glob('siren\\data\\icons\\*.png') + glob.glob('siren\\data\\icons\\*.ico'),
'data\\help': glob.glob('siren\\data\\help\\*'),
'data\\licenses': ['LICENSE']+glob.glob('siren\\data\\licenses\\LICENSE*'),
'': ['LICENSE']}
OPTIONS = {
'compressed': True,
'packages': DU_PACKAGES+ST_PACKAGES,
'dll_excludes': ['MSVCP90.dll','api-ms-win-core-string-l1-1-0.dll', 'api-ms-win-core-memory-l1-1-2.dll', 'api-ms-win-core-file-l1-2-1.dll', 'api-ms-win-core-libraryloader-l1-2-1.dll',
'api-ms-win-core-string-l2-1-0.dll', 'api-ms-win-core-profile-l1-1-0.dll', 'api-ms-win-core-string-obsolete-l1-1-0.dll', 'api-ms-win-core-debug-l1-1-1.dll', 'api-ms-win-core-sidebyside-l1-1-0.dll',
'api-ms-win-core-processthreads-l1-1-2.dll','api-ms-win-core-kernel32-legacy-l1-1-1.dll','api-ms-win-core-handle-l1-1-0.dll','api-ms-win-core-timezone-l1-1-0.dll','api-ms-win-core-processenvironment-l1-2-0.dll',
'api-ms-win-core-processenvironment-l1-2-0.dll', 'api-ms-win-core-registry-l1-1-0.dll', 'api-ms-win-core-util-l1-1-0.dll', 'api-ms-win-core-atoms-l1-1-0.dll', 'api-ms-win-core-winrt-error-l1-1-1.dll', 'api-ms-win-core-heap-l1-2-0.dll',
'api-ms-win-core-heap-l2-1-0.dll', 'api-ms-win-core-delayload-l1-1-1.dll', 'api-ms-win-core-rtlsupport-l1-2-0.dll', 'api-ms-win-core-libraryloader-l1-2-0.dll', 'api-ms-win-core-localization-l1-2-1.dll', 'api-ms-win-core-sysinfo-l1-2-1.dll',
'api-ms-win-core-synch-l1-2-0.dll', 'api-ms-win-core-errorhandling-l1-1-1.dll', 'api-ms-win-core-shlwapi-obsolete-l1-2-0.dll', 'api-ms-win-core-localization-obsolete-l1-3-0.dll', 'api-ms-win-security-base-l1-2-0.dll',
'QtCore4.dll','QGui4.dll','QtNetwork4.dll'],
'includes' : ['matplotlib.backends.backend_wx', 'scipy.special.*', 'scipy.linalg.*', 'scipy.sparse.csgraph._validation','scipy.special._ufuncs_cxx','matplotlib.backends.backend_tkagg'],
'excludes': ['matplotlib.backends.backend_qt4agg', 'PySide.QtSvg', 'PySide.QtNetwork', 'PySide.QtGui', 'PySide.QtCore', 'win32con', 'Tkinter', 'IPython', 'jupyter_core', '_sqlite3',
'email', '_gtkagg', '_tkagg', '_ssl', 'nose', 'pygments', 'doctest', 'scipy.ndimage', 'pandas', 'win32clipboard',
'tornado', 'PIL', 'pydoc_data', 'curses', 'PySide', 'certifi'],
}
###
# Set extra options
MPL = matplotlib.get_py2exe_datafiles()
## C:\\Python27\\
bsm_files = [f for f in glob.glob('C:\\Users\\pc-perso\\AppData\\Local\\Enthought\\Canopy\\User\\Lib\\site-packages\\mpl_toolkits\\basemap\\data\\*') if not re.search("_f.dat", f)]
MTK = [('mpl_toolkits\\basemap\\data', bsm_files)]
extra_options.update(dict(
windows=[{"script": APP, "icon_resources": [(1, "siren\\data\\icons\\siren_icon.ico")]}],
data_files= PACKAGE_DATA.items() + MPL + MTK,
options={'py2exe': OPTIONS})
)
# Run setup
setup(**extra_options)
else:
################ LINUX SETUP
from distutils.core import setup
DU_FILES = [APP[:-3], "server_siren"]
DU_PACKAGES = ['siren', 'siren.reremi', 'siren.interface', 'siren.work', 'siren.views', 'siren.reremi.grako']
PACKAGE_DATA = {'siren.reremi': ['miner_confdef.xml', 'inout_confdef.xml'],
'siren.views': ['views_confdef.xml'],
'siren.interface': ['ui_confdef.xml'],
'siren': ['data/icons/*.png', 'data/icons/*.ico', 'data/help/*', 'data/licenses/LICENSE*']}
extra_options.update(dict(
platforms="UNIX",
description=DESCRIPTION,
long_description=DESCRIPTION_LONG,
package_data=PACKAGE_DATA,
packages=DU_PACKAGES,
py_modules=DU_FILES
))
# Run setup
setup(**extra_options)
| 44.413919 | 245 | 0.624742 | 1,514 | 12,125 | 4.885073 | 0.241083 | 0.025149 | 0.033532 | 0.046106 | 0.369659 | 0.291509 | 0.214575 | 0.184018 | 0.11371 | 0.085046 | 0 | 0.014658 | 0.217897 | 12,125 | 272 | 246 | 44.577206 | 0.765264 | 0.061361 | 0 | 0.158974 | 1 | 0.005128 | 0.405861 | 0.212884 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.076923 | null | null | 0.035897 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
605aaab08a04c413f122d3d648b036aa10ef0e2d | 412 | py | Python | IsThisAValidTeamName/stats/admin.py | ksajan/iis-ms-del | 6339f639d674fedb88454b43dcd64493be2a4558 | [
"MIT"
] | 2 | 2019-12-24T13:32:22.000Z | 2019-12-26T11:26:08.000Z | IsThisAValidTeamName/stats/admin.py | ksajan/iis-ms-del | 6339f639d674fedb88454b43dcd64493be2a4558 | [
"MIT"
] | 1 | 2019-12-26T07:53:34.000Z | 2019-12-26T07:53:34.000Z | IsThisAValidTeamName/stats/admin.py | ksajan/iis-ms-del | 6339f639d674fedb88454b43dcd64493be2a4558 | [
"MIT"
] | 35 | 2019-12-22T05:05:43.000Z | 2019-12-22T07:16:56.000Z | from django.contrib import admin
from .models import Company, BotRun
# Register your models here.
@admin.register(Company)
class CompanyAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'code', 'amount_from', 'amount_to', 'risk_factor',)
@admin.register(BotRun)
class BotRunAdmin(admin.ModelAdmin):
list_display = ('id', 'company', 'user', 'money', 'days', 'investment_returned', 'return_percent') | 37.454545 | 102 | 0.730583 | 50 | 412 | 5.88 | 0.62 | 0.088435 | 0.129252 | 0.176871 | 0.190476 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.11165 | 412 | 11 | 102 | 37.454545 | 0.803279 | 0.063107 | 0 | 0 | 0 | 0 | 0.249351 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.25 | 0 | 0.75 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
606c2efada985488baddd403b59eb26b8101d408 | 889 | py | Python | zerver/filters.py | yakkl/yakkl | 89ecf4ee8998554a0634667067e16f428e4c480c | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | zerver/filters.py | yakkl/yakkl | 89ecf4ee8998554a0634667067e16f428e4c480c | [
"ECL-2.0",
"Apache-2.0"
] | 4 | 2020-06-06T00:51:42.000Z | 2022-02-10T21:38:40.000Z | zerver/filters.py | yakkl/yakkl | 89ecf4ee8998554a0634667067e16f428e4c480c | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
import re
from typing import Any, Dict
from django.http import HttpRequest
from django.views.debug import SafeExceptionReporterFilter
class YakklExceptionReporterFilter(SafeExceptionReporterFilter):
def get_post_parameters(self, request: HttpRequest) -> Dict[str, Any]:
filtered_post = SafeExceptionReporterFilter.get_post_parameters(self, request).copy()
filtered_vars = ['content', 'secret', 'password', 'key', 'api-key', 'subject', 'stream',
'subscriptions', 'to', 'csrfmiddlewaretoken', 'api_key',
'realm_counts', 'installation_counts']
for var in filtered_vars:
if var in filtered_post:
filtered_post[var] = '**********'
return filtered_post
def clean_data_from_query_parameters(val: str) -> str:
return re.sub(r"([a-z_-]+=)([^&]+)([&]|$)", r"\1******\3", val)
| 40.409091 | 96 | 0.64342 | 94 | 889 | 5.893617 | 0.553191 | 0.086643 | 0.061372 | 0.075812 | 0.101083 | 0 | 0 | 0 | 0 | 0 | 0 | 0.002853 | 0.211474 | 889 | 21 | 97 | 42.333333 | 0.787447 | 0 | 0 | 0 | 0 | 0 | 0.181306 | 0.028153 | 0 | 0 | 0 | 0 | 0 | 1 | 0.125 | false | 0.0625 | 0.25 | 0.0625 | 0.5625 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 2 |
607e57fd93ec78101f79963ed3fe8704a913dc61 | 50 | py | Python | net/constants.py | ggidofalvy-tc/peering-manager | 0c358b108494f51936264f3ec5d600c20827a745 | [
"Apache-2.0"
] | 173 | 2020-08-08T15:38:08.000Z | 2022-03-21T11:35:25.000Z | net/constants.py | ggidofalvy-tc/peering-manager | 0c358b108494f51936264f3ec5d600c20827a745 | [
"Apache-2.0"
] | 192 | 2020-08-08T22:03:45.000Z | 2022-03-31T04:20:44.000Z | net/constants.py | ggidofalvy-tc/peering-manager | 0c358b108494f51936264f3ec5d600c20827a745 | [
"Apache-2.0"
] | 33 | 2020-08-14T21:24:38.000Z | 2022-03-06T14:55:13.000Z | # VLAN bounds
VLAN_MIN = 1
VLAN_MAX = 2 ** 12 - 2
| 12.5 | 22 | 0.62 | 10 | 50 | 2.9 | 0.7 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.135135 | 0.26 | 50 | 3 | 23 | 16.666667 | 0.648649 | 0.22 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
6088128bf2c4a9f82c825ad1b4a21c3f291f8001 | 8,578 | py | Python | vmware_nsx/tests/unit/nsx_v3/test_client_cert.py | salv-orlando/vmware-nsx | 6ad0d595aa8099004eb6dd5ff62c7a91b0e11dfd | [
"Apache-2.0"
] | null | null | null | vmware_nsx/tests/unit/nsx_v3/test_client_cert.py | salv-orlando/vmware-nsx | 6ad0d595aa8099004eb6dd5ff62c7a91b0e11dfd | [
"Apache-2.0"
] | null | null | null | vmware_nsx/tests/unit/nsx_v3/test_client_cert.py | salv-orlando/vmware-nsx | 6ad0d595aa8099004eb6dd5ff62c7a91b0e11dfd | [
"Apache-2.0"
] | null | null | null | # Copyright (c) 2015 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from unittest import mock
from oslo_config import cfg
from neutron.tests.unit import testlib_api
from vmware_nsx.common import exceptions as nsx_exc
from vmware_nsx.plugins.common_v3 import utils
from vmware_nsx.plugins.nsx_v3 import cert_utils
class NsxV3ClientCertProviderTestCase(testlib_api.SqlTestCase):
CERT = "-----BEGIN CERTIFICATE-----\n" \
"MIIDJTCCAg0CBFh36j0wDQYJKoZIhvcNAQELBQAwVzELMAkGA1UEBhMCVVMxEzAR\n" \
"BgNVBAgMCkNhbGlmb3JuaWExDjAMBgNVBAoMBU15T3JnMQ8wDQYDVQQLDAZNeVVu\n" \
"aXQxEjAQBgNVBAMMCW15b3JnLmNvbTAeFw0xNzAxMTIyMDQyMzdaFw0yNzAxMTAy\n" \
"MDQyMzdaMFcxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMQ4wDAYD\n" \
"VQQKDAVNeU9yZzEPMA0GA1UECwwGTXlVbml0MRIwEAYDVQQDDAlteW9yZy5jb20w\n" \
"ggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC/wsYintlWVaSeXwaSrdPa\n" \
"+AHtL1ooH7q0uf6tt+6Rwiy10YRjAVJhapj9995gqgJ2402J+3gzNXLCbXjjDR/D\n" \
"9xjAzKHu61r0AVNd9/0+8yXQrEDuzlwHSCKz+zjq5ZEZ7RkLIUdreaZJFPTCwry3\n" \
"wuTnBfqcE7xWl6WfWR8evooV+ZzIfjQdoSliIyn3YGxNN5pc1P40qt0pxOsNBGXG\n" \
"2FIZXpML8TpKw0ga/wE70CJd6tRvSsAADxQXehfKvGtHvlJYS+3cTahC7reQXJnc\n" \
"qsjgYkiWyhhR4jdcTD/tDlVcJroM1jFVxpsCg/AU3srWWWeAGyVe42ZhqWVf0Urz\n" \
"AgMBAAEwDQYJKoZIhvcNAQELBQADggEBAA/lLfmXe8wPyBhN/VMb5bu5Ey56qz+j\n" \
"jCn7tz7FjRvsB9P0fLUDOBKNwyon3yopDNYJ4hnm4yKoHCHURQLZKWHzm0XKzE+4\n" \
"cA/M13M8OEg5otnVVHhz1FPQWnJq7bLHh/KXYcc5Rkc7UeHEPj0sDjfUjCPGdepc\n" \
"Ghu1ZcgHsL4JCuvcadG+RFGeDTug3yO92Fj2uFy5DlzzWOZSi4otpZRd9JZkAtZ1\n" \
"umZRBJ2A504nJx4MplmNqvLNkmxMLKQdvZYNNiYr6icOavDOJA5RhzgoppJZkV2w\n" \
"v2oC+8BFarXnZSk37HAWjwcaqzBLbIyPYpClW5IYMr8LiixSBACc+4w=\n" \
"-----END CERTIFICATE-----\n"
PKEY = "-----BEGIN PRIVATE KEY-----\n" \
"MIIEwAIBADANBgkqhkiG9w0BAQEFAASCBKowggSmAgEAAoIBAQC/wsYintlWVaSe\n" \
"XwaSrdPa+AHtL1ooH7q0uf6tt+6Rwiy10YRjAVJhapj9995gqgJ2402J+3gzNXLC\n" \
"bXjjDR/D9xjAzKHu61r0AVNd9/0+8yXQrEDuzlwHSCKz+zjq5ZEZ7RkLIUdreaZJ\n" \
"FPTCwry3wuTnBfqcE7xWl6WfWR8evooV+ZzIfjQdoSliIyn3YGxNN5pc1P40qt0p\n" \
"xOsNBGXG2FIZXpML8TpKw0ga/wE70CJd6tRvSsAADxQXehfKvGtHvlJYS+3cTahC\n" \
"7reQXJncqsjgYkiWyhhR4jdcTD/tDlVcJroM1jFVxpsCg/AU3srWWWeAGyVe42Zh\n" \
"qWVf0UrzAgMBAAECggEBAJrGuie9cQy3KZzOdD614RaPMPbhTnKuUYOH0GEk4YFy\n" \
"aaYDS0iiC30njf8HLs10y3JsOuyRNU6X6F24AGe68xW3/pm3UUjHXG0wGLry68wA\n" \
"c1g/gFV/6FXUSnZc4m7uBjUX4yvRm5TK5oV8TaZZifsEar9xWvrZDx4RXpQEWhL0\n" \
"L/TyrOZSfRtBgdWX6Ag4XQVsCfZxJoCi2ZyvaMBsWTH06x9AGo1Io5t1AmA9Hsfb\n" \
"6BsSz186nqb0fq4UMfrWrSCz7M/1s03+hBOVICH2TdaRDZLtDVa1b2x4sFpfdp9t\n" \
"VVxuSHxcmvzOPMIv3NXwj0VitTYYJDBFKoEfx1mzhNkCgYEA59gYyBfpsuCOevP2\n" \
"tn7IeysbtaoKDzHE+ksjs3sAn6Vr2Y0Lbed26NpdIVL6u3HAteJxqrIh0zpkpAtp\n" \
"akdqlj86oRaBUqLXxK3QNpUx19f7KN7UsVAbzUJSOm2n1piPg261ktfhtms2rxnQ\n" \
"+9yluINu+z1wS4FG9SwrRmwwfsUCgYEA072Ma1sj2MER5tmQw1zLANkzP1PAkUdy\n" \
"+oDuJmU9A3/+YSIkm8dGprFglPkLUaf1B15oN6wCJVMpB1lza3PM/YT70rpqc7cq\n" \
"PHJXQlZFMBhyVfIkCv3wICTLD5phhgAWlzlwm094f2uAnbG6WUkrVfZajuh0pW53\n" \
"1i0OTfxAvlcCgYEAkDB2oSM2JhjApDlMbA2HtAqIbkA1h2OlpSDMMFjEd4WTALdW\n" \
"r2CwNHtyRkJsS92gQ750gPvOS6daZifuxLlr0cu7M+piPbmnRdvvzbKWUC40NyP2\n" \
"1dwDnnGr4EjIhI9XWh+lb5EyAJjHZrlAnxOIQawEft6kE2FwdxSkSWUJ+B0CgYEA\n" \
"n2xYDXzRwKGdmPK2zGFRd5IRw9yLYNcq+vGYXdBb4Aa+wOO0LJYd2+Qxk/jvTMvo\n" \
"8WNjlIcuFmxGuAHhpUXLUhaOhFtXS0jdxCVTDd9muI+vhoaKHLyVz53kRhs20m2+\n" \
"lJ3q6wUq9MU8UX8/j3pH5rFV/cOIEAbcs6W4337OQIECgYEAoLtQyqXjH45FlCQx\n" \
"xK8dY+GuxIP+TIwiq23yhu3e+3LIgXJw8DwBFN5yJyH2HMnhGkD4PurEx2sGHeLO\n" \
"EG6L8PNDOxpvSzcgxwmZsUK6j3nAbKycF3PDDXA4kt8WDXBr86OMQsFtpjeO+fGh\n" \
"YWJa+OKc2ExdeMewe9gKIDQ5stw=\n" \
"-----END PRIVATE KEY-----\n"
def _init_config(self, storage_type='nsx-db',
password=None, cert_file=None):
cfg.CONF.set_override('nsx_use_client_auth', True, 'nsx_v3')
cfg.CONF.set_override('nsx_client_cert_storage',
storage_type, 'nsx_v3')
cfg.CONF.set_override('nsx_client_cert_file', cert_file, 'nsx_v3')
cfg.CONF.set_override('nsx_client_cert_pk_password',
password, 'nsx_v3')
# pk password secret is cached - reset it for each test
cert_utils.reset_secret()
self._provider = utils.get_client_cert_provider()
def validate_db_provider(self, expected_cert_data):
fname = None
with self._provider() as p:
# verify cert data was exported to CERTFILE
fname = p.filename()
with open(fname, 'r') as f:
actual = f.read()
self.assertEqual(expected_cert_data, actual)
# after with statement, cert file should be deleted
self.assertFalse(os.path.isfile(fname))
def validate_basic_provider(self, expected_cert_data):
fname = None
with self._provider as p:
fname = p.filename()
with open(fname, 'r') as f:
actual = f.read()
self.assertEqual(expected_cert_data, actual)
# with statement should not touch the file
self.assertTrue(os.path.isfile(fname))
def test_db_provider_without_cert(self):
"""Verify init fails if no cert is provided in client cert mode"""
# certificate not generated - exception should be raised
self._init_config()
# no certificate in table
mock.patch(
"vmware_nsx.db.db.get_certificate",
return_value=(None, None)).start()
self.assertRaises(nsx_exc.ClientCertificateException,
self._provider().__enter__)
# now verify return to normal after failure
mock.patch(
"vmware_nsx.db.db.get_certificate",
return_value=(self.CERT, self.PKEY)).start()
self.validate_db_provider(self.CERT + self.PKEY)
def test_db_provider_with_cert(self):
"""Verify successful certificate load from storage"""
self._init_config()
mock.patch(
"vmware_nsx.db.db.get_certificate",
return_value=(self.CERT, self.PKEY)).start()
self.validate_db_provider(self.CERT + self.PKEY)
def test_db_provider_with_encryption(self):
"""Verify successful encrypted PK load from storage"""
password = 'topsecret'
self._init_config(password=password)
secret = cert_utils.generate_secret_from_password(password)
encrypted_pkey = cert_utils.symmetric_encrypt(secret, self.PKEY)
# db should contain encrypted key
mock.patch(
"vmware_nsx.db.db.get_certificate",
return_value=(self.CERT, encrypted_pkey)).start()
self.validate_db_provider(self.CERT + self.PKEY)
def test_db_provider_with_bad_decrypt(self):
"""Verify loading plaintext PK from storage fails in encrypt mode"""
mock.patch(
"vmware_nsx.db.db.get_certificate",
return_value=(self.CERT, self.PKEY)).start()
# after decrypt failure, cert will be deleted
mock.patch(
"vmware_nsx.db.db.delete_certificate").start()
self._init_config(password='topsecret')
# since PK in DB is not encrypted, we should fail to decrypt it on load
self.assertRaises(nsx_exc.ClientCertificateException,
self._provider().__enter__)
def test_basic_provider(self):
fname = '/tmp/cert.pem'
# with basic provider, the file is provided by admin
with open(fname, 'w') as f:
f.write(self.CERT)
f.write(self.PKEY)
self._init_config(storage_type='none', cert_file=fname)
with self._provider as p:
self.assertEqual(fname, p.filename())
self.validate_basic_provider(self.CERT + self.PKEY)
os.remove(fname)
| 44.216495 | 79 | 0.707624 | 810 | 8,578 | 7.328395 | 0.350617 | 0.013646 | 0.014151 | 0.018868 | 0.18969 | 0.17217 | 0.168464 | 0.168464 | 0.146563 | 0.128369 | 0 | 0.057735 | 0.206458 | 8,578 | 193 | 80 | 44.445596 | 0.814309 | 0.150152 | 0 | 0.277778 | 0 | 0 | 0.449689 | 0.419462 | 0 | 0 | 0 | 0 | 0.055556 | 1 | 0.063492 | false | 0.055556 | 0.055556 | 0 | 0.142857 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
60a9efbf568e64d9c18d42d746fbcde94b0b1b78 | 829 | py | Python | Python3/python_lang/string_functions.py | sreeise/Programming-Reference | c77f6a46abab28b8f0f4a56ebd9843310b19d489 | [
"MIT"
] | 2 | 2019-04-28T00:56:22.000Z | 2019-08-03T17:41:19.000Z | Python3/python_lang/string_functions.py | sreeise/ProgrammingSnippets | c77f6a46abab28b8f0f4a56ebd9843310b19d489 | [
"MIT"
] | 1 | 2018-07-10T22:33:12.000Z | 2018-07-16T22:30:35.000Z | Python3/python_lang/string_functions.py | sreeise/ProgrammingSnippets | c77f6a46abab28b8f0f4a56ebd9843310b19d489 | [
"MIT"
] | null | null | null | # Checks if all characters of a string are alphanumeric (a-z, A-Z and 0-9).
c = "qA2"
print(c.isalnum())
# Checks if all the characters of a string are alphabetical (a-z and A-Z).
print(c.isalpha())
# Checks if all characters in a string are digits.
print(c.isdigit())
# Checks if all characters in a string are lowercase
print(c.islower())
# Checks if all characters of a string are uppercase
print(c.isupper())
def is_al_num(s):
return s.isalnum()
def alpha(s):
return s.isalpha()
def run_method_for_each_char(s):
print(any([char.isalnum() for char in s]))
print(any([char.isalpha() for char in s]))
print(any([char.isdigit() for char in s]))
print(any([char.islower() for char in s]))
print(any([char.isupper() for char in s]))
if __name__ == "__main__":
run_method_for_each_char(c) | 23.685714 | 75 | 0.683957 | 145 | 829 | 3.786207 | 0.289655 | 0.07286 | 0.100182 | 0.118397 | 0.513661 | 0.400729 | 0.400729 | 0.240437 | 0 | 0 | 0 | 0.004412 | 0.179735 | 829 | 35 | 76 | 23.685714 | 0.802941 | 0.358263 | 0 | 0 | 0 | 0 | 0.020873 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.166667 | false | 0 | 0 | 0.111111 | 0.277778 | 0.555556 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 2 |
60aaee8733f7a771ae58d1ee9e66ec2a0ab0ae5b | 157 | py | Python | src/convert.py | NathanHouwaart/EmotionRecognition | 4eb4478286a1dc925f8b4983923e31c421700338 | [
"MIT"
] | null | null | null | src/convert.py | NathanHouwaart/EmotionRecognition | 4eb4478286a1dc925f8b4983923e31c421700338 | [
"MIT"
] | null | null | null | src/convert.py | NathanHouwaart/EmotionRecognition | 4eb4478286a1dc925f8b4983923e31c421700338 | [
"MIT"
] | null | null | null | import cntk as C
model_path = "./out/model_98.cntk"
z = C.Function.load(model_path, device=C.device.cpu())
z.save("model.onnx", format=C.ModelFormat.ONNX)
| 22.428571 | 54 | 0.726115 | 28 | 157 | 3.964286 | 0.607143 | 0.162162 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.014085 | 0.095541 | 157 | 6 | 55 | 26.166667 | 0.767606 | 0 | 0 | 0 | 0 | 0 | 0.184713 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.25 | 0 | 0.25 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
60ab232d8c4a0ee63033d4b6eaecf99e3ed70a59 | 325 | py | Python | budget/views.py | lnsmith/ScoutCampfires | 5ee3058648ab3b3854e369f7dc25c41aa31ac9bd | [
"MIT"
] | null | null | null | budget/views.py | lnsmith/ScoutCampfires | 5ee3058648ab3b3854e369f7dc25c41aa31ac9bd | [
"MIT"
] | null | null | null | budget/views.py | lnsmith/ScoutCampfires | 5ee3058648ab3b3854e369f7dc25c41aa31ac9bd | [
"MIT"
] | null | null | null | from django.shortcuts import render
from django.http import HttpResponse
from .models import BudgetItem
def budget(request):
budgetItems = BudgetItem.objects.all()
scoutType = request.GET.get('scoutType')
return render(request, 'budget/home.html', context={'budgetItems':budgetItems,'scoutType':scoutType})
| 36.111111 | 109 | 0.76 | 37 | 325 | 6.675676 | 0.567568 | 0.080972 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.129231 | 325 | 8 | 110 | 40.625 | 0.872792 | 0 | 0 | 0 | 0 | 0 | 0.138462 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.142857 | false | 0 | 0.428571 | 0 | 0.714286 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 2 |
60af6ed26bc6545ce90a596bec631b5bd73c55d0 | 130 | py | Python | python-for-beginners/12 - Loops/while.py | kbsat/c9-python-getting-started | 4033c9aaad27d517478c832c31145b97f2b35d6c | [
"MIT"
] | null | null | null | python-for-beginners/12 - Loops/while.py | kbsat/c9-python-getting-started | 4033c9aaad27d517478c832c31145b97f2b35d6c | [
"MIT"
] | null | null | null | python-for-beginners/12 - Loops/while.py | kbsat/c9-python-getting-started | 4033c9aaad27d517478c832c31145b97f2b35d6c | [
"MIT"
] | null | null | null | names = ['Christopher', 'Susan']
index = 0
while index < len(names):
print(names[index])
# 조건을 바꿈!!
index = index + 1
| 18.571429 | 32 | 0.584615 | 17 | 130 | 4.470588 | 0.647059 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.020408 | 0.246154 | 130 | 6 | 33 | 21.666667 | 0.755102 | 0.061538 | 0 | 0 | 0 | 0 | 0.133333 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.2 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
60c5a6381a4070bae68195485e5333ce7b6e2479 | 530 | py | Python | examples/synthetic/park2_3/park2_3_mf.py | crcollins/dragonfly | d1857a79253cc6305a715acce7a93d6c7fc19b2a | [
"MIT"
] | 3 | 2020-10-11T14:37:25.000Z | 2021-08-30T08:49:16.000Z | examples/synthetic/park2_3/park2_3_mf.py | crcollins/dragonfly | d1857a79253cc6305a715acce7a93d6c7fc19b2a | [
"MIT"
] | null | null | null | examples/synthetic/park2_3/park2_3_mf.py | crcollins/dragonfly | d1857a79253cc6305a715acce7a93d6c7fc19b2a | [
"MIT"
] | null | null | null | """
Parkd2 function.
-- kandasamy@cs.cmu.edu
"""
# pylint: disable=invalid-name
from park2_3 import park2_3_z_x
def park2_3_mf(z, x):
""" Computes the Park2_3 function. """
f = [z[0][0]/5000.0, z[1]/10.0]
return park2_3_z_x(f, x)
# Write a function like this called 'obj'....
def cost(z):
""" Cost function. """
return 0.1 + 0.9 * (z[0][0]/5000 + z[1]/10) / 2.0
def objective(z, x):
""" Objective. """
return park2_3_mf(z, x)
def main(z, x):
""" main function. """
return park2_3_mf(z, x), cost(z)
| 17.096774 | 51 | 0.596226 | 97 | 530 | 3.113402 | 0.381443 | 0.139073 | 0.07947 | 0.089404 | 0.139073 | 0.10596 | 0 | 0 | 0 | 0 | 0 | 0.096471 | 0.198113 | 530 | 30 | 52 | 17.666667 | 0.614118 | 0.358491 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.4 | false | 0 | 0.1 | 0 | 0.9 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
60d28cd46ae6a4bc082e03e9f986d6078b4b909c | 3,887 | py | Python | pinecone/settings.py | cdot65/configuration-backup-api | 94df552375d9d8f2241a69f61b4cc11e11f60662 | [
"MIT"
] | 1 | 2021-12-21T16:10:02.000Z | 2021-12-21T16:10:02.000Z | pinecone/settings.py | cdot65/configuration-backup-api | 94df552375d9d8f2241a69f61b4cc11e11f60662 | [
"MIT"
] | null | null | null | pinecone/settings.py | cdot65/configuration-backup-api | 94df552375d9d8f2241a69f61b4cc11e11f60662 | [
"MIT"
] | null | null | null | from pathlib import Path
import environ
# pinecone/
BASE_DIR = Path(__file__).resolve(strict=True).parent.parent
print(BASE_DIR)
APPS_DIR = BASE_DIR / "pinecone"
env = environ.Env()
ENV_FILE = BASE_DIR / ".env"
if Path(ENV_FILE).exists():
# OS environment variables take precedence over variables from .env
env.read_env(str(ENV_FILE))
# GENERAL
# ------------------------------------------------------------------------------
DEBUG = env.bool("DJANGO_DEBUG", False)
TIME_ZONE = "UTC"
LANGUAGE_CODE = "en-us"
SITE_ID = 1
USE_I18N = True
USE_L10N = True
USE_TZ = True
LOCALE_PATHS = [str(BASE_DIR / "locale")]
# SUPER SECRET KEY
# ------------------------------------------------------------------------------
SECRET_KEY = env("DJANGO_SECRET_KEY")
# ALLOWED HOSTS
# ------------------------------------------------------------------------------
ALLOWED_HOSTS = ['0.0.0.0', 'localhost', 'pinecone', 'python.dmz.home']
# APPS
# ------------------------------------------------------------------------------
DJANGO_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
THIRD_PARTY_APPS = [
'rest_framework',
'rest_framework.authtoken',
]
LOCAL_APPS =[
'backup.apps.BackupConfig',
]
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'pinecone.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'pinecone.wsgi.application'
# DATABASES
# ------------------------------------------------------------------------------
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': 'postgres',
'HOST': 'db',
'PORT': 5432,
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# STATIC
# ------------------------------------------------------------------------------
STATIC_URL = '/static/'
import os
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
# REST FRAMEWORK DRF API SETTINGS
# ------------------------------------------------------------------------------
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
| 26.993056 | 91 | 0.581168 | 335 | 3,887 | 6.552239 | 0.423881 | 0.088838 | 0.054214 | 0.038269 | 0.071071 | 0.071071 | 0 | 0 | 0 | 0 | 0 | 0.005234 | 0.164394 | 3,887 | 143 | 92 | 27.181818 | 0.670567 | 0.210188 | 0 | 0.020619 | 0 | 0 | 0.518361 | 0.417705 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.061856 | 0.030928 | 0 | 0.030928 | 0.010309 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
60dc178e8ee9f23a83b697993e49670315a7aa0e | 2,754 | py | Python | xgboost_model/xgb_mapper.py | forestyaser/HousePricePrediction | b23d8e9bbea13801d7b911a32cd8a5e81235478f | [
"Apache-2.0"
] | null | null | null | xgboost_model/xgb_mapper.py | forestyaser/HousePricePrediction | b23d8e9bbea13801d7b911a32cd8a5e81235478f | [
"Apache-2.0"
] | null | null | null | xgboost_model/xgb_mapper.py | forestyaser/HousePricePrediction | b23d8e9bbea13801d7b911a32cd8a5e81235478f | [
"Apache-2.0"
] | null | null | null | import sklearn
from sklearn_pandas import DataFrameMapper
import pickle
import numpy as np
import pandas as pd
import gc
import os
from RealMasterService.src.main.config import constants, RealMasterServiceConfig
from RealMasterService.src.main.utils.utils import check_local_file_exist
def init_xgb_mapper(df, xgb_pickle=RealMasterServiceConfig.XGB_MAPPER):
mapper = DataFrameMapper([
('A_c', sklearn.preprocessing.LabelBinarizer()),
('Bsmt1_out', sklearn.preprocessing.LabelBinarizer()),
('Community', sklearn.preprocessing.LabelBinarizer()),
('Gar_type', sklearn.preprocessing.LabelBinarizer()),
('Heating', sklearn.preprocessing.LabelBinarizer()),
('Pool', sklearn.preprocessing.LabelBinarizer()),
('Style', sklearn.preprocessing.LabelBinarizer()),
('Type_own1_out', sklearn.preprocessing.LabelBinarizer()),
('Den_fr', sklearn.preprocessing.LabelBinarizer()),
(['Dom'], sklearn.preprocessing.StandardScaler()),
(['Taxes'], sklearn.preprocessing.StandardScaler()),
(['Area_code'], sklearn.preprocessing.StandardScaler()),
(['Depth'], sklearn.preprocessing.StandardScaler()),
(['Front_ft'], sklearn.preprocessing.StandardScaler()),
(['Bath_tot'], sklearn.preprocessing.StandardScaler()),
(['Br'], sklearn.preprocessing.StandardScaler()),
(['Br_plus'], sklearn.preprocessing.StandardScaler()),
(['Park_spcs'], sklearn.preprocessing.StandardScaler()),
(['Kit_plus'], sklearn.preprocessing.StandardScaler()),
(['Rms'], sklearn.preprocessing.StandardScaler()),
(['Rooms_plus'], sklearn.preprocessing.StandardScaler()),
(['Garage'], sklearn.preprocessing.StandardScaler()),
(['lat'], sklearn.preprocessing.StandardScaler()),
(['lng'], sklearn.preprocessing.StandardScaler()),
(['Lp_dol'], sklearn.preprocessing.StandardScaler()),
(constants.DISCRETE_ROOM_AREA, None),
(constants.MONTH, None),
], input_df=True)
data_temp = np.round(mapper.fit_transform(df.copy()).astype(np.double), 3)
if check_local_file_exist(xgb_pickle):
os.remove(xgb_pickle)
with open(xgb_pickle, "wb") as f:
pickle.dump(mapper, f)
print("Fitting: ", type(mapper))
del data_temp
gc.collect()
return
def proc_xgb_mapper(df):
pickle_train = RealMasterServiceConfig.XGB_MAPPER
if os.path.isfile(pickle_train):
with open(pickle_train, 'rb') as f:
mapper = pickle.load(f)
data_tmp = np.round(mapper.transform(df.copy()).astype(np.double), 3)
return pd.DataFrame(data_tmp, columns=mapper.transformed_names_)
else:
print('Cannot find xgb_mapper.pkl')
| 40.5 | 81 | 0.679739 | 277 | 2,754 | 6.595668 | 0.386282 | 0.273673 | 0.297756 | 0.062397 | 0.032841 | 0.032841 | 0.032841 | 0 | 0 | 0 | 0 | 0.001759 | 0.174292 | 2,754 | 67 | 82 | 41.104478 | 0.801671 | 0 | 0 | 0 | 0 | 0 | 0.071922 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.035088 | false | 0 | 0.157895 | 0 | 0.22807 | 0.035088 | 0 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
60dc37762ba1fb9382a8b78f8b3b5073ef46751c | 24,694 | py | Python | typed_python/compiler/tests/arithmetic_compilation_test.py | APrioriInvestments/typed_python | a3191e5d30333eba156c2a910abc78f7813dcaa3 | [
"Apache-2.0"
] | 105 | 2019-12-02T01:44:46.000Z | 2022-03-28T20:27:38.000Z | typed_python/compiler/tests/arithmetic_compilation_test.py | APrioriInvestments/typed_python | a3191e5d30333eba156c2a910abc78f7813dcaa3 | [
"Apache-2.0"
] | 173 | 2019-10-08T19:37:06.000Z | 2022-01-24T18:43:42.000Z | typed_python/compiler/tests/arithmetic_compilation_test.py | APrioriInvestments/typed_python | a3191e5d30333eba156c2a910abc78f7813dcaa3 | [
"Apache-2.0"
] | 1 | 2020-01-23T00:06:42.000Z | 2020-01-23T00:06:42.000Z | # Copyright 2017-2019 typed_python Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import operator
import sys
from math import isfinite, trunc, floor, ceil, nan, inf
from typed_python import (
OneOf, ListOf, Tuple, Compiled, makeNamedTuple,
Int8, Int16, Int32, Float32,
UInt8, UInt16, UInt32, UInt64,
)
from typed_python.type_promotion import (
computeArithmeticBinaryResultType, isSignedInt, isUnsignedInt, bitness
)
from typed_python import Entrypoint
import unittest
In = OneOf(int, float)
Out = OneOf(int, float, bool)
def add(x: In, y: In) -> Out:
return x+y
def sub(x: In, y: In) -> Out:
return x-y
def mul(x: In, y: In) -> Out:
return x*y
def div(x: In, y: In) -> Out:
return x/y
def mod(x: In, y: In) -> Out:
return x%y
def lshift(x: In, y: In) -> Out:
return x << y
def rshift(x: In, y: In) -> Out:
return x >> y
def pow(x: In, y: In) -> Out:
return x ** y
def bitxor(x: In, y: In) -> Out:
return x ^ y
def bitand(x: In, y: In) -> Out:
return x&y
def bitor(x: In, y: In) -> Out:
return x|y
def less(x: In, y: In) -> Out:
return x < y
def greater(x: In, y: In) -> Out:
return x > y
def lessEq(x: In, y: In) -> Out:
return x <= y
def greaterEq(x: In, y: In) -> Out:
return x >= y
def eq(x: In, y: In) -> Out:
return x == y
def neq(x: In, y: In) -> Out:
return x != y
ALL_OPERATIONS = [
add, sub, mul, div, mod, lshift, rshift,
pow, bitxor, bitand, bitor, less,
greater, lessEq, greaterEq, eq, neq
]
class TestArithmeticCompilation(unittest.TestCase):
def test_compile_simple(self):
@Compiled
def f(x: int) -> int:
return x+x+x
self.assertEqual(f(20), 60)
self.assertEqual(f(10), 30)
def test_in_to_out(self):
@Compiled
def identity(x: In) -> Out:
return x
self.assertIsInstance(identity(0.5), float)
self.assertIsInstance(identity(0.0), float)
self.assertIsInstance(identity(1), int)
def SKIPtest_binary_operators(self):
failures = 0
successes = 0
for f in ALL_OPERATIONS:
if f in [pow]:
lvals = range(-5, 5)
rvals = range(5)
lvals = list(lvals) + [x * 1 for x in lvals]
rvals = list(rvals) + [x * 1 for x in rvals]
else:
lvals = list(range(-20, 20))
rvals = lvals
lvals = list(lvals) + [x / 3 for x in lvals]
rvals = list(rvals) + [x / 3 for x in rvals]
f_fast = Compiled(f)
for val1 in lvals:
for val2 in rvals:
try:
pyVal = f(val1, val2)
except Exception:
pyVal = "Exception"
try:
llvmVal = f_fast(val1, val2)
except Exception:
llvmVal = "Exception"
if type(pyVal) is not type(llvmVal) or pyVal != llvmVal:
print("FAILURE", f, val1, val2, pyVal, llvmVal)
failures += 1
else:
successes += 1
self.assertEqual(failures, 0, successes)
def checkFunctionOfIntegers(self, f):
f_fast = Compiled(f)
for i in range(100):
self.assertEqual(f_fast(i), f(i))
def test_assignment_of_pod(self):
def f(x: int) -> int:
y = x
return y
self.checkFunctionOfIntegers(f)
def test_simple_loop(self):
def f(x: int) -> int:
y = 0
while x > 0:
x = x - 1
y = y + x
return y
self.checkFunctionOfIntegers(f)
def test_call_other_typed_function(self):
def g(x: int) -> int:
return x+1
def f(x: int) -> int:
return g(x+2)
self.checkFunctionOfIntegers(f)
def test_basic_type_conversion(self):
def f(x: int) -> int:
y = 1.5
return int(y)
self.checkFunctionOfIntegers(f)
def test_integers_in_closures(self):
y = 2
def f(x: int) -> int:
return x+y
self.checkFunctionOfIntegers(f)
def test_negation(self):
@Compiled
def negate_int(x: int):
return -x
@Compiled
def negate_float(x: float):
return -x
self.assertEqual(negate_int(10), -10)
self.assertEqual(negate_float(20.5), -20.5)
def test_can_stringify_unsigned(self):
@Entrypoint
def toString(x):
return str(x)
self.assertEqual(toString(UInt64(10)), "10u64")
self.assertEqual(toString(UInt32(10)), "10u32")
self.assertEqual(toString(UInt16(10)), "10u16")
self.assertEqual(toString(UInt8(10)), "10u8")
def test_can_compile_register_builtins(self):
registerTypes = [bool, Int8, Int16, Int32, int, UInt8, UInt16, UInt32, UInt64, Float32, float]
def suitable_range(t):
if t in [bool]:
return [0, 1]
elif isUnsignedInt(t):
return [0, 5, 10, 15, 50, 100, 150]
elif isSignedInt(t):
return [0, 5, 10, 15, 50, 100, -5, -10, -15, -50, -100]
elif t in [Float32, float]:
return [x / 2.0 for x in range(-100, 100)]
for T in registerTypes:
def f_round0(x: T):
return round(x)
def f_round1(x: T):
return round(x, 1)
def f_round2(x: T):
return round(x, 2)
def f_round_1(x: T):
return round(x, -1)
def f_round_2(x: T):
return round(x, -2)
def f_trunc(x: T):
return trunc(x)
def f_floor(x: T):
return floor(x)
def f_ceil(x: T):
return ceil(x)
def f_int(x: T):
return int(x)
def f_float(x: T):
return float(x)
def f_complex(x: T):
return complex(x)
def f_format(x: T):
return format(x)
# not_tested_yet = [f_complex]
ops = [f_int, f_float, f_format, f_round0, f_round1, f_round2, f_round_1, f_round_2, f_trunc, f_floor, f_ceil]
for op in ops:
c_op = Compiled(op)
for v in suitable_range(T):
r1 = op(T(v))
r2 = c_op(T(v))
self.assertEqual(r1, r2)
# note that types are necessarily different sometimes,
# e.g. round(float(1), 0) returns int when interpreted,
# but float when compiled
def test_can_call_types_with_no_args(self):
@Entrypoint
def makeEmpty(T):
return T()
self.assertEqual(makeEmpty(int), 0)
self.assertEqual(makeEmpty(float), 0.0)
self.assertEqual(makeEmpty(bool), False)
self.assertEqual(makeEmpty(str), "")
def test_not_on_float(self):
@Entrypoint
def doit(f):
if not f:
return "its false"
return "its true"
self.assertEqual(doit(1.0), "its true")
self.assertEqual(doit(0.0), "its false")
def test_can_compile_register_operations(self):
failed = False
registerTypes = [bool, Int8, Int16, Int32, int, UInt8, UInt16, UInt32, UInt64, Float32, float]
def result_or_exception(f, *p):
try:
return f(*p)
except Exception:
return "exception"
def equal_result(a, b):
if type(a) in (float, Float32):
epsilon = float(1e-6)
if a < 1e-32: # these results happen to be from calculations that magnify errors
epsilon = float(1e-5)
if a != 0.0:
return abs(float(b - a) / a) < epsilon
else:
return abs(float(b - a)) < epsilon
return a == b
def signed_overflow(T, v):
return isUnsignedInt(T) and (v >= 2**(bitness(T) - 1) or v < -2**(bitness(T) - 1))
def suitable_range(t):
if t in [bool]:
return [0, 1]
elif isUnsignedInt(t):
return [0, 1, 2, (1 << (bitness(t) // 4)) - 1, (1 << (bitness(t) // 2)) - 1, (1 << bitness(t)) - 1]
elif isSignedInt(t):
return [0, 1, 2, (1 << (bitness(t) // 2 - 1)) - 1, (1 << (bitness(t) - 1)) - 1,
-1, -2, -(1 << (bitness(t) // 2 - 1)), -(1 << (bitness(t) - 1))]
elif t in [Float32]:
return [0.0, 1.0/3.0, 0.5, 1.0, 1.5, 2.0, (2 - 1 / (2**23)) * 2**127,
-1.0/3.0, -0.5, -1.0, -1.5, -2.0, -(2 - 1 / (2**23)) * 2**127]
elif t in [float]:
return [0.0, 1e-16, 9.876e-16, 1.0/3.0, 0.5, 1.0, 1.5, 10.0/7.0, 2.0, 3.0, 10.0/3.0, 100.0/3.0, sys.float_info.max,
-1e-16, -9.876e-16, -1.0/3.0, -0.5, -1.0, -10.0/7.0, -1.5, -2.0, -3.0, -10.0/3.0, -100.0/3.0, -sys.float_info.max]
for T in registerTypes:
def not_(x: T):
return not x
def invert(x: T):
return ~x
def neg(x: T):
return -x
def pos(x: T):
return +x
def abs_(x: T):
return abs(x)
if T is not bool:
self.assertEqual(T(1) + T(2), T(3))
if T in [bool]:
suitable_ops = [not_]
else:
suitable_ops = [invert, neg, pos, abs_]
typed_to_native_op = {
invert: operator.__inv__,
not_: operator.__not__,
neg: operator.__neg__,
pos: operator.__pos__,
abs_: operator.__abs__,
}
for op in suitable_ops:
native_op = typed_to_native_op[op]
compiled_op = Compiled(op)
for v in suitable_range(T):
comparable = True
interpreterResult = result_or_exception(native_op, v)
if isSignedInt(T):
if interpreterResult >= 2**(bitness(T) - 1) or interpreterResult < -2**(bitness(T) - 1):
comparable = False
elif isUnsignedInt(T):
if interpreterResult >= 2**bitness(T) or interpreterResult < 0:
comparable = False
typedPythonResult = result_or_exception(op, T(v))
if typedPythonResult == NotImplemented:
typedPythonResult = "exception"
compilerResult = result_or_exception(compiled_op, T(v))
self.assertEqual(
type(typedPythonResult), type(compilerResult),
(T, type(typedPythonResult), type(compilerResult), op.__name__)
)
if comparable:
self.assertTrue(equal_result(type(compilerResult)(typedPythonResult), compilerResult),
(T, op.__name__, typedPythonResult, compilerResult))
self.assertTrue(equal_result(type(compilerResult)(interpreterResult), compilerResult),
(T, op.__name__, interpreterResult, compilerResult))
for T1 in registerTypes:
for T2 in registerTypes:
def add(x: T1, y: T2):
return x + y
def sub(x: T1, y: T2):
return x - y
def mul(x: T1, y: T2):
return x * y
def div(x: T1, y: T2):
return x / y
def floordiv(x: T1, y: T2):
return x // y
def mod(x: T1, y: T2):
return x % y
def less(x: T1, y: T2):
return x < y
def greater(x: T1, y: T2):
return x > y
def lessEq(x: T1, y: T2):
return x <= y
def greaterEq(x: T1, y: T2):
return x >= y
def bitand(x: T1, y: T2):
return x & y
def bitor(x: T1, y: T2):
return x | y
def bitxor(x: T1, y: T2):
return x ^ y
def neq(x: T1, y: T2):
return x != y
def rshift(x: T1, y: T2):
return x >> y
def lshift(x: T1, y: T2):
return x << y
def pow(x: T1, y: T2):
return x ** y
if T1 in [bool] or T2 in [bool]:
suitable_ops = [bitand, bitor, bitxor]
else:
suitable_ops = [
add, sub, mul, div, mod, floordiv,
less, greater, lessEq, greaterEq, neq,
bitand, bitor, bitxor,
lshift,
rshift, pow
]
typed_to_native_op = {
sub: operator.sub,
add: operator.add,
mul: operator.mul,
div: operator.truediv,
floordiv: operator.floordiv,
mod: operator.mod,
less: operator.lt,
greater: operator.gt,
lessEq: operator.le,
greaterEq: operator.ge,
neq: operator.ne,
bitand: operator.and_,
bitor: operator.or_,
bitxor: operator.xor,
rshift: operator.rshift,
lshift: operator.lshift,
pow: operator.pow
}
for op in suitable_ops:
native_op = typed_to_native_op[op]
compiled_op = Compiled(op)
for v1 in suitable_range(T1):
for v2 in suitable_range(T2):
comparable = True
T_result = computeArithmeticBinaryResultType(T1, T2)
if isSignedInt(T_result):
if signed_overflow(T1, v1) or signed_overflow(T2, v2):
comparable = False
if (op in (lshift, rshift) and v2 > 1024) \
or (op is pow and (v1 > 1 or v1 < -1) and v2 > 1024):
interpreterResult = "expected to disagree"
else:
interpreterResult = result_or_exception(native_op, v1, v2)
T_result = computeArithmeticBinaryResultType(T1, T2)
if interpreterResult == "exception":
pass
elif type(interpreterResult) is complex:
interpreterResult = "expected to disagree"
elif isSignedInt(T_result):
if interpreterResult >= 2**(bitness(T_result) - 1) or interpreterResult < -2**(bitness(T_result) - 1):
comparable = False
elif isUnsignedInt(T_result):
if interpreterResult >= 2**bitness(T_result) or interpreterResult < 0:
comparable = False
elif T_result in (float, Float32):
if interpreterResult >= 2**128 or interpreterResult <= -2**128:
comparable = False
native_comparable = comparable
if (T1 is Float32 or T2 is Float32) and op in [mod, floordiv]:
# can't expect Float32 mod and floordiv to match native calculations
# typed should still match compiled
native_comparable = False
if ((T1 is Float32 and T2 is float) or (T1 is float and T2 is Float32)) \
and op in [less, greater, lessEq, greaterEq, neq]:
native_comparable = False
if T1 is int and T2 is int and \
((op is lshift and v1 != 0 and v2 > 1024) or
(op is pow and (v1 > 1 or v1 < -1) and v2 > 1024)):
typedPythonResult = "expected to disagree"
else:
typedPythonResult = result_or_exception(op, T1(v1), T2(v2))
if type(typedPythonResult) in [float, Float32, float] and not isfinite(typedPythonResult):
typedPythonResult = "expected to disagree"
if type(typedPythonResult) is complex:
typedPythonResult = "expected to disagree"
if op is pow and type(typedPythonResult) is int:
typedPythonResult = float(typedPythonResult)
compilerResult = result_or_exception(compiled_op, T1(v1), T2(v2))
if type(compilerResult) in [float, Float32, float] and not isfinite(compilerResult):
compilerResult = "expected to disagree"
# for debugging
# if type(typedPythonResult) != type(compilerResult):
# print("type mismatch", type(typedPythonResult).__name__, type(compilerResult).__name__)
# if type(typedPythonResult) == type(compilerResult):
# if comparable and not equal_result(typedPythonResult, compilerResult):
# print("result mismatch")
# try:
# if native_comparable and not equal_result(type(compilerResult)(interpreterResult), compilerResult):
# print("mismatch")
# except Exception:
# print("mismatch exception")
if type(typedPythonResult) != type(compilerResult):
print(
f"interpreter and compiler types for {op.__name__} on arguments of type "
f"{T1} and {T2} were not the same. the interpreter gave {type(typedPythonResult)} but"
f"compiler gave {type(compilerResult)}"
)
failed = True
if "expected to disagree" not in (typedPythonResult, compilerResult, interpreterResult):
if (comparable and not equal_result(type(compilerResult)(typedPythonResult), compilerResult) or
native_comparable and not equal_result(type(compilerResult)(interpreterResult), compilerResult)):
print(
f"results for {op.__name__} on arguments "
f"{v1} of type {T1} and {v2} of type {T2} do not agree: "
f"interpreter gives {interpreterResult}, "
f"typed_python gave {typedPythonResult}, and "
f"the compiler gave {compilerResult}"
)
failed = True
self.assertFalse(failed)
def test_int_of_nan(self):
@Entrypoint
def f(x):
return int(x)
with self.assertRaisesRegex(Exception, "NaN"):
f(nan)
with self.assertRaisesRegex(Exception, "infinity"):
f(inf)
def test_mod_constant_in_tuple(self):
@Entrypoint
def rf(row):
return row.x % 1.0
self.assertEqual(rf(makeNamedTuple(x=1.0)), 0.0)
def test_pow_with_bad_inputs(self):
@Entrypoint
def callPow(x, y):
return x ** y
with self.assertRaises(ZeroDivisionError):
callPow(0.0, -1.0)
with self.assertRaises(ZeroDivisionError):
callPow(0, -1)
def test_floordiv_with_bad_inputs(self):
@Entrypoint
def callFloordiv(x, y):
return x // y
with self.assertRaises(ZeroDivisionError):
callFloordiv(1.0, 0.0)
with self.assertRaises(ZeroDivisionError):
callFloordiv(1, 0)
def test_shift_with_bad_inputs(self):
@Entrypoint
def callShift(x, y):
return x << y
with self.assertRaises(ValueError):
callShift(1, -2)
with self.assertRaises(OverflowError):
callShift(1, 2048)
def test_formatting_with_format_strings_works(self):
@Entrypoint
def format(x):
return f"{x:.6g}"
assert format(1.0) == f"{1.0:.6g}"
def test_formatting_strings_in_loop(self):
@Entrypoint
def format(a, b, c, d):
res = ListOf(str)()
for i in range(10000):
res.append(f"{i} {a} {b} {c} {d}")
return res
format(1, 2, 3, 4)
def test_string_joining_in_loop(self):
@Entrypoint
def format(a, b, c, d):
res = ListOf(str)()
for i in range(10000):
l = ListOf(str)()
l.append(str(a))
l.append(str(b))
l.append(str(c))
res.append("".join(l))
return res
format(1, 2, 3, 4)
def test_unary_ops_on_constants(self):
@Entrypoint
def sliceAtPositiveZero(x):
return x[+0]
self.assertIs(sliceAtPositiveZero.resultTypeFor(Tuple(int, float)).interpreterTypeRepresentation, int)
@Entrypoint
def sliceAtNegativeZero(x):
return x[-0]
self.assertIs(sliceAtNegativeZero.resultTypeFor(Tuple(int, float)).interpreterTypeRepresentation, int)
@Entrypoint
def sliceAtInvertZero(x):
return x[~0]
self.assertIs(sliceAtInvertZero.resultTypeFor(Tuple(int, float)).interpreterTypeRepresentation, float)
@Entrypoint
def sliceAtNotZero(x):
return x[int(not 0)]
self.assertIs(sliceAtNotZero.resultTypeFor(Tuple(int, float)).interpreterTypeRepresentation, float)
@Entrypoint
def sliceAtPositiveZeroFloat(x):
return x[int(+0.0)]
self.assertIs(sliceAtPositiveZeroFloat.resultTypeFor(Tuple(int, float)).interpreterTypeRepresentation, int)
@Entrypoint
def sliceAtNegativeZeroFloat(x):
return x[int(-0.0)]
self.assertIs(sliceAtNegativeZeroFloat.resultTypeFor(Tuple(int, float)).interpreterTypeRepresentation, int)
@Entrypoint
def sliceAtNotZeroFloat(x):
return x[int(not 0.0)]
self.assertIs(sliceAtNotZeroFloat.resultTypeFor(Tuple(int, float)).interpreterTypeRepresentation, float)
@Entrypoint
def sliceAtNotFalse(x):
return x[int(not False)]
self.assertIs(sliceAtNotZeroFloat.resultTypeFor(Tuple(int, float)).interpreterTypeRepresentation, float)
| 33.966988 | 138 | 0.482749 | 2,672 | 24,694 | 4.366018 | 0.129117 | 0.033002 | 0.026059 | 0.030173 | 0.452083 | 0.380336 | 0.268301 | 0.242157 | 0.149151 | 0.081862 | 0 | 0.041177 | 0.42075 | 24,694 | 726 | 139 | 34.013774 | 0.774399 | 0.057058 | 0 | 0.296154 | 0 | 0.003846 | 0.029633 | 0.002021 | 0 | 0 | 0 | 0 | 0.082692 | 1 | 0.209615 | false | 0.001923 | 0.013462 | 0.144231 | 0.409615 | 0.005769 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 2 |
60e7235b0dc2163e9f59edbb9ecd219e642aac8f | 1,458 | py | Python | database/migrations/0003_auto_20170820_0318.py | safrimus/malikburhani | 7cb6b23b0f8282ddc8052f7cd62740d4e632a739 | [
"MIT"
] | null | null | null | database/migrations/0003_auto_20170820_0318.py | safrimus/malikburhani | 7cb6b23b0f8282ddc8052f7cd62740d4e632a739 | [
"MIT"
] | null | null | null | database/migrations/0003_auto_20170820_0318.py | safrimus/malikburhani | 7cb6b23b0f8282ddc8052f7cd62740d4e632a739 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-08-20 03:18
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('database', '0002_auto_20170806_1404'),
]
operations = [
migrations.AlterField(
model_name='category',
name='created',
field=models.DateTimeField(default=django.utils.timezone.now, help_text='Date product was added to database'),
),
migrations.AlterField(
model_name='customer',
name='created',
field=models.DateTimeField(default=django.utils.timezone.now, help_text='Date customer added to database'),
),
migrations.AlterField(
model_name='invoice',
name='created',
field=models.DateTimeField(default=django.utils.timezone.now, help_text='Date of creation of the invoice'),
),
migrations.AlterField(
model_name='product',
name='created',
field=models.DateTimeField(default=django.utils.timezone.now, help_text='Date product was added to database'),
),
migrations.AlterField(
model_name='source',
name='created',
field=models.DateTimeField(default=django.utils.timezone.now, help_text='Date product was added to database'),
),
]
| 34.714286 | 122 | 0.628944 | 155 | 1,458 | 5.8 | 0.354839 | 0.073415 | 0.126808 | 0.16129 | 0.619577 | 0.619577 | 0.619577 | 0.570634 | 0.570634 | 0.570634 | 0 | 0.030584 | 0.259945 | 1,458 | 41 | 123 | 35.560976 | 0.802595 | 0.046639 | 0 | 0.529412 | 1 | 0 | 0.191781 | 0.016583 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.088235 | 0 | 0.176471 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
60e941969fc21f14129b2a9d0e3d293c667124b1 | 47,720 | py | Python | multiwoz-dst/submission4/submission4.py | adamlin120/ConvLab-2 | 5da1803a923329565c8c75a8f18c9d3fc8b45c2d | [
"Apache-2.0"
] | null | null | null | multiwoz-dst/submission4/submission4.py | adamlin120/ConvLab-2 | 5da1803a923329565c8c75a8f18c9d3fc8b45c2d | [
"Apache-2.0"
] | null | null | null | multiwoz-dst/submission4/submission4.py | adamlin120/ConvLab-2 | 5da1803a923329565c8c75a8f18c9d3fc8b45c2d | [
"Apache-2.0"
] | null | null | null | import re
from copy import deepcopy
from difflib import get_close_matches
from typing import Dict, List, Iterable, Tuple
import torch
from transformers import MBartTokenizer, MBartForConditionalGeneration
from convlab2.dst import DST
BELIEF = "<BELIEF>"
SLOT_SEP = "<SLOT>"
SLOT_NAME_SEP = "<SLOT_NAME>"
SLOT_VALUE_SEP = "<SLOT_VALUE>"
def build_history_from_utterances(
system_utterances: List[str], user_utterances: List[str], lang: str
) -> str:
system, user = {"en": ("system", "user"), "zh": ("系統", "用戶")}[lang]
history = ""
for sys, usr in zip(system_utterances, user_utterances):
if sys is not None:
history += f"{system} : {sys} "
history += f"{user} : {usr} "
return history.strip()
def get_history_utterances(
turns: List[Tuple[str, str, Dict[str, Dict[str, str]]]],
num_history_turns: int,
) -> Tuple[List[str], List[str]]:
if isinstance(num_history_turns, int):
system_utterances, user_utterances, _ = zip(*turns)
if num_history_turns > 0:
system_utterances = system_utterances[-num_history_turns:]
user_utterances = user_utterances[-num_history_turns:]
else:
raise ValueError(
f"num_history_turns: {num_history_turns} should be -1 or positive integer"
)
return system_utterances, user_utterances
class MBartDSTChinese(DST):
model_checkpoint = "ytlin/19rdmhqc"
num_history_turns = -1
lang = "zh"
lang_code = "zh_CN"
MAX_LENGTH = 512
carry_slot_values = False
def __init__(self):
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.tokenizer = MBartTokenizer.from_pretrained(self.model_checkpoint)
self.model = (
MBartForConditionalGeneration.from_pretrained(self.model_checkpoint)
.eval()
.to(self.device)
)
self.user_utterances = []
self.system_utterances = []
self.state = deepcopy(belief_template)
self.turns = []
def init_session(self):
self.user_utterances = []
self.system_utterances = []
self.state = deepcopy(belief_template)
self.turns = []
def update_turn(self, sys_utt, user_utt):
sys_utt = clean_utterance(sys_utt) if sys_utt is not None else None
user_utt = clean_utterance(user_utt)
self.system_utterances.append(sys_utt)
self.user_utterances.append(user_utt)
self.turns.append((sys_utt, user_utt, None))
system_utterances, user_utterances = get_history_utterances(
self.turns, self.num_history_turns
)
history = build_history_from_utterances(
system_utterances, user_utterances, self.lang
)
input_ids = self.tokenizer.prepare_seq2seq_batch(
src_texts=[history],
src_lang=self.lang_code,
).to(self.device)["input_ids"]
if input_ids.size(-1) > self.MAX_LENGTH:
input_ids = input_ids[:, len(input_ids) - self.MAX_LENGTH :]
gen_tokens = self.model.generate(
input_ids,
max_length=self.MAX_LENGTH,
eos_token_id=self.tokenizer.eos_token_id,
pad_token_id=self.tokenizer.pad_token_id,
decoder_start_token_id=self.tokenizer.lang_code_to_id[self.lang_code],
use_cache=True,
)[0]
gen = self.tokenizer.decode(gen_tokens, skip_special_tokens=True)
belief = self.parse_belief(gen)
if self.carry_slot_values:
self.update_belief(belief)
else:
self.state = belief
return deepcopy(self.state)
def parse_belief(self, gen: str) -> Dict[str, Dict[str, str]]:
belief_str = (
gen.split(BELIEF, 1)[-1]
.strip()
.rsplit(self.tokenizer.pad_token, 1)[0]
.strip()
)
slots_combined = re.split(SLOT_SEP, belief_str)[1:]
slots = list(
map(
lambda x: re.split(f"{SLOT_VALUE_SEP}|{SLOT_NAME_SEP}", x),
slots_combined,
)
)
belief = deepcopy(belief_template)
for slot in slots:
domain = "".join(slot[0].split()).strip()
slot_name = "".join(slot[1].split()).strip() if len(slot) >= 2 else ""
slot_value = "".join(slot[2].split()).strip() if len(slot) >= 3 else ""
if not (domain and slot_name and slot_value):
continue
domain = map_to_possible_value(domain, belief.keys())
slot_name = map_to_possible_value(slot_name, belief[domain].keys())
slot_value = map_to_possible_value(slot_value, ontology[domain][slot_name])
belief[domain][slot_name] = slot_value
return belief
def update_belief(self, new_belief: Dict[str, Dict[str, str]]):
for domain, domain_slots in self.state.items():
for slot_name, slot_value in domain_slots.items():
new_slot_value = new_belief.get(domain, {}).get(slot_name, "").strip()
if new_slot_value and new_slot_value != slot_value:
self.state[domain][slot_name] = new_slot_value
def map_to_possible_value(value: str, possible_values: Iterable[str]) -> str:
return (
value
if value in possible_values
else get_close_matches(value, possible_values, 1, 0)[0]
)
def clean_utterance(utterance: str) -> str:
return " ".join(re.split("(\d)", " ".join(utterance.split())))
belief_template = {
"出租车": {
"出发时间": "",
"目的地": "",
"出发地": "",
"到达时间": "",
},
"餐厅": {
"时间": "",
"日期": "",
"人数": "",
"食物": "",
"价格范围": "",
"名称": "",
"区域": "",
},
"公共汽车": {
"人数": "",
"出发时间": "",
"目的地": "",
"日期": "",
"到达时间": "",
"出发地": "",
},
"旅馆": {
"停留天数": "",
"日期": "",
"人数": "",
"名称": "",
"区域": "",
"停车处": "",
"价格范围": "",
"星级": "",
"互联网": "",
"类型": "",
},
"景点": {
"类型": "",
"名称": "",
"区域": "",
},
"列车": {
"票价": "",
"人数": "",
"出发时间": "",
"目的地": "",
"日期": "",
"到达时间": "",
"出发地": "",
},
}
ontology = {
"旅馆": {
"名称": [
"秋季别墅酒店",
"亨廷顿万豪酒店或阿姆斯大学酒店",
"如家酒店",
"艾伦拜尔或秋季别墅酒店或列文顿旅馆",
"萨代艾尔",
"亚历山大住宿加早餐旅馆或萨代艾尔",
"玛格丽特拉酒店",
"假日快捷剑桥酒店",
"剑桥贝尔弗莱酒店",
"洛弗尔旅馆酒店",
"亨廷顿万豪酒店或剑桥贝尔弗莱酒店",
"芬奇住宿加早餐旅馆",
"阿什利酒店或洛弗尔旅馆酒店",
"努斯",
"是",
"阿尔法米尔顿宾馆",
"汉密尔顿旅馆",
"不",
"剑桥桥梁宾馆",
"城北住宿加早餐酒店或萨代艾尔",
"none",
"市中心住宿加早餐酒店或萨代艾尔",
"樱桃",
"罗萨斯住宿加早餐旅馆",
"努沙山林小屋",
"假日酒店",
"阿伯里小屋旅馆",
"剑桥假日酒店",
"瓦德尔布里",
"阿尔法米尔顿或汉密尔顿旅馆",
"万豪酒店",
"橡果旅馆",
"萨代艾尔别墅酒店",
"剑桥桥梁宾馆或埃尔斯布雷旅社宾馆",
"沃克沃斯宾馆",
"拱门宾馆",
"伊莱娜",
"沃克沃斯",
"亨廷顿万豪酒店",
"阿什利酒店",
"柯克伍德",
"阿什利酒店或洛弗尔旅馆酒店或客房城市",
"安纳托里亚酒店",
"埃尔斯布雷旅社宾馆或罗萨斯住宿加早餐旅馆",
"非(汉密尔顿旅馆)",
"冈维尔酒店",
"价值别墅酒店",
"贝尔弗莱酒店",
"霍布森旅馆",
"艾伦拜尔或亚历山大住宿加早餐旅馆",
"亚历山大住宿加早餐旅馆",
"伦兹菲尔德酒店",
"阿姆斯大学酒店",
"莱姆豪斯",
"阿瓦隆",
"特大号5",
"亚历山大或萨代艾尔或冈维尔酒店或阿姆斯大学酒店",
"柯克伍德别墅酒店",
"列文顿旅馆",
"埃尔斯布雷旅社宾馆",
"艾伦拜尔",
"橡果地带",
"不在意",
"苏",
"亚历山大住宿加早餐旅馆或阿姆斯大学酒店",
"卡罗莱纳家庭旅馆",
"A&B 宾馆",
"cote",
"橡果宾馆",
"惠尔",
"冈维尔酒店或伦兹菲尔德酒店",
"沃克沃斯宾馆或秋季别墅酒店",
"斯里珀兹",
"剑桥贝尔弗莱",
"剑桥希尔顿逸林酒店",
"兰香楼",
"客房城市",
"城北住宿加早餐酒店",
"未提及",
],
"区域": ["西部", "中心", "不在意", "东方", "北方", "未提及", "西部或中心", "南方", "none"],
"停车处": ["有", "是的", "不在意", "未提及", "没有", "免费", "不是", "none"],
"价格范围": [
"便宜> 适中",
"中等的",
"不在意",
"未提及",
"$100",
"便宜的或中等的",
"中等的或便宜的",
"昂贵的",
"便宜的",
"none",
],
"星级": ["1", "3|4", "2", "3", "4|5", "4", "未提及", "不在意", "0", "5", "none"],
"互联网": ["有", "是的", "不在意", "未提及", "没有", "免费", "不是", "none"],
"类型": ["酒店", "不在意", "未提及", "宾馆", "住宿加早餐酒店", "酒店或宾馆", "none"],
"停留天数": [
"8",
"1",
"3|1",
"五",
"2",
"5|4",
"3",
"1晚",
"3晚",
"4",
"北",
"5",
"2晚",
"6",
"7",
"4晚",
"none",
"5晚",
],
"日期": [
"星期一<星期四",
"星期二",
"星期五",
"星期日",
"星期三",
"星期六",
"不在意",
"未提及",
"星期三或星期五",
"星期一",
"星期四",
"星期五>星期二",
"星期日>星期一",
"星期六或星期二",
"none",
],
"人数": ["8", "1", "2", "3", "4", "5", "6", "7", "二", "none"],
},
"列车": {
"票价": [""],
"出发时间": [
"15:34",
"17:50",
"07:40",
"11:11",
"05:40",
"21:29",
"21:11",
"07:17",
"1532",
"早上",
"18:09",
"06:09",
"05:15",
"13:15",
"07:21",
"00:00",
"20:30",
"12:56",
"1329",
"20:01",
"17:11",
"08:00",
"17:01",
"19:35",
"20:36",
"20:19",
"05:29",
"05:30",
"13:00",
"09:19",
"11:35",
"01:44",
"14:19",
"15:45",
"08:01",
"10:19",
"08:06",
"11:54",
"13:17",
"19:00",
"19:11",
"14:21",
"09:30",
"19:40",
"08:10",
"14:01",
"09:54",
"9:00",
"21:00",
"15:17",
"18:06",
"18:00",
"16:30之后",
"14:45",
"16:00",
"19:45",
"15:15",
"14:09",
"06:00",
"19:16",
"午餐后",
"17:59",
"10:36",
"17:15",
"21:30",
"none",
"09:17",
"12:32",
"06:01",
"20:45",
"11:01",
"14:40",
"21:01",
"15:50",
"9",
"18:15",
"13:30",
"11:00",
"07:00",
"06:30",
"12:00",
"13:11",
"05:17",
"13:29",
"10:45",
"17:16",
"12:26",
"07:54",
"02:00",
"10:00",
"05:24",
"17:45",
"17:00",
"08:11",
"07:01",
"09:23",
"19:54",
"05:45",
"20:21",
"13:24",
"17:40",
"21:45",
"05:00",
"1145",
"18:21",
"09:11",
"16:45",
"15:01",
"下午",
"14:00",
"05:16",
"12:19",
"07:35",
"15:16",
"05:11",
"20:00",
"15:30",
"10:21",
"17:30",
"20:15",
"05:36",
"21:39",
"18:30",
"16:15",
"17:19",
"12:30",
"09:40",
"11:21",
"19:48",
"16:30",
"06:45",
"13:40",
"18:40",
"15:29",
"11:15",
"10:11",
"12:15",
"08:52",
"12:48",
"莱斯特",
"17:29",
"8:15",
"22:00",
"10:32",
"09:00",
"19:15",
"08:09",
"929",
"09:39",
"08:45",
"19:30",
"09:59",
"13:39",
"15:54",
"22:09",
"06:10",
"21:50",
"07:15",
"08:16",
"09:45",
"13:32",
"19:50",
"1545",
"20:40",
"13:36",
"17:21",
"18:46",
"09:29",
"14:15",
"06:40",
"15:24",
"05:35",
"05:01",
"8:00",
"09:50",
"10:30",
"11:30",
"21:15",
"不在意",
"22:01",
"10",
"07:27",
"13:45",
"05:54",
"15:00",
"13:50",
"13:01",
"08:30",
"09:15",
"11:48",
"11:29",
"13:54",
"07:45",
"845",
"05:50",
"11:17",
"18:45",
"11:50",
"11:39",
"12:45",
"15:39",
"11:45",
"10:15",
"08:08",
"18:36",
"14:30",
"08:15",
"未提及",
"08:32",
"下午5:45",
"19:17",
"15:11",
],
"目的地": [
"伯明翰新街",
"亨廷顿万豪酒店",
"彼得堡",
"亨廷顿万豪",
"林恩",
"咖哩王子餐厅",
"利物浦",
"中心",
"利物浦大街",
"伦敦",
"伦敦利物浦街",
"挪威",
"none",
"诺里奇",
"伊利",
"布罗克斯本",
"斯坦斯特德机场",
"不在意",
"剑桥",
"格拉斯顿堡",
"铜壶餐厅",
"金斯林",
"伯恩茅斯",
"斯多福特主教",
"莱斯特",
"伦敦国王十字区",
"未提及",
"美食汉堡厨房",
"城北中心",
"斯蒂夫尼奇",
],
"日期": ["星期二", "星期五", "星期日", "星期三", "星期六", "不在意", "未提及", "星期一", "星期四", "none"],
"到达时间": [
"21:51",
"03:00",
"16:44",
"11:32",
"18:03",
"18:07",
"14:43",
"10:54",
"13:15",
"07:08",
"20:30",
"13:03",
"13:52",
"8:30",
"21:08",
"08:00",
"05:30",
"13:00",
"06:15",
"15:45",
"11:54",
"10:09",
"13:17",
"19:00",
"20:06",
"09:30",
"12:07",
"09:06",
"14:01",
"16:08",
"07:30",
"21:00",
"13:51",
"18:06",
"18:00",
"14:45",
"16:00",
"19:45",
"15:15",
"19:27",
"20:54",
"13:58",
"20:08",
"17:15",
"21:30",
"none",
"10:08",
"18:32",
"20:45",
"06:01",
"19:51",
"剑桥",
"18:15",
"13:30",
"11:00",
"07:00",
"06:30",
"12:00",
"15:07",
"19:52",
"08:07",
"10:45",
"16:23",
"02:00",
"10:00",
"21:20",
"20:38",
"17:45",
"17:00",
"21:07",
"15:06",
"19:54",
"21:45",
"10:06",
"08:23",
"10:23",
"09:32",
"08:56",
"16:45",
"12:06",
"8",
"07:52",
"15:01",
"16:32",
"14:00",
"07:35",
"11:06",
"17:23",
"05:52",
"20:00",
"13:06",
"15:30",
"17:30",
"20:15",
"22:07",
"18:30",
"16:15",
"20:07",
"12:30",
"08:54",
"16:30",
"06:45",
"06:55",
"16:07",
"06:43",
"10:43",
"11:52",
"07:44",
"9:30",
"11:15",
"12:15",
"21:24",
"19:32",
"17:51",
"22:00",
"10:32",
"09:00",
"19:15",
"06:07",
"08:45",
"19:30",
"18:35",
"15:54",
"07:15",
"13:32",
"21:06",
"09:45",
"1545",
"14:15",
"15:24",
"10:07",
"13:38",
"14:24",
"16:58",
"18:10",
"10:30",
"11:30",
"21:15",
"不在意",
"22:01",
"19:57",
"1100",
"17:58",
"18:23",
"13:45",
"23:30",
"02:30",
"15:00",
"22:06",
"20:20",
"08:30",
"23:00",
"09:15",
"23:27",
"08:44",
"19:58",
"09:01",
"18:45",
"16:06",
"12:45",
"11:45",
"10:15",
"14:07",
"12:43",
"14:30",
"08:15",
"未提及",
"19:44",
"20:32",
"16:43",
],
"出发地": [
"伯明翰新街",
"彼得堡",
"汉密尔顿旅馆",
"利物浦",
"埃尔斯布雷旅社宾馆",
"伦敦",
"亨廷顿",
"斯特拉特福德",
"瓦德尔布里公园旅馆",
"伦敦利物浦街",
"none",
"诺里奇",
"伊利",
"布罗克斯本",
"斯坦斯特德机场",
"不在意",
"剑桥",
"伦敦东",
"电影世界",
"达克斯福德",
"金斯林",
"帕纳哈尔餐厅",
"斯多福特主教",
"布鲁克希尔",
"莱斯特",
"撑船",
"市政厅",
"伦敦国王十字区",
"未提及",
"阿尔法·米尔顿",
"伦敦利物浦",
"一号咖啡馆",
"斯蒂夫尼奇",
],
"人数": ["8", "1", "2", "3", "4", "不在意", "5", "10", "6", "7", "15", "9", "none"],
},
"景点": {
"类型": [
"娱乐",
"远足或历史的",
"划船",
"夜店",
"博物馆茶壶院",
"小船",
"游泳池",
"特别的",
"音乐厅",
"剧院",
"运动",
"none",
"娱乐或电影院或博物馆或剧院",
"户外的",
"不在意",
"学院",
"多元化运动",
"美食酒吧",
"博物馆",
"博物馆或夜店",
"画廊",
"电影院",
"多元化运动或剧院",
"音乐会",
"公园",
"撑船",
"音乐厅或小船",
"酒店",
"教堂",
"建筑学",
"丘吉尔学院",
"未提及",
"公园或小船",
],
"名称": [
"交界处",
"拜亚德艺术",
"丘吉尔学院公寓酒店",
"三一街学院",
"如家酒店",
"剑桥临时艺术",
"城堡画廊",
"羊的绿色和lammas土地公园芬堤道",
"努沙山林小屋或保龄球中心",
"地点",
"剑桥当代艺术博物馆",
"植物园",
"修道院游泳池",
"基督学院或圣凯瑟琳市",
"adc 剧院",
"咖啡果冻画廊",
"保龄球中心",
"当代艺术博物馆",
"电影院",
"惠普科学历史博物馆",
"基督学院或唐宁学院",
"咖啡果冻博物馆",
"剑桥船夫餐厅",
"十二大街画廊",
"果冻巷",
"柏丽游泳池",
"撑船",
"酱",
"摄政画廊",
"模拟数字剧院",
"考古和人类学博物馆或菲茨威廉博物馆",
"玩的愉快",
"保龄球中心或努沙山林小屋",
"切里欣顿庄园",
"诸圣堂",
"芒福德剧院",
"耶稣学院",
"大圣玛丽教堂",
"剑桥谷物交易所",
"剑桥大学植物园",
"撑船或芬克芬之家",
"瓦德尔布里公园旅馆",
"冈维尔和凯厄斯学院",
"切里欣顿村中心",
"none",
"芬堤道上的绿草羊群拉姆斯兰公园",
"金树篱学习池",
"休斯学堂",
"水壶的院子",
"剑桥郡民俗博物馆",
"剑桥",
"画廊",
"努沙山林小屋",
"王室学习游泳池",
"卡莱尔大厅学堂",
"剑桥科技博物馆",
"圣三一教堂",
"县民俗博物馆",
"基督教堂",
"皇后学院",
"老教堂",
"修道院游泳池和阿斯特鲁夫",
"江轮乔治娜",
"米尔顿国家公园",
"斯库德默撑篙公司",
"伦敦国王学院或休斯学堂",
"电影世界电影院",
"甲乙丙剧院",
"圣凯瑟琳学院",
"西德尼·苏塞克斯学院",
"路点",
"康巴尔夜总会",
"拱门宾馆",
"耶稣绿色户外游泳池",
"惠普尔博物馆",
"科希努尔",
"古典考古博物馆",
"斯库达莫尔撑船公司或剑桥船夫餐厅",
"坦",
"冈维尔酒店",
"普里马韦拉",
"剑桥艺术剧院",
"菲兹俱乐部",
"披萨",
"价值别墅酒店",
"灵魂树",
"格顿学院人民肖像展",
"万德伯里国家公园",
"视图电影院",
"霍布森旅馆",
"人物肖像展",
"斯库达莫尔船艇公司",
"基督学院",
"圣基督学院",
"斯科特极地博物馆",
"曼谷城市酒店",
"伊曼纽尔学院",
"苏格兰极地",
"绿草羊群公园",
"三一学院",
"小圣玛丽教堂",
"愉快的时光",
"阿姆斯大学酒店",
"丘吉尔学院",
"床",
"威廉艺术与古董",
"西德尼·苏塞克斯学院或冈维尔与凯斯学院",
"一号咖啡馆",
"科学历史博物馆",
"圣体学院",
"布劳顿画廊",
"剑桥和乡村民俗博物馆",
"圣巴纳巴斯新闻画廊",
"埃尔斯布雷旅社宾馆",
"皇后",
"舞蹈俱乐部",
"免费",
"月亮之上音乐厅",
"牛津大学彭布罗克学院",
"剑桥玉米交易所",
"芬克芬之家",
"唐宁学院",
"考古与人类博物馆",
"卡莱尔学院",
"剑桥植物园",
"修道院游泳池和人造草皮球场",
"圣约翰学院",
"不在意",
"城堡画廊或普里马韦拉",
"考古和人类学博物馆",
"菲茨威廉博物馆",
"学院",
"博物馆",
"船",
"城市",
"考古博物馆",
"旧校舍",
"麦格达伦学院",
"林恩斯特沃画廊",
"切里欣顿水上乐园",
"剑桥艺术品",
"鲁斯金画廊",
"灵魂之树夜店",
"斯库德默撑篙公司或剑桥船夫餐厅",
"伦敦国王学院",
"剑桥当代艺术馆",
"耶稣绿地",
"学校",
"切里欣顿会所",
"拉姆斯兰公园",
"未提及",
"剑桥图书印刷画廊",
"萨尔萨舞舞蹈俱乐部",
"茶壶院",
"圣玛丽大教堂",
"切里欣顿水上公园",
],
"区域": ["西部", "中心或西部", "中心", "不在意", "北方", "未提及", "东方", "南方", "none"],
},
"餐厅": {
"价格范围": ["中等的", "不在意", "未提及", "中等的或便宜的", "昂贵的", "便宜的", "none"],
"区域": ["西部", "东方或南方", "中心", "不在意", "北方", "未提及", "东方", "星期四", "南方", "none"],
"食物": [
"加勒比地区的",
"中国的或墨西哥的",
"北美的>印度的",
"口味清淡的",
"加泰罗尼亚的",
"国际的",
"现代折中的",
"印度的或非洲的",
"犹太食品",
"罗马尼亚的",
"新加坡的",
"印度的",
"交叉",
"世界",
"比利时的",
"美洲",
"清真",
"美国的",
"墨西哥的",
"丹Magdalene的",
"英国的",
"北印度的",
"创造性的",
"烧烤",
"斯堪的纳维亚",
"新西兰",
"不寻常的",
"寿司",
"美国传统的",
"广东的",
"越南的",
"犹太食品或英国的",
"黎巴嫩的",
"圣诞节",
"南非的",
"巴西的",
"传统的",
"亚洲东方的",
"海鲜",
"北非的",
"加勒比地区的>印度的",
"现代欧洲的",
"none",
"中国的",
"韩国的",
"苏格兰的",
"拉美的",
"欧洲的",
"西班牙的或葡萄牙的",
"摩洛哥的",
"泛亚的",
"澳大利亚的",
"俄罗斯的",
"厄立特里亚的",
"瑞典的",
"斯里兰卡的",
"意大利的或印度的",
"英格兰的",
"法国的",
"牛排餐厅",
"牙买加的>中国的",
"威尔士的",
"中东的",
"亚洲的",
"希腊",
"匈牙利的",
"道焦面馆",
"科西嘉",
"现代欧洲",
"现代全球的",
"北美的",
"德国的",
"巴斯克人",
"意大利的",
"现代英格兰的",
"日本的",
"开胃小菜",
"西方",
"阿富汗",
"奥地利的",
"东欧的",
"非洲的",
"泰国和中国的",
"波兰的",
"融合",
"牙买加的",
"西班牙的",
"土耳其的",
"北欧的",
"泰国",
"烧烤>现代欧洲的",
"印度尼西亚的",
"下午茶",
"澳大利亚的或印度的",
"葡萄牙的",
"马来西亚的",
"波利尼西亚的",
"威尼斯的",
"不在意",
"托斯卡纳的",
"分子美食",
"波斯的",
"地中海的",
"现代美国的",
"小酒馆",
"古巴的",
"素食的",
"南印度的",
"巴西的或葡萄牙的",
"未提及",
"爱尔兰的",
"瑞士的",
],
"名称": [
"美味厨房",
"游客休闲之家酒店",
"秋季别墅酒店",
"咖喱之家",
"橡树小酒馆",
"拉米莫萨餐厅",
"鱼米之乡",
"好运",
"梅泽酒吧餐馆",
"询问",
"小丑咖啡馆",
"皇家标准酒店",
"泰姬唐杜里餐厅",
"栀子花餐厅",
"火锅",
"蛞蝓和莴苣餐厅",
"铜壶餐厅",
"卢卡厨房酒吧和河畔法式餐厅",
"回味轩",
"南部",
"北京餐馆",
"清平餐厅",
"上海人家",
"福来居或尼拉拉",
"基姆莫伊中餐厅",
"艾瑞娜餐厅和迈克尔咖啡馆",
"剑桥船夫餐厅",
"梅兹酒吧",
"柏丽游泳池",
"阿里巴巴餐厅",
"西贡市",
"库托餐厅",
"芬迪顿必胜客",
"拉塔斯卡西班牙餐厅",
"梅格纳餐厅",
"甘地餐厅",
"22号餐厅",
"剑桥马哈尔餐厅",
"德鲁纳烹饪酒吧",
"问餐厅",
"南多斯市中心",
"唐杜里烹饪法",
"努斯",
"格樂麗雅",
"萨拉通餐厅",
"不",
"格拉夫顿酒店餐厅",
"失踪的袜子餐厅",
"none",
"剑桥滋意餐厅",
"咖喱女王",
"洛克凡",
"檀槟饭店",
"梅泽酒吧",
"西塔泥炉炭火烹饪",
"剑桥",
"贝都因",
"努沙山林小屋",
"必胜客樱桃辛顿或美食餐厅",
"贝多因人餐厅",
"圣约翰小饭馆",
"西塔尔饭店",
"剑桥旅馆餐厅",
"咖哩王子餐厅或拉吉泰姬陵旅馆",
"尼拉拉",
"王公唐杜里餐厅",
"美食汉堡厨房",
"萨代艾尔别墅酒店",
"泥炉炭火烹饪法宫",
"道焦面馆",
"伊莱娜",
"客家",
"时髦的",
"咖哩王子餐厅",
"豫园",
"阿什利酒店",
"丑小鸭餐厅",
"好运中餐外卖",
"河畔牛排烧烤店",
"科希努尔",
"必胜客",
"达里的厨房酒馆",
"欧洲人",
"安纳托里亚酒店",
"二号餐厅",
"二号餐厅和科特餐厅",
"一七餐厅",
"普里马韦拉",
"火锅店",
"陈查理餐厅",
"港式小厨",
"唐人饭店",
"市中心必胜客",
"皇家香料餐厅",
"艾菲斯餐馆",
"印度之家餐厅",
"亚历克斯餐厅",
"价值别墅酒店",
"萨拉通餐厅或曼谷城市酒店",
"奇基多餐厅",
"藏红花法式餐厅",
"北京烤鸭店",
"蛞蝓和莴苣美食酒吧",
"dif",
"西拉酒",
"巴尔巴坎饭店",
"后街小酒馆",
"拉拉萨酒店",
"小牛披萨餐厅酒吧",
"霍布森旅馆",
"小首尔",
"帕纳哈尔餐厅",
"斯库达莫尔船艇公司",
"cam",
"曼谷城市酒店",
"沃阿巴河",
"智慧佛主题餐厅",
"河畔啤酒庄",
"莱姆豪斯",
"牛排披萨烹饪吧",
"必胜客樱桃辛顿",
"一号咖啡馆",
"南多斯烤鸡店",
"布鲁姆斯伯里餐厅",
"咖喱饭",
"布劳顿画廊",
"迈克尔咖啡屋",
"普雷佐餐厅",
"涂鸦馆",
"无",
"桥梁餐厅",
"味美面馆",
"安纳托利亚餐厅和艾菲餐厅",
"车站餐厅咖啡吧",
"印度之西餐厅",
"城市驿站餐厅",
"瓦尔斯蒂饭店",
"上海",
"阿登酒店",
"不在意",
"拉吉泰姬陵旅馆",
"金陵饭店",
"温恩德比斯特剑桥酒店",
"分子美食",
"科希努尔餐厅",
"城市",
"厨房和酒吧",
"格拉夫顿酒店",
"弗兰基&本尼",
"道焦面馆或杰饭店",
"拉面道",
"cote",
"一七饭店",
"美食餐厅",
"奇基托餐厅酒吧",
"剑桥小饭馆",
"幸运星餐厅",
"福来居",
"仲夏坞餐厅",
"皮帕莎餐厅",
"兰香楼",
"拉玛格里塔餐厅",
"唐帕斯夸里披萨店",
"杰饭店",
"马哈尔",
"艾菲啤酒",
"披萨快递",
"幸运星民宿",
"费兹毕丽斯餐厅",
"市中心国王街道4号",
"咖哩王",
"未提及",
"查理餐厅",
"达芬奇披萨餐厅",
"米饭之家",
"河畔牛排烧烤餐厅",
"芝麻餐厅酒吧",
"洛弗尔餐厅",
],
"时间": [
"19:45",
"15:15",
"09:45",
"15:30|16:30",
"03:00",
"14:00",
"18:00|12:15",
"14:15",
"17:15",
"20:00",
"15:30",
"none",
"17:30",
"20:15",
"18:30",
"20:45",
"10:30",
"16:15",
"11:30",
"12:30",
"13:15",
"16:00",
"20:30",
"不在意",
"14:40",
"17:30|16:30",
"16:30",
"13:45",
"9",
"1430",
"18:15",
"13:30",
"10:48",
"15:00",
"11:00",
"下午4点",
"13:00",
"06:30",
"12:00",
"1345",
"09:15",
"9:30",
"晚上8点",
"15:45",
"11:15",
"1330",
"12:15",
"11:30|12:30",
"10:45",
"19:00",
"09:30",
"18:45",
"晚上7点",
"10:00",
"01:00",
"12:45",
"17:00",
"11:45",
"10:15",
"17:45",
"22:00",
"19:15",
"09:00",
"14:30",
"9:00",
"21:00",
"17:00|16:00",
"21:45",
"19:30",
"1145",
"08:45",
"1715",
"18:00",
"14:45",
"16:45",
],
"日期": [
"星期日或星期四",
"星期二",
"星期五",
"星期日",
"星期三",
"星期六",
"不在意",
"星期六或星期四",
"星期一",
"星期四",
"none",
],
"人数": ["8", "1", "2", "4|7", "3", "4", "5", "6", "7", "none"],
},
"出租车": {
"出发时间": [
"22:15",
"03:00",
"13:15",
"05:15",
"20:30",
"01:45",
"08:00",
"05:30",
"13:00",
"06:15",
"15:45",
"02:45",
"19:00",
"09:30",
"07:30",
"21:00",
"24:00",
"18:00",
"14:45",
"16:00",
"19:45",
"15:15",
"24:15",
"06:00",
"17:15",
"21:30",
"none",
"22:45",
"20:45",
"18:15",
"13:30",
"11:00",
"07:00",
"06:30",
"2:30之后",
"12:00",
"15:25",
"03:15",
"13:45之后",
"10:45",
"02:00",
"10:00",
"17:45",
"17:00",
"星期五",
"05:45",
"24:45",
"21:45",
"05:00",
"22:30",
"11:45之后",
"16:45",
"亨廷顿万豪酒店",
"04:15",
"14:00",
"21:25",
"20:00",
"15:30",
"17:30",
"20:15",
"04:45",
"18:30",
"16:15",
"12:30",
"星期四",
"06:45",
"16:30",
"03:30",
"03:45",
"11:15",
"12:15",
"02:15",
"01:00",
"22:00",
"09:00",
"19:15",
"23:15",
"04:30",
"01:30",
"08:45",
"19:30",
"07:15",
"09:45",
"03:20",
"14:15",
"8:00",
"24:30",
"10:30",
"00:45",
"21:15",
"不在意",
"11:30",
"13:45",
"23:30",
"02:30",
"15:00",
"10:50",
"15:45之后",
"23:00",
"08:30",
"09:15",
"01:15",
"07:45",
"23:45",
"18:45",
"12:45",
"11:45",
"10:15",
"04:00",
"14:30",
"08:15",
"未提及",
],
"目的地": [
"交界处",
"拜亚德艺术",
"游客休闲之家酒店",
"丘吉尔学院公寓酒店",
"秋季别墅酒店",
"咖喱之家",
"鱼米之乡",
"橡树小酒馆",
"拉米莫萨餐厅",
"好运",
"如家酒店",
"城堡画廊",
"询问",
"小丑咖啡馆",
"萨代艾尔",
"皇家标准酒店",
"切里欣顿水上公园",
"泰姬唐杜里餐厅",
"栀子花餐厅",
"蛞蝓和莴苣餐厅",
"观光胜地",
"adc 剧院",
"铜壶餐厅",
"咖啡果冻画廊",
"回味轩",
"保龄球中心",
"北京餐馆",
"上海人家",
"惠普科学历史博物馆",
"基姆莫伊中餐厅",
"剑桥船夫餐厅",
"斯多福特主教火车站",
"假日快捷剑桥酒店",
"十二大街画廊",
"剑桥贝尔弗莱酒店",
"柏丽游泳池",
"阿里巴巴餐厅",
"洛弗尔旅馆酒店",
"剑桥路基督教堂",
"撑船",
"西贡市",
"摄政画廊",
"库托餐厅",
"玩的愉快",
"芬迪顿必胜客",
"拉塔斯卡西班牙餐厅",
"甘地餐厅",
"梅格纳餐厅",
"诸圣堂",
"芬奇住宿加早餐旅馆",
"切里欣顿庄园",
"纽马克特路发现者街角",
"剑桥马哈尔餐厅",
"德鲁纳烹饪酒吧",
"南多斯市中心",
"芒福德剧院",
"耶稣学院",
"格樂麗雅",
"汉密尔顿旅馆",
"阿尔法米尔顿宾馆",
"剑桥谷物交易所",
"美食餐厅",
"剑桥大学植物园",
"萨拉通餐厅",
"剑桥桥梁宾馆",
"瓦德尔布里公园旅馆",
"格拉夫顿酒店餐厅",
"冈维尔和凯厄斯学院",
"切里欣顿村中心",
"失踪的袜子餐厅",
"none",
"剑桥滋意餐厅",
"芬堤道上的绿草羊群拉姆斯兰公园",
"洛克凡",
"檀槟饭店",
"休斯学堂",
"梅泽酒吧",
"西塔泥炉炭火烹饪",
"剑桥",
"剑桥郡民俗博物馆",
"美食酒吧",
"罗萨斯住宿加早餐旅馆",
"努沙山林小屋",
"贝都因",
"王室学习游泳池",
"阿伯里小屋旅馆",
"卡莱尔大厅学堂",
"剑桥科技博物馆",
"圣约翰小饭馆",
"圣三一教堂",
"剑桥旅馆餐厅",
"尼拉拉",
"皇后学院",
"斯蒂夫尼奇火车站",
"江轮乔治娜",
"米尔顿国家公园",
"斯里珀兹酒店",
"lamimosa",
"斯库德默撑篙公司",
"王公唐杜里餐厅",
"电影世界电影院",
"萨代艾尔别墅酒店",
"美食汉堡厨房",
"剑桥休闲公园克利夫顿路",
"圣凯瑟琳学院",
"伦敦利物浦街火车站",
"路点",
"西德尼·苏塞克斯学院",
"道焦面馆",
"泥炉炭火烹饪法宫",
"拱门宾馆",
"康巴尔夜总会",
"伊莱娜",
"沃克沃斯宾馆",
"亨廷顿万豪酒店",
"客家",
"饭店",
"耶稣绿色户外游泳池",
"咖哩王子餐厅",
"阿什利酒店",
"豫园",
"丑小鸭餐厅",
"安纳托利亚餐厅",
"河畔牛排烧烤店",
"剑桥商店",
"科希努尔",
"达里的厨房酒馆",
"古典考古博物馆",
"沃克沃斯酒店",
"二号餐厅",
"安纳托里亚酒店",
"冈维尔酒店",
"普里马韦拉",
"火锅店",
"陈查理餐厅",
"彼得伯勒火车站",
"港式小厨",
"阿登布鲁克医院",
"唐人饭店",
"剑桥艺术剧院",
"菲兹俱乐部",
"市中心摄政街",
"市中心必胜客",
"皇家香料餐厅",
"艾菲斯餐馆",
"印度之家餐厅",
"价值别墅酒店",
"诺威奇火车站",
"高大的纪念碑",
"藏红花法式餐厅",
"帕克赛德警察局",
"格顿学院人民肖像展",
"圣巴纳巴斯",
"西拉酒",
"视图电影院",
"后街小酒馆",
"拉拉萨酒店",
"霍布森旅馆",
"小首尔",
"基督学院",
"帕纳哈尔餐厅",
"斯科特极地博物馆",
"曼谷城市酒店",
"沃阿巴河",
"伊曼纽尔学院",
"三一学院",
"小圣玛丽教堂",
"亚历山大住宿加早餐旅馆",
"伦兹菲尔德酒店",
"阿姆斯大学酒店",
"河畔啤酒庄",
"斯坦斯特德机场火车站",
"丘吉尔学院",
"莱姆豪斯",
"阿瓦隆",
"客家或橡果宾馆",
"牛排披萨烹饪吧",
"威廉艺术与古董",
"必胜客樱桃辛顿",
"市旅游博物馆旁的剑桥郡博览会",
"一号咖啡馆",
"南多斯烤鸡店",
"布鲁姆斯伯里餐厅",
"柯克伍德别墅酒店",
"圣体学院",
"咖喱饭",
"布劳顿画廊",
"迈克尔咖啡屋",
"普雷佐餐厅",
"涂鸦馆",
"无",
"埃尔斯布雷旅社宾馆",
"味美面馆",
"圣巴纳巴斯新闻画廊",
"艾伦拜尔",
"舞蹈俱乐部",
"伊利火车站",
"牛津大学彭布罗克学院",
"月亮之上音乐厅",
"车站餐厅咖啡吧",
"剑桥火车站",
"芬克芬之家",
"唐宁学院",
"布罗克斯本火车站",
"车站路",
"城市驿站餐厅",
"瓦尔斯蒂饭店",
"卡莱尔学院",
"修道院游泳池和人造草皮球场",
"圣约翰学院",
"伦敦国王十字区站",
"考古和人类学博物馆",
"菲茨威廉博物馆",
"拉吉泰姬陵旅馆",
"金陵饭店",
"温恩德比斯特剑桥酒店",
"伯明翰新街火车站",
"莱斯特火车站",
"旧校舍",
"格拉夫顿酒店",
"弗兰基&本尼",
"卡罗莱纳家庭旅馆",
"A&B 宾馆",
"拉面道",
"麦格达伦学院",
"cote",
"橡果宾馆",
"奇基托餐厅酒吧",
"林恩斯特沃画廊",
"剑桥小饭馆",
"剑桥艺术品",
"福来居",
"灵魂之树夜店",
"一七饭店",
"仲夏坞餐厅",
"伦敦国王学院",
"皮帕莎餐厅",
"切里欣顿水上乐园",
"鲁斯金画廊",
"剑桥当代艺术馆",
"兰香楼",
"唐帕斯夸里披萨店",
"拉玛格里塔餐厅",
"客房城市",
"城北住宿加早餐酒店",
"杰饭店",
"幸运星民宿",
"披萨快递",
"费兹毕丽斯餐厅",
"咖哩王",
"未提及",
"剑桥图书印刷画廊",
"茶壶院",
"萨尔萨舞舞蹈俱乐部",
"达芬奇披萨餐厅",
"米饭之家",
"圣玛丽大教堂",
"芝麻餐厅酒吧",
],
"出发地": [
"交界处",
"拜亚德艺术",
"游客休闲之家酒店",
"秋季别墅酒店",
"咖喱之家",
"橡树小酒馆",
"拉米莫萨餐厅",
"鱼米之乡",
"好运",
"如家酒店",
"城堡画廊",
"伦敦利物浦街",
"小丑咖啡馆",
"询问",
"林恩斯特沃画廊",
"萨代艾尔",
"皇家标准酒店",
"泰姬唐杜里餐厅",
"栀子花餐厅",
"蛞蝓和莴苣餐厅",
"adc 剧院",
"铜壶餐厅",
"咖啡果冻画廊",
"回味轩",
"保龄球中心",
"切斯特敦路172号",
"切里欣顿路",
"北京餐馆",
"惠普科学历史博物馆",
"基姆莫伊中餐厅",
"市中心我的酒店",
"剑桥船夫餐厅",
"斯多福特主教火车站",
"假日快捷剑桥酒店",
"米尔巷格兰塔广场剑桥希尔顿逸林酒店",
"十二大街画廊",
"剑桥贝尔弗莱酒店",
"柏丽游泳池",
"阿里巴巴餐厅",
"洛弗尔旅馆酒店",
"撑船",
"西贡市",
"摄政画廊",
"库托餐厅",
"玩的愉快",
"拉塔斯卡西班牙餐厅",
"切里欣顿庄园",
"芬迪顿必胜客",
"甘地餐厅",
"诸圣堂",
"芬奇住宿加早餐旅馆",
"梅格纳餐厅",
"剑桥马哈尔餐厅",
"德鲁纳烹饪酒吧",
"问餐厅",
"南多斯市中心",
"芒福德剧院",
"耶稣学院",
"格樂麗雅",
"阿尔法米尔顿宾馆",
"汉密尔顿旅馆",
"剑桥谷物交易所",
"伍德布里奇路4455号",
"剑桥大学植物园",
"萨拉通餐厅",
"剑桥桥梁宾馆",
"瓦德尔布里公园旅馆",
"格拉夫顿酒店餐厅",
"失踪的袜子餐厅",
"冈维尔和凯厄斯学院",
"切里欣顿村中心",
"none",
"剑桥滋意餐厅",
"芬堤道上的绿草羊群拉姆斯兰公园",
"咖喱女王",
"洛克凡",
"金斯林火车站",
"檀槟饭店",
"休斯学堂",
"伊利",
"唐宁街",
"梅泽酒吧",
"剑桥郡民俗博物馆",
"剑桥",
"西塔泥炉炭火烹饪",
"罗萨斯住宿加早餐旅馆",
"努沙山林小屋",
"贝都因",
"伦敦利物浦街火车站",
"王室学习游泳池",
"阿伯里小屋旅馆",
"卡莱尔大厅学堂",
"圣约翰小饭馆",
"剑桥科技博物馆",
"绿草羊群拉姆斯兰公园",
"圣三一教堂",
"汇合剧院",
"剑桥旅馆餐厅",
"皇后学院",
"酒店",
"尼拉拉",
"斯蒂夫尼奇火车站",
"江轮乔治娜",
"米尔顿国家公园",
"家",
"斯库德默撑篙公司",
"王公唐杜里餐厅",
"电影世界电影院",
"萨代艾尔别墅酒店",
"美食汉堡厨房",
"圣凯瑟琳学院",
"沃克沃斯宾馆",
"路点",
"泥炉炭火烹饪法宫",
"道焦面馆",
"西德尼·苏塞克斯学院",
"拱门宾馆",
"康巴尔夜总会",
"伊莱娜",
"格顿学院",
"亨廷顿万豪酒店",
"客家",
"耶稣绿色户外游泳池",
"咖哩王子餐厅",
"阿什利酒店",
"豫园",
"丑小鸭餐厅",
"好运中餐外卖",
"河畔牛排烧烤店",
"科希努尔",
"古典考古博物馆",
"达里的厨房酒馆",
"二号餐厅",
"安纳托里亚酒店",
"冈维尔酒店",
"普里马韦拉",
"彼得伯勒火车站",
"陈查理餐厅",
"火锅店",
"剑桥艺术剧院",
"菲兹俱乐部",
"阿登布鲁克医院",
"唐人饭店",
"剑桥城市信息中心",
"市中心必胜客",
"皇家香料餐厅",
"印度之家餐厅",
"价值别墅酒店",
"诺威奇火车站",
"提及的",
"克莱尔霍学院",
"藏红花法式餐厅",
"帕克赛德警察局",
"格顿学院人民肖像展",
"西拉酒",
"后街小酒馆",
"视图电影院",
"拉拉萨酒店",
"霍布森旅馆",
"帕纳哈尔餐厅",
"基督学院",
"小首尔",
"切里欣顿社区中心",
"斯科特极地博物馆",
"新英格兰",
"沃阿巴河",
"曼谷城市酒店",
"伊曼纽尔学院",
"三一学院",
"亚历山大住宿加早餐旅馆",
"伦兹菲尔德酒店",
"小圣玛丽教堂",
"阿姆斯大学酒店",
"河畔啤酒庄",
"丘吉尔学院",
"莱姆豪斯",
"阿瓦隆",
"牛排披萨烹饪吧",
"威廉艺术与古董",
"必胜客樱桃辛顿",
"一号咖啡馆",
"南多斯烤鸡店",
"布鲁姆斯伯里餐厅",
"柯克伍德别墅酒店",
"圣体学院",
"咖喱饭",
"布劳顿画廊",
"列文顿旅馆",
"迈克尔咖啡屋",
"橡果宾馆或客家",
"涂鸦馆",
"普雷佐餐厅",
"埃尔斯布雷旅社宾馆",
"圣巴纳巴斯新闻画廊",
"味美面馆",
"艾伦拜尔",
"伊利火车站",
"舞蹈俱乐部",
"月亮之上音乐厅",
"车站餐厅咖啡吧",
"牛津大学彭布罗克学院",
"剑桥火车站",
"芬克芬之家",
"唐宁学院",
"卡莱尔学院",
"布罗克斯本火车站",
"瓦尔斯蒂饭店",
"城市驿站餐厅",
"修道院游泳池和人造草皮球场",
"圣约翰学院",
"伦敦国王十字区站",
"考古和人类学博物馆",
"菲茨威廉博物馆",
"拉吉泰姬陵旅馆",
"金陵饭店",
"温恩德比斯特剑桥酒店",
"伯明翰新街火车站",
"博物馆",
"旧校舍",
"弗兰基&本尼",
"A&B 宾馆",
"卡罗莱纳家庭旅馆",
"拉面道",
"麦格达伦学院",
"cote",
"橡果宾馆",
"美食餐厅",
"一七饭店",
"切里欣顿水上乐园",
"剑桥艺术品",
"福来居",
"灵魂之树夜店",
"鲁斯金画廊",
"伦敦国王学院",
"奇基托餐厅酒吧",
"阿尔耶斯布雷洛奇酒店",
"剑桥小饭馆",
"仲夏坞餐厅",
"剑桥当代艺术馆",
"兰香楼",
"客房城市",
"拉玛格里塔餐厅",
"唐帕斯夸里披萨店",
"城北住宿加早餐酒店",
"杰饭店",
"披萨快递",
"幸运星民宿",
"费兹毕丽斯餐厅",
"咖哩王",
"未提及",
"剑桥图书印刷画廊",
"萨尔萨舞舞蹈俱乐部",
"茶壶院",
"达芬奇披萨餐厅",
"米饭之家",
"圣玛丽大教堂",
"芝麻餐厅酒吧",
],
"到达时间": [
"22:15",
"03:00",
"13:15",
"05:15",
"20:30",
"01:45",
"08:00",
"05:30",
"13:00",
"06:15",
"15:45",
"02:45",
"19:00",
"09:30",
"17:05",
"15:23",
"07:30",
"21:00",
"24:00",
"18:00",
"14:45",
"16:00",
"19:45",
"15:15",
"24:15",
"06:00",
"17:15",
"21:30",
"none",
"20:45",
"18:15",
"13:30",
"11:00",
"07:00",
"06:30",
"12:00",
"03:15",
"10:45",
"02:00",
"10:00",
"17:00",
"17:45",
"05:45",
"24:45",
"21:45",
"22:30",
"16;15",
"16:45",
"04:15",
"14:00",
"20:00",
"15:30",
"17:30",
"20:15",
"18:30",
"04:45",
"16:15",
"12:30",
"06:45",
"16:30",
"03:30",
"03:45",
"11:15",
"12:15",
"02:15",
"01:00",
"22:00",
"09:00",
"19:15",
"23:15",
"04:30",
"01:30",
"19:30",
"07:15",
"09:45",
"14:15",
"24:30",
"10:30",
"11:30",
"21:15",
"不在意",
"13:45",
"23:30",
"02:30",
"15:00",
"23:00",
"08:30",
"09:15",
"01:15",
"07:45",
"18:45",
"12:45",
"11:45",
"10:15",
"04:00",
"14:30",
"08:15",
"未提及",
"13:05",
"15分钟",
],
},
"公共汽车": {
"出发时间": ["21:45", "未提及"],
"目的地": ["伦敦国王十字区", "未提及", "斯多福特主教", "剑桥", "科希努尔"],
"日期": ["星期三", "未提及"],
"到达时间": ["未提及"],
"出发地": ["剑桥", "未提及"],
},
}
| 22.30949 | 87 | 0.276865 | 3,432 | 47,720 | 3.795163 | 0.252914 | 0.009674 | 0.010365 | 0.011516 | 0.17881 | 0.132745 | 0.104798 | 0.082917 | 0.070173 | 0.056353 | 0 | 0.127709 | 0.561065 | 47,720 | 2,138 | 88 | 22.319925 | 0.493889 | 0 | 0 | 0.647393 | 0 | 0 | 0.222758 | 0.001153 | 0 | 0 | 0 | 0 | 0 | 1 | 0.004265 | false | 0 | 0.003318 | 0.000948 | 0.013744 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
60ea0402c755413aeadaaa05b6f7a413a4181651 | 296 | py | Python | binaryninja/update_to_latest.py | 0t1s1/PaperMachete | ec110b2d18f3b8cf85ecd54b572f25ee0bc8e447 | [
"MIT"
] | 116 | 2017-09-24T14:48:34.000Z | 2022-03-17T06:24:17.000Z | binaryninja/update_to_latest.py | 0t1s1/PaperMachete | ec110b2d18f3b8cf85ecd54b572f25ee0bc8e447 | [
"MIT"
] | 21 | 2017-10-05T21:31:30.000Z | 2020-05-25T05:27:19.000Z | binaryninja/update_to_latest.py | 0t1s1/PaperMachete | ec110b2d18f3b8cf85ecd54b572f25ee0bc8e447 | [
"MIT"
] | 26 | 2017-09-25T03:12:12.000Z | 2022-01-06T19:12:55.000Z | import pexpect
import subprocess
import sys
child = pexpect.spawn('python /tmp/version_switcher.py')
child.logfile = sys.stdout
child.expect('Choice:')
child.sendline('1')
child.expect('Choice:')
child.sendline('1')
child.timeout=600
child.expect(['Choice:', 'UpdateSuccess'])
child.terminate()
| 21.142857 | 56 | 0.756757 | 39 | 296 | 5.717949 | 0.538462 | 0.147982 | 0.2287 | 0.197309 | 0.300448 | 0.300448 | 0.300448 | 0 | 0 | 0 | 0 | 0.018248 | 0.074324 | 296 | 13 | 57 | 22.769231 | 0.79562 | 0 | 0 | 0.333333 | 0 | 0 | 0.226351 | 0.081081 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.25 | 0 | 0.25 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
60eda0ae6d631b835183c3f1ed1d234a2006144f | 1,042 | py | Python | client/setup.py | TrackerSB/DriveBuild | d3f05ccabfd70732b7c32dca539861f79d02b0b3 | [
"MIT"
] | 3 | 2020-01-03T19:50:05.000Z | 2020-03-30T13:01:51.000Z | client/setup.py | TrackerSB/DriveBuild | d3f05ccabfd70732b7c32dca539861f79d02b0b3 | [
"MIT"
] | 9 | 2020-01-20T21:33:42.000Z | 2020-07-21T04:18:52.000Z | client/setup.py | TrackerSB/DriveBuild | d3f05ccabfd70732b7c32dca539861f79d02b0b3 | [
"MIT"
] | 3 | 2020-03-27T20:53:56.000Z | 2020-04-04T10:10:03.000Z | import setuptools
import os
with open(os.path.join(os.path.dirname(__file__), "README.md"), "r") as fh:
long_description = fh.read()
setuptools.setup(
name="drivebuild-client",
version="0.42",
author="Stefan Huber",
author_email="huberst@fim.uni-passau.de",
description="A client for accessing a DriveBuild MainApp.",
long_description=long_description,
long_description_content_type="text/markdown",
license="MIT",
packages=setuptools.find_packages(
include=("drivebuildclient",)
),
python_requires=">=3.6",
install_requires=[
"dill",
"flask",
"protobuf"
],
classifiers=[
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
],
project_urls={
"Source": "https://github.com/TrackerSB/DriveBuild"
}
)
| 28.162162 | 75 | 0.6238 | 110 | 1,042 | 5.772727 | 0.636364 | 0.149606 | 0.19685 | 0.16378 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.014963 | 0.230326 | 1,042 | 36 | 76 | 28.944444 | 0.776808 | 0 | 0 | 0.058824 | 0 | 0 | 0.404031 | 0.023992 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.029412 | 0.058824 | 0 | 0.058824 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
60ef8810f26b2935944f4ddfef172795cb5f9ccb | 285 | py | Python | test/run/ClassTest.py | pip-services-python/pip-services-commons-python | ecfe0aab2b1442ed3b550115dd2c2472537452de | [
"MIT"
] | null | null | null | test/run/ClassTest.py | pip-services-python/pip-services-commons-python | ecfe0aab2b1442ed3b550115dd2c2472537452de | [
"MIT"
] | null | null | null | test/run/ClassTest.py | pip-services-python/pip-services-commons-python | ecfe0aab2b1442ed3b550115dd2c2472537452de | [
"MIT"
] | 2 | 2020-03-11T21:41:13.000Z | 2020-03-14T00:26:20.000Z | # -*- coding: utf-8 -*-
class ClassTest:
def __init__(self, value1, value2):
self.value1 = value1
self._value2 = value2
@property
def value2(self):
return self._value2
@value2.setter
def value2(self, value):
self._value2 = value
| 17.8125 | 39 | 0.589474 | 32 | 285 | 5.03125 | 0.4375 | 0.186335 | 0.198758 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.06 | 0.298246 | 285 | 15 | 40 | 19 | 0.745 | 0.073684 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.3 | false | 0 | 0 | 0.1 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
60f1e65a7bc426d0b8bc9016321dfa4760d45b01 | 1,180 | py | Python | setup.py | KellerChe/copy-from-the-google-speech-to-text-model | ea82667ae7853ea55ef157dd5cbc01ca09305342 | [
"Apache-2.0"
] | null | null | null | setup.py | KellerChe/copy-from-the-google-speech-to-text-model | ea82667ae7853ea55ef157dd5cbc01ca09305342 | [
"Apache-2.0"
] | null | null | null | setup.py | KellerChe/copy-from-the-google-speech-to-text-model | ea82667ae7853ea55ef157dd5cbc01ca09305342 | [
"Apache-2.0"
] | null | null | null | '''
Copyright: University of Queensland, 2019
Contributors:
Nicholas Lambourne - (University of Queensland, 2019)
Ben Foley - (University of Queensland, 2019)
Robert Cochran - (University of Queensland, 2019)
Nicholas Buckeridge - (University of Queensland, 2019)
Emmanuel Tope-Ojo - (University of Queensland, 2019)
Rah Sanders-Dwyer - (University of Queensland, 2019)
'''
from setuptools import setup, find_packages
requirements = [dependency.strip() for dependency in open("requirements.txt", "r").readlines()]
with open('README.md', 'r') as readme:
long_description = readme.read()
setup(
name='elpis',
version='0.93.08',
packages=find_packages(),
url='https://github.com/CoEDL/elpis',
install_requires=requirements,
include_package_data=True,
license='',
author='CoEDL',
author_email='b.foley@uq.edu.au',
description='',
long_description=long_description,
classifiers=[
"Programming Language :: Python :: 3.6",
"Topic :: Text Processing :: Linguistic",
"Operating System :: Linux",
],
entry_points={
},
) | 30.25641 | 95 | 0.644068 | 125 | 1,180 | 6 | 0.64 | 0.112 | 0.205333 | 0.242667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.038631 | 0.232203 | 1,180 | 39 | 96 | 30.25641 | 0.789183 | 0.375424 | 0 | 0 | 0 | 0 | 0.261644 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.041667 | 0 | 0.041667 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
8800fe0506b6d86aeaa4e491ae6bf5ba64484826 | 110 | py | Python | exe.curso em video/def 48.py | Lorenzo-Lopes/Python-Estudo | 7ee623ce29b6a0e9fac48189fbd9c641be84d418 | [
"MIT"
] | null | null | null | exe.curso em video/def 48.py | Lorenzo-Lopes/Python-Estudo | 7ee623ce29b6a0e9fac48189fbd9c641be84d418 | [
"MIT"
] | null | null | null | exe.curso em video/def 48.py | Lorenzo-Lopes/Python-Estudo | 7ee623ce29b6a0e9fac48189fbd9c641be84d418 | [
"MIT"
] | null | null | null | s=0
tot =0
for c in range(1, 500, 2):
if (c % 3) == 0:
s += c
tot += 1
print(s)
print(tot) | 13.75 | 26 | 0.427273 | 23 | 110 | 2.043478 | 0.565217 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.147059 | 0.381818 | 110 | 8 | 27 | 13.75 | 0.544118 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.25 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
880583e4d529ca210f2cb100f974f1c50bb8b39f | 2,211 | py | Python | typedb/concept/answer/numeric.py | rpatil524/client-python | e8daba79842a81669f4f4c2799bcc8610e610551 | [
"Apache-2.0"
] | 47 | 2019-01-22T19:17:13.000Z | 2021-02-06T15:39:59.000Z | typedb/concept/answer/numeric.py | rpatil524/client-python | e8daba79842a81669f4f4c2799bcc8610e610551 | [
"Apache-2.0"
] | 85 | 2019-01-22T14:51:34.000Z | 2021-04-08T15:41:43.000Z | typedb/concept/answer/numeric.py | rpatil524/client-python | e8daba79842a81669f4f4c2799bcc8610e610551 | [
"Apache-2.0"
] | 24 | 2019-01-22T13:21:42.000Z | 2021-03-02T18:06:03.000Z | #
# Copyright (C) 2021 Vaticle
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
import typedb_protocol.common.answer_pb2 as answer_proto
from typedb.api.answer.numeric import Numeric
from typedb.common.exception import TypeDBClientException, BAD_ANSWER_TYPE, ILLEGAL_CAST
class _Numeric(Numeric):
def __init__(self, int_value, float_value):
self._int_value = int_value
self._float_value = float_value
@staticmethod
def of(numeric_proto: answer_proto.Numeric):
numeric_case = numeric_proto.WhichOneof("value")
if numeric_case == "long_value":
return _Numeric(numeric_proto.long_value, None)
elif numeric_case == "double_value":
return _Numeric(None, numeric_proto.double_value)
elif numeric_case == "nan":
return _Numeric(None, None)
else:
raise TypeDBClientException.of(BAD_ANSWER_TYPE, numeric_case)
def is_int(self):
return self._int_value is not None
def is_float(self):
return self._float_value is not None
def is_nan(self):
return not self.is_int() and not self.is_float()
def as_float(self):
if self.is_float():
return self._float_value
else:
raise TypeDBClientException.of(ILLEGAL_CAST, "float")
def as_int(self):
if self.is_int():
return self._int_value
else:
raise TypeDBClientException.of(ILLEGAL_CAST, "int")
| 33.5 | 88 | 0.704206 | 300 | 2,211 | 5 | 0.366667 | 0.04 | 0.032 | 0.064 | 0.089333 | 0.089333 | 0.064 | 0 | 0 | 0 | 0 | 0.005239 | 0.222976 | 2,211 | 65 | 89 | 34.015385 | 0.86787 | 0.352329 | 0 | 0.088235 | 0 | 0 | 0.026931 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.205882 | false | 0 | 0.088235 | 0.088235 | 0.558824 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
88114ea12bad47b47a1f5b4eccf6db2a5c8db812 | 144 | py | Python | chap13/list1303.py | ytianjin/GitTest | a657f46098728ad90f7140fadad356e8561c9a7a | [
"MIT"
] | null | null | null | chap13/list1303.py | ytianjin/GitTest | a657f46098728ad90f7140fadad356e8561c9a7a | [
"MIT"
] | null | null | null | chap13/list1303.py | ytianjin/GitTest | a657f46098728ad90f7140fadad356e8561c9a7a | [
"MIT"
] | null | null | null | # 向文件添加两行字符串
f = open('hello.txt', 'a') # 打开(文本+追加模式)
f.write('Fine, thanks.\n')
f.write('And you?\n')
f.close() # 关闭 | 18 | 41 | 0.486111 | 22 | 144 | 3.181818 | 0.772727 | 0.171429 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.284722 | 144 | 8 | 42 | 18 | 0.679612 | 0.173611 | 0 | 0 | 0 | 0 | 0.321101 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
8812e24719059de0a52cd076a8b021354b204dd2 | 1,101 | py | Python | backend/grafit/crawler/crawler.py | bopopescu/grafit | 2823fec3905d7c9cde48cd787224bcc3b7454c0f | [
"MIT"
] | 16 | 2018-10-12T16:33:52.000Z | 2020-06-23T20:11:34.000Z | backend/grafit/crawler/crawler.py | bopopescu/grafit | 2823fec3905d7c9cde48cd787224bcc3b7454c0f | [
"MIT"
] | 41 | 2018-10-14T21:28:38.000Z | 2021-06-10T22:01:45.000Z | backend/grafit/crawler/crawler.py | bopopescu/grafit | 2823fec3905d7c9cde48cd787224bcc3b7454c0f | [
"MIT"
] | 4 | 2018-10-28T10:47:26.000Z | 2020-07-20T04:17:04.000Z | from ..crawler.source import Source
import logging
import re
import html2text
logger = logging.getLogger()
logger.setLevel(logging.INFO)
class Crawler:
def __init__(self):
self.text_maker = html2text.HTML2Text()
self.text_maker.ignore_links = True
self.text_maker.skip_internal_links = True
self.text_maker.bypass_tables = True
self.text_maker.ignore_anchors = True
self.text_maker.ignore_emphasis = True
self.text_maker.ignore_tables = True
self.text_maker.single_line_break = True
self.text_maker.ignore_images = True
def getWebContent(self, articleText: str) -> str:
content = ""
sources = Crawler.__extractURL(articleText)
for source in sources:
content += source.getContent(self.text_maker)
return content
@staticmethod
def __extractURL(content: str) -> list:
urlRegex = r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
urls = re.findall(urlRegex, content)
return list({Source(url) for url in urls})
| 30.583333 | 100 | 0.647593 | 137 | 1,101 | 4.992701 | 0.416058 | 0.116959 | 0.190058 | 0.173977 | 0.241228 | 0 | 0 | 0 | 0 | 0 | 0 | 0.010551 | 0.22525 | 1,101 | 35 | 101 | 31.457143 | 0.791325 | 0 | 0 | 0 | 0 | 0.035714 | 0.070845 | 0.070845 | 0 | 0 | 0 | 0 | 0 | 1 | 0.107143 | false | 0.035714 | 0.142857 | 0 | 0.357143 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
71576f27d7a1758fc55dd1b8368e79c3a9d0114d | 1,191 | py | Python | groupflow_scripts/kill_running_test.py | alexcraig/GroupFlow | a772c46cc2df440179ca53c36dd739a1b38ff312 | [
"Apache-2.0"
] | 16 | 2015-06-19T21:10:06.000Z | 2021-03-23T00:08:36.000Z | groupflow_scripts/kill_running_test.py | alexcraig/GroupFlow | a772c46cc2df440179ca53c36dd739a1b38ff312 | [
"Apache-2.0"
] | null | null | null | groupflow_scripts/kill_running_test.py | alexcraig/GroupFlow | a772c46cc2df440179ca53c36dd739a1b38ff312 | [
"Apache-2.0"
] | 17 | 2015-06-18T19:28:22.000Z | 2022-01-04T13:59:26.000Z | #!/usr/bin/env python
import os
import sys
import signal
from subprocess import call
ps_out = os.popen('ps -e | grep python2.7')
for line in ps_out:
print line,
line_split = line.strip().split(' ')
try:
os.kill(int(line_split[0]), signal.SIGTERM)
except Exception as e:
print str(e.strerror)
ps_out = os.popen('ps -e | grep vlc')
for line in ps_out:
print line,
line_split = line.strip().split(' ')
try:
os.kill(int(line_split[0]), signal.SIGTERM)
except Exception as e:
print str(e.strerror)
ps_out = os.popen('ps -e | grep controller')
for line in ps_out:
print line,
line_split = line.strip().split(' ')
try:
os.kill(int(line_split[0]), signal.SIGTERM)
except Exception as e:
print str(e.strerror)
ps_out = os.popen('ps -e | grep python')
for line in ps_out:
line_split = line.strip().split(' ')
proc_id = int(line_split[0])
if proc_id != os.getpid() and proc_id != os.getppid():
print line,
try:
os.kill(proc_id, signal.SIGTERM)
except Exception as e:
print str(e.strerror)
call(['mn', '-c'])
call(['rm', '-rf', 'mcastlog_*']) | 25.891304 | 58 | 0.608732 | 184 | 1,191 | 3.826087 | 0.255435 | 0.056818 | 0.039773 | 0.068182 | 0.723011 | 0.670455 | 0.670455 | 0.643466 | 0.643466 | 0.643466 | 0 | 0.006674 | 0.245172 | 1,191 | 46 | 59 | 25.891304 | 0.776418 | 0.016793 | 0 | 0.675 | 0 | 0 | 0.087959 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.1 | null | null | 0.2 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
716328010c1f033b3f1131b65b133b1e3f1e5cb6 | 830 | py | Python | maps_hash/c2.py | henryto/ds | 514bd20c933cf05f8f6550add1fc3df28f3eac0b | [
"BSD-3-Clause"
] | null | null | null | maps_hash/c2.py | henryto/ds | 514bd20c933cf05f8f6550add1fc3df28f3eac0b | [
"BSD-3-Clause"
] | 1 | 2021-05-10T18:11:07.000Z | 2021-05-10T18:11:07.000Z | maps_hash/c2.py | henryto/ds | 514bd20c933cf05f8f6550add1fc3df28f3eac0b | [
"BSD-3-Clause"
] | null | null | null | def staircase(n):
num_dict = dict({})
return staircase_faster(n, num_dict)
def staircase_faster(n, num_dict):
if n == 1:
output = 1
elif n == 2:
output = 2
elif n == 3:
output = 4
else:
if (n - 1) in num_dict:
first_output = num_dict[n - 1]
else:
first_output = staircase_faster(n - 1, num_dict)
if (n - 2) in num_dict:
second_output = num_dict[n - 2]
else:
second_output = staircase_faster(n - 2, num_dict)
if (n - 3) in num_dict:
third_output = num_dict[n - 3]
else:
third_output = staircase_faster(n - 3, num_dict)
output = first_output + second_output + third_output
num_dict[n] = output;
return output
| 25.151515 | 61 | 0.519277 | 110 | 830 | 3.672727 | 0.172727 | 0.225248 | 0.19802 | 0.138614 | 0.207921 | 0 | 0 | 0 | 0 | 0 | 0 | 0.029528 | 0.387952 | 830 | 32 | 62 | 25.9375 | 0.765748 | 0 | 0 | 0.153846 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.076923 | false | 0 | 0 | 0 | 0.153846 | 0 | 0 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
718498fa4165e5e67e0b04ec8e9d941bf0407cfa | 1,929 | py | Python | acos_client/v21/admin.py | sana-ag/acos-client | 88707cc029551cfae0d4a32904b9c282d4dad0b4 | [
"Apache-2.0"
] | 33 | 2015-02-11T16:42:04.000Z | 2021-08-24T16:06:23.000Z | acos_client/v21/admin.py | sana-ag/acos-client | 88707cc029551cfae0d4a32904b9c282d4dad0b4 | [
"Apache-2.0"
] | 154 | 2015-01-12T18:46:28.000Z | 2022-01-22T13:59:48.000Z | acos_client/v21/admin.py | sana-ag/acos-client | 88707cc029551cfae0d4a32904b9c282d4dad0b4 | [
"Apache-2.0"
] | 68 | 2015-01-12T22:29:57.000Z | 2021-07-13T07:21:05.000Z | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import absolute_import
from __future__ import unicode_literals
from acos_client.v21 import base
class Admin(base.BaseV21):
@property
def administrator(self):
return self.Administrator(self.client)
class Administrator(base.BaseV21):
def all(self, **kwargs):
return self._get('system.admin.administrator.getAll', **kwargs)
def get(self, name, **kwargs):
params = {"admin_name": name}
return self._post('system.admin.administrator.search', params, **kwargs)
def create(self, name, **kwargs):
params = {
"administrator": {
"admin_name": name
}
}
return self._post('system.admin.administrator.create', params, **kwargs)
def update(self, name, **kwargs):
params = {
"administrator": {
"admin_name": name
}
}
return self._post('system.admin.administrator.update', params, **kwargs)
def delete(self, name, **kwargs):
params = {"admin_name": name}
return self._post('system.admin.administrator.delete', params, **kwargs)
def all_delete(self, **kwargs):
return self._post('system.admin.administrator.deleteAll', **kwargs)
| 33.842105 | 84 | 0.617937 | 218 | 1,929 | 5.366972 | 0.412844 | 0.059829 | 0.123077 | 0.08547 | 0.297436 | 0.297436 | 0.264957 | 0.264957 | 0.264957 | 0.264957 | 0 | 0.007205 | 0.280456 | 1,929 | 56 | 85 | 34.446429 | 0.835735 | 0.283048 | 0 | 0.25 | 0 | 0 | 0.195175 | 0.14693 | 0 | 0 | 0 | 0 | 0 | 1 | 0.21875 | false | 0 | 0.09375 | 0.09375 | 0.59375 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
7198ef1260fdf6531e3587a683bc311a6ad1c14f | 433 | py | Python | 005.py | xianlinfeng/project_euler_python3 | 77eca44eb2b1d13bc70d6dc0258b737449d43a23 | [
"MIT"
] | null | null | null | 005.py | xianlinfeng/project_euler_python3 | 77eca44eb2b1d13bc70d6dc0258b737449d43a23 | [
"MIT"
] | null | null | null | 005.py | xianlinfeng/project_euler_python3 | 77eca44eb2b1d13bc70d6dc0258b737449d43a23 | [
"MIT"
] | null | null | null |
if __name__ == "__main__":
primes = [2, 3, 5, 7, 11, 13, 17, 19]
s = 1
m = 1
for i in range(1, 21):
if i in primes:
s *= i
m *= i
elif m % i == 0:
pass
elif m % i != 0:
j = m
while True:
j += s
if j % i == 0:
m = j
s = j
break
print(m)
| 20.619048 | 41 | 0.277136 | 56 | 433 | 2 | 0.5 | 0.053571 | 0.107143 | 0.125 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.120482 | 0.616628 | 433 | 20 | 42 | 21.65 | 0.554217 | 0 | 0 | 0 | 0 | 0 | 0.018519 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.052632 | 0 | 0 | 0 | 0.052632 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 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 | 2 |
71b9d640bcc81f3db453e316eed22abc3e0860e1 | 157 | py | Python | 3.py | luigitabarca/appp | a3c8417cf7deb7f5c413ee879e6192007741a570 | [
"MIT"
] | null | null | null | 3.py | luigitabarca/appp | a3c8417cf7deb7f5c413ee879e6192007741a570 | [
"MIT"
] | null | null | null | 3.py | luigitabarca/appp | a3c8417cf7deb7f5c413ee879e6192007741a570 | [
"MIT"
] | null | null | null |
from requests_html import HTMLSession
session = HTMLSession()
my_url = 'https://coinbit.co.kr/'
r = session.get(my_url)
p=r.html.render()
print(p) | 17.444444 | 38 | 0.694268 | 24 | 157 | 4.416667 | 0.708333 | 0.09434 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.159236 | 157 | 9 | 39 | 17.444444 | 0.80303 | 0 | 0 | 0 | 0 | 0 | 0.147651 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.166667 | 0 | 0.166667 | 0.166667 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
71daed41f5f1a9e888f3a0b8337dc776c8227206 | 2,412 | py | Python | service/emails.py | YossyMejia/api-hacienda_python | 82c83fbf7673c37005ded12f1787b5d65247c4aa | [
"MIT"
] | null | null | null | service/emails.py | YossyMejia/api-hacienda_python | 82c83fbf7673c37005ded12f1787b5d65247c4aa | [
"MIT"
] | null | null | null | service/emails.py | YossyMejia/api-hacienda_python | 82c83fbf7673c37005ded12f1787b5d65247c4aa | [
"MIT"
] | null | null | null | import base64
from infrastructure import company_smtp
from infrastructure import documents
from configuration import globalsettings
from infrastructure.email import send_email
from service import fe_enums
cfg = globalsettings.cfg
def sent_email_fe(data):
smtp_data = company_smtp.get_company_smtp(data['company_user'])
if smtp_data.get('host'):
host = smtp_data[0]['host']
sender = smtp_data[0]['user']
password = smtp_data[0]['password']
port = smtp_data[0]['port']
encrypt_type = smtp_data[0]['encrypt_type']
else:
host = cfg['email']['host']
sender = cfg['email']['user']
password = cfg['email']['password']
port = cfg['email']['port']
encrypt_type = cfg['email']['type']
document = documents.get_document(data['key_mh'])[0]
receivers = document['email']
subject = "Envio de "+fe_enums.tagNamePDF[document['document_type']] + ' Numero: ' + document['key_mh']
body = 'Adjuntamos los datos de la ' + fe_enums.tagNamePDF[document['document_type']]
name_file1 = fe_enums.tagNamePDF[document['document_type']] + '_' + document['key_mh']+'.pdf'
name_file2 = document['document_type'] + "_" + document['key_mh']+'.xml'
name_file3 = "AHC_" + document['key_mh']+'.xml'
file1 = base64.b64decode(document['pdfdocument'])
file2 = base64.b64decode(document['signxml'])
file3 = base64.b64decode(document['answerxml'])
result = send_email(receivers, subject, body, file1, file2, file3, host, sender, password, port,
encrypt_type, name_file1, name_file2, name_file3)
return result
def send_custom_email(data, file1, file2):
smtp_data = company_smtp.get_company_smtp(data['company_id'])
receivers = data['receivers']
subject = data['subject']
body = data['body']
name_file1 = file1.filename
name_file2 = file2.filename
file1 = file1.stream.read()
file2 = file2.stream.read()
host = smtp_data[0]['host']
sender = smtp_data[0]['user']
password = smtp_data[0]['password']
port = smtp_data[0]['port']
encrypt_type = smtp_data[0]['encrypt_type']
# todo: lista de receptores pasar a receptor (enviar email a varios usuarios)
result = send_email(receivers, subject, body, file1, file2,host, sender, password, port,
encrypt_type,name_file1, name_file2)
return result
| 35.470588 | 107 | 0.666667 | 301 | 2,412 | 5.13289 | 0.232558 | 0.07767 | 0.058252 | 0.048544 | 0.423948 | 0.423948 | 0.32233 | 0.32233 | 0.264078 | 0.20712 | 0 | 0.026302 | 0.196103 | 2,412 | 67 | 108 | 36 | 0.7705 | 0.031095 | 0 | 0.235294 | 0 | 0 | 0.143959 | 0 | 0 | 0 | 0 | 0.014925 | 0 | 1 | 0.039216 | false | 0.098039 | 0.117647 | 0 | 0.196078 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 2 |
71e52936da7a1425200d820167fda9a59ecbebfb | 1,467 | py | Python | tests/test_cycles.py | hpi-dhc/pypg | cf6fa7a3b248ae9d68821b47943490082348f531 | [
"MIT"
] | 3 | 2020-11-06T09:17:33.000Z | 2022-02-04T08:39:28.000Z | tests/test_cycles.py | hpi-dhc/pypg | cf6fa7a3b248ae9d68821b47943490082348f531 | [
"MIT"
] | null | null | null | tests/test_cycles.py | hpi-dhc/pypg | cf6fa7a3b248ae9d68821b47943490082348f531 | [
"MIT"
] | null | null | null | """
====================================
Tests the Filters Module
====================================
"""
import unittest
import numpy as np
import pandas as pd
from pypg.cycles import find_onset
class TestFilters(unittest.TestCase):
"""
Unit tests for the cycles module.
"""
def setUp(self):
self.ppg = [2438.0, 2438.0, 2438.0, 2455.0, 2455.0, 2384.0, 2384.0, 2384.0, 2418.0,
2418.0, 2415.0, 2415.0, 2415.0, 2398.0, 2398.0, 2388.0, 2388.0, 2388.0,
2340.0, 2340.0, 2340.0, 2340.0, 2340.0, 2399.0, 2399.0, 2353.0, 2353.0,
2353.0, 2318.0, 2318.0, 2324.0, 2324.0, 2324.0, 2283.0, 2283.0, 2333.0,
2333.0, 2333.0, 2326.0, 2326.0, 2274.0, 2274.0, 2274.0, 2309.0, 2309.0,
2224.0, 2224.0, 2224.0, 2288.0, 2288.0, 2268.0, 2268.0, 2268.0, 2250.0]
self.int_data = int(2438)
self.pandas_data = pd.Series(self.ppg)
self.numpy_data = np.array(self.ppg)
def test_find_onset(self):
"""
Tests if the returned data type is correct.
"""
result_pandas = find_onset(self.pandas_data, 1000)
result_numpy = find_onset(self.numpy_data, 1000)
self.assertIsInstance(result_pandas, np.ndarray)
self.assertIsInstance(result_numpy, np.ndarray)
with self.assertRaises(Exception):
find_onset(self.int_data, 1000)
if __name__ == '__main__':
unittest.main()
| 32.6 | 91 | 0.564417 | 218 | 1,467 | 3.688073 | 0.302752 | 0.05597 | 0.037313 | 0.049751 | 0.210199 | 0.032338 | 0.032338 | 0.032338 | 0.032338 | 0 | 0 | 0.261426 | 0.25426 | 1,467 | 44 | 92 | 33.340909 | 0.473492 | 0.119973 | 0 | 0 | 0 | 0 | 0.006426 | 0 | 0 | 0 | 0 | 0 | 0.125 | 1 | 0.083333 | false | 0 | 0.166667 | 0 | 0.291667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
e07aac44e0754445c247695df4f69dc2631739e8 | 2,889 | py | Python | everpay/token.py | everFinance/everpay.py | fbf8551f3fc37089ff25c1b1350ca1b1f03031bb | [
"MIT"
] | 4 | 2022-02-09T03:59:27.000Z | 2022-02-09T15:48:27.000Z | everpay/token.py | everFinance/everpay.py | fbf8551f3fc37089ff25c1b1350ca1b1f03031bb | [
"MIT"
] | null | null | null | everpay/token.py | everFinance/everpay.py | fbf8551f3fc37089ff25c1b1350ca1b1f03031bb | [
"MIT"
] | null | null | null | TOKEN_LIST = [
#kovan
['ethereum', '42', 'eth', '0x0000000000000000000000000000000000000000', 18],
['ethereum', '42', 'usdt', '0xd85476c906b5301e8e9eb58d174a6f96b9dfc5ee', 6],
['ethereum', '42', 'usdc', '0xb7a4f3e9097c08da09517b5ab877f7a917224ede', 6],
['ethereum', '42', 'dai', '0xc4375b7de8af5a38a93548eb8453a498222c4ff2', 18],
['arweave', '99', 'pia', 'n05LTiuWcAYjizXAu-ghegaWjL89anZ6VdvuHcU6dno', 18],
['arweave', '99', 'vrt', 'usjm4PCxUd5mtaon7zc97-dt-3qf67yPyqgzLnLqk5A', 18],
['arweave', '99', 'xyz', 'mzvUgNc8YFk0w5K5H7c8pyT-FC5Y_ba0r7_8766Kx74', 18],
['arweave', '99', 'ardrive', '-8A6RexFkpfWwuyVO98wzSFZh0d6VJuI-buTJvlwOJQ', 18],
['arweave,ethereum', '0,42', 'ar', 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA,0xcc9141efa8c20c7df0778748255b1487957811be', 12],
['moonbase', '1287', 'dev', '0x0000000000000000000000000000000000000000', 18],
['moonbase', '1287', 'zlk', '0x322f069e9b8b554f3fb43cefcb0c7b3222242f0e', 18],
#mainnet
['ethereum', '1', 'eth', '0x0000000000000000000000000000000000000000', 18],
['ethereum', '1', 'usdt', '0xdac17f958d2ee523a2206206994597c13d831ec7', 6],
['ethereum', '1', 'wbtc', '0x2260fac5e5542a773aa44fbcfedf7c193bc2c599', 8],
['ethereum', '1', 'usdc', '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', 6],
['ethereum', '1', 'dai', '0x6b175474e89094c44da98b954eedeac495271d0f', 18],
['ethereum', '1', 'uni', '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984', 18],
['ethereum', '1', 'sos', '0x3b484b82567a09e2588a13d54d032153f0c0aee0', 18],
['ethereum', '1', 'bank', '0x2d94aa3e47d9d5024503ca8491fce9a2fb4da198', 18],
['ethereum', '1', 'dodo', '0x43dfc4159d86f3a37a5a4b3d4580b888ad7d4ddd', 18],
['ethereum', '1', 'mask', '0x69af81e73a73b40adf4f3d4223cd9b1ece623074', 18],
['moonbeam', '1284', 'zlk', '0x3fd9b6c9a24e09f67b7b706d72864aebb439100c', 18],
['moonbeam', '1284', 'glmr', '0x0000000000000000000000000000000000000000', 18],
['arweave,ethereum', '0,1', 'ar', 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA,0x4fadc7a98f2dc96510e42dd1a74141eeae0c1543', 12],
['arweave', '0', 'ardrive', '-8A6RexFkpfWwuyVO98wzSFZh0d6VJuI-buTJvlwOJQ', 18],
['arweave', '0', 'vrt', 'usjm4PCxUd5mtaon7zc97-dt-3qf67yPyqgzLnLqk5A', 18],
]
def get_token_id(chain_type, chain_id, token_symbol):
for token in TOKEN_LIST:
if token[0] == chain_type and token[1] == chain_id and token[2] == token_symbol:
return token[3]
def get_token_decimal(chain_type, chain_id, token_symbol):
for token in TOKEN_LIST:
if token[0] == chain_type and token[1] == chain_id and token[2] == token_symbol:
return token[4]
def get_token_tag(chain_type, chain_id, token_symbol, token_id=''):
if not token_id:
token_id = get_token_id(chain_type, chain_id, token_symbol)
return '-'.join([chain_type, token_symbol, token_id]) | 60.1875 | 133 | 0.702319 | 251 | 2,889 | 7.936255 | 0.330677 | 0.045181 | 0.033133 | 0.032129 | 0.251004 | 0.14759 | 0.134036 | 0.134036 | 0.134036 | 0.110442 | 0 | 0.29278 | 0.132226 | 2,889 | 48 | 134 | 60.1875 | 0.501795 | 0.004154 | 0 | 0.1 | 0 | 0 | 0.538595 | 0.412378 | 0 | 0 | 0.292072 | 0 | 0 | 1 | 0.075 | false | 0 | 0 | 0 | 0.15 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 |
e085ef9e1ef8f8aff5d9f60037fc39a1732633cc | 1,957 | py | Python | lib/common/obfuscation.py | terrorizer1980/Empire | 9259e5106986847d2bb770c4289c0c0f1adf2344 | [
"BSD-3-Clause"
] | 49 | 2015-09-02T15:20:09.000Z | 2022-03-05T18:18:23.000Z | lib/common/obfuscation.py | rmusser01/Empire | c1bdbd0fdafd5bf34760d5b158dfd0db2bb19556 | [
"BSD-3-Clause"
] | 1 | 2020-11-04T08:15:12.000Z | 2020-11-04T08:15:12.000Z | lib/common/obfuscation.py | InfinitelyFreedom/Empire | 3a922f60d92658fb716efb3be5a1c15074114766 | [
"BSD-3-Clause"
] | 24 | 2015-09-08T11:45:23.000Z | 2022-02-07T23:53:58.000Z | """ Contains methods to encrypt, obfuscate, minify, etc. source code, either
Python or Powershell, for use in agents, stagers, etc.
In essence: you should be able to put Python or Powershell code strings into
any function in this file, and get back a string which has the same
functionality but different meta-characteristics (no comments, shorter length,
better evasion, etc.)
"""
from builtins import object
from pyminifier import minification as py_minifier
from pyminifier import token_utils as py_tokenizer
################################################################################
#
# Python Encryption/Obfuscation/Minification/Etc.
#
################################################################################
class PyminifierOptions(object):
"""
Irritating options "struct" needed for pyminifier.
See: https://liftoff.github.io/pyminifier/_modules/pyminifier/minification.html#minify
"""
tabs = False
def py_minify(code):
"""
minifies a string (of python code) passed
see: https://liftoff.github.io/pyminifier/_modules/pyminifier/minification.html#minify
"""
tokenized = py_tokenizer.listified_tokenizer(code)
options = PyminifierOptions()
minified = py_minifier.minify(tokenized, options)
return minified
# TODO py_obfuscate fails with the following:
# File "/usr/lib/python2.7/site-packages/pyminifier/obfuscate.py", line 92, in apply_obfuscation
# tokens, obfuscate_variable, variable, name_generator)
# TypeError: replace_obfuscatables() takes at least 5 arguments (4 given)
# def py_obfuscate(code):
# py_obfuscator.name_generator = py_obfuscator.obfuscation_machine(identifier_length=1)
# return py_obfuscator.apply_obfuscation(code)
################################################################################
#
# Powershell Encryption/Obfuscation/Minification/Etc.
#
################################################################################
| 35.581818 | 98 | 0.638733 | 207 | 1,957 | 5.932367 | 0.570048 | 0.029316 | 0.029316 | 0.058632 | 0.117264 | 0.117264 | 0.117264 | 0.117264 | 0.117264 | 0.117264 | 0 | 0.004094 | 0.126214 | 1,957 | 54 | 99 | 36.240741 | 0.714035 | 0.60092 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.018519 | 0 | 1 | 0.1 | false | 0 | 0.3 | 0 | 0.7 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.