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
fe07b0d65355435bfe80638b0233d70fcb2d730a
6,277
py
Python
sandia_hand/ros/sandia_hand_teleop/simple_grasp/simple_grasp.py
adarshrs/Drone-Simulator-for-ROS-Kinetic
a44eef1bcaacc55539325bba663f0c8abfd7c75b
[ "MIT" ]
null
null
null
sandia_hand/ros/sandia_hand_teleop/simple_grasp/simple_grasp.py
adarshrs/Drone-Simulator-for-ROS-Kinetic
a44eef1bcaacc55539325bba663f0c8abfd7c75b
[ "MIT" ]
null
null
null
sandia_hand/ros/sandia_hand_teleop/simple_grasp/simple_grasp.py
adarshrs/Drone-Simulator-for-ROS-Kinetic
a44eef1bcaacc55539325bba663f0c8abfd7c75b
[ "MIT" ]
null
null
null
#!/usr/bin/env python # # Software License Agreement (Apache License) # # Copyright 2013 Open Source Robotics Foundation # Author: Morgan Quigley # # 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 roslib; roslib.load_manifest('sandia_hand_teleop') import rospy import sys from sandia_hand_msgs.srv import SimpleGraspSrv, SimpleGraspSrvResponse, SimpleGraspWithSlew, SimpleGraspWithSlewResponse from sandia_hand_msgs.msg import SimpleGrasp from osrf_msgs.msg import JointCommands g_jc_pub = None g_jc = JointCommands() g_prev_jc_target = JointCommands() def grasp_srv(req): grasp_cb(req.grasp) return SimpleGraspSrvResponse() def grasp_slew_srv(req): #print "going to %s in %.3f" % (req.grasp.name, req.slew_duration) rate = rospy.Rate(100.0) t_start = rospy.Time.now() t_end = t_start + rospy.Duration(req.slew_duration) while rospy.Time.now() < t_end: dt = (rospy.Time.now() - t_start).to_sec() dt_norm = dt / req.slew_duration #print "%.3f" % dt_norm grasp_spline(req.grasp.name, req.grasp.closed_amount, dt_norm) rate.sleep() grasp_spline(req.grasp.name, req.grasp.closed_amount, 1.0) return SimpleGraspWithSlewResponse() def grasp_spline(grasp_name, closed_amount, spline_amount): global g_jc_pub, g_jc, g_prev_jc_target #print "request: grasp [%s] amount [%f]" % (grasp_name, closed_amount) # save some typing gn = grasp_name x = closed_amount if x < 0: x = 0 elif x > 1: x = 1 origin = [0] * 12 g0 = [0] * 12 if (gn == "cylindrical"): g0 = [0,1.5,1.7, 0,1.5,1.7, 0,1.5,1.7, 0.2,.8,1.2] elif (gn == "spherical"): origin = [-0.7,0,0, 0.1,0,0, 0.7,0,0, 0,0,0] g0 = [0,1.4,1.4, 0,1.4,1.4, 0,1.4,1.4, 0,0.7,0.7] elif (gn == "prismatic"): origin = [0,1.4,0, 0,1.4,0, 0,1.4,0, -0.1,0.8,-0.8] g0 = [0,0,1.4, 0,0,1.4, 0,0,1.4, 0,0,1.4] elif (gn == "finger_0_test"): g0 = [0,1.5,1.7, 0,0,0, 0,0,0, 0,0,0] elif (gn == "number_one"): origin = [0,0,0, 0,1.5,1.5, 0,1.5,1.5, 0.4,0.8,1 ] elif (gn == "peace"): origin = [-0.2,0,0, 0.05,0,0, 0,1.5,1.5, 0.4,0.8,1 ] elif (gn == "asl_a"): origin = [0,1.5,1.5, 0,1.5,1.5, 0,1.5,1.5, 1.5,0.9,0.2 ] elif (gn == "asl_b"): origin = [0.1,0,0, 0,0,0, -0.1,0,0, 1,0.8,0.9 ] elif (gn == "asl_c"): origin = [0,0.7,0.9, 0,0.7,0.9, 0,0.7,0.9, 0,0.4,0.4 ] elif (gn == "asl_d"): origin = [0,0,0, 0,1.5,1.5, 0,1.5,1.5, 0.4,0.8,1 ] elif (gn == "asl_e"): origin = [0,1,1.8, 0,1,1.8, 0,1,1.8, 1.5,0.6,1] elif (gn == "asl_f"): origin = [0,1.3,1.2, 0.1,0,0, 0.2,0,0, 0.3,0.7,0.7 ] elif (gn == "asl_g"): origin = [0,1.5,0, 0,1.5,1.5, 0,1.5,1.5, 0,1,-.4 ] elif (gn == "asl_h"): origin = [0.1,1.5,0, 0,1.5,0, 0,1.5,1.5, 0,1,0.6 ] elif (gn == "asl_i"): origin = [0,1.5,1.5, 0,1.5,1.5, 0,0,0, 1.5,1.0,0.3 ] elif (gn == "asl_j"): origin = [0,1.5,1.5, 0,1.5,1.5, 0,0,0, 1.5,1.0,0.3 ] g0 = [0,0,0, 0,0,0, 0,0,0, 0.5,1,1] g1 = [0,0,0, 0,0,0, 0,0,0, 0,1,1] elif (gn == "asl_k"): origin = [0,0,0, 0,1.5,0, 0,1.5,1.5, 1.5,1.0,0.3] elif (gn == "asl_l"): origin = [0,0,0, 0,1.5,1.5, 0,1.5,1.5, 1.5,0,0] elif (gn == "asl_m"): origin = [0,1,1.5, 0,1,1.5, 0,1,1.5, 0,1,1] elif (gn == "asl_n"): origin = [0,1,1.5, 0,1,1.5, 0,1.5,1.5, 0,1,1] elif (gn == "asl_o"): origin = [0.1,1.3,1.2, 0,1.3,1.2, -0.1,1.3,1.2, 0.2,0.8,0.5] elif (gn == "asl_p"): origin = [0,0,0, 0,1.5,0, 0,1.5,1.5, 1.5,1,0.3] elif (gn == "asl_q"): origin = [0,1.3,1.2, 0,1.5,1.5, 0,1.5,1.5, 0.4,0.8,0.5] elif (gn == "asl_r"): origin = [0.1,0,0, -0.1,0,0, 0,1.5,1.5, 0,1,1] elif (gn == "asl_s"): origin = [0,1.5,1.5, 0,1.5,1.5, 0,1.5,1.5, 0,1,0.2] elif (gn == "asl_t"): origin = [-.4,1.3,1.5, 0,1.5,1.5, 0,1.5,1.5, 0.4,1,1] elif (gn == "asl_u"): origin = [0,0,0, 0,0,0, 0,1.5,1.5, 0,1,1] elif (gn == "asl_v"): origin = [-0.3,0,0, 0.1,0,0, 0,1.5,1.5, 0,1,1] elif (gn == "asl_w"): origin = [-0.3,0,0, 0,0,0, 0.3,0,0, 0,1,1] elif (gn == "asl_x"): origin = [0,0,1.5, 0,1.5,1.5, 0,1.5,1.5, 0,1,1] elif (gn == "asl_y"): origin = [0,1.5,1.5, 0,1.5,1.5, 0.3,0,0, 1.5,0,0] elif (gn == "asl_z"): origin = [0,1.0,0, 0,1.5,1.5, 0,1.5,1.5, 0.4,0.8,0.8] g0 = [0.3,0.3,0, 0,0,0, 0,0,0, 0,0,0] g1 = [-0.3,0.3,0, 0,0,0, 0,0,0, 0,0,0] else: return None # bogus g_jc.position = [0] * 12 if (spline_amount < 0): spline_amount = 0 elif (spline_amount > 1): spline_amount = 1 for i in xrange(0, 12): target = origin[i] + g0[i] * x prev_target = g_prev_jc_target.position[i] #g_jc.position[i] = origin[i] + g0[i] * x #delta = target - g_prev_jc_target.position[i] # compute convex combination between old and new targets g_jc.position[i] = ( spline_amount) * target + \ (1.0 - spline_amount) * prev_target #print "joint state: %s" % (str(g_jc.position)) g_jc_pub.publish(g_jc) if (spline_amount == 1.0): for i in xrange(0, 12): g_prev_jc_target.position[i] = g_jc.position[i] # todo: make this better def grasp_cb(msg): grasp_spline(msg.name, msg.closed_amount, 1) if __name__ == '__main__': rospy.init_node('simple_grasp') g_jc.name = ["f0_j0", "f0_j1", "f0_j2", "f1_j0", "f1_j1", "f1_j2", "f2_j0", "f2_j1", "f2_j2", "f3_j0", "f3_j1", "f3_j2"] g_jc.position = [0] * 12 g_prev_jc_target.position = [0] * 12 g_jc_pub = rospy.Publisher('joint_commands', JointCommands, queue_size=1) # same namespace g_jc_srv = rospy.Service('simple_grasp', SimpleGraspSrv, grasp_srv) g_sgws_srv = rospy.Service('simple_grasp_with_slew', SimpleGraspWithSlew, grasp_slew_srv) g_jc_sub = rospy.Subscriber('simple_grasp', SimpleGrasp, grasp_cb) print "simple grasp service is now running." rospy.spin()
37.142012
121
0.58563
1,354
6,277
2.602659
0.162482
0.074915
0.067253
0.057889
0.382804
0.323496
0.294268
0.248297
0.224177
0.191544
0
0.147444
0.196113
6,277
168
122
37.363095
0.550931
0.168552
0
0.059259
0
0
0.07341
0.004239
0
0
0
0.005952
0
0
null
null
0
0.044444
null
null
0.007407
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
0
0
1
fe07d62ba16713663bde826dc0ce1fe3d2c478fc
1,680
py
Python
ui/ui_prestamo_libros.py
edzzn/Manejo_Liberia
c735d35b32fc53839acfc48d4e088e69983edf16
[ "MIT" ]
null
null
null
ui/ui_prestamo_libros.py
edzzn/Manejo_Liberia
c735d35b32fc53839acfc48d4e088e69983edf16
[ "MIT" ]
null
null
null
ui/ui_prestamo_libros.py
edzzn/Manejo_Liberia
c735d35b32fc53839acfc48d4e088e69983edf16
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'PrestamoDeLibros.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(400, 300) self.pushButton = QtGui.QPushButton(Form) self.pushButton.setGeometry(QtCore.QRect(140, 70, 121, 41)) self.pushButton.setObjectName(_fromUtf8("pushButton")) self.pushButton_2 = QtGui.QPushButton(Form) self.pushButton_2.setGeometry(QtCore.QRect(140, 160, 121, 41)) self.pushButton_2.setObjectName(_fromUtf8("pushButton_2")) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): Form.setWindowTitle(_translate("Form", "Form", None)) self.pushButton.setText(_translate("Form", "Solicitar", None)) self.pushButton_2.setText(_translate("Form", "Reservar", None)) if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) Form = QtGui.QWidget() ui = Ui_Form() ui.setupUi(Form) Form.show() sys.exit(app.exec_())
31.111111
79
0.689881
195
1,680
5.8
0.415385
0.099027
0.070734
0.099027
0.205128
0.145004
0.145004
0.145004
0.145004
0.145004
0
0.033898
0.192262
1,680
53
80
31.698113
0.799558
0.113095
0
0.162162
1
0
0.045209
0
0
0
0
0
0
1
0.135135
false
0
0.054054
0.081081
0.297297
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
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
fe0ae5c8386d6c3d6f937a81ff9888fef7e3e87d
215
py
Python
hwtest/automated/usb3_test.py
crvallance/wlanpi-hwtest
8858ef6e8fa78767238b968b121b4d5ab2155701
[ "MIT" ]
null
null
null
hwtest/automated/usb3_test.py
crvallance/wlanpi-hwtest
8858ef6e8fa78767238b968b121b4d5ab2155701
[ "MIT" ]
null
null
null
hwtest/automated/usb3_test.py
crvallance/wlanpi-hwtest
8858ef6e8fa78767238b968b121b4d5ab2155701
[ "MIT" ]
null
null
null
from hwtest.shell_utils import run_command def test_linux_usb3hub(): """ Test for Linux Foundation 3.0 root hub in `lsusb` output """ resp = run_command(["lsusb"]) assert "1d6b:0003" in resp
17.916667
60
0.665116
31
215
4.451613
0.774194
0.144928
0
0
0
0
0
0
0
0
0
0.054217
0.227907
215
11
61
19.545455
0.777108
0.260465
0
0
0
0
0.097902
0
0
0
0
0
0.25
1
0.25
false
0
0.25
0
0.5
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
1
fe0ede7a40a877fbc5bae0945b61462c0561098f
5,249
py
Python
experiments/cifar10_recon.py
coopersigrist/RecurrentNeuralSystem-
bd5bb680ec7f2166547709195f7bb3cd52cca5e8
[ "MIT" ]
3
2021-03-03T20:08:34.000Z
2021-03-19T15:27:58.000Z
experiments/cifar10_recon.py
coopersigrist/RecurrentNeuralSystem-
bd5bb680ec7f2166547709195f7bb3cd52cca5e8
[ "MIT" ]
null
null
null
experiments/cifar10_recon.py
coopersigrist/RecurrentNeuralSystem-
bd5bb680ec7f2166547709195f7bb3cd52cca5e8
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ReNS experiments - CIFAR10 Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1byZ4xTfCK2x1Rhkxpl-Vv4sqA-bo4bis # SETUP """ #@title Insatlling Pyorch # !pip install torch # !pip install torchvision #@title Import Dependencies import numpy as np import torch import torch.nn as nn import torchvision.datasets as dsets import torchvision.transforms as transforms from torch.autograd import Variable from tqdm import tqdm from typing import Optional, Union, Tuple, List, Sequence, Iterable import math from scipy.spatial.distance import euclidean from torch.nn.modules.utils import _pair from torchvision import models from sklearn.metrics import jaccard_score import matplotlib.pyplot as plt from models.models import RegularAutoEncoder, ModulatedAutoEncoder, PseudoRecAutoEncoder """# TRAINING""" batch_size = 32 num_epochs = 5 transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) # Load MNIST data. train_data = dsets.CIFAR10(root = './data', train = True, transform = transform, download = True) test_data = dsets.CIFAR10(root = './data', train = False, transform = transform) train_gen = torch.utils.data.DataLoader(dataset = train_data, batch_size = batch_size, shuffle = True) test_gen = torch.utils.data.DataLoader(dataset = test_data, batch_size = batch_size, shuffle = False) reflexor_size = 500 image_size = 32 channels = 3 # net = recurrentLayer(784, 784, 10, 5, 10, 0) net1 = RegularAutoEncoder(channels * image_size ** 2, channels * image_size ** 2, reflexor_size) net2 = ModulatedAutoEncoder(channels * image_size ** 2, channels * image_size ** 2, reflexor_size) net3 = PseudoRecAutoEncoder(channels * image_size ** 2, channels * image_size ** 2, reflexor_size) lr = .0001 # size of step loss_function = nn.MSELoss() # Unnormalize the image to display it def img_fix(img): return np.transpose((img / 2 + 0.5).numpy(), (1, 2, 0)) # Commented out IPython magic to ensure Python compatibility. train_losses = [[],[],[]] test_losses = [[],[],[]] real_imgs = [[],[],[]] reconstructed_imgs = [[],[],[]] param_counts = np.ones(3) steps = [[],[],[]] for num, net in enumerate([net1, net2, net3]): optimizer = torch.optim.Adam( net.parameters(), lr=lr) param_counts[num] = (sum(p.numel() for p in net.parameters() if p.requires_grad)) for epoch in range(num_epochs): for i ,(images,labels) in enumerate(train_gen): #images = Variable(images.view(-1,28*28)) labels = Variable(images.view(-1,3 * image_size ** 2)) optimizer.zero_grad() outputs = net(images) loss = loss_function(outputs, labels) loss.backward() optimizer.step() if (i+1) % 300 == 0: temp_loss = loss.item() print('Epoch [%d/%d], Step [%d/%d], Loss: %.4f' %(epoch+1, num_epochs, i+1, len(train_data)//batch_size, temp_loss)) dupe = Variable(outputs[0].data, requires_grad=False) # plt.imshow(img_fix(images[0])) # plt.show() # plt.imshow(img_fix(dupe.view(3, image_size, image_size))) # plt.show() train_losses[num].append(temp_loss) steps[num].append((50000 * epoch) + ((i + 1) * batch_size)) real_imgs[num].append(img_fix(images[0])) reconstructed_imgs[num].append(img_fix(dupe.view(3, image_size, image_size))) # Test Data score = 0 total = 0 for images,labels in test_gen: #images = Variable(images.view(-1,784)) output = net(images) score += loss_function(output, images.view(-1, 3 * image_size ** 2)).item() test_losses[num].append((score)) plt.plot(steps[0], train_losses[0], label= "Baseline") plt.plot(steps[1], train_losses[1], label= "Modulated") plt.plot(steps[2], train_losses[2], label= "Recurrent with Modulation") plt.xlabel('Iteration') plt.ylabel('Loss') plt.title('Training loss history') plt.legend() plt.show() plt.plot(steps[0], test_losses[0], label= "Baseline") plt.plot(steps[1], test_losses[1], label= "Modulated") plt.plot(steps[2], test_losses[2], label= "Recurrent with Modulation") plt.xlabel('Iteration') plt.ylabel('Loss') plt.title('Testing loss history') plt.legend() plt.show() for num,count in enumerate(param_counts): param_counts[num] /= 1000 plt.bar(["Base", "Modulated", "ReNS"], param_counts) plt.xlabel('Model') plt.ylabel('# of thousands of Parameters') plt.show() from mpl_toolkits.axes_grid1 import ImageGrid num_smaples = len(real_imgs[0]) for num in [0,1,2]: fig = plt.figure(figsize=(20.,20.)) grid = ImageGrid(fig, 111, # similar to subplot(111) nrows_ncols=(2, num_smaples), # creates 2x2 grid of axes axes_pad=0.1, # pad between axes in inch. ) for ax, im in zip(grid, real_imgs[num]+reconstructed_imgs[num]): # Iterating over the grid returns the Axes. ax.imshow(im) ax.axis("off") plt.show()
29.994286
98
0.649076
704
5,249
4.725852
0.322443
0.035167
0.024046
0.032462
0.262699
0.253081
0.164713
0.151488
0.111211
0.091374
0
0.034099
0.212231
5,249
174
99
30.166667
0.770496
0.150124
0
0.113208
1
0
0.057718
0
0
0
0
0
0
1
0.009434
false
0
0.150943
0.009434
0.169811
0.009434
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
0
0
1
fe13f782ba0630659072cb056a27d408b76a7090
1,973
py
Python
{{cookiecutter.repo_name}}/setup.py
ocesaulo/cookiecutter-ocn_sci
d41e826f56ba67cfde878ffc8188d497214a5f5b
[ "MIT" ]
null
null
null
{{cookiecutter.repo_name}}/setup.py
ocesaulo/cookiecutter-ocn_sci
d41e826f56ba67cfde878ffc8188d497214a5f5b
[ "MIT" ]
null
null
null
{{cookiecutter.repo_name}}/setup.py
ocesaulo/cookiecutter-ocn_sci
d41e826f56ba67cfde878ffc8188d497214a5f5b
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """The setup script.""" from setuptools import setup, find_packages with open('README.rst') as readme_file: readme = readme_file.read() {%- set license_classifiers = { 'MIT license': 'License :: OSI Approved :: MIT License', 'BSD license': 'License :: OSI Approved :: BSD License', 'ISC license': 'License :: OSI Approved :: ISC License (ISCL)', 'Apache Software License 2.0': 'License :: OSI Approved :: Apache Software License', 'GNU General Public License v3': 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)' } %} # get the dependencies and installs with open(path.join(here, 'requirements.txt'), encoding='utf-8') as f: all_reqs = f.read().split('\n') install_requires = [x.strip() for x in all_reqs if 'git+' not in x] dependency_links = [x.strip().replace('git+', '') for x in all_reqs if x.startswith('git+')] tests_requirements = ['pytest'], setup_requirements = ['pytest-runner'] requirements = [ # package requirements go here ] setup( name='{{ cookiecutter.repo_name }}', version=__version__, description="{{ cookiecutter.project_short_description }}", long_description=readme, author="{{ cookiecutter.full_name.replace('\"', '\\\"') }}", author_email='{{ cookiecutter.email }}', url='https://github.com/{{ cookiecutter.github_username }}/{{ cookiecutter.repo_name }}', packages=find_packages(include=['{{ cookiecutter.repo_name }}'], exclude=('docs', 'tests*',)), {%- if cookiecutter.open_source_license in license_classifiers %} license="{{ cookiecutter.open_source_license }}", {%- endif %} install_requires=install_requires, dependency_links=dependency_links, setup_requires=setup_requirements, test_suite='tests', tests_require=test_requirements, keywords='{{ cookiecutter.repo_name }}', classifiers=[ 'Programming Language :: Python :: 3.6', ] )
34.614035
103
0.667511
228
1,973
5.600877
0.447368
0.039154
0.070478
0.058731
0.062647
0.023493
0
0
0
0
0
0.005501
0.170806
1,973
56
104
35.232143
0.775061
0.053218
0
0
0
0
0.410103
0.118957
0
0
0
0
0
0
null
null
0
0.02439
null
null
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
1
0
0
0
0
0
0
0
0
1
fe1823b5cc5e17b94ed66896e05441088fc1ee56
1,503
py
Python
Class Work oop.py
fatimatswanya/fatimaCSC102
cab70bd696d39a9e16bcb57e0180e872be4f49bc
[ "MIT" ]
null
null
null
Class Work oop.py
fatimatswanya/fatimaCSC102
cab70bd696d39a9e16bcb57e0180e872be4f49bc
[ "MIT" ]
null
null
null
Class Work oop.py
fatimatswanya/fatimaCSC102
cab70bd696d39a9e16bcb57e0180e872be4f49bc
[ "MIT" ]
null
null
null
class Student: studentLevel = 'first year computer science 2020/2021 session' studentCounter = 0 registeredCourse='csc102' def __init__(self, thename, thematricno, thesex,thehostelname,theage,thecsc102examscore): self.name = thename self.matricno = thematricno self.sex = thesex self.hostelname =thehostelname self.age=theage self.csc102examscore=thecsc102examscore Student.studentCounter = Student.studentCounter + 1 def getName(self): return self.name def setName(self, thenewName): self.name = thenewName def agedeterminer(self): if self.age>16: print('Student is above 16') def finalscore(self): if self.csc102examscore < 45: print('You will carryover this course, sorry') else: print('You have passed') @classmethod def course(): print(f'Students registered course is {Student.registeredCourse}') @staticmethod def PAUNanthem(): print('Pau, here we come, Pau, here we come ') @staticmethod def ODDorEVEN(num): if num % 2==0: print('Number is even') else: print('Number is odd') @classmethod def studentnum(cls): print(Student.studentCounter) studendt1 = Student('James Kaka', '021074', 'M','Amethyst','16', '49') print(studendt1.getName()) studendt1.setName('James Gaga') print(studendt1.getName()) Student.PAUNanthem()
26.368421
93
0.632069
158
1,503
5.987342
0.487342
0.02537
0.021142
0.027484
0
0
0
0
0
0
0
0.042572
0.265469
1,503
57
94
26.368421
0.814312
0
0
0.181818
0
0
0.186959
0.017299
0
0
0
0
0
1
0.204545
false
0.022727
0
0.022727
0.318182
0.227273
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
0
0
0
1
fe18f53bb174876b9174543e0887f93aad3f8c21
6,686
py
Python
tests/test_disque.py
abdul-khalid/pydisque
a9b5caa6dac0621a0174d168f4a04c88d0e2f8b5
[ "MIT" ]
1
2019-02-28T09:48:22.000Z
2019-02-28T09:48:22.000Z
tests/test_disque.py
abdul-khalid/pydisque
a9b5caa6dac0621a0174d168f4a04c88d0e2f8b5
[ "MIT" ]
null
null
null
tests/test_disque.py
abdul-khalid/pydisque
a9b5caa6dac0621a0174d168f4a04c88d0e2f8b5
[ "MIT" ]
null
null
null
""" Unit Tests for the pydisque module. Currently, most of these tests require a fresh instance of Disque to be valid and pass. """ import unittest import json import time import random import six from pydisque.client import Client from redis.exceptions import ResponseError class TestDisque(unittest.TestCase): """TestCase class for pydisque.""" testID = None def setUp(self): """Setup the tests.""" self.client = Client(['localhost:7711']) self.client.connect() self.testID = "%d.%d" % (time.time(), random.randint(1000, 1000000)) def test_publish_and_receive(self): """Test the most important functions of pydisque.""" t1 = str(time.time()) self.client.add_job("test_q", t1, timeout=100) jobs = self.client.get_job(['test_q']) assert len(jobs) == 1 for queue_name, job_id, job in jobs: assert job == six.b(t1) self.client.ack_job(job_id) assert len(self.client.get_job(['test_q'], timeout=100)) == 0 def test_nack(self): """Fetch the queue, return a job, check that it's back.""" t1 = str(time.time()) queuename = "test_nack." + self.testID self.client.add_job(queuename, str(t1), timeout=100) jobs = self.client.get_job([queuename]) # NACK the first read assert len(jobs) == 1 for queue_name, job_id, job in jobs: assert len(jobs) == 1 assert job == six.b(t1) self.client.nack_job(job_id) # this time ACK it jobs = self.client.get_job([queuename]) assert len(jobs) == 1 for queue_name, job_id, job in jobs: assert job == six.b(t1) self.client.ack_job(job_id) assert len(self.client.get_job([queuename], timeout=100)) == 0 def test_qpeek(self): """ Test qpeek. Ran into some problems with an ENQUEUE/DEQUEUE test that was using qpeek, checking core functionality of qpeek(). """ queuename = "test_qpeek-%s" % self.testID job_id = self.client.add_job(queuename, "Peek A Boo") peeked = self.client.qpeek(queuename, 1) assert peeked[0][1] == job_id def test_qscan(self): """ Test the qscan function. This test relies on add_job() being functional, and the local disque not being a disque proxy to a mesh. TODO: unique the queues with self.testID. """ t1 = str(time.time()) self.client.add_job("q1", t1, timeout=100) self.client.add_job("q2", t1, timeout=100) qb = self.client.qscan() assert qb[0] assert qb[1] assert six.b("q1") in qb[1] assert six.b("q2") in qb[1] def test_jscan(self): """Simple test of the jscan function.""" t1 = time.time() queuename = "test_jscan-%s" % self.testID j1 = self.client.add_job(queuename, str(t1), timeout=100) jerbs = self.client.jscan(queue=queuename) assert j1 in jerbs[1] def test_del_job(self): """Simple test of del_job, needs qpeek. FIXME: This function has grown ugly. """ t1 = time.time() queuename = "test_del_job-%s" % self.testID j1 = self.client.add_job(queuename, str(t1)) jerbs = self.client.qpeek(queuename, 1) jlist = [] for item in jerbs: jlist.append(item[1]) assert j1 in jlist self.client.del_job(j1) jerbs = self.client.qpeek(queuename, 1) jlist = [] for item in jerbs: jlist.append(item[1]) assert j1 not in jerbs def test_qlen(self): """Simple test of qlen.""" queuename = "test_qlen-%s" % self.testID lengthOfTest = 100 test_job = "Useless Job." for x in range(lengthOfTest): self.client.add_job(queuename, test_job) assert self.client.qlen(queuename) == lengthOfTest def test_qstat(self): """Testing QSTAT (default behavior).""" queuename = "test_qstat-%s" % self.testID testqueue = ["a", "b", "c"] for x in testqueue: self.client.add_job(queuename, x) stat = self.client.qstat(queuename) # check the basics assert 'jobs-in' in stat assert 'jobs-out' in stat def test_qstat_dict(self): """Testing QSTAT's (new dict behavior).""" queuename = "test_qstat_dict-%s" % self.testID testqueue = ["a", "b", "c"] for x in testqueue: self.client.add_job(queuename, x) stat = self.client.qstat(queuename, True) assert stat.get('jobs-in', None) is not None assert stat.get('jobs-out', None) is not None def test_shownack(self): """Test that NACK and SHOW work appropriately.""" queuename = "test_show-%s" % self.testID test_job = "Show me." self.client.add_job(queuename, test_job) jobs = self.client.get_job([queuename]) for queue_name, job_id, job in jobs: self.client.nack_job(job_id) shown = self.client.show(job_id, True) assert shown.get('body') == test_job assert shown.get('nacks') == 1 def test_pause(self): """Test that a PAUSE message is acknowledged.""" queuename = "test_show-%s" % self.testID test_job = "Jerbs, they are a thing" self.client.pause(queuename, kw_in=True) try: job_id = self.client.add_job(queuename, test_job) except ResponseError: pass # can we add a job again? self.client.pause(queuename, kw_none=True) job_id = self.client.add_job(queuename, test_job) jobs = self.client.get_job([queuename]) # TODO(canardleteer): add a test of PAUSE SHOW def test_get_job(self): queue_name = "test_get_job." + self.testID job = str(time.time()) job_id = self.client.add_job(queue_name, job) expected = [(queue_name, job_id, job)] got = self.client.get_job([queue_name], withcounters=False) assert expected == got def test_get_job_withcounters(self): queue_name = "test_get_job." + self.testID job = str(time.time()) job_id = self.client.add_job(queue_name, job) nacks = 0 additional_deliveries = 0 expected = [(queue_name, job_id, job, nacks, additional_deliveries)] got = self.client.get_job([queue_name], withcounters=True) assert expected == got if __name__ == '__main__': unittest.main()
28.695279
76
0.588095
893
6,686
4.270997
0.195969
0.110121
0.051127
0.062926
0.455427
0.404562
0.369953
0.347142
0.272155
0.248034
0
0.017797
0.294047
6,686
232
77
28.818966
0.790254
0.147173
0
0.382353
0
0
0.053326
0
0
0
0
0.012931
0.191176
1
0.102941
false
0.007353
0.051471
0
0.169118
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
0
0
0
1
a3aceb33684c4eb53e7c078943f4c37d7dd1af91
4,321
py
Python
airspace_surgery.py
wipfli/airspaces
c2e01615fa6a065895ed04b8f342a38732e9196b
[ "Apache-2.0" ]
1
2021-12-28T23:40:51.000Z
2021-12-28T23:40:51.000Z
airspace_surgery.py
wipfli/airspaces
c2e01615fa6a065895ed04b8f342a38732e9196b
[ "Apache-2.0" ]
1
2021-01-30T13:15:14.000Z
2021-02-07T14:50:27.000Z
airspace_surgery.py
wipfli/aviation
c2e01615fa6a065895ed04b8f342a38732e9196b
[ "Apache-2.0" ]
null
null
null
import glob import json path_in = './airspaces/' path_out = './airspaces_processed/' filenames = [path.split('/')[-1] for path in glob.glob(path_in + '*')] remove = { 'france_fr.geojson': [ 314327, 314187, 314360, 314359, 314362, 314361, 314364, 314363, 314333, 314329, 314331, ], 'germany_de.geojson': [ 307563, 307638, 307639, 307640, ] } replacements = { 'france_fr.geojson': [ ['Bale10 119.35', 'Bale 10 TMA 130.9'], ['Bale1 119.35', 'Bale 1 TMA 130.9'], ['Bale2 119.35', 'Bale 2 TMA 130.9'], ['Bale3 119.35', 'Bale 3 TMA 130.9'], ['Bale4 119.35', 'Bale 4 TMA 130.9'], ['Bale5 119.35', 'Bale 5 TMA 130.9'], ['Bale5 119.35', 'Bale 5 TMA 130.9'], ['Bale6 119.35', 'Bale 6 TMA 130.9'], ['Bale7 119.35', 'Bale 7 TMA 130.9'], ['Bale8 119.35', 'Bale 8 TMA 130.9'], ['Bale9 119.35', 'Bale 9 TMA 130.9'], ['Bale AZ4T1 134.67', 'Bale T1 TMA HX 134.68'], ['Bale AZ4T2 134.67', 'Bale T2 TMA HX 134.68'], ['Bale AZ4T3 134.67', 'Bale T3 TMA HX 134.68'], ['CTR BALE', 'Bale CTR 118.3'] ], 'switzerland_ch.geojson': [ ['ZURICH 10 TMA 118.1', 'ZURICH 10 TMA 124.7'], ['ZURICH 11 TMA 118.1', 'ZURICH 11 TMA 124.7'], ['ZURICH 12 TMA 118.1', 'ZURICH 12 TMA 124.7'], ['ZURICH 13 TMA 118.1', 'ZURICH 13 TMA 124.7'], ['ZURICH 14 TMA 118.1', 'ZURICH 14 TMA HX 127.755'], ['ZURICH 15 TMA 118.1', 'ZURICH 15 TMA HX 127.755'], ['ZURICH 1 TMA 118.1', 'ZURICH 1 TMA 124.7'], ['ZURICH 2 CTR 118.1', 'ZURICH 2 CTR HX 118.975'], ['ZURICH 2 TMA 118.1', 'ZURICH 2 TMA 124.7'], ['ZURICH 3 TMA 118.1', 'ZURICH 3 TMA 124.7'], ['ZURICH 4A TMA 118.1', 'ZURICH 4A TMA 124.7'], ['ZURICH 4B TMA 118.1', 'ZURICH 4B TMA 124.7'], ['ZURICH 4C TMA 118.1', 'ZURICH 4C TMA 124.7'], ['ZURICH 5 TMA 118.1', 'ZURICH 5 TMA 124.7'], ['ZURICH 6 TMA 118.1', 'ZURICH 6 TMA 124.7'], ['ZURICH 7 TMA 118.1', 'ZURICH 7 TMA 124.7'], ['ZURICH 8 TMA 118.1', 'ZURICH 8 TMA 124.7'], ['ZURICH 9 TMA 118.1', 'ZURICH 9 TMA 124.7'], ['BERN 1 TMA 121.025', 'BERN 1 TMA HX 127.325'], ['BERN 2 TMA 121.025', 'BERN 2 TMA HX 127.325'], ['BERN CTR 121.025', 'BERN CTR HX 121.025'], ['EMMEN 1 CTR 120.425', 'EMMEN 1 CTR HX 120.425'], ['EMMEN 1 TMA 120.425', 'EMMEN 1 TMA HX 134.130'], ['EMMEN 2 CTR 120.425', 'EMMEN 2 CTR HX 120.425'], ['EMMEN 2 TMA 120.425', 'EMMEN 2 TMA HX 134.130'], ['EMMEN 3 TMA 120.425', 'EMMEN 3 TMA HX 134.130'], ['EMMEN 4 TMA 120.425', 'EMMEN 4 TMA HX 134.130'], ['EMMEN 5 TMA 120.425', 'EMMEN 5 TMA HX 134.130'], ['EMMEN 6 TMA 120.425', 'EMMEN 6 TMA HX 134.130'], ] } for filename in filenames: print(filename) with open(path_in + filename) as f: data = json.load(f) if filename in replacements: targets = [r[0] for r in replacements[filename]] for feature in data['features']: if feature['properties']['N'] in targets: print('replace ' + feature['properties']['N'] + '...') feature['properties']['N'] = next(x for x in replacements[filename] if x[0] == feature['properties']['N'])[1] if filename in remove: features_out = [f for f in data['features'] if int(f['properties']['ID']) not in remove[filename]] else: features_out = data['features'] print('removed ' + str(len(data['features']) - len(features_out)) + ' features') geojson = { 'type': 'FeatureCollection', 'features': features_out } print('write ' + filename + '...') with open(path_out + filename, 'w') as f: json.dump(geojson, f) all_features = [] for filename in filenames: print('read ' + filename + '...') with open(path_out + filename) as f: all_features += json.load(f)['features'] print('write airspaces.geojson...') with open('airspaces.geojson', 'w') as f: json.dump({ 'type': 'FeatureCollection', 'features': all_features }, f) print('done')
34.023622
125
0.532053
639
4,321
3.56964
0.197183
0.031565
0.078913
0.096887
0.187199
0.04954
0.022359
0.022359
0.022359
0.022359
0
0.200856
0.297153
4,321
126
126
34.293651
0.550214
0
0
0.090909
0
0
0.44573
0.010183
0
0
0
0
0
1
0
false
0
0.018182
0
0.018182
0.063636
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
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
a3b256695d6b1472ade6817590ffa769163e8848
487
py
Python
src/villages/migrations/0008_auto_20161228_2209.py
pwelzel/bornhack-website
af794e6a2fba06e09626259c7768feb30ff394be
[ "BSD-3-Clause" ]
null
null
null
src/villages/migrations/0008_auto_20161228_2209.py
pwelzel/bornhack-website
af794e6a2fba06e09626259c7768feb30ff394be
[ "BSD-3-Clause" ]
null
null
null
src/villages/migrations/0008_auto_20161228_2209.py
pwelzel/bornhack-website
af794e6a2fba06e09626259c7768feb30ff394be
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2016-12-28 22:09 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('villages', '0007_village_camp'), ] operations = [ migrations.AlterField( model_name='village', name='camp', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='camps.Camp'), ), ]
22.136364
98
0.620123
56
487
5.321429
0.678571
0.080537
0.09396
0.147651
0
0
0
0
0
0
0
0.057221
0.246407
487
21
99
23.190476
0.754768
0.13963
0
0
1
0
0.110577
0
0
0
0
0
0
1
0
false
0
0.153846
0
0.384615
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
a3b459175d9e5a84e03ca2cd0f4e7e7f14be6f69
3,101
py
Python
firmware/modulator.py
mfkiwl/OpenXcvr
9bea6efd03cd246f16982f0fadafed684ac5ce1c
[ "MIT" ]
14
2020-02-16T15:36:31.000Z
2022-03-27T02:24:40.000Z
firmware/modulator.py
mfkiwl/OpenXcvr
9bea6efd03cd246f16982f0fadafed684ac5ce1c
[ "MIT" ]
1
2020-11-23T16:16:33.000Z
2020-11-23T16:16:33.000Z
firmware/modulator.py
mfkiwl/OpenXcvr
9bea6efd03cd246f16982f0fadafed684ac5ce1c
[ "MIT" ]
4
2021-03-29T16:55:03.000Z
2022-01-23T16:43:59.000Z
from baremetal import * from math import pi, sin, cos import sys from scale import scale from settings import * from ssb import ssb_polar def modulator(clk, audio, audio_stb, settings): audio_bits = audio.subtype.bits #AM modulation am_mag = Unsigned(12).constant(0) + audio + 2048 am_phase = Signed(32).constant(0) am_stb = audio_stb #FM modulation fm_mag = Unsigned(12).constant(4095) frequency = Signed(32).constant(0) + audio nfm_scaled_frequency = frequency * (2**(32-audio_bits) * 5 / 50) nfm_phase = nfm_scaled_frequency.subtype.register(clk, en=audio_stb, init=0) nfm_phase.d(nfm_phase + nfm_scaled_frequency) scaled_frequency = frequency * (2**(32-audio_bits) * 8 / 50) fm_phase = scaled_frequency.subtype.register(clk, en=audio_stb, init=0) fm_phase.d(fm_phase + scaled_frequency) fm_stb = Boolean().register(clk, d=audio_stb, init=0) #ssb ssb_mag, ssb_phase, ssb_stb = ssb_polar(clk, audio, audio_stb, settings.mode==LSB) ssb_mag <<= 1 ssb_phase = Signed(32).constant(0) + ssb_phase ssb_phase <<= (32 - audio_bits) #cw modulation cw_mag = Unsigned(12).constant(0) cw_phase = Signed(32).constant(0) cw_stb = audio_stb #mode switching magnitude = Unsigned(12).select(settings.mode, am_mag, fm_mag, fm_mag, ssb_mag, ssb_mag, cw_mag) phase = Signed(32).select(settings.mode, am_phase, nfm_phase, fm_phase, ssb_phase, ssb_phase, cw_phase) stb = Boolean().select(settings.mode, am_stb, fm_stb, fm_stb, ssb_stb, ssb_stb, cw_stb) return magnitude, phase, audio_stb import numpy as np from matplotlib import pyplot as plt def test_modulator(stimulus, mode): settings = Settings() settings.mode = Unsigned(3).input("filter_mode") clk = Clock("clk") audio_in = Signed(12).input("i_data_in") audio_stb_in = Boolean().input("stb_in") i, q, stb = modulator(clk, audio_in, audio_stb_in, settings) #simulate clk.initialise() settings.mode.set(mode) response = [] for data in stimulus: for j in range(200): audio_stb_in.set(j==199) audio_in.set(data) clk.tick() if stb.get(): print i.get(), q.get() if i.get() is None or q.get() is None: continue response.append(i.get()*(2**20)+1j*q.get()) response = np.array(response) plt.title("Modulator") plt.xlabel("Time (samples)") plt.ylabel("Value") a, = plt.plot(np.real(response), label="I") b, = plt.plot(np.imag(response), label="Q") c, = plt.plot(stimulus*(2**20), label="Audio Input") plt.legend(handles=[a, b, c]) plt.show() if __name__ == "__main__" and "sim" in sys.argv: #mode am stim am stimulus=( np.sin(np.arange(1000)*2.0*pi*0.02)*1023+ np.sin(np.arange(1000)*2.0*pi*0.03)*1023 ) #test_modulator(stimulus, FM) #test_modulator(stimulus, FM) #test_modulator(stimulus, NBFM) test_modulator(stimulus, USB)
29.533333
117
0.633022
456
3,101
4.111842
0.258772
0.046933
0.056
0.036267
0.2528
0.1488
0.1488
0.074667
0.074667
0.0512
0
0.038737
0.234118
3,101
104
118
29.817308
0.750737
0.053209
0
0
0
0
0.027683
0
0
0
0
0
0
0
null
null
0
0.117647
null
null
0.014706
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
0
0
1
a3b4f00010ceb5e0331d09eb4a19ef587eba8526
348
py
Python
groundstation/broadcast_events/__init__.py
richo/groundstation
7ed48dd355051ee6b71164fc801e3893c09d11db
[ "MIT" ]
26
2015-06-18T20:17:07.000Z
2019-09-26T09:55:35.000Z
groundstation/broadcast_events/__init__.py
richo/groundstation
7ed48dd355051ee6b71164fc801e3893c09d11db
[ "MIT" ]
null
null
null
groundstation/broadcast_events/__init__.py
richo/groundstation
7ed48dd355051ee6b71164fc801e3893c09d11db
[ "MIT" ]
5
2015-07-20T01:52:47.000Z
2017-01-08T09:54:07.000Z
from broadcast_ping import BroadcastPing EVENT_TYPES = { "PING": BroadcastPing, } class UnknownBroadcastEvent(Exception): pass def new_broadcast_event(data): event_type, payload = data.split(" ", 1) if event_type not in EVENT_TYPES: raise UnknownBroadcastEvent(event_type) return EVENT_TYPES[event_type](payload)
23.2
47
0.732759
41
348
5.97561
0.560976
0.146939
0.130612
0
0
0
0
0
0
0
0
0.003534
0.186782
348
14
48
24.857143
0.862191
0
0
0
0
0
0.014368
0
0
0
0
0
0
1
0.090909
false
0.090909
0.090909
0
0.363636
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
0
0
0
1
a3b8b5beaa0f8d8ecd98462fe75b978547dc1472
4,248
py
Python
Python X/Dictionaries in python.py
nirobio/puzzles
fda8c84d8eefd93b40594636fb9b7f0fde02b014
[ "MIT" ]
null
null
null
Python X/Dictionaries in python.py
nirobio/puzzles
fda8c84d8eefd93b40594636fb9b7f0fde02b014
[ "MIT" ]
null
null
null
Python X/Dictionaries in python.py
nirobio/puzzles
fda8c84d8eefd93b40594636fb9b7f0fde02b014
[ "MIT" ]
null
null
null
{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# dictionaries, look-up tables & key-value pairs\n", "# d = {} OR d = dict()\n", "# e.g. d = {\"George\": 24, \"Tom\": 32}\n", "\n", "d = {}\n", "\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "d[\"George\"] = 24" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "d[\"Tom\"] = 32\n", "d[\"Jenny\"] = 16" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'George': 24, 'Tom': 32, 'Jenny': 16}\n" ] } ], "source": [ "print(d)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'Jenny' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m<ipython-input-5-0bdfff196d23>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0md\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mJenny\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mNameError\u001b[0m: name 'Jenny' is not defined" ] } ], "source": [ "print(d[Jenny])" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "32\n" ] } ], "source": [ "print(d[\"Tom\"])" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "d[\"Jenny\"] = 20" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "20\n" ] } ], "source": [ "print(d[\"Jenny\"])" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "# keys are strings or numbers \n", "\n", "d[10] = 100" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "100\n" ] } ], "source": [ "print(d[10])" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "# how to iterate over key-value pairs" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "key:\n", "George\n", "value:\n", "24\n", "\n", "key:\n", "Tom\n", "value:\n", "32\n", "\n", "key:\n", "Jenny\n", "value:\n", "20\n", "\n", "key:\n", "10\n", "value:\n", "100\n", "\n" ] } ], "source": [ " for key, value in d.items():\n", " print(\"key:\")\n", " print(key)\n", " print(\"value:\")\n", " print(value)\n", " print(\"\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.6" } }, "nbformat": 4, "nbformat_minor": 4 }
18.88
354
0.439266
439
4,248
4.161731
0.246014
0.061303
0.085386
0.149425
0.490969
0.277504
0.277504
0.242474
0.08867
0.041598
0
0.078859
0.298493
4,248
224
355
18.964286
0.534228
0
0
0.392857
0
0.004464
0.535546
0.113701
0
0
0
0
0
1
0
true
0
0
0
0
0.049107
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
0
0
0
0
0
1
a3bafb776906d3ce50f018766ee8f4cea08b123b
1,059
py
Python
container/pyf/graphqltypes/Event.py
Pompino/react-components-23KB
3201a417c5160e1b77f29fc1eac74ae9dc10d6ad
[ "MIT" ]
2
2021-10-30T18:18:33.000Z
2021-12-01T10:21:28.000Z
container/pyf/graphqltypes/Event.py
Pompino/react-components-23KB
3201a417c5160e1b77f29fc1eac74ae9dc10d6ad
[ "MIT" ]
null
null
null
container/pyf/graphqltypes/Event.py
Pompino/react-components-23KB
3201a417c5160e1b77f29fc1eac74ae9dc10d6ad
[ "MIT" ]
null
null
null
from typing_extensions import Required #from sqlalchemy.sql.sqltypes import Boolean from graphene import ObjectType, String, Field, ID, List, DateTime, Mutation, Boolean, Int from models.EventsRelated.EventModel import EventModel from graphqltypes.Utils import extractSession class EventType(ObjectType): id = ID() name = String() lastchange = DateTime() externalId = String() users = List('graphqltypes.User.UserType') def resolve_users(parent, info): session = extractSession(info) dbRecord = session.query(EventModel).get(parent.id) return dbRecord.users groups = List('graphqltypes.Group.GroupType') def resolve_users(parent, info): session = extractSession(info) dbRecord = session.query(EventModel).get(parent.id) return dbRecord.groups rooms = List('graphqltypes.Room.RoomType') def resolve_rooms(parent, info): session = extractSession(info) dbRecord = session.query(EventModel).get(parent.id) return dbRecord.rooms
32.090909
90
0.700661
114
1,059
6.473684
0.412281
0.065041
0.069106
0.126016
0.406504
0.406504
0.406504
0.406504
0.406504
0.406504
0
0
0.206799
1,059
32
91
33.09375
0.878571
0.040604
0
0.333333
0
0
0.078818
0.078818
0
0
0
0
0
1
0.125
false
0
0.166667
0
0.75
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
a3bea3b575a46a0bd0557e3e985c4141109eee00
266
py
Python
controllers/restart.py
Acidburn0zzz/helloworld
9d88357658c55dadf9d4c6f923b63e8cb6207f75
[ "MIT" ]
null
null
null
controllers/restart.py
Acidburn0zzz/helloworld
9d88357658c55dadf9d4c6f923b63e8cb6207f75
[ "MIT" ]
null
null
null
controllers/restart.py
Acidburn0zzz/helloworld
9d88357658c55dadf9d4c6f923b63e8cb6207f75
[ "MIT" ]
null
null
null
import os from base import BaseHandler class RestartHandler(BaseHandler): def get(self): if not self.authenticate(superuser=True): return os.system('touch ' + self.application.settings["restart_path"]) self.redirect(self.get_argument("next"))
22.166667
67
0.725564
33
266
5.787879
0.757576
0
0
0
0
0
0
0
0
0
0
0
0.157895
266
11
68
24.181818
0.852679
0
0
0
0
0
0.082707
0
0
0
0
0
0
1
0.125
false
0
0.25
0
0.625
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
a3c17e6746a0528783d5b0c338fdad4e4910e00a
1,976
py
Python
misc/python/materialize/checks/insert_select.py
guswynn/materialize
f433173ed71f511d91311769ec58c2d427dd6c3b
[ "MIT" ]
null
null
null
misc/python/materialize/checks/insert_select.py
guswynn/materialize
f433173ed71f511d91311769ec58c2d427dd6c3b
[ "MIT" ]
157
2021-12-28T19:17:45.000Z
2022-03-31T17:44:27.000Z
misc/python/materialize/checks/insert_select.py
guswynn/materialize
f433173ed71f511d91311769ec58c2d427dd6c3b
[ "MIT" ]
null
null
null
# Copyright Materialize, Inc. and contributors. All rights reserved. # # Use of this software is governed by the Business Source License # included in the LICENSE file at the root of this repository. # # As of the Change Date specified in that file, in accordance with # the Business Source License, use of this software will be governed # by the Apache License, Version 2.0. from textwrap import dedent from typing import List from materialize.checks.actions import Testdrive from materialize.checks.checks import Check class InsertSelect(Check): def initialize(self) -> Testdrive: return Testdrive( dedent( """ > CREATE TABLE insert_select_destination (f1 STRING); > CREATE TABLE insert_select_source_table (f1 STRING); > INSERT INTO insert_select_source_table SELECT 'T1' || generate_series FROM generate_series(1,10000); """ ) ) def manipulate(self) -> List[Testdrive]: return [ Testdrive(dedent(s)) for s in [ """ > INSERT INTO insert_select_source_table SELECT 'T2' || generate_series FROM generate_series(1, 10000); > INSERT INTO insert_select_destination SELECT * FROM insert_select_source_table; """, """ > INSERT INTO insert_select_source_table SELECT 'T3' || generate_series FROM generate_series(1, 10000); > INSERT INTO insert_select_destination SELECT * FROM insert_select_source_table; """, ] ] def validate(self) -> Testdrive: return Testdrive( dedent( """ > SELECT LEFT(f1, 2), COUNT(*), COUNT(DISTINCT f1) FROM insert_select_destination GROUP BY LEFT(f1, 2); T1 20000 10000 T2 20000 10000 T3 10000 10000 """ ) )
34.666667
119
0.598684
217
1,976
5.304147
0.359447
0.104257
0.093831
0.119896
0.374457
0.315378
0.315378
0.180712
0.180712
0.180712
0
0.047619
0.330466
1,976
56
120
35.285714
0.822373
0.18168
0
0.173913
0
0
0
0
0
0
0
0
0
1
0.130435
false
0
0.173913
0.130435
0.478261
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
0
0
0
1
a3c2ca7e8eeb8a5b7daf690508f0da4c87ebd47d
3,323
py
Python
evaluation/wordpress/pull_docker_images_from_private_registry.py
seveirbian/gear-old
8d3529a9bf42e652a9d7475c9d14e9a6afc69a76
[ "Apache-2.0" ]
null
null
null
evaluation/wordpress/pull_docker_images_from_private_registry.py
seveirbian/gear-old
8d3529a9bf42e652a9d7475c9d14e9a6afc69a76
[ "Apache-2.0" ]
null
null
null
evaluation/wordpress/pull_docker_images_from_private_registry.py
seveirbian/gear-old
8d3529a9bf42e652a9d7475c9d14e9a6afc69a76
[ "Apache-2.0" ]
null
null
null
import sys # package need to be installed, pip install docker import docker import time import yaml import os import xlwt auto = False private_registry = "202.114.10.146:9999/" # result result = [["tag", "finishTime", "size", "data"], ] class Puller: def __init__(self, images): self.images_to_pull = images def check(self): # detect whether the file exists, if true, delete it if os.path.exists("./images_pulled.txt"): os.remove("./images_pulled.txt") def pull(self): self.check() client = docker.from_env() # if don't give a tag, then all image under this registry will be pulled repos = self.images_to_pull[0]["repo"] for repo in repos: tags = self.images_to_pull[1][repo] for tag in tags: print "start pulling: ", private_registry+repo, ":", tag # get present time startTime = time.time() # get present net data cnetdata = get_net_data() # pull images try: image_pulled = client.images.pull(repository=private_registry+repo, tag=str(tag)) # print pull time finishTime = time.time() - startTime print "finished in " , finishTime, "s" # get image's size size = image_pulled.attrs[u'Size'] / 1000000.0 print "image size: ", size data = get_net_data() - cnetdata print "pull data: ", data print "\n" # record the image and its pulling time result.append([tag, finishTime, size, data]) except docker.errors.NotFound: print private_registry+repo + " not found...\n\n" except docker.errors.ImageNotFound: print private_registry+repo + " image not fount...\n\n" if auto != True: raw_input("Next?") class Generator: def __init__(self, profilePath=""): self.profilePath = profilePath def generateFromProfile(self): if self.profilePath == "": print "Error: profile path is null" with open(self.profilePath, 'r') as f: self.images = yaml.load(f, Loader=yaml.FullLoader) return self.images def get_net_data(): netCard = "/proc/net/dev" fd = open(netCard, "r") for line in fd.readlines(): if line.find("enp0s3") >= 0: field = line.split() data = float(field[1]) / 1024.0 / 1024.0 fd.close() return data if __name__ == "__main__": if len(sys.argv) == 2: auto = True generator = Generator(os.path.split(os.path.realpath(__file__))[0]+"/image_versions.yaml") images = generator.generateFromProfile() puller = Puller(images) puller.pull() # create a workbook sheet workbook = xlwt.Workbook() sheet = workbook.add_sheet("run_time") for row in range(len(result)): for column in range(len(result[row])): sheet.write(row, column, result[row][column]) workbook.save(os.path.split(os.path.realpath(__file__))[0]+"/pull.xls")
27.46281
101
0.550707
387
3,323
4.599483
0.379845
0.033708
0.042697
0.026966
0.033708
0.033708
0.033708
0.033708
0
0
0
0.019091
0.337948
3,323
121
102
27.46281
0.79
0.0969
0
0
0
0
0.093311
0
0
0
0
0
0
0
null
null
0
0.083333
null
null
0.111111
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
0
0
1
a3c978469e28670107c4646aa77b54f6269dda05
2,244
py
Python
tests/test_prior.py
frodre/LMR
4c00d3f9db96447e69bd3f426d59524f7b5f3ef5
[ "BSD-3-Clause" ]
17
2018-08-27T18:50:36.000Z
2021-03-17T22:48:55.000Z
tests/test_prior.py
mingsongli/LMR
4c00d3f9db96447e69bd3f426d59524f7b5f3ef5
[ "BSD-3-Clause" ]
5
2018-10-15T22:13:27.000Z
2019-04-26T11:45:58.000Z
tests/test_prior.py
mingsongli/LMR
4c00d3f9db96447e69bd3f426d59524f7b5f3ef5
[ "BSD-3-Clause" ]
11
2018-10-11T19:35:34.000Z
2021-08-17T12:08:11.000Z
import sys sys.path.append('../') import LMR_config as cfg import LMR_prior import numpy as np import pytest def test_prior_seed(): cfg_obj = cfg.Config(**{'core':{'seed': 2}}) prior_cfg = cfg_obj.prior prior_source = '20cr' datadir_prior = 'data' datafile_prior = '[vardef_template]_gridded_dat.nc' state_variables = {'air': 'anom'} state_kind = 'anom' X = LMR_prior.prior_assignment(prior_source) X.prior_datadir = datadir_prior X.prior_datafile = datafile_prior X.statevars = state_variables X.Nens = 1 X.detrend = False X.kind = state_kind X.avgInterval = [1,2,3,4,5,6,7,8,9,10,11,12] X.populate_ensemble(prior_source, prior_cfg) X2 = LMR_prior.prior_assignment(prior_source) X2.prior_datadir = datadir_prior X2.prior_datafile = datafile_prior X2.statevars = state_variables X2.Nens = 1 X2.detrend = False X2.kind = state_kind X2.avgInterval = [1,2,3,4,5,6,7,8,9,10,11,12] X2.populate_ensemble(prior_source, prior_cfg) np.testing.assert_equal(X2.ens, X.ens) def test_prior_use_full_prior(): cfg_obj = cfg.Config(**{'core': {'seed': None}}) prior_cfg = cfg_obj.prior prior_source = '20cr' datadir_prior = 'data' datafile_prior = '[vardef_template]_gridded_dat.nc' state_variables = {'air': 'anom'} state_kind = 'anom' avgInterval = [1,2,3,4,5,6,7,8,9,10,11,12] X = LMR_prior.prior_assignment(prior_source) X.prior_datadir = datadir_prior X.prior_datafile = datafile_prior X.statevars = state_variables X.Nens = None X.detrend = False X.kind = state_kind X.avgInterval = avgInterval X.populate_ensemble(prior_source, prior_cfg) X2 = LMR_prior.prior_assignment(prior_source) X2.prior_datadir = datadir_prior X2.prior_datafile = datafile_prior X2.statevars = state_variables X2.Nens = None X2.detrend = False X2.kind = state_kind X2.avgInterval = avgInterval X2.read_prior() # Transform full prior into ensemble-like shape prior_vals = X2.prior_dict['air']['value'] prior_vals = prior_vals.reshape(prior_vals.shape[0], -1) prior_vals = prior_vals.T np.testing.assert_equal(X.ens, prior_vals)
24.933333
60
0.685829
333
2,244
4.363363
0.216216
0.068135
0.035788
0.063317
0.75086
0.75086
0.695114
0.695114
0.695114
0.598761
0
0.041134
0.198307
2,244
89
61
25.213483
0.766537
0.020053
0
0.59375
0
0
0.058824
0.029184
0
0
0
0
0.03125
1
0.03125
false
0
0.078125
0
0.109375
0
0
0
0
null
0
0
0
0
1
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
1
a3d28839e9a9ab62ac7936ca858e4cb438e092b3
16,562
py
Python
tests/test_mag.py
jdddog/mag-archiver
079e735e610d6b81b3ac8dc479d4f93bb0aacb11
[ "Apache-2.0" ]
null
null
null
tests/test_mag.py
jdddog/mag-archiver
079e735e610d6b81b3ac8dc479d4f93bb0aacb11
[ "Apache-2.0" ]
null
null
null
tests/test_mag.py
jdddog/mag-archiver
079e735e610d6b81b3ac8dc479d4f93bb0aacb11
[ "Apache-2.0" ]
null
null
null
# Copyright 2020 Curtin University # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Author: James Diprose import os import unittest from unittest.mock import patch import pendulum from azure.common import AzureMissingResourceHttpError from azure.cosmosdb.table.tableservice import TableService from azure.storage.blob import ContainerProperties from mag_archiver.azure import create_table from mag_archiver.mag import make_mag_query, MagState, MagDateType, MagRelease, MagTask, MagArchiverClient, \ hide_if_not_none class TestMag(unittest.TestCase): def test_hide_if_not_none(self): # Test that None is returned for None value = hide_if_not_none(None) self.assertEqual(value, None) # Test that 'hidden' is returned: string value = hide_if_not_none('hello world') self.assertEqual(value, 'hidden') # Test that 'hidden' is returned: integer value = hide_if_not_none(123) self.assertEqual(value, 'hidden') def test_make_mag_query(self): start_date = pendulum.datetime(year=2020, month=4, day=1) end_date = pendulum.datetime(year=2020, month=5, day=1) # No parameters query = make_mag_query() self.assertEqual(query, '') # State parameter query = make_mag_query(state=MagState.discovered) self.assertEqual(query, "State eq 'discovered'") query = make_mag_query(state=MagState.archived) self.assertEqual(query, "State eq 'archived'") query = make_mag_query(state=MagState.done) self.assertEqual(query, "State eq 'done'") # Start date parameter query = make_mag_query(start_date=start_date, date_type=MagDateType.release) self.assertEqual(query, "ReleaseDate ge datetime'2020-04-01T00:00Z'") query = make_mag_query(start_date=start_date, date_type=MagDateType.discovered) self.assertEqual(query, "DiscoveredDate ge datetime'2020-04-01T00:00Z'") query = make_mag_query(start_date=start_date, date_type=MagDateType.archived) self.assertEqual(query, "ArchivedDate ge datetime'2020-04-01T00:00Z'") query = make_mag_query(start_date=start_date, date_type=MagDateType.done) self.assertEqual(query, "DoneDate ge datetime'2020-04-01T00:00Z'") # End date parameter query = make_mag_query(end_date=end_date, date_type=MagDateType.release) self.assertEqual(query, "ReleaseDate lt datetime'2020-05-01T00:00Z'") query = make_mag_query(end_date=end_date, date_type=MagDateType.discovered) self.assertEqual(query, "DiscoveredDate lt datetime'2020-05-01T00:00Z'") query = make_mag_query(end_date=end_date, date_type=MagDateType.archived) self.assertEqual(query, "ArchivedDate lt datetime'2020-05-01T00:00Z'") query = make_mag_query(end_date=end_date, date_type=MagDateType.done) self.assertEqual(query, "DoneDate lt datetime'2020-05-01T00:00Z'") # Start date, end date and date type query = make_mag_query(start_date=start_date, end_date=end_date, date_type=MagDateType.release) self.assertEqual(query, "ReleaseDate ge datetime'2020-04-01T00:00Z' and ReleaseDate lt " "datetime'2020-05-01T00:00Z'") query = make_mag_query(start_date=start_date, end_date=end_date, date_type=MagDateType.discovered) self.assertEqual(query, "DiscoveredDate ge datetime'2020-04-01T00:00Z' and DiscoveredDate lt " "datetime'2020-05-01T00:00Z'") query = make_mag_query(start_date=start_date, end_date=end_date, date_type=MagDateType.archived) self.assertEqual(query, "ArchivedDate ge datetime'2020-04-01T00:00Z' and ArchivedDate lt " "datetime'2020-05-01T00:00Z'") query = make_mag_query(start_date=start_date, end_date=end_date, date_type=MagDateType.done) self.assertEqual(query, "DoneDate ge datetime'2020-04-01T00:00Z' and DoneDate lt " "datetime'2020-05-01T00:00Z'") # State, start date, end date and date type query = make_mag_query(state=MagState.discovered, start_date=start_date, end_date=end_date, date_type=MagDateType.discovered) self.assertEqual(query, "State eq 'discovered' and DiscoveredDate ge datetime'2020-04-01T00:00Z' " "and DiscoveredDate lt datetime'2020-05-01T00:00Z'") query = make_mag_query(state=MagState.archived, start_date=start_date, end_date=end_date, date_type=MagDateType.archived) self.assertEqual(query, "State eq 'archived' and ArchivedDate ge datetime'2020-04-01T00:00Z' " "and ArchivedDate lt datetime'2020-05-01T00:00Z'") query = make_mag_query(state=MagState.done, start_date=start_date, end_date=end_date, date_type=MagDateType.done) self.assertEqual(query, "State eq 'done' and DoneDate ge datetime'2020-04-01T00:00Z' " "and DoneDate lt datetime'2020-05-01T00:00Z'") def make_mag_release(account_name: str, account_key: str, year: int, month: int, day: int): min_date = pendulum.datetime(1601, 1, 1) partition_key_ = 'mag' row_key_ = f'mag-{year:0>4d}-{month:0>2d}-{day:0>2d}' state_ = MagState.discovered task_ = MagTask.not_started release_date_ = pendulum.datetime(year=year, month=month, day=day) source_container_ = row_key_ source_container_last_modified_ = pendulum.datetime(year=year, month=month, day=day, hour=1) release_container_ = '' release_path_ = '' discovered_date_ = pendulum.datetime(year=year, month=month, day=day, hour=2) archived_date_ = min_date done_date_ = min_date return MagRelease(partition_key_, row_key_, state_, task_, release_date_, source_container_, source_container_last_modified_, release_container_, release_path_, discovered_date_, archived_date_, done_date_, account_name=account_name, account_key=account_key) class TestMagRelease(unittest.TestCase): def __init__(self, *args, **kwargs): super(TestMagRelease, self).__init__(*args, **kwargs) self.account_name = os.getenv('STORAGE_ACCOUNT_NAME') self.account_key = os.getenv('STORAGE_ACCOUNT_KEY') create_table(self.account_name, self.account_key, MagRelease.TABLE_NAME) def test_secrets_hidden(self): # Check that account key is hidden account_name = 'myaccountname' secret = 'secret' # Check that account_key and sas_token are hidden release = make_mag_release(account_name, secret, 2020, 1, 1) self.assertIn('account_key=hidden', release.__repr__()) self.assertNotIn(secret, release.__str__()) self.assertNotIn(secret, release.__repr__()) # Check that account_key is None release = make_mag_release(account_name, None, 2020, 1, 1) self.assertIn('account_key=None', release.__repr__()) def test_create(self): release = make_mag_release(self.account_name, self.account_key, 2019, 6, 1) try: success = release.create() self.assertTrue(success) finally: release.delete() def test_delete(self): release = make_mag_release(self.account_name, self.account_key, 2019, 6, 1) # Check that we can create and then delete release.create() release.delete() # Check that second delete fails with self.assertRaises(AzureMissingResourceHttpError): release.delete() def test_update(self): release = make_mag_release(self.account_name, self.account_key, 2019, 6, 1) try: release.create() # Update release release.state = MagState.archived release.archived_date = pendulum.utcnow().microsecond_(0) release.update() # Verify that release is updated service = TableService(account_name=self.account_name, account_key=self.account_key) entity = service.get_entity(MagRelease.TABLE_NAME, release.partition_key, release.row_key) updated_release = MagRelease.from_entity(entity) self.assertEqual(release.state, updated_release.state) self.assertEqual(release.archived_date, updated_release.archived_date) finally: release.delete() def make_containers(): containers = [] cp1 = ContainerProperties() cp1.name = 'mag-2020-04-17' cp1.last_modified = pendulum.datetime(year=2020, month=4, day=18) containers.append(cp1) cp3 = ContainerProperties() cp3.name = 'mag-2020-05-01' cp3.last_modified = pendulum.datetime(year=2020, month=5, day=1) containers.append(cp3) cp2 = ContainerProperties() cp2.name = 'mag-2020-04-24' cp2.last_modified = pendulum.datetime(year=2020, month=4, day=25) containers.append(cp2) return containers class TestMagArchiverClient(unittest.TestCase): def __init__(self, *args, **kwargs): super(TestMagArchiverClient, self).__init__(*args, **kwargs) self.account_name = os.getenv('STORAGE_ACCOUNT_NAME') self.account_key = os.getenv('STORAGE_ACCOUNT_KEY') create_table(self.account_name, self.account_key, MagRelease.TABLE_NAME) def test_secrets_hidden(self): # Check that account key is hidden account_name = 'myaccountname' secret = 'secret' # Check that account_key and sas_token are hidden client = MagArchiverClient(account_name=account_name, account_key=secret, sas_token=secret) expected = f'MagArchiverClient(account_name={account_name}, account_key=hidden, sas_token=hidden)' self.assertEqual(client.__str__(), expected) self.assertEqual(client.__repr__(), expected) self.assertNotIn(secret, client.__str__()) self.assertNotIn(secret, client.__repr__()) # Check that account_key and sas_token are None client = MagArchiverClient(account_name=account_name) expected = f'MagArchiverClient(account_name={account_name}, account_key=None, sas_token=None)' self.assertEqual(client.__str__(), expected) self.assertEqual(client.__repr__(), expected) @patch('mag_archiver.mag.list_containers') @patch('pendulum.datetime.now') def test_list_containers(self, mock_now, mock_list_containers): # Mock time mock_now.return_value = pendulum.datetime(year=2020, month=5, day=1, minute=10) # Mock containers containers_in = make_containers() mock_list_containers.return_value = containers_in # Test that 2 containers are returned when last_modified_thresh=1 client = MagArchiverClient(account_name=self.account_name, account_key=self.account_key) containers_out = client.list_containers(last_modified_thresh=1) self.assertEqual(len(containers_out), 2) # Test that 3 containers are returned when last_modified_thresh=0 containers_out = client.list_containers(last_modified_thresh=0) self.assertEqual(len(containers_out), 3) # Test sort order reverse=False self.assertEqual(containers_in[0].name, containers_out[0].name) self.assertEqual(containers_in[2].name, containers_out[1].name) self.assertEqual(containers_in[1].name, containers_out[2].name) # Test sort order reverse=True containers_out = client.list_containers(last_modified_thresh=0, reverse=True) self.assertEqual(len(containers_out), 3) self.assertEqual(containers_in[1].name, containers_out[0].name) self.assertEqual(containers_in[2].name, containers_out[1].name) self.assertEqual(containers_in[0].name, containers_out[2].name) @patch('mag_archiver.mag.list_containers') @patch('pendulum.datetime.now') def test_update_releases(self, mock_now, mock_list_containers): # Mock time mock_now.return_value = pendulum.datetime(year=2020, month=5, day=1, minute=10) # Mock containers containers_in = make_containers() mock_list_containers.return_value = containers_in # Mock fetching of containers client = MagArchiverClient(account_name=self.account_name, account_key=self.account_key) containers = client.list_containers(last_modified_thresh=1) try: # Update releases based on containers num_updated, num_errors = client.update_releases(containers) self.assertEqual(num_updated, 2) self.assertEqual(num_errors, 0) finally: # Clean up service = TableService(account_name=self.account_name, account_key=self.account_key) for container in containers: service.delete_entity(MagRelease.TABLE_NAME, 'mag', container.name.replace("mag-", "")) @patch('mag_archiver.mag.list_containers') @patch('pendulum.datetime.now') def test_list_releases(self, mock_now, mock_list_containers): # Mock time mock_now.return_value = pendulum.datetime(year=2020, month=5, day=1, hour=1) # Mock containers containers_in = make_containers() mock_list_containers.return_value = containers_in # Mock fetching of containers client = MagArchiverClient(account_name=self.account_name, account_key=self.account_key) containers = client.list_containers(last_modified_thresh=1) try: # Update releases based on containers num_updated, num_errors = client.update_releases(containers) self.assertEqual(num_updated, 3) self.assertEqual(num_errors, 0) # Two releases start_date = pendulum.datetime(year=2020, month=4, day=17) end_date = pendulum.datetime(year=2020, month=5, day=1) releases = client.list_releases(start_date=start_date, end_date=end_date, state=MagState.discovered, date_type=MagDateType.release) self.assertEqual(len(releases), 2) # 1 release start_date = pendulum.datetime(year=2020, month=4, day=17, minute=1) end_date = pendulum.datetime(year=2020, month=5, day=1) releases = client.list_releases(start_date=start_date, end_date=end_date, state=MagState.discovered, date_type=MagDateType.release) self.assertEqual(len(releases), 1) # Three releases start_date = pendulum.datetime(year=2020, month=4, day=17) end_date = pendulum.datetime(year=2020, month=5, day=1, minute=1) releases = client.list_releases(start_date=start_date, end_date=end_date, state=MagState.discovered, date_type=MagDateType.release, reverse=False) self.assertEqual(len(releases), 3) # Sorting reverse=False self.assertEqual(releases[0].row_key, '2020-04-17') self.assertEqual(releases[1].row_key, '2020-04-24') self.assertEqual(releases[2].row_key, '2020-05-01') # Sorting reverse=True releases = client.list_releases(start_date=start_date, end_date=end_date, state=MagState.discovered, date_type=MagDateType.release, reverse=True) self.assertEqual(releases[0].row_key, '2020-05-01') self.assertEqual(releases[1].row_key, '2020-04-24') self.assertEqual(releases[2].row_key, '2020-04-17') finally: # Clean up service = TableService(account_name=self.account_name, account_key=self.account_key) for container in containers: service.delete_entity(MagRelease.TABLE_NAME, 'mag', container.name.replace("mag-", ""))
45.128065
112
0.676368
2,046
16,562
5.239003
0.116325
0.069969
0.028734
0.030133
0.736729
0.710234
0.680847
0.625618
0.599123
0.553037
0
0.042021
0.226965
16,562
366
113
45.251366
0.795204
0.101739
0
0.367089
0
0
0.117663
0.059641
0
0
0
0
0.244726
1
0.059072
false
0
0.037975
0
0.118143
0
0
0
0
null
0
0
0
0
1
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
1
a3d5083187f3606549524985d8222291ba30b943
4,199
py
Python
tests/unit/transport/plugins/asyncssh/test_asyncssh_transport.py
carlmontanari/nssh
fa2277ea0b8fdb81de3064e1d48bad9264f0cd64
[ "MIT" ]
1
2020-02-09T17:43:43.000Z
2020-02-09T17:43:43.000Z
tests/unit/transport/plugins/asyncssh/test_asyncssh_transport.py
carlmontanari/nssh
fa2277ea0b8fdb81de3064e1d48bad9264f0cd64
[ "MIT" ]
null
null
null
tests/unit/transport/plugins/asyncssh/test_asyncssh_transport.py
carlmontanari/nssh
fa2277ea0b8fdb81de3064e1d48bad9264f0cd64
[ "MIT" ]
null
null
null
import asyncio from io import BytesIO import pytest from asyncssh.connection import SSHClientConnection from asyncssh.stream import SSHReader from scrapli.exceptions import ScrapliConnectionNotOpened, ScrapliTimeout class DumbContainer: def __init__(self): self.preferred_auth = () def __getattr__(self, item): # options has a billion attributes, just return None, doesnt matter for this test return None def test_close(monkeypatch, asyncssh_transport): def _close(cls): pass monkeypatch.setattr( "asyncssh.connection.SSHClientConnection.close", _close, ) # lie and pretend the session is already assigned options = DumbContainer() asyncssh_transport.session = SSHClientConnection( loop=asyncio.get_event_loop_policy().get_event_loop(), options=options ) asyncssh_transport.close() assert asyncssh_transport.session is None assert asyncssh_transport.stdin is None assert asyncssh_transport.stdout is None def test_close_catch_brokenpipe(monkeypatch, asyncssh_transport): def _close(cls): raise BrokenPipeError monkeypatch.setattr( "asyncssh.connection.SSHClientConnection.close", _close, ) # lie and pretend the session is already assigned options = DumbContainer() asyncssh_transport.session = SSHClientConnection( loop=asyncio.get_event_loop_policy().get_event_loop(), options=options ) asyncssh_transport.close() assert asyncssh_transport.session is None assert asyncssh_transport.stdin is None assert asyncssh_transport.stdout is None def test_isalive_no_session(asyncssh_transport): assert asyncssh_transport.isalive() is False def test_isalive(asyncssh_transport): # lie and pretend the session is already assigned options = DumbContainer() asyncssh_transport.session = SSHClientConnection( loop=asyncio.get_event_loop_policy().get_event_loop(), options=options ) # lie and tell asyncssh auth is done asyncssh_transport.session._auth_complete = True # also have to lie and create a transport and have it return False when is_closing is called asyncssh_transport.session._transport = DumbContainer() asyncssh_transport.session._transport.is_closing = lambda: False assert asyncssh_transport.isalive() is True def test_isalive_attribute_error(asyncssh_transport): # lie and pretend the session is already assigned options = DumbContainer() asyncssh_transport.session = SSHClientConnection( loop=asyncio.get_event_loop_policy().get_event_loop(), options=options ) # lie and tell asyncssh auth is done asyncssh_transport.session._auth_complete = True assert asyncssh_transport.isalive() is False async def test_read(monkeypatch, asyncssh_transport): async def _read(cls, _): return b"somebytes" monkeypatch.setattr( "asyncssh.stream.SSHReader.read", _read, ) # lie and pretend the session is already assigned/stdout is already a thing asyncssh_transport.stdout = SSHReader("", "") assert await asyncssh_transport.read() == b"somebytes" async def test_read_exception_not_open(asyncssh_transport): with pytest.raises(ScrapliConnectionNotOpened): await asyncssh_transport.read() async def test_read_exception_timeout(monkeypatch, asyncssh_transport): async def _read(cls, _): await asyncio.sleep(0.5) monkeypatch.setattr( "asyncssh.stream.SSHReader.read", _read, ) # lie and pretend the session is already assigned/stdout is already a thing asyncssh_transport.stdout = SSHReader("", "") asyncssh_transport._base_transport_args.timeout_transport = 0.1 with pytest.raises(ScrapliTimeout): await asyncssh_transport.read() def test_write(asyncssh_transport): asyncssh_transport.stdin = BytesIO() asyncssh_transport.write(b"blah") asyncssh_transport.stdin.seek(0) assert asyncssh_transport.stdin.read() == b"blah" def test_write_exception(asyncssh_transport): with pytest.raises(ScrapliConnectionNotOpened): asyncssh_transport.write("blah")
28.958621
96
0.740414
485
4,199
6.17732
0.208247
0.226969
0.080107
0.032043
0.641522
0.614152
0.524032
0.495327
0.495327
0.495327
0
0.001468
0.188616
4,199
144
97
29.159722
0.877898
0.138128
0
0.511111
0
0
0.049889
0.041574
0
0
0
0
0.122222
1
0.122222
false
0.011111
0.066667
0.011111
0.222222
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
0
0
0
0
0
0
0
0
0
0
1
a3d593a4708a16249302174780a07f2fdc88109b
664
py
Python
dataPresenter.py
thebouv/IUS-Hacktoberfest
084634ec2feff3e81862d85b3938e1ae2c5aadff
[ "MIT" ]
3
2019-09-30T18:25:12.000Z
2019-10-01T21:47:41.000Z
dataPresenter.py
thebouv/IUS-Hacktoberfest
084634ec2feff3e81862d85b3938e1ae2c5aadff
[ "MIT" ]
3
2019-09-27T22:44:34.000Z
2019-10-09T17:00:37.000Z
dataPresenter.py
thebouv/IUS-Hacktoberfest
084634ec2feff3e81862d85b3938e1ae2c5aadff
[ "MIT" ]
6
2019-09-28T04:17:16.000Z
2019-10-08T18:47:26.000Z
from plotly.subplots import make_subplots import plotly.graph_objects as go import plotly.io as pio from dataProcessor import parseLabels, parseLangs import plotly.io as pio import os years = parseLabels() langs = parseLangs() #make the plotly results fig = make_subplots( rows=1, cols=2, specs=[[{"type": "xy"}, {"type": "domain"}]], ) fig.add_trace(go.Bar(y = list(langs.values()), x = list(langs.keys()), showlegend=False), row=1, col=1) fig.add_trace(go.Pie(values = list(years.values()), labels = list(years.keys())), row=1, col=2) fig.update_layout(height=600) pio.write_html(fig, 'index.html', auto_open=True)
22.133333
89
0.680723
99
664
4.484848
0.525253
0.081081
0.063063
0.072072
0.085586
0
0
0
0
0
0
0.016275
0.167169
664
29
90
22.896552
0.786618
0.034639
0
0.111111
0
0
0.040689
0
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
1
a3d7408e9bd4e19d03c2fd8dc2282dcab222a6b8
2,782
py
Python
db/redis_db.py
Lifeistrange/WeiboSpider
8aa3465487ef64bb6e9bb4bd503f182a1b38c292
[ "MIT" ]
1
2018-07-23T03:58:53.000Z
2018-07-23T03:58:53.000Z
db/redis_db.py
545314690/WeiboSpider-1.6.4
d29cc9b926da5790768ddebdfdf9bf6c617a0e03
[ "MIT" ]
null
null
null
db/redis_db.py
545314690/WeiboSpider-1.6.4
d29cc9b926da5790768ddebdfdf9bf6c617a0e03
[ "MIT" ]
2
2018-06-25T09:21:24.000Z
2018-07-23T03:59:31.000Z
# coding:utf-8 import datetime import json import re import redis from config.conf import get_redis_args redis_args = get_redis_args() class Cookies(object): rd_con = redis.StrictRedis(host=redis_args.get('host'), port=redis_args.get('port'), password=redis_args.get('password'), db=redis_args.get('cookies')) rd_con_broker = redis.StrictRedis(host=redis_args.get('host'), port=redis_args.get('port'), password=redis_args.get('password'), db=redis_args.get('broker')) @classmethod def store_cookies(cls, name, cookies): pickled_cookies = json.dumps( {'cookies': cookies, 'loginTime': datetime.datetime.now().timestamp()}) cls.rd_con.hset('account', name, pickled_cookies) cls.rd_con.lpush('account_queue', name) @classmethod def fetch_cookies(cls): for i in range(cls.rd_con.llen('account_queue')): name = cls.rd_con.rpop('account_queue').decode('utf-8') if name: j_account = cls.rd_con.hget('account', name).decode('utf-8') if j_account: cls.rd_con.lpush('account_queue', name) # 当账号不存在时,这个name也会清除,并取下一个name account = json.loads(j_account) login_time = datetime.datetime.fromtimestamp(account['loginTime']) if datetime.datetime.now() - login_time > datetime.timedelta(hours=20): cls.rd_con.hdel('account', name) continue # 丢弃这个过期账号,account_queue会在下次访问的时候被清除,这里不清除是因为分布式的关系 return name, account['cookies'] else: return None @classmethod def delete_cookies(cls, name): cls.rd_con.hdel('account', name) return True @classmethod def check_login_task(cls): if cls.rd_con_broker.llen('login_queue') > 0: cls.rd_con_broker.delete('login_queue') class Urls(object): rd_con = redis.StrictRedis(host=redis_args.get('host'), port=redis_args.get('port'), password=redis_args.get('password'), db=redis_args.get('urls')) @classmethod def store_crawl_url(cls, url, result): cls.rd_con.set(url, result) class IdNames(object): rd_con = redis.StrictRedis(host=redis_args.get('host'), port=redis_args.get('port'), password=redis_args.get('password'), db=redis_args.get('id_name')) @classmethod def store_id_name(cls, user_name, user_id): cls.rd_con.set(user_name, user_id) @classmethod def fetch_uid_by_name(cls, user_name): user_id = cls.rd_con.get(user_name) if user_id: return user_id.decode('utf-8') return ''
36.12987
103
0.611431
349
2,782
4.653295
0.234957
0.105296
0.125616
0.061576
0.376232
0.361453
0.333128
0.297414
0.297414
0.2617
0
0.003423
0.264917
2,782
76
104
36.605263
0.790709
0.03271
0
0.237288
0
0
0.088202
0
0
0
0
0
0
1
0.118644
false
0.067797
0.084746
0
0.40678
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
0
0
0
1
a3d86cad8d3203300d44bd218c5b17bca9639482
409
py
Python
data/contacts.py
rgurevych/python_for_testers
04023a5d6ea480f7828aa56e8a4094b744e05721
[ "Apache-2.0" ]
null
null
null
data/contacts.py
rgurevych/python_for_testers
04023a5d6ea480f7828aa56e8a4094b744e05721
[ "Apache-2.0" ]
null
null
null
data/contacts.py
rgurevych/python_for_testers
04023a5d6ea480f7828aa56e8a4094b744e05721
[ "Apache-2.0" ]
null
null
null
from models.contact import Contact testdata = [Contact(first_name="Firstname", last_name="Lastname", mobile_phone="+12345678", work_phone="12345", home_phone="67890", fax="55443322", email_1="email_1@email.com", email_2="email_2@email.com", email_3="email_3@email.com", address="Street, 15 \n 12345 New-York")]
51.125
116
0.577017
49
409
4.591837
0.612245
0.106667
0.097778
0
0
0
0
0
0
0
0
0.134021
0.288509
409
7
117
58.428571
0.639175
0
0
0
0
0
0.301471
0
0
0
0
0
0
1
0
false
0
0.2
0
0.2
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
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
1
a3da86d4ce645eeb7110c2f1c12a4c42e43e9f77
2,681
py
Python
cats/types.py
AdamBrianBright/cats-python
163cbde06c0d56520c217c0d66ddca34c7e0f63b
[ "MIT" ]
2
2021-10-04T05:39:03.000Z
2021-10-07T06:44:19.000Z
cats/types.py
AdamBrianBright/cats-python
163cbde06c0d56520c217c0d66ddca34c7e0f63b
[ "MIT" ]
7
2021-08-17T17:50:23.000Z
2021-08-31T08:44:13.000Z
cats/types.py
AdamBrianBright/cats-python
163cbde06c0d56520c217c0d66ddca34c7e0f63b
[ "MIT" ]
2
2021-10-01T20:58:25.000Z
2021-10-04T05:40:35.000Z
from pathlib import Path from types import GeneratorType from typing import AsyncIterable, Iterable, TypeAlias import ujson from cats.errors import MalformedHeadersError try: from django.db.models import QuerySet, Model except ImportError: QuerySet = type('QuerySet', (list,), {}) Model = type('Model', (list,), {}) __all__ = [ 'Bytes', 'BytesGen', 'BytesAsyncGen', 'BytesAnyGen', 'Byte', 'Json', 'File', 'List', 'Missing', 'MISSING', 'QuerySet', 'Model', 'T_Headers', 'Headers', ] Bytes: TypeAlias = bytes | bytearray | memoryview BytesGen: TypeAlias = Iterable[Bytes] BytesAsyncGen: TypeAlias = AsyncIterable[Bytes] BytesAnyGen: TypeAlias = BytesGen | BytesAsyncGen Byte: TypeAlias = Bytes Json: TypeAlias = str | int | float | dict | list | bool | None File: TypeAlias = Path | str List = list | tuple | set | GeneratorType | QuerySet class Missing(str): """ Custom Missing type is required for Pydantic to work properly. IDK """ __slots__ = () def __init__(self): super().__init__() def __eq__(self, other): return isinstance(other, Missing) def __bool__(self): return False MISSING = Missing() class Headers(dict): __slots__ = () def __init__(self, *args, **kwargs): v = self._convert(*args, **kwargs) if (offset := v.get('offset', None)) and (not isinstance(offset, int) or offset < 0): raise MalformedHeadersError('Invalid offset header', headers=v) super().__init__(v) @classmethod def _key(cls, key: str) -> str: return key.replace(' ', '-').title() def __getitem__(self, item): return super().__getitem__(self._key(item)) def __setitem__(self, key, value): return super().__setitem__(self._key(key), value) def __delitem__(self, key): return super().__delitem__(self._key(key)) def __contains__(self, item): return super().__contains__(self._key(item)) @classmethod def _convert(cls, *args, **kwargs): return {cls._key(k): v for k, v in dict(*args, **kwargs).items() if isinstance(k, str)} def update(self, *args, **kwargs) -> None: super().update(self._convert(*args, **kwargs)) def encode(self) -> bytes: return ujson.dumps(self, ensure_ascii=False, escape_forward_slashes=False).encode('utf-8') @classmethod def decode(cls, headers: Bytes) -> 'Headers': try: headers = ujson.loads(headers) except ValueError: # + UnicodeDecodeError headers = None return cls(headers or {}) T_Headers: TypeAlias = Headers | dict[str]
25.056075
98
0.631481
300
2,681
5.37
0.356667
0.037244
0.014898
0.019863
0
0
0
0
0
0
0
0.000974
0.234241
2,681
106
99
25.292453
0.783731
0.032824
0
0.092105
0
0
0.058207
0
0
0
0
0
0
1
0.171053
false
0
0.092105
0.118421
0.447368
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
0
0
0
1
a3dad87fce4f18faf3a3d29b5cefbd7b89d614d5
384
py
Python
raven/utils/urlparse.py
MyCollege/raven
9447f3a55ae7703afe84c3493625e3c3fb700700
[ "BSD-3-Clause" ]
null
null
null
raven/utils/urlparse.py
MyCollege/raven
9447f3a55ae7703afe84c3493625e3c3fb700700
[ "BSD-3-Clause" ]
null
null
null
raven/utils/urlparse.py
MyCollege/raven
9447f3a55ae7703afe84c3493625e3c3fb700700
[ "BSD-3-Clause" ]
null
null
null
from __future__ import absolute_import try: import urlparse as _urlparse except ImportError: from urllib import parse as _urlparse def register_scheme(scheme): for method in filter(lambda s: s.startswith('uses_'), dir(_urlparse)): uses = getattr(_urlparse, method) if scheme not in uses: uses.append(scheme) urlparse = _urlparse.urlparse
22.588235
74
0.708333
48
384
5.416667
0.5625
0.076923
0
0
0
0
0
0
0
0
0
0
0.221354
384
16
75
24
0.869565
0
0
0
0
0
0.013021
0
0
0
0
0
0
1
0.090909
false
0
0.363636
0
0.454545
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
1
a3db35b8c7d191b6f652e750b697cd40a1dc6c0c
516
py
Python
setup.py
stjordanis/MONeT-1
98a5c7d149ca19c8c64069dbd8f27ce7f97bf3af
[ "MIT" ]
161
2020-10-28T02:21:50.000Z
2022-03-11T05:06:16.000Z
setup.py
stjordanis/MONeT-1
98a5c7d149ca19c8c64069dbd8f27ce7f97bf3af
[ "MIT" ]
4
2020-10-28T02:27:43.000Z
2021-03-31T00:04:43.000Z
setup.py
stjordanis/MONeT-1
98a5c7d149ca19c8c64069dbd8f27ce7f97bf3af
[ "MIT" ]
15
2020-10-28T02:32:12.000Z
2021-12-23T13:20:23.000Z
import setuptools setuptools.setup( name="monet_memory_optimized_training", version="0.0.1", description="Memory Optimized Network Training Framework", url="https://github.com/philkr/lowrank_conv", packages=setuptools.find_packages(include = ['monet', 'monet.*', 'models', 'checkmate', 'gist']), classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires='>=3.6', )
32.25
101
0.655039
54
516
6.148148
0.777778
0.090361
0
0
0
0
0
0
0
0
0
0.01432
0.187985
516
15
102
34.4
0.778043
0
0
0
0
0
0.503876
0.060078
0
0
0
0
0
1
0
true
0
0.071429
0
0.071429
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
0
0
0
0
0
1
a3dc8e80c4d30f101894ef231d725a510807944b
833
py
Python
handypackages/subscribe/migrations/0001_initial.py
roundium/handypackages
b8a0e4952644144b31168f9a4ac8e743933d87c7
[ "MIT" ]
1
2019-07-31T11:40:06.000Z
2019-07-31T11:40:06.000Z
handypackages/subscribe/migrations/0001_initial.py
roundium/handypackages
b8a0e4952644144b31168f9a4ac8e743933d87c7
[ "MIT" ]
10
2020-02-12T01:16:25.000Z
2021-06-10T18:42:24.000Z
handypackages/subscribe/migrations/0001_initial.py
roundium/handypackages
b8a0e4952644144b31168f9a4ac8e743933d87c7
[ "MIT" ]
1
2019-07-31T11:40:18.000Z
2019-07-31T11:40:18.000Z
# Generated by Django 2.2.1 on 2019-06-22 11:03 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='SubscribeModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('email', models.EmailField(db_index=True, max_length=255, unique=True, verbose_name='Email')), ('create_time', models.DateTimeField(auto_now_add=True, verbose_name='Subscribe Time')), ], options={ 'verbose_name': 'Subscribe Email', 'verbose_name_plural': 'Subscribe Emails', 'abstract': False, }, ), ]
29.75
114
0.57503
83
833
5.614458
0.626506
0.118026
0.064378
0
0
0
0
0
0
0
0
0.031034
0.303721
833
27
115
30.851852
0.772414
0.054022
0
0
1
0
0.156489
0
0
0
0
0
0
1
0
false
0
0.05
0
0.25
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
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
a3e04f191bacc2a7d80fcd1ad9bb0b6bdef01714
788
py
Python
1.py
zweed4u/dailycodingproblem
6e40eaad347e283f86a11adeff01c6426211a0be
[ "MIT" ]
null
null
null
1.py
zweed4u/dailycodingproblem
6e40eaad347e283f86a11adeff01c6426211a0be
[ "MIT" ]
null
null
null
1.py
zweed4u/dailycodingproblem
6e40eaad347e283f86a11adeff01c6426211a0be
[ "MIT" ]
null
null
null
#!/usr/bin/python3 """ Good morning! Here's your coding interview problem for today. This problem was recently asked by Google. Given a list of numbers and a number k, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. Bonus: Can you do this in one pass? """ def func(l, k): sums = [] for index, element in enumerate(l): print(f'Current element: {element}') if index == 0: # first element - need another print() continue for num in range(index): print(f'Appending {l[index]} + {l[num]}') sums.append(l[num] + l[index]) print() print(sums) return k in sums print(func([10, 15, 3, 7], 17))
26.266667
97
0.593909
124
788
3.774194
0.580645
0.017094
0.021368
0.025641
0
0
0
0
0
0
0
0.041145
0.290609
788
29
98
27.172414
0.796064
0.467005
0
0.142857
0
0
0.138686
0
0
0
0
0
0
1
0.071429
false
0
0
0
0.142857
0.428571
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
1
a3f0b2c627b66a9afed0141c901b2c8dc3a62a08
1,265
py
Python
peon/tests/test_project/test_file/test_function_def/test_functions/test_reflection_at_line.py
roch1990/peon
0e9e40956c05138c0820fe380b354fdd1fe95e01
[ "MIT" ]
32
2020-05-18T14:02:59.000Z
2022-02-06T15:00:12.000Z
peon/tests/test_project/test_file/test_function_def/test_functions/test_reflection_at_line.py
roch1990/peon
0e9e40956c05138c0820fe380b354fdd1fe95e01
[ "MIT" ]
42
2020-05-22T20:29:08.000Z
2021-03-10T21:24:23.000Z
peon/tests/test_project/test_file/test_function_def/test_functions/test_reflection_at_line.py
roch1990/peon
0e9e40956c05138c0820fe380b354fdd1fe95e01
[ "MIT" ]
4
2020-07-02T06:32:42.000Z
2022-01-24T22:46:02.000Z
import _ast from peon.src.project.file.function_def.function import FunctionLint class ReflectionAtLineFixture: empty_node = _ast.Pass is_instance_at_first_lvl = _ast.FunctionDef(id='isinstance', lineno=1) type_at_first_lvl = _ast.FunctionDef(id='type', lineno=1) is_instance_at_second_lvl = _ast.FunctionDef(body=[_ast.Expr(id='isinstance', lineno=2)], lineno=1) type_at_second_lvl = _ast.FunctionDef(body=[_ast.Expr(id='type', lineno=2)], lineno=1) def test_empty_node(): assert FunctionLint( definition=ReflectionAtLineFixture.empty_node, ).reflection_at_line() == tuple() def test_is_instance_at_first_lvl(): assert FunctionLint( definition=ReflectionAtLineFixture.is_instance_at_first_lvl, ).reflection_at_line() == (1,) def test_type_at_first_lvl(): assert FunctionLint( definition=ReflectionAtLineFixture.type_at_first_lvl, ).reflection_at_line() == (1,) def test_is_instance_at_second_lvl(): assert FunctionLint( definition=ReflectionAtLineFixture.is_instance_at_second_lvl, ).reflection_at_line() == (2,) def test_type_at_second_lvl(): assert FunctionLint( definition=ReflectionAtLineFixture.type_at_second_lvl, ).reflection_at_line() == (2,)
30.119048
103
0.746245
160
1,265
5.46875
0.225
0.068571
0.082286
0.291429
0.654857
0.601143
0.541714
0.313143
0.164571
0
0
0.009234
0.143874
1,265
41
104
30.853659
0.798707
0
0
0.321429
0
0
0.022134
0
0
0
0
0
0.178571
1
0.178571
false
0.035714
0.071429
0
0.464286
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
0
0
0
1
a3f0f192476289dad6988d88e198337f911d4da1
4,419
py
Python
db2_funcs.py
Nama/A.T.S.P.-Website
658db78da1b12c01ef9ead2dc44d1ecd97b178d8
[ "MIT" ]
4
2015-10-18T18:46:13.000Z
2019-11-16T02:34:05.000Z
db2_funcs.py
Adventure-Terraria-Server-Project/A.T.S.P.-Website
658db78da1b12c01ef9ead2dc44d1ecd97b178d8
[ "MIT" ]
null
null
null
db2_funcs.py
Adventure-Terraria-Server-Project/A.T.S.P.-Website
658db78da1b12c01ef9ead2dc44d1ecd97b178d8
[ "MIT" ]
2
2015-09-30T21:53:19.000Z
2019-03-22T07:59:49.000Z
############################################################################### # # '''Website Database-connection-related features''' # # # ############################################################################### import cymysql from conf import website_db from time import gmtime from time import strftime db_host = website_db.ip db_port = website_db.port db = website_db.db db_user = website_db.user db_pw = website_db.pw ############################################################################### # # '''Databse-connect and close''' # # # ############################################################################### def db_con(): conn = cymysql.connect(host=db_host, port=db_port, user=db_user, passwd=db_pw, db=db) cur = conn.cursor() return conn, cur def db_close(conn, cur): cur.close() conn.close() ############################################################################### # # '''Donation-Page data''' # # # ############################################################################### def donate_save(nick): conn, cur = db_con() time = strftime('%Y.%m.%d - %H:%M:%S', gmtime()) cur.execute('INSERT INTO `donate` (`time`, `user`) VALUES (%s, %s)', (time, nick)) conn.commit() db_close(conn, cur) def donate_read(): conn, cur = db_con() cur.execute('SELECT * FROM `donate` ORDER BY `time` DESC LIMIT 20') nicks = list() for r in cur.fetchall(): nicks.append([r[0], r[1]]) db_close(conn, cur) return nicks ############################################################################### # # '''Short-URL data''' # # # ############################################################################### def shorturl_save(surl, url): conn, cur = db_con() cur.execute('INSERT INTO `shorturls` (`surl`, `url`) VALUES (%s, %s)', (surl, url)) conn.commit() db_close(conn, cur) def shorturl_read(): conn, cur = db_con() cur.execute('SELECT * FROM `shorturls`') urls = list() for r in cur.fetchall(): urls.append([r[0], r[0], r[1]]) db_close(conn, cur) return urls ############################################################################### # # '''Old Worlds''' # # # ############################################################################### def get_old_worlds(item): conn, cur = db_con() sql = 'SELECT * FROM `oldworlds` ORDER BY `date` DESC LIMIT {0}, {1}'.format(item, 20) cur.execute(sql) worlds = cur.fetchall() db_close(conn, cur) return worlds ############################################################################### # # '''Server Backup-Size in Dash''' # # # ############################################################################### def backup_size(): conn, cur = db_con() dbtshock = [] tserver = [] htdocs = [] cur.execute('SELECT * FROM `backups`') for r in cur.fetchall(): if r[1] == 'db': dbtshock.append([r[0] * 1000, r[2]]) elif r[1] == 'tserver': tserver.append([r[0] * 1000, r[2]]) elif r[1] == 'htdocs': htdocs.append([r[0] * 1000, r[2]]) db_close(conn, cur) return (dbtshock, tserver, htdocs)
33.992308
90
0.296673
324
4,419
3.938272
0.268519
0.076803
0.060345
0.076803
0.273511
0.22884
0.167712
0.125392
0.125392
0
0
0.012021
0.397601
4,419
129
91
34.255814
0.467318
0.009957
0
0.261538
0
0
0.129266
0
0
0
0
0
0
1
0.123077
false
0.015385
0.061538
0
0.261538
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
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
1
a3fb5ed7db5f1e3f6fa910bcda6e0eacb2e1cb30
2,470
py
Python
backends/fortify/summarize-fortify.py
tautschnig/one-line-scan
24e1deedd595e3406eb8d5c69ff9629c5a87d0aa
[ "Apache-2.0" ]
16
2018-05-21T09:53:01.000Z
2022-02-15T08:48:11.000Z
backends/fortify/summarize-fortify.py
tautschnig/one-line-scan
24e1deedd595e3406eb8d5c69ff9629c5a87d0aa
[ "Apache-2.0" ]
6
2018-07-09T06:13:05.000Z
2020-11-11T14:49:35.000Z
backends/fortify/summarize-fortify.py
tautschnig/one-line-scan
24e1deedd595e3406eb8d5c69ff9629c5a87d0aa
[ "Apache-2.0" ]
5
2019-05-27T19:51:48.000Z
2021-12-14T13:04:49.000Z
#!/usr/bin/env python # # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license" file accompanying this file. This file is distributed # on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either # express or implied. See the License for the specific language governing # permissions and limitations under the License. # # Parse the report.html of Fortify and create an ASCII summary import os import sys from subprocess import call from xml.etree import ElementTree # print usage if len(sys.argv) != 2: print "usage summarizy-fortify.py LOGDIR" sys.exit(1) # get directory where the logs are placed logdir=sys.argv[1] # strip this part of the directory information of workdirectory = os.getcwd() + '/' # get the fortify report; first make it valid XML filename=logdir+'/log/report.html' call(['perl', '-p', '-i', '-e', 's#<((img|meta) [^>]+)>#<$1/>#', filename]) # make sure we can run this script multiple times on the same html file call(['perl', '-p', '-i', '-e', 's#//>#/>#', filename]) # parse the html file and jump to the last table data=ElementTree.parse(filename).getroot() table=data.find('.//table')[-1] # iterate over all rows and print their content in a more useable format for data in table.iter('tr'): # handle only the rows that contain results if len(data) != 4: continue # extract file information, convert absolute path into relative one location=data[2].find('a') # header does not have <a ...> if location is None: continue filename=location.get('href') filename=filename.replace('file://','') filename=filename.replace(workdirectory,'') severity=data[3].text if severity is None: severity=data[3].find('span').text # strip newline and space sequences problem=data[0].text.replace('\n','').replace('\r','') short=problem.replace(' ',' ') while len(short) < len(problem): problem=short short=problem.replace(' ',' ') column=ElementTree.tostring(data[2].findall("*")[0]).split(':')[2] printstring = filename + ':' + column.strip() + ', ' + \ severity.strip() + ', ' + \ problem if data[1].text is not None: printstring = printstring + ', ' + data[1].text print printstring
33.835616
77
0.681781
358
2,470
4.703911
0.494413
0.035629
0.010689
0.011876
0.014252
0.014252
0
0
0
0
0
0.009305
0.173279
2,470
72
78
34.305556
0.815377
0.466397
0
0.105263
0
0
0.118513
0
0
0
0
0
0
0
null
null
0
0.105263
null
null
0.105263
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
0
0
1
430006e2469bed3f7e4c977ba2de4f246799468c
1,714
py
Python
testsite/wsgi.py
stungkit/djaodjin-saas
93c8631509ffd5b0fb91283cd4a4aeaf9826e97e
[ "BSD-2-Clause" ]
null
null
null
testsite/wsgi.py
stungkit/djaodjin-saas
93c8631509ffd5b0fb91283cd4a4aeaf9826e97e
[ "BSD-2-Clause" ]
null
null
null
testsite/wsgi.py
stungkit/djaodjin-saas
93c8631509ffd5b0fb91283cd4a4aeaf9826e97e
[ "BSD-2-Clause" ]
null
null
null
""" WSGI config for testsite project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os, signal #pylint: disable=invalid-name def save_coverage(*args, **kwargs): #pylint:disable=unused-argument sys.stderr.write("saving coverage\n") cov.stop() cov.save() if os.getenv('DJANGO_COVERAGE'): import atexit, sys import coverage cov = coverage.coverage(data_file=os.path.join(os.getenv('DJANGO_COVERAGE'), ".coverage.%d" % os.getpid())) cov.start() atexit.register(save_coverage) try: signal.signal(signal.SIGTERM, save_coverage) except ValueError as e: # trapping signals does not work with manage # trying to do so fails with # ValueError: signal only works in main thread pass os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testsite.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application #pylint: disable=invalid-name application = get_wsgi_application()
34.979592
80
0.748541
239
1,714
5.309623
0.539749
0.082742
0.042553
0.037825
0
0
0
0
0
0
0
0
0.171529
1,714
48
81
35.708333
0.893662
0.596266
0
0
0
0
0.145185
0.032593
0
0
0
0
0
1
0.052632
false
0.052632
0.210526
0
0.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
1
0
0
0
0
0
1
4302245408f7928b493623fbaac5ca5daff6a97c
229
py
Python
kattis/Soda Slurper.py
jaredliw/python-question-bank
9c8c246623d8d171f875700b57772df0afcbdcdf
[ "MIT" ]
1
2021-04-08T07:49:15.000Z
2021-04-08T07:49:15.000Z
kattis/Soda Slurper.py
jaredliw/leetcode-solutions
9c8c246623d8d171f875700b57772df0afcbdcdf
[ "MIT" ]
null
null
null
kattis/Soda Slurper.py
jaredliw/leetcode-solutions
9c8c246623d8d171f875700b57772df0afcbdcdf
[ "MIT" ]
1
2022-01-23T02:12:24.000Z
2022-01-23T02:12:24.000Z
# CPU: 0.06 s possessed, found, condition = map(int, input().split()) possessed += found count = 0 while possessed >= condition: div, mod = divmod(possessed, condition) count += div possessed = div + mod print(count)
22.9
55
0.663755
30
229
5.066667
0.566667
0.184211
0
0
0
0
0
0
0
0
0
0.021858
0.200873
229
9
56
25.444444
0.808743
0.048035
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
0.125
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
0
0
1
4304c73b6843ca7119c4f1f8d49418f514b2fb58
9,413
py
Python
submodules/hal/analysis/constraintTurnover/turnoverModel.py
pbasting/cactus
833d8ca015deecdfa5d0aca01211632cdaca9e58
[ "MIT-0" ]
null
null
null
submodules/hal/analysis/constraintTurnover/turnoverModel.py
pbasting/cactus
833d8ca015deecdfa5d0aca01211632cdaca9e58
[ "MIT-0" ]
null
null
null
submodules/hal/analysis/constraintTurnover/turnoverModel.py
pbasting/cactus
833d8ca015deecdfa5d0aca01211632cdaca9e58
[ "MIT-0" ]
null
null
null
#!/usr/bin/env python #Copyright (C) 2013 by Glenn Hickey # #Released under the MIT license, see LICENSE.txt #!/usr/bin/env python """This is a two-state continuous time markov model: 0: unconstratined. 1: constrained. There are two transition rates to go between states. lossRate: 1->0 and gainRate: 0->1. Probability Matrix and Stationary Distribution are computed from the two rates and a time t. (see pdf) """ import argparse import os import sys import copy import random import math from collections import defaultdict import numpy as np import subprocess import tempfile #constrained is always 1. unconstrained is always 0 # compute probability matrix from rates and time. def computePMatrix(lossRate, gainRate, t): assert t >= 0 assert lossRate >= 0 assert gainRate >= 0 x = gainRate / lossRate y = gainRate + lossRate eyt = math.exp(-y * t) c = 1.0 / (x + 1.0) P = [ [c * (1.0 + x * eyt), c * (x - x * eyt)], [c * (1.0 - eyt), c * (x + eyt)] ] assert math.fabs(P[0][0] + P[0][1] - 1.0) < 0.00001 assert math.fabs(P[1][0] + P[1][1] - 1.0) < 0.00001 return P # compute stationary distribution from rates and time def computeStationaryDist(lossRate, gainRate, t): assert t >= 0 assert lossRate >= 0 assert gainRate >= 0 x = gainRate / lossRate y = gainRate + lossRate eyt = math.exp(-y * t) pi0 = (eyt - 1.0) / ( x * eyt + eyt - x - 1.0) pi1 = 1. - pi0 # assert pi0 * ( ((1.0 + x * eyt) / (x + 1.0)) -1.0) + (1.0 - pi0) * ((1.0 - eyt) / (x + 1.0)) == 0 assert pi0 >= 0 and pi0 <= 1.0 assert pi1 >= 0 and pi1 <= 1.0 return [pi0, pi1] # compute the absolute difference between the values of the # probability matrix and stationary distribution computed from a given # rate, and a set of absolute values of the same. This is a sum of four # differences, 2 for the distribution, 4 for the matrix. def diffOnePoint(lossRate, gainRate, piEst, Pest, t): P = computePMatrix(lossRate, gainRate, t) pi = computeStationaryDist(lossRate, gainRate, t) d = math.fabs(pi[0] - piEst[0]) d += math.fabs(pi[1] - piEst[1]) d += math.fabs(P[0][0] - Pest[0][0]) d += math.fabs(P[0][1] - Pest[0][1]) d += math.fabs(P[1][0] - Pest[1][0]) d += math.fabs(P[1][1] - Pest[1][1]) return d # compute the sum of squared differences for a pair of rate parameters # and a set of data points. Each data point is a 3 tuple: # (1x2 stationary distribution pi, 2x2 probability matrix P, time t) def diffSqManyPoints(lossRate, gainRate, estVals): dtot = 0 for estVal in estVals: piEst = estVal[0] Pest = estVal[1] t = estVal[2] d = diffOnePoint(lossRate, gainRate, piEst, Pest, t) dtot += d * d return dtot # use really simple gradient descent type approach to find rate values that # minimize the squared difference with some data points. Each data point # is a 3-tuple as described above. The gradient descent iteratres over # maxIt iterations. Each iteration it tries to add and subtract delta from # the current best rates (4 combinations: add delta to gain, add delta to loss, # subtract delta from gain, subtract delta from loss). The best pair # of rate parameters are returned, along with their square difference from # the data. def gradDescent(lrStart, grStart, estVals, maxIt, delta): bestDiff = diffSqManyPoints(lrStart, grStart, estVals) bestLr = lrStart bestGr = grStart lastChangeIterator = 0 for i in range(maxIt): lr = bestLr gr = bestGr dpl = diffSqManyPoints(lr + delta, gr, estVals) rval = random.randint(0, 3) if rval == 0 and dpl < bestDiff: bestDiff = dpl bestLr = lr + delta bestGr = gr lastChangeIterator = i dpg = diffSqManyPoints(lr, gr + delta, estVals) if rval == 1 and dpg < bestDiff: bestDiff = dpg bestLr = lr bestGr = gr + delta lastChangeIterator = i if rval == 2 and lr > delta: dml = diffSqManyPoints(lr - delta, gr, estVals) if dml < bestDiff: bestDiff = dml bestLr = lr - delta bestGr = gr lastChangeIterator = i if rval == 3 and gr > delta: dmg = diffSqManyPoints(lr, gr - delta, estVals) if dmg < bestDiff: bestDiff = dmg bestLr = lr bestGr = gr - delta lastChangeIterator = i # # Hack: if nothing happened, instead of returning, try adding # 10x the step value and seeing what happens. # if i == lastChangeIterator + 8: boostDelta = delta * 10. dpl = diffSqManyPoints(lr + boostDelta, gr, estVals) if rval == 0 and dpl < bestDiff: bestDiff = dpl bestLr = lr + boostDelta bestGr = gr lastChangeIterator = i dpg = diffSqManyPoints(lr, gr + boostDelta, estVals) if rval == 1 and dpg < bestDiff: bestDiff = dpg bestLr = lr bestGr = gr + boostDelta lastChangeIterator = i if rval == 2 and lr > boostDelta: dml = diffSqManyPoints(lr - boostDelta, gr, estVals) if dml < bestDiff: bestDiff = dml bestLr = lr - boostDelta bestGr = gr lastChangeIterator = i if rval == 3 and gr > boostDelta: dmg = diffSqManyPoints(lr, gr - boostDelta, estVals) if dmg < bestDiff: bestDiff = dmg bestLr = lr bestGr = gr - boostDelta lastChangeIterator = i # we tried the 10x and now give up elif i > lastChangeIterator + 8: break return (bestLr, bestGr, bestDiff) # add some noise to parameters def addNoise(P, pi, maxNoise): d = random.uniform(-maxNoise, maxNoise) P[0][0] += d P[0][1] -= d d = random.uniform(-maxNoise, maxNoise) P[1][0] += d P[1][1] -= d d = random.uniform(-maxNoise, maxNoise) pi[0] += d pi[1] -= d # generate some random "estimated" parameters for values of t # within a given range. random noise is added as specifed by maxNoise def generateData(n, tRange, lossRate, gainRate, maxNoise): genVals = [] for i in range(n): t = random.uniform(tRange[0], tRange[1]) P = computePMatrix(lossRate, gainRate, t) pi = computeStationaryDist(lossRate, gainRate, t) addNoise(P, pi, maxNoise) genVals.append((pi, P, t)) return genVals def main(argv=None): if argv is None: argv = sys.argv parser = argparse.ArgumentParser() parser.add_argument("N", type=int, help="number of simulated data sets") parser.add_argument("size", type=int, help="number of simulated data points per set") parser.add_argument("minRate", type=float, help="minimum true rate") parser.add_argument("maxRate", type=float, help="maximum true rate") parser.add_argument("minT", type=float, help="minimum true t") parser.add_argument("maxT", type=float, help="maximum true t") parser.add_argument("--maxIt", type=int, default=1000, help="number of iterations for gradient descent") parser.add_argument("--step", type=float, default=0.001, help="gradient descent step") parser.add_argument("--noise", type=float, default=0, help="max amount of noise to add") parser.add_argument("--retries", type=int, default=5, help="number of gradient descents to run") args = parser.parse_args() assert (args.N > 0 and args.size > 0 and args.minRate > 0 and args.maxRate > 0 and args.minT > 0 and args.maxT > 0 and args.maxIt > 0 and args.step > 0 and args.noise >= 0 and args.retries > 1) for n in range(args.N): lrTrue = random.uniform(args.minRate, args.maxRate) grTrue = random.uniform(args.minRate, args.maxRate) genVals = generateData(args.size, (args.minT, args.maxT), lrTrue, grTrue, args.noise) bestLr, bestGr, bestDiff = (0, 0, 1000000) for retry in range(args.retries): lrStart = random.uniform(0.0001, 1.0) grStart = random.uniform(0.0001, 1.0) (lrEst, grEst, diff) = gradDescent(lrStart, grStart, genVals, args.maxIt, args.step) if diff < bestDiff: bestLr, bestGr, bestDiff = (lrEst, grEst, diff) print "Truth=(%f,%f), Start=(%f,%f) Est=(%f,%f), dsq=%f" % ( lrTrue, grTrue, lrStart, grStart, bestLr, bestGr, (lrTrue - bestLr) * (lrTrue - bestLr) + (grTrue - bestGr) * (grTrue - bestGr)) print "--------------------------------" if __name__ == "__main__": sys.exit(main())
38.577869
282
0.566769
1,185
9,413
4.486076
0.211814
0.008653
0.031979
0.007524
0.382995
0.300038
0.233634
0.179458
0.160647
0.11851
0
0.030332
0.327526
9,413
243
283
38.736626
0.809479
0.17359
0
0.271277
0
0.005319
0.053083
0.00429
0
0
0
0
0.058511
0
null
null
0
0.053191
null
null
0.010638
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
0
0
1
43064e88b72bbd60715e819272f83d07fbf6fa68
322
py
Python
feed/migrations/0002_remove_player_finished_decks.py
kubapi/hater
fe4ef653e169143b9ea8cc17494e8e35b2a7bc76
[ "MIT" ]
null
null
null
feed/migrations/0002_remove_player_finished_decks.py
kubapi/hater
fe4ef653e169143b9ea8cc17494e8e35b2a7bc76
[ "MIT" ]
null
null
null
feed/migrations/0002_remove_player_finished_decks.py
kubapi/hater
fe4ef653e169143b9ea8cc17494e8e35b2a7bc76
[ "MIT" ]
null
null
null
# Generated by Django 3.2.3 on 2021-06-13 19:58 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('feed', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='player', name='finished_decks', ), ]
17.888889
47
0.583851
34
322
5.441176
0.823529
0
0
0
0
0
0
0
0
0
0
0.084444
0.301242
322
17
48
18.941176
0.737778
0.139752
0
0
1
0
0.130909
0
0
0
0
0
0
1
0
false
0
0.090909
0
0.363636
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
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
4313de468396c7f2ca9e8be49eccd525b21cb61b
309
py
Python
test123.py
umousesonic/zinc
9e170269d3b209a80ac79d5850894ddc1d95c62f
[ "BSD-3-Clause" ]
null
null
null
test123.py
umousesonic/zinc
9e170269d3b209a80ac79d5850894ddc1d95c62f
[ "BSD-3-Clause" ]
null
null
null
test123.py
umousesonic/zinc
9e170269d3b209a80ac79d5850894ddc1d95c62f
[ "BSD-3-Clause" ]
null
null
null
from runner import runner if __name__ == '__main__': r = runner() p = 'public class main{public static void main (String[] args){' \ 'public String StudentAnswer(String myInput){' \ 'return "myOutput"; ' \ '}System.out.println("hello world!");}}' print (r.sendCode(p, ''))
34.333333
70
0.601942
35
309
5.085714
0.714286
0
0
0
0
0
0
0
0
0
0
0
0.23301
309
9
71
34.333333
0.751055
0
0
0
0
0
0.53871
0.083871
0
0
0
0
0
1
0
false
0
0.125
0
0.125
0.25
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
0
0
1
4318e19519ef3b4ec8fbfd551e4ad75ec635df69
9,102
py
Python
src/transbigdata/CoordinatesConverter.py
cirno1w/transport
f088b4111992dd5ec6371db71cf1d26689cf8c26
[ "BSD-3-Clause" ]
1
2022-03-06T00:15:19.000Z
2022-03-06T00:15:19.000Z
src/transbigdata/CoordinatesConverter.py
anitagraser/transbigdata
0eb972c78f9154c0a3f780f197ef9af406b2bb71
[ "BSD-3-Clause" ]
null
null
null
src/transbigdata/CoordinatesConverter.py
anitagraser/transbigdata
0eb972c78f9154c0a3f780f197ef9af406b2bb71
[ "BSD-3-Clause" ]
null
null
null
import numpy as np x_pi = 3.14159265358979324 * 3000.0 / 180.0 pi = 3.1415926535897932384626 a = 6378245.0 ee = 0.00669342162296594323 def gcj02tobd09(lng, lat): """ Convert coordinates from GCJ02 to BD09 Parameters ------- lng : Series or number Longitude lat : Series or number Latitude return ------- lng : Series or number Longitude (Converted) lat : Series or number Latitude (Converted) """ try: lng = lng.astype(float) lat = lat.astype(float) except: lng = float(lng) lat = float(lat) z = np.sqrt(lng * lng + lat * lat) + 0.00002 * np.sin(lat * x_pi) theta = np.arctan2(lat, lng) + 0.000003 * np.cos(lng * x_pi) bd_lng = z * np.cos(theta) + 0.0065 bd_lat = z * np.sin(theta) + 0.006 return bd_lng, bd_lat def bd09togcj02(bd_lon, bd_lat): """ Convert coordinates from BD09 to GCJ02 Parameters ------- lng : Series or number Longitude lat : Series or number Latitude return ------- lng : Series or number Longitude (Converted) lat : Series or number Latitude (Converted) """ try: bd_lon = bd_lon.astype(float) bd_lat = bd_lat.astype(float) except: bd_lon = float(bd_lon) bd_lat = float(bd_lat) x = bd_lon - 0.0065 y = bd_lat - 0.006 z = np.sqrt(x * x + y * y) - 0.00002 * np.sin(y * x_pi) theta = np.arctan2(y, x) - 0.000003 * np.cos(x * x_pi) gg_lng = z * np.cos(theta) gg_lat = z * np.sin(theta) return gg_lng, gg_lat def wgs84togcj02(lng, lat): """ Convert coordinates from WGS84 to GCJ02 Parameters ------- lng : Series or number Longitude lat : Series or number Latitude return ------- lng : Series or number Longitude (Converted) lat : Series or number Latitude (Converted) """ try: lng = lng.astype(float) lat = lat.astype(float) except: lng = float(lng) lat = float(lat) dlat = transformlat(lng - 105.0, lat - 35.0) dlng = transformlng(lng - 105.0, lat - 35.0) radlat = lat / 180.0 * pi magic = np.sin(radlat) magic = 1 - ee * magic * magic sqrtmagic = np.sqrt(magic) dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi) dlng = (dlng * 180.0) / (a / sqrtmagic * np.cos(radlat) * pi) mglat = lat + dlat mglng = lng + dlng return mglng, mglat def gcj02towgs84(lng, lat): """ Convert coordinates from GCJ02 to WGS84 Parameters ------- lng : Series or number Longitude lat : Series or number Latitude return ------- lng : Series or number Longitude (Converted) lat : Series or number Latitude (Converted) """ try: lng = lng.astype(float) lat = lat.astype(float) except: lng = float(lng) lat = float(lat) dlat = transformlat(lng - 105.0, lat - 35.0) dlng = transformlng(lng - 105.0, lat - 35.0) radlat = lat / 180.0 * pi magic = np.sin(radlat) magic = 1 - ee * magic * magic sqrtmagic = np.sqrt(magic) dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi) dlng = (dlng * 180.0) / (a / sqrtmagic * np.cos(radlat) * pi) mglat = lat + dlat mglng = lng + dlng return lng * 2 - mglng, lat * 2 - mglat def wgs84tobd09(lon,lat): """ Convert coordinates from WGS84 to BD09 Parameters ------- lng : Series or number Longitude lat : Series or number Latitude return ------- lng : Series or number Longitude (Converted) lat : Series or number Latitude (Converted) """ try: lon = lon.astype(float) lat = lat.astype(float) except: lon = float(lon) lat = float(lat) lon,lat = wgs84togcj02(lon,lat) lon,lat = gcj02tobd09(lon,lat) return lon,lat def bd09towgs84(lon,lat): """ Convert coordinates from BD09 to WGS84 Parameters ------- lng : Series or number Longitude lat : Series or number Latitude return ------- lng : Series or number Longitude (Converted) lat : Series or number Latitude (Converted) """ try: lon = lon.astype(float) lat = lat.astype(float) except: lon = float(lon) lat = float(lat) lon,lat = bd09togcj02(lon,lat) lon,lat = gcj02towgs84(lon,lat) return lon,lat def bd09mctobd09(x,y): """ Convert coordinates from BD09MC to BD09 Parameters ------- x : Series or number x coordinates y : Series or number y coordinates return ------- lng : Series or number Longitude (Converted) lat : Series or number Latitude (Converted) """ MCBAND = [12890594.86, 8362377.87, 5591021, 3481989.83, 1678043.12, 0] MC2LL = [ [1.410526172116255e-8, 0.00000898305509648872, -1.9939833816331, 200.9824383106796, -187.2403703815547, 91.6087516669843, -23.38765649603339, 2.57121317296198, -0.03801003308653, 17337981.2], [-7.435856389565537e-9, 0.000008983055097726239, -0.78625201886289, 96.32687599759846, -1.85204757529826, -59.36935905485877, 47.40033549296737, -16.50741931063887, 2.28786674699375, 10260144.86], [-3.030883460898826e-8, 0.00000898305509983578, 0.30071316287616, 59.74293618442277, 7.357984074871, -25.38371002664745, 13.45380521110908, -3.29883767235584, 0.32710905363475, 6856817.37], [-1.981981304930552e-8, 0.000008983055099779535, 0.03278182852591, 40.31678527705744, 0.65659298677277, -4.44255534477492, 0.85341911805263, 0.12923347998204, -0.04625736007561, 4482777.06], [3.09191371068437e-9, 0.000008983055096812155, 0.00006995724062, 23.10934304144901, -0.00023663490511, -0.6321817810242, -0.00663494467273, 0.03430082397953, -0.00466043876332, 2555164.4], [2.890871144776878e-9, 0.000008983055095805407, -3.068298e-8, 7.47137025468032, -0.00000353937994, -0.02145144861037, -0.00001234426596, 0.00010322952773, -0.00000323890364, 826088.5] ] y1 = y.iloc[0] for cD in range(len(MCBAND)): if y1 >= MCBAND[cD]: cE = MC2LL[cD] break cD = cE T = cD[0] + cD[1] * np.abs(x); cB = np.abs(y) / cD[9] cE = cD[2] + cD[3] * cB + cD[4] * cB * cB +\ cD[5] * cB * cB * cB + cD[6] * cB * cB * cB * cB +\ cD[7] * cB * cB * cB * cB * cB +\ cD[8] * cB * cB * cB * cB * cB * cB return T,cE def transformlat(lng, lat): ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + \ 0.1 * lng * lat + 0.2 * np.sqrt(np.fabs(lng)) ret += (20.0 * np.sin(6.0 * lng * pi) + 20.0 * np.sin(2.0 * lng * pi)) * 2.0 / 3.0 ret += (20.0 * np.sin(lat * pi) + 40.0 * np.sin(lat / 3.0 * pi)) * 2.0 / 3.0 ret += (160.0 * np.sin(lat / 12.0 * pi) + 320 * np.sin(lat * pi / 30.0)) * 2.0 / 3.0 return ret def transformlng(lng, lat): import numpy as np ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + \ 0.1 * lng * lat + 0.1 * np.sqrt(np.abs(lng)) ret += (20.0 * np.sin(6.0 * lng * pi) + 20.0 * np.sin(2.0 * lng * pi)) * 2.0 / 3.0 ret += (20.0 * np.sin(lng * pi) + 40.0 * np.sin(lng / 3.0 * pi)) * 2.0 / 3.0 ret += (150.0 * np.sin(lng / 12.0 * pi) + 300.0 * np.sin(lng / 30.0 * pi)) * 2.0 / 3.0 return ret def getdistance(lon1, lat1, lon2, lat2): ''' Input the origin/destination location in the sequence of [lon1, lat1, lon2, lat2] (in decimal) from DataFrame. The output is the distance (m). Parameters ------- lon1 : Series or number Start longitude lat1 : Series or number Start latitude lon2 : Series or number End longitude lat2 : Series or number End latitude return ------- distance : Series or number The distance ''' try: lon1 = lon1.astype(float) lat1 = lat1.astype(float) lon2 = lon2.astype(float) lat2 = lat2.astype(float) except: lon1 = float(lon1) lat1 = float(lat1) lon2 = float(lon2) lat2 = float(lat2) lon1, lat1, lon2, lat2 = map(lambda r:r*pi/180, [lon1, lat1, lon2, lat2]) dlon = lon2 - lon1 dlat = lat2 - lat1 a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2)**2 c = 2 * np.arcsin(a**0.5) r = 6371 # 地球平均半径,单位为公里 return c * r * 1000 def transform_shape(gdf,method): ''' Convert coordinates of all data. The input is the geographic elements’ DataFrame. Parameters ------- gdf : GeoDataFrame Geographic elements method : function The coordinate converting function return ------- gdf : GeoDataFrame The result of converting ''' from shapely.ops import transform gdf1 = gdf.copy() gdf1['geometry'] = gdf1['geometry'].apply(lambda r:transform(method, r)) return gdf1
28.267081
202
0.568556
1,216
9,102
4.234375
0.192434
0.051272
0.089726
0.042921
0.441833
0.408623
0.376966
0.357934
0.353661
0.353661
0
0.219756
0.297078
9,102
322
203
28.267081
0.585027
0.263349
0
0.415584
0
0
0.002607
0
0
0
0
0
0
1
0.071429
false
0
0.019481
0
0.162338
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
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
431a5970e46f202baf11c026a61fe4077fcce70d
8,343
py
Python
cloudify_rest_client/exceptions.py
aleixsanchis/cloudify-rest-client
6acaadee8286ab647465824d3c8e13d4c43ca9ba
[ "Apache-2.0" ]
null
null
null
cloudify_rest_client/exceptions.py
aleixsanchis/cloudify-rest-client
6acaadee8286ab647465824d3c8e13d4c43ca9ba
[ "Apache-2.0" ]
null
null
null
cloudify_rest_client/exceptions.py
aleixsanchis/cloudify-rest-client
6acaadee8286ab647465824d3c8e13d4c43ca9ba
[ "Apache-2.0" ]
null
null
null
######## # Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # * See the License for the specific language governing permissions and # * limitations under the License. class CloudifyClientError(Exception): def __init__(self, message, server_traceback=None, status_code=-1, error_code=None, response=None): super(CloudifyClientError, self).__init__(message) self.status_code = status_code self.error_code = error_code self.server_traceback = server_traceback self.response = response self.message = message def __str__(self): if self.status_code != -1: formatted_error = '{0}: {1}'.format(self.status_code, self.message) return formatted_error return self.message class DeploymentEnvironmentCreationInProgressError(CloudifyClientError): """ Raised when there's attempt to execute a deployment workflow and deployment environment creation workflow execution is still running. In such a case, workflow execution should be retried after a reasonable time or after the execution of deployment environment creation workflow has terminated. """ ERROR_CODE = 'deployment_environment_creation_in_progress_error' class DeploymentEnvironmentCreationPendingError(CloudifyClientError): """ Raised when there's attempt to execute a deployment workflow and deployment environment creation workflow execution is pending. In such a case, workflow execution should be retried after a reasonable time or after the execution of deployment environment creation workflow has terminated. """ ERROR_CODE = 'deployment_environment_creation_pending_error' class IllegalExecutionParametersError(CloudifyClientError): """ Raised when an attempt to execute a workflow with wrong/missing parameters has been made. """ ERROR_CODE = 'illegal_execution_parameters_error' class NoSuchIncludeFieldError(CloudifyClientError): """ Raised when an _include query parameter contains a field which does not exist for the queried data model. """ ERROR_CODE = 'no_such_include_field_error' class MissingRequiredDeploymentInputError(CloudifyClientError): """ Raised when a required deployment input was not specified on deployment creation. """ ERROR_CODE = 'missing_required_deployment_input_error' class UnknownDeploymentInputError(CloudifyClientError): """ Raised when an unexpected input was specified on deployment creation. """ ERROR_CODE = 'unknown_deployment_input_error' class UnknownDeploymentSecretError(CloudifyClientError): """ Raised when a required secret was not found on deployment creation. """ ERROR_CODE = 'unknown_deployment_secret_error' class UnsupportedDeploymentGetSecretError(CloudifyClientError): """ Raised when an unsupported get_secret intrinsic function appears in the blueprint on deployment creation. """ ERROR_CODE = 'unsupported_deployment_get_secret_error' class FunctionsEvaluationError(CloudifyClientError): """ Raised when function evaluation failed. """ ERROR_CODE = 'functions_evaluation_error' class UnknownModificationStageError(CloudifyClientError): """ Raised when an unknown modification stage was provided. """ ERROR_CODE = 'unknown_modification_stage_error' class ExistingStartedDeploymentModificationError(CloudifyClientError): """ Raised when a deployment modification start is attempted while another deployment modification is currently started """ ERROR_CODE = 'existing_started_deployment_modification_error' class DeploymentModificationAlreadyEndedError(CloudifyClientError): """ Raised when a deployment modification finish/rollback is attempted on a deployment modification that has already been finished/rolledback """ ERROR_CODE = 'deployment_modification_already_ended_error' class UserUnauthorizedError(CloudifyClientError): """ Raised when a call has been made to a secured resource with an unauthorized user (no credentials / bad credentials) """ ERROR_CODE = 'unauthorized_error' class ForbiddenError(CloudifyClientError): """ Raised when a call has been made by a user that is not permitted to perform it """ ERROR_CODE = 'forbidden_error' class PluginInUseError(CloudifyClientError): """ Raised if a central deployment agent plugin deletion is attempted and at least one deployment is currently using this plugin. """ ERROR_CODE = 'plugin_in_use' class PluginInstallationError(CloudifyClientError): """ Raised if a central deployment agent plugin installation fails. """ ERROR_CODE = 'plugin_installation_error' class PluginInstallationTimeout(CloudifyClientError): """ Raised if a central deployment agent plugin installation times out. """ ERROR_CODE = 'plugin_installation_timeout' class MaintenanceModeActiveError(CloudifyClientError): """ Raised when a call has been blocked due to maintenance mode being active. """ ERROR_CODE = 'maintenance_mode_active' def __str__(self): return self.message class MaintenanceModeActivatingError(CloudifyClientError): """ Raised when a call has been blocked while maintenance mode is activating. """ ERROR_CODE = 'entering_maintenance_mode' def __str__(self): return self.message class NotModifiedError(CloudifyClientError): """ Raised when a 304 not modified error was returned """ ERROR_CODE = 'not_modified' def __str__(self): return self.message class InvalidExecutionUpdateStatus(CloudifyClientError): """ Raised when execution update failed do to invalid status update """ ERROR_CODE = 'invalid_exception_status_update' class NotClusterMaster(CloudifyClientError): """ Raised when the request was served by a manager that is not the master node of a manager cluster. The client should query for the cluster status to learn the master's address, and retry the request. If the client stores the server address, it should update the storage with the new master node address. """ ERROR_CODE = 'not_cluster_master' class RemovedFromCluster(CloudifyClientError): """ Raised when attempting to contact a manager that was removed from a cluster. The client should retry the request with another manager in the cluster. If the client stores the server address, it should remove this node's address from storage. """ ERROR_CODE = 'removed_from_cluster' class DeploymentPluginNotFound(CloudifyClientError): """ Raised when a plugin is listed in the blueprint but is not installed on the manager. """ ERROR_CODE = 'deployment_plugin_not_found' ERROR_MAPPING = dict([ (error.ERROR_CODE, error) for error in [ DeploymentEnvironmentCreationInProgressError, DeploymentEnvironmentCreationPendingError, IllegalExecutionParametersError, NoSuchIncludeFieldError, MissingRequiredDeploymentInputError, UnknownDeploymentInputError, UnknownDeploymentSecretError, UnsupportedDeploymentGetSecretError, FunctionsEvaluationError, UnknownModificationStageError, ExistingStartedDeploymentModificationError, DeploymentModificationAlreadyEndedError, UserUnauthorizedError, ForbiddenError, MaintenanceModeActiveError, MaintenanceModeActivatingError, NotModifiedError, InvalidExecutionUpdateStatus, PluginInUseError, PluginInstallationError, PluginInstallationTimeout, NotClusterMaster, RemovedFromCluster, DeploymentPluginNotFound]])
31.364662
79
0.737744
869
8,343
6.932106
0.286536
0.041833
0.101096
0.049801
0.247344
0.229914
0.204847
0.173639
0.133466
0.097278
0
0.002261
0.204842
8,343
265
80
31.483019
0.905788
0.408366
0
0.084211
0
0
0.158084
0.134698
0
0
0
0
0
1
0.052632
false
0
0
0.031579
0.621053
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
431a7feaee1aa406c7c2670e03999a74240a7466
475
py
Python
api/error_handler.py
chuo06/palindrome
57660301390d7b2b05780e1f6ab0343e43726619
[ "MIT" ]
null
null
null
api/error_handler.py
chuo06/palindrome
57660301390d7b2b05780e1f6ab0343e43726619
[ "MIT" ]
1
2015-10-22T16:56:55.000Z
2015-10-22T16:56:55.000Z
api/error_handler.py
chuo06/palindrome
57660301390d7b2b05780e1f6ab0343e43726619
[ "MIT" ]
null
null
null
from functools import wraps from werkzeug.exceptions import HTTPException from api.exceptions import MessageNotFound def api_error_handler(func): @wraps(func) def handle_errors(*args, **kwargs): try: return func(*args, **kwargs) except MessageNotFound as e: return e.message, 404 except HTTPException: raise except Exception: return "API Internal error", 500 return handle_errors
25
45
0.650526
52
475
5.865385
0.538462
0.104918
0
0
0
0
0
0
0
0
0
0.017699
0.286316
475
18
46
26.388889
0.882006
0
0
0
0
0
0.037895
0
0
0
0
0
0
1
0.133333
false
0
0.2
0
0.6
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
431a878ee70ba62b9e15ce81300906f432dc9b82
406
py
Python
src/nile/core/run.py
kootsZhin/nile
5b685158c06418a126229cfbcaeaaf78a38cd8a0
[ "MIT" ]
121
2021-10-30T08:42:44.000Z
2022-03-31T13:17:58.000Z
src/nile/core/run.py
kootsZhin/nile
5b685158c06418a126229cfbcaeaaf78a38cd8a0
[ "MIT" ]
56
2021-10-31T16:45:06.000Z
2022-03-31T04:41:08.000Z
src/nile/core/run.py
kootsZhin/nile
5b685158c06418a126229cfbcaeaaf78a38cd8a0
[ "MIT" ]
22
2021-11-18T11:24:56.000Z
2022-03-30T08:15:18.000Z
"""Command to run Nile scripts.""" import logging from importlib.machinery import SourceFileLoader from nile.nre import NileRuntimeEnvironment def run(path, network): """Run nile scripts passing on the NRE object.""" logger = logging.getLogger() logger.disabled = True script = SourceFileLoader("script", path).load_module() nre = NileRuntimeEnvironment(network) script.run(nre)
27.066667
59
0.73399
47
406
6.319149
0.574468
0.047138
0.094276
0
0
0
0
0
0
0
0
0
0.165025
406
14
60
29
0.876106
0.17734
0
0
0
0
0.018576
0
0
0
0
0
0
1
0.111111
false
0
0.333333
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
0
0
0
1
0
0
0
0
1
431ad1cf3cfa9d05b69ae287dc97e25b7fff4c83
548
py
Python
Python/Basic Data Types/Lists/Solution.py
PawarAditi/HackerRank
fcd9d1450ee293372ce5f1d4a3b7284ecf472657
[ "MIT" ]
219
2018-06-17T19:47:22.000Z
2022-03-27T15:28:56.000Z
Python/Basic Data Types/Lists/Solution.py
PawarAditi/HackerRank
fcd9d1450ee293372ce5f1d4a3b7284ecf472657
[ "MIT" ]
2
2020-08-12T16:47:41.000Z
2020-12-15T17:05:57.000Z
Python/Basic Data Types/Lists/Solution.py
PawarAditi/HackerRank
fcd9d1450ee293372ce5f1d4a3b7284ecf472657
[ "MIT" ]
182
2018-12-12T21:36:50.000Z
2022-03-26T17:49:51.000Z
array = [] for _ in range(int(input())): command = input().strip().split(" ") cmd_type = command[0] if (cmd_type == "print"): print(array) elif (cmd_type == "sort"): array.sort() elif (cmd_type == "reverse"): array.reverse() elif (cmd_type == "pop"): array.pop() elif (cmd_type == "remove"): array.remove(int(command[1])) elif (cmd_type == "append"): array.append(int(command[1])) elif (cmd_type == "insert"): array.insert(int(command[1]), int(command[2]))
30.444444
54
0.541971
68
548
4.235294
0.338235
0.194444
0.229167
0.104167
0.152778
0.152778
0
0
0
0
0
0.012285
0.257299
548
18
54
30.444444
0.695332
0
0
0
0
0
0.069217
0
0
0
0
0
0
1
0
false
0
0
0
0
0.111111
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
0
0
0
0
0
0
0
0
1
431c1fde6c2d30474384ca5aeeb0ee0eb0db4a71
5,096
py
Python
mundiapi/models/update_plan_request.py
hugocpolos/MundiAPI-PYTHON
164545cc58bf18c946d5456e9ba4d55a378a339a
[ "MIT" ]
10
2017-08-30T15:53:00.000Z
2021-02-11T18:06:56.000Z
mundiapi/models/update_plan_request.py
hugocpolos/MundiAPI-PYTHON
164545cc58bf18c946d5456e9ba4d55a378a339a
[ "MIT" ]
4
2018-05-05T15:15:09.000Z
2021-12-22T00:52:41.000Z
mundiapi/models/update_plan_request.py
hugocpolos/MundiAPI-PYTHON
164545cc58bf18c946d5456e9ba4d55a378a339a
[ "MIT" ]
7
2017-04-27T13:46:52.000Z
2021-04-14T13:44:23.000Z
# -*- coding: utf-8 -*- """ mundiapi This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). """ class UpdatePlanRequest(object): """Implementation of the 'UpdatePlanRequest' model. Request for updating a plan Attributes: name (string): Plan's name description (string): Description installments (list of int): Number os installments statement_descriptor (string): Text that will be shown on the credit card's statement currency (string): Currency interval (string): Interval interval_count (int): Interval count payment_methods (list of string): Payment methods accepted by the plan billing_type (string): Billing type status (string): Plan status shippable (bool): Indicates if the plan is shippable billing_days (list of int): Billing days accepted by the plan metadata (dict<object, string>): Metadata minimum_price (int): Minimum price trial_period_days (int): Number of trial period in days, where the customer will not be charged """ # Create a mapping from Model property names to API property names _names = { "name":'name', "description":'description', "installments":'installments', "statement_descriptor":'statement_descriptor', "currency":'currency', "interval":'interval', "interval_count":'interval_count', "payment_methods":'payment_methods', "billing_type":'billing_type', "status":'status', "shippable":'shippable', "billing_days":'billing_days', "metadata":'metadata', "minimum_price":'minimum_price', "trial_period_days":'trial_period_days' } def __init__(self, name=None, description=None, installments=None, statement_descriptor=None, currency=None, interval=None, interval_count=None, payment_methods=None, billing_type=None, status=None, shippable=None, billing_days=None, metadata=None, minimum_price=None, trial_period_days=None): """Constructor for the UpdatePlanRequest class""" # Initialize members of the class self.name = name self.description = description self.installments = installments self.statement_descriptor = statement_descriptor self.currency = currency self.interval = interval self.interval_count = interval_count self.payment_methods = payment_methods self.billing_type = billing_type self.status = status self.shippable = shippable self.billing_days = billing_days self.metadata = metadata self.minimum_price = minimum_price self.trial_period_days = trial_period_days @classmethod def from_dictionary(cls, dictionary): """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class. """ if dictionary is None: return None # Extract variables from the dictionary name = dictionary.get('name') description = dictionary.get('description') installments = dictionary.get('installments') statement_descriptor = dictionary.get('statement_descriptor') currency = dictionary.get('currency') interval = dictionary.get('interval') interval_count = dictionary.get('interval_count') payment_methods = dictionary.get('payment_methods') billing_type = dictionary.get('billing_type') status = dictionary.get('status') shippable = dictionary.get('shippable') billing_days = dictionary.get('billing_days') metadata = dictionary.get('metadata') minimum_price = dictionary.get('minimum_price') trial_period_days = dictionary.get('trial_period_days') # Return an object of this model return cls(name, description, installments, statement_descriptor, currency, interval, interval_count, payment_methods, billing_type, status, shippable, billing_days, metadata, minimum_price, trial_period_days)
35.144828
84
0.577119
476
5,096
6.014706
0.228992
0.06811
0.047153
0.037723
0.05344
0.020957
0
0
0
0
0
0.000903
0.348312
5,096
144
85
35.388889
0.861186
0.300432
0
0
1
0
0.156481
0
0
0
0
0
0
1
0.02381
false
0
0
0
0.071429
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
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
432a6247ae50ed5ff0d32ef0b60b3d2a095bea22
1,441
py
Python
vision_datasets/common/dataset_registry.py
shonohs/vision-datasets
bdd0ebf5c0c0561486ebb0b96600196b2b89f77c
[ "MIT" ]
null
null
null
vision_datasets/common/dataset_registry.py
shonohs/vision-datasets
bdd0ebf5c0c0561486ebb0b96600196b2b89f77c
[ "MIT" ]
null
null
null
vision_datasets/common/dataset_registry.py
shonohs/vision-datasets
bdd0ebf5c0c0561486ebb0b96600196b2b89f77c
[ "MIT" ]
null
null
null
import copy import json from .dataset_info import DatasetInfoFactory class DatasetRegistry: """ A central registry of all available datasets """ def __init__(self, datasets_json: str): self.datasets = [DatasetInfoFactory.create(d) for d in json.loads(datasets_json)] def get_dataset_info(self, dataset_name, dataset_version=None): datasets = [d for d in self.datasets if d.name == dataset_name and (not dataset_version or d.version == dataset_version)] if not datasets: return None sorted_datasets = sorted(datasets, key=lambda d: d.version) return copy.deepcopy(sorted_datasets[-1]) def list_data_version_and_types(self): return [{'name': d.name, 'version': d.version, 'type': d.type, 'description': d.description} for d in self.datasets] @staticmethod def _get_default_dataset_json(json_file_name): import sys py_version = sys.version_info if py_version.minor >= 7: import importlib.resources as pkg_resources from vision_datasets import resources datasets_json = pkg_resources.read_text(resources, json_file_name) else: import pkgutil resource_package = 'vision_datasets' resource_path = '/'.join(('resources', json_file_name)) datasets_json = pkgutil.get_data(resource_package, resource_path) return datasets_json
36.948718
129
0.679389
180
1,441
5.183333
0.355556
0.064309
0.019293
0.015005
0.038585
0
0
0
0
0
0
0.001821
0.238029
1,441
38
130
37.921053
0.847905
0.030534
0
0
0
0
0.03693
0
0
0
0
0
0
1
0.142857
false
0
0.25
0.035714
0.571429
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
432b745399b0d0440cefd7ae239847b77b6d7688
3,009
py
Python
crypt.py
ElyTgy/VaultDB
9eef6f7298d26bd9a18d403971e1c3c6e7a2bf8a
[ "MIT" ]
2
2021-09-27T07:40:21.000Z
2021-10-04T17:32:40.000Z
crypt.py
ElyTgy/VaultDB
9eef6f7298d26bd9a18d403971e1c3c6e7a2bf8a
[ "MIT" ]
3
2021-10-01T17:47:20.000Z
2021-10-21T07:57:13.000Z
crypt.py
ElyTgy/VaultDB
9eef6f7298d26bd9a18d403971e1c3c6e7a2bf8a
[ "MIT" ]
3
2021-09-26T13:26:05.000Z
2021-10-22T02:53:20.000Z
# Importing Fernet class from cryptography.fernet import Fernet # Importing dump and load function from pickle import dump,load # To generate a strong pw def generate_pw(): from random import choice choices = list("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_-+=.,/<>?;:\\|[]}{") pw = "" for i in range(25): pw += choice(choices) return pw del pw,choice # To get master pw from the file def get_masterpw(): # Opening the file storing master pw with open("key.key",'rb') as file: # Loading data keys = load(file) # Master pw is converted from bytes to string key = keys[0].decode() del keys # Return keys return key # To get key from the file def get_key(): # Opening the file storing master pw with open("key.key",'rb') as file: # Loading data keys = load(file) # Key is converted from bytes to string key = keys[1].decode() del keys # Return keys return key # To store master pw in the file def add_keys(masterpw,key): # Opening the file to store master pw with open("key.key",'wb') as file: # Making list of value to upload # key is already in bytes # Converting to bytes is not necessary keys = [masterpw.encode(),key] # Dumping the master pw to file dump(keys,file) # Deleting the variable del masterpw,key,keys # Checking if user is running program for first time def is_1st_time(): # Trying to open bytes file # If file is opened means program was executed once or more try: with open("key.key",'rb') as file: pass return False # FileNotFound means its first time # Or either its not in directory of this file or user deleted it :) # except FileNotFoundError: return True # Function to copy pw to clipboard def copy2clip(pw): # Importing copy function from pyperclip import copy # Copying pw to clipboard copy(pw) del pw,copy # Encrypting the text def encrypt(text, key): try: # Defining Fernet(class) using the key fernet = Fernet(key) # Encryption # Text is converted to bytes encrypted_text = fernet.encrypt(text.encode()) del key # Return encrypted text return encrypted_text # Error message if any except Exception as e: print(f"Error occured:{e}\nProcess failed!") # Decrypting the text def decrypt(text, key): try: # Defining Fernet(class) using the key fernet = Fernet(key) # Decryption # Text is converted from bytes to string decrypted_text = fernet.decrypt(text).decode() del key # Return decrypted text return decrypted_text # Error message if any except Exception as e: print(f"Error occured:{e}\nProcess failed!")
30.393939
114
0.613825
393
3,009
4.671756
0.307888
0.030501
0.023965
0.030501
0.351852
0.333333
0.3061
0.294118
0.218954
0.218954
0
0.007692
0.30874
3,009
99
115
30.393939
0.875
0.384181
0
0.37037
1
0
0.113769
0.053092
0
0
0
0
0
1
0.148148
false
0.018519
0.074074
0
0.351852
0.037037
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
4331f36c8fbfd4af3f45057825bf7f902a91aa4d
2,911
py
Python
application/model/radar_score_20180117/score_calculate.py
ace-gabriel/chrome-extension
be0b7d7278f56f8218be7f734b3fb1e05a4f3eb9
[ "MIT" ]
4
2018-09-11T22:27:55.000Z
2018-11-16T22:54:14.000Z
application/model/radar_score_20180117/score_calculate.py
ace-gabriel/chrome-extension
be0b7d7278f56f8218be7f734b3fb1e05a4f3eb9
[ "MIT" ]
null
null
null
application/model/radar_score_20180117/score_calculate.py
ace-gabriel/chrome-extension
be0b7d7278f56f8218be7f734b3fb1e05a4f3eb9
[ "MIT" ]
null
null
null
# coding: utf-8 import pickle # import json # import types path = 'application/model/radar_score_20180117/' def f(x, x_range, score): bottom = 20 y = [] for i in x: if i < x_range[0]: pos = 0 else: for j in range(len(x_range)): if j == len(x_range) - 1 or \ i >= x_range[j] and i < x_range[j + 1]: pos = j break s = sum(score[:pos]) + score[pos] * (i - x_range[pos]) y.append(s + bottom) return y def process_score(house): # with open('radar.json', 'r') as fj: # house = json.load(fj) # print radar # print house score = { 'score_appreciation': 60, 'score_cost': 60, 'score_rental': 60, 'score_airbnb': 60, 'score_anti_risk': 60 } with open(path+'scoremodel.pkl', 'rb') as fp: # pickle.dump([radar, factor, x_range, score], fopen) N = 4 a = pickle.load(fp) if 'increase_ratio' in house and house['increase_ratio'] != None: # 房屋增值 x = house['increase_ratio'] * a[1] score['score_appreciation'] = f([x], a[2], a[3])[0] # print x, score['score_appreciation'] a = pickle.load(fp) if 'house_price_dollar' in house and house['house_price_dollar'] != None: # 持有成本 x = a[1] / house['house_price_dollar'] # print 'house_price_dollar', house['house_price_dollar'] score['score_cost'] = f([x], a[2], a[3])[0] # print score['score_cost'] if 'airbnb_rent' in house and house['airbnb_rent'] != None: # 短租收益 a = pickle.load(fp) x = house['airbnb_rent'] * 12.0 / house['house_price_dollar'] * a[1] score['score_airbnb'] = f([x], a[2], a[3])[0] # print score['score_airbnb'] a = pickle.load(fp) if 'rental_income_ratio' in house and house['rental_income_ratio'] != None: # 长租收益 x = house['rental_income_ratio'] * a[1] score['score_rental'] = f([x], a[2], a[3])[0] # print score['score_rental'] if 'neighborhood' in house and 'id' in house['neighborhood'] and house['neighborhood']['id'] != None: with open(path+'region_anti_drop.pkl', 'r') as fp: # 抗跌能力 region = pickle.load(fp) score_anti = pickle.load(fp) if house['neighborhood']['id'] in region: # print house['neighborhood']['id'] i = region.index(house['neighborhood']['id']) score['score_anti_risk'] = score_anti[i] # for i in score: # print '%20s %2.3f ' % (i, score[i]) # check: make sure score in range(20, 100) for i in score: if score[i] < 20: score[i] = 20 if score[i] > 100: score[i] = 100 return score if __name__ == '__main__': # README print "This is a program calculating house's 5 scores:" \ "Anti Drop Score," \ "House Appreciation," \ "Possess Cost," \ "Long-term Income" \ "Short-term Income"
27.72381
103
0.564411
417
2,911
3.788969
0.244604
0.063291
0.04557
0.032911
0.139873
0.049367
0.049367
0.049367
0.041772
0.041772
0
0.030894
0.277224
2,911
104
104
27.990385
0.720057
0.176572
0
0.063492
0
0
0.26043
0.016435
0
0
0
0
0
0
null
null
0
0.015873
null
null
0.015873
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
0
0
1
43338fccc231cf2b75bc14f3df4523f468ef4c58
347
py
Python
evetool/urls.py
Sult/evetool
155db9f3b0ecc273fe3c75daf8f9c6f37cb3e47f
[ "MIT" ]
null
null
null
evetool/urls.py
Sult/evetool
155db9f3b0ecc273fe3c75daf8f9c6f37cb3e47f
[ "MIT" ]
null
null
null
evetool/urls.py
Sult/evetool
155db9f3b0ecc273fe3c75daf8f9c6f37cb3e47f
[ "MIT" ]
null
null
null
from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static urlpatterns = [ # Examples: # url(r'^$', 'evetool.views.home', name='home'), url(r'^', include('users.urls')), url(r'^', include('apis.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
31.545455
67
0.691643
47
347
5.042553
0.425532
0.126582
0.177215
0.151899
0
0
0
0
0
0
0
0
0.135447
347
10
68
34.7
0.79
0.161383
0
0
0
0
0.072917
0
0
0
0
0
0
1
0
false
0
0.428571
0
0.428571
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
1
4336c7b257868aa7e53dc95e1f352acf6bc002a4
175
py
Python
simple_exercises/lanesexercises/py_functions2/rep_ex3.py
ilante/programming_immanuela_englander
45d51c99b09ae335a67e03ac5ea79fc775bdf0bd
[ "MIT" ]
null
null
null
simple_exercises/lanesexercises/py_functions2/rep_ex3.py
ilante/programming_immanuela_englander
45d51c99b09ae335a67e03ac5ea79fc775bdf0bd
[ "MIT" ]
null
null
null
simple_exercises/lanesexercises/py_functions2/rep_ex3.py
ilante/programming_immanuela_englander
45d51c99b09ae335a67e03ac5ea79fc775bdf0bd
[ "MIT" ]
null
null
null
# 3. Define a function to check whether a number is even def even(num): if num%2 == 0: return True else: return False print(even(4)) print(even(-5))
15.909091
56
0.6
29
175
3.62069
0.758621
0.171429
0
0
0
0
0
0
0
0
0
0.040323
0.291429
175
10
57
17.5
0.806452
0.308571
0
0
0
0
0
0
0
0
0
0
0
1
0.142857
false
0
0
0
0.428571
0.285714
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
0
0
0
0
0
1
433c71e69aaf2d22844233c421ede8abdf861e77
241
py
Python
linter.py
dndrsn/SublimeLinter-contrib-cspell
ba2335a9282335e52282ee93f3bb2a55f9536984
[ "MIT" ]
null
null
null
linter.py
dndrsn/SublimeLinter-contrib-cspell
ba2335a9282335e52282ee93f3bb2a55f9536984
[ "MIT" ]
null
null
null
linter.py
dndrsn/SublimeLinter-contrib-cspell
ba2335a9282335e52282ee93f3bb2a55f9536984
[ "MIT" ]
null
null
null
from SublimeLinter.lint import Linter, STREAM_STDOUT class CSpell(Linter): cmd = 'cspell stdin' defaults = {'selector': 'source'} regex = r'^[^:]*:(?P<line>\d+):(?P<col>\d+) - (?P<message>.*)$' error_stream = STREAM_STDOUT
26.777778
67
0.618257
30
241
4.866667
0.733333
0.164384
0
0
0
0
0
0
0
0
0
0
0.170124
241
8
68
30.125
0.73
0
0
0
0
0
0.323651
0.136929
0
0
0
0
0
1
0
false
0
0.166667
0
1
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
0
0
0
1
43468039289e0d25ecbf534436703bc05e6e79e6
5,156
py
Python
python/app/plugins/http/Struts2/S2_052.py
taomujian/linbing
fe772a58f41e3b046b51a866bdb7e4655abaf51a
[ "MIT" ]
351
2020-02-26T05:23:26.000Z
2022-03-26T12:39:19.000Z
python/app/plugins/http/Struts2/S2_052.py
taomujian/linbing
fe772a58f41e3b046b51a866bdb7e4655abaf51a
[ "MIT" ]
15
2020-03-26T07:31:49.000Z
2022-03-09T02:12:17.000Z
python/app/plugins/http/Struts2/S2_052.py
taomujian/linbing
fe772a58f41e3b046b51a866bdb7e4655abaf51a
[ "MIT" ]
99
2020-02-28T07:30:46.000Z
2022-03-16T16:41:09.000Z
#!/usr/bin/env python3 from app.lib.utils.request import request from app.lib.utils.encode import base64encode from app.lib.utils.common import get_capta, get_useragent class S2_052_BaseVerify: def __init__(self, url): self.info = { 'name': 'S2-052漏洞,又名CVE-2017-9805漏洞', 'description': 'Struts2 Remote Code Execution Vulnerability, Struts 2.1.6 - Struts 2.3.33, Struts 2.5 - Struts 2.5.12', 'date': '2017-09-05', 'exptype': 'check', 'type': 'RCE' } self.url = url if not self.url.startswith("http") and not self.url.startswith("https"): self.url = "http://" + self.url self.capta = get_capta() self.headers = { 'User-Agent': get_useragent(), 'Content-Type': "application/xml", } self.payload =''' <map> <entry> <jdk.nashorn.internal.objects.NativeString> <flags>0</flags> <value class="com.sun.xml.internal.bind.v2.runtime.unmarshaller.Base64Data"> <dataHandler> <dataSource class="com.sun.xml.internal.ws.encoding.xml.XMLMessage$XmlDataSource"> <is class="javax.crypto.CipherInputStream"> <cipher class="javax.crypto.NullCipher"> <initialized>false</initialized> <opmode>0</opmode> <serviceIterator class="javax.imageio.spi.FilterIterator"> <iter class="javax.imageio.spi.FilterIterator"> <iter class="java.util.Collections$EmptyIterator"/> <next class="java.lang.ProcessBuilder"> <command> {cmd} </command> <redirectErrorStream>false</redirectErrorStream> </next> </iter> <filter class="javax.imageio.ImageIO$ContainsFilter"> <method> <class>java.lang.ProcessBuilder</class> <name>start</name> <parameter-types/> </method> <name>foo</name> </filter> <next class="string">foo</next> </serviceIterator> <lock/> </cipher> <input class="java.lang.ProcessBuilder$NullInputStream"/> <ibuffer></ibuffer> <done>false</done> <ostart>0</ostart> <ofinish>0</ofinish> <closed>false</closed> </is> <consumed>false</consumed> </dataSource> <transferFlavors/> </dataHandler> <dataLen>0</dataLen> </value> </jdk.nashorn.internal.objects.NativeString> <jdk.nashorn.internal.objects.NativeString reference="../jdk.nashorn.internal.objects.NativeString"/> </entry> <entry> <jdk.nashorn.internal.objects.NativeString reference="../../entry/jdk.nashorn.internal.objects.NativeString"/> <jdk.nashorn.internal.objects.NativeString reference="../../entry/jdk.nashorn.internal.objects.NativeString"/> </entry> </map> ''' def check(self): """ 检测是否存在漏洞 :param: :return bool True or False: 是否存在漏洞 """ try: self.check_payload = self.payload.format(cmd = '<string>calc</string>') check_req = request.post(self.url, headers = self.headers, data = self.check_payload) if check_req.status_code == 500 and 'java.security.Provider$Service' in check_req.text: return True else: return False except Exception as e: print(e) return False finally: pass if __name__ == "__main__": S2_052 = S2_052_BaseVerify('http://127.0.0.1:8088/struts2_rest_showcase_war_exploded/orders/3')
48.641509
138
0.413693
380
5,156
5.531579
0.439474
0.038059
0.068506
0.095147
0.227402
0.20647
0.161751
0.123216
0.123216
0.123216
0
0.027283
0.488169
5,156
106
139
48.641509
0.769231
0.014546
0
0.087912
0
0.065934
0.771519
0.225902
0
0
0
0
0
1
0.021978
false
0.010989
0.032967
0
0.098901
0.010989
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
0
0
0
0
0
0
1
4346e00af4df20f2f609af7be11fe806991cbce3
905
py
Python
UPD/extension/utils.py
RIDCorix/UPD
8694d119181a4afffafbfbab510f697399c1ea13
[ "MIT" ]
null
null
null
UPD/extension/utils.py
RIDCorix/UPD
8694d119181a4afffafbfbab510f697399c1ea13
[ "MIT" ]
null
null
null
UPD/extension/utils.py
RIDCorix/UPD
8694d119181a4afffafbfbab510f697399c1ea13
[ "MIT" ]
null
null
null
import sys # def get_tools(): # manager = PluginManager() # manager.setPluginPlaces(["plugins/file_cabinet"]) # manager.collectPlugins() # return [plugin.plugin_object for plugin in manager.getAllPlugins()] def get_tools(): import importlib tools = ['file_cabinet', 'us', 'automator', 'main'] tool_installation_dir1 = 'C:/Users/User/UPD/plugins' tool_installation_dir2 = '/Users/mac/UPD/plugins' sys.path.append(tool_installation_dir1) sys.path.append(tool_installation_dir2) tool_instances = [] auto_load_modules = ['tasks', 'ui', 'models', 'renderers'] for tool in tools: tool_instances.append(importlib.import_module('.'.join([tool, 'tool'])).tool) for module in auto_load_modules: try: importlib.import_module('.'.join([tool, module])) except: pass return tool_instances
34.807692
85
0.654144
102
905
5.588235
0.45098
0.112281
0.038596
0.059649
0.203509
0
0
0
0
0
0
0.005626
0.214365
905
25
86
36.2
0.796062
0.222099
0
0
0
0
0.146132
0.067335
0
0
0
0
0
1
0.055556
false
0.055556
0.222222
0
0.333333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
434716a29a916c0a3138b2d8297566e972c6c138
7,640
py
Python
sgcache/control.py
vfxetc/sgcache
670bfac2904373e19c2dac7504d2d7f87018833d
[ "BSD-3-Clause" ]
13
2017-09-06T21:48:57.000Z
2022-02-08T20:50:52.000Z
sgcache/control.py
vfxetc/sgcache
670bfac2904373e19c2dac7504d2d7f87018833d
[ "BSD-3-Clause" ]
1
2021-04-04T18:07:04.000Z
2021-04-04T18:07:04.000Z
sgcache/control.py
vfxetc/sgcache
670bfac2904373e19c2dac7504d2d7f87018833d
[ "BSD-3-Clause" ]
1
2019-07-19T01:23:19.000Z
2019-07-19T01:23:19.000Z
from __future__ import absolute_import from select import select import errno import functools import itertools import json import logging import os import socket import threading import time import traceback log = logging.getLogger(__name__) from .utils import makedirs, unlink class TimeOut(Exception): pass base_handlers = { 'ping': lambda control, msg: {'type': 'pong', 'pid': os.getpid()} } def _coerce_msg(type=None, **msg): if type: if isinstance(type, basestring): msg['type'] = type return msg elif msg: raise ValueError('cannot specify dict message and kwargs') else: msg = dict(type) if 'type' not in msg: raise ValueError('message requires type') return msg class ControlClient(object): handlers = base_handlers.copy() def __init__(self, addr=None, sock=None, server=None): self.addr = addr self.sock = sock self.server = server self._line_buffer = '' self._message_buffer = [] self._handler_reply_ids = None self._session_generator = itertools.count(1) if sock is None: self.connect() def connect(self): # This is indempodent. if self.sock is not None: return if self.addr is None: return if isinstance(self.addr, basestring): self.sock = socket.socket(socket.AF_UNIX) else: self.sock = socket.socket(socket.AF_INET) self.sock.connect(self.addr) return True def close(self): if self.sock: self.sock.close() self.sock = None def _readline(self, timeout=None): if not self.sock: return if timeout: end_time = time.time() + timeout buffer_ = self._line_buffer while True: r, _, _ = select([self.sock], [], [], max(0, end_time - time.time()) if timeout else None) if not r: raise TimeOut() new = self.sock.recv(4096) if not new: self.sock = None self._line_buffer = '' return buffer_ += new if '\n' in buffer_: line, buffer_ = buffer_.split('\n', 1) self._line_buffer = buffer_ return line def recv(self, timeout=None): try: return self._message_buffer.pop(0) except IndexError: pass for attempt_num in (0, 1): self.connect() try: line = self._readline(timeout) except socket.error as e: if attempt_num: raise if line: try: return json.loads(line) except: self.send('error', message='malformed message') self.close() return if attempt_num: return def recv_for(self, wait_id, timeout=None): for i in xrange(len(self._message_buffer)): msg = self._message_buffer[i] if msg.get('for') == wait_id: self._message_buffer.pop(i) return msg while True: msg = self.recv(timeout) if not msg: return if msg.get('for') == wait_id: return msg self._message_buffer.append(msg) def send(self, *args, **kwargs): msg = _coerce_msg(*args, **kwargs) wait_id = msg.get('wait') if wait_id is True: wait_id = msg['wait'] = next(self._session_generator) encoded = json.dumps(msg) # Track what has been sent automatically. if wait_id is not None and self._handler_reply_ids is not None: self._handler_reply_ids.add(wait_id) # Attempt to reconnect a couple times when sending this. for attempt_num in (0, 1): self.connect() try: self.sock.send(encoded + '\n') except socket.error as e: if attempt_num: raise return wait_id def reply_to(self, original, *args, **kwargs): wait_id = original.get('wait') if wait_id is None: raise ValueError('original message has no session') msg = _coerce_msg(*args, **kwargs) msg['for'] = wait_id self.send(msg) def send_and_recv(self, type, **kwargs): timeout = kwargs.pop('timeout') msg = _coerce_msg(type, **kwargs) msg['wait'] = True wait_id = self.send(msg) return self.recv_for(wait_id, timeout) def ping(self, timeout=None): return self.send_and_recv('ping', pid=os.getpid(), timeout=timeout) def loop(self, async=False): if async: thread = threading.Thread(target=self.loop) thread.daemon = True thread.start() return thread while True: msg = self.recv() if not msg: return type_ = msg.get('type') wait_id = msg.get('wait') func = self.handlers.get(type_) if func is None and self.server: func = self.server.handlers.get(type_) if func is None: log.warning('unknown message type %r' % type_) self.reply_to(msg, 'error', message='unknown message type %r' % type_) continue if self.server and self.server.name: log.info('%s handling %s' % (self.server.name, type_)) else: log.info('handling %s' % type_) self._handler_reply_ids = set() try: res = func(self, msg) except Exception as e: self.reply_to(msg, 'error', message='unhandled exception %s' % e) continue # If the handler replied, then we are done. if res is None and wait_id is None or wait_id in self._handler_reply_ids: continue res = res.copy() if isinstance(res, dict) and 'type' in res else {'type': 'result', 'value': res} if wait_id is not None: res['for'] = wait_id self.send(res) class ControlServer(object): def __init__(self, addr, name=None): self.addr = addr self.name = name self.handlers = base_handlers.copy() if isinstance(self.addr, basestring): self.sock = socket.socket(socket.AF_UNIX) if os.path.exists(self.addr): # TODO: Try connecting to it before destroying it. unlink(self.addr) makedirs(os.path.dirname(self.addr)) else: self.sock = socket.socket(socket.AF_INET) self.sock.bind(self.addr) self.sock.listen(5) def register(self, func=None, **kwargs): if func is None: return functools(self.register(**kwargs)) self.handlers[kwargs.get('name') or func.__name__] = func def loop(self, async=False): if async: thread = threading.Thread(target=self.loop) thread.daemon = True thread.start() return thread while True: try: client_sock, addr = self.sock.accept() except socket.timeout: continue client = ControlClient(sock=client_sock, server=self) client.loop(async=True)
27.383513
109
0.534817
890
7,640
4.446067
0.194382
0.02881
0.025777
0.024008
0.257266
0.196614
0.157695
0.144049
0.144049
0.109679
0
0.002698
0.369241
7,640
278
110
27.482014
0.818427
0.026963
0
0.373206
0
0
0.042272
0
0
0
0
0.003597
0
0
null
null
0.009569
0.062201
null
null
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
1
0
0
0
0
0
0
0
0
1
434721dba4ee0af8165b368cf20f7e199d6dcfdf
502
py
Python
lantz/drivers/tektronix/tds1002b.py
mtsolmn/lantz-drivers
f48caf9000ddd08f2abb837d832e341410af4788
[ "BSD-3-Clause" ]
4
2019-05-04T00:10:53.000Z
2020-10-22T18:08:40.000Z
lantz/drivers/tektronix/tds1002b.py
mtsolmn/lantz-drivers
f48caf9000ddd08f2abb837d832e341410af4788
[ "BSD-3-Clause" ]
3
2019-07-12T13:44:17.000Z
2020-10-22T19:32:08.000Z
lantz/drivers/tektronix/tds1002b.py
mtsolmn/lantz-drivers
f48caf9000ddd08f2abb837d832e341410af4788
[ "BSD-3-Clause" ]
9
2019-04-03T17:07:03.000Z
2021-02-15T21:53:55.000Z
# -*- coding: utf-8 -*- """ lantz.drivers.tektronix.tds1012 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Implements the drivers to control an oscilloscope. :copyright: 2015 by Lantz Authors, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from lantz.core import Feat, MessageBasedDriver class TDS1002b(MessageBasedDriver): MANUFACTURER_ID = '0x699' MODEL_CODE = '0x363' @Feat(read_once=True) def idn(self): return self.query('*IDN?')
22.818182
68
0.633466
57
502
5.526316
0.77193
0.044444
0.088889
0
0
0
0
0
0
0
0
0.052369
0.201195
502
21
69
23.904762
0.733167
0.496016
0
0
0
0
0.066667
0
0
0
0.044444
0
0
1
0.142857
false
0
0.142857
0.142857
0.857143
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
0
0
0
1
4a2f4eecfe75a9c91356c84f877db3d3e9fc53fc
2,139
py
Python
iHome/house/models.py
yeyuning1/iHome
aceb87d786ab66cf74ff47f549ec73388d21c9e3
[ "MIT" ]
2
2019-08-13T07:34:35.000Z
2019-08-13T08:11:46.000Z
iHome/house/models.py
yeyuning1/iHome
aceb87d786ab66cf74ff47f549ec73388d21c9e3
[ "MIT" ]
null
null
null
iHome/house/models.py
yeyuning1/iHome
aceb87d786ab66cf74ff47f549ec73388d21c9e3
[ "MIT" ]
null
null
null
from django.db import models # Create your models here. from utils.models import BaseModel class House(BaseModel): '''房屋信息''' user = models.ForeignKey('users.User', on_delete=models.CASCADE, verbose_name='房屋用户') area = models.ForeignKey('address.Area', on_delete=models.SET_NULL, null=True, verbose_name='房屋地区') title = models.CharField(max_length=64, null=False, verbose_name='房屋标题') price = models.IntegerField(default=0, verbose_name='房屋单价') # 单价分 address = models.CharField(max_length=512, default='', verbose_name='房屋地址') room_count = models.SmallIntegerField(default=1, verbose_name='房间数目') acreage = models.IntegerField(default=0, verbose_name='房屋面积') unit = models.CharField(max_length=32, default='', verbose_name='房屋单元') # 如几室几厅 capacity = models.SmallIntegerField(default=1, verbose_name='房屋容纳') # 房屋容纳的人数 beds = models.CharField(max_length=64, default='', verbose_name='房屋床铺配置') deposit = models.IntegerField(default=0, verbose_name='房屋押金') min_days = models.SmallIntegerField(default=1, verbose_name='最少入住天数') max_days = models.SmallIntegerField(default=0, verbose_name='最大入住天数') # 0表示不限制 order_count = models.IntegerField(default=0, verbose_name='预计该房屋的订单数') index_image_url = models.CharField(max_length=500, default='', verbose_name='房屋主图片的路径') facilities = models.ManyToManyField('Facility')#配套设施 class Meta: db_table = 'ih_house_info' verbose_name = '房屋信息' verbose_name_plural = verbose_name class Facility(models.Model): '''房屋设施信息''' name = models.CharField(max_length=32, verbose_name='设施名称') class Meta: db_table = 'ih_facility_info' verbose_name = '设施信息' verbose_name_plural = verbose_name class HouseImage(BaseModel): '''房屋图片''' house = models.ForeignKey(House, verbose_name='房屋信息', on_delete=models.CASCADE) url = models.CharField(max_length=256, null=False, verbose_name='房屋图片地址') class Meta: db_table = 'ih_house_image' verbose_name = '房屋图片' verbose_name_plural = verbose_name
41.941176
104
0.697522
260
2,139
5.523077
0.346154
0.206825
0.087744
0.116992
0.410864
0.268802
0
0
0
0
0
0.014815
0.179523
2,139
50
105
42.78
0.803419
0.033193
0
0.166667
0
0
0.087131
0
0
0
0
0
0
1
0
false
0
0.055556
0
0.75
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
0
0
0
0
0
0
0
0
0
0
1
4a31433e8acb3aa3c417194791048caf8fdb3d24
15,863
py
Python
cltwit/main.py
Psycojoker/cltwit
3164f263df60d608da124ceb7d1e56bbdde7c930
[ "WTFPL", "Unlicense" ]
null
null
null
cltwit/main.py
Psycojoker/cltwit
3164f263df60d608da124ceb7d1e56bbdde7c930
[ "WTFPL", "Unlicense" ]
null
null
null
cltwit/main.py
Psycojoker/cltwit
3164f263df60d608da124ceb7d1e56bbdde7c930
[ "WTFPL", "Unlicense" ]
null
null
null
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Cltwit is a command line twitter utility Author : Jérôme Launay Date : 2013 """ import os import sys import re import getopt import gettext import sqlite3 import webbrowser import ConfigParser from sqlite2csv import sqlite2csv from cltwitdb import cltwitdb from utils import LocalTimezone from cltwitreport import TweetsReport APP_NAME = 'cltwit' LOC_PATH = os.path.dirname(__file__) + '/locale' gettext.find(APP_NAME, LOC_PATH) gettext.install(APP_NAME, LOC_PATH, True) try: import tweepy except ImportError: print(_("Veuillez installer tweetpy https://github.com/tweepy/tweepy")) sys.exit() # Répertoire pour conf et bdd __cltwitdir__ = os.path.expanduser("~/.config/cltwit") # Fichier de configuration __configfile__ = __cltwitdir__ + "/cltwit.conf" # base de données et table sqlite __dblocation__ = __cltwitdir__ + '/data.db' __tablename__ = 'twitter' __Local__ = LocalTimezone() # gestion des couleurs sur le terminal BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8) def has_colours(stream): """Vérifier la prise en charge des couleurs par le terminal""" if not hasattr(stream, "isatty"): return False if not stream.isatty(): return False # couleurs auto sur un TTY try: import curses curses.setupterm() return curses.tigetnum("colors") > 2 except: # Si erreur on suppose false return False __has_colours__ = has_colours(sys.stdout) def printout(text, colour=WHITE): """Print en couleur""" if __has_colours__: seq = "\x1b[1;%dm" % (30 + colour) + text + "\x1b[0m" sys.stdout.write(seq) else: sys.stdout.write(text.encode("Utf-8")) def checkdb(): """ Vérifier la présence de la bdd sqlite et la créer si absente """ if (not os.path.exists(__dblocation__)): printout(_(u"Vous devez d'abord lancer la commande --database create \ pour créer une base de données de vos tweets."), RED) sys.exit() def checkconfig(): """Récupérer la configuration ou la créer""" # On ouvre le fichier de conf config = ConfigParser.RawConfigParser() try: config.read(__configfile__) if config.has_option('twitterapi', 'access_token'): access_token = config.get('twitterapi', 'access_token') if config.has_option('twitterapi', 'access_password'): access_password = config.get('twitterapi', 'access_password') except: pass auth = tweepy.OAuthHandler("Jus1rnqM6S0WojJfOH1kQ", "AHQ5sTC8YYArHilXmqnsstOivY6ygQ2N27L1zBwk") # Si aucune conf , autorisation de connexion à twitter via OAuth if not(config.has_option('twitterapi', 'access_token') and config.has_option('twitterapi', 'access_password')): # On ouvre le navigateur web pour récupếrer le numéro d'autorisation while True: try: webbrowser.open(auth.get_authorization_url()) var = raw_input(_("Entrez le token !\n")) auth.get_access_token(var) except Exception, e: print(str(e)) continue break var = auth.access_token # On récupère le token et le password access_password = str(var).split("&")[0].split("=")[1] access_token = str(var).split("&")[1].split("=")[1] # écrire le fichier de conf avec les informations récupérées try: cfgfile = open(__configfile__, 'w') if not(config.has_section('twitterapi')): config.add_section('twitterapi') config.set('twitterapi', 'access_token', access_token) config.set('twitterapi', 'access_password', access_password) config.write(cfgfile) except IOError: pass finally: cfgfile.close() else: # Si un fichier de conf existait déjà auth.set_access_token(access_token, access_password) return auth def login(): """ Se connecter à l'api twitter via tweepy """ auth = checkconfig() api = tweepy.API(auth) # On vérifie la connexion à l'api en récupérant le user name try: twittername = api.me().screen_name except Exception, e: if 'Unable to get username' in (str(e)): printout(_(u"Impossible de s'authentifier avec l'api Twitter.\ Fonctionne en mode déconnecté"), RED) print("\n") twittername = "offline_mode" printout(_(u"Authentifié avec le user twitter {0}").format(twittername.decode('utf-8')), GREEN) print("\n") return api, auth, twittername def get_friends_followers(api): """Renvoie la liste des id des friends et followers""" friend_id = [] follower_id = [] printout(_(u"Récupération des Followers..."), YELLOW) print("\n") for follower in tweepy.Cursor(api.followers).items(): follower_id.append(follower.id) printout((u"Récupération des Friends..."), YELLOW) print("\n") for friend in tweepy.Cursor(api.friends).items(): friend_id.append(friend.id) return friend_id, follower_id def get_diff(liste1, liste2): """Renvoie les objets de liste1 qui ne sont pas dans liste2""" return list(set(liste1).difference(set(liste2))) def follow_users(api, user): """Suivre une personne""" try: api.create_friendship(user) printout(_(u"Vous suivez maintenant {0}").format(api.get_user(user).screen_name.decode('utf-8')), GREEN) except Exception, e: print(e) def unfollow_user(api, user): """Cesser de suivre une personne""" try: api.destroy_friendship(user) printout(_(u"Vous ne suivez plus {0}").format(api.get_user(user).screen_name.decode('utf-8')), GREEN) except Exception, e: print(e) def main(argv=None): """ Point d'entrée """ # Si le répertoire pour la conf et la base de données n'existe pas le créer if not os.path.exists(__cltwitdir__): os.makedirs(__cltwitdir__) #~ twittername = "offline_mode" # Traitement des arguments if argv is None: argv = sys.argv if len(argv) == 1: help() try: opts, args = getopt.getopt(sys.argv[1:], "r:ahfut:o:s:d:", ["report", "api", "help", "follow", "unfollow", "tweet=", "output=", "search=", "database="]) except getopt.GetoptError, err: print(err) help() sys.exit() # traitement des options for option, value in opts: if option in ('-a', '--api'): api, auth, twittername = login() res = api.rate_limit_status() rtime = res['reset_time'] rhits = res['remaining_hits'] hlimit = res['hourly_limit'] from dateutil.parser import parse drtime = parse(rtime) printout(_("Informations sur l'utilisation de l'api Twitter"), YELLOW) print("\n") # Définir l'heure locale qui correspond à l'heure renvoyée # par l'api Twitter rlocaltime = drtime.astimezone(__Local__) printout(_("Maximum d'appels par heure: "), BLUE) print hlimit printout(_("Nombre d'appels restants: "), BLUE) print rhits printout(_("Heure du prochain reset: "), BLUE) print rlocaltime.strftime("%H:%M %Y-%m-%d") if option in ('-r', '--report'): api, auth, twittername = login() checkdb() conn = sqlite3.connect(__dblocation__) c = conn.cursor() c.execute("select substr(date, 1,4) from twitter order by date asc limit 1") dmois = c.fetchone()[0] c.execute("select substr(date, 1,4) from twitter order by date desc limit 1") fmois = c.fetchone()[0] # Requête des données à exporter dd = dict() for a in range(int(dmois), int(fmois) + 1): result = [] for m in range(1, 13): mois = ('{num:02d}'.format(num=m)) c.execute("select count(*) from twitter where substr(date, 1,4) = '{0}' and substr(date, 6,2) = '{1}'".format(a, mois)) result.append(c.fetchone()[0]) dd[a] = result c.close() conn.close() treport = TweetsReport(value) # twittername = "offline" treport.ecrireTitre(twittername) nb = 0 for annee, donnees in dd.items(): nb += 1 if nb == 4: treport.NextPage() nb = 1 saut = 0 if nb == 1: saut = 0 if nb == 2: saut = 200 if nb == 3: saut = 400 treport.ecrireLegende(saut, annee, donnees) treport.addPie(saut, donnees) treport.save() printout(_(u"Report {0} créé !").format(value), GREEN) print("\n") sys.exit(0) if option in ('-d', '--database'): if value in ('u', 'update'): # Se connecter à l'api twitter api, auth, twittername = login() # Mettre à jour la base de données db = cltwitdb(__dblocation__, __tablename__) printout(_(u"Mise à jour de la base de données de {0}").format(twittername.decode('utf-8')), YELLOW) print("\n") nb = db.update(api, twittername) printout(_(u"Ajout de {0} tweet(s) dans la base de données.").format(nb), GREEN) if value in ('c', 'create'): # Se connecter à l'api twitter api, auth, twittername = login() # Créer la base de données db = cltwitdb(__dblocation__, __tablename__) printout(_(u"Création de la liste des tweets de ") + twittername.decode('utf-8'), YELLOW) db.create(api, twittername) printout(_(u"Base de données crée"), GREEN) sys.exit() #~ database_create(api,twittername) if option in ("-o", "--output"): # Exporter en csv checkdb() conn = sqlite3.connect(__dblocation__) c = conn.cursor() # Requête des données à exporter c.execute('select date, tweet, url from {0} order by date desc'.format(__tablename__)) # On appelle la classe sqlite2csv qui se charge de l'export export = sqlite2csv(open(value, "wb")) # Entête du fichier csv export.writerow(["Date", "Tweet", "URL"]) # Lignes du fichier csv export.writerows(c) # On ferme la connexion sqlite et le curseur c.close() conn.close() printout(_(u"Fichier csv {0} créé.").format(value.decode('utf-8')), GREEN) sys.exit() if option in ("-s", "--search"): # Rechercher un motif dans la base des tweets checkdb() printout(_(u"Recherche de {0} dans vos anciens tweets...") .format(value.decode('utf-8')), YELLOW) print("\n") # la méthode search retourne un tuple avec les champs # qui contiennent le motif db = cltwitdb(__dblocation__, __tablename__) results = db.search(value, "tweet") for result in results: print((u"{0} -> {1}\n{2}\n\n").format(result[1].decode('utf-8'), result[4].decode('utf-8'), result[2].decode('utf-8'))) if option in ("-u", "--unfollow"): # Se connecter à l'api twitter api, auth, twittername = login() # Créer les liste friend et followers (par id) friend_id, follower_id = get_friends_followers(api) # Création des listes follow et unfollow follow_liste = get_diff(follower_id, friend_id) unfollow_liste = get_diff(friend_id, follower_id) # Un-follow printout(_("Vous suivez {0} personnes qui ne vous suivent pas.") .format(len(unfollow_liste)), YELLOW) print("\n") printout(_("Voulez changer cela ? (o/N)"), BLUE) print("\n") reponse = raw_input("> ") if (reponse.lower() == 'o' or reponse.lower() == 'y'): for user in unfollow_liste: printout(_("Voulez-vous cesser de suivre {0} ? (o/N)") .format(api.get_user(user).screen_name), BLUE) print("\n") reponse = raw_input("> ") if (reponse.lower() == 'o' or reponse.lower() == 'y'): unfollow_user(api, user) if option in ("-f", "--follow"): # Se connecter à l'api twitter api, auth, twittername = login() # Créer les liste friend et followers (par id) friend_id, follower_id = get_friends_followers(api) # Création des listes follow et unfollow follow_liste = get_diff(follower_id, friend_id) unfollow_liste = get_diff(friend_id, follower_id) # follow printout(_("{0} personnes vous suivent alors que vous ne les suivez pas.") .format(len(follow_liste)), YELLOW) print("\n") printout(_("Voulez changer cela ? (o/N)"), BLUE) print("\n") reponse = raw_input("> ") if (reponse.lower() == 'o' or reponse.lower() == 'y'): for user in follow_liste: printout(_("Voulez-vous suivre {0} ? (o/N)" .format(api.get_user(user).screen_name)), BLUE) print("\n") reponse = raw_input("> ") if (reponse.lower() == 'o' or reponse.lower() == 'y'): follow_users(api, user) if option in ("-t", "--tweet"): # Se connecter à l'api twitter api, auth, twittername = login() # Envoyer un tweet tweet_size = len(re.sub("https://\S*", "X"*23, re.sub("http://\S*", "X"*22, value))) if tweet_size < 141: api.update_status(value) print("\n") printout(_(u"Tweet envoyé !"), GREEN) else: printout(_(u"La limite pour un tweet est de 140 caractères, votre message \ fait {0} caractères de trop").format(str(tweet_size - 140).decode('utf-8')), RED) sys.exit() if option in ("-h", "--help"): help() def help(): printout(_(u""" Usage : cltwit [OPTIONS] Options : -f (--follow) *Ajouter des personnes qui vous suivent et que vous ne suivez pas -u (--unfollow) *Cesser de suivre les personnes que vous suivez et qui \ vous ne suivent pas -s (--search) MOTIF *Search ( rechercher MOTIF dans vos anciens tweets) -t (--tweet) *Envoyer un tweet (message de 140 caractères maximum) -o (--output) FILENAME.csv *Exporter l'intégralité de vos tweets dans \ le fichier FILENAME.csv -a (--api) * Obtenir des informations sur l'utilisation de l'api twitter -r (--report) FILENAME.pdf * Générer un reporting format pdf avec la repartition des tweets par année et par mois -d (--database) c|u c (create) *Créer ou récréer la base de données des tweets u (update) *Mettre à jour la base de données des tweets """), BLUE ) if __name__ == "__main__": try: sys.exit(main()) except KeyboardInterrupt: print("\n") print(_(u"Merci d'avoir utilisé clitwit !"))
36.635104
140
0.566034
1,890
15,863
4.621164
0.234392
0.017518
0.012594
0.012022
0.272269
0.236432
0.178154
0.173918
0.154225
0.154225
0
0.011848
0.313623
15,863
432
141
36.719907
0.79032
0.100801
0
0.278638
0
0.003096
0.201855
0.004455
0
0
0
0
0
0
null
null
0.024768
0.049536
null
null
0.167183
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
0
0
1
4a38f4cdb8c158390444f36146a5ad23b2ae9c67
4,998
py
Python
jenkinsapi/view.py
julienduchesne/jenkinsapi
369dc54a8d5bb1f4e985c647378b9e1e62c26961
[ "MIT" ]
null
null
null
jenkinsapi/view.py
julienduchesne/jenkinsapi
369dc54a8d5bb1f4e985c647378b9e1e62c26961
[ "MIT" ]
52
2019-06-25T12:47:14.000Z
2021-04-12T12:24:08.000Z
jenkinsapi/view.py
klauern/jenkinsapi
605ad22a0109d3f51452c7abd23b0376a44682da
[ "MIT" ]
null
null
null
""" Module for jenkinsapi views """ import six import logging from jenkinsapi.jenkinsbase import JenkinsBase from jenkinsapi.job import Job from jenkinsapi.custom_exceptions import NotFound log = logging.getLogger(__name__) class View(JenkinsBase): """ View class """ def __init__(self, url, name, jenkins_obj): self.name = name self.jenkins_obj = jenkins_obj JenkinsBase.__init__(self, url) self.deleted = False def __str__(self): return self.name def __getitem__(self, job_name): assert isinstance(job_name, str) api_url = self.python_api_url(self.get_job_url(job_name)) return Job(api_url, job_name, self.jenkins_obj) def __contains__(self, job_name): """ True if view_name is the name of a defined view """ return job_name in self.keys() def delete(self): """ Remove this view object """ url = "%s/doDelete" % self.baseurl self.jenkins_obj.requester.post_and_confirm_status(url, data='') self.jenkins_obj.poll() self.deleted = True def keys(self): return self.get_job_dict().keys() def iteritems(self): it = six.iteritems(self.get_job_dict()) for name, url in it: yield name, Job(url, name, self.jenkins_obj) def values(self): return [a[1] for a in self.iteritems()] def items(self): return [a for a in self.iteritems()] def _get_jobs(self): if 'jobs' in self._data: for viewdict in self._data["jobs"]: yield viewdict["name"], viewdict["url"] def get_job_dict(self): return dict(self._get_jobs()) def __len__(self): return len(self.get_job_dict().keys()) def get_job_url(self, str_job_name): if str_job_name in self: return self.get_job_dict()[str_job_name] else: # noinspection PyUnboundLocalVariable views_jobs = ", ".join(self.get_job_dict().keys()) raise NotFound("Job %s is not known, available jobs" " in view are: %s" % (str_job_name, views_jobs)) def get_jenkins_obj(self): return self.jenkins_obj def add_job(self, str_job_name, job=None): """ Add job to a view :param str_job_name: name of the job to be added :param job: Job object to be added :return: True if job has been added, False if job already exists or job not known to Jenkins """ if not job: if str_job_name in self.get_job_dict(): log.warning( 'Job %s is already in the view %s', str_job_name, self.name) return False else: # Since this call can be made from nested view, # which doesn't have any jobs, we can miss existing job # Thus let's create top level Jenkins and ask him # http://jenkins:8080/view/CRT/view/CRT-FB/view/CRT-SCRT-1301/ top_jenkins = self.get_jenkins_obj().get_jenkins_obj_from_url( self.baseurl.split('view/')[0]) if not top_jenkins.has_job(str_job_name): log.error( msg='Job "%s" is not known to Jenkins' % str_job_name) return False else: job = top_jenkins.get_job(str_job_name) log.info(msg='Creating job %s in view %s' % (str_job_name, self.name)) url = '%s/addJobToView' % self.baseurl params = {'name': str_job_name} self.get_jenkins_obj().requester.post_and_confirm_status( url, data={}, params=params) self.poll() log.debug(msg='Job "%s" has been added to a view "%s"' % (job.name, self.name)) return True def _get_nested_views(self): for viewdict in self._data.get("views", []): yield viewdict["name"], viewdict["url"] def get_nested_view_dict(self): return dict(self._get_nested_views()) def get_config_xml_url(self): return '%s/config.xml' % self.baseurl def get_config(self): """ Return the config.xml from the view """ url = self.get_config_xml_url() response = self.get_jenkins_obj().requester.get_and_confirm_status(url) return response.text def update_config(self, config): """ Update the config.xml to the view """ url = self.get_config_xml_url() config = str(config) # cast unicode in case of Python 2 response = self.get_jenkins_obj().requester.post_url( url, params={}, data=config) return response.text @property def views(self): return self.get_jenkins_obj().get_jenkins_obj_from_url( self.baseurl).views
30.290909
79
0.580232
656
4,998
4.181402
0.204268
0.051039
0.047393
0.030623
0.302588
0.233686
0.131243
0.089683
0.068538
0.034998
0
0.00324
0.320728
4,998
164
80
30.47561
0.804713
0.131253
0
0.108911
0
0
0.061435
0
0
0
0
0
0.009901
1
0.207921
false
0
0.049505
0.09901
0.445545
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
0
0
0
1
4a41ae80cb8630870b8a540d9da1afa369fa489a
2,875
py
Python
supertokens_python/recipe_module.py
girish946/supertokens-python
ce0e7f6035941b3a8d3d1f7ae867224fd9c41c3c
[ "Apache-2.0" ]
36
2021-10-05T17:06:07.000Z
2022-03-29T14:11:39.000Z
supertokens_python/recipe_module.py
girish946/supertokens-python
ce0e7f6035941b3a8d3d1f7ae867224fd9c41c3c
[ "Apache-2.0" ]
56
2021-09-02T08:24:29.000Z
2022-03-30T07:29:07.000Z
supertokens_python/recipe_module.py
girish946/supertokens-python
ce0e7f6035941b3a8d3d1f7ae867224fd9c41c3c
[ "Apache-2.0" ]
8
2022-01-28T14:49:55.000Z
2022-03-26T01:28:38.000Z
# Copyright (c) 2021, VRAI Labs and/or its affiliates. All rights reserved. # # This software is licensed under the Apache License, Version 2.0 (the # "License") as published by the Apache Software Foundation. # # 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 annotations import abc from typing import Union, List, TYPE_CHECKING try: from typing import Literal except ImportError: from typing_extensions import Literal from .framework.response import BaseResponse if TYPE_CHECKING: from supertokens_python.framework.request import BaseRequest from .supertokens import AppInfo from .normalised_url_path import NormalisedURLPath from .exceptions import SuperTokensError class RecipeModule(abc.ABC): def __init__(self, recipe_id: str, app_info: AppInfo): self.recipe_id = recipe_id self.app_info = app_info def get_recipe_id(self): return self.recipe_id def get_app_info(self): return self.app_info def return_api_id_if_can_handle_request( self, path: NormalisedURLPath, method: str) -> Union[str, None]: apis_handled = self.get_apis_handled() for current_api in apis_handled: if not current_api.disabled and current_api.method == method and self.app_info.api_base_path.append( current_api.path_without_api_base_path).equals(path): return current_api.request_id return None @abc.abstractmethod def is_error_from_this_recipe_based_on_instance(self, err): pass @abc.abstractmethod def get_apis_handled(self) -> List[APIHandled]: pass @abc.abstractmethod async def handle_api_request(self, request_id: str, request: BaseRequest, path: NormalisedURLPath, method: str, response: BaseResponse): pass @abc.abstractmethod async def handle_error(self, request: BaseRequest, err: SuperTokensError, response: BaseResponse): pass @abc.abstractmethod def get_all_cors_headers(self): pass class APIHandled: def __init__(self, path_without_api_base_path: NormalisedURLPath, method: Literal['post', 'get', 'delete', 'put', 'options', 'trace'], request_id: str, disabled: bool): self.path_without_api_base_path = path_without_api_base_path self.method = method self.request_id = request_id self.disabled = disabled
34.638554
119
0.718261
378
2,875
5.240741
0.37037
0.030288
0.027764
0.036345
0.131247
0.061585
0
0
0
0
0
0.00354
0.213913
2,875
82
120
35.060976
0.873009
0.227826
0
0.192308
0
0
0.012693
0
0
0
0
0
0
1
0.153846
false
0.096154
0.211538
0.038462
0.480769
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
0
0
0
1
4a4408798c8290d4f3dfdd7e187e5ce0fde47eee
1,018
py
Python
2015/main/13/part2.py
sgravrock/adventofcode
1f5263ee242c8446ac1c08d2aef195a0a4595ccb
[ "MIT" ]
null
null
null
2015/main/13/part2.py
sgravrock/adventofcode
1f5263ee242c8446ac1c08d2aef195a0a4595ccb
[ "MIT" ]
null
null
null
2015/main/13/part2.py
sgravrock/adventofcode
1f5263ee242c8446ac1c08d2aef195a0a4595ccb
[ "MIT" ]
null
null
null
import sys import itertools def readfile(f): result = {} for line in f: fields = line.rstrip().split(" ") p1 = fields[0] p2 = fields[10].replace(".", "") n = int(fields[3]) if fields[2] == "lose": n *= -1 result[(p1, p2)] = n return result def optimal(config): add_self(config) diners = set([k[0] for k in config.keys()]) arrangements = list(itertools.permutations(diners)) all = [(arr, happiness(config, arr)) for arr in arrangements] return max(all, key=lambda p: p[1]) def happiness(config, arrangement): return sum([happiness_for_pair(config, p) for p in makepairs(arrangement)]) def happiness_for_pair(config, pair): opposite = (pair[1], pair[0]) return config[pair] + config[opposite] def add_self(config): for d in set([k[0] for k in config.keys()]): config[(d, "self")] = 0 config[("self", d)] = 0 def makepairs(arr): n = len(arr) for i in xrange(1, n): yield (arr[i-1], arr[i]) yield (arr[n-1], arr[0]) if __name__ == "__main__": print optimal(readfile(sys.stdin))
23.674419
76
0.650295
163
1,018
3.97546
0.355828
0.046296
0.040123
0.024691
0.064815
0.064815
0.064815
0.064815
0
0
0
0.024823
0.168959
1,018
42
77
24.238095
0.741135
0
0
0
0
0
0.021611
0
0
0
0
0
0
0
null
null
0
0.057143
null
null
0.028571
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
1
4a444c988302d74c981cef9771e8cb5c4e9d2945
29,855
py
Python
networking/connection/stun_client.py
bcgrendel/python_networking
b4c847d9eeeea078868b8dcb3d385e02eb0b8e96
[ "MIT" ]
null
null
null
networking/connection/stun_client.py
bcgrendel/python_networking
b4c847d9eeeea078868b8dcb3d385e02eb0b8e96
[ "MIT" ]
null
null
null
networking/connection/stun_client.py
bcgrendel/python_networking
b4c847d9eeeea078868b8dcb3d385e02eb0b8e96
[ "MIT" ]
null
null
null
import socket import sys import traceback import struct import threading; from threading import Thread; import time; import datetime; import json #import buffered_message; import hashlib from Crypto.PublicKey import RSA from connection_state import ConnectionState # publickey = RSA.importKey(key_string) import tcp; import udp; # ************* # EXAMPLE USAGE # ************* ''' import socket import tcp import udp import stun_client import time start_listening = True local_ip = socket.gethostbyname(socket.gethostname()) local_port = 30779 server_ip = socket.gethostbyname(socket.gethostname()) server_port = 30788 socket_timeout = 3.0 peer_block_manager = None client = stun_client.STUN_Client(start_listening, local_ip, local_port, server_ip, server_port, socket_timeout, peer_block_manager) # Set your available listening port ranges client.available_ports = [[35000, 35100], [36500, 36700],] # Register a user acccount with the stun server. class RegisterCallback: def __init__(self): self.error_message = "" self.success = None def handle_timeout(self, params=None): self.success = False self.error_message = "Registration request to server has timed-out." def complete_registration(self, success, error_message=""): self.success = success self.error_message = error_message username = "test_user" password = "test_pass123" profile_map = {} callback_object = RegisterCallback() registration_type = "permanent" client.register(username, password, profile_map, callback_object, registration_type) response_check_interval = 0.5; while callback_object.success == None: time.sleep(response_check_interval) if not callback_object.success: print "Error: %s" % callback_object.error_message exit() # Login with username and password. class AuthCallback: def __init__(self): self.error_message = "" self.success = None def handle_timeout(self, params=None): self.success = False self.error_message = "Authentication request to server has timed-out." def complete_authentication(self, success, error_message=""): self.success = success self.error_message = error_message callback_object = AuthCallback() login = True # this authentication is to login. It'd be False if we wanted to log out. client.authenticate(username, password, callback_object, login) while callback_object.success == None: time.sleep(response_check_interval) if not callback_object.success: print "Error: %s" % callback_object.error_message exit() # Now we can access the list of peers connected to the server. # Alternatively, assign a function reference to client.peer_map_callback (argument will be a reference to client.peer_map) to be notified of peer list updates as they are received. # # sample peer_map: # ["test_user":["test_user", None], "another_user":["another_user", None],] # Get a peer from the list. peer_username = None; for _username, data in client.peer_map.iteritems(): if username != _username: peer_username = _username break # Connect to that peer (hole-punch) class ConnectionCallback: def __init__(self): self.error_message = "" self.success = None self.client_key = None def handle_timeout(self, params=None): self.success = False self.error_message = "Connection request to server has timed-out." def complete_connection(self, peer_username, success, error_message=""): self.success = success if success: self.client_key = error_message else: self.error_message = error_message buffer_size = 128 callback_object = ConnectionCallback() client.connect_to_peer(peer_username, buffer_size, callback_object) while callback_object.success == None: time.sleep(response_check_interval) if not callback_object.success: print "Error: %s" % callback_object.error_message exit() client_key = callback_object.client_key udp_client = client.client_map[client_key] # Now you can communicate with that peer. udp_client.send_message("Greetings!") udp_client.pop_all_messages() ''' class STUN_Client: def __init__(self, start_listen_thread=False, local_ip=socket.gethostbyname(socket.gethostname()), local_port=30779, server_ip=socket.gethostbyname(socket.gethostname()), server_port=30788, socket_timeout=3.0, peer_block_manager=None): self.local_ip = local_ip; self.local_port = local_port; self.socket_timeout = socket_timeout; self.peer_block_manager = peer_block_manager; self.thread_sleep_duration = 0.1; self.error_log = []; self.username = None; self.password = None; self.profile_map = {}; self.authenticated = False; self.auth_callback = None; self.auth_keys = None; self.auth_timeout = 15; # 15 seconds is the limit for authentication requests. It's just a magic number like many of these timeout values. self.last_auth = None; self.login_expiration = 20; # login will expire after this many seconds passes without successful keep-alive authentication self.auth_keep_alive_interval = 5; self.auth_keep_alive_multiplier = 1; # Avoid hammering the server if it's down. Will increment every time re-auth fails, returns to 1 upon successful authentication. self.re_auth_ready = None; self.master_log = []; # all messages recieved self.message_log_map = {}; # log per message type. # this will handle callbacks for keeping track of whether the user's authentication expires (namely from losing connection to the server.) self.authentication_monitor_object = None; self.hole_punch_timeout = 20; self.hole_punch_max_attempts = 20; self.server_response_timeout = 20; # Server response flags. Set to None when sending a request; they are flipped to True upon receiving a response. Used for determining response time-out. self._auth_status = None; self._registration_status = None; # Private. Internal use only. self._holepunch_status = {}; self.available_ports = [[34000, 34100],] # list of ranges, e.g. ports 34000 - 34100 self.used_ports = []; self.registration_key = None; self.udp_client_keep_alive_timeout = 30; # dictionary of active udp connections (hole-punched) self.client_map = {}; self.callback_map = {}; self.send_queue = []; self.connection_state = ConnectionState(False); # Initialize TCP client. self.init_tcp_client(server_ip, server_port); self.peer_map = {}; # Start listening to the stun server. self.init_stun_listener(); self.keep_alive_monitor = KeepAliveMonitor(self); self.peer_map_callback = None; def shutdown(self, stun_only=True): self.authenticated = False; self.connection_state.active = False; # kills main thread, making the logout auth sequence impossible in its current implementation (get salt/key, then perform request) which needs the main loop. self.stun_client.disconnect(); if not stun_only: # disconnect all udp clients... for key, client in self.client_map.iteritems(): client.disconnect(); self.client_map.clear(); self.peer_map.clear(); del self.used_ports[:] def restart(self, stun_only=True): self.shutdown(stun_only); self.init_tcp_client(self.server_ip, self.server_port); self.init_stun_listener(); def log_error(self, error_message, extra=None): err_msg = "[STUN_Server] Line #%s: %s\n\n%s" % (str(traceback.tb_lineno(sys.exc_traceback)), traceback.format_exc(), sys.exc_info()); timestamp = time.time(); date_string = datetime.datetime.fromtimestamp(timestamp).strftime('(%Y-%m-%d) %H:%M:%S') self.error_log.append((timestamp, date_string, err_msg, extra)); def monitor_response(self, target_object, target_key=None, timeout=20, callback=None, callback_params=None, timeout_callback=None, timeout_callback_params=None): """Waits until target is no longer null or timeout occurs. Timeout is in seconds. target_object and target_key should be strings. If target key is not null, then target_object will be treated as a dictionary (using target_key for the index). This function is best utilized on its own separate thread.""" # Wait until salt and key have been retrieved or timeout occurs. time_elapsed = 0; start_time = time.time(); target_attribute = getattr(self, target_object); target = None; connection_state = self.connection_state #print "Monitoring for %s" % target_object; # Behold, python lambda expressions in the wild! if target_key == None: target = lambda parent: getattr(parent, target_object); else: target = lambda parent: getattr(parent, target_object)[target_key]; while time_elapsed < timeout: time_elapsed = time.time() - start_time; # check for shutdown. if not connection_state.active: return; # check for target condition if target(self) != None: break; time.sleep(self.thread_sleep_duration); # Check for timeout. if target(self) == None: #print "Timeout on %s" % target_object; has_timeout_callback = timeout_callback != None; if has_timeout_callback: if timeout_callback_params != None: timeout_callback(timeout_callback_params); else: timeout_callback(); return; #else: # print "No timeout on %s" % target_object; # Success, run the callback if one was provided (maybe not if one is only concerned with the timeout event). if callback != None: if callback_params != None: callback(target_object, target_key, callback_params); else: callback(target_object, target_key); def authenticate_thread(self, username, password, callback_object=None, login=True): # callback_object should have a complete_authentication(success, error_message) method. self.username = username; self.password = password; self.auth_callback = callback_object; timeout_handler = None; has_timeout_handler = ((callback_object != None) and (hasattr(callback_object, "handle_timeout"))) if has_timeout_handler: timeout_handler = callback_object.handle_timeout # Send salt and dynamic key retrieval request. self.auth_keys = None; message = "auth_salt_request %s" % username; if not self.stun_send_message(message): #callback_object.complete_authentication(False, "Failed to connect to the server."); if timeout_handler != None: timeout_handler("Failed to connect to the server."); return; # Wait until salt and key have been retrieved or timeout occurs. self.monitor_response("auth_keys", None, self.server_response_timeout, self.authenticate_send_credentials, [login, callback_object], timeout_handler, "Server failed to respond."); def authenticate_send_credentials(self, target_object=None, target_key=None, params=None): callback_object = None; if params != None: callback_object = params[1]; login = params[0] # hash the password salt, dynamic_key = self.auth_keys; if not salt: if callback_object != None: callback_object.complete_authentication(False, "Failed to connect to the server."); return; salted_password = "%s%s" % (salt, self.password) hashed_salted_password = hashlib.sha384(salted_password).hexdigest(); #print "hash1: %s\n" % hashed_salted_password; key_and_hash = "%s%s" % (dynamic_key, hashed_salted_password) hashed_password = hashlib.sha384(key_and_hash).hexdigest(); #print "hash2: %s" % hashed_password; self._auth_status = None; # Send authentication request. message = "authenticate %s" % json.dumps([self.username, hashed_password, login, json.dumps(self.available_ports), json.dumps(self.used_ports)]); if not self.stun_send_message(message): if callback_object != None: callback_object.complete_authentication(False, "Failed to connect to the server."); return; timeout_handler = None; has_timeout_handler = ((callback_object != None) and (hasattr(callback_object, "handle_timeout"))) if has_timeout_handler: timeout_handler = callback_object.handle_timeout self.monitor_response("_auth_status", None, self.server_response_timeout, None, None, timeout_handler); def registration_completion_handler(self, target_object, target_key, params): callback_object = params; registration_handler = None; has_registration_handler = ((callback_object != None) and (hasattr(callback_object, "complete_registration"))) if has_registration_handler: callback_object.complete_registration(True, ""); def send_encrypted_registration_request(self, target_object=None, target_key=None, params=None): username, password, profile_map, callback_object, registration_type = params; self._registration_status = None; # Construct the message. message = "%s" % json.dumps([username, password, profile_map, registration_type]); # Encrypt the message. public_key = RSA.importKey(self.registration_key) message = public_key.encrypt(message, 32); # Tack on the username in plain text and json_encode again. The STUN Server needs to username to determine which private key to use to decrypt the message. message = "register %s %s" % (username, message[0]); if not self.stun_send_message(message): callback_object.complete_registration(False, "Failed to connect to the server."); return; timeout_handler = None; has_timeout_handler = ((callback_object != None) and (hasattr(callback_object, "handle_timeout"))) if has_timeout_handler: timeout_handler = callback_object.handle_timeout # Wait until salt and key have been retrieved or timeout occurs. self.monitor_response("_registration_status", None, self.server_response_timeout, self.registration_completion_handler, callback_object, timeout_handler); def register_thread(self, username, password, profile_map, callback_object=None, registration_type="permanent"): # callback_object should have a complete_registration(success, error_message) method. self.username = username; self.password = password; self.profile_map = profile_map; self.register_callback = callback_object; self.registration_key = None; message = "register_key %s" % username; if not self.stun_send_message(message): callback_object.complete_registration(False, "Failed to connect to the server."); return; timeout_handler = None; has_timeout_handler = ((callback_object != None) and (hasattr(callback_object, "handle_timeout"))) if has_timeout_handler: timeout_handler = callback_object.handle_timeout params = [username, password, profile_map, callback_object, registration_type]; self.monitor_response("registration_key", None, self.server_response_timeout, self.send_encrypted_registration_request, params, timeout_handler); def authenticate(self, username, password, callback_object=None, login=True): """Non-blocking. Sends a user authentication request.""" # Spawn a separate thread to perform authentication. This is to keep from blocking the caller, since a callback is expected to handle results. Thread(target=self.authenticate_thread, args=(username, password, callback_object, login)).start(); def maintain_authentication(self, callback_object=None): #self.authentication_monitor_object username = self.username password = self.password last_auth = self.last_auth self.re_auth_ready = True; while self.authenticated: last_reauth = self.keep_alive_monitor.last_reauth_attempt; now = time.time(); ready_time = last_reauth + (self.auth_keep_alive_multiplier * self.auth_keep_alive_interval); time_for_another_reauth_attempt = now >= ready_time; # By re_auth_ready, I'm saying a re-authentication attempt isn't currently in progress. Yes, it's a poorly named variable. # I'll need to rename it something better. Maybe later (trademark). if self.re_auth_ready and time_for_another_reauth_attempt: self.re_auth_ready = False; self.authenticate(self.username, self.password, self.keep_alive_monitor); time.sleep(self.thread_sleep_duration); def logout(self): self.authenticated = False; self.authenticate(self.username, self.password, self.keep_alive_monitor, False); def register(self, username, password, profile_map, callback_object=None, registration_type="permanent"): """Non-blocking. Sends a user registration request. Only type of registration available for now is 'permanent'. Temporary to come later, maybe (for guests/'unregistered' users). Note that profile_map should be a json-encoded string (you can store arbitrary data here).""" # Spawn a separate thread to perform registration. This is to keep from blocking the caller, since a callback is expected to handle results. Thread(target=self.register_thread, args=(username, password, profile_map, callback_object, registration_type)).start(); def init_tcp_client(self, server_ip, server_port, buffer_size=1024): self.server_ip = server_ip; self.server_port = server_port; self.stun_client = tcp.TCP_Client(server_ip, server_port, buffer_size); def init_stun_listener(self): self.connection_state = ConnectionState(True); Thread(target=self.stun_listen_loop).start(); def stun_send_message(self, message, json_encode=False, prepare=True): try: self.stun_client.send_message(message, json_encode, prepare); return True; except: return False; def stun_listen_loop(self): connection_state = self.connection_state message_object = None while self.connection_state.active: try: message_object = self.stun_client.pop_message(); is_valid_message = ((message_object != None) and (len(message_object) > 2)); self.master_log.append(message_object); if is_valid_message: message = message_object[2]; message_type, message_body = message.split(" ",1); if message_type not in self.message_log_map: self.message_log_map[message_type] = []; self.message_log_map[message_type].append(message_object); #print "MESSAGE: %s\n" % message_object; if(message_type == "peer_map"): # peer data should be [[peer_username, public_profile_map], ...] message_data = json.loads(message_body); self.update_peer_map(message_data); if self.peer_map_callback != None: self.peer_map_callback(self.peer_map); elif(message_type == "hole_punch"): peer_allowed = True; # message body should be [listen_ip, listen_port, peer_ip, peer_port, peer_username, buffer_size] message_data = json.loads(message_body); listen_ip, listen_port, peer_ip, peer_port, peer_username, buffer_size = message_data port_in_use = False; # Ensure port isn't already in use. if listen_port in self.used_ports: port_in_use = True; self.stun_send_message("hole_punch_reject %s" % json.dumps([listen_ip, listen_port, self.username, peer_ip, peer_port, peer_username, buffer_size, port_in_use])); continue; message_body = json.dumps([listen_ip, listen_port, self.username, peer_ip, peer_port, peer_username, buffer_size, port_in_use]); if(self.peer_block_manager != None): peer_allowed = self.peer_block_manager.is_peer_allowed(message_data); if(peer_allowed): self.stun_send_message("hole_punch_ack %s" % message_body); else: self.stun_send_message("hole_punch_reject %s" % message_body); elif(message_type == "hole_punch_request_rejected"): # Deals with requests that fail due to lack of authentication (this client or the target client) or target client doesn't exist. # message_body should be [listen_ip, listen_port, self.username, target_ip, target_port, username, buffer_size] fail_type, target_username, error_message = json.loads(message_body); if target_username in self.callback_map: callback_object = self.callback_map[target_username]; callback_object.complete_connection(target_username, False, error_message); del self.callback_map[target_username]; elif(message_type == "hole_punch_rejected"): # message_body should be [listen_ip, listen_port, self.username, target_ip, target_port, username, buffer_size] message_data = json.loads(message_body); listen_ip, listen_port, self.username, target_ip, target_port, username, buffer_size = message_data client_key = "%s-%s-%s" % (target_ip, target_port, username); callback_object = None; if client_key in self.callback_map: callback_object = self.callback_map[client_key] if callback_object != None: callback_object.complete_connection(client_key, False, "Peer rejected the connection request."); del self.callback_map[client_key]; elif(message_type == "init_hole_punch"): try: listen_ip, listen_port, peer_ip, peer_port, peer_username, buffer_size = json.loads(message_body); if listen_port not in self.used_ports: self.used_ports.append(listen_port); # No else. We're just going to hope there's no way for that if to not run, and that we're just being half-assed at feeling paranoid. # My mind is feeling like it's been twisted into a few knots at this point, to be honest. Thread(target=self.connect_to_remote_peer, args=(listen_ip, listen_port, peer_ip, peer_port, buffer_size, peer_username)).start(); client_key = "%s_%s_%s" % (peer_ip, peer_port, peer_username) if peer_username in self._holepunch_status: self._holepunch_status[peer_username] = True; if peer_username in self.callback_map: self.callback_map[client_key] = self.callback_map[peer_username]; del self.callback_map[peer_username] except Exception as e: self.log_error(e); elif(message_type == "auth_keys"): # message body should be [salt, dynamic_key] self.auth_keys = json.loads(message_body); elif(message_type == "auth_response"): # message body should be [success, username, profile_map, login, error_message] success, username, profile_map, login, error_message = json.loads(message_body); self._auth_status = True; new_auth = not self.authenticated; if success: if login: self.authenticated = True; self.auth_keep_alive_multiplier = 1; self.last_auth = time.time(); self.username = username; self.profile_map = profile_map; if new_auth: Thread(target=self.maintain_authentication).start(); else: self.authenticated = False; self.auth_keep_alive_multiplier = 1; self.last_auth = time.time(); self.username = username; self.profile_map = profile_map; if self.auth_callback != None: self.auth_callback.complete_authentication(success, error_message); elif(message_type == "registration_key"): # message body should be "public_key" self.registration_key = message_body; elif(message_type == "registration_response"): # message body should be [success, username, profile_map, error_message] success, username, profile_map, error_message = json.loads(message_body); if success: self.username = username; self.profile_map = profile_map; self._registration_status = True; if self.registration_callback != None: self.register_callback.complete_registration(success, error_message); except Exception as exc: self.log_error(exc, message_object); time.sleep(self.thread_sleep_duration); def update_peer_map(self, packet): username_list = []; current_username_list = self.peer_map.keys(); for user_block in packet: peer_username, profile_map = user_block; valid_username = ((peer_username != None) and (peer_username.replace(" ","").replace("\t","").replace("\n","").replace("\r","") != "")); if valid_username: username_list.append(peer_username); self.peer_map[peer_username] = user_block; remove_username_list = []; for username in current_username_list: if username not in username_list: remove_username_list.append(username); for username in remove_username_list: del self.peer_map[username]; def auto_select_local_endpoint(self): listen_ip = self.local_ip; range_count = len(self.available_ports); for i in range(0, range_count): x = range_count - (1 + i) port_range = self.available_ports[x] port_count = port_range[1] - port_range[0] for j in range(0, port_count): port = port_range[1] - j; if port not in self.used_ports: return (listen_ip, port); return None; def connect_to_peer(self, target_username, buffer_size, callback_object=None, listen_ip = None, listen_port = None): """ callback_object should have a complete_connection(target, success, error_message) method where success is True or False. Extract info with: ip, port, username = target.split("-",2) Returns False if it fails to send request message (e.g. peer is blocked or connection to server failed.). """ local_endpoint_not_specified = ((listen_ip == None) or (listen_port == None)) if local_endpoint_not_specified: try: listen_ip, listen_port = self.auto_select_local_endpoint(); except: callback_object.complete_connection(client_key, False, "All available allowed local ports are already in use. Cannot initiate connection to peer."); return False; # Disallow connecting to yourself. What are you trying to pull? if self.username == target_username: callback_object.complete_connection(client_key, False, "You cannot connect to yourself."); return False; # disallow connecting to blocked peers. if(self.peer_block_manager != None): peer_allowed = self.peer_block_manager.is_peer_allowed([target_username, buffer_size]); if not peer_allowed: callback_object.complete_connection(client_key, False, "This peer has been blocked."); return False; client_key = target_username; self.callback_map[client_key] = callback_object; self._holepunch_status[client_key] = None; # Start hole_punch process. message = "request_hole_punch %s" % json.dumps([listen_ip, listen_port, self.username, target_username, buffer_size]) if not self.stun_send_message(message): callback_object.complete_connection(client_key, False, "Failed to connect to the server."); del self.callback_map[client_key]; return False; timeout_handler = None; has_timeout_handler = ((callback_object != None) and (hasattr(callback_object, "handle_timeout"))) if has_timeout_handler: timeout_handler = callback_object.handle_timeout # Wait until salt and key have been retrieved or timeout occurs. Thread(target=self.monitor_response, args=("_holepunch_status", client_key, self.server_response_timeout, None, None, timeout_handler)).start(); return True; def connect_to_remote_peer(self, local_ip, local_port, target_ip, target_port, buffer_size, username): """Warning: Internal use only!""" print "Connecting to remote peer." udp_client = udp.UDP_Client(True, local_ip, local_port, target_ip, target_port, buffer_size, True); client_key = "%s_%s_%s" % (target_ip, target_port, username) callback_object = None; if client_key in self.callback_map: callback_object = self.callback_map[client_key] if self.hole_punch(udp_client, self.hole_punch_max_attempts, self.hole_punch_timeout): print "Hole-punch succeeded." if callback_object != None: callback_object.complete_connection(username, True, client_key); self.client_map[client_key] = udp_client; # success, add it to the map. else: print "Hole-punch failed." # remove that port from the used ports list. port_count = len(self.used_ports); for i in range(0, port_count): if self.used_ports[i] == local_port: del self.used_ports[i] break; # run the callback, if there is one. if callback_object != None: callback_object.complete_connection(client_key, False, "Failed to connect to peer."); def hole_punch_send_loop(self, udp_client, maximum_retries=20, delay=0.5): for i in range(0, maximum_retries): udp_client.send_message("syn", False, False); time.sleep(delay); # Create and return a udp socket that has established connection with the target peer, or None if it fails. def hole_punch(self, udp_client, maximum_retries=20, timeout=20): print "Performing hole-punch." delay = 0.5 result = False; connection_state = self.connection_state Thread(target=self.hole_punch_send_loop, args=(udp_client, maximum_retries, delay)).start(); start_time = time.time(); for i in range(0, maximum_retries): time.sleep(delay) if not connection_state.active: # give up and close it out. udp_client.disconnect(); print "Fail 1"; return False; packet = ""; try: packet = udp_client.pop_message(); except: pass; if packet != None: print "hole_punch_response: " + str(packet); if len(packet) >= 3: # check the packet. if(packet[2] == "syn"): udp_client.send_message("ack", False, False); # send acknowledge elif(packet[2] == "ack"): udp_client.send_message("ack2", False, False); # send ack ack and return socket. result = True; print "Success 1"; break; elif(packet[2] == "ack2"): result = True; # ack ack received, return socket. print "Success 2"; break; # check for timeout time_elapsed = time.time() - start_time; if(time_elapsed >= timeout): print "Fail 2"; break; return result; class KeepAliveMonitor: def __init__(self, parent): self.parent = parent; self.last_reauth_attempt = time.time(); def complete_authentication(self, success, error_message=""): self.parent.re_auth_ready = True; self.last_reauth_attempt = time.time(); if not success: self.parent.auth_keep_alive_multiplier += 1; def handle_timeout(self, params=None): self.last_reauth_attempt = time.time(); self.parent.re_auth_ready = True; self.parent.auth_keep_alive_multiplier += 1;
38.374036
197
0.73589
4,073
29,855
5.138227
0.115394
0.052179
0.017202
0.009461
0.454224
0.377341
0.319381
0.282445
0.241638
0.226395
0
0.005943
0.165835
29,855
777
198
38.423423
0.834404
0.146341
0
0.300439
0
0
0.054777
0.003313
0
0
0
0
0
0
null
null
0.046053
0.032895
null
null
0.019737
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
0
0
1
4a4d871b786cc8a162c159d5da63831c271b0be6
956
py
Python
experiments/nmt/utils/vocabulary_coverage.py
lvapeab/GroundHog_INMT
d5ad1d466eaf5040e99b9aaaa1b28c96402436ce
[ "BSD-3-Clause" ]
null
null
null
experiments/nmt/utils/vocabulary_coverage.py
lvapeab/GroundHog_INMT
d5ad1d466eaf5040e99b9aaaa1b28c96402436ce
[ "BSD-3-Clause" ]
null
null
null
experiments/nmt/utils/vocabulary_coverage.py
lvapeab/GroundHog_INMT
d5ad1d466eaf5040e99b9aaaa1b28c96402436ce
[ "BSD-3-Clause" ]
null
null
null
import cPickle import argparse parser = argparse.ArgumentParser( "Computes the coverage of a shortlist in a corpus file") parser.add_argument("--vocab", required=True, help="Vocabulary to use (.pkl)") parser.add_argument("--text", required=True, help="Beam size, turns on beam-search") args = parser.parse_args() with open(args.vocab, 'rb') as f: d = cPickle.load(f) with open(args.text, 'rb') as f: text = f.read().splitlines() n_words = 0 n_unks = 0 split_vocab = 0 split_vocabulary = {} for line in text: for word in line.split(): if split_vocabulary.get(word) is None: split_vocabulary[word] = split_vocab split_vocab += 1 if d.get(word) is None: n_unks += 1 n_words += 1 print "Coverage: %f (%d unknown words out of %d of a total of %d)"%((float)(split_vocab - n_unks)/split_vocab, n_unks, split_vocab, n_words)
28.117647
140
0.621339
141
956
4.078014
0.41844
0.104348
0.057391
0.045217
0.071304
0.071304
0.071304
0
0
0
0
0.008463
0.258368
956
33
141
28.969697
0.802539
0
0
0
0
0
0.191423
0
0
0
0
0
0
0
null
null
0
0.076923
null
null
0.038462
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
0
0
1
4a54b5369073023cda9e88293fbf883952f8a99e
493
py
Python
notion/ctx.py
jfhbrook/notion-tools
dd7c7fb07f98deaf5bba236aa5b4ea3d09ff0f3d
[ "MIT" ]
1
2022-01-19T22:24:35.000Z
2022-01-19T22:24:35.000Z
notion/ctx.py
jfhbrook/notion-tools
dd7c7fb07f98deaf5bba236aa5b4ea3d09ff0f3d
[ "MIT" ]
4
2021-12-28T05:15:49.000Z
2021-12-28T05:18:25.000Z
notion/ctx.py
jfhbrook/notion-tools
dd7c7fb07f98deaf5bba236aa5b4ea3d09ff0f3d
[ "MIT" ]
null
null
null
from notion.client import NotionClient from notion.settings import Settings class Context: def __init__(self): self.settings = Settings.from_file() self._client = None def get_client(self): if not self._client: self.settings.validate() self._client = NotionClient(token_v2=self.settings.token, monitor=False) return self._client def update_settings(self, **kwargs): self.settings = self.settings.update(**kwargs)
27.388889
84
0.6714
58
493
5.5
0.413793
0.188088
0
0
0
0
0
0
0
0
0
0.002653
0.235294
493
17
85
29
0.843501
0
0
0
0
0
0
0
0
0
0
0
0
1
0.230769
false
0
0.153846
0
0.538462
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
0
0
0
1
4a5d879c71ea4b0d47b4f6335a7e75debaa68573
1,368
py
Python
modules/voxelman/config.py
Relintai/pandemonium_engine
3de05db75a396b497f145411f71eb363572b38ae
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
modules/voxelman/config.py
Relintai/pandemonium_engine
3de05db75a396b497f145411f71eb363572b38ae
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
modules/voxelman/config.py
Relintai/pandemonium_engine
3de05db75a396b497f145411f71eb363572b38ae
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
def can_build(env, platform): return True def configure(env): pass def get_doc_classes(): return [ "WorldArea", "VoxelLight", "VoxelLightNode", "VoxelLevelGenerator", "VoxelLevelGeneratorFlat", "VoxelSurfaceMerger", "VoxelSurfaceSimple", "VoxelSurface", "VoxelLibraryMerger", "VoxelLibrarySimple", "VoxelLibrary", "VoxelLibraryMergerPCM", "VoxelMaterialCache", "VoxelMaterialCachePCM", "VoxelCubePoints", "VoxelMesherCubic", "VoxelMeshData", "MarchingCubesCellData", "VoxelMesherMarchingCubes", "VoxelMesher", "EnvironmentData", "VoxelChunk", "VoxelChunkDefault", "VoxelStructure", "BlockVoxelStructure", "VoxelWorld", "VoxelMesherBlocky", "VoxelWorldBlocky", "VoxelChunkBlocky", "VoxelMesherLiquidBlocky", "VoxelWorldMarchingCubes", "VoxelChunkMarchingCubes", "VoxelMesherCubic", "VoxelWorldCubic", "VoxelChunkCubic", "VoxelMesherDefault", "VoxelWorldDefault", "VoxelJob", "VoxelTerrainJob", "VoxelLightJob", "VoxelPropJob", "VoxelMesherJobStep", ] def get_doc_path(): return "doc_classes"
18.739726
35
0.576754
65
1,368
12.046154
0.830769
0.015326
0.022989
0
0
0
0
0
0
0
0
0
0.318713
1,368
72
36
19
0.840129
0
0
0.039216
0
0
0.506589
0.13104
0
0
0
0
0
1
0.078431
false
0.019608
0
0.058824
0.137255
0
0
0
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
4a6725140b49d63b56d6ce94163eb9cfc057133e
4,295
py
Python
content_generator/vitae.py
empiricalstateofmind/personal_website
cb361f9fd6bd1b1dc8dd39c87cc003d847ae4a2c
[ "MIT" ]
null
null
null
content_generator/vitae.py
empiricalstateofmind/personal_website
cb361f9fd6bd1b1dc8dd39c87cc003d847ae4a2c
[ "MIT" ]
3
2015-09-10T09:26:29.000Z
2015-10-30T10:47:33.000Z
content_generator/vitae.py
empiricalstateofmind/personal_website
cb361f9fd6bd1b1dc8dd39c87cc003d847ae4a2c
[ "MIT" ]
null
null
null
# Generate the vitae.json file used to populate the Vitae section of the website. import pandas as pd import re from datetime import datetime from collections import defaultdict import json # Publications def create_publications(filepath): publications = pd.read_excel(filepath, sheet_name='publications', endcoding='utf-8') publications = publications.fillna('') publication_store = defaultdict(list) for ix, pub in publications.iterrows(): date = pub.publication_date.strftime('%Y') entry = {'title': pub.title, 'authors': pub.authors, 'arxiv': pub.arxiv_link, 'abstract':pub.abstract, 'date': date} if pub.journal_link != '': entry['link'] = pub.journal_link if pub.journal != '': entry['journal'] = pub.journal publication_store[pub.type].append(entry) return publication_store def create_conferences(filepath): conferences = pd.read_excel(filepath, sheet_name='conferences', endcoding='utf-8') conferences = conferences.fillna('') categories = [('invited', 'Invited Talks \& Posters'), ('contributed', 'Contributed Talks \& Posters'), ('attended', 'Attended'), ('school', 'Schools')] conference_store = {} for key, subtitle in categories: data = conferences[conferences.type == key] collection = [] if len(data) > 0: for ix, conf in data.iterrows(): if conf.include=='no': continue date = conf.timestamp.strftime('%b. %Y') if key in ['attended', 'school']: contribution = 'Attendee' else: contribution = "{} {}".format(conf.type.capitalize(), conf.medium.capitalize()) entry = {'title':conf.title, 'location':conf.location, 'date':date, 'contribution': contribution, } if conf.link != '': entry['link'] = conf.link if (conf.presentation_title != '') & (conf.presentation_authors != ''): entry['presentation_authors'] = conf.presentation_authors entry['presentation_title'] = conf.presentation_title collection.append(entry) conference_store[key] = collection return conference_store def create_teaching(filepath): teaching = pd.read_excel(filepath, sheet_name='teaching', endcoding='utf-8') teaching = teaching.fillna('') teaching_store = [] for ix, teach in teaching.sort_values(by='type').iterrows(): if teach['type'] == 'supervision': entry = { 'date': teach.date, 'project_award': teach.program, 'title': teach.title, 'student': teach.student_name, 'institution': teach.location } teaching_store.append(entry) return teaching_store def create_reviewing(filepath): reviewing = pd.read_excel(filepath, sheet_name='journals', endcoding='utf-8') reviewing = reviewing.fillna('') review_store = [] for ix, review in reviewing.iterrows(): entry = {'name': review.journal_name, 'short_name': review.journal_shortname} review_store.append(entry) return review_store if __name__ == "__main__": # FILEPATH = "D:/Dropbox/projects/personal_cv/vitae.xlsx" # We can pass this as an argument later FILEPATH = "../../../Projects/personal_cv/vitae.xlsx" vitae = {'publications':create_publications(FILEPATH), 'conferences':create_conferences(FILEPATH), 'teaching':create_teaching(FILEPATH), 'reviewing':create_reviewing(FILEPATH)} with open('../app/mod_home/static/vitae.json', 'w') as file: json.dump(vitae, file, sort_keys=True, indent=4) with open('../app/static/vitae.json', 'w') as file: json.dump(vitae, file, sort_keys=True, indent=4)
33.818898
102
0.563213
416
4,295
5.677885
0.302885
0.015241
0.018628
0.032176
0.15326
0.096528
0.049111
0.049111
0.049111
0.049111
0
0.002384
0.316414
4,295
127
103
33.818898
0.802112
0.043539
0
0.022727
1
0
0.132227
0.024384
0
0
0
0
0
1
0.045455
false
0
0.056818
0
0.147727
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
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
4a6776593c88474050fcd17038b16a7c7bc8d4c6
7,509
py
Python
cement/ext/ext_generate.py
tomekr/cement
fece8629c48bcd598fd61d8aa7457a5df4c4f831
[ "BSD-3-Clause" ]
826
2015-01-09T13:23:35.000Z
2022-03-18T01:19:40.000Z
cement/ext/ext_generate.py
tomekr/cement
fece8629c48bcd598fd61d8aa7457a5df4c4f831
[ "BSD-3-Clause" ]
316
2015-01-14T10:35:22.000Z
2022-03-08T17:18:10.000Z
cement/ext/ext_generate.py
tomekr/cement
fece8629c48bcd598fd61d8aa7457a5df4c4f831
[ "BSD-3-Clause" ]
112
2015-01-10T15:04:26.000Z
2022-03-16T08:11:58.000Z
""" Cement generate extension module. """ import re import os import inspect import yaml import shutil from .. import Controller, minimal_logger, shell from ..utils.version import VERSION, get_version LOG = minimal_logger(__name__) class GenerateTemplateAbstractBase(Controller): class Meta: pass def _generate(self, source, dest): msg = 'Generating %s %s in %s' % ( self.app._meta.label, self._meta.label, dest ) self.app.log.info(msg) data = {} # builtin vars maj_min = float('%s.%s' % (VERSION[0], VERSION[1])) data['cement'] = {} data['cement']['version'] = get_version() data['cement']['major_version'] = VERSION[0] data['cement']['minor_version'] = VERSION[1] data['cement']['major_minor_version'] = maj_min f = open(os.path.join(source, '.generate.yml')) yaml_load = yaml.full_load if hasattr(yaml, 'full_load') else yaml.load g_config = yaml_load(f) f.close() vars = g_config.get('variables', {}) exclude_list = g_config.get('exclude', []) ignore_list = g_config.get('ignore', []) # default ignore the .generate.yml config g_config_yml = r'^(.*)[\/\\\\]%s[\/\\\\]\.generate\.yml$' % \ self._meta.label ignore_list.append(g_config_yml) var_defaults = { 'name': None, 'prompt': None, 'validate': None, 'case': None, 'default': None, } for defined_var in vars: var = var_defaults.copy() var.update(defined_var) for key in ['name', 'prompt']: assert var[key] is not None, \ "Required generate config key missing: %s" % key val = None if var['default'] is not None and self.app.pargs.defaults: val = var['default'] elif var['default'] is not None: default_text = ' [%s]' % var['default'] else: default_text = '' # pragma: nocover if val is None: class MyPrompt(shell.Prompt): class Meta: text = "%s%s:" % (var['prompt'], default_text) default = var.get('default', None) p = MyPrompt() val = p.prompt() # pragma: nocover if var['case'] in ['lower', 'upper', 'title']: val = getattr(val, var['case'])() elif var['case'] is not None: self.app.log.warning( "Invalid configuration for variable " + "'%s': " % var['name'] + "case must be one of lower, upper, or title." ) if var['validate'] is not None: assert re.match(var['validate'], val), \ "Invalid Response (must match: '%s')" % var['validate'] data[var['name']] = val try: self.app.template.copy(source, dest, data, force=self.app.pargs.force, ignore=ignore_list, exclude=exclude_list) except AssertionError as e: if re.match('(.*)already exists(.*)', e.args[0]): raise AssertionError(e.args[0] + ' (try: --force)') else: raise # pragma: nocover def _clone(self, source, dest): msg = 'Cloning %s %s template to %s' % ( self.app._meta.label, self._meta.label, dest ) self.app.log.info(msg) if os.path.exists(dest) and self.app.pargs.force is True: shutil.rmtree(dest) elif os.path.exists(dest): msg = "Destination path already exists: %s (try: --force)" % dest raise AssertionError(msg) shutil.copytree(source, dest) def _default(self): source = self._meta.source_path dest = self.app.pargs.dest if self.app.pargs.clone is True: self._clone(source, dest) else: self._generate(source, dest) def setup_template_items(app): template_dirs = [] template_items = [] # look in app template dirs for path in app._meta.template_dirs: subpath = os.path.join(path, 'generate') if os.path.exists(subpath) and subpath not in template_dirs: template_dirs.append(subpath) # use app template module, find it's path on filesystem if app._meta.template_module is not None: mod_parts = app._meta.template_module.split('.') mod = mod_parts.pop() try: mod = app.__import__(mod, from_module='.'.join(mod_parts)) mod_path = os.path.dirname(inspect.getfile(mod)) subpath = os.path.join(mod_path, 'generate') if os.path.exists(subpath) and subpath not in template_dirs: template_dirs.append(subpath) # FIXME: not exactly sure how to test for this so not covering except AttributeError: # pragma: nocover msg = 'unable to load template module' + \ '%s from %s' % (mod, '.'.join(mod_parts)) # pragma: nocover app.log.debug(msg) # pragma: nocover for path in template_dirs: for item in os.listdir(path): if item not in template_items: template_items.append(item) class GenerateTemplate(GenerateTemplateAbstractBase): class Meta: label = item stacked_on = 'generate' stacked_type = 'nested' help = 'generate %s from template' % item arguments = [ # ------------------------------------------------------ (['dest'], {'help': 'destination directory path'}), # ------------------------------------------------------ (['-f', '--force'], {'help': 'force operation if destination exists', 'dest': 'force', 'action': 'store_true'}), # ------------------------------------------------------ (['-D', '--defaults'], {'help': 'use all default variable values', 'dest': 'defaults', 'action': 'store_true'}), # ------------------------------------------------------ (['--clone'], {'help': 'clone this template to destination path', 'dest': 'clone', 'action': 'store_true'}), ] source_path = os.path.join(path, item) app.handler.register(GenerateTemplate) class Generate(Controller): class Meta: label = 'generate' stacked_on = 'base' stacked_type = 'nested' config_section = 'generate' def _setup(self, app): super(Generate, self)._setup(app) def _default(self): self._parser.print_help() def load(app): app.handler.register(Generate) app.hook.register('pre_run', setup_template_items)
35.088785
80
0.481555
754
7,509
4.669761
0.233422
0.023857
0.015337
0.011928
0.088043
0.077251
0.077251
0.077251
0.077251
0.077251
0
0.001276
0.373818
7,509
213
81
35.253521
0.747554
0.072446
0
0.149068
1
0
0.14475
0.005617
0
0
0
0.004695
0.031056
1
0.043478
false
0.006211
0.049689
0
0.142857
0.006211
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
0
0
1
4a71705f7aaede9643300a7a698cb26841f08adc
1,936
py
Python
tests/test_pandas.py
ONSdigital/ons_utils
5ff0952c174984deb601af8ad4c21f26c7b24623
[ "MIT" ]
null
null
null
tests/test_pandas.py
ONSdigital/ons_utils
5ff0952c174984deb601af8ad4c21f26c7b24623
[ "MIT" ]
null
null
null
tests/test_pandas.py
ONSdigital/ons_utils
5ff0952c174984deb601af8ad4c21f26c7b24623
[ "MIT" ]
1
2022-03-17T08:03:17.000Z
2022-03-17T08:03:17.000Z
"""Tests for the pandas helpers in the pd_helpers.py module.""" import pytest from pandas.testing import assert_frame_equal from tests.conftest import create_dataframe from ons_utils.pandas import * def test_nested_dict_to_df(): """Test for nested_dict_to_df.""" input_d = { 'bones': { 'femur': {'tendons': 24}, 'humerus': {'tendons': 14}, }, 'muscles': { 'gluteus_maximus': {'tendons': 18}, }, 'cars': 7, } actual = nested_dict_to_df( input_d, columns=['number'], level_names=('a', 'b', 'c'), ) expected = create_dataframe([ ('a', 'b', 'c', 'number'), ('bones', 'femur', 'tendons', 24), ('bones', 'humerus', 'tendons', 14), ('cars', None, None, 7), ('muscles', 'gluteus_maximus', 'tendons', 18), ]) assert_frame_equal( # Sort values as dict order not preserved. actual.sort_values(['a', 'b']), # Set index because function returns a MultiIndex. expected.set_index(['a', 'b', 'c']) ) class TestStacker: """Group of tests for Stacker.""" @pytest.mark.skip(reason="test shell") def test_Stacker(self): """Test for Stacker.""" pass @pytest.mark.skip(reason="test shell") def test_convert_level_to_datetime(): """Test for this.""" pass class TestMultiIndexSlicer: """Group of tests for MultiIndexSlicer.""" @pytest.mark.skip(reason="test shell") def test_MultiIndexSlicer(self): """Test for MultiIndexSlicer.""" pass @pytest.mark.skip(reason="test shell") def test_get_index_level_values(): """Test for this.""" pass @pytest.mark.skip(reason="test shell") def test_shifted_within_year_apply(): """Test for this.""" pass @pytest.mark.skip(reason="test shell") def test_shifted_within_year_ffill(): """Test for this.""" pass
22.776471
63
0.591426
231
1,936
4.770563
0.367965
0.044465
0.076225
0.108893
0.352087
0.297641
0.261343
0.261343
0.196007
0.123412
0
0.009642
0.25
1,936
84
64
23.047619
0.749311
0.178719
0
0.235294
0
0
0.140442
0
0
0
0
0
0.039216
1
0.137255
false
0.117647
0.078431
0
0.254902
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
0
0
0
1
4a73d46ee78874a78fab6b3b0aaa918a453b1649
8,296
py
Python
source/accounts/views.py
kishan2064/hashpy1
2f8c6fddb07e80e9a7b37a5632ed8ab8bf68d264
[ "BSD-3-Clause" ]
null
null
null
source/accounts/views.py
kishan2064/hashpy1
2f8c6fddb07e80e9a7b37a5632ed8ab8bf68d264
[ "BSD-3-Clause" ]
5
2020-02-11T22:31:59.000Z
2021-06-10T17:45:14.000Z
source/accounts/views.py
kishan2064/hashpy1
2f8c6fddb07e80e9a7b37a5632ed8ab8bf68d264
[ "BSD-3-Clause" ]
null
null
null
from django.contrib.auth import login, authenticate, REDIRECT_FIELD_NAME, get_user_model from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.views import PasswordResetView as BasePasswordResetView, SuccessURLAllowedHostsMixin from django.shortcuts import get_object_or_404, resolve_url from django.utils.crypto import get_random_string from django.utils.decorators import method_decorator from django.utils.http import is_safe_url from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_protect from django.views.decorators.debug import sensitive_post_parameters from django.utils.translation import gettext_lazy as _ from django.views.generic import RedirectView from django.views.generic.edit import FormView from django.conf import settings from .utils import ( get_login_form, send_activation_email, get_password_reset_form, send_reset_password_email, send_activation_change_email, is_username_disabled, get_resend_ac_form ) from .forms import SignUpForm, ProfileEditForm, ChangeEmailForm from .models import Activation UserModel = get_user_model() class SuccessRedirectView(SuccessURLAllowedHostsMixin, FormView): redirect_field_name = REDIRECT_FIELD_NAME def get_success_url(self): url = self.get_redirect_url() return url or resolve_url(settings.LOGIN_REDIRECT_URL) def get_redirect_url(self): redirect_to = self.request.POST.get( self.redirect_field_name, self.request.GET.get(self.redirect_field_name, '') ) url_is_safe = is_safe_url( url=redirect_to, allowed_hosts=self.get_success_url_allowed_hosts(), require_https=self.request.is_secure(), ) return redirect_to if url_is_safe else '' def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['request'] = self.request return kwargs class SignInView(SuccessRedirectView): template_name = 'accounts/login.html' form_class = get_login_form() success_url = '/' @method_decorator(sensitive_post_parameters('password')) @method_decorator(csrf_protect) @method_decorator(never_cache) def dispatch(self, request, *args, **kwargs): # Sets a test cookie to make sure the user has cookies enabled request.session.set_test_cookie() return super(SignInView, self).dispatch(request, *args, **kwargs) def form_valid(self, form): # If the test cookie worked, go ahead and # delete it since its no longer needed if self.request.session.test_cookie_worked(): self.request.session.delete_test_cookie() login(self.request, form.get_user()) return super(SignInView, self).form_valid(form) class SignUpView(FormView): template_name = 'accounts/register.html' form_class = SignUpForm success_url = '/' def form_valid(self, form): user = form.save(commit=False) if is_username_disabled(): # Set temporary username user.username = get_random_string() else: user.username = form.cleaned_data.get('username') if settings.ENABLE_USER_ACTIVATION: user.is_active = False user.save() # Change the username to "user_ID" form if is_username_disabled(): user.username = 'user_{}'.format(user.id) user.save() if settings.ENABLE_USER_ACTIVATION: send_activation_email(self.request, user) messages.add_message(self.request, messages.SUCCESS, _('You are registered. To activate the account, follow the link sent to the mail.')) else: raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(self.request, user) messages.add_message(self.request, messages.SUCCESS, _('You are successfully registered!')) return super(SignUpView, self).form_valid(form) class ActivateView(RedirectView): permanent = False query_string = True pattern_name = 'index' def get_redirect_url(self, *args, **kwargs): assert 'code' in kwargs act = get_object_or_404(Activation, code=kwargs['code']) # Activate user's profile user = act.user user.is_active = True user.save() # Remove activation record, it is unneeded act.delete() messages.add_message(self.request, messages.SUCCESS, _('You have successfully activated your account!')) login(self.request, user) return super(ActivateView, self).get_redirect_url() class ReSendActivationCodeView(SuccessRedirectView): template_name = 'accounts/resend_activation_code.html' form_class = get_resend_ac_form() success_url = '/' def form_valid(self, form): user = form.get_user() activation = user.activation_set.get() activation.delete() send_activation_email(self.request, user) messages.add_message(self.request, messages.SUCCESS, _('A new activation code has been sent to your e-mail.')) return super(ReSendActivationCodeView, self).form_valid(form) class PasswordResetView(BasePasswordResetView): form_class = get_password_reset_form() def form_valid(self, form): send_reset_password_email(self.request, form.get_user()) return super(PasswordResetView, self).form_valid(form) class ProfileEditView(LoginRequiredMixin, FormView): template_name = 'accounts/profile/edit.html' form_class = ProfileEditForm success_url = '/accounts/profile/edit/' def get_initial(self): initial = super(ProfileEditView, self).get_initial() user = self.request.user initial['first_name'] = user.first_name initial['last_name'] = user.last_name return initial def form_valid(self, form): user = self.request.user user.first_name = form.cleaned_data.get('first_name') user.last_name = form.cleaned_data.get('last_name') user.save() messages.add_message(self.request, messages.SUCCESS, _('Profile data has been successfully updated.')) return super(ProfileEditView, self).form_valid(form) class ChangeEmailView(LoginRequiredMixin, FormView): template_name = 'accounts/profile/change_email.html' form_class = ChangeEmailForm success_url = '/accounts/change/email/' def get_form_kwargs(self): kwargs = super(ChangeEmailView, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs def get_initial(self): initial = super(ChangeEmailView, self).get_initial() user = self.request.user initial['email'] = user.email return initial def form_valid(self, form): user = self.request.user email = form.cleaned_data.get('email') email = email.lower() if hasattr(settings, 'EMAIL_ACTIVATION_AFTER_CHANGING') and settings.EMAIL_ACTIVATION_AFTER_CHANGING: send_activation_change_email(self.request, user, email) messages.add_message(self.request, messages.SUCCESS, _('To complete the change of mail, click on the link sent to it.')) else: user.email = email user.save() messages.add_message(self.request, messages.SUCCESS, _('Email successfully changed.')) return super(ChangeEmailView, self).form_valid(form) class ChangeEmailActivateView(RedirectView): permanent = False query_string = True pattern_name = 'change_email' def get_redirect_url(self, *args, **kwargs): assert 'code' in kwargs act = get_object_or_404(Activation, code=kwargs['code']) # Change user's email user = act.user user.email = act.email user.save() # Remove activation record, it is unneeded act.delete() messages.add_message(self.request, messages.SUCCESS, _('You have successfully changed your email!')) return super(ChangeEmailActivateView, self).get_redirect_url()
32.155039
118
0.690333
988
8,296
5.573887
0.184211
0.053931
0.027238
0.031959
0.345742
0.261304
0.231524
0.200291
0.166879
0.134193
0
0.001547
0.22095
8,296
257
119
32.280156
0.850534
0.039055
0
0.319527
0
0
0.090304
0.024491
0
0
0
0
0.011834
1
0.088757
false
0.053254
0.106509
0
0.473373
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
0
0
0
1
4a78cf1db1ffe2307d7c782737a9e5d96a2685ca
1,254
py
Python
workbox/workbox/lib/helpers.py
pr3sto/workbox
558147a1a387dcfbe03be0fbc366d1d793364da6
[ "MIT" ]
null
null
null
workbox/workbox/lib/helpers.py
pr3sto/workbox
558147a1a387dcfbe03be0fbc366d1d793364da6
[ "MIT" ]
null
null
null
workbox/workbox/lib/helpers.py
pr3sto/workbox
558147a1a387dcfbe03be0fbc366d1d793364da6
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """Template Helpers used in workbox""" import logging import socket from datetime import datetime from markupsafe import Markup import psutil import tg log = logging.getLogger(__name__) def current_year(): """ Return current year. """ now = datetime.now() return now.strftime('%Y') def is_docker_enabled(): """ Detect if docker service is started. """ for proc in psutil.process_iter(): if 'docker' in proc.name(): return True return False def get_server_load_value(): """ Get server load value. """ return psutil.virtual_memory().percent def get_free_port(): """ Find and returns free port number. """ soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc.bind(("", 0)) free_port = soc.getsockname()[1] soc.close() return free_port def get_vagrantfiles_base_folder(): """ Return base folder for vagrantfiles. """ return tg.config.get('workbox.vagrantfiles.basefolder') def get_hostname(): """ Return hostname. """ return tg.config.get('workbox.hostname') try: from webhelpers2 import date, html, number, misc, text except SyntaxError: log.error("WebHelpers2 helpers not available with this Python Version")
22.392857
75
0.679426
161
1,254
5.15528
0.521739
0.028916
0.031325
0.043373
0.057831
0
0
0
0
0
0
0.004975
0.198565
1,254
55
76
22.8
0.820896
0.184211
0
0
0
0
0.115189
0.0316
0
0
0
0
0
1
0.193548
false
0
0.225806
0
0.645161
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
4a7c28f2d0e401facd4b7a43c6ef059a3a83d500
1,193
py
Python
neutron/agent/ovsdb/native/helpers.py
congnt95/neutron
6a73a362c5ff5b7c28c15a49f47a9900c0d2b4e1
[ "Apache-2.0" ]
1,080
2015-01-04T08:35:00.000Z
2022-03-27T09:15:52.000Z
neutron/agent/ovsdb/native/helpers.py
congnt95/neutron
6a73a362c5ff5b7c28c15a49f47a9900c0d2b4e1
[ "Apache-2.0" ]
24
2015-02-21T01:48:28.000Z
2021-11-26T02:38:56.000Z
neutron/agent/ovsdb/native/helpers.py
congnt95/neutron
6a73a362c5ff5b7c28c15a49f47a9900c0d2b4e1
[ "Apache-2.0" ]
1,241
2015-01-02T10:47:10.000Z
2022-03-27T09:42:23.000Z
# Copyright (c) 2015 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import functools from oslo_config import cfg from neutron.conf.agent import ovs_conf as agent_ovs_conf from neutron.conf.plugins.ml2.drivers import ovs_conf as ml2_ovs_conf from neutron.privileged.agent.ovsdb.native import helpers as priv_helpers agent_ovs_conf.register_ovs_agent_opts(cfg.CONF) ml2_ovs_conf.register_ovs_opts(cfg=cfg.CONF) enable_connection_uri = functools.partial( priv_helpers.enable_connection_uri, log_fail_as_error=False, check_exit_code=False, timeout=cfg.CONF.OVS.ovsdb_timeout, inactivity_probe=cfg.CONF.OVS.of_inactivity_probe * 1000)
37.28125
78
0.776194
186
1,193
4.811828
0.537634
0.067039
0.02905
0.035754
0
0
0
0
0
0
0
0.014911
0.156748
1,193
31
79
38.483871
0.874751
0.487846
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.416667
0
0.416667
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
0
0
0
1
4a7c6a7695f0b0415525906b878d73cc448533e5
264
py
Python
console_weather.py
AlBan52/API_weather
86779a2da622ad7a4537070e5c28a04235415161
[ "MIT" ]
null
null
null
console_weather.py
AlBan52/API_weather
86779a2da622ad7a4537070e5c28a04235415161
[ "MIT" ]
null
null
null
console_weather.py
AlBan52/API_weather
86779a2da622ad7a4537070e5c28a04235415161
[ "MIT" ]
null
null
null
import requests locations = ['Лондон', 'Шереметьево', 'Череповец'] payload = {'mnTq': '', 'lang': 'ru'} for location in locations: response = requests.get(f'http://wttr.in/{location}', params=payload) response.raise_for_status() print(response.text)
26.4
73
0.681818
31
264
5.741935
0.741935
0
0
0
0
0
0
0
0
0
0
0
0.140152
264
9
74
29.333333
0.784141
0
0
0
0
0
0.231061
0
0
0
0
0
0
1
0
false
0
0.142857
0
0.142857
0.142857
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
0
0
1
4a82ccd998802091de5e9ed946344d30c5ebeba5
8,124
py
Python
geopy/geocoders/google.py
ulope/geopy
605d0d84137a93949ad03820fa31dc2dab77f089
[ "MIT" ]
1
2021-03-12T15:31:30.000Z
2021-03-12T15:31:30.000Z
geopy/geocoders/google.py
ulope/geopy
605d0d84137a93949ad03820fa31dc2dab77f089
[ "MIT" ]
null
null
null
geopy/geocoders/google.py
ulope/geopy
605d0d84137a93949ad03820fa31dc2dab77f089
[ "MIT" ]
null
null
null
import logging from urllib import urlencode from urllib2 import urlopen import simplejson import xml from xml.parsers.expat import ExpatError from geopy.geocoders.base import Geocoder from geopy import Point, Location, util class Google(Geocoder): """Geocoder using the Google Maps API.""" def __init__(self, api_key=None, domain='maps.google.com', resource='maps/geo', format_string='%s', output_format='kml'): """Initialize a customized Google geocoder with location-specific address information and your Google Maps API key. ``api_key`` should be a valid Google Maps API key. It is required for the 'maps/geo' resource to work. ``domain`` should be a the Google Maps domain to connect to. The default is 'maps.google.com', but if you're geocoding address in the UK (for example), you may want to set it to 'maps.google.co.uk'. ``resource`` is the HTTP resource to give the query parameter. 'maps/geo' is the HTTP geocoder and is a documented API resource. 'maps' is the actual Google Maps interface and its use for just geocoding is undocumented. Anything else probably won't work. ``format_string`` is a string containing '%s' where the string to geocode should be interpolated before querying the geocoder. For example: '%s, Mountain View, CA'. The default is just '%s'. ``output_format`` can be 'json', 'xml', 'kml', 'csv', or 'js' and will control the output format of Google's response. The default is 'kml' since it is supported by both the 'maps' and 'maps/geo' resources. The 'js' format is the most likely to break since it parses Google's JavaScript, which could change. However, it currently returns the best results for restricted geocoder areas such as the UK. """ self.api_key = api_key self.domain = domain self.resource = resource self.format_string = format_string self.output_format = output_format @property def url(self): domain = self.domain.strip('/') resource = self.resource.strip('/') return "http://%(domain)s/%(resource)s?%%s" % locals() def geocode(self, string, exactly_one=True, language_code=None, sensor=False, viewport_center=None, viewport_span=None): params = {'q': self.format_string % string, 'output': self.output_format.lower(), 'sensor': str(sensor).lower(), } if language_code: params.update({'gl': language_code}) if viewport_center and viewport_span: params.update({ 'll': viewport_center, 'spn': viewport_span, }) if self.resource.rstrip('/').endswith('geo'): # An API key is only required for the HTTP geocoder. params['key'] = self.api_key url = self.url % urlencode(params) return self.geocode_url(url, exactly_one) def reverse(self, coord, exactly_one=True): (lat,lng) = coord params = {'q': self.format_string % lat+','+self.format_string % lng, 'output': self.output_format.lower() } if self.resource.rstrip('/').endswith('geo'): # An API key is only required for the HTTP geocoder. params['key'] = self.api_key url = self.url % urlencode(params) return self.geocode_url(url, exactly_one, reverse=True) def geocode_url(self, url, exactly_one=True, reverse=False): logging.getLogger().info("Fetching %s..." % url) page = urlopen(url) dispatch = getattr(self, 'parse_' + self.output_format) return dispatch(page, exactly_one, reverse) def parse_xml(self, page, exactly_one=True, reverse=False): """Parse a location name, latitude, and longitude from an XML response. """ if not isinstance(page, basestring): page = util.decode_page(page) try: doc = xml.dom.minidom.parseString(page) except ExpatError: places = [] else: places = doc.getElementsByTagName('Placemark') if (exactly_one and len(places) != 1) and (not reverse): raise ValueError("Didn't find exactly one placemark! " \ "(Found %d.)" % len(places)) def parse_place(place): location = util.get_first_text(place, ['address', 'name']) or None points = place.getElementsByTagName('Point') point = points and points[0] or None coords = util.get_first_text(point, 'coordinates') or None if coords: longitude, latitude = [float(f) for f in coords.split(',')[:2]] else: latitude = longitude = None _, (latitude, longitude) = self.geocode(location) return (location, (latitude, longitude)) if exactly_one: return parse_place(places[0]) else: return (parse_place(place) for place in places) def parse_csv(self, page, exactly_one=True, reverse=False): raise NotImplementedError def parse_kml(self, page, exactly_one=True, reverse=False): return self.parse_xml(page, exactly_one, reverse) def parse_json(self, page, exactly_one=True, reverse=False): if not isinstance(page, basestring): page = util.decode_page(page) json = simplejson.loads(page) places = json.get('Placemark', []) if (exactly_one and len(places) != 1) and (not reverse): raise ValueError("Didn't find exactly one placemark! " \ "(Found %d.)" % len(places)) def parse_place(place): location = place.get('address') longitude, latitude = place['Point']['coordinates'][:2] # Add support for pulling out the canonical name locality = place.get('AddressDetails',{}).get('Country',{}).get('AdministrativeArea',{}).get('Locality',{}).get('LocalityName') administrative = place.get('AddressDetails',{}).get('Country',{}).get('AdministrativeArea',{}).get('AdministrativeAreaName') return util.RichResult((location, (latitude, longitude)), locality=locality, administrative=administrative) if exactly_one: return parse_place(places[0]) else: return (parse_place(place) for place in places) def parse_js(self, page, exactly_one=True, reverse=False): """This parses JavaScript returned by queries the actual Google Maps interface and could thus break easily. However, this is desirable if the HTTP geocoder doesn't work for addresses in your country (the UK, for example). """ if not isinstance(page, basestring): page = util.decode_page(page) LATITUDE = r"[\s,]lat:\s*(?P<latitude>-?\d+\.\d+)" LONGITUDE = r"[\s,]lng:\s*(?P<longitude>-?\d+\.\d+)" LOCATION = r"[\s,]laddr:\s*'(?P<location>.*?)(?<!\\)'," ADDRESS = r"(?P<address>.*?)(?:(?: \(.*?@)|$)" MARKER = '.*?'.join([LATITUDE, LONGITUDE, LOCATION]) MARKERS = r"{markers: (?P<markers>\[.*?\]),\s*polylines:" def parse_marker(marker): latitude, longitude, location = marker location = re.match(ADDRESS, location).group('address') latitude, longitude = float(latitude), float(longitude) return (location, (latitude, longitude)) match = re.search(MARKERS, page) markers = match and match.group('markers') or '' markers = re.findall(MARKER, markers) if exactly_one: if len(markers) != 1 and (not reverse): raise ValueError("Didn't find exactly one marker! " \ "(Found %d.)" % len(markers)) marker = markers[0] return parse_marker(marker) else: return (parse_marker(marker) for marker in markers)
41.238579
139
0.601674
970
8,124
4.959794
0.242268
0.041571
0.02328
0.02619
0.302432
0.276242
0.251299
0.215963
0.192683
0.192683
0
0.001709
0.279665
8,124
196
140
41.44898
0.820403
0.018218
0
0.269841
0
0
0.107027
0.03123
0
0
0
0
0
0
null
null
0
0.063492
null
null
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
1
0
0
0
0
0
0
0
0
1
4a85a5edb74a35f6879d8683f009ca6b7f10f18c
194
py
Python
migrations/20220114_03_Heqaz-insert-default-serverinfo.py
lin483/Funny-Nations
2bb1cd23a3d5f1e4a4854c73ac27f62c98127ef6
[ "MIT" ]
126
2022-01-15T02:29:07.000Z
2022-03-30T09:57:40.000Z
migrations/20220114_03_Heqaz-insert-default-serverinfo.py
lin483/Funny-Nations
2bb1cd23a3d5f1e4a4854c73ac27f62c98127ef6
[ "MIT" ]
18
2022-01-11T22:24:35.000Z
2022-03-16T00:13:01.000Z
migrations/20220114_03_Heqaz-insert-default-serverinfo.py
lin483/Funny-Nations
2bb1cd23a3d5f1e4a4854c73ac27f62c98127ef6
[ "MIT" ]
25
2022-01-22T15:06:27.000Z
2022-03-01T04:34:19.000Z
""" insert default serverInfo """ from yoyo import step __depends__ = {'20220114_02_lHBKM-new-table-serverinfo'} steps = [ step("INSERT INTO `serverInfo` (`onlineMinute`) VALUES (0);") ]
16.166667
65
0.695876
22
194
5.863636
0.818182
0
0
0
0
0
0
0
0
0
0
0.066667
0.149485
194
11
66
17.636364
0.715152
0.128866
0
0
0
0
0.565217
0.236025
0
0
0
0
0
1
0
false
0
0.2
0
0.2
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
0
0
0
0
0
1
4a866ef89141cc4c966674193758ad5f52e83702
551
py
Python
Arknights/flags.py
AlaricGilbert/ArknightsAutoHelper
9e2db0c4e0d1be30856df731ab192da396121d94
[ "MIT" ]
null
null
null
Arknights/flags.py
AlaricGilbert/ArknightsAutoHelper
9e2db0c4e0d1be30856df731ab192da396121d94
[ "MIT" ]
1
2019-09-10T13:58:24.000Z
2019-09-10T13:58:24.000Z
Arknights/flags.py
AlaricGilbert/ArknightsAutoHelper
9e2db0c4e0d1be30856df731ab192da396121d94
[ "MIT" ]
null
null
null
TINY_WAIT = 1 SMALL_WAIT = 3 MEDIUM_WAIT = 5 BIG_WAIT = 10 SECURITY_WAIT = 15 BATTLE_FINISH_DETECT = 12 BATTLE_NONE_DETECT_TIME = 90 BATTLE_END_SIGNAL_MAX_EXECUTE_TIME = 15 # 关键动作的偏移 FLAGS_START_BATTLE_BIAS = (50, 25) FLAGS_ENSURE_TEAM_INFO_BIAS = (25, 50) # 正方形偏移 FLAGS_CLICK_BIAS_TINY = (3, 3) FLAGS_CLICK_BIAS_SMALL = (5, 5) FLAGS_CLICK_BIAS_MEDIUM = (10, 10) FLAGS_CLICK_BIAS_BIG = (15, 15) FLAGS_CLICK_BIAS_HUGE = (30, 30) # 拖动偏移 # 用于左右拖动的偏移,也就是偏移初始坐标点 FLAGS_SWIPE_BIAS_TO_LEFT = ((1, 1), (1, 1)) FLAGS_SWIPE_BIAS_TO_RIGHT = ((1, 1), (1, 1))
21.192308
44
0.751361
97
551
3.804124
0.43299
0.03252
0.189702
0.086721
0
0
0
0
0
0
0
0.094737
0.137931
551
25
45
22.04
0.682105
0.07078
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
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
0
0
0
0
0
0
0
0
1
4a868fe7e98135f318566006794d9b95f620108a
3,229
py
Python
elasticsearch/client/shutdown.py
Conky5/elasticsearch-py
93543a7fee51c0da6e898c9155bdb5f965c5bb53
[ "Apache-2.0" ]
4
2021-05-31T19:34:27.000Z
2021-06-01T18:14:31.000Z
elasticsearch/client/shutdown.py
Conky5/elasticsearch-py
93543a7fee51c0da6e898c9155bdb5f965c5bb53
[ "Apache-2.0" ]
22
2021-05-15T00:01:49.000Z
2022-02-26T00:08:00.000Z
elasticsearch/client/shutdown.py
Conky5/elasticsearch-py
93543a7fee51c0da6e898c9155bdb5f965c5bb53
[ "Apache-2.0" ]
null
null
null
# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from .utils import SKIP_IN_PATH, NamespacedClient, _make_path, query_params class ShutdownClient(NamespacedClient): @query_params() def delete_node(self, node_id, params=None, headers=None): """ Removes a node from the shutdown list `<https://www.elastic.co/guide/en/elasticsearch/reference/current>`_ .. warning:: This API is **experimental** so may include breaking changes or be removed in a future version :arg node_id: The node id of node to be removed from the shutdown state """ if node_id in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'node_id'.") return self.transport.perform_request( "DELETE", _make_path("_nodes", node_id, "shutdown"), params=params, headers=headers, ) @query_params() def get_node(self, node_id=None, params=None, headers=None): """ Retrieve status of a node or nodes that are currently marked as shutting down `<https://www.elastic.co/guide/en/elasticsearch/reference/current>`_ .. warning:: This API is **experimental** so may include breaking changes or be removed in a future version :arg node_id: Which node for which to retrieve the shutdown status """ return self.transport.perform_request( "GET", _make_path("_nodes", node_id, "shutdown"), params=params, headers=headers, ) @query_params() def put_node(self, node_id, body, params=None, headers=None): """ Adds a node to be shut down `<https://www.elastic.co/guide/en/elasticsearch/reference/current>`_ .. warning:: This API is **experimental** so may include breaking changes or be removed in a future version :arg node_id: The node id of node to be shut down :arg body: The shutdown type definition to register """ for param in (node_id, body): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.transport.perform_request( "PUT", _make_path("_nodes", node_id, "shutdown"), params=params, headers=headers, body=body, )
33.989474
85
0.637039
413
3,229
4.878935
0.346247
0.041687
0.014888
0.020844
0.451613
0.392556
0.392556
0.392556
0.392556
0.392556
0
0.001726
0.28244
3,229
94
86
34.351064
0.867933
0.531124
0
0.46875
0
0
0.116732
0
0
0
0
0
0
1
0.09375
false
0.0625
0.03125
0
0.25
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
0
0
0
1
4a89792f0a691e63a2efbaa3d996bdb8f827265c
1,170
py
Python
api/views/domain.py
lndba/apasa_backend
e0bb96e22a22f6e2a5a2826f225388113473e7e2
[ "Apache-2.0" ]
1
2019-08-06T07:31:40.000Z
2019-08-06T07:31:40.000Z
api/views/domain.py
lndba/apasa_backend
e0bb96e22a22f6e2a5a2826f225388113473e7e2
[ "Apache-2.0" ]
null
null
null
api/views/domain.py
lndba/apasa_backend
e0bb96e22a22f6e2a5a2826f225388113473e7e2
[ "Apache-2.0" ]
null
null
null
from rest_framework.viewsets import ModelViewSet,GenericViewSet from rest_framework.response import Response from api.serializers.domain import * from api.pagination.page import MyPageNumberPagination from api.models import * class MDomainListViewSet(ModelViewSet): queryset = MasterDomainName.objects.all().order_by('id') pagination_class = MyPageNumberPagination serializer_class = MDomainListSerializers class DnsListViewSet(GenericViewSet): def list(self, request, *args, **kwargs): res = {"count": 0, 'results': None} domain_id = request.query_params.get('domain') dns_list = Dns.objects.all().filter(master_domain_name=domain_id) dns_count = Dns.objects.all().filter(master_domain_name=domain_id).count() page = MyPageNumberPagination() page_dns_list = page.paginate_queryset(dns_list,request,self) ser = DnsListSerializers(instance=page_dns_list,many=True) res['results'] = ser.data res['count'] = dns_count return Response(res) class DnsUpdataViewSet(ModelViewSet): queryset = Dns.objects.all().order_by('id') serializer_class = DnsUpdataSerializers
35.454545
82
0.737607
132
1,170
6.356061
0.416667
0.047676
0.046484
0.040524
0.147795
0.102503
0.102503
0.102503
0.102503
0
0
0.00102
0.162393
1,170
32
83
36.5625
0.855102
0
0
0
0
0
0.029085
0
0
0
0
0
0
1
0.041667
false
0
0.208333
0
0.625
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
4a92c1904e0ba01d29ac9f188cf088ddb5d2ab71
1,488
py
Python
src/python/reduce_fps_parallel.py
blancKaty/alignmentFralework_and_classif
192565a928dad0d98553e0602e91eed59c4a193d
[ "Apache-2.0" ]
null
null
null
src/python/reduce_fps_parallel.py
blancKaty/alignmentFralework_and_classif
192565a928dad0d98553e0602e91eed59c4a193d
[ "Apache-2.0" ]
null
null
null
src/python/reduce_fps_parallel.py
blancKaty/alignmentFralework_and_classif
192565a928dad0d98553e0602e91eed59c4a193d
[ "Apache-2.0" ]
1
2019-10-05T05:40:08.000Z
2019-10-05T05:40:08.000Z
import os import shutil import sys import multiprocessing import glob def copy(source, dest): shutil.copyfile(source, dest) def main(): input_folder = sys.argv[1] output_folder = sys.argv[2] print 'input reduce fps : ' , sys.argv fps = int(sys.argv[3]); final_length=float(sys.argv[4]) ; max_length=final_length * fps ; print 'normalisation param : ' , fps , final_length , max_length if os.path.exists(output_folder): shutil.rmtree(output_folder) os.makedirs(output_folder) pool = multiprocessing.Pool(multiprocessing.cpu_count()) print "Using a Pool of", multiprocessing.cpu_count(), "processes" X = sorted(next(os.walk(input_folder))[1]) print X for x in X: folder = os.path.join(output_folder, x) os.mkdir(folder) #Y = os.listdir(os.path.join(input_folder, x)) #print input_folder , x Y = glob.glob(input_folder+"/"+x+"/*.jpg") Y.sort() sizeV=len(Y) #print sizeV if (sizeV > max_length) : Y=Y[int(sizeV/2)-int(max_length/2): int(sizeV/2)+int(max_length/2)] for idx, i in enumerate(range(0, len(Y), fps)): y = Y[i] source = y #print y , "image_{:05d}.jpg".format(idx + 1) y = "image_{:05d}.jpg".format(idx + 1) dest = os.path.join(folder, y) #print source , dest pool.apply_async(copy, (source, dest)) pool.close() pool.join() if __name__ == '__main__': main()
24
72
0.608871
213
1,488
4.107981
0.319249
0.062857
0.034286
0.027429
0.100571
0.100571
0.100571
0
0
0
0
0.014273
0.24664
1,488
61
73
24.393443
0.76628
0.09543
0
0
0
0
0.072388
0
0
0
0
0
0
0
null
null
0
0.125
null
null
0.1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
1
4a93ca990a939c4bbe34b2ca2569173da90ecbc7
3,598
py
Python
ansible/utils/module_docs_fragments/docker.py
EnjoyLifeFund/macHighSierra-py36-pkgs
5668b5785296b314ea1321057420bcd077dba9ea
[ "BSD-3-Clause", "BSD-2-Clause", "MIT" ]
1
2021-04-02T08:08:39.000Z
2021-04-02T08:08:39.000Z
ansible/utils/module_docs_fragments/docker.py
EnjoyLifeFund/Debian_py36_packages
1985d4c73fabd5f08f54b922e73a9306e09c77a5
[ "BSD-3-Clause", "BSD-2-Clause", "MIT" ]
null
null
null
ansible/utils/module_docs_fragments/docker.py
EnjoyLifeFund/Debian_py36_packages
1985d4c73fabd5f08f54b922e73a9306e09c77a5
[ "BSD-3-Clause", "BSD-2-Clause", "MIT" ]
1
2020-05-03T01:13:16.000Z
2020-05-03T01:13:16.000Z
# This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # class ModuleDocFragment(object): # Docker doc fragment DOCUMENTATION = ''' options: docker_host: description: - "The URL or Unix socket path used to connect to the Docker API. To connect to a remote host, provide the TCP connection string. For example, 'tcp://192.0.2.23:2376'. If TLS is used to encrypt the connection, the module will automatically replace 'tcp' in the connection URL with 'https'." required: false default: "unix://var/run/docker.sock" aliases: - docker_url tls_hostname: description: - When verifying the authenticity of the Docker Host server, provide the expected name of the server. default: localhost required: false api_version: description: - The version of the Docker API running on the Docker Host. Defaults to the latest version of the API supported by docker-py. required: false default: default provided by docker-py aliases: - docker_api_version timeout: description: - The maximum amount of time in seconds to wait on a response from the API. required: false default: 60 cacert_path: description: - Use a CA certificate when performing server verification by providing the path to a CA certificate file. required: false default: null aliases: - tls_ca_cert cert_path: description: - Path to the client's TLS certificate file. required: false default: null aliases: - tls_client_cert key_path: description: - Path to the client's TLS key file. required: false default: null aliases: - tls_client_key ssl_version: description: - Provide a valid SSL version number. Default value determined by docker-py, currently 1.0. required: false default: "1.0" tls: description: - Secure the connection to the API by using TLS without verifying the authenticity of the Docker host server. default: false tls_verify: description: - Secure the connection to the API by using TLS and verifying the authenticity of the Docker host server. default: false notes: - Connect to the Docker daemon by providing parameters with each task or by defining environment variables. You can define DOCKER_HOST, DOCKER_TLS_HOSTNAME, DOCKER_API_VERSION, DOCKER_CERT_PATH, DOCKER_SSL_VERSION, DOCKER_TLS, DOCKER_TLS_VERIFY and DOCKER_TIMEOUT. If you are using docker machine, run the script shipped with the product that sets up the environment. It will set these variables for you. See https://docker-py.readthedocs.org/en/stable/machine/ for more details. '''
38.276596
118
0.660645
476
3,598
4.930672
0.369748
0.019173
0.059651
0.024286
0.23562
0.224542
0.200682
0.200682
0.089476
0.089476
0
0.007029
0.288216
3,598
93
119
38.688172
0.90941
0.17871
0
0.388889
0
0.055556
0.971749
0.017699
0
0
0
0
0
1
0
false
0
0
0
0.027778
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
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
4a9b559c6d7c0db14da8219dc9c4e053b7a27ff8
442
bzl
Python
tools/mirrors.bzl
kkiningh/slime
85853115e284bda35b3da10957823d23428b65d3
[ "Apache-2.0" ]
null
null
null
tools/mirrors.bzl
kkiningh/slime
85853115e284bda35b3da10957823d23428b65d3
[ "Apache-2.0" ]
null
null
null
tools/mirrors.bzl
kkiningh/slime
85853115e284bda35b3da10957823d23428b65d3
[ "Apache-2.0" ]
null
null
null
DEFAULT_MIRRORS = { "bitbucket": [ "https://bitbucket.org/{repository}/get/{commit}.tar.gz", ], "buildifier": [ "https://github.com/bazelbuild/buildtools/releases/download/{version}/{filename}", ], "github": [ "https://github.com/{repository}/archive/{commit}.tar.gz", ], "pypi": [ "https://files.pythonhosted.org/packages/source/{p}/{package}/{package}-{version}.tar.gz", ], }
29.466667
98
0.58371
43
442
5.976744
0.627907
0.058366
0.085603
0
0
0
0
0
0
0
0
0
0.190045
442
14
99
31.571429
0.717877
0
0
0.285714
0
0.071429
0.687783
0
0
0
0
0
0
1
0
false
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
4a9cb65121c1db2693bb70ca50a62adb977ff292
2,059
py
Python
201805_ChIP_ATAC/codes_old/read_txt.py
ScrippsPipkinLab/GenomeTracks
89824daceba82f7a52cf8a31149845548fe1aa76
[ "CC0-1.0" ]
null
null
null
201805_ChIP_ATAC/codes_old/read_txt.py
ScrippsPipkinLab/GenomeTracks
89824daceba82f7a52cf8a31149845548fe1aa76
[ "CC0-1.0" ]
2
2020-12-09T02:41:54.000Z
2020-12-09T02:45:43.000Z
201805_ChIP_ATAC/codes_old/read_txt.py
ScrippsPipkinLab/GenomeTracks
89824daceba82f7a52cf8a31149845548fe1aa76
[ "CC0-1.0" ]
null
null
null
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Jun 6 21:15:23 2017 @author: yolandatiao """ import csv import glob import os from astropy.io import ascii # For using ascii table to open csv from astropy.table import Table, Column # For using astropy table functions os.chdir("/Volumes/Huitian/GSE88987/codes") import fc_basic_astropy_subprocess as fc os.chdir("/Volumes/Huitian/Genombrower/codes/txt") flist=[] for fname in glob.glob("*.txt"): flist.append(fname) nlist=[] fnflist=[] print len(flist) for i in flist: fnflist.append(i[:-4]) with open(i, "r") as fin: rfin=csv.reader(fin, delimiter=",") nlist.append(int(next(rfin)[0])) #print nlist outab=Table() outab["filename_nf"]=fnflist outab["bdgaccu"]=nlist ascii.write(outab, "meta.csv", format="csv", overwrite=True) metab=ascii.read("meta_write_bash.csv") metab=fc.setcolnames(metab) with open("bdgnorm.sh","r") as fin: rfin=csv.reader(fin, delimiter=",") inrow=next(rfin)[0] print inrow for x in xrange(0, len(metab)): xshname="%s.sh"%x with open(xshname, "w") as fout: wfout=csv.writer(fout, delimiter="\t") wfout.writerow(["cd /gpfs/home/hdiao/Geombrowser"]) outrow=inrow osfactor=str(metab["1000000000_scalingfactor"][x]) ofname=str(metab["filename_nf"][x]) outrow=outrow.replace("sfactor", osfactor) outrow=outrow.replace("inputfile", ofname) fout.writelines(outrow) with open("qsub.sh", "w") as fout: for x in xrange(0, 66): fout.writelines("qsub %s.sh"%x) fout.writelines("\n") os.chdir("/Volumes/Huitian/Genombrower/codes/rename") meta=ascii.read("rename_meta.csv") with open("rename.sh", "w") as fout: for x in xrange(0, len(meta)): fout.writelines("mv ") fout.writelines(meta["oldname"][x]) fout.writelines(" ") fout.writelines(meta["newnamenf"][x]) fout.writelines(".bdg") fout.writelines("\n")
21.226804
78
0.629432
283
2,059
4.547703
0.39576
0.097902
0.032634
0.048951
0.154623
0.154623
0.082362
0.082362
0.034188
0
0
0.022059
0.207382
2,059
96
79
21.447917
0.766544
0.059252
0
0.074074
0
0
0.183099
0.087757
0
0
0
0
0
0
null
null
0
0.111111
null
null
0.037037
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
1
4aa2559e81941797f8eb297eceb0ea501eab99d6
7,104
py
Python
services/spotify-service.py
thk4711/mediamanager
8f6d21c220767aa9ee5d65635d2993dba07eceed
[ "MIT" ]
null
null
null
services/spotify-service.py
thk4711/mediamanager
8f6d21c220767aa9ee5d65635d2993dba07eceed
[ "MIT" ]
null
null
null
services/spotify-service.py
thk4711/mediamanager
8f6d21c220767aa9ee5d65635d2993dba07eceed
[ "MIT" ]
1
2022-02-07T08:09:15.000Z
2022-02-07T08:09:15.000Z
#!/usr/bin/python3 # -*- coding: utf-8 -*- import time import json import os import sys import time import urllib import socket import argparse import requests import lib.common as common base_url = 'http://localhost:24879/player/' #------------------------------------------------------------------------------# # do something on startup # #------------------------------------------------------------------------------# def init(): global port check_port() script_path = os.path.dirname(os.path.abspath(__file__)) os.chdir(script_path) parser = argparse.ArgumentParser(description='media manager spotify connect service') parser.add_argument('-p', '--port', type=int, help='WEB server port', required=True) args = parser.parse_args() port = args.port #------------------------------------------------------------------------------# # check if librespot-java is running # #------------------------------------------------------------------------------# def check_port(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex(('localhost', 24879)) if result == 0: sock.close() return print("Please check if SpoCon is configured correctly and running", file = sys.stderr ) sock.close() exit(1) #------------------------------------------------------------------------------# # get metadata from spotify # #------------------------------------------------------------------------------# def get_metadata(): meta_data = {} global current_cover try: current_track = get_player() album = current_track['item']['album'] current_cover = album['images'][0]['url'] tmp_cover = current_cover tmp_cover=tmp_cover.replace('https://i.scdn.co/image/','') meta_data['track'] = current_track['item']['name'] meta_data['album'] = album['name'] meta_data['artist'] = album['artists'][0]['name'] meta_data['cover'] = 'external_' + tmp_cover meta_data['playstatus'] = get_play_status() if meta_data['playstatus'] == False: meta_data['track'] = '' meta_data['album'] = '' meta_data['artist'] = '' meta_data['cover'] = 'images/pause.png' return(bytes(json.dumps(meta_data), 'utf-8')) except: meta_data['track'] = '' meta_data['album'] = '' meta_data['artist'] = '' meta_data['cover'] = 'images/pause.png' meta_data['playstatus'] = False return(bytes(json.dumps(meta_data), 'utf-8')) #------------------------------------------------------------------------------# # get play status # #------------------------------------------------------------------------------# def get_play_status(mode=False): playing = False ret_val = False ret_str = 'NO' try: current_track = get_player() playing = current_track['is_playing'] except: pass if playing == True: try: path = 'http://localhost:24879/player/current/' ret = requests.post(url = path) data = ret.json() if 'current' in data: ret_str = 'YES' ret_val = True get_player() except: pass if mode: return(bytes(ret_str, 'utf-8')) return(ret_val) #------------------------------------------------------------------------------# # get whats currently playing # #------------------------------------------------------------------------------# def get_current(): path = 'http://localhost:24879/player/current/' ret = requests.post(url = path) return ret.json() #------------------------------------------------------------------------------# # get player data from API # #------------------------------------------------------------------------------# def get_player(): path = 'http://localhost:24879/web-api/v1/me/player' ret = requests.get(url = path) return ret.json() #------------------------------------------------------------------------------# # read cover image fom spotify connect web # #------------------------------------------------------------------------------# def read_cover_image(): webURL = urllib.request.urlopen(current_cover) data = webURL.read() return(data) #------------------------------------------------------------------------------# # play next song # #------------------------------------------------------------------------------# def next(): requests.post(url = base_url + 'next') #------------------------------------------------------------------------------# # play previuous song # #------------------------------------------------------------------------------# def prev(): requests.post(url = base_url + 'prev') #------------------------------------------------------------------------------# # start playing # #------------------------------------------------------------------------------# def play(): requests.post(url = base_url + 'resume') #------------------------------------------------------------------------------# # stop playing # #------------------------------------------------------------------------------# def pause(): requests.post(url = base_url + 'pause') #------------------------------------------------------------------------------# # handle http get request # #------------------------------------------------------------------------------# def respond_to_get_request(data): if 'action' not in data: return(bytes('failed', 'utf-8')) if data['action'] == 'play': play() elif data['action'] == 'pause': pause() elif data['action'] == 'prev': get_metadata() prev() elif data['action'] == 'next': get_metadata() next() elif data['action'] == 'metadata': return(get_metadata()) elif data['action'] == 'coverimage': return(read_cover_image()) elif data['action'] == 'getplaystatus': return(get_play_status(True)) return(bytes('OK', 'utf-8')) #------------------------------------------------------------------------------# # main program # #------------------------------------------------------------------------------# init() common.http_get_handler = respond_to_get_request common.run_http(port) while True: time.sleep(2000)
39.466667
91
0.366273
538
7,104
4.678439
0.29368
0.057211
0.035757
0.030195
0.191101
0.123957
0.123957
0.123957
0.09853
0.09853
0
0.007739
0.254223
7,104
179
92
39.687151
0.467346
0.433699
0
0.258065
0
0
0.163581
0
0
0
0
0
0
1
0.096774
false
0.016129
0.080645
0
0.201613
0.008065
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
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
1
4aa74af42d1bc1038ceab671898746be1f6af4af
3,163
py
Python
google/ads/google_ads/v0/proto/services/media_file_service_pb2_grpc.py
jwygoda/google-ads-python
863892b533240cb45269d9c2cceec47e2c5a8b68
[ "Apache-2.0" ]
null
null
null
google/ads/google_ads/v0/proto/services/media_file_service_pb2_grpc.py
jwygoda/google-ads-python
863892b533240cb45269d9c2cceec47e2c5a8b68
[ "Apache-2.0" ]
null
null
null
google/ads/google_ads/v0/proto/services/media_file_service_pb2_grpc.py
jwygoda/google-ads-python
863892b533240cb45269d9c2cceec47e2c5a8b68
[ "Apache-2.0" ]
null
null
null
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from google.ads.google_ads.v0.proto.resources import media_file_pb2 as google_dot_ads_dot_googleads__v0_dot_proto_dot_resources_dot_media__file__pb2 from google.ads.google_ads.v0.proto.services import media_file_service_pb2 as google_dot_ads_dot_googleads__v0_dot_proto_dot_services_dot_media__file__service__pb2 class MediaFileServiceStub(object): """Service to manage media files. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.GetMediaFile = channel.unary_unary( '/google.ads.googleads.v0.services.MediaFileService/GetMediaFile', request_serializer=google_dot_ads_dot_googleads__v0_dot_proto_dot_services_dot_media__file__service__pb2.GetMediaFileRequest.SerializeToString, response_deserializer=google_dot_ads_dot_googleads__v0_dot_proto_dot_resources_dot_media__file__pb2.MediaFile.FromString, ) self.MutateMediaFiles = channel.unary_unary( '/google.ads.googleads.v0.services.MediaFileService/MutateMediaFiles', request_serializer=google_dot_ads_dot_googleads__v0_dot_proto_dot_services_dot_media__file__service__pb2.MutateMediaFilesRequest.SerializeToString, response_deserializer=google_dot_ads_dot_googleads__v0_dot_proto_dot_services_dot_media__file__service__pb2.MutateMediaFilesResponse.FromString, ) class MediaFileServiceServicer(object): """Service to manage media files. """ def GetMediaFile(self, request, context): """Returns the requested media file in full detail. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def MutateMediaFiles(self, request, context): """Creates media files. Operation statuses are returned. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_MediaFileServiceServicer_to_server(servicer, server): rpc_method_handlers = { 'GetMediaFile': grpc.unary_unary_rpc_method_handler( servicer.GetMediaFile, request_deserializer=google_dot_ads_dot_googleads__v0_dot_proto_dot_services_dot_media__file__service__pb2.GetMediaFileRequest.FromString, response_serializer=google_dot_ads_dot_googleads__v0_dot_proto_dot_resources_dot_media__file__pb2.MediaFile.SerializeToString, ), 'MutateMediaFiles': grpc.unary_unary_rpc_method_handler( servicer.MutateMediaFiles, request_deserializer=google_dot_ads_dot_googleads__v0_dot_proto_dot_services_dot_media__file__service__pb2.MutateMediaFilesRequest.FromString, response_serializer=google_dot_ads_dot_googleads__v0_dot_proto_dot_services_dot_media__file__service__pb2.MutateMediaFilesResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'google.ads.googleads.v0.services.MediaFileService', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,))
48.661538
163
0.812204
379
3,163
6.192612
0.21372
0.049851
0.051129
0.063911
0.695356
0.695356
0.676608
0.590541
0.590541
0.53856
0
0.009716
0.121404
3,163
64
164
49.421875
0.834833
0.093582
0
0.2
1
0
0.105728
0.063296
0
0
0
0
0
1
0.1
false
0
0.075
0
0.225
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
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
4aaa0313e4b848ea3e028c07ae2b856db9916524
715
py
Python
arturtamborskipl/urls.py
arturtamborski/arturtamborskipl
9b93be045f58d5802d9a61568d7ecfbb12042b59
[ "MIT" ]
1
2017-05-05T12:01:43.000Z
2017-05-05T12:01:43.000Z
arturtamborskipl/urls.py
arturtamborski/arturtamborskipl
9b93be045f58d5802d9a61568d7ecfbb12042b59
[ "MIT" ]
null
null
null
arturtamborskipl/urls.py
arturtamborski/arturtamborskipl
9b93be045f58d5802d9a61568d7ecfbb12042b59
[ "MIT" ]
null
null
null
from django.conf.urls import url, include from django.contrib import admin from django.views.generic import RedirectView from django.views.generic import TemplateView from django.contrib.sitemaps.views import sitemap from django.conf import settings from blog.sitemaps import ArticleSitemap urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^robots\.txt$', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), url(r'^sitemap\.xml$', sitemap, {'sitemaps': {'blog': ArticleSitemap}}, name='sitemap'), url(r'^', include('blog.urls')), ] if settings.DEBUG: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ]
29.791667
103
0.721678
92
715
5.51087
0.380435
0.118343
0.055227
0.086785
0.110454
0
0
0
0
0
0
0
0.135664
715
23
104
31.086957
0.820388
0
0
0
0
0
0.131469
0
0
0
0
0
0
1
0
false
0
0.444444
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
0
0
0
1
0
0
0
0
1
4aab427f1e96678aba34462ced9f7928129f2aef
7,288
py
Python
lib/reinteract/editor.py
jonkuhn/reinteract-jk
319c8d930f142cf3c3b8693fbff1b84fd582387c
[ "BSD-2-Clause" ]
1
2016-05-08T14:35:25.000Z
2016-05-08T14:35:25.000Z
lib/reinteract/editor.py
jonkuhn/reinteract-jk
319c8d930f142cf3c3b8693fbff1b84fd582387c
[ "BSD-2-Clause" ]
null
null
null
lib/reinteract/editor.py
jonkuhn/reinteract-jk
319c8d930f142cf3c3b8693fbff1b84fd582387c
[ "BSD-2-Clause" ]
null
null
null
# Copyright 2008 Owen Taylor # # This file is part of Reinteract and distributed under the terms # of the BSD license. See the file COPYING in the Reinteract # distribution for full details. # ######################################################################## import os import gobject import gtk import pango from application import application from format_escaped import format_escaped from notebook import NotebookFile from shell_buffer import ShellBuffer from shell_view import ShellView from save_file import SaveFileBuilder class Editor(gobject.GObject): def __init__(self, notebook): gobject.GObject.__init__(self) self.notebook = notebook self._unsaved_index = application.allocate_unsaved_index() ####################################################### # Utility ####################################################### def _clear_unsaved(self): if self._unsaved_index != None: application.free_unsaved_index(self._unsaved_index) self._unsaved_index = None def _update_filename(self, *args): self.notify('filename') self.notify('title') def _update_modified(self, *args): self.notify('modified') self.notify('title') def _update_state(self, *args): self.notify('state') def _update_file(self): self.notify('file') def __prompt_for_name(self, title, save_button_text, action, check_name=None): builder = SaveFileBuilder(title, self._get_display_name(), save_button_text, check_name) builder.dialog.set_transient_for(self.widget.get_toplevel()) if self._get_filename() != None: builder.name_entry.set_text(os.path.basename(self._get_filename())) while True: response = builder.dialog.run() if response != gtk.RESPONSE_OK: break raw_name = builder.name_entry.get_text() error_message = None try: raw_name = application.validate_name(raw_name) except ValueError, e: error_message = e.message if not error_message: extension = "." + self._get_extension() if not (raw_name.lower().endswith(extension)): raw_name += extension if not error_message: fullname = os.path.join(self.notebook.folder, raw_name) if os.path.exists(fullname): error_message = "'%s' already exists" % raw_name if error_message: dialog = gtk.MessageDialog(parent=self.widget.get_toplevel(), buttons=gtk.BUTTONS_OK, type=gtk.MESSAGE_ERROR) dialog.set_markup("<big><b>Please choose a different name</b></big>") dialog.format_secondary_text(error_message) dialog.run() dialog.destroy() continue action(fullname) break builder.dialog.destroy() ####################################################### # Implemented by subclasses ####################################################### def _get_display_name(self): raise NotImplementedError() def _get_modified(self): raise NotImplementedError() def _get_state(self): return NotebookFile.NONE def _get_filename(self): return NotImplementedError() def _get_file(self): return NotImplementedError() def _get_extension(self): return NotImplementedError() def _save(self, filename): return NotImplementedError() ####################################################### # Public API ####################################################### def close(self): if self._unsaved_index != None: application.free_unsaved_index(self._unsaved_index) self._unsaved_index = None self.widget.destroy() def confirm_discard(self, before_quit=False): if not self.modified: return True if before_quit: message_format = self.DISCARD_FORMAT_BEFORE_QUIT continue_button_text = '_Quit without saving' else: message_format = self.DISCARD_FORMAT continue_button_text = '_Discard' if self._get_filename() == None: save_button_text = gtk.STOCK_SAVE_AS else: save_button_text = gtk.STOCK_SAVE message = format_escaped("<big><b>" + message_format + "</b></big>", self._get_display_name()) dialog = gtk.MessageDialog(parent=self.widget.get_toplevel(), buttons=gtk.BUTTONS_NONE, type=gtk.MESSAGE_WARNING) dialog.set_markup(message) dialog.add_buttons(continue_button_text, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, save_button_text, 1) dialog.set_default_response(1) response = dialog.run() dialog.destroy() if response == gtk.RESPONSE_OK: return True elif response == 1: self.save() if self.modified: return False else: return True else: return False def load(self, filename): raise NotImplementedError() def save(self, filename=None): if filename == None: filename = self._get_filename() if filename == None: def action(fullname): self._save(fullname) self._clear_unsaved() self.notebook.refresh() self.__prompt_for_name(title="Save As...", save_button_text="_Save", action=action) else: self._save(filename) def rename(self): if self._get_filename() == None: self.save() return old_name = os.path.basename(self._get_filename()) title = "Rename '%s'" % old_name def check_name(name): return name != "" and name != old_name def action(fullname): old_filename = self._get_filename() self._save(fullname) self._clear_unsaved() os.remove(old_filename) self.notebook.refresh() self.__prompt_for_name(title=title, save_button_text="_Rename", action=action, check_name=check_name) @property def needs_calculate(self): return (self.state != NotebookFile.EXECUTE_SUCCESS and self.state != NotebookFile.NONE and self.state != NotebookFile.EXECUTING) def calculate(self): pass def undo(self): pass def redo(self): pass @gobject.property def filename(self): return self._get_filename() @gobject.property def file(self): return self._get_file() @gobject.property def modified(self): return self._get_modified() @gobject.property def state(self): return self._get_state() @gobject.property def title(self): if self.modified: return "*" + self._get_display_name() else: return self._get_display_name()
29.387097
109
0.565587
748
7,288
5.240642
0.208556
0.028571
0.030612
0.020408
0.266582
0.144388
0.1
0.1
0.079082
0.079082
0
0.001366
0.296789
7,288
247
110
29.506073
0.763512
0.030873
0
0.325581
0
0
0.027515
0
0
0
0
0
0
0
null
null
0.017442
0.05814
null
null
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
1
0
0
0
0
0
0
0
0
1
4aadfd2d97ab81dd6472cc9d6d7741a3c62a553c
2,316
py
Python
server/server-flask/app/docs/admin/survey/survey.py
DSM-DMS/Project-DMS-Web
73a5d8fc2310bca90169414abf50f541ca0724c7
[ "MIT" ]
11
2017-07-04T07:44:07.000Z
2017-09-19T12:56:55.000Z
server/server-flask/app/docs/admin/survey/survey.py
DSM-DMS/DMS
73a5d8fc2310bca90169414abf50f541ca0724c7
[ "MIT" ]
null
null
null
server/server-flask/app/docs/admin/survey/survey.py
DSM-DMS/DMS
73a5d8fc2310bca90169414abf50f541ca0724c7
[ "MIT" ]
2
2017-10-23T06:11:16.000Z
2017-10-26T03:27:57.000Z
SURVEY_POST = { 'tags': ['설문조사 관리'], 'description': '설문조사 등록', 'parameters': [ { 'name': 'Authorization', 'description': 'JWT Token', 'in': 'header', 'type': 'str', 'required': True }, { 'name': 'title', 'description': '설문조사 제목', 'in': 'formData', 'type': 'str', 'required': True }, { 'name': 'start_date', 'description': '시작 날짜(YYYY-MM-DD)', 'in': 'formData', 'type': 'str', 'required': True }, { 'name': 'end_date', 'description': '종료 날짜(YYYY-MM-DD)', 'in': 'formData', 'type': 'str', 'required': True }, { 'name': 'target', 'description': '대상 학년', 'in': 'formData', 'type': 'list', 'required': True } ], 'responses': { '201': { 'description': '설문조사 등록 성공' }, '403': { 'description': '권한 없음' } } } QUESTION_POST = { 'tags': ['설문조사 관리'], 'description': '설문조사에 질문 등록', 'parameters': [ { 'name': 'Authorization', 'description': 'JWT Token', 'in': 'header', 'type': 'str', 'required': True }, { 'name': 'id', 'description': '질문을 추가할 설문조사 ID', 'in': 'formData', 'type': 'str', 'required': True }, { 'name': 'title', 'description': '질문 제목', 'in': 'formData', 'type': 'str', 'required': True }, { 'name': 'is_objective', 'description': '객관식 여부', 'in': 'formData', 'type': 'bool', 'required': True }, { 'name': 'choice_paper', 'description': '객관식 선택지', 'in': 'formData', 'type': 'list', 'required': False } ], 'responses': { '201': { 'description': '질문 추가 성공' }, '403': { 'description': '권한 없음' } } }
23.16
47
0.345423
161
2,316
4.931677
0.347826
0.13602
0.161209
0.167506
0.656171
0.47733
0.47733
0.395466
0.307305
0.307305
0
0.009967
0.480138
2,316
99
48
23.393939
0.649502
0
0
0.489796
0
0
0.330743
0
0
0
0
0
0
1
0
false
0
0
0
0
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
0
0
0
1
4ab1c757764878f4d5cd5d264e6b8d82bbff63ba
12,893
py
Python
models.py
Bileonaire/api-ridemyway
af5a669c811356998e1935ace555ba955de1e8d0
[ "MIT" ]
null
null
null
models.py
Bileonaire/api-ridemyway
af5a669c811356998e1935ace555ba955de1e8d0
[ "MIT" ]
null
null
null
models.py
Bileonaire/api-ridemyway
af5a669c811356998e1935ace555ba955de1e8d0
[ "MIT" ]
1
2018-10-20T12:00:53.000Z
2018-10-20T12:00:53.000Z
"""Handles data storage for Users, rides and requests """ # pylint: disable=E1101 import datetime from flask import make_response, jsonify, current_app from werkzeug.security import generate_password_hash import psycopg2 import config from databasesetup import db class User(): """Contains user columns and methods to add, update and delete a user""" def __init__(self, username, email, password, admin): self.username = username self.email = email self.password = generate_password_hash(password, method='sha256') if admin == True: self.admin = '1' else: self.admin = '0' new_user = "INSERT INTO users (username, email, password, admin) VALUES " \ "('" + self.username + "', '" + self.email + "', '" + self.password + "', '" + self.admin + "')" db_cursor = db.con() db_cursor.execute(new_user) db.commit() @staticmethod def update_user(user_id, username, email, password, admin): """Updates user information""" try: db_cursor = db.con() db_cursor.execute("UPDATE users SET username=%s, email=%s, password=%s, admin=%s WHERE user_id=%s", (username, email, password, admin, user_id)) db.commit() return make_response(jsonify({"message" : "user has been successfully updated"}), 200) except: return make_response(jsonify({"message" : "user does not exist"}), 404) @staticmethod def delete_user(user_id): """Deletes a user""" try: db_cursor = db.con() db_cursor.execute("DELETE FROM users WHERE user_id=%s", (user_id,)) db.commit() return make_response(jsonify({"message" : "user has been successfully deleted"}), 200) except: return make_response(jsonify({"message" : "user does not exists"}), 404) @staticmethod def get_user(user_id): """Gets a particular user""" db_cursor = db.con() db_cursor.execute("SELECT * FROM users WHERE user_id=%s", (user_id,)) user = db_cursor.fetchall() if user != []: user=user[0] info = {user[0] : {"email": user[1], "username": user[2], "admin": user[4]}} return make_response(jsonify({"profile" : info}), 200) return make_response(jsonify({"message" : "user does not exists"}), 404) @staticmethod def get_all_users(): """Gets all users""" db_cursor = db.con() db_cursor.execute("SELECT * FROM users") users = db_cursor.fetchall() all_users = [] for user in users: info = {user[0] : {"email": user[1], "username": user[2], "admin": user[4]}} all_users.append(info) return make_response(jsonify({"All users" : all_users}), 200) class Ride(): """Contains ride columns and methods to add, update and delete a ride""" def __init__(self, ride, driver_id, departuretime, numberplate, maximum, status): self.ride = ride self.driver_id = driver_id self.departuretime = departuretime self.numberplate = numberplate self.maximum = maximum self.status = status new_ride = "INSERT INTO rides (ride, driver_id, departuretime, numberplate, maximum, status) VALUES " \ "('" + self.ride + "', '" + self.driver_id + "', '" + self.departuretime + "', '" + self.numberplate + "','" + self.maximum + "','" + self.status + "' )" db_cursor = db.con() db_cursor.execute(new_ride) db.commit() @classmethod def create_ride(cls, ride, driver_id, departuretime, numberplate, maximum, status="pending"): """Creates a new ride""" cls(ride, driver_id, departuretime, numberplate, maximum, status) return make_response(jsonify({"message" : "ride has been successfully created"}), 201) @staticmethod def update_ride(ride_id, ride, driver_id, departuretime, numberplate, maximum): """Updates ride information""" try: db_cursor = db.con() db_cursor.execute("UPDATE rides SET ride=%s, driver_id=%s, departuretime=%s, numberplate=%s, maximum=%s WHERE ride_id=%s", (ride, driver_id, departuretime, numberplate, maximum, ride_id)) db.commit() return make_response(jsonify({"message" : "user has been successfully updated"}), 200) except: return make_response(jsonify({"message" : "user does not exist"}), 404) @staticmethod def start_ride(ride_id, driver_id): """starts a ride""" db_cursor = db.con() db_cursor.execute("SELECT * FROM rides WHERE ride_id=%s", (ride_id,)) ride = db_cursor.fetchall() if ride != []: ride = ride[0] if int(ride[2]) == driver_id: db_cursor.execute("UPDATE rides SET status=%s WHERE ride_id=%s", ("given", ride_id,)) db_cursor.execute("UPDATE request SET status=%s WHERE ride_id=%s and accepted=%s", ("taken", ride_id, True,)) db_cursor.execute("UPDATE request SET status=%s WHERE ride_id=%s and accepted=%s", ("rejected", ride_id, False,)) db.commit() return {"message" : "ride has started"} return {"message" : "The ride you want to start is not your ride."} return {"message" : "ride does not exist"} @staticmethod def delete_ride(ride_id): """Deletes a ride""" db_cursor = db.con() db_cursor.execute("SELECT * FROM rides") rides = db_cursor.fetchall() for ride in rides: if ride[0] == ride_id: db_cursor.execute("DELETE FROM rides WHERE ride_id=%s", (ride_id,)) db.commit() return make_response(jsonify({"message" : "ride has been successfully deleted"}), 200) return make_response(jsonify({"message" : "user does not exists"}), 404) @staticmethod def get_ride(ride_id): """Gets a particular ride""" db_cursor = db.con() db_cursor.execute("SELECT * FROM rides WHERE ride_id=%s", (ride_id,)) ride = db_cursor.fetchall() if ride != []: ride=ride[0] info = {ride[0] : {"ride": ride[1], "driver_id": ride[2], "departure_time": ride[3], "cost": ride[4], "maximum": ride[5], "status": ride[6]}} return make_response(jsonify({"ride" : info}), 200) return make_response(jsonify({"message" : "ride does not exists"}), 404) @staticmethod def get_all_rides(): """Gets all rides""" db_cursor = db.con() db_cursor.execute("SELECT * FROM rides") rides = db_cursor.fetchall() all_rides = [] for ride in rides: info = {ride[0] : {"ride": ride[1], "driver_id": ride[2], "departure_time": ride[3], "cost": ride[4], "maximum": ride[5], "status": ride[6]}} all_rides.append(info) return make_response(jsonify({"All rides" : all_rides}), 200) class Request: """Contains menu columns and methods to add, update and delete a request""" def __init__(self, ride_id, user_id, accepted, status): self.ride_id = str(ride_id) self.user_id = str(user_id) self.accepted = accepted self.status = status new_request = "INSERT INTO request (ride_id, user_id, accepted, status) VALUES " \ "('" + self.ride_id + "', '" + self.user_id + "', '" + '0' + "', '" + self.status + "')" db_cursor = db.con() db_cursor.execute(new_request) db.commit() @classmethod def request_ride(cls, ride_id, user_id, accepted=False, status="pending"): """Creates a new request""" db_cursor = db.con() db_cursor.execute("SELECT status FROM rides WHERE ride_id=%s", (ride_id,)) ride = db_cursor.fetchone() if ride[0] == "pending": cls(ride_id, user_id, accepted, status) return make_response(jsonify({"message" : "request has been successfully sent for approval"}), 201) return make_response(jsonify({"message" : "ride is already given"}), 400) @staticmethod def delete_request(request_id): """Deletes a request""" try: db_cursor = db.con() db_cursor.execute("DELETE FROM request WHERE request_id=%s", (request_id,)) db.commit() return make_response(jsonify({"message" : "ride has been successfully deleted"}), 200) except: return make_response(jsonify({"message" : "the specified request does not exist in requests"}), 404) @staticmethod def accept_request(request_id): """Accepts request""" try: db_cursor = db.con() db_cursor.execute("UPDATE request SET accepted=%s WHERE request_id=%s", (True, request_id)) db.commit() return make_response(jsonify({"message" : "request has been successfully accepted"}), 200) except KeyError: return make_response(jsonify({"message" : "the specified request does not exist in requests"}), 404) @staticmethod def get_requests(request_id): """Gets a particular request""" db_cursor = db.con() db_cursor.execute("SELECT * FROM request WHERE request_id=%s", (request_id,)) request = db_cursor.fetchone() if request != None: info = {request[0] : {"user_id": request[1], "ride_id": request[2], "status": request[3], "accepted": request[4]}} return make_response(jsonify({"request" : info}), 200) return make_response(jsonify({"message" : "request does not exists"}), 404) @staticmethod def get_particular_riderequests(ride_id): db_cursor = db.con() db_cursor.execute("SELECT * FROM request WHERE ride_id=%s", (ride_id,)) requests = db_cursor.fetchall() if requests != []: ride_requests = [] for request in requests: info = {request[0] : {"user_id": request[1], "ride_id": request[2], "status": request[3], "accepted": request[4]}} ride_requests.append(info) return make_response(jsonify({"ride_requests" : ride_requests}), 200) return make_response(jsonify({"message" : "ride does not exists"}), 404) @staticmethod def get_all_requests(): """Gets all request""" db_cursor = db.con() db_cursor.execute("SELECT * FROM request") requests = db_cursor.fetchall() ride_requests = [] for request in requests: info = {request[0] : {"user_id": request[1], "ride_id": request[2], "status": request[3], "accepted": request[4]}} ride_requests.append(info) return make_response(jsonify({"ride_requests" : ride_requests}), 200) class Relation: """Contains method to get driver_id and maximum from a requested ride""" @staticmethod def get_driver_id(request_id): """Gets all request""" db_cursor = db.con() db_cursor.execute("SELECT * FROM request WHERE request_id=%s", (request_id,)) request = db_cursor.fetchone() ride_id = str(request[2]) db_cursor.execute("SELECT driver_id FROM rides WHERE ride_id=%s", (ride_id,)) driver_id = db_cursor.fetchone() if driver_id == None: return make_response(jsonify({"message" : "ride does not exists"}), 404) driver_id = driver_id[0] return int(driver_id) @staticmethod def get_maximum(request_id): """Gets all request""" db_cursor = db.con() db_cursor.execute("SELECT * FROM request WHERE request_id=%s", (str(request_id),)) request = db_cursor.fetchone() db_cursor.execute("SELECT maximum FROM rides WHERE ride_id=%s", (request[2],)) maximum = db_cursor.fetchone() maximum = maximum[0] return maximum
39.307927
173
0.556891
1,458
12,893
4.757888
0.098765
0.069194
0.07669
0.097304
0.653453
0.624477
0.575032
0.535102
0.515064
0.43996
0
0.015788
0.317149
12,893
327
174
39.428135
0.772149
0.051656
0
0.534413
1
0.008097
0.197028
0
0
0
0
0
0
1
0.08502
false
0.032389
0.024292
0
0.255061
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
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
4ab456260f6c742ad312aaa99e3e2590ddc0675c
731
py
Python
olamundo.py/exercicios_refeitos/ex029.py
gabrielviticov/exercicios-python
4068cb0029513f8ab8bd12fa3a9055f37b4040d4
[ "MIT" ]
null
null
null
olamundo.py/exercicios_refeitos/ex029.py
gabrielviticov/exercicios-python
4068cb0029513f8ab8bd12fa3a9055f37b4040d4
[ "MIT" ]
null
null
null
olamundo.py/exercicios_refeitos/ex029.py
gabrielviticov/exercicios-python
4068cb0029513f8ab8bd12fa3a9055f37b4040d4
[ "MIT" ]
null
null
null
''' ex029: Escreva um programa que leia a velocidade de uma carro. Se ele ultrapassar 80 km/h, mostre uma mensagem dizendo que ele foi multado. A multa vai custar R$ 7,00 por cada Km acima do limite. ''' from colorise import set_color, reset_color cor = { 'limpa':'\033[m', 'white':'\033[1;97m' } set_color(fg='green') velocidade_carro = int(input('Informe a velocidade do carro KM/H: ')) if velocidade_carro > 80: multa = (velocidade_carro - 80) * 7.00 print('\nMULTADO! VOCÊ ULTRAPASSOU O LIMITE PERMITIDO. LOGO TERÁ QUE PAGAR ', end='') reset_color() print('{}R${:.2f}{}'.format(cor['white'], multa, cor['limpa'])) else: set_color(fg='green') print('\nCONTINUE ASSIM. DIRIGINDO COM SEGURANÇA!')
36.55
195
0.679891
112
731
4.366071
0.625
0.04908
0.0409
0.06135
0
0
0
0
0
0
0
0.041322
0.172367
731
19
196
38.473684
0.766942
0.266758
0
0.133333
0
0
0.386364
0
0
0
0
0
0
1
0
false
0.066667
0.066667
0
0.066667
0.2
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
0
0
0
1
4ab62b5efbeb5c0a7886f27f8824551ce65f3eab
256
py
Python
fruit/mixin/drawable.py
felko/fruit
4768fd333ac3b7c0bd6d339304b23e20e312d2d1
[ "MIT" ]
4
2017-06-14T14:50:05.000Z
2019-07-29T16:51:24.000Z
fruit/mixin/drawable.py
felko/fruit
4768fd333ac3b7c0bd6d339304b23e20e312d2d1
[ "MIT" ]
null
null
null
fruit/mixin/drawable.py
felko/fruit
4768fd333ac3b7c0bd6d339304b23e20e312d2d1
[ "MIT" ]
null
null
null
#!/usr/bin/env python3.4 # coding: utf-8 class Drawable: """ Base class for drawable objects. """ def draw(self): """ Returns a Surface object. """ raise NotImplementedError( "Method `draw` is not implemented for {}".format(type(self)))
15.058824
64
0.648438
33
256
5.030303
0.848485
0
0
0
0
0
0
0
0
0
0
0.014563
0.195313
256
16
65
16
0.791262
0.375
0
0
0
0
0.282609
0
0
0
0
0
0
1
0.25
false
0
0
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
1
0
0
0
0
0
0
0
1
4ab9a2726c38f9bfc3c6566bc523e4832e60605f
2,808
py
Python
website/website/apps/entry/admin.py
SimonGreenhill/Language5
c59f502dda7be27fc338f0338cc3b03e63bad9c8
[ "MIT" ]
1
2020-08-17T05:56:16.000Z
2020-08-17T05:56:16.000Z
website/website/apps/entry/admin.py
SimonGreenhill/Language5
c59f502dda7be27fc338f0338cc3b03e63bad9c8
[ "MIT" ]
5
2020-06-05T17:51:56.000Z
2022-01-13T00:42:51.000Z
website/website/apps/entry/admin.py
SimonGreenhill/Language5
c59f502dda7be27fc338f0338cc3b03e63bad9c8
[ "MIT" ]
1
2015-02-23T22:54:00.000Z
2015-02-23T22:54:00.000Z
from django.contrib import admin from django.db.models import Count from reversion.admin import VersionAdmin from website.apps.lexicon.models import Lexicon from website.apps.entry.models import Task, TaskLog, Wordlist, WordlistMember from website.apps.core.admin import TrackedModelAdmin class CheckpointListFilter(admin.SimpleListFilter): title = 'Has Checkpoint' # Parameter for the filter that will be used in the URL query. parameter_name = 'has_checkpoint' def lookups(self, request, model_admin): """ Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar. """ return ( ('yes', 'Has Checkpoint'), ('no', 'No Checkpoint'), ) def queryset(self, request, queryset): """ Returns the filtered queryset based on the value provided in the query string and retrievable via `self.value()`. """ if self.value() == 'yes': return queryset.filter(checkpoint__isnull=False).exclude(checkpoint__iexact='') if self.value() == 'no': return queryset.filter(checkpoint__isnull=True).filter(checkpoint__exact='') class TaskAdmin(TrackedModelAdmin, VersionAdmin): date_hierarchy = 'added' list_display = ('id', 'name', 'editor', 'records', 'completable', 'done') list_filter = ('editor', 'done', 'completable', CheckpointListFilter, 'source', 'language', 'view') ordering = ('-id',) exclude = ('lexicon',) list_select_related = True class TaskLogAdmin(admin.ModelAdmin): date_hierarchy = 'time' list_display = ('person', 'task_id', 'time', 'page', 'message') list_filter = ('person', 'page', ) ordering = ('-time',) list_select_related = True def task_id(self, instance): return instance.task_id class WordlistMembersInline(admin.TabularInline): model = Wordlist.words.through extra = 0 # don't add anything new unless explicitly told to. class TaskWordlistAdmin(TrackedModelAdmin, VersionAdmin): date_hierarchy = 'added' list_display = ('id', 'name', 'words_count') ordering = ('name',) filter_horizontal = ('words',) inlines = [WordlistMembersInline,] def get_queryset(self, request): return Wordlist.objects.annotate(words_count=Count("words")) def words_count(self, inst): return inst.words_count words_count.admin_order_field = 'words_count' admin.site.register(Task, TaskAdmin) admin.site.register(TaskLog, TaskLogAdmin) admin.site.register(Wordlist, TaskWordlistAdmin)
33.428571
103
0.666667
317
2,808
5.791798
0.410095
0.03268
0.02451
0.014161
0.142702
0.103486
0.103486
0.103486
0.069717
0
0
0.00046
0.225071
2,808
83
104
33.831325
0.84329
0.160969
0
0.078431
0
0
0.109389
0
0
0
0
0
0
1
0.098039
false
0
0.117647
0.058824
0.823529
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
4abb4683ee2e4ff41f7985424a94c70975cdae94
356
py
Python
src/modules/python.py
fest2bash/fest2bash
008282f67d4d4415c27b3b9b6162daf54f8d6028
[ "MIT" ]
null
null
null
src/modules/python.py
fest2bash/fest2bash
008282f67d4d4415c27b3b9b6162daf54f8d6028
[ "MIT" ]
null
null
null
src/modules/python.py
fest2bash/fest2bash
008282f67d4d4415c27b3b9b6162daf54f8d6028
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import re import sys sys.dont_write_bytecode = True from pprint import pprint from base import BaseFest2Bash class Fest2Bash(BaseFest2Bash): def __init__(self, manifest): super(Fest2Bash, self).__init__(manifest) def generate(self, *args, **kwargs): return self.manifest
19.777778
49
0.710674
46
356
5.282609
0.652174
0.098765
0
0
0
0
0
0
0
0
0
0.020619
0.182584
356
17
50
20.941176
0.814433
0.120787
0
0
0
0
0
0
0
0
0
0
0
1
0.181818
false
0
0.454545
0.090909
0.818182
0.090909
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
1
4abedd6e3a784e93e18495ecbb7c4ea6ddcaa98a
3,255
py
Python
apps/pyscrabble/pyscrabble-hatchet/setup.py
UWSysLab/diamond
1beec323c084d9d477c770ca6b9625c8f5682a39
[ "MIT" ]
19
2016-08-22T23:54:24.000Z
2021-03-19T08:08:35.000Z
apps/pyscrabble/pyscrabble-hatchet/setup.py
UWSysLab/diamond
1beec323c084d9d477c770ca6b9625c8f5682a39
[ "MIT" ]
3
2020-12-02T18:29:32.000Z
2021-06-23T20:26:09.000Z
apps/pyscrabble/pyscrabble-hatchet/setup.py
UWSysLab/diamond
1beec323c084d9d477c770ca6b9625c8f5682a39
[ "MIT" ]
5
2017-01-25T19:31:49.000Z
2018-07-25T05:08:19.000Z
# setup.py for pyscrabble from distutils.core import setup try: import py2exe HAS_PY2EXE = True except ImportError: HAS_PY2EXE = False import glob import os import pkg_resources import sys from pyscrabble.constants import VERSION from pyscrabble import util from pyscrabble import dist def fix_path(item): if type(item) in (list, tuple): if 'config' in item[0]: return (item[0].replace('config', dist.get_app_data_dir()), item[1]) else: return (item[0].replace('resources/', 'share/pyscrabble/'), item[1]) else: return item kwargs = { 'name': 'pyscrabble', 'version': VERSION, 'author': 'Kevin Conaway', 'author_email': 'kevin.a.conaway@gmail.com', 'url': 'http://pyscrabble.sourceforge.net', 'data_files': dist.getDataFiles(), 'packages': ['pyscrabble', 'pyscrabble.command', 'pyscrabble.game', 'pyscrabble.gui', 'pyscrabble.net'] } if HAS_PY2EXE and 'py2exe' in sys.argv: #eggpacks = pkg_resources.require("nevow") #for egg in eggpacks: # if os.path.isdir(egg.location): # sys.path.insert(0, egg.location) try: import modulefinder import win32com for p in win32com.__path__[1:]: modulefinder.AddPackagePath("win32com",p) for extra in ["win32com.shell"]: __import__(extra) m = sys.modules[extra] for p in m.__path__[1:]: modulefinder.addPackagePath(extra, p) except ImportError: print 'import error' kwargs['py_modules'] = ['pyscrabble-main', 'server_console', 'db_upgrade'] kwargs['options'] = { "py2exe": { "packages": "encodings, nevow", "includes": "pango,atk,gobject,decimal,dumbdbm,dbhash,xml.sax.expatreader", "dll_excludes": ["iconv.dll","intl.dll","libatk-1.0-0.dll", "libgdk_pixbuf-2.0-0.dll","libgdk-win32-2.0-0.dll", "libglib-2.0-0.dll","libgmodule-2.0-0.dll", "libgobject-2.0-0.dll","libgthread-2.0-0.dll", "libgtk-win32-2.0-0.dll","libpango-1.0-0.dll", "libpangowin32-1.0-0.dll"], } } kwargs['windows'] = [{ "script": "pyscrabble-main.py", "icon_resources" : [(1, "resources/images/py.ico")] }] kwargs['console'] = [{ "script": "server_service.py", "icon_resources" : [(1, "resources/images/py.ico")] }, { "script": "server_console.py", "icon_resources" : [(1, "resources/images/py.ico")] }] kwargs['service'] = ['server_service'] kwargs['data_files'] += [('.', ['CHANGELOG.txt'])] kwargs['data_files'] += [('.', ['LICENSE.txt'])] #for egg in eggpacks: # kwargs['data_files'] += dist.getResourceDirs(egg.location, ensureLower=False, basePath=None, outdir='extra') else: kwargs['scripts'] = ['pyscrabble-main.py', 'server_console.py', 'db_upgrade.py'] kwargs['data_files'] = [fix_path(x) for x in kwargs['data_files']] kwargs['cmdclass'] = {'install_lib': dist.InstallLib, 'install_scripts' : dist.InstallScripts} setup(**kwargs)
37.848837
118
0.580031
374
3,255
4.930481
0.363636
0.010846
0.027115
0.022777
0.097614
0.065076
0.065076
0.065076
0.045553
0
0
0.025248
0.257757
3,255
86
119
37.848837
0.737997
0.088786
0
0.16
0
0
0.360473
0.084899
0
0
0
0
0
0
null
null
0
0.2
null
null
0.013333
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
0
0
1
4abf8e0a8ee60fe90e1a20e373c9a2a3d84d695d
3,504
py
Python
ssbio/databases/pdbflex.py
JoshuaMeyers/ssbio
624618602437e2c2e4adf90962adcef3af2d5b40
[ "MIT" ]
76
2017-03-06T02:50:38.000Z
2022-02-08T08:08:48.000Z
ssbio/databases/pdbflex.py
JoshuaMeyers/ssbio
624618602437e2c2e4adf90962adcef3af2d5b40
[ "MIT" ]
30
2017-03-09T14:54:05.000Z
2021-10-06T10:57:45.000Z
ssbio/databases/pdbflex.py
JoshuaMeyers/ssbio
624618602437e2c2e4adf90962adcef3af2d5b40
[ "MIT" ]
21
2017-09-01T23:00:31.000Z
2022-02-23T14:04:30.000Z
import requests import ssbio.utils import os.path as op # #### PDB stats # Request flexibility data about one particular PDB. # # http://pdbflex.org/php/api/PDBStats.php?pdbID=1a50&chainID=A # # pdbID of structure you are interested in # chainID of chain you are interested in # # [{"pdbID":"1a50", # "chainID":"A", # "parentClusterID":"4hn4A", # "avgRMSD":"0.538", # "maxRMSD":"2.616", # "flexibilityLabel":"Low", # "otherClusterMembers":["4hn4A","4hpjA","4hpxA","4kkxA",...], # "PDBFlexLink":"http:\/\/pdbflex.org\/cluster.html#!\/4hn4A\/20987\/1a50A"}] # # Note: you can omit the chainID and PDBFlex will return information for all chains. # # #### RMSD profile # Request RMSD array used for local flexibility plots # # http://pdbflex.org/php/api/rmsdProfile.php?pdbID=1a50&chainID=A # # pdbID PDB ID of structure you are interested in # chainID Chain ID of chain you are interested in # # {"queryPDB":"1a50A", # "clusterName":"4hn4A", # "profile":"[0.616,0.624,0.624,0.624,0.624,0.624,0.029,0.013,0.016,0.023,0.025,0.028,0.030,0.034,0.035,0.035,0.035,0.035,0.036,0.033,0.027,0.023,0.017...]"} # # #### PDB representatives # Request representatives for a PDB's own cluster. Returns a list of chains that represent the most distinct structures in the cluster. # # http://pdbflex.org/php/api/representatives.php?pdbID=1a50&chainID=A # # pdbID PDB ID of structure you are interested in # chainID Chain ID of chain you are interested in # # ["2trsA","3pr2A","1kfjA"] def get_pdbflex_info(pdb_id, chain_id, outdir, force_rerun=False): outfile = '{}{}_pdbflex_stats.json'.format(pdb_id, chain_id) pdbflex_link = 'http://pdbflex.org/php/api/PDBStats.php?pdbID={}&chainID={}'.format(pdb_id, chain_id) infolist = ssbio.utils.request_json(link=pdbflex_link, outfile=outfile, outdir=outdir, force_rerun_flag=force_rerun) # TODO: will running with chain ID always return a single item list? assert len(infolist) == 1 newdict = {} for k, v in infolist[0].items(): if k == 'avgRMSD' and v: newdict[k] = float(v) elif k == 'maxRMSD' and v: newdict[k] = float(v) else: newdict[k] = v return newdict def get_pdbflex_rmsd_profile(pdb_id, chain_id, outdir, force_rerun=False): outfile = '{}{}_pdbflex_rmsdprofile.json'.format(pdb_id, chain_id) pdbflex_link = 'http://pdbflex.org/php/api/rmsdProfile.php?pdbID={}&chainID={}'.format(pdb_id, chain_id) infodict = ssbio.utils.request_json(link=pdbflex_link, outfile=outfile, outdir=outdir, force_rerun_flag=force_rerun) infodict['profile'] = [float(x) for x in infodict['profile'].strip('[]').split(',')] return infodict def get_pdbflex_representatives(pdb_id, chain_id, outdir, force_rerun=False): outfile = '{}{}_pdbflex_representatives.json'.format(pdb_id, chain_id) pdbflex_link = 'http://pdbflex.org/php/api/representatives.php?pdbID={}&chainID={}'.format(pdb_id, chain_id) infolist = ssbio.utils.request_json(link=pdbflex_link, outfile=outfile, outdir=outdir, force_rerun_flag=force_rerun) # infolist = [str(x) for x in infolist.strip('[]').split(',')] return infolist
40.275862
161
0.627854
467
3,504
4.599572
0.289079
0.039106
0.041899
0.050279
0.538641
0.538641
0.502328
0.477654
0.398976
0.389199
0
0.051699
0.227169
3,504
87
162
40.275862
0.741507
0.434646
0
0.225806
0
0
0.157403
0.044156
0
0
0
0.011494
0.032258
1
0.096774
false
0
0.096774
0
0.290323
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
0
0
0
1
4abff12be5f57f68704691116cfaac62253e2192
1,065
py
Python
api/insights/insights/infrastructure/mysql/read/modify_notes.py
manisharmagarg/qymatix
0dc240970359429ae5105db79f9aebf1a99ba6fd
[ "Apache-2.0" ]
null
null
null
api/insights/insights/infrastructure/mysql/read/modify_notes.py
manisharmagarg/qymatix
0dc240970359429ae5105db79f9aebf1a99ba6fd
[ "Apache-2.0" ]
null
null
null
api/insights/insights/infrastructure/mysql/read/modify_notes.py
manisharmagarg/qymatix
0dc240970359429ae5105db79f9aebf1a99ba6fd
[ "Apache-2.0" ]
null
null
null
""" Modify Notes """ # pylint: disable=too-few-public-methods from ...mysql.mysql_connection import MySqlConnection from ...mysql.orm.autogen_entities import Task class ModifyNotes(object): """ ModifyNotes responsible to update the record in db """ def __init__(self, db_name, notes_id, title=None, comment=None): super(ModifyNotes, self).__init__() self.data_db = 'data_{}'.format(db_name) self.notes_id = notes_id self.title = title self.comment = comment connection = MySqlConnection(self.data_db) self.session = connection.session() self.results = self.modify_notes() def modify_notes(self): """ function: query to update the notes record return: updated notes Id """ notes_obj = self.session.query(Task). \ filter_by(id=self.notes_id).first() notes_obj.title = self.title notes_obj.description = self.comment self.session.add(notes_obj) self.session.commit() return notes_obj.id
29.583333
68
0.642254
129
1,065
5.093023
0.395349
0.053272
0.033486
0.057839
0
0
0
0
0
0
0
0
0.250704
1,065
35
69
30.428571
0.823308
0.160563
0
0
1
0
0.008343
0
0
0
0
0
0
1
0.1
false
0
0.1
0
0.3
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
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
4ac08cf9f315cf058d8ec6ec1e3e396023b3a1de
1,834
py
Python
desktop/core/ext-py/pyasn1-0.4.6/tests/type/test_namedval.py
yetsun/hue
2e48f0cc70e233ee0e1b40733d4b2a18d8836c66
[ "Apache-2.0" ]
5,079
2015-01-01T03:39:46.000Z
2022-03-31T07:38:22.000Z
desktop/core/ext-py/pyasn1-0.4.6/tests/type/test_namedval.py
yetsun/hue
2e48f0cc70e233ee0e1b40733d4b2a18d8836c66
[ "Apache-2.0" ]
1,623
2015-01-01T08:06:24.000Z
2022-03-30T19:48:52.000Z
desktop/core/ext-py/pyasn1-0.4.6/tests/type/test_namedval.py
yetsun/hue
2e48f0cc70e233ee0e1b40733d4b2a18d8836c66
[ "Apache-2.0" ]
2,033
2015-01-04T07:18:02.000Z
2022-03-28T19:55:47.000Z
# # This file is part of pyasn1 software. # # Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com> # License: http://snmplabs.com/pyasn1/license.html # import sys try: import unittest2 as unittest except ImportError: import unittest from tests.base import BaseTestCase from pyasn1.type import namedval class NamedValuesCaseBase(BaseTestCase): def setUp(self): BaseTestCase.setUp(self) self.e = namedval.NamedValues(('off', 0), ('on', 1)) def testDict(self): assert set(self.e.items()) == set([('off', 0), ('on', 1)]) assert set(self.e.keys()) == set(['off', 'on']) assert set(self.e) == set(['off', 'on']) assert set(self.e.values()) == set([0, 1]) assert 'on' in self.e and 'off' in self.e and 'xxx' not in self.e assert 0 in self.e and 1 in self.e and 2 not in self.e def testInit(self): assert namedval.NamedValues(off=0, on=1) == {'off': 0, 'on': 1} assert namedval.NamedValues('off', 'on') == {'off': 0, 'on': 1} assert namedval.NamedValues(('c', 0)) == {'c': 0} assert namedval.NamedValues('a', 'b', ('c', 0), d=1) == {'c': 0, 'd': 1, 'a': 2, 'b': 3} def testLen(self): assert len(self.e) == 2 assert len(namedval.NamedValues()) == 0 def testAdd(self): assert namedval.NamedValues(off=0) + namedval.NamedValues(on=1) == {'off': 0, 'on': 1} def testClone(self): assert namedval.NamedValues(off=0).clone(('on', 1)) == {'off': 0, 'on': 1} assert namedval.NamedValues(off=0).clone(on=1) == {'off': 0, 'on': 1} def testStrRepr(self): assert str(self.e) assert repr(self.e) suite = unittest.TestLoader().loadTestsFromModule(sys.modules[__name__]) if __name__ == '__main__': unittest.TextTestRunner(verbosity=2).run(suite)
31.084746
96
0.598691
259
1,834
4.19305
0.301158
0.064457
0.044199
0.051565
0.303867
0.289134
0.200737
0.116022
0.116022
0.116022
0
0.034843
0.217557
1,834
58
97
31.62069
0.721951
0.078517
0
0
0
0
0.045752
0
0
0
0
0
0.459459
1
0.189189
false
0
0.162162
0
0.378378
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
1
0
0
0
0
0
0
0
0
0
1
434e153d430f769d0af982184da673ab7f398f75
6,213
py
Python
terra/terra/emails.py
dymaxionlabs/platform
98fe893d4632d62fea3e2357f16d970014037cdf
[ "BSD-3-Clause" ]
null
null
null
terra/terra/emails.py
dymaxionlabs/platform
98fe893d4632d62fea3e2357f16d970014037cdf
[ "BSD-3-Clause" ]
null
null
null
terra/terra/emails.py
dymaxionlabs/platform
98fe893d4632d62fea3e2357f16d970014037cdf
[ "BSD-3-Clause" ]
null
null
null
import os from datetime import date from django.conf import settings from django.core.mail import send_mail from django.template.loader import render_to_string from django.utils import translation from django.utils.translation import ugettext as _ from mailchimp3 import MailChimp class Email: from_email = settings.DEFAULT_FROM_EMAIL subject = None template_name = 'basic' preview_text = '' templates_basedir = os.path.join(settings.BASE_DIR, 'templates') def __init__(self, recipients, language_code='en'): self.recipients = recipients self.language_code = language_code def send_mail(self): send_mail(self.subject, self.body, self.from_email, self.recipients, html_message=self.html_body) @property def body(self): return render_to_string(self.body_template, self.template_params) @property def html_body(self): return self._reformat_mailchimp_template( render_to_string(self.htmlbody_template, self.template_params)) @property def body_template(self): return os.path.join( self.templates_basedir, '{name}.{lc}.txt'.format(name=self.template_name, lc=self.language_code)) @property def htmlbody_template(self): return os.path.join( self.templates_basedir, '{name}.{lc}.html'.format(name=self.template_name, lc=self.language_code)) @property def template_params(self): return {} def _reformat_mailchimp_template(self, html): """ Replaces MailChimp variables for Django template variables, and do some post-processing. """ for var, newvar in self.mc_variables.items(): html = html.replace(str(var), str(newvar)) return html @property def mc_variables(self): return { '*|MC:SUBJECT|*': self.subject, '*|MC_PREVIEW_TEXT|*': self.preview_text, '*|CURRENT_YEAR|*': date.today().year, '*|LIST:COMPANY|*': settings.COMPANY_NAME, '*|HTML:LIST_ADDRESS_HTML|*': settings.LIST_ADDRESS_HTML, '*|UNSUB|*': '%unsubscribe_url%', # Unused variables (for now): '*|IFNOT:ARCHIVE_PAGE|*': '', '*|LIST:DESCRIPTION|*': '', '*|END:IF|*': '', } class EarlyAccessBetaEmail(Email): template_name = 'early_access_beta' @property def signup_url(self): return '{base_url}/signup?beta=1&email={email}'.format( base_url=settings.WEBCLIENT_URL, email= self.recipients[0]) @property def subject(self): with translation.override(self.language_code): return _('validate your email') @property def template_params(self): return {**super().template_params, 'signup_url': self.signup_url} @property def mc_variables(self): return {**super().mc_variables, '*|SIGNUP_URL|*': self.signup_url} class WelcomeEmail(Email): template_name = 'welcome' link = '{base_url}/login'.format(base_url=settings.WEBCLIENT_URL) def __init__(self, user, *args, **kwargs): super().__init__(*args, **kwargs) self.user = user @property def subject(self): with translation.override(self.language_code): return _('your account is ready') % {'name': self.first_name} @property def template_params(self): return { **super().template_params, 'first_name': self.first_name, 'link': self.link, } @property def mc_variables(self): return { **super().mc_variables, '*|FNAME|*': self.first_name, '*|TEXT:LINK|*': self.link, } @property def first_name(self): return self.user.first_name or self.user.username class TrainingCompletedEmail(Email): template_name = 'training_completed' def __init__(self, estimator, *args, **kwargs): super().__init__(*args, **kwargs) self.estimator = estimator self.link = '{web_client_url}/models/new/od/select?id={uuid}'.format( web_client_url = settings.WEBCLIENT_URL, uuid = estimator.uuid ) @property def subject(self): with translation.override(self.language_code): return _('training of your model completed') @property def template_params(self): return { **super().template_params, 'name': self.estimator_name, 'num_classes': self.num_classes, 'link': self.link, } @property def mc_variables(self): return { **super().mc_variables, '*|NAME|*': self.estimator_name, '*|NUM_CLASSES|*': self.num_classes, '*|LINK|*': self.link, } @property def estimator_name(self): return self.estimator.name @property def num_classes(self): return len(self.estimator.classes) class PredictionCompletedEmail(Email): template_name = 'prediction_completed' def __init__(self, estimator, *args, **kwargs): super().__init__(*args, **kwargs) self.estimator = estimator @property def subject(self): with translation.override(self.language_code): return _('prediction of your model completed') @property def template_params(self): return { **super().template_params, 'name': self.estimator_name, 'num_classes': self.num_classes, } @property def mc_variables(self): return { **super().mc_variables, '*|NAME|*': self.estimator_name, '*|NUM_CLASSES|*': self.num_classes, } @property def estimator_name(self): return self.estimator.name @property def num_classes(self): return len(self.estimator.classes) def notify(subject, body='.'): send_mail(subject, body, 'damian@dymaxionlabs.com', ['monitor@dymaxionlabs.com'])
27.860987
77
0.600998
663
6,213
5.39819
0.208145
0.073764
0.033529
0.034926
0.507404
0.488684
0.43392
0.4247
0.4247
0.381112
0
0.000671
0.280863
6,213
222
78
27.986486
0.800358
0.018831
0
0.502924
0
0
0.11298
0.029688
0
0
0
0
0
1
0.181287
false
0
0.046784
0.116959
0.461988
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
0
0
0
1
4354188cd39459be1c39fa882aceb00bf1b969f5
1,683
py
Python
actions/lib/Template_Parser.py
pjimmybrcd/campus_ztp_nps
2ab266b32fbcddcbdf9031138aabc40942914c3a
[ "Apache-2.0" ]
null
null
null
actions/lib/Template_Parser.py
pjimmybrcd/campus_ztp_nps
2ab266b32fbcddcbdf9031138aabc40942914c3a
[ "Apache-2.0" ]
null
null
null
actions/lib/Template_Parser.py
pjimmybrcd/campus_ztp_nps
2ab266b32fbcddcbdf9031138aabc40942914c3a
[ "Apache-2.0" ]
null
null
null
""" Copyright 2016 Brocade Communications Systems, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from jinja2 import Template, Environment, StrictUndefined, UndefinedError, meta class Template_Parser(object): def __init__(self, configuration_template_file, variables={}): ''' Loads the configuration file ''' self.profile = "" self.variables = variables try: with open(configuration_template_file, 'r') as f: self.profile = "".join(line for line in f) except: raise IOError("Template file '%s' not found!", configuration_template_file) def set_variables(self, variables): ''' Sets the variables ''' self.variables = variables def get_required_variables(self): ''' Returns a set of the required variables in the template ''' return meta.find_undeclared_variables(Environment().parse(self.profile)) def get_parsed_lines(self): ''' Returns a set of lines with all variables filed in ''' try: return Template(self.profile, undefined=StrictUndefined).render(self.variables) except UndefinedError as e: raise Exception(e)
39.139535
91
0.699346
215
1,683
5.390698
0.506977
0.051769
0.064711
0.02761
0.029336
0
0
0
0
0
0
0.00686
0.22044
1,683
42
92
40.071429
0.876524
0.434938
0
0.210526
0
0
0.032644
0
0
0
0
0
0
1
0.210526
false
0
0.052632
0
0.421053
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
0
0
0
1
43559b99540d7f4aefb586b6180111026c8c9f97
461
py
Python
lca_writer/data/loader.py
line-mind/lca_writer
0f356cf20285ba684826dfdd18b75d0f0ebea120
[ "BSD-3-Clause" ]
1
2022-02-10T21:32:54.000Z
2022-02-10T21:32:54.000Z
lca_writer/data/loader.py
line-mind/lca_writer
0f356cf20285ba684826dfdd18b75d0f0ebea120
[ "BSD-3-Clause" ]
1
2018-12-22T23:12:30.000Z
2018-12-22T23:12:30.000Z
lca_writer/data/loader.py
line-mind/lca_writer
0f356cf20285ba684826dfdd18b75d0f0ebea120
[ "BSD-3-Clause" ]
1
2019-10-09T07:03:09.000Z
2019-10-09T07:03:09.000Z
import os __all__ = ['DATA_FOLDER', 'load_data'] DATA_FOLDER = os.path.dirname(os.path.abspath(__file__)) def load_data(name): """ Loads an Excel form from the data folder with the specified name. Parameters ---------- name : str The name of the form without file extension. """ from ..lca_writer import LCAWriter # to prevent recursive import p = os.path.join(DATA_FOLDER, name + '.xlsx') return LCAWriter(p)
20.954545
69
0.652928
63
461
4.555556
0.555556
0.139373
0
0
0
0
0
0
0
0
0
0
0.229935
461
21
70
21.952381
0.808451
0.383948
0
0
0
0
0.099206
0
0
0
0
0
0
1
0.142857
false
0
0.285714
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
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
4356793fe5f5eb5615052cdcbe88626695d774de
841
py
Python
app/v1/utils/mixins.py
pndemo/yummy-recipes-api
ae6729bd1c886ce9872d83488a6eaa99e92be513
[ "MIT" ]
null
null
null
app/v1/utils/mixins.py
pndemo/yummy-recipes-api
ae6729bd1c886ce9872d83488a6eaa99e92be513
[ "MIT" ]
3
2019-12-20T23:17:20.000Z
2022-03-21T22:16:25.000Z
app/v1/utils/mixins.py
pndemo/yummy-recipes-api
ae6729bd1c886ce9872d83488a6eaa99e92be513
[ "MIT" ]
1
2017-12-13T12:44:11.000Z
2017-12-13T12:44:11.000Z
""" Model mixin classes for auth, category and recipe modules """ from app import db # pylint: disable=C0103 # pylint: disable=E1101 class BaseMixin(object): """ Define the 'BaseModel' mapped to all database tables. """ id = db.Column(db.Integer, primary_key=True, autoincrement=True) def save(self): """Save to database table""" db.session.add(self) db.session.commit() def delete(self): """Delete from database table""" db.session.delete(self) db.session.commit() class TimestampMixin(object): """ Database logging of data manipulation timestamps. """ date_created = db.Column(db.DateTime, default=db.func.current_timestamp()) date_modified = db.Column(db.DateTime, default=db.func.current_timestamp(), \ onupdate=db.func.current_timestamp())
29
81
0.67063
104
841
5.365385
0.557692
0.064516
0.053763
0.11828
0.168459
0.168459
0.168459
0.168459
0.168459
0
0
0.011923
0.20214
841
28
82
30.035714
0.819672
0.307967
0
0.153846
0
0
0
0
0
0
0
0
0
1
0.153846
false
0
0.076923
0
0.615385
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
435956da8c173c0f00fa6d13687b5307a4d9b2a5
499
py
Python
sync_ends/main.py
nirav1997/sync_ends
04e39ec26ac43ad4e6d4e1bdf685eb73c03b1dbb
[ "MIT" ]
null
null
null
sync_ends/main.py
nirav1997/sync_ends
04e39ec26ac43ad4e6d4e1bdf685eb73c03b1dbb
[ "MIT" ]
null
null
null
sync_ends/main.py
nirav1997/sync_ends
04e39ec26ac43ad4e6d4e1bdf685eb73c03b1dbb
[ "MIT" ]
null
null
null
import sys sys.path.append("..") from src.sync_ends_service import SyncEnd from src.parser import Parser def main(): # get the arguments from commadn line parser = Parser() collection_name, api_key, trigger_interval, slack_channel, slack_token = parser.get_argumenets() sync_end = SyncEnd(api_key, collection_name, trigger_interval, slack_channel, slack_token) try: sync_end.start() except Exception as e: print(e) if __name__ == "__main__": main()
22.681818
100
0.709419
67
499
4.940299
0.552239
0.042296
0.120846
0.163142
0.223565
0.223565
0
0
0
0
0
0
0.198397
499
21
101
23.761905
0.8275
0.07014
0
0
0
0
0.021645
0
0
0
0
0
0
1
0.071429
false
0
0.214286
0
0.285714
0.071429
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
0
0
0
1
4361fce279ba39aaf412d8930d6f84378c2aa668
460
py
Python
python/modules_packages_libraries/models/animal_kigdom/animals.py
aloa04/practice
0f11874a597450a70f3c6f01fe64b6aa9e9d5b9f
[ "Apache-2.0" ]
null
null
null
python/modules_packages_libraries/models/animal_kigdom/animals.py
aloa04/practice
0f11874a597450a70f3c6f01fe64b6aa9e9d5b9f
[ "Apache-2.0" ]
null
null
null
python/modules_packages_libraries/models/animal_kigdom/animals.py
aloa04/practice
0f11874a597450a70f3c6f01fe64b6aa9e9d5b9f
[ "Apache-2.0" ]
null
null
null
class Animal(): edad:int patas:int ruido:str nombre: str kgComida: float = 0 def __init__(self, edad, patas, ruido, nombre): self.edad =edad self.patas = patas self.ruido = ruido self.nombre = nombre def comer(self, alimento): self.kgComida += alimento print('Hola,', self.nombre, 'comes', self.kgComida) def hacerRuido(self): print('Hola', self.nombre, 'haces' , self.ruido)
24.210526
57
0.595652
56
460
4.821429
0.375
0.111111
0.096296
0.140741
0
0
0
0
0
0
0
0.003021
0.280435
460
19
58
24.210526
0.812689
0
0
0
0
0
0.041215
0
0
0
0
0
0
1
0.1875
false
0
0
0
0.5625
0.125
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
4364633db5685f14b086dbb59f77e9958e56ad15
2,913
py
Python
yampy/apis/groups.py
Kunal-Shah-Bose/yam-python
1d24b4b5c4bfb512804183efe741a2f7a75889e5
[ "Apache-2.0" ]
null
null
null
yampy/apis/groups.py
Kunal-Shah-Bose/yam-python
1d24b4b5c4bfb512804183efe741a2f7a75889e5
[ "Apache-2.0" ]
null
null
null
yampy/apis/groups.py
Kunal-Shah-Bose/yam-python
1d24b4b5c4bfb512804183efe741a2f7a75889e5
[ "Apache-2.0" ]
1
2019-01-10T18:50:35.000Z
2019-01-10T18:50:35.000Z
from yampy.apis.utils import ArgumentConverter, none_filter, stringify_booleans from yampy.models import extract_id class GroupsAPI(object): """ Provides an interface for accessing the groups related endpoints of the Yammer API. You should not instantiate this class directly; use the :meth:`yampy.Yammer.groups` method instead. """ def __init__(self, client): """ Initializes a new GroupsAPI that will use the given client object to make HTTP requests. """ self._client = client self._argument_converter = ArgumentConverter( none_filter, stringify_booleans, ) def all(self, mine=None, reverse=None): """ Returns all the groups in the current user's network. Customize the response using the keyword arguments: * mine -- Only return group of current user. * reverse -- return group in descending order by name. """ return self._client.get("/groups", **self._argument_converter( mine=mine, reverse=reverse, )) def find(self, group_id): """ Returns the group identified by the given group_id. """ return self._client.get(self._group_path(group_id)) def members(self, group_id, page=None, reverse=None): """ Returns the group identified by the given group_id. Customize the response using the keyword arguments: * page -- Enable pagination, and return the nth page of 50 users. """ path = "/group_memberships" return self._client.get(path, **self._argument_converter( page=page, reverse=reverse, )) def join(self, group_id): """ Join the group identified by the given group_id. Return True """ path = "/group_memberships" group_id = extract_id(group_id) return self._client.post(path, **self._argument_converter( group_id=group_id, )) def leave(self, group_id): """ Leave the group identified by the given group_id. Return True """ path = "/group_memberships" group_id = extract_id(group_id) return self._client.delete(path, **self._argument_converter( group_id=group_id, )) def create(self, name, private=False): """ Create a group. Return Group info """ path = "/groups" return self._client.post(path, **self._argument_converter( name=name, private=private, )) def delete(self, group_id): """ Delete a group. Return True if success """ return self._client.delete(self._group_path(group_id), delete="true") def _group_path(self, group_id): return "/groups/%d" % extract_id(group_id)
28.281553
79
0.599725
338
2,913
4.985207
0.295858
0.08724
0.066469
0.047478
0.389911
0.308012
0.308012
0.255786
0.226706
0.123442
0
0.000994
0.309303
2,913
102
80
28.558824
0.836481
0.310333
0
0.372093
0
0
0.047647
0
0
0
0
0
0
1
0.209302
false
0
0.046512
0.023256
0.465116
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
0
0
0
1
4368cab14b8dd0a73f5639ed6a1c9ef3a5f4c07f
354
py
Python
krispy/mod_user/models.py
jlaura/krispy
b1b2bf8a3e315608152c7dad15d384d0669f5e27
[ "0BSD" ]
2
2016-03-31T05:35:28.000Z
2017-04-12T00:11:59.000Z
krispy/mod_user/models.py
jlaura/krispy
b1b2bf8a3e315608152c7dad15d384d0669f5e27
[ "0BSD" ]
null
null
null
krispy/mod_user/models.py
jlaura/krispy
b1b2bf8a3e315608152c7dad15d384d0669f5e27
[ "0BSD" ]
null
null
null
from app import db from flask.ext.login import UserMixin class User(UserMixin, db.Model): __tablename__ = 'oauth2users' id = db.Column(db.Integer, primary_key=True) social_id = db.Column(db.String(64), nullable=False, unique=True) nickname = db.Column(db.String(64), nullable=False) email = db.Column(db.String(64), nullable=True)
29.5
69
0.717514
52
354
4.769231
0.519231
0.129032
0.16129
0.193548
0.354839
0.354839
0.25
0
0
0
0
0.023333
0.152542
354
11
70
32.181818
0.803333
0
0
0
0
0
0.03125
0
0
0
0
0
0
1
0
false
0
0.25
0
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
0
0
0
1
4369ad9700348a9af2bc92b402bcac16112c9914
16,746
py
Python
blog_app/blog/views.py
flxj/Django_blog
01eb12553335115fee5faecafe8cacf2f0615135
[ "MIT" ]
1
2019-03-27T02:24:22.000Z
2019-03-27T02:24:22.000Z
blog_app/blog/views.py
flxj/Django_blog
01eb12553335115fee5faecafe8cacf2f0615135
[ "MIT" ]
null
null
null
blog_app/blog/views.py
flxj/Django_blog
01eb12553335115fee5faecafe8cacf2f0615135
[ "MIT" ]
null
null
null
import markdown from comments.forms import CommentForm,BookCommentForm,MovieCommentForm from django.shortcuts import render, get_object_or_404 from.models import Post,Category,Tag, Book,Movie #from django.http import HttpResponse from django.views.generic import ListView, DetailView from django.utils.text import slugify from markdown.extensions.toc import TocExtension from django.db.models import Q """ def index(request): #post_list = Post.objects.all().order_by('-created_time') post_list = Post.objects.all() return render(request, 'blog/index.html', context={'post_list': post_list}) """ class IndexView(ListView): model = Post template_name = 'blog/index.html' context_object_name = 'post_list' paginate_by = 10 def get_context_data(self, **kwargs): """ 在视图函数中将模板变量传递给模板是通过给 render 函数的 context 参数传递一个字典实现的, 例如 render(request, 'blog/index.html', context={'post_list': post_list}), 这里传递了一个 {'post_list': post_list} 字典给模板。 在类视图中,这个需要传递的模板变量字典是通过 get_context_data 获得的, 所以我们复写该方法,以便我们能够自己再插入一些我们自定义的模板变量进去。 """ # 首先获得父类生成的传递给模板的字典。 context = super().get_context_data(**kwargs) # 父类生成的字典中已有 paginator、page_obj、is_paginated 这三个模板变量, # paginator 是 Paginator 的一个实例, # page_obj 是 Page 的一个实例, # is_paginated 是一个布尔变量,用于指示是否已分页。 # 例如如果规定每页 10 个数据,而本身只有 5 个数据,其实就用不着分页,此时 is_paginated=False。 # 关于什么是 Paginator,Page 类在 Django Pagination 简单分页:http://zmrenwu.com/post/34/ 中已有详细说明。 # 由于 context 是一个字典,所以调用 get 方法从中取出某个键对应的值。 paginator = context.get('paginator') page = context.get('page_obj') is_paginated = context.get('is_paginated') # 调用自己写的 pagination_data 方法获得显示分页导航条需要的数据,见下方。 pagination_data = self.pagination_data(paginator, page, is_paginated) # 将分页导航条的模板变量更新到 context 中,注意 pagination_data 方法返回的也是一个字典。 context.update(pagination_data) # 将更新后的 context 返回,以便 ListView 使用这个字典中的模板变量去渲染模板。 # 注意此时 context 字典中已有了显示分页导航条所需的数据。 return context def pagination_data(self, paginator, page, is_paginated): if not is_paginated: # 如果没有分页,则无需显示分页导航条,不用任何分页导航条的数据,因此返回一个空的字典 return {} # 当前页左边连续的页码号,初始值为空 left = [] # 当前页右边连续的页码号,初始值为空 right = [] # 标示第 1 页页码后是否需要显示省略号 left_has_more = False # 标示最后一页页码前是否需要显示省略号 right_has_more = False # 标示是否需要显示第 1 页的页码号。 # 因为如果当前页左边的连续页码号中已经含有第 1 页的页码号,此时就无需再显示第 1 页的页码号, # 其它情况下第一页的页码是始终需要显示的。 # 初始值为 False first = False # 标示是否需要显示最后一页的页码号。 # 需要此指示变量的理由和上面相同。 last = False # 获得用户当前请求的页码号 page_number = page.number # 获得分页后的总页数 total_pages = paginator.num_pages # 获得整个分页页码列表,比如分了四页,那么就是 [1, 2, 3, 4] page_range = paginator.page_range if page_number == 1: # 如果用户请求的是第一页的数据,那么当前页左边的不需要数据,因此 left=[](已默认为空)。 # 此时只要获取当前页右边的连续页码号, # 比如分页页码列表是 [1, 2, 3, 4],那么获取的就是 right = [2, 3]。 # 注意这里只获取了当前页码后连续两个页码,你可以更改这个数字以获取更多页码。 right = page_range[page_number:page_number + 2] # 如果最右边的页码号比最后一页的页码号减去 1 还要小, # 说明最右边的页码号和最后一页的页码号之间还有其它页码,因此需要显示省略号,通过 right_has_more 来指示。 if right[-1] < total_pages - 1: right_has_more = True # 如果最右边的页码号比最后一页的页码号小,说明当前页右边的连续页码号中不包含最后一页的页码 # 所以需要显示最后一页的页码号,通过 last 来指示 if right[-1] < total_pages: last = True elif page_number == total_pages: # 如果用户请求的是最后一页的数据,那么当前页右边就不需要数据,因此 right=[](已默认为空), # 此时只要获取当前页左边的连续页码号。 # 比如分页页码列表是 [1, 2, 3, 4],那么获取的就是 left = [2, 3] # 这里只获取了当前页码后连续两个页码,你可以更改这个数字以获取更多页码。 left = page_range[(page_number - 3) if (page_number - 3) > 0 else 0:page_number - 1] # 如果最左边的页码号比第 2 页页码号还大, # 说明最左边的页码号和第 1 页的页码号之间还有其它页码,因此需要显示省略号,通过 left_has_more 来指示。 if left[0] > 2: left_has_more = True # 如果最左边的页码号比第 1 页的页码号大,说明当前页左边的连续页码号中不包含第一页的页码, # 所以需要显示第一页的页码号,通过 first 来指示 if left[0] > 1: first = True else: # 用户请求的既不是最后一页,也不是第 1 页,则需要获取当前页左右两边的连续页码号, # 这里只获取了当前页码前后连续两个页码,你可以更改这个数字以获取更多页码。 left = page_range[(page_number - 3) if (page_number - 3) > 0 else 0:page_number - 1] right = page_range[page_number:page_number + 2] # 是否需要显示最后一页和最后一页前的省略号 if right[-1] < total_pages - 1: right_has_more = True if right[-1] < total_pages: last = True # 是否需要显示第 1 页和第 1 页后的省略号 if left[0] > 2: left_has_more = True if left[0] > 1: first = True data = { 'left': left, 'right': right, 'left_has_more': left_has_more, 'right_has_more': right_has_more, 'first': first, 'last': last, } return data #显示全文 """ def detail(request, pk): post = get_object_or_404(Post, pk=pk) # 阅读量 +1 post.increase_views() post.body = markdown.markdown(post.body, extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', 'markdown.extensions.tables', ]) form = CommentForm() # 获取这篇 post 下的全部评论 comment_list = post.comment_set.all() # 将文章、表单、以及文章下的评论列表作为模板变量传给 detail.html 模板,以便渲染相应数据。 context = {'post': post, 'form': form, 'comment_list': comment_list } return render(request, 'blog/detail.html', context=context) """ class PostDetailView(DetailView): model = Post template_name = 'blog/detail.html' context_object_name = 'post' def get(self, request, *args, **kwargs): # 覆写 get 方法的目的是因为每当文章被访问一次,就得将文章阅读量 +1 # get 方法返回的是一个 HttpResponse 实例 # 之所以需要先调用父类的 get 方法,是因为只有当 get 方法被调用后, # 才有 self.object 属性,其值为 Post 模型实例,即被访问的文章 post response = super(PostDetailView, self).get(request, *args, **kwargs) # 将文章阅读量 +1 # 注意 self.object 的值就是被访问的文章 post self.object.increase_views() # 视图必须返回一个 HttpResponse 对象 return response def get_object(self, queryset=None): # 覆写 get_object 方法的目的是因为需要对 post 的 body 值进行渲染 post = super(PostDetailView, self).get_object(queryset=None) #此处先将markdown禁掉,因为显然经过markdown渲染的文本,再经过MathJax渲染就不能看了 #但是不经markdown渲染,代码段又不能正常显示,淦 #所以以后写带公式的博文,公式格式参考MathJax附带的样例,防止自己写的经过markdown渲染后抽风 md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', 'markdown.extensions.toc', TocExtension(slugify=slugify), ]) post.body = md.convert(post.body) post.toc = md.toc return post def get_context_data(self, **kwargs): # 覆写 get_context_data 的目的是因为除了将 post 传递给模板外(DetailView 已经帮我们完成), # 还要把评论表单、post 下的评论列表传递给模板。 context = super(PostDetailView, self).get_context_data(**kwargs) form = CommentForm() comment_list = self.object.comment_set.all() context.update({ 'form': form, 'comment_list': comment_list }) return context #查看归档 """ def archives(request, year, month): post_list = Post.objects.filter(created_time__year=year, created_time__month=month ).order_by('-created_time') return render(request, 'blog/index.html', context={'post_list': post_list}) """ class ArchivesView(ListView): model = Post template_name = 'blog/index.html' context_object_name = 'post_list' def get_queryset(self): year = self.kwargs.get('year') month = self.kwargs.get('month') return super(ArchivesView, self).get_queryset().filter(created_time__year=year, created_time__month=month ) #查看分类文章 """ def category(request, pk): cate = get_object_or_404(Category, pk=pk) post_list = Post.objects.filter(category=cate).order_by('-created_time') return render(request, 'blog/index.html', context={'post_list': post_list}) """ class CategoryView(ListView): model = Post template_name = 'blog/index.html' context_object_name = 'post_list' def get_queryset(self): cate = get_object_or_404(Category, pk=self.kwargs.get('pk')) return super(CategoryView, self).get_queryset().filter(category=cate) #查看标签文章 class TagView(ListView): model = Post template_name = 'blog/index.html' context_object_name = 'post_list' def get_queryset(self): tag = get_object_or_404(Tag, pk=self.kwargs.get('pk')) return super(TagView, self).get_queryset().filter(tags=tag) #文章搜索 def search(request): q = request.GET.get('q') error_msg = '' if not q: error_msg = "请输入关键词" return render(request, 'blog/index.html', {'error_msg': error_msg}) post_list = Post.objects.filter(Q(title__icontains=q) | Q(body__icontains=q)) return render(request, 'blog/index.html', {'error_msg': error_msg, 'post_list': post_list}) #查看书评 class BookView(ListView): model = Book template_name = 'blog/book.html' context_object_name = 'book_list' paginate_by = 20 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) paginator = context.get('paginator') page = context.get('page_obj') is_paginated = context.get('is_paginated') pagination_data = self.pagination_data(paginator, page, is_paginated) context.update(pagination_data) return context def pagination_data(self, paginator, page, is_paginated): if not is_paginated: return {} left = [] right = [] left_has_more = False right_has_more = False first = False last = False page_number = page.number total_pages = paginator.num_pages page_range = paginator.page_range if page_number == 1: right = page_range[page_number:page_number + 2] if right[-1] < total_pages - 1: right_has_more = True if right[-1] < total_pages: last = True elif page_number == total_pages: left = page_range[(page_number - 3) if (page_number - 3) > 0 else 0:page_number - 1] if left[0] > 2: left_has_more = True if left[0] > 1: first = True else: left = page_range[(page_number - 3) if (page_number - 3) > 0 else 0:page_number - 1] right = page_range[page_number:page_number + 2] if right[-1] < total_pages - 1: right_has_more = True if right[-1] < total_pages: last = True if left[0] > 2: left_has_more = True if left[0] > 1: first = True data = { 'left': left, 'right': right, 'left_has_more': left_has_more, 'right_has_more': right_has_more, 'first': first, 'last': last, } return data class BookDetailView(DetailView): model = Book template_name = 'blog/bookdetail.html' context_object_name = 'book' def get_object(self, queryset=None): # 覆写 get_object 方法的目的是因为需要对 book 的 review 值进行渲染 book = super(BookDetailView, self).get_object(queryset=None) md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', #'markdown.extensions.toc', #TocExtension(slugify=slugify), ]) book.review = md.convert(book.review) #book.toc = md.toc return book def get_context_data(self, **kwargs): context = super(BookDetailView, self).get_context_data(**kwargs) form = BookCommentForm() comment_list = self.object.bookcomment_set.all() context.update({ 'form': form, 'comment_list': comment_list }) return context #书评归档 class BookArchivesView(ListView): model = Book template_name = 'blog/book.html' context_object_name = 'book_list' def get_queryset(self): year = self.kwargs.get('year') month = self.kwargs.get('month') return super(BookArchivesView, self).get_queryset().filter(created_time__year=year, created_time__month=month ) ###影评相关 class FilmView(ListView): model = Movie template_name = 'blog/film.html' context_object_name = 'film_list' paginate_by = 36 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) paginator = context.get('paginator') page = context.get('page_obj') is_paginated = context.get('is_paginated') pagination_data = self.pagination_data(paginator, page, is_paginated) context.update(pagination_data) return context def pagination_data(self, paginator, page, is_paginated): if not is_paginated: return {} left = [] right = [] left_has_more = False right_has_more = False first = False last = False page_number = page.number total_pages = paginator.num_pages page_range = paginator.page_range if page_number == 1: right = page_range[page_number:page_number + 2] if right[-1] < total_pages - 1: right_has_more = True if right[-1] < total_pages: last = True elif page_number == total_pages: left = page_range[(page_number - 3) if (page_number - 3) > 0 else 0:page_number - 1] if left[0] > 2: left_has_more = True if left[0] > 1: first = True else: left = page_range[(page_number - 3) if (page_number - 3) > 0 else 0:page_number - 1] right = page_range[page_number:page_number + 2] if right[-1] < total_pages - 1: right_has_more = True if right[-1] < total_pages: last = True if left[0] > 2: left_has_more = True if left[0] > 1: first = True data = { 'left': left, 'right': right, 'left_has_more': left_has_more, 'right_has_more': right_has_more, 'first': first, 'last': last, } return data class FilmDetailView(DetailView): model = Movie template_name = 'blog/filmdetail.html' context_object_name = 'film' def get_object(self, queryset=None): film = super(FilmDetailView, self).get_object(queryset=None) md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', 'markdown.extensions.codehilite', #'markdown.extensions.toc', #TocExtension(slugify=slugify), ]) film.review = md.convert(film.review) #film.toc = md.toc return film def get_context_data(self, **kwargs): context = super(FilmDetailView, self).get_context_data(**kwargs) form = MovieCommentForm() comment_list = self.object.moviecomment_set.all() context.update({ 'form': form, 'comment_list': comment_list }) return context #影评归档 class FilmArchivesView(ListView): model = Movie template_name = 'blog/film.html' context_object_name = 'film_list' def get_queryset(self): year = self.kwargs.get('year') month = self.kwargs.get('month') return super(FilmArchivesView, self).get_queryset().filter(created_time__year=year, created_time__month=month ) def about(request): return render(request, 'blog/about.html')
33.967546
96
0.582706
1,813
16,746
5.184225
0.163817
0.044686
0.018725
0.024258
0.604107
0.571763
0.545803
0.528035
0.513565
0.498457
0
0.012035
0.320256
16,746
493
97
33.967546
0.81367
0.15341
0
0.746711
0
0
0.066185
0.0151
0
0
0
0
0
1
0.065789
false
0
0.026316
0.003289
0.325658
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
436c11b07a0ae268fa5c1da96fe20213b0b714a7
3,501
py
Python
aiogram/types/inline_query.py
SvineruS/aiogram
7892edf45302fa195544430ac5db11dcbcbf7ae6
[ "MIT" ]
1
2021-01-10T18:04:25.000Z
2021-01-10T18:04:25.000Z
aiogram/types/inline_query.py
SvineruS/aiogram
7892edf45302fa195544430ac5db11dcbcbf7ae6
[ "MIT" ]
5
2021-02-13T14:30:27.000Z
2021-02-13T17:27:58.000Z
aiogram/types/inline_query.py
SvineruS/aiogram
7892edf45302fa195544430ac5db11dcbcbf7ae6
[ "MIT" ]
1
2022-02-10T14:57:27.000Z
2022-02-10T14:57:27.000Z
import typing from . import base from . import fields from .inline_query_result import InlineQueryResult from .location import Location from .user import User class InlineQuery(base.TelegramObject): """ This object represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results. https://core.telegram.org/bots/api#inlinequery """ id: base.String = fields.Field() from_user: User = fields.Field(alias='from', base=User) location: Location = fields.Field(base=Location) query: base.String = fields.Field() offset: base.String = fields.Field() async def answer(self, results: typing.List[InlineQueryResult], cache_time: typing.Optional[base.Integer] = None, is_personal: typing.Optional[base.Boolean] = None, next_offset: typing.Optional[base.String] = None, switch_pm_text: typing.Optional[base.String] = None, switch_pm_parameter: typing.Optional[base.String] = None): """ Use this method to send answers to an inline query. No more than 50 results per query are allowed. Source: https://core.telegram.org/bots/api#answerinlinequery :param results: A JSON-serialized array of results for the inline query :type results: :obj:`typing.List[types.InlineQueryResult]` :param cache_time: The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300. :type cache_time: :obj:`typing.Optional[base.Integer]` :param is_personal: Pass True, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query :type is_personal: :obj:`typing.Optional[base.Boolean]` :param next_offset: Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don‘t support pagination. Offset length can’t exceed 64 bytes. :type next_offset: :obj:`typing.Optional[base.String]` :param switch_pm_text: If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter :type switch_pm_text: :obj:`typing.Optional[base.String]` :param switch_pm_parameter: Deep-linking parameter for the /start message sent to the bot when user presses the switch button. 1-64 characters, only A-Z, a-z, 0-9, _ and - are allowed. :type switch_pm_parameter: :obj:`typing.Optional[base.String]` :return: On success, True is returned :rtype: :obj:`base.Boolean` """ return await self.bot.answer_inline_query(self.id, results=results, cache_time=cache_time, is_personal=is_personal, next_offset=next_offset, switch_pm_text=switch_pm_text, switch_pm_parameter=switch_pm_parameter)
52.253731
118
0.625821
445
3,501
4.826966
0.32809
0.040968
0.083799
0.067039
0.15689
0.116387
0.070764
0.037244
0
0
0
0.004928
0.304484
3,501
66
119
53.045455
0.877207
0.053985
0
0
0
0
0.002805
0
0
0
0
0
0
1
0
true
0
0.230769
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
0
0
0
0
0
1