max_stars_repo_path
stringlengths 4
182
| max_stars_repo_name
stringlengths 6
116
| max_stars_count
int64 0
191k
| id
stringlengths 7
7
| content
stringlengths 100
10k
| size
int64 100
10k
|
---|---|---|---|---|---|
python/yunet/trt_yunet.py
|
NobuoTsukamoto/tensorrt-examples
| 33 |
2171104
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
TensorRT YuNet .
Copyright (c) 2021 <NAME>
This software is released under the MIT License.
See the LICENSE file in the project root for more information.
"""
# This source corresponds to TensorRT by referring to the following.
# https://github.com/opencv/opencv_zoo/blob/e6e1754dcf0c058cad20166498e68f17c71fa3b1/models/face_detection_yunet/yunet.py
from itertools import product
import numpy as np
import cv2 as cv
import tensorrt as trt
import common
TRT_LOGGER = trt.Logger(trt.Logger.INFO)
trt.init_libnvinfer_plugins(TRT_LOGGER, "")
class TrtYuNet:
def __init__(
self,
model_path,
input_size=[160, 120],
conf_threshold=0.6,
nms_threshold=0.3,
top_k=5000,
keep_top_k=750,
):
self._model_path = model_path
self._engine = self._getEngine(self._model_path)
self._context = self._engine.create_execution_context()
self._input_size = input_size # [w, h]
self._conf_threshold = conf_threshold
self._nms_threshold = nms_threshold
self._top_k = top_k
self._keep_top_k = keep_top_k
self._min_sizes = [[10, 16, 24], [32, 48], [64, 96], [128, 192, 256]]
self._steps = [8, 16, 32, 64]
self._variance = [0.1, 0.2]
# Generate priors
self._priorGen()
@property
def name(self):
return self.__class__.__name__
def setInputSize(self, input_size):
self._input_size = input_size # [w, h]
# Regenerate priors
self._priorGen()
def _getEngine(self, engine_file_path):
print("Reading engine from file {}".format(engine_file_path))
with open(engine_file_path, "rb") as f, trt.Runtime(TRT_LOGGER) as runtime:
return runtime.deserialize_cuda_engine(f.read())
def _preprocess(self, image):
image = cv.resize(image, (self._input_size[0], self._input_size[1]))
image = np.asarray(image, dtype="float32")
image = image.transpose(2, 0, 1)
return image
def infer(self, image):
# Preprocess
input_blob = self._preprocess(image)
# Forward
inputs, outputs, bindings, stream = common.allocate_buffers(self._engine)
inputs[0].host = np.ascontiguousarray(input_blob)
outputs = common.do_inference_v2(
self._context,
bindings=bindings,
inputs=inputs,
outputs=outputs,
stream=stream,
)
# Postprocess
results = self._postprocess(outputs)
return results
def _postprocess(self, output_blob):
# Decode
dets = self._decode(output_blob)
# NMS
keepIdx = cv.dnn.NMSBoxes(
bboxes=dets[:, 0:4].tolist(),
scores=dets[:, -1].tolist(),
score_threshold=self._conf_threshold,
nms_threshold=self._nms_threshold,
top_k=self._top_k,
) # box_num x class_num
if len(keepIdx) > 0:
dets = dets[keepIdx]
dets = np.squeeze(dets, axis=1)
return dets[: self._keep_top_k]
else:
return np.empty(shape=(0, 15))
def _priorGen(self):
w, h = self._input_size
feature_map_2th = [int(int((h + 1) / 2) / 2), int(int((w + 1) / 2) / 2)]
feature_map_3th = [int(feature_map_2th[0] / 2), int(feature_map_2th[1] / 2)]
feature_map_4th = [int(feature_map_3th[0] / 2), int(feature_map_3th[1] / 2)]
feature_map_5th = [int(feature_map_4th[0] / 2), int(feature_map_4th[1] / 2)]
feature_map_6th = [int(feature_map_5th[0] / 2), int(feature_map_5th[1] / 2)]
feature_maps = [
feature_map_3th,
feature_map_4th,
feature_map_5th,
feature_map_6th,
]
priors = []
for k, f in enumerate(feature_maps):
min_sizes = self._min_sizes[k]
for i, j in product(range(f[0]), range(f[1])): # i->h, j->w
for min_size in min_sizes:
s_kx = min_size / w
s_ky = min_size / h
cx = (j + 0.5) * self._steps[k] / w
cy = (i + 0.5) * self._steps[k] / h
priors.append([cx, cy, s_kx, s_ky])
self.priors = np.array(priors, dtype=np.float32)
def _decode(self, outputBlob):
loc = np.array(outputBlob[0]).reshape([-1, 14])
conf = np.array(outputBlob[1]).reshape([-1, 2])
iou = np.array(outputBlob[2]).reshape([-1, 1])
# get score
cls_scores = conf[:, 1]
iou_scores = iou[:, 0]
# clamp
_idx = np.where(iou_scores < 0.0)
iou_scores[_idx] = 0.0
_idx = np.where(iou_scores > 1.0)
iou_scores[_idx] = 1.0
scores = np.sqrt(cls_scores * iou_scores)
scores = scores[:, np.newaxis]
scale = np.array(self._input_size)
# get bboxes
bboxes = np.hstack(
(
(
self.priors[:, 0:2]
+ loc[:, 0:2] * self._variance[0] * self.priors[:, 2:4]
)
* scale,
(self.priors[:, 2:4] * np.exp(loc[:, 2:4] * self._variance)) * scale,
)
)
# (x_c, y_c, w, h) -> (x1, y1, w, h)
bboxes[:, 0:2] -= bboxes[:, 2:4] / 2
# get landmarks
landmarks = np.hstack(
(
(
self.priors[:, 0:2]
+ loc[:, 4:6] * self._variance[0] * self.priors[:, 2:4]
)
* scale,
(
self.priors[:, 0:2]
+ loc[:, 6:8] * self._variance[0] * self.priors[:, 2:4]
)
* scale,
(
self.priors[:, 0:2]
+ loc[:, 8:10] * self._variance[0] * self.priors[:, 2:4]
)
* scale,
(
self.priors[:, 0:2]
+ loc[:, 10:12] * self._variance[0] * self.priors[:, 2:4]
)
* scale,
(
self.priors[:, 0:2]
+ loc[:, 12:14] * self._variance[0] * self.priors[:, 2:4]
)
* scale,
)
)
dets = np.hstack((bboxes, landmarks, scores))
return dets
| 6,476 |
workflows/nlp/visualization_views.py
|
xflows/textflows
| 18 |
2171884
|
'''
NLP visualization views.
@author: <NAME> <<EMAIL>>
'''
from django.shortcuts import render
import nlp
def definition_sentences_viewer(request, input_dict, output_dict, widget):
"""
Parses the input XML and displays the definition sentences given as input.
@author: <NAME>, 2012
"""
sentences = nlp.parse_def_sentences(input_dict['candidates'])
return render(request, 'visualizations/def_sentences.html',{'widget' : widget, 'sentences' : sentences})
def definition_sentences_viewer2(request, input_dict, output_dict, widget):
"""
Parses the input XML and displays the definition sentences given as input.
@author: <NAME>, 2012
"""
ids_sentence = input_dict["ids_sentence"] == "true"
ids_article = input_dict["ids_article"] == "true"
text_sentence = input_dict["text_sentence"] == "true"
sentences = nlp.parse_def_sentences2(input_dict['candidates'])
return render(request, 'visualizations/def_sentences2.html',{'widget' : widget, 'sentences' : sentences, 'ids_sentence': ids_sentence, 'ids_article': ids_article, 'text_sentence':text_sentence})
def term_candidate_viewer(request, input_dict, output_dict, widget):
"""
Parses the input and displays the term candidates.
@author: <NAME>, 2012
"""
terms = []
for line in input_dict['candidates'].split('\n'):
try:
score, cand, lemma = line.split('\t')
except:
continue
terms.append({'score' : score,
'cand' : cand.replace('[', '').replace(']',''),
'lemma' : lemma.replace('<<', '').replace('>>','')
})
terms = sorted(terms, key = lambda x: x['score'], reverse=True)
return render(request, 'visualizations/terms.html', {'widget' : widget, 'terms' : terms})
| 1,836 |
volkscv/analyzer/statistics/processor/base.py
|
YuxinZou/volkscv
| 59 |
2170297
|
from ..base import Base
from ..plotter import BasePlotter, Compose, SubPlotter
class BaseProcessor(Base):
""" Base class of processors.
Args:
data: Data to be processed.
"""
def __init__(self, data):
self.data = data
self.processor = []
def default_plot(self, *args, **kwargs):
""" A default plot function. It will call the default_plot function
of each processed processors in self.processor.
"""
for p in self.processor:
p_ = getattr(self, p)
if isinstance(p_, SubPlotter):
p_.plot()
elif isinstance(p_, BasePlotter):
p_.figure(p_.text, *args, **kwargs)
p_.title(p_.text)
p_.plot()
elif isinstance(p_, Compose):
if p_.flag:
p_.plot()
else:
p_.figure(p_.text, *args, **kwargs)
p_.title(p_.text)
p_.plot()
elif isinstance(p_, BaseProcessor):
p_.default_plot(*args, **kwargs)
else:
continue
def plot(self):
""" Call the plot method or each processor in self.processor."""
for p in self.processor:
if hasattr(self, p):
p_ = getattr(self, p)
p_.plot()
| 1,377 |
model/DHS_resnext_back.py
|
lartpang/DHSNet-PyTorch
| 3 |
2172129
|
import torch
import torch.nn.functional as F
from torch import nn
from model import ResNeXt101
class R3Net(nn.Module):
def __init__(self, new_block):
super(R3Net, self).__init__()
self.upsample = lambda x: F.interpolate(
x, scale_factor=2, mode='nearest'
)
resnext = ResNeXt101()
# 对应的五个阶段
self.layer0 = resnext.layer0 # 1/4
self.layer1 = resnext.layer1 # 1/4
self.layer2 = resnext.layer2 # 1/8
self.layer3 = resnext.layer3 # 1/16
self.layer4 = resnext.layer4 # 1/32
# 这里可以考虑去掉, 直接换成一个卷积与上采样的组合, 这样可以任意输入图片了.
self.fc_line = nn.Linear(7 * 7 * 2048, 196)
# 这里括号里的都是前期卷积的特征图的对应的通道数量 => in_channels
self.rcl1 = new_block(1024)
self.rcl2 = new_block(512)
self.rcl3 = new_block(256)
self.rcl4 = new_block(3)
for m in self.modules():
if isinstance(m, nn.ReLU) or isinstance(m, nn.Dropout):
m.inplace = True
def forward(self, x_1):
# 获取五个阶段的特征输出
x_4 = self.layer0(x_1) # x/4
x_4 = self.layer1(x_4) # x/4
x_8 = self.layer2(x_4) # x/8
x_16 = self.layer3(x_8) # x/16 = 14
x_32 = self.layer4(x_16) # x/32
bz = x_32.shape[0]
x = x_32.view(bz, -1)
# x = F.adaptive_avg_pool2d(x, (1, 1)).view(bz, -1)
x = self.fc_line(x) # generate the SMRglobal
x = x.view(bz, 1, 14, -1)
x1 = torch.sigmoid(x)
x = self.rcl1.forward(x_16, x)
x2 = torch.sigmoid(x)
x = self.upsample(x)
x = self.rcl2.forward(x_8, x)
x3 = torch.sigmoid(x)
x = self.upsample(x)
x = self.rcl3.forward(x_4, x)
x4 = torch.sigmoid(x)
x = self.upsample(x)
x = self.upsample(x)
x = self.rcl4.forward(x_1, x)
x5 = torch.sigmoid(x)
# 训练的时候要对7个预测都进行监督(深监督)
return x1, x2, x3, x4, x5
| 2,040 |
net/fasterrcnn.py
|
TangZhenchaoTZC/Keras-mask-detection
| 3 |
2171995
|
"""fasterRCNN构建,这里只是返回模型"""
from net import backbone as backbone
from net import RPN as RPN
from net import classify as classify
from keras.layers import Input
from keras.models import Model
def get_model(flag,class_num):
"""直观反映流程,用于训练"""
inputs = Input(shape=(None, None, 3))
roi_input = Input(shape=(None, 4))
#共享特征层
base_layers = backbone.ResNet50(inputs)
#默认为9
anchor_num = len(flag.anchor_box_scales) * len(flag.anchor_box_ratios)
#建立RPN
rpn = RPN.RPN(base_layers,anchor_num)
#[:2]切片,只选择列表内最初的两个索引0,1
#index=0,N行1列9*坐标个数的概率值,index=1,N行4列,N行1列9*坐标个数的的偏移信息
model_rpn = Model(inputs, rpn[:2])
#roi_input为建议框[None, 4],None与每次处理的建议框数量num_rois有关,config中定义为32
# classifier为[out_class,out_regr]
# out_class为(Batch_size,32个建议框,21)
# out_regr为(Batch_size,32个建议框,80)
classifier = classify.end_classify(base_layers, roi_input, flag.num_rois, nb_classes=class_num, trainable=True)
model_classifier = Model([inputs, roi_input], classifier)
#model_all实际上是合并了RPN网络和分类网络,即为fasterrcnn网络
model_all = Model([inputs, roi_input], rpn[:2]+classifier)
return model_rpn,model_classifier,model_all
def get_predict_model(config,num_classes):
"""用于预测"""
inputs = Input(shape=(None, None, 3))
roi_input = Input(shape=(None, 4))
feature_map_input = Input(shape=(None,None,1024))
base_layers = backbone.ResNet50(inputs)
num_anchors = len(config.anchor_box_scales) * len(config.anchor_box_ratios)
rpn = RPN.RPN(base_layers, num_anchors)
model_rpn = Model(inputs, rpn)
classifier = classify.end_classify(feature_map_input, roi_input, config.num_rois, nb_classes=num_classes, trainable=True)
model_classifier_only = Model([feature_map_input, roi_input], classifier)
return model_rpn,model_classifier_only
| 1,814 |
userbot/clients/__init__.py
|
CoeF/Ayiin-Userbot
| 2 |
2171585
|
from .client_list import client_id, clients_list
from .logger import ayiin_userbot_on
from .startup import ayiin_client, multiayiin
| 132 |
ReflectionPadding3D.py
|
gegewen/ccsnet_v1.0
| 2 |
2170915
|
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Layer
import tensorflow as tf
reg_weights = 0.001
class ReflectionPadding3D(Layer):
def __init__(self, padding=(1, 1, 1), dim_ordering='default', **kwargs):
super(ReflectionPadding3D, self).__init__(**kwargs)
if dim_ordering == 'default':
dim_ordering = K.image_data_format()
self.padding = padding
self.dim_ordering = dim_ordering
def call(self, x, mask=None):
top_pad = self.padding[0]
bottom_pad = self.padding[0]
left_pad = self.padding[1]
right_pad = self.padding[1]
front_pad = self.padding[2]
back_pad = self.padding[2]
paddings = [[0, 0], [left_pad, right_pad], [top_pad, bottom_pad], [front_pad, back_pad], [0, 0]]
return tf.pad(x, paddings, mode='REFLECT', name=None)
def compute_output_shape(self, input_shape):
if self.dim_ordering == 'tf':
rows = input_shape[1] + self.padding[0] + self.padding[0] if input_shape[1] is not None else None
cols = input_shape[2] + self.padding[1] + self.padding[1] if input_shape[2] is not None else None
dep = input_shape[3] + self.padding[2] + self.padding[2] if input_shape[3] is not None else None
return (input_shape[0],
rows,
cols,
dep,
input_shape[4])
else:
raise ValueError('Invalid dim_ordering:', self.dim_ordering)
def get_config(self):
config = super(ReflectionPadding3D, self).get_config()
config.update({'padding': self.padding,
'dim_ordering': self.dim_ordering})
return config
| 1,751 |
flux_balance_analysis/collate_cluster_output.py
|
llambourne/isoenzymes_flux_balance
| 0 |
2171284
|
"""Script to read in all the costs and write to csv."""
import os
import cPickle as pickle
from collections import defaultdict
import cobra
from fba_utils import *
def collate_cluster_output(modelPath):
modelName = modelPath.split('/')[-1][:-4]
modelDir = '../models/' + modelName
clusterDir = os.path.join(modelDir, 'cluster_output')
flcOutPath = os.path.join(modelDir, 'function_loss_costs.tsv')
glcOutPath = os.path.join(modelDir, 'gene_loss_costs.tsv')
noGrowthOutPath = os.path.join(modelDir, 'minimal_media_no_growth.tsv')
dblGenePath = os.path.join(modelDir, 'double_gene_loss_growth.csv')
dblFunctionPath = os.path.join(modelDir, 'double_function_loss_growth.csv')
model = cobra.io.read_sbml_model(modelPath)
modelGeneNames = set([g.id for g in model.genes])
with open('../data/processed/carbon_sources.txt', 'r') as f:
carbonSourceNames = [l.strip() for l in f.readlines()]
with open('../data/processed/nitrogen_sources.txt', 'r') as f:
nitrogenSourceNames = [l.strip() for l in f.readlines()]
mediaWithGrowth = []
mediaNoGrowth = []
glc = defaultdict(list)
flc = defaultdict(list)
dblGLC = {}
dblFLC = {}
for c in carbonSourceNames:
for n in nitrogenSourceNames:
fnGLC = ('gene_loss_cost_' + c + '_AND_' + n + '.pkl').replace(' ', '_')
glcInPath = os.path.join(clusterDir, fnGLC)
if not os.path.exists(glcInPath):
model = minimal_media(model, c, n)
if model.optimize().f > 0.01:
raise UserWarning('growth on media but no file found\n' +
c + ' AND ' + n)
mediaNoGrowth.append((c, n))
continue
with open(glcInPath, 'r') as f:
mediaWithGrowth.append((c, n))
glcOneMedia = pickle.load(f)
if set(glcOneMedia.keys()) != modelGeneNames:
raise UserWarning('Unknown or missing genes in:'+glcInPath)
for geneName, cost in glcOneMedia.items():
glc[geneName].append(cost)
fnFLC = ('function_loss_cost_' + c + '_AND_' + n + '.pkl').replace(' ', '_')
flcInPath = os.path.join(clusterDir, fnFLC)
with open(flcInPath, 'r') as f:
flcOneMedia = pickle.load(f)
if set(flcOneMedia.keys()) != modelGeneNames:
raise UserWarning('Unknown or missing genes in:'+flcInPath)
for geneName, cost in flcOneMedia.items():
flc[geneName].append(cost)
print len(mediaNoGrowth), '/', len(carbonSourceNames) * len(nitrogenSourceNames),
print 'Environments with no wildtype growth'
########### Load double function knockouts #######################
for i in range(len(model.genes) - 1):
filePath = os.path.join(clusterDir,
'growth_double_function_knockouts_'+str(i)+'.pkl')
if not os.path.exists(filePath):
raise UserWarning(filePath + ' does not exist')
with open(filePath, 'r') as f:
dblFunctionKO = pickle.load(f)
if len(dblFunctionKO) != (len(model.genes) - i) - 1:
raise UserWarning('Unexpected number of double knockouts'
' in file: ' + filePath + 'found ' +
str(len(dblFunctionKO)) + ' expected: '
+ str((len(model.genes) - i) - 1))
if any([k in dblFLC for k in dblFunctionKO]):
raise UserWarning('Duplicate entries in results')
dblFLC.update(dblFunctionKO)
########### Load double gene knockouts #######################
for i in range(len(model.genes) - 1):
filePath = os.path.join(clusterDir,
'growth_double_gene_knockouts_'+str(i)+'.pkl')
if not os.path.exists(filePath):
raise UserWarning(filePath + ' does not exist')
with open(filePath, 'r') as f:
result = pickle.load(f)
for i in range(result['data'].shape[0]):
geneA = result['x'][i]
for j in range(result['data'].shape[1]):
geneB = result['y'][j]
dblGLC[(geneA, geneB)] = result['data'][i, j]
################### write out data ###############################
if not os.path.exists(noGrowthOutPath):
with open(noGrowthOutPath, 'w') as f:
for c, n in mediaNoGrowth:
f.write(c + '\t' + n + '\n')
else:
print noGrowthOutPath, 'already exists'
if not os.path.exists(flcOutPath):
with open(flcOutPath, 'w') as f:
f.write('ORF ID\t' + '\t'.join([' AND '.join(cn)
for cn in mediaWithGrowth]) + '\n')
for geneName, costs in flc.items():
f.write(geneName + '\t' + '\t'.join([str(c) for c in costs])+'\n')
else:
print flcOutPath, 'already exists'
if not os.path.exists(glcOutPath):
with open(glcOutPath, 'w') as f:
f.write('ORF ID\t' + '\t'.join([' AND '.join(cn)
for cn in mediaWithGrowth]) + '\n')
for geneName, costs in glc.items():
f.write(geneName + '\t' + '\t'.join([str(c) for c in costs])+'\n')
else:
print glcOutPath, 'already exists'
if not os.path.exists(dblGenePath):
with open(dblGenePath, 'w') as f:
for (geneA, geneB), growth in dblGLC.items():
f.write(geneA + ',' + geneB + ',' + str(growth) + '\n')
else:
print dblGenePath, 'already exists'
if not os.path.exists(dblFunctionPath):
with open(dblFunctionPath, 'w') as f:
for (geneA, geneB), growth in dblFLC.items():
f.write(geneA + ',' + geneB + ',' + str(growth) + '\n')
else:
print dblFunctionPath, 'already exists'
def main():
collate_cluster_output('../data/external/yeast_7.6/yeast_7.6.xml')
if __name__ == '__main__':
main()
| 6,224 |
PFPO/common/metrics.py
|
phillipcpark/PredictiveFPO
| 0 |
2171188
|
from mpmath import mp
from collections import Counter
from numpy import amax, argmax
#
def prec_recall(predicts, labels, classes, ignore_class, pred_thresh=None):
correct = {}
incorrect = {}
true = {0:0, 1:0}
for c in range(classes):
correct[c] = 0
incorrect[c] = 0
for p_idx in range(len(predicts)):
gt = int(labels[p_idx].detach().numpy())
if (gt == ignore_class):
continue
true[gt] += 1
pred_class = None
if not(pred_thresh is None):
max_prob = amax(predicts.detach().numpy()[p_idx])
if (max_prob >= pred_thresh):
pred_class = argmax(predicts[p_idx].detach().numpy())
else:
pred_class = 0
else:
pred_class = argmax(predicts[p_idx].detach().numpy())
if (pred_class == gt):
correct[pred_class] += 1
else:
incorrect[pred_class] += 1
prec = {}
rec = {}
for c in range(classes):
if (true[c] == 0):
if (incorrect[c] == 0):
prec[c] = 1.0
rec[c] = 1.0
else:
prec[c] = 0.0
rec[c] = 1.0
else:
if (correct[c] + incorrect[c] == 0):
prec[c] = 0.0
rec[c] = 0.0
else:
prec[c] = float(correct[c]) / (correct[c] + incorrect[c])
rec[c] = float(correct[c]) / true[c]
return prec, rec
#
def relative_error(val_num, val_denom):
mp.prec = 65
try:
return mpmath.fabs((val_num - val_denom) / val_denom)
except:
return 0.0
# see if error sample is acceptable
def accept_err(errs, thresh, accept_proportion):
sz = len(errs)
gt_thresh = 0
max_count = int(sz * (1.0 - accept_proportion))
accept_thresh = thresh
for err in errs:
if (err > accept_thresh):
gt_thresh += 1
prop_gt_thresh = float(gt_thresh) / float(sz)
if (prop_gt_thresh >= (1.0 - accept_proportion)):
return False, prop_gt_thresh
return True, prop_gt_thresh
#
def update_freq_delta(prec_freq_deltas, otc_tuned, otc_orig):
# precision counts
total = len(otc_tuned)
orig_counts = {32:0, 64:0, 80:0}
for prec in otc_orig:
orig_counts[prec] += 1
prec_counts = {32:0, 64:0, 80:0}
for prec in otc_tuned:
prec_counts[prec] += 1
for k in prec_counts.keys():
prec_freq_deltas[k].append(float(prec_counts[k])/total - float(orig_counts[k])/total)
| 2,652 |
code/gui/config.py
|
matfurrier/QlikForecast
| 6 |
2171744
|
import qrspy
host = 'localhost'
port = 4242
certPath = 'C:/ProgramData/Qlik/Sense/Repository/Exported Certificates/.Local Certificates/'
qrs = qrspy.ConnectQlik(server = host + ':' + str(port),
certificate = (certPath + 'client.pem', certPath + 'client_key.pem'))
print(qrs)
| 324 |
setup.py
|
Fitblip/DVR-Scan
| 0 |
2172143
|
#!/usr/bin/env python
#
# DVR-Scan: Video Motion Event Detection & Extraction Tool
# --------------------------------------------------------------
# [ Site: https://github.com/Breakthrough/DVR-Scan/ ]
# [ Documentation: http://dvr-scan.readthedocs.org/ ]
#
# Installation and build script for DVR-Scan. To install DVR-Scan in the
# current environment, run:
#
# > python setup.py install
#
# This will allow you to use the `dvr-scan` command from the terminal or
# command prompt. When upgrading to a new version, running the above command
# will automatically overwrite any existing older version.
#
import sys
from setuptools import setup
if sys.version_info < (2, 6) or (3, 0) <= sys.version_info < (3, 3):
print('DVR-Scan requires at least Python 2.6 or 3.3 to run.')
sys.exit(1)
def get_requires():
# type: () -> List[str]
""" Get Requires: Returns a list of required packages. """
requires = ['numpy', 'tqdm']
if sys.version_info == (2, 6):
requires += ['argparse']
return requires
def get_extra_requires():
# type: () -> Dict[str, List[str]]
""" Get Extra Requires: Returns a list of extra/optional packages. """
return {
'opencv:python_version <= "3.5"':
['opencv-python<=4.2.0.32'],
'opencv:python_version > "3.5"':
['opencv-python'],
'opencv-headless:python_version <= "3.5"':
['opencv-python-headless<=4.2.0.32'],
'opencv-headless:python_version > "3.5"':
['opencv-python-headless'],
}
setup(
name='dvr-scan',
version='1.1.0',
description="Tool for finding and extracting motion events in video files (e.g. security camera footage).",
long_description=open('package-info.rst').read(),
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/Breakthrough/DVR-Scan',
license="BSD 2-Clause",
keywords="video computer-vision analysis",
install_requires=get_requires(),
extras_require=get_extra_requires(),
packages=['dvr_scan'],
package_data={'': ['../LICENSE*', '../package-info.rst']},
#include_package_data = True, # Only works with this line commented.
#test_suite="unitest.py",
entry_points={"console_scripts": ["dvr-scan=dvr_scan:main"]},
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Console',
'Environment :: Console :: Curses',
'Intended Audience :: Developers',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Topic :: Multimedia :: Video',
'Topic :: Multimedia :: Video :: Conversion',
'Topic :: Multimedia :: Video :: Non-Linear Editor',
'Topic :: Utilities'
]
)
| 3,322 |
visualisation/tests/test_visualisation.py
|
Zac-HD/awra_cms
| 20 |
2171927
|
from nose.tools import nottest
def test_imports():
import awrams.visualisation
# assert False
@nottest
def test_drive():
import awrams.visualisation.vis as vis
import awrams.visualisation.results as res
# from awrams.utils.catchments import CatchmentDB,CATCHMENT_SHAPEFILE
# catchments = CatchmentDB()
import os.path as o #import dirname,join
import awrams.simulation as sim
# res_dir = o.abspath(o.join('..','simulation','notebooks','_results'))
res_dir = o.abspath(o.join(o.dirname(__file__),'..','..','simulation','notebooks','_results'))
results = res.load_results(res_dir)
results.path
results.variables
results[:,'1 dec 2010',:].spatial()
v = results.variables.s0,results.variables.ss
results[v,'dec 2010',vis.extents.from_boundary_coords(-39.5,143.5,-44,149)].spatial()
vis.plt.savefig('map_of_tasmania.png', format='png', dpi=120)
v = results.variables.qtot
v.agg_method = 'sum'
results[v,'dec 2010',vis.extents.from_boundary_coords(-39.5,143.5,-44,149)].spatial()
results.variables.s0.data.shape
results.variables.s0.agg_data.shape
# v = results.variables.s0,results.variables.ss
# results[v,'dec 2010',catchments.by_name.Lachlan_Gunning()].spatial(interpolation=None) #interpolation="bilinear")
#
# vis.show_extent(catchments.by_name.Lachlan_Gunning())
# vis.show_extent(catchments.by_name.Lachlan_Gunning(),vis.extents.from_boundary_coords(-40,142,-30,154))
#
# catchments.list()
v = results.variables.qtot,results.variables.ss
results[v,'dec 2010',:].spatial(clim=(0,100),xlabel="longitude")
q = results[v,'dec 2010',vis.extents.from_boundary_coords(-39.5,143.5,-44,149)]
q.get_data_limits()
q.spatial(clim=(0,200),xlabel="longitude")
gridview = q.mpl
view = gridview.children[0,1]
view.ax.set_xlabel("ALSO LONGITUDE!")
vis.plt.show()
p = 'dec 2010 - jan 2011'
e = vis.extents.from_cell_coords(-34,117)
results[:,p,e].timeseries()
# v = results.variables.qtot,results.variables.ss
# p = 'dec 2010 - jan 2011'
# e = catchments.by_name.Murrumbidgee_MittagangCrossing()
# results[v,p,e].timeseries()
#
# results.variables.qtot.data.shape,results.variables.qtot.agg_data.shape
| 2,292 |
db_migrate.py
|
gimmy1/flask_taskR
| 0 |
2172206
|
from views import db
from _config import DATABASE_PATH
import sqlite3
from datetime import datetime
with sqlite3.connect(DATABASE_PATH) as connection:
# get a cursor object used to execute SQL commands
c = connection.cursor()
# temporarily change the name of tasks table
c.execute("""ALTER TABLE users RENAME TO old_users""")
# recreate a new tasks table with updated schema
db.create_all()
# retrieve data from old_tasks table
c.execute("""SELECT name, email, password,
FROM old_users ORDER BY id ASC""")
# save all rows as a list of tuples; set posted_date to now and user_id to
# 1
data = [(row[0], row[1], row[2], 'user') for row in c.fetchall()]
# insert data to tasks table
c.executemany(
"""INSERT INTO users (name, email, password, role) VALUES (?, ?, ?, ?)""", data)
# delete old_tasks table
c.execute("DROP TABLE old_users")
| 929 |
tests/contrib/django/app/middlewares.py
|
ocelotl/opentelemetry-auto-instr-python-1
| 2 |
2170998
|
# Copyright 2019, OpenTelemetry Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from django.http import HttpResponse
try:
from django.utils.deprecation import MiddlewareMixin
MiddlewareClass = MiddlewareMixin
except ImportError:
MiddlewareClass = object
class CatchExceptionMiddleware(MiddlewareClass):
def process_exception(self, request, exception):
return HttpResponse(status=500)
class HandleErrorMiddlewareSuccess(MiddlewareClass):
""" Converts an HttpError (that may be returned from an exception handler)
generated by a view or previous middleware and returns a 200
HttpResponse.
"""
def process_response(self, request, response):
if response.status_code == 500:
return HttpResponse(status=200)
return response
class HandleErrorMiddlewareClientError(MiddlewareClass):
""" Converts an HttpError (that may be returned from an exception handler)
generated by a view or previous middleware and returns a 404
HttpResponse.
"""
def process_response(self, request, response):
if response.status_code == 500:
return HttpResponse(status=404)
return response
| 1,708 |
flax_tools/metrics/mean.py
|
cgarciae/flax-tools
| 2 |
2164953
|
from dataclasses import dataclass
import enum
import typing as tp
import jax
import jax.numpy as jnp
import numpy as np
from flax_tools import utils
from flax_tools.metrics.metric import Metric, MapArgs
from flax_tools.metrics.reduce import Reduce, Reduction
@utils.dataclass
class Mean(Reduce):
@classmethod
def new(
cls,
name: tp.Optional[str] = None,
on: tp.Optional[utils.IndexLike] = None,
):
return super().new(
reduction=Reduction.weighted_mean,
name=name,
on=on,
)
| 564 |
bin/exp_generator.py
|
limbo018/OpenMPL
| 42 |
2170267
|
import os
algorithms = ["ILP",
"SDP",
"DL",
"BACKTRACK"]
shape = "POLYGON"
file_path = ""
out = ""
coloring_distance = "100"
layer1 = "15"
layer2 = "16"
color_num = "3"
algo = ""
thread_num = "1"
record = "1"
input_folder = "big/"
output_folder = "benchout/"
file_names = os.listdir(input_folder)
fp = open('experiments.sh', 'w')
for file_name in file_names:
file_path = input_folder + file_name
out = output_folder + "out_" + file_name
for algo in algorithms:
sh = "./OpenMPL " + "-shape " + shape + " -in " + file_path + " -out " + out + " -coloring_distance " + coloring_distance + " -uncolor_layer " + layer1 + " -uncolor_layer " + layer2 + " -color_num " + color_num + " -algo " + algo + " -thread_num " + thread_num + " -use_stitch -gen_stitch" + " -record " + record
fp.write(sh)
fp.write("\n")
fp.write("\n")
fp.close()
| 917 |
hint_cli/hint.py
|
agarthetiger/hint
| 1 |
2170665
|
import glob
import os
import logging
import subprocess
import click
from rich.console import Console
from rich.markdown import Markdown
from hint_cli import repo, config_manager
from hint_cli.format import format_for_stdout
from markdown import parser
logger = logging.getLogger(__name__)
conf = None
def print_markdown(hint_markdown):
console = Console()
md = Markdown(hint_markdown)
console.print(md)
def print_to_console(hint_text: str):
for line in hint_text.split('\n'):
# Skip blank lines
if not line.strip():
continue
formatted_line = format_for_stdout(line)
click.echo(message=formatted_line)
def get_section(hint_text: str, section: str):
"""
Return a section of text based on the section heading from the
hint_text string. '\n' delimited string containing a markdown document.
Args:
hint_text (str): '\n' delimited string containing a markdown document.
section (str): Section heading to search the hint_text for.
Returns:
str: Either the section of text from the hint_text with the
section heading or an error message indicating the section
could not be found.
"""
hint_text_list = hint_text.split("\n")
section = section.lower()
toc = parser.get_toc(hint_text_list)
try:
return "\n".join(hint_text_list[toc[section].start:toc[section].end])
except KeyError:
return f"Section '{section}' not found in document."
def get_display_text(hint_text, subsections):
"""
Get the requested sections of text from the hint_text document.
Args:
hint_text (str): Hint text to display
subsections (tuple): Optional section(s) to return instead of
the whole document.
Returns:
str: Text to display from the hint_text argument.
"""
if len(subsections) == 0:
return hint_text
else:
display_text = ""
for section in subsections:
display_text += get_section(hint_text, section)
if len(display_text) > 0:
return display_text
else:
return hint_text
def get_topic_from_repo(git_repo: str, topic: str):
"""
Get the topic text from the git repository.
Args:
git_repo:
topic:
Returns:
"""
local_path = repo.pull_repo(remote_repo=git_repo, local_path=config_manager.REPO_PATH)
with open(f"{local_path}/{topic}.md", "r") as f:
text = f.read()
return text
def create_or_edit_topic(topic: str):
"""
Creates or edits a markdown file with the name of the topic.
Args:
topic: Name of the topic to create or edit.
"""
subprocess.run(['vim', f"{config_manager.REPO_PATH}/{topic}.md"])
repo.push_all_changes(config_manager.REPO_PATH)
def search_for_text_in_topics(search_term: str):
"""
Search for the requested text in all the hint topic files.
Args:
search_term (str): String to search in the topic files for.
Returns:
String message containing details of the files and the
lines containing the matches.
"""
msg = ""
for topic_file in glob.glob(f"{config_manager.REPO_PATH}/*.md"):
with open(topic_file) as file:
matches = [line
for line in file.readlines()
if line.find(search_term) != -1]
if len(matches) > 0:
msg += f"Matches found in {topic_file}\n"
for match in matches:
msg += f"{match}\n"
return msg
def search_for_topic(topic: str):
"""
Check if the topic (file) exists. Topics are files in a locally
cloned git repository. The topic name should match a markdown
file with a .md file extension. Future versions may fuzzy-match
the filename, or search other locations such as a remote GitHub
repository.
The folder this methods uses to check for the file is defined
by `config.REPO_PATH`
Args:
topic: Name of the topic to verify exists.
Returns:
bool: True if topic (file) exists, otherwise False.
"""
msg = ""
if os.path.isfile(f"{config_manager.REPO_PATH}/{topic}.md"):
msg = f'Hint found for `{topic}`.\n'
else:
msg = f'Hints for topic "{topic}" not found, run `hint --edit ' \
f'{topic}` to create it.\n'
msg += search_for_text_in_topics(topic)
print_to_console(msg)
def display_topic(topic: str, subsections: tuple):
"""
Display the hint topic to the console. If there are no subsections
specified, display the whole file, otherwise just display the
subsections from the topic.
Args:
topic (str): Name of the topic to display
subsections (tuple): Optional subsections to display from the
specified topic.
Returns:
Nothing. Correct function is to print text to the console.
"""
# If no other flags passed, display the hint topic [and subsections]
full_hint_text = get_topic_from_repo(git_repo=conf['hint']['repo'], topic=topic)
display_text = get_display_text(full_hint_text, subsections)
print_to_console(display_text)
def _get_topics(ctx, args, incomplete: str):
"""
Callback function for Click command-line auto-completion.
This allows tab-completion of existing hint topics.
See https://click.palletsprojects.com/en/7.x/bashcomplete/?#what-it-completes
Returns:
(list): Filenames matching the incomplete arg value.
"""
return [filename.split('/')[-1][0:-3]
for filename in glob.glob(f"{config_manager.REPO_PATH}/{incomplete}*.md")]
@click.command()
@click.option('-e', '--edit', is_flag=True)
@click.option('-s', '--search', is_flag=True)
@click.argument('topic', autocompletion=_get_topics)
@click.argument('subsections', nargs=-1)
@click.version_option()
def cli(edit, search, topic, subsections):
"""
CLI entrypoint.
Args:
edit (bool): True if the topic should be edited. Will be
created if it does not exist.
search (bool): True if the topic string should be searched for.
Search will first look for filename matches, and if not found
the file contents will be searched instead.
topic (string): Name of the topic to create, update or search for.
subsections (tuple): Optional sub-sections to display. Only valid
for the (default) display action.
Returns:
Non-zero exit code on failure, otherwise correct operation
is to print output to the console.
"""
global conf
conf = config_manager.get_config()
if edit:
create_or_edit_topic(topic=topic)
elif search:
search_for_topic(topic=topic)
else:
display_topic(topic=topic, subsections=subsections)
| 6,852 |
tests/python/tg/test_buffer_access_feature_lines.py
|
QinHan-Erin/AMOS
| 22 |
2171944
|
import tvm
import tvm.te as te
import tvm.tg as tg
import numpy as np
def pprint_dict(d):
import json
print(json.dumps(d, indent=2, sort_keys=False))
| 156 |
setup.py
|
joaopalmeiro/pygments-styles
| 0 |
2171959
|
from setuptools import setup, find_packages
setup(
name = 'pygments-styles',
version = '1.0',
description = "A set of custom Pygments styles",
author = "<NAME>",
author_email='<EMAIL>',
license = 'MIT',
install_requires = ['pygments'],
packages = find_packages(),
entry_points = '''
[pygments.styles]
cv = styles.cv:CVStyle
'''
)
| 385 |
algorithms/Python/strings/rabin-karp-algorithm.py
|
akrish4/DSA-
| 1 |
2172214
|
'''
String pattern matching algorithm which performs efficiently for large text and patterns
Algorithm:
Rabin Karp works on the concept of hashing. If the substring of the given text
is same as the pattern then the corresponding hash value should also be same. Exploiting this idea
and designing a hash function which can be computed in O(m) time for both pattern and initial window
of text. The subsequent window each will require only O(1) time. And we slide the window n-m times
after the initial window. Therefore the overall complexity of calculating hash function for text is O(n-m+1)
Once the hash value matches, the underlying string is again checked with pattern for matching
Complexity:
Best case: O(n-m+1)
Worst case: O(nm)
'''
def rabin_karp(T: str, P: str, q: int ,d: int = 256) -> None :
'''
Parameters:
T: string
The string where the pattern needs to be searched
P: string
The pattern to be searched
q: int
An appropriately chosen prime number based on length of input strings
The higher the prime number, the lower the collisions and spurious hits
d: int, default value 256
Denotes the no of unique character that is used for encoding
Example:
>>> pos = rabin_karp("AAEXCRTDDEAAFT","AA",101)
Pattern found at pos: 0
Pattern found at pos: 10
'''
n = len(T) # length of text
m = len(P) # length of pattern
p=0 # Hash value of pattern
t=0 # Hash value of text
#Computing h: (h=d^m-1 mod q)
h=1
for i in range(1,m):
h = (h*d)%q
#Computing hash value of pattern and initial window (of size m) of text
for j in range(m):
p = (d*p + ord(P[j])) % q
t = (d*t + ord(T[j])) % q
found = False
pos=[] # To store positions
#Sliding window and matching
for s in range(n-m+1):
if p==t: # if hash value matches
if P == T[s:s+m]: # check for string match
pos.append(s)
if not found:
found = True
if s<n-m:
t = (d*(t-ord(T[s])*h) + ord(T[s+m])) % q # updating hash value of t for next window
if t<0:
t = t+q # To make sure t is positive integer
if not found: # If pattern not found in text
pos.append(-1)
#Printing results
if pos[0]==-1:
print("Pattern not found")
else:
for i in pos:
print(f"Pattern found at pos: {i}")
if __name__ == "__main__":
T = "AAEXCRTDDEAAFT"
P = "AA"
rabin_karp(T,P,101)
| 2,762 |
Django/todoDemo/models.py
|
Jackey-Sparrow/python-coil
| 0 |
2170645
|
from django.db import models
class BlogPost(models.Model):
title = models.CharField(max_length=150)
body = models.TextField(),
timeStamp = models.DateTimeField()
| 176 |
mods/NERO_Battle/module.py
|
gjacobrobertson/opennero-394n
| 0 |
2172243
|
import sys
import NERO.module
import NERO.constants as constants
import NeroEnvironment
import OpenNero
import common
# this value, between 0 (slowest) and 100 (fastest)
# overrides the default from NERO Training
BATTLE_DEFAULT_SPEEDUP = 80
class NeroModule(NERO.module.NeroModule):
def __init__(self):
NERO.module.NeroModule.__init__(self)
if OpenNero.getAppConfig().rendertype != 'null':
self.set_speedup(BATTLE_DEFAULT_SPEEDUP)
print 'setting speedup for on-screen battle'
def create_environment(self):
return NeroEnvironment.NeroEnvironment()
def load_team(self, location, team=constants.OBJECT_TYPE_TEAM_0):
NERO.module.NeroModule.load_team(self, location, team)
rtneat = OpenNero.get_ai('rtneat-%s' % team)
if rtneat:
rtneat.set_lifetime(sys.maxint)
rtneat.disable_evolution()
OpenNero.disable_ai() # don't run until button
def start_rtneat(self, team=constants.OBJECT_TYPE_TEAM_0):
NERO.module.NeroModule.start_rtneat(self, team)
rtneat = OpenNero.get_ai('rtneat-%s' % team)
if rtneat:
rtneat.set_lifetime(sys.maxint)
rtneat.disable_evolution()
def delMod():
NERO.module.gMod = None
def getMod():
if not NERO.module.gMod:
NERO.module.gMod = NeroModule()
return NERO.module.gMod
script_server = None
def getServer():
global script_server
if script_server is None:
script_server = common.menu_utils.GetScriptServer()
common.startScript("NERO_Battle/menu.py")
return script_server
def parseInput(strn):
if strn == "deploy" or len(strn) < 2:
return
mod = getMod()
# first word is command rest is filename
loc, val = strn.split(' ',1)
vali = 1
if strn.isupper():
vali = int(val)
if loc == "HP": mod.hpChange(vali)
if loc == "SP": mod.set_speedup(vali)
if loc == "load1": mod.load_team(val, constants.OBJECT_TYPE_TEAM_0)
if loc == "load2": mod.load_team(val, constants.OBJECT_TYPE_TEAM_1)
if loc == "rtneat":
mod.deploy('rtneat', constants.OBJECT_TYPE_TEAM_0)
mod.deploy('rtneat', constants.OBJECT_TYPE_TEAM_1)
if loc == "qlearning":
mod.deploy('qlearning', constants.OBJECT_TYPE_TEAM_0)
mod.deploy('qlearning', constants.OBJECT_TYPE_TEAM_1)
if loc == "pause": OpenNero.disable_ai()
if loc == "resume": OpenNero.enable_ai()
def ServerMain():
print "Starting mod NERO_Battle"
| 2,517 |
main.py
|
manoj2601/BitTorrent-Mechanism
| 0 |
2171924
|
#!/usr/bin/env python
import socket
import sys
import hashlib
import threading
from threading import Lock
import time
import matplotlib
matplotlib.use('Agg')
import numpy as np
import matplotlib.pyplot as plt
import otherfunc
#globally defined
host = []
path = []
tcps = []
port = 80
chunkSize = 10240 #10KB
chunks = []
i=0
totalBytes = int(sys.argv[3]) #given file size
while(i < totalBytes):
chunks.append((i, min(totalBytes-1, i+chunkSize-1)))
i += chunkSize
totalChunks = len(chunks)
totalThreads = 0
executedTotal = [0]*totalThreads
timeTaken = [0.0]*totalThreads
downloadedParts = [""]*totalChunks
isVisited = [False]*totalChunks
def DrawPlot():
fig = plt.figure()
plt.title(f"Relation in Time and total downloaded chunks by all threads")
plt.xlabel("downloaded chunks")
plt.ylabel("Time taken (in sec)")
for i in range(0, totalThreads):
X = []
for j in range(0, len(timeTaken[i])):
X.append(len(X)+1)
plt.plot(X, timeTaken[i], label=f"thread-{i}")
plt.legend()
plt.savefig(f"myPlot.png")
plt.close()
def getHost(threadID):
h = host[0]
p = path[0]
tcps[0]-=1
if(tcps[0] ==0):
host.pop(0)
path.pop(0)
tcps.pop(0)
return h, p
class myThread (threading.Thread):
def __init__(self, threadID, name, hostID):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.hostID = hostID
def run(self):
print("Starting " + self.name)
downloadData(self.name, self.threadID, self.hostID)
print("Exiting " + self.name)
def downloadData(threadName, threadID, hostID):
timetaken = []
chunksDownloaded = []
i = threadID
cnt = 0
host1 = hostID[0]
path1 = hostID[1]
print(f"establishing a new tcp connection for {threadName}")
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True:
try:
print(f"hand-shaking the tcp connection {threadName}")
clientSocket.connect((host1, port))
break
except:
print(f"Unable to hand-shake, retrying {threadName}")
sTime = time.clock()
while(i<totalChunks):
currChunk = chunks[i]
command = f"GET {path1} HTTP/1.1\r\nHost:{host1}\r\nConnection:keep-alive\r\nRange: bytes={currChunk[0]}-{currChunk[1]}\r\n\r\n"
clientSocket.sendall(command.encode())
count = 0
start = False
prev = ['a', 'a', 'a', 'a']
j=0
string = ""
header = ""
success = True
while count < currChunk[1]-currChunk[0]+1:
recev = True
while True:
try:
data = clientSocket.recv(1)
break
except:
recev = False
break
j=j+1
if not data or not recev:
print(f"Data not received in {threadName}")
success = False
recev = True
break
if(start):
string += data.decode()
count = count+1
continue
header += data.decode()
otherfunc.updatLast4char(prev, data.decode())
start = otherfunc.isHeaderDone(prev)
if(not success): #internet connection closed
clientSocket.close()
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True:
try:
clientSocket.connect((host1, port))
break
except:
print(f"Unable to rehand-shake, retrying {threadName}")
continue
cnt+=1
executedTotal[threadID]+=1
isVisited[i] = True
downloadedParts[i] = string
print("downloaded chunk: ", i)
i+=totalThreads
chunksDownloaded.append(cnt)
timetaken.append(time.clock()-sTime)
# when max limit of requests for a tcp connection reached
if(header.find('Connection: close') != -1):
clientSocket.close()
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True:
try:
clientSocket.connect((host1, port))
break
except:
print(f"Unable to rehand-shake, retrying {threadName}")
timeTaken[threadID] = timetaken
clientSocket.close()
def initialization():
global executedTotal
global timeTaken
global downloadedParts
global isVisited
executedTotal = [0]*totalThreads
timeTaken = [None]*totalThreads
for i in range(0, totalChunks):
downloadedParts[i] = "" #initialization
isVisited = [False]*totalChunks
def DownloadFile():
initialization()
allthreads = []
for i in range(0, totalThreads):
h,p = getHost(i)
thread = myThread(i, f"Thread-{i}", (h,p))
allthreads.append(thread)
for i in range(0, totalThreads):
allthreads[i].start()
for t in allthreads:
t.join()
print("Saving file")
filename = sys.argv[2]
file1 = open(filename, "w")
for i in range(0,totalChunks):
file1.write(downloadedParts[i])
file1.close()
print("total number of chunks executed by each Thread:")
for i in range(0, totalThreads):
print(f"thread-{i} ", executedTotal[i])
otherfunc.checkmd5sum(filename)
print("File downloaded")
def ReadInput():
input = open(sys.argv[1], "r")
i=1
line = input.readline()
print(line)
global totalThreads
totalThreads=0
while line != "":
host1, path1, totalThreads1 = otherfunc.splitLine(line)
global host
global path
global tcps
host.append(host1)
path.append(path1)
tcps.append(totalThreads1)
totalThreads += totalThreads1
line = input.readline()
DownloadFile();
ReadInput()
DrawPlot()
| 5,073 |
alfastaff_shedule/migrations/0004_auto_20201119_1407.py
|
spanickroon/Alfa-Staff
| 1 |
2171825
|
# Generated by Django 3.0.7 on 2020-11-19 11:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('alfastaff_shedule', '0003_scheduleforoneday_holiday'),
]
operations = [
migrations.AddField(
model_name='scheduleforoneday',
name='day_off',
field=models.BooleanField(blank=True, null=True, verbose_name='Выходной'),
),
migrations.AlterField(
model_name='scheduleforoneday',
name='month',
field=models.PositiveSmallIntegerField(blank=True, choices=[(1, 'Jun'), (2, 'Feb'), (3, 'Mar'), (4, 'Apr'), (5, 'May'), (6, 'Jun'), (7, 'Jul'), (8, 'Aug'), (9, 'Sep'), (10, 'Oct'), (11, 'Nov'), (12, 'Dec')], null=True, verbose_name='Месяц'),
),
]
| 815 |
bbcode/bbtags/smilies.py
|
unoti/django-bbcode
| 0 |
2171761
|
from bbcode import *
from bbcode import settings
import re
class Smilies(SelfClosingTagNode):
open_pattern = re.compile(':(?P<name>[a-zA-Z-]+):')
def parse(self):
name = self.match.groupdict()['name']
return '<img src="%s%s.gif" alt="%s" />' % (
settings.SMILEY_MEDIA_URL, name, name)
class AlternativeSmilie(SelfClosingTagNode):
def __init__(self, *args, **kwargs):
if not hasattr(self, 'alias'):
self.alias = self.__class__.__name__.lower()
SelfClosingTagNode.__init__(self, *args, **kwargs)
def parse(self):
alias = self.match.group()
return '<img src="%s%s.gif" alt="%s" />' % (
settings.SMILEY_MEDIA_URL, self.alias, alias)
class LOL(AlternativeSmilie):
# :D, :-D, :-d, :d
open_pattern = re.compile(':-?(D|d)')
class Smilie(AlternativeSmilie):
# :), :-)
open_pattern = re.compile(':-?\)')
class Wink(AlternativeSmilie):
# ;), ;-), ;-D, ;D, ;d, ;-d
open_pattern = re.compile(';-?(\)|d|D)')
class Razz(AlternativeSmilie):
# :P, :-P, :p, :-p
open_pattern = re.compile(':-?(P|p)')
class Eek(AlternativeSmilie):
# o_O....
open_pattern = re.compile('(o|O|0)_(o|O|0)')
class Sad(AlternativeSmilie):
# :-(, :(
open_pattern = re.compile(':-?\(')
class Crying(AlternativeSmilie):
# ;_;, :'(, :'-(
open_pattern = re.compile("(;_;|:'-?\()")
class Yell(AlternativeSmilie):
# ^.^
open_pattern = re.compile('^\.^')
class Grin(AlternativeSmilie):
# xD, XD, *g*
open_pattern = re.compile('(xD|XD|\*g\*)')
class Neutral(AlternativeSmilie):
# :-|, :|
open_pattern = re.compile('(:-?\|)')
register(Smilies)
register(LOL)
register(Smilie)
register(Wink)
register(Razz)
register(Eek)
register(Sad)
register(Crying)
register(Yell)
register(Grin)
register(Neutral)
| 1,917 |
pixelsToStrokesView.py
|
rohun-tripati/pythonRepo
| 1 |
2170723
|
# This file is only python 3 compatible
import glob
import os
import random
import matplotlib
matplotlib.use('Agg')
import matplotlib.lines as mlines
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import numpy as np
from os.path import join
import global_constants
def add_arrow_to_line2D(
axes, line, arrow_locs=[0.3, 0.7],
arrowstyle='-|>', arrowsize=3, transform=None):
"""
Add arrows to a matplotlib.lines.Line2D at selected locations.
Parameters:
-----------
axes:
line: list of 1 Line2D obbject as returned by plot command
arrow_locs: list of locations where to insert arrows, % of total length
arrowstyle: style of the arrow
arrowsize: size of the arrow
transform: a matplotlib transform instance, default to data coordinates
Returns:
--------
arrows: list of arrows
"""
if (not (isinstance(line, list)) or not (isinstance(line[0],
mlines.Line2D))):
raise ValueError("expected a matplotlib.lines.Line2D object")
x, y = line[0].get_xdata(), line[0].get_ydata()
arrow_kw = dict(arrowstyle=arrowstyle, mutation_scale=10 * arrowsize)
color = line[0].get_color()
use_multicolor_lines = isinstance(color, np.ndarray)
if use_multicolor_lines:
raise NotImplementedError("multicolor lines not supported")
else:
arrow_kw['color'] = color
linewidth = line[0].get_linewidth()
if isinstance(linewidth, np.ndarray):
raise NotImplementedError("multiwidth lines not supported")
else:
arrow_kw['linewidth'] = linewidth
if transform is None:
transform = axes.transData
arrows = []
for loc in arrow_locs:
s = np.cumsum(np.sqrt(np.diff(x) ** 2 + np.diff(y) ** 2))
n = np.searchsorted(s, s[-1] * loc)
arrow_tail = (x[n], y[n])
arrow_head = (np.mean(x[n:n + 2]), np.mean(y[n:n + 2]))
p = mpatches.FancyArrowPatch(
arrow_tail, arrow_head, transform=transform,
**arrow_kw)
axes.add_patch(p)
arrows.append(p)
return arrows
def arrow_view(strokepath, jump_points, arrow_size, output_path):
strokefile = open(strokepath, "r")
first = ["r", "g", "b"]
second = ["^", "--", "s", "o"]
x = []
y = []
fig, ax = plt.subplots(1, 1)
for line in strokefile.readlines():
line = line.strip()
if line == ".PEN_DOWN" or line == ".PEN_UP":
# change colour
rand = random.random() % 12
last = first[int(rand / 4)] + second[int(rand) % 4]
jumppoints = jump_points
if len(x) > 1:
if len(x) > jumppoints:
x = [x[index] for index in range(0, len(x), jumppoints)]
y = [y[index] for index in range(0, len(y), jumppoints)]
line = ax.plot(x, y, 'k-')
add_arrow_to_line2D(ax, line, arrow_locs=np.linspace(0., 1., 200), arrowstyle='->', arrowsize=arrow_size)
x = []
y = []
continue
else:
coor = line.split()
x.append(int(coor[0]))
y.append(int(coor[1]))
export_to_image(strokepath, "_arrow_" + str(jump_points) + "_" + str(arrow_size), fig, output_path)
def color_view(stroke_path, output_path):
stroke_data = open(stroke_path, "r").readlines()
first = ["r", "g", "b", "c", "k"]
second = ["^", "--", "s", "o", "+", "*", "d"]
for index, line_style in enumerate(second):
fig = plt.figure()
ax = fig.add_subplot(111)
x = []
y = []
for line in stroke_data:
line = line.strip()
if line == ".PEN_DOWN" or line == ".PEN_UP":
rand = int((random.random() * 100) % len(first))
last = first[rand] + line_style
if len(x) > 1:
ax.plot(x, y, last)
x = []
y = []
continue
else:
coor = line.split()
x.append(int(coor[0]))
y.append(int(coor[1]))
export_to_image(stroke_path, "_variation_" + str(index), fig, output_path)
def normal_view(stroke_path, output_path):
stroke_data = open(stroke_path, "r").readlines()
x = []
y = []
min_distance, min_x, min_y, selection_folder = 10e10, -1, -1, "correct"
for line in stroke_data:
line = line.strip()
if line == ".PEN_DOWN" or line == ".PEN_UP":
if len(x) > 1:
plt.plot(x, y, "b-")
if x[0] * x[0] + y[0] * y[0] < min_distance:
min_distance, min_x, min_y, selection_folder = x[0] * x[0] + y[0] * y[0], x[0], y[0], "correct"
if len(x) > 2 and x[-1] * x[-1] + y[-1] * y[-1] < min_distance:
min_distance, min_x, min_y, selection_folder = x[-1] * x[-1] + y[-1] * y[-1], x[-1], y[-1], "wrong"
x = []
y = []
continue
else:
coor = line.split()
x.append(int(float(coor[0])))
y.append(int(float(coor[1])))
export_to_image(stroke_path, "_variation_normal", plt, join(output_path, selection_folder))
plt.clf()
def export_to_image(stroke_path, tag, fig, output_path):
# Split by whatever is the system path delimiter
directory, file_name = os.path.split(stroke_path)
fig.savefig(join(output_path, file_name.rstrip(".tif.txt") + tag + ".png"))
if __name__ == '__main__':
output_path = "revision_data/stroke_to_images/"
# image_path_list = [{"path" : global_constants.offline_word_ban_data_set, "filter" : "Image1."}]
# image_path_list.append({"path" : global_constants.offline_word_eng_data_set, "filter" : "file8_24_3."})
# image_path_list.append({"path" : global_constants.offline_word_hin_data_set, "filter" : "file0_0_110."})
image_path_list = [{"path" : global_constants.online_char_hin_data, "filter": "file", "output": "char_hin"},
{"path" : global_constants.online_char_eng_data, "filter": "img", "output": "char_eng"}]
number_to_output = 1000
for image_dictionary in image_path_list:
image_files = glob.glob(join(image_dictionary["path"], "**", "*" + image_dictionary["filter"] + "*"), recursive=True)
if len(image_files) != 0:
os.makedirs(join(output_path, image_dictionary['output'], "correct"), exist_ok=True)
os.makedirs(join(output_path, image_dictionary['output'], "wrong"), exist_ok=True)
sorted_image_files = sorted(image_files)
random.seed(0)
random.shuffle(sorted_image_files)
for index, input_image in enumerate(sorted_image_files):
if index%100 ==0:
print(image_dictionary["output"], index, number_to_output)
normal_view(input_image, join(output_path, image_dictionary['output']))
# arrow_view(input_image, jump_points=5, arrow_size=2, output_path)
# color_view(input_image, output_path)
if index >= number_to_output:
break
| 7,193 |
instantiate_laws.py
|
dominique-unruh/registers
| 2 |
2171863
|
#!/usr/bin/python3
import glob
import os
import re
import sys
from hashlib import sha1
from stat import S_IREAD, S_IRGRP, S_IROTH
from typing import Union, Collection, Match, Dict, Optional, Tuple, Any, Set
had_errors = False
source_files: set[str] = set()
generated_files: set[str] = set()
def multisubst(mappings: Collection[(Union[re.Pattern, str])], content: str) -> str:
replacements = []
patterns = []
i = 0
for pat, repl in mappings:
if isinstance(pat, str):
pat_str = re.escape(pat)
else:
pat_str = pat.pattern
replacements.append(repl)
patterns.append(f"(?P<GROUP_{i}>\\b(?:{pat_str})\\b)")
i += 1
pattern = re.compile("|".join(patterns))
def repl_func(m: Match):
# print(m)
for name, text in m.groupdict().items():
if text is None:
continue
if text.startswith("GROUP_"):
continue
idx = int(name[6:])
# print(name, idx)
return replacements[idx]
assert False
return pattern.sub(repl_func, content)
def write_to_file(file, content):
global generated_files
generated_files.add(file)
try:
with open(file, 'rt') as f:
old_content = f.read()
if content == old_content:
print("(Nothing changed, not writing.)")
return
os.remove(file)
except FileNotFoundError: pass
with open(file, 'wt') as f:
f.write(content)
os.chmod(file, S_IREAD | S_IRGRP | S_IROTH)
def rewrite_laws(outputfile: str, template: str, substitutions: Dict[str, str]):
global source_files
print(f"Rewriting {template} -> {outputfile}")
source_files.add(template)
with open(template, 'rt') as f:
content = f.read()
new_content = multisubst(substitutions.items(), content)
new_content = f"""(*
* This is an autogenerated file. Do not edit.
* The original is {template}. It was converted using instantiate_laws.py.
*)
""" + new_content
write_to_file(outputfile, new_content)
def read_instantiation_header(file: str) -> Optional[Tuple[str, Optional[str], Dict[str, str]]]:
global source_files
global had_errors
source_files.add(file)
with open(file, 'rt') as f:
content = f.read()
assert file.startswith("Axioms_")
basename = file[len("Axioms_"):]
assert basename.endswith(".thy")
basename = basename[:-len(".thy")]
m = re.compile(r"""\(\* AXIOM INSTANTIATION [^\n]*\n(.*?)\*\)""", re.DOTALL).search(content)
if m is None:
print(f"*** Could not find AXIOM INSTANTIATION header in {file}.")
had_errors = True
lines = []
else:
lines = m.group(1).splitlines()
substitutions = {
'theory Laws': f'theory Laws_{basename}',
'imports Laws': f'imports Laws_{basename}',
'theory Laws_Complement': f'theory Laws_Complement_{basename}',
'Axioms': f'Axioms_{basename}',
'Axioms_Complement': f'Axioms_Complement_{basename}'
}
# print(substitutions)
for line in lines:
if line.strip() == "":
continue
if re.match(r"^\s*#", line):
continue
m = re.match(r"^\s*(.+?)\s+\\<rightarrow>\s+(.+?)\s*$", line)
if m is None:
print(f"*** Invalid AXIOM INSTANTIATION line in {file}: {line}")
had_errors = True
continue
key = m.group(1)
val = m.group(2)
if key in substitutions:
print(f"*** Repeated AXIOM INSTANTIATION key in {file}: {line}")
had_errors = True
substitutions[key] = val
# print(substitutions)
laws_complement = f"Laws_Complement_{basename}.thy" if os.path.exists(f"Axioms_Complement_{basename}.thy") else None
return (f"Laws_{basename}.thy", laws_complement, substitutions)
def rewrite_all():
for f in glob.glob("Axioms_*.thy"):
if f.startswith("Axioms_Complement"): continue
lawfile, lawfile_complement, substitutions = read_instantiation_header(f)
rewrite_laws(lawfile, "Laws.thy", substitutions)
if lawfile_complement is not None:
rewrite_laws(lawfile_complement, "Laws_Complement.thy", substitutions)
def create_check_theory():
global source_files, generated_files
print("Creating Check_Autogenerated_Files.thy")
hash_checks = []
for kind, files in (("Source", source_files), ("Generated", generated_files)):
for file in sorted(files):
with open(file, 'rb') as f:
hash = sha1(f.read()).hexdigest()
hash_checks.append(f' check "{kind}" "{file}" "{hash}"')
hash_checks_concat = ";\n".join(hash_checks)
content = rf"""(*
* This is an autogenerated file. Do not edit.
* It was created using instantiate_laws.py.
* It checks whether the other autogenerated files are up-to-date.
*)
theory Check_Autogenerated_Files
(* These imports are not actually needed, but in jEdit, they will conveniently trigger a re-execution of the checking code below upon changes. *)
imports Laws_Classical Laws_Quantum Laws_Complement_Quantum
begin
ML \<open>
let
fun check kind file expected = let
val content = File.read (Path.append (Resources.master_directory \<^theory>) (Path.basic file))
val hash = SHA1.digest content |> SHA1.rep
in
if hash = expected then () else
error (kind ^ " file " ^ file ^ " has changed.\nPlease run \"python3 instantiate_laws.py\" to recreated autogenerated files.\nExpected SHA1 hash " ^ expected ^ ", got " ^ hash)
end
in
{hash_checks_concat}
end
\<close>
end
"""
write_to_file("Check_Autogenerated_Files.thy", content)
rewrite_all()
create_check_theory()
if had_errors:
sys.exit(1)
| 5,785 |
oh/migrations/versions/11e366ca2e4f_support_default_ticket_description.py
|
akshitdewan/cs61a-apps
| 5 |
2172108
|
"""support-default-ticket-description
Revision ID: 11e366ca2e4f
Revises: <KEY>
Create Date: 2021-02-13 05:20:07.890020
"""
# revision identifiers, used by Alembic.
revision = "11e366ca2e4f"
down_revision = "<KEY>"
from sqlalchemy import orm
from alembic import op
import sqlalchemy as sa
import oh_queue.models
from oh_queue.models import *
def upgrade():
# Get alembic DB bind
connection = op.get_bind()
session = orm.Session(bind=connection)
for course in session.query(ConfigEntry.course).distinct():
session.add(
ConfigEntry(
key="default_description",
value="",
public=True,
course=course[0],
)
)
session.commit()
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
| 880 |
apps/users/task.py
|
Curiou/classify_email
| 0 |
2171489
|
# !/usr/bin/python
# -*- coding: utf-8 -*-
"""
Author: <NAME>
Contact: <EMAIL> or <EMAIL>
File: task.py
Time: 2020/8/23 18:07
File Intro:
"""
import time
from celery import shared_task
from celery import Celery, platforms
from utils.send_msm import send_email
platforms.C_FORCE_ROOT = True # 加上这一行
from django.core.mail import send_mail
@shared_task
def add(a, b):
return a + b
@shared_task
def async_send_mail(*args, **kwargs):
send_email(*args, **kwargs)
return args
| 511 |
vertnet/parsers/base.py
|
rafelafrance/traiter_vertnet
| 0 |
2171054
|
"""Common logic for parsing trait notations."""
from typing import Callable, List
from traiter.old.parser import Parser, RulesInput
from vertnet.pylib.trait import Trait
def fix_up_nop(trait, _): # pylint: disable=unused-argument
"""Fix problematic parses."""
return trait
class Base(Parser): # pylint: disable=too-few-public-methods
"""Shared lexer logic."""
def __init__(
self,
rules: RulesInput,
name: str = "parser",
fix_up: Callable[[Trait, str], Trait] = None,
) -> None:
"""Build the trait parser."""
super().__init__(name=name, rules=rules)
self.fix_up = fix_up if fix_up else fix_up_nop
# pylint: disable=arguments-differ
def parse(self, text: str, field: str = None) -> List[Trait]:
"""Find the traits in the text."""
traits = []
tokens = super().parse(text)
for token in tokens:
trait_list = token.action(token)
# The action function can reject the token
if not trait_list:
continue
# Some parses represent multiple traits, fix them all up
if not isinstance(trait_list, list):
trait_list = [trait_list]
# Add the traits after any fix up.
for trait in trait_list:
trait = self.fix_up(trait, text)
if trait: # The parse may fail during fix up
if field:
trait.field = field
traits.append(trait)
# from pprint import pp
# pp(traits)
return traits
def convert(token):
"""Convert parsed tokens into a result."""
return Trait(value=token.group["value"].lower(), start=token.start, end=token.end)
| 1,782 |
tool/Global.py
|
GaoChrishao/Transformer_MT
| 2 |
2171366
|
# *_*coding:utf-8 *_*
default_batch_size = 10 # 训练批次大小。
epochs = 20 # 训练迭代轮次。
# 是否使用GPU
use_gpu = True
gpu_index = 0 # 创建摸摸胸训练时,使用的GPU序号
map_gpu_index = 0 # 载入模型时,使用的GPU序号(如果设备没变,则与gpu_index一致)
# encoder和decoder的层数
num_layers = 3
# 多头注意力中的头数
num_heads = 4
# 字嵌入和位置嵌入的维度
d_model = 256
embedding_dim = d_model
# 全连接
d_ff = d_model * 4
# 特殊字符
char_space = ' '
char_start = '<start>'
char_end = '<end>'
char_unknown = '<?>'
word_end = '<e>' # bpe标志
# 数据集
corpus_encoder_path = './data/de.txt'
corpus_decoder_path = './data/en.txt'
# bpe切分后的数据集
combined_vocab_path = './data/2k/de2en_2k_vocab.txt'
# bpe字典
encoder_bpe_dic_path = './data/2k/de_2000.txt'
decoder_bpe_dic_path = './data/2k/en_2000.txt'
# 重新切分并预处理好的数据集
train_file_path = "./data/2k/train_2k.txt"
valid_file_path = "./data/2k/valid_2k.txt"
test_file_path = "./data/2k/test_2k.txt"
# 训练集字典信息
data_path_vocab_desc = './data/2k/corps_2k_desc.txt'
# 保存模型名称
modelName = "de2en_2k"
# 模型存储路径
def modelPath(epoch):
return './save/' + modelName + '_%04d' % (epoch + 1) + '.pt'
# 打印训练进度
def printProgress(epoch, prog, batch_no, batch_all, batch_size, loss, accu, lr):
print('\rEpoch:%04d prog:%.4f%% batch:%d/%d batch_size:%d mean_loss=%.6f mean_accu=%.2f%% lr=%.6f' % (
epoch + 1, prog, batch_no, batch_all, batch_size, loss, accu, lr), end="")
# 输出参数到文件
def writeParametersToFile(n_layers, n_heads, d_model, d_ff, batch_size, encoder_len, decoder_len):
progress = 'n_layers' + '%d' % (n_layers) + \
' n_heads:%d' % (n_heads) + \
' d_model:%d' % (d_model) + \
' d_ff:%d' % (d_ff) + \
' batch_size:%d' % (batch_size) + \
' encoder_len:%d' % (encoder_len) + \
' decoder_len:%d' % (decoder_len) + "\n"
with open('./save/' + modelName + '.txt', 'a') as f:
f.write('\n')
f.write(progress)
# 输出训练进度到文件
def writeProgreeToFile(epoch, batch_all, loss, train_accu, valid_accu, lr):
progress = 'Epoch:' + '%04d' % (epoch + 1) + \
' batch:%d' % (batch_all) + \
' loss=' + '{:.6f}'.format(loss) + \
' train_accu=' + '{:.6f}'.format(train_accu) + \
' valid_accu=' + '{:.6f}'.format(valid_accu) + \
' lr=' + '{:.6f}\n'.format(lr)
with open('./save/' + modelName + '.txt', 'a') as f:
f.write(progress)
| 2,393 |
leetcode/medium/Intersection_of_Two_Linked_Lists.py
|
shhuan/algorithms
| 0 |
2170627
|
# -*- coding: utf-8 -*-
"""
created by huash at 2015-04-12 09:37
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.
"""
__author__ = 'huash'
import sys
import os
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param two ListNodes
# @return the intersected ListNode
def getIntersectionNode(self, headA, headB):
if not headA or not headB:
return None
lenA = 1
ha = headA
while ha.next:
lenA += 1
ha = ha.next
lenB = 1
hb = headB
while hb.next:
lenB += 1
hb = hb.next
ha = headA
hb = headB
if lenA > lenB:
for k in range(lenA-lenB):
ha = ha.next
elif lenA < lenB:
for k in range(lenB-lenA):
hb = hb.next
while ha and hb and ha.val != hb.val:
ha = ha.next
hb = hb.next
if ha:
return ha
return None
s = Solution()
l1 = ListNode('a1')
l1.next = ListNode('a2')
nn = l1.next
nn.next = ListNode('c1')
nn = nn.next
nn.next = ListNode('c2')
nn = nn.next
nn.next = ListNode('c3')
l2 = ListNode('b1')
l2.next = ListNode('b2')
nn = l2.next
nn.next = ListNode('b3')
nn = nn.next
nn.next = ListNode('c1')
nn = nn.next
nn.next = ListNode('c2')
nn = nn.next
nn.next = ListNode('c3')
print(s.getIntersectionNode(l1, l2))
| 2,040 |
puls/models/systems.py
|
za-creature/puls
| 1 |
2171151
|
# coding=utf-8
from __future__ import absolute_import, unicode_literals, division
from puls.models.components import Component
from puls.models.classes import Class, ClassField
from puls.models.targets import Target
from puls import app
import mongoengine as mge
import flask_wtf
import datetime
import wtforms as wtf
class System(app.db.Document):
# basic meta
target = mge.ReferenceField(Target, required=True)
budget = mge.FloatField(required=True)
currency = mge.StringField(required=True)
price = mge.FloatField(required=True)
performance = mge.FloatField(required=True)
components = mge.ListField(mge.ReferenceField(Component))
created = mge.DateTimeField(default=datetime.datetime.now)
| 729 |
Python/zzz_training_challenge/Python_Challenge/solutions/ch06_arrays/solutions/ex13_minesweeper.py
|
Kreijeck/learning
| 0 |
2171718
|
# Beispielprogramm für das Buch "Python Challenge"
#
# Copyright 2020 by <NAME>
import random
from ch06_arrays.intro.intro import print_array, get_dimension
from ch06_arrays.intro.intro_directions_example import Direction
def place_bombs_randomly(width, height, probability):
bombs = [[False for x in range(width + 2)] for y in range(height + 2)]
for y in range(1, len(bombs) - 1):
for x in range(1, len(bombs[0]) - 1):
bombs[y][x] = random.random() < probability
return bombs
def calc_bomb_count(bombs):
max_y, max_x = get_dimension(bombs)
bomb_count = [[0 for x in range(max_x)] for y in range(max_y)]
for y in range(1, max_y - 1):
for x in range(1, max_x - 1):
if not bombs[y][x]:
for current_dir in Direction:
dx, dy = current_dir.to_dx_dy()
if bombs[y + dy][x + dx]:
bomb_count[y][x] += 1
else:
bomb_count[y][x] = 9
return bomb_count
def print_board(bombs, bomb_symbol, solution):
for y in range(1, len(bombs) - 1):
for x in range(1, len(bombs[0]) - 1):
if bombs[y][x]:
print(bomb_symbol, end=" ")
elif solution is not None and len(solution) != 0:
print(solution[y][x], end=" ")
else:
print(".", end=" ")
print()
print()
def main():
bombs = place_bombs_randomly(10, 5, 0.5)
print_board(bombs, "B", None)
bomb_counts = calc_bomb_count(bombs)
print_board(bombs, "B", bomb_counts)
if __name__ == "__main__":
main()
| 1,640 |
audacity_scripting/__init__.py
|
adthomas811/audacity-python-scripting
| 1 |
2170674
|
from datetime import datetime
import logging
from os import mkdir
from os.path import abspath, dirname, isdir, isfile, join
from time import sleep
package_path = dirname(abspath(__file__))
log_dir_path = join(package_path, '_logs')
LOGGER_NAME = __name__
if not isdir(log_dir_path):
mkdir(log_dir_path)
current_time = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
log_file = join(log_dir_path, current_time + '.log')
if isfile(log_file):
sleep(1)
current_time = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
log_file = join(log_dir_path, current_time + '.log')
# Create the Logger
logger = logging.getLogger(LOGGER_NAME)
logger.setLevel(logging.DEBUG)
# Create the Handler for logging data to a file
logger_handler = logging.FileHandler(log_file)
logger_handler.setLevel(logging.DEBUG)
# Create a Formatter for formatting the log messages
logger_formatter = logging.Formatter('%(asctime)s - %(levelname)-8s - '
'%(message)s')
# Add the Formatter to the Handler
logger_handler.setFormatter(logger_formatter)
# Add the Handler to the Logger
logger.addHandler(logger_handler)
| 1,134 |
listing_app/urls.py
|
SenJames/Car-Listing
| 0 |
2171582
|
'''
This is the views that links us to the main views.
'''
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
from . import views
app_name = 'listing_app'
urlpatterns= [
url(r"^home/", views.index, name='home'),
url(r"^list/$", views.car_view, name='cars_list'),
url(r"^grid/$", views.car_grid, name='cars_grid'),
url(r"^list-page/$", views.car_page, name='cars_page'),
url(r"^grid-page/$", views.car_page_grid, name='cars_page_grid'),
url(r"^list-price/$", views.car_price_list, name='cars_price_list'),
url(r"^grid-price/$", views.car_price_grid, name='cars_price_grid'),
path('car_detail/<int:car_id>/', views.car_detailed, name='detail'),
# path('car_detail/review/<int:car_id>/', views.review, name='detail')
path("edit/<int:user_id>/", views.edit_dash, name="edit"),
path("order/<int:user_id>", views.createOrder, name="create_order"),
path("update_order/<str:pk>", views.updateOrder, name="update_order"),
path("delete_order/<int:pk>", views.deleteOrder, name="delete_order"),
path("order-page/<int:user_id>", views.orderPage, name="order_page"),
path("register/", views.register, name="register"),
path("dealer_register/", views.registerDealers, name="dealer_reg"),
path("login/", views.login, name="login"),
path("logout/", views.logout, name="logout"),
path("contact/", views.contact_us, name="contact-us"),
path("about-us/", views.about_us, name="about-us"),
path("compare/", views.compareCar, name="compare"),
# path("blog/", views.blog, name="blog"),
path("blog-detail/", views.blog_detail, name="blog-detail"),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| 1,781 |
grafana/common/dashboards/aggregated/qtype_vs_tld.py
|
MikeAT/visualizer
| 6 |
2171987
|
# Copyright 2021 Internet Corporation for Assigned Names and Numbers.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at https://mozilla.org/MPL/2.0/.
#
# Developed by Sinodun IT (sinodun.com)
#
# Aggregation QTYPE vs TLD plots
import textwrap
import grafanalib.core as GCore
import grafanacommon as GCommon
def dash(myuid, agginfo, nodesel, **kwargs):
return GCommon.Dashboard(
title = "QTYPE vs TLD",
tags = [
agginfo['graph_tag']
],
uid = myuid,
rows = [
GCore.Row(
height = GCore.Pixels(GCore.DEFAULT_ROW_HEIGHT.num * 2),
panels = [
GCommon.BarChart(
title = 'QTYPE for most popular Undelegated TLDs queried',
orientation = GCommon.BAR_CHART_ORIENTATION_HORIZONTAL,
layout = GCommon.BarChartLayout(
barmode = GCommon.BAR_CHART_LAYOUT_MODE_STACK,
showlegend = True,
xaxis = GCommon.BarChartAxis(
title = 'Queries per second',
),
yaxis = GCommon.BarChartAxis(
autotick = False,
axtype = GCommon.BAR_CHART_AXIS_TYPE_CATEGORY,
tickmargin = 90,
),
),
autotrace = True,
targets = [
GCommon.ClickHouseTableTarget(
database = agginfo['database'],
table = 'QtypeUndelegatedTld' + agginfo['table_suffix'],
round = agginfo['round'],
query = textwrap.dedent("""\
SELECT
notEmpty(QType) ? QType : concat('TYPE', toString(QueryType)) AS DisplayQType,
sum(Cnt) / ($to - $from) AS TldCnt,
empty(Tld) ? '"."' : (isValidUTF8(Tld) ? Tld : base64Encode(Tld)) AS DisplayTld
FROM
(
SELECT
Tld,
QueryType,
sum(Cnt) AS Cnt,
any(TotalCnt) AS TotalCnt
FROM
(
SELECT
Tld,
sum(toUInt64(Count)) AS TotalCnt
FROM $table
WHERE
$timeFilter
AND NodeID IN {nodesel}
GROUP BY Tld
ORDER BY TotalCnt DESC, Tld ASC
LIMIT 40
) AS TldCount
ALL LEFT JOIN
(
SELECT
Tld,
QueryType,
sum(toUInt64(Count)) AS Cnt
FROM $table
WHERE
$timeFilter
AND NodeID IN {nodesel}
GROUP BY
Tld,
QueryType
UNION ALL
(
SELECT
Tld,
QueryType,
CAST(0 AS UInt64) AS Cnt
FROM
(
SELECT
0 AS Zero,
Tld
FROM $table
WHERE
$timeFilter
AND NodeID IN {nodesel}
GROUP BY Tld
) AS ZeroTld
ALL LEFT JOIN
(
SELECT
0 AS Zero,
QueryType
FROM $table
WHERE
$timeFilter
AND NodeID IN {nodesel}
GROUP BY QueryType
) AS ZeroTYpe USING Zero
)
) AS TldQTypeCounts USING Tld
GROUP BY
Tld,
QueryType
) AS TldQTypeCountsTotal
ALL INNER JOIN
(
SELECT
value_name AS QType,
toUInt16(value) AS QueryType
FROM {nodeinfo_database}.iana_text
WHERE registry_name = 'QTYPE'
) AS QTypeName USING QueryType
GROUP BY
Tld,
QueryType,
QType
ORDER BY
sum(TotalCnt) ASC,
DisplayQType,
Tld DESC""".format(
nodesel=nodesel,
nodeinfo_database=agginfo['nodeinfo_database'])),
refId = 'A'
)
],
),
],
),
]
)
| 7,320 |
lib/Pentest.py
|
PinkRoccade-Local-Government-OSS/PinkWave
| 1 |
2170787
|
#!/usr/bin/python
"""
Create a Pentest object to start defined exploit(s) and automaticly log found exploits and tests per host.
"""
import time,colors,sys
from os.path import dirname
from Report import Report
from Macro import Macro
from PyExploit import PyExploit
from ShellParse import ShellParse
# Import PinkWave extensions
appDir = dirname(dirname(__file__ ))
sys.path.append(appDir)
from extensions.Util import Util,vdkException
class Pentest:
def __init__(self):
self.browser = None
# Copy from ShellParse
self.target = None
self.requestNames = []
self.request = None
self.exploits = None
self.macros = []
self.creds = []
self.ports = []
self.ssl = None
self.reportId = 0
self.wordlist = None
def parameters(self):
parameters = []
if self.request != "get":
parameters.append("--request=%s" % self.request)
if self.requestNames is not None:
parameters.append("--requestNames=:%s" % ";".join(self.requestNames))
if len(self.macros) != 0:
parameters.append("--macros=%s" % ";".join(self.macros))
if self.creds is not None:
parameters.append("--creds=%s" % ";".join(self.creds))
if self.ports is not None:
parameters.append("--ports=%s" % ";".join(self.ports))
if self.ssl != "443":
parameters.append("--ssl=%s" % self.ssl)
if self.wordlist is not None:
parameters.append("--wordlist=%s" % self.wordlist)
return "-".join(parameters)
"""
Create a Pentest object with variables
"""
def create(self, browser, shellParse):
self.browser = browser
for key,value in shellParse.propsValue().iteritems():
setattr(self,key,value)
if self.request is None:
self.request = "get"
if self.target is not None and "http://" not in self.target and "https://" not in self.target:
self.target = "http://" + self.target
if self.ssl is not None:
self.ssl = str(self.ssl)
return self
"""
Execute Pentest, save found exploits to csv
"""
def start(self):
# Allow execution of single macro
if len(self.exploits) == 0:
for m in self.macros:
ma = Macro().start(m,self.browser)
if self.target is None:
return
Util.createDir(Util.getReportDir(self.target))
pyExploit = PyExploit(self.exploits)
for m in self.macros:
ma = Macro().start(m,self.browser)
timeStart = time.time()
try:
pyExploit.start(self)
timeEnd = time.time()
print "[^] No Exploit detected..."
r = Report(pyExploit, "OK",(timeEnd-timeStart))
r.export()
except vdkException as ex:
timeEnd = time.time()
if "_potential" in str(type(ex)):
print "\033[1;91m[?] Potential Exploit detected! (%s)\033[1;m" % pyExploit.exploitPath
else:
print "\033[1;91m[!] Exploit detected! (%s)\033[1;m" % pyExploit.exploitPath
r = Report(pyExploit, ex.message,(timeEnd-timeStart))
r.export()
raise
| 3,318 |
client.py
|
ray-project/redis-replication
| 0 |
2171819
|
import redis
import random
import time
client1 = redis.StrictRedis(port=6379)
client2 = redis.StrictRedis(port=6380)
client1.execute_command("flushall")
client1.execute_command("replication.ready")
written1 = 0
written2 = 0
t = time.time()
for i in range(100000):
a = random.randint(0, 100000)
b = random.randint(0, 100000)
try:
client1.execute_command("replication.write", str(a), str(b))
written1 += 1
except:
pass
try:
client2.execute_command("replication.write", str(a), str(b))
written2 += 1
except:
pass
if i % 10 == 0:
if time.time() > t + 1.0:
t = time.time()
print("written1: {}, written2: {}".format(written1, written2))
| 745 |
locale/pot/api/core/_autosummary/pyvista-Light-positional-1.py
|
tkoyama010/pyvista-doc-translations
| 4 |
2171853
|
# Create a spotlight shining on the origin.
#
import pyvista as pv
light = pv.Light(position=(1, 1, 1))
light.positional = True
light.cone_angle = 30
| 150 |
clip/model_zoo.py
|
ttlmh/Bridge-Prompt
| 2 |
2171914
|
import os
def get_model_path(ckpt):
if os.path.isfile(ckpt):
return ckpt
else:
print('not found pretrained model in {}'.format(ckpt))
raise FileNotFoundError
| 190 |
src/proposals/management/commands/loadproposals.py
|
kaka-lin/pycon.tw
| 47 |
2171930
|
import json
from django.apps import apps
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
User = get_user_model()
class Command(BaseCommand):
help = 'Load talk proposals from data dumped by `manage.py dumpdata`.'
def add_arguments(self, parser):
parser.add_argument('filename', help='Name of file to load data from')
def handle(self, *args, filename, **options):
with open(filename) as f:
data = json.load(f)
for dataset in data:
model = apps.get_model(*dataset['model'].split('.'))
fields = dataset.pop('fields', {})
submitter = fields.pop('submitter', None)
if submitter is not None:
try:
submitter = User.objects.get(pk=submitter)
except User.DoesNotExist:
submitter = User.objects.first()
fields['submitter'] = submitter
model.objects.update_or_create(fields, pk=dataset['pk'])
| 1,032 |
src/water_management/exceptionclass.py
|
viswan29/watermanagement
| 0 |
2171101
|
"""
Exception class to raise exception
"""
class NotAllowed(Exception):
def __init__(self, m):
self.message = m
def __str__(self):
return self.message
| 181 |
test_civic_jabber_ingest/models/test_article.py
|
civic-jabber/data-ingest
| 0 |
2170470
|
import datetime
from civic_jabber_ingest.models.article import Article
MOCK_ARTICLE = {
"id": "1",
"extraction_date": datetime.datetime(2020, 6, 8),
"source_id": "4",
"source_name": "Parrot News",
"source_brand": "Parrot News",
"source_description": "A news source for parrots",
"title": "You'll never believe the size of these parrots!",
"body": "Parrts are big and parrts are tall!",
"summary": "Parrts are big and parrts are tall!",
"keywords": ["big", "parrot"],
"images": ["big_bird.jpg", "little_bird.jpg"],
"url": "https://www.birds.com/news/big-birds",
}
def test_article_loads_from_dict():
article = Article.from_dict(MOCK_ARTICLE)
assert article.to_dict() == MOCK_ARTICLE
| 743 |
cico_common.py
|
imapex/CICO
| 0 |
2172202
|
import os
meraki_api_token = os.getenv("MERAKI_API_TOKEN")
meraki_org = os.getenv("MERAKI_ORG")
spark_api_token = os.getenv("SPARK_API_TOKEN")
s3_bucket = os.getenv("S3_BUCKET")
s3_key = os.getenv("S3_ACCESS_KEY_ID")
s3_secret = os.getenv("S3_SECRET_ACCESS_KEY")
def meraki_support():
if meraki_api_token and meraki_org:
return True
else:
return False
def spark_call_support():
if spark_api_token:
return True
else:
return False
def umbrella_support():
if s3_bucket and s3_key and s3_secret:
return True
else:
return False
| 601 |
lecture.py
|
RaoulChartreuse/pycin-
| 1 |
2171896
|
import numpy as np
import matplotlib.pyplot as plt
import argparse
# l'argument parser
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", required = True,
help = "Chemin vers le fichier video")
args = ap.parse_args()
filename= args.input
#r=np.load(filename)
#Ecriture de la version c++
r=np.fromfile(filename,sep=" ")
x=np.arange(r.size)
print r,x
fig, ax = plt.subplots(figsize=(8, 4))
ax.hist(r[~np.isnan(r)],200,histtype='step')
ax.set_yscale("log", nonposy='clip')
plt.show()
| 546 |
siptrackd_twisted/attribute.py
|
sii/siptrackd
| 0 |
2171840
|
from twisted.web import xmlrpc
from twisted.internet import defer
import xmlrpclib
from siptrackdlib import attribute
import siptrackdlib.errors
from siptrackd_twisted import helpers
from siptrackd_twisted import gatherer
from siptrackd_twisted import baserpc
import siptrackd_twisted.errors
class AttributeRPC(baserpc.BaseRPC):
node_type = 'attribute'
@helpers.ValidateSession()
@defer.inlineCallbacks
def xmlrpc_add(self, session, parent_oid, name, atype, value):
"""Create a new attribute."""
parent = self.object_store.getOID(parent_oid, user = session.user)
# Binary data is converted into xmlrpclib.Binary objects. If this is
# a binary attribute, make sure we received an xmlrpclib.Binary object
# and extract the data.
if atype == 'binary':
try:
value = str(value)
except:
raise siptrackdlib.errors.SiptrackError('attribute value doesn\'t match type')
obj = parent.add(session.user, 'attribute', name, atype, value)
yield self.object_store.commit(obj)
defer.returnValue(obj.oid)
@helpers.ValidateSession()
@defer.inlineCallbacks
def xmlrpc_set_value(self, session, oid, value):
"""Set an existing attributes value."""
attribute = self.getOID(session, oid)
# Binary data is converted into xmlrpclib.Binary objects. If this is
# a binary attribute, make sure we received an xmlrpclib.Binary object
# and extract the data.
if attribute.atype == 'binary':
try:
value = str(value)
except:
raise siptrackdlib.errors.SiptrackError('attribute value doesn\'t match type')
attribute.value = value
yield self.object_store.commit(attribute)
defer.returnValue(True)
class VersionedAttributeRPC(baserpc.BaseRPC):
node_type = 'versioned attribute'
@helpers.ValidateSession()
@defer.inlineCallbacks
def xmlrpc_add(self, session, parent_oid, name, atype, max_versions, value = None):
"""Create a new versioned attribute."""
parent = self.object_store.getOID(parent_oid, user = session.user)
# Binary data is converted into xmlrpclib.Binary objects. If this is
# a binary attribute, make sure we received an xmlrpclib.Binary object
# and extract the data.
if atype == 'binary':
try:
value = value.data
except:
raise siptrackdlib.errors.SiptrackError('attribute value doesn\'t match type')
obj = parent.add(session.user, 'versioned attribute', name, atype, value, max_versions)
yield self.object_store.commit(obj)
defer.returnValue(obj.oid)
@helpers.ValidateSession()
@defer.inlineCallbacks
def xmlrpc_set_value(self, session, oid, value):
"""Set an existing attributes value."""
attribute = self.getOID(session, oid)
# Binary data is converted into xmlrpclib.Binary objects. If this is
# a binary attribute, make sure we received an xmlrpclib.Binary object
# and extract the data.
if attribute.atype == 'binary':
try:
value = value.data
except:
raise siptrackdlib.errors.SiptrackError('attribute value doesn\'t match type')
attribute.value = value
yield self.object_store.commit(attribute)
defer.returnValue(True)
@helpers.ValidateSession()
@defer.inlineCallbacks
def xmlrpc_set_max_versions(self, session, oid, max_versions):
"""Set an existing attributes value."""
attribute = self.getOID(session, oid)
attribute.max_versions = max_versions
yield self.object_store.commit(attribute)
defer.returnValue(True)
class EncryptedAttributeRPC(baserpc.BaseRPC):
node_type = 'encrypted attribute'
@helpers.ValidateSession()
@defer.inlineCallbacks
def xmlrpc_add(self, session, parent_oid, name, atype, value):
"""Create a new attribute."""
parent = self.object_store.getOID(parent_oid, user = session.user)
obj = parent.add(session.user, 'encrypted attribute', name, atype, value)
yield self.object_store.commit(obj)
defer.returnValue(obj.oid)
@helpers.ValidateSession()
@defer.inlineCallbacks
def xmlrpc_set_value(self, session, oid, value):
"""Set an existing attributes value."""
attribute = self.getOID(session, oid)
attribute.value = value
yield self.object_store.commit(attribute)
defer.returnValue(True)
def encrypted_attribute_data_extractor(node, user):
# errors.SiptrackError is raised by attribute.getPassword often when
# searching objects or listing objects with enca attributes connected
# to keys that the current user does not have access to. So default to
# showing a blank attribute.
#
# TODO: Some indication that the user lacks password key access to show
# the encrypted attribute. Or solve it in siptrackweb by simply showing
# the password key each attribute is connected to along with the blank
# attribute value.
try:
value = node.getAttribute(user)
except Exception as e:
value = ''
pass
return [node.name, node.atype, value]
def attribute_data_extractor(node, user):
value = node.value
# Binary data needs to be wrapped in xmlrpclib.Binary.
# if node.atype == 'binary':
# value = xmlrpclib.Binary(value)
return [node.name, node.atype, value]
def versioned_attribute_data_extractor(node, user):
values = node.values
# Binary data needs to be wrapped in xmlrpclib.Binary.
if node.atype == 'binary':
values = [xmlrpclib.Binary(value) for value in node.values]
return [node.name, node.atype, values, node.max_versions]
gatherer.node_data_registry.register(attribute.Attribute,
attribute_data_extractor)
gatherer.node_data_registry.register(attribute.VersionedAttribute,
versioned_attribute_data_extractor)
gatherer.node_data_registry.register(
attribute.EncryptedAttribute,
encrypted_attribute_data_extractor
)
| 6,211 |
src/boptx/algorithms/__init__.py
|
sebhoerl/boptx
| 1 |
2171796
|
from .uniform import UniformAlgorithm
from .fdsa import FDSAAlgorithm
from .spsa import SPSAAlgorithm
from .es import EvolutionarySearchAlgorithm
from .de import DifferentialEvolutionAlgorithm
from .nes import XNESAlgorithm
from .nes import ElitistXNESAlgorithm
from .nelder_mead import NelderMeadAlgorithm
from .cmaes import CMAESAlgorithm
from .sensitivity import SensitivityAlgorithm
from .opdyts import OpdytsAlgorithm
from .cmaese import CMAES1P1Algorithm
| 461 |
l1t_cli/commands/dqm/gui/start/__init__.py
|
kreczko/l1t-cli
| 0 |
2170736
|
"""
dqm gui start:
starts the offline DQM GUI on port 8060
Usage:
dqm gui start
"""
import logging
import os
import hepshell
from hepshell.interpreter import time_function
LOG = logging.getLogger(__name__)
from l1t_cli.commands.dqm.gui.setup import DQM_GUI_PATH
class Command(hepshell.Command):
def __init__(self, path=__file__, doc=__doc__):
super(Command, self).__init__(path, doc)
@time_function('dqm gui start', LOG)
def run(self, args, variables):
self.__prepare(args, variables)
commands = [
'cd {DQM_GUI_PATH}',
'source current/apps/dqmgui/128/etc/profile.d/env.sh',
'$PWD/current/config/dqmgui/manage -f dev start "I did read documentation"'
]
all_in_one = ' && '.join(commands)
all_in_one = all_in_one.format(DQM_GUI_PATH = DQM_GUI_PATH)
from hepshell.interpreter import call
code, _, stderr = call(all_in_one, logger=LOG, shell = True)
if not code == 0:
msg = 'Could not start DQM GUI: {0}'.format(stderr)
LOG.error(msg)
return False
self.__text = 'DQM GUI now available at http://localhost:8060/dqm/dev'
return True
def __can_run(self):
# if DQMOffline exists
return True
| 1,345 |
network_class.py
|
MagicGrapes/SmithChartPy
| 0 |
2171699
|
"""
Author: <NAME>
October 29, 2016
Description: Classes and functions to perform basic network abstraction and plotting
"""
from numpy import pi as pi
class network(object):
"""Class for one dimension network (i.e. a matching network)."""
element_array=[]
def __init__(self):
self.ZP2=lambda freq: 50.0 #Network termination on output
self.ZP1=lambda freq: 50.0 #Network termination on output
def compute_node_impedances(self,freq):
"""Calculate impedances at each node walking back from the output impedance, Zp2"""
Zarr=[self.ZP2(freq)]
for elem in self.element_array:
if elem.orientation==0: #series
Zarr.append(Zarr[-1]+elem.Z(freq))
elif elem.orientation==1: #shunt
Zarr.append(1.0/(1.0/Zarr[-1]+elem.Y(freq)))
#Zarr.reverse()
return Zarr
def print_net(self):
for elem in self.element_array:
print(elem.name, elem.val)
def move_element(self,n_a,n_b):
"""
Moves element to new index shifting other elements accordingly.
Simplies drag-drop action of components
"""
self.element_array.insert(n_b,self.element_array.pop(n_a))
class element(object):
"""Class for a single impedance/admittance element (i.e. capacitor, indcutor, etc.)."""
def __init__(self,*args,**kargs):
self.name=''
self.icon=''
self.orientation=0
self.default=''
if 'shunt'in kargs:
self.orientation=kargs['shunt'] # 0: Series, 1:Shunt
self.val={}
self.Zfunc=lambda self,x: 1e-14 #function to define series impedance
self.Yfunc=lambda self,x: 1e14 #function to define admittance
# def __setval__(self,val):
# self.val=val
def Z(self,freq):
return self.Zfunc(self,freq)
def Y(self,freq):
return self.Yfunc(self,freq)
def set_val(self,val,**kargs):
self.val[self.default]=val
#Populate self.val with kargs dictionary at later date
class cap(element):
"""Modification of element class to model an ideal capacitor"""
def __init__(self,*args,**kargs):
element.__init__(self,*args,**kargs)
self.name='cap'
self.default='C'
if 'min' in kargs:
self.val['min']=kargs['min']
else:
self.val['min']=1e-12
if 'max' in kargs:
self.val['max']=kargs['max']
else:
self.val['max']=12.1e-12
if 'step' in kargs:
self.val['step']=kargs['step']
else:
self.val['step']=0.1e-12
self.val['unit']='pF' #Unit not used to scale value variable
if len(args)!=1:
print("ERROR: cap(element) requires 1 argument")
else:
self.val[self.default]=args[0]
#self.Zfunc=lambda self,freq: 1j/(2*pi*freq*self.val['C']) #function to define series impedance
self.Yfunc=lambda self,freq: (1j*2*pi*freq*self.val['C']) #function to define admittance
self.Zfunc=lambda self,freq: 1.0/self.Yfunc(self,freq)
class ind(element):
"""Modification of element class to model an ideal capacitor"""
def __init__(self,*args,**kargs):
element.__init__(self,*args,**kargs)
self.name='ind'
self.default='L'
if 'min' in kargs:
self.val['min']=kargs['min']
else:
self.val['min']=1e-9
if 'max' in kargs:
self.val['max']=kargs['max']
else:
self.val['max']=12.1e-9
if 'step' in kargs:
self.val['step']=kargs['step']
else:
self.val['step']=0.1e-9
self.val['unit']='nH' #Unit not used to scale value variable
if len(args)!=1:
print("ERROR: ind(element) requires 1 argument")
else:
self.val['L']=args[0]
self.Zfunc=lambda self,freq: 1j*2*pi*freq*self.val['L'] #function to define series impedance
self.Yfunc=lambda self,freq: 1.0/self.Zfunc(self,freq)
class indQ(element):
"""Modification of element class to model an capacitor with a fixed Q"""
def __init__(self,*args,**kargs):
element.__init__(self)
self.name='indQ'
if len(args)!=2:
print("ERROR: indQ(element) requires 2 arguments")
else:
self.val['L']=args[0]
self.val['Q']=args[1]
#function to define series impedance
self.Zfunc=lambda self,freq: 2*pi*freq*self.val['L']/self.val['Q']+1j*2*pi*freq*self.val['L']
#function to define admittance
self.Yfunc=lambda self,freq: 1.0j/self.Zfunc(self,x)
class capQ(element):
"""Modification of element class to model an capacitor with a fixed L"""
def __init__(self,*args,**kargs):
element.__init__(self)
self.name='capQ'
if len(args)!=2:
print("ERROR: capQ(element) requires 2 arguments")
else:
self.val['C']=args[0]
self.val['Q']=args[1]
#function to define series impedance
self.Zfunc=lambda self,freq: (1.0/(2*pi*freq*self.val['C']))/self.val['Q']+1.0j/(2*pi*freq*self.val['C'])
#function to define admittance
self.Yfunc=lambda self,freq: 1.0/self.Zfunc(self,x)
if __name__=='__main__':
net=network()
#TEST CASE -- matching 50.0 Ohms to ~5.0 Ohms at 2 GHz
L1=ind(0.75e-9)
C1=cap(6.3e-12,shunt=1)
L2=ind(2.0e-9)
C2=cap(1.6e-12,shunt=1)
net.element_array.append(C2)
net.element_array.append(L2)
net.element_array.append(C1)
net.element_array.append(L1)
print(net.compute_node_impedances(2.0e9))
| 5,807 |
IRIS_data_download/IRIS_download_support/obspy/io/reftek/__init__.py
|
earthinversion/Fnet_IRIS_data_automated_download
| 2 |
2171919
|
# -*- coding: utf-8 -*-
"""
obspy.io.reftek - REFTEK130 read support for ObsPy
==================================================
This module provides read support for the RefTek 130 data format.
Currently the low level read routines are designed to operate on waveform files
written by RefTek 130 digitizers which are composed of event header/trailer and
data packages. These packages do not store information on network or location
code during acquisition. Furthermore, it is unclear how consistently the level
of detail on the recorded channel codes is set in the headers (real world test
data at hand recorded with a Reftek 130 do contain the information on the first
two channel code characters, the band and instrument code but lack information
on the component codes, i.e. ZNE, which with high likelihood were set in the
acquisition parameters). Therefore, additional information on network and
location codes should be supplied and ideally component codes should be
supplied as well when reading files with :func:`~obspy.core.stream.read` (or
should be filled in manually after reading). See the low-level routine
:func:`obspy.io.reftek.core._read_reftek130` for additional arguments that can
be supplied to :func:`~obspy.core.stream.read`.
Currently, only event header/trailer (EH/ET) and data packets (DT) are
implemented and any other packets will be ignored (a warning is shown if any
other packets are encountered during reading). So far, only data encoding "C0"
(STEIM 1 compressed data) is implemented due to the lack of test data in other
encodings.
Reading
-------
Reading Reftek130 data is handled by using ObsPy's standard
:func:`~obspy.core.stream.read` function. The format is detected
automatically and optionally can be explicitly set if known
beforehand to skip format detection.
>>> from obspy import read
>>> st = read("/path/to/225051000_00008656") # doctest: +SKIP
>>> st # doctest: +SKIP
<obspy.core.stream.Stream object at 0x...>
>>> print(st) # doctest: +SKIP
8 Trace(s) in Stream:
.KW1..EH0 | 2015-10-09T22:50:51.000000Z - ... | 200.0 Hz, 3165 samples
.KW1..EH0 | 2015-10-09T22:51:06.215000Z - ... | 200.0 Hz, 892 samples
.KW1..EH0 | 2015-10-09T22:51:11.675000Z - ... | 200.0 Hz, 2743 samples
.KW1..EH1 | 2015-10-09T22:50:51.000000Z - ... | 200.0 Hz, 3107 samples
.KW1..EH1 | 2015-10-09T22:51:05.925000Z - ... | 200.0 Hz, 768 samples
.KW1..EH1 | 2015-10-09T22:51:10.765000Z - ... | 200.0 Hz, 2925 samples
.KW1..EH2 | 2015-10-09T22:50:51.000000Z - ... | 200.0 Hz, 3405 samples
.KW1..EH2 | 2015-10-09T22:51:08.415000Z - ... | 200.0 Hz, 3395 samples
Network, location and component codes can be specified during reading:
>>> st = read("/path/to/225051000_00008656", network="BW", location="",
... component_codes="ZNE")
>>> st # doctest: +ELLIPSIS
<obspy.core.stream.Stream object at 0x...>
>>> print(st) # doctest: +ELLIPSIS
8 Trace(s) in Stream:
BW.KW1..EHE | 2015-10-09T22:50:51.000000Z - ... | 200.0 Hz, 3405 samples
BW.KW1..EHE | 2015-10-09T22:51:08.415000Z - ... | 200.0 Hz, 3395 samples
BW.KW1..EHN | 2015-10-09T22:50:51.000000Z - ... | 200.0 Hz, 3107 samples
BW.KW1..EHN | 2015-10-09T22:51:05.925000Z - ... | 200.0 Hz, 768 samples
BW.KW1..EHN | 2015-10-09T22:51:10.765000Z - ... | 200.0 Hz, 2925 samples
BW.KW1..EHZ | 2015-10-09T22:50:51.000000Z - ... | 200.0 Hz, 3165 samples
BW.KW1..EHZ | 2015-10-09T22:51:06.215000Z - ... | 200.0 Hz, 892 samples
BW.KW1..EHZ | 2015-10-09T22:51:11.675000Z - ... | 200.0 Hz, 2743 samples
Reftek 130 specific metadata (from event header packet) is stored
in ``stats.reftek130``.
>>> print(st[0].stats) # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
network: BW
station: KW1
location:
channel: EHE
starttime: 2015-10-09T22:50:51.000000Z
endtime: 2015-10-09T22:51:08.020000Z
sampling_rate: 200.0
delta: 0.005
npts: 3405
calib: 1.0
_format: REFTEK130
reftek130: ...
Details on the individual packets can be retrieved with the low level
:class:`~obspy.io.reftek.core.Reftek130` object:
>>> from obspy.core.util.base import get_example_file
>>> from obspy.io.reftek.core import Reftek130
>>> rt = Reftek130.from_file(get_example_file("225051000_00008656"))
>>> print(rt) # doctest: +ELLIPSIS
Reftek130 (29 packets, file: ...225051000_00008656)
Packet Sequence Byte Count Data Fmt Sampling Rate Time
| Packet Type | Event # | Station | Channel # |
| | Unit ID | | Data Stream # | | # of samples |
| | | Exper.# | | | | | | | |
0000 EH AE4C 0 416 427 0 C0 KW1 200 2015-10-09T22:50:51.000000Z
0001 DT AE4C 0 1024 427 0 C0 0 549 2015-10-09T22:50:51.000000Z
0002 DT AE4C 0 1024 427 0 C0 1 447 2015-10-09T22:50:51.000000Z
0003 DT AE4C 0 1024 427 0 C0 2 805 2015-10-09T22:50:51.000000Z
0004 DT AE4C 0 1024 427 0 C0 0 876 2015-10-09T22:50:53.745000Z
0005 DT AE4C 0 1024 427 0 C0 1 482 2015-10-09T22:50:53.235000Z
0006 DT AE4C 0 1024 427 0 C0 1 618 2015-10-09T22:50:55.645000Z
0007 DT AE4C 0 1024 427 0 C0 2 872 2015-10-09T22:50:55.025000Z
0008 DT AE4C 0 1024 427 0 C0 0 892 2015-10-09T22:50:58.125000Z
0009 DT AE4C 0 1024 427 0 C0 1 770 2015-10-09T22:50:58.735000Z
0010 DT AE4C 0 1024 427 0 C0 2 884 2015-10-09T22:50:59.385000Z
0011 DT AE4C 0 1024 427 0 C0 0 848 2015-10-09T22:51:02.585000Z
0012 DT AE4C 0 1024 427 0 C0 1 790 2015-10-09T22:51:02.585000Z
0013 DT AE4C 0 1024 427 0 C0 2 844 2015-10-09T22:51:03.805000Z
0014 DT AE4C 0 1024 427 0 C0 0 892 2015-10-09T22:51:06.215000Z
0015 DT AE4C 0 1024 427 0 C0 1 768 2015-10-09T22:51:05.925000Z
0016 DT AE4C 0 1024 427 0 C0 2 884 2015-10-09T22:51:08.415000Z
0017 DT AE4C 0 1024 427 0 C0 1 778 2015-10-09T22:51:10.765000Z
0018 DT AE4C 0 1024 427 0 C0 0 892 2015-10-09T22:51:11.675000Z
0019 DT AE4C 0 1024 427 0 C0 2 892 2015-10-09T22:51:12.835000Z
0020 DT AE4C 0 1024 427 0 C0 1 736 2015-10-09T22:51:14.655000Z
0021 DT AE4C 0 1024 427 0 C0 0 892 2015-10-09T22:51:16.135000Z
0022 DT AE4C 0 1024 427 0 C0 2 860 2015-10-09T22:51:17.295000Z
0023 DT AE4C 0 1024 427 0 C0 1 738 2015-10-09T22:51:18.335000Z
0024 DT AE4C 0 1024 427 0 C0 0 892 2015-10-09T22:51:20.595000Z
0025 DT AE4C 0 1024 427 0 C0 1 673 2015-10-09T22:51:22.025000Z
0026 DT AE4C 0 1024 427 0 C0 2 759 2015-10-09T22:51:21.595000Z
0027 DT AE4C 0 1024 427 0 C0 0 67 2015-10-09T22:51:25.055000Z
0028 ET AE4C 0 416 427 0 C0 KW1 200 2015-10-09T22:50:51.000000Z
(detailed packet information with: 'print(Reftek130.__str__(compact=False))')
>>> print(rt.__str__(compact=False)) # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS
Reftek130 (29 packets, file: ...225051000_00008656)
EH Packet
packet_sequence: 0
experiment_number: 0
unit_id: AE4C
byte_count: 416
time: 2015-10-09T22:50:51.000000Z
event_number: 427
data_stream_number: 0
data_format: C0
flags: 0
--------------------
_reserved_2:
_reserved_3:
...
detrigger_time: None
digital_filter_list:
first_sample_time: 2015-10-09T22:50:51.000000Z
last_sample_time: None
position:
...
sampling_rate: 200
station_channel_number: (None, None, None, None, None, None, None, ...)
station_comment: STATION COMMENT
station_name: KW1
station_name_extension:
stream_name: EH
time_quality: ?
time_source: 1
total_installed_channels: 3
trigger_time: 2015-10-09T22:50:51.000000Z
trigger_time_message: Trigger Time = 2015282225051000
<BLANKLINE>
trigger_type: CON
DT Packet
packet_sequence: 1
experiment_number: 0
unit_id: AE4C
byte_count: 1024
time: 2015-10-09T22:50:51.000000Z
event_number: 427
data_stream_number: 0
channel_number: 0
number_of_samples: 549
data_format: C0
flags: 0
DT Packet
packet_sequence: 2
experiment_number: 0
unit_id: AE4C
byte_count: 1024
time: 2015-10-09T22:50:51.000000Z
event_number: 427
data_stream_number: 0
channel_number: 1
number_of_samples: 447
data_format: C0
flags: 0
...
:copyright:
The ObsPy Development Team (<EMAIL>)
:license:
GNU Lesser General Public License, Version 3
(https://www.gnu.org/copyleft/lesser.html)
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import * # NOQA
if __name__ == '__main__':
import doctest
doctest.testmod(exclude_empty=True)
| 8,868 |
app_gerenciador_de_livros/migrations/0004_alter_livros_estrelas.py
|
raphaelaferraz/book_manager
| 1 |
2170058
|
# Generated by Django 4.0.1 on 2022-01-07 23:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_gerenciador_de_livros', '0003_alter_livros_estrelas'),
]
operations = [
migrations.AlterField(
model_name='livros',
name='estrelas',
field=models.IntegerField(),
),
]
| 399 |
utils/hazmat/structs/weakref.py
|
thatbirdguythatuknownot/pyutils
| 3 |
2171488
|
import weakref
import ctypes
from .base import Struct
from .common import PyObject, PyObject_p, Py_hash_t, update_types
#https://github.com/python/cpython/blob/master/Include/weakrefobject.h
class PyWeakReference(Struct):
@property
def value(self):
return self.wr_object
PyWeakReference._fields_ = [ #pylint: disable=protected-access
("ob_base", PyObject), ("wr_object", PyObject_p), ("wr_callback", PyObject_p),
("hash", Py_hash_t), ("wr_prev", ctypes.POINTER(PyWeakReference)),
("wr_next", ctypes.POINTER(PyWeakReference))
]
update_types({weakref.ref: PyWeakReference})
| 582 |
Python/DNA_manipulation/Mutation.py
|
LilyYC/legendary-train
| 0 |
2170211
|
def correct_mutations(strands, clean, names, sequences):
""" (list of str, str, list of str, list of str) -> NoneType
Precondition: strands and clean only contain characters in 'A', 'T', 'C' or
'G'. clean contains exactly one 1-cutter from names and sequences.
sequences is the corresponding list of recognition sequences of names.
len(names) == len(sequences).
Modify strands by replacing all bases starting at the 1-cutter in strands
with all bases starting at the 1-cutter in clean.
>>> correct_mutations(['CCCAGCTGGG', 'CGTTTTTAAAAA'], 'AGAGCTTTT', ['AluI',
'BamHI'], ['AGCT', 'GGATCC'])
>>> strands
['CCCAGCTTTT', 'CGTTTTTAAAAA']
>>> correct_mutations(['AAGGCCCCCGGG', 'TTGGCCGGCC'], 'TAGGCCAA', ['HaeIII',
'SmaI'], ['GGCC', 'CCCGGG'])
>>> strands
['AAGGCCAA', 'TTGGCCGGCC']
"""
result = []
for item in sequences:
for ch in strands:
if item in clean and ch.count(item) == 1:
a = ch[0:ch.find(item)] + clean[clean.find(item):]
result.append(a)
else:
result.append(ch)
if _name_=='_main_':
import docttest
docttest.testmod()
| 1,233 |
crypt/DH.py
|
galicea/eduprog
| 0 |
2171086
|
#!/usr/bin/env python
"""
Diffie-Hellman Key Demo in Python
author: <NAME>, Galicea
License: GNU General Public License <http://www.gnu.org/licenses/>.
pip install primesieve
pip install numpy
"""
import numpy as np
import primesieve
from random import randint
def generate_primes(n1,n2):
return primesieve.primes(n1, n2)
def int_from_bytes(n):
try: # python 3
int.from_bytes(n, byteorder="big")
except:
import struct
format = 'Q' * (len(n) / 8)
return struct.unpack(format, n)[0]
class DiffieHellman(object):
"""
Demo implementation of the Diffie-Hellman protocol.
"""
def __init__(self, generator=2, group=None, keyBytes=72):
"""
Generate group and keys.
"""
if group:
self.group=group
else:
self.group = self.getPrime()
self.generator = generator
self.privateKey = self.genPrivateKey(keyBytes)
self.publicKey = self.genPublicKey()
def genPrivateKey(self, size):
"""
Private Key = random with the specified number of bits (size*8)
http://stefanocappellini.com/generate-pseudorandom-bytes-with-python/
"""
return np.random.bytes(size)
def genPublicKey(self):
"""
key = generator ** privateKey % group.
"""
return pow(self.generator, int_from_bytes(self.privateKey), self.group)
def sharedSecret(self, otherKey):
"""
sharedSecret = otherKey ** privateKey % group
"""
return pow(otherKey, int_from_bytes(self.privateKey), self.group)
def getPrime(self, min=1000):
"""
Eratosthenes sieve http://code.activestate.com/recipes/117119/
https://github.com/hickford/primesieve-python
"""
prime_list = generate_primes(min, min+100)
while (not prime_list):
prime_list = generate_primes(min, min+100)
n=randint(0, len(prime_list)-1)
return prime_list[n]
if __name__=="__main__":
first = DiffieHellman()
# generator and group as public
print "generator=%s, group=%s" % (first.generator, first.group)
two = DiffieHellman(generator=first.generator, group=first.group)
print 'shared secret [1] = %s' % first.sharedSecret(two.publicKey)
print 'shared secret [2] = %s' % two.sharedSecret(first.publicKey)
| 2,098 |
src/content.py
|
tensor-nsk-lesson/Social_network
| 0 |
2170505
|
from connect import connect
def get_content_by_type(status):
conn = connect()
cur = conn.cursor()
cur.execute('select * from "GlobalContent" where "Status" = '+status.__str__())
rows = cur.fetchall()
result = []
for row in rows:
data = {
"IdFile": row[0],
"File": row[1],
"Status": row[2]
}
result.append(data)
conn.close()
return result
def add_content_for_user(id_user, id_file):
conn = connect()
cur = conn.cursor()
cur.execute('select * from "GlobalContent" where "IdFile" = '+id_file.__str__())
result = cur.fetchone()
cur.execute('insert into "LocalContent" ("IdContent", "IdFile") values('+id_user.__str__()+','+result[0].__str__()+')')
conn.commit()
conn.close()
return
| 838 |
app/src/data_collector.py
|
mss28/vulnerability_data_analysis
| 0 |
2172158
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import re
import time
import redis
import requests
import traceback
localRedis = redis.StrictRedis(host='redis', port=6379, decode_responses=True)
download_url_template = "https://raw.githubusercontent.com/{:s}/{:s}/package.json"
npm_search_url_template = 'https://api.github.com/search/code?q={:s} in:file path:/+extension:json+filename:package.json&sort=stars&order=desc&page={:d}'
auth_user = '' # put git user name
auth_pass = '' # put git password
# Redis keys
ALL_LIBS = "all_libs" # store name all libraries
LIB_STAT_KEY = '{:s}.is_loaded' # store loading status of a library
SLEEP_DURATION = 60
def page_visit_torify(url):
session = requests.session()
session.proxies = {'http': 'socks5h://localhost:9050', 'https': 'socks5h://localhost:9050'}
return session.get(url)
def get_download_ur(html_url):
result = re.search(r'^https://github.com/(.*)/blob/(.*)/package\.json$', html_url)
download_url = None
if result:
repo_id, commit_hash = result.groups()
download_url = download_url_template.format(repo_id, commit_hash)
return download_url
def download_file(download_url):
# make sure to service tor start
# req = requests.get(download_url)
req = page_visit_torify(download_url)
return json.loads(req.text.encode('utf-8').decode("utf8"))
def get_from_dependencies(key, packages, target_lib_name):
key_lib = packages.get(key)
if key_lib is None:
return None
else:
return key_lib.get(target_lib_name, None)
def find_library_version(target_lib_name, package_json):
result = get_from_dependencies('dependencies', package_json, target_lib_name)
if result is None:
result = get_from_dependencies('devDependencies', package_json, target_lib_name)
if result is None:
result = get_from_dependencies('bundledDependencies', package_json, target_lib_name)
if result is None:
result = get_from_dependencies('optionalDependencies', package_json, target_lib_name)
if result is None:
result = get_from_dependencies('peerDependencies', package_json, target_lib_name)
return result
def get_req_status(req):
headers = req.headers
# print("\t***Headers***")
# print(headers)
# print("***---***")
status_code = headers['Status']
status, last = False, 99999999
if status_code == "200 OK":
status = True
if 'Link' in headers:
last_reg = re.search(r'<https://api.github.com/search/code.*page=(.*)>; rel="last"', headers['Link'])
if last_reg is not None:
last = int(last_reg.groups()[0])
elif status_code == "422 Unprocessable Entity":
raise Exception(status_code)
return status, last
def search(target_lib_name, output_file):
print('\tSearching for the library: {:s}'.format(target_lib_name))
current_page = 1
max_page = 1
while current_page <= max_page:
url = npm_search_url_template.format(target_lib_name, current_page)
req, status, last_page = None, False, 0
while not status:
req = requests.get(url, auth=(auth_user, auth_pass))
status, last_page = get_req_status(req)
if not status:
print(
"\t......................Putting to sleep for {:d} seconds......................".format(
SLEEP_DURATION)
)
time.sleep(SLEEP_DURATION)
max_page = last_page
r = json.loads(req.text.encode('utf-8').decode("utf8"))
for item in r['items']:
repo = item['repository']
html_url = item['html_url']
download_url = get_download_ur(html_url)
if download_url is not None:
package_json = download_file(download_url)
lib_version = find_library_version(target_lib_name, package_json)
result = {
'target_lib_name': target_lib_name,
"repo_id": repo['id'],
"repo_name": "https://github.com/{:s}".format(repo['full_name']),
"lib_version": lib_version
}
if output_file is not None:
output_file.write('{:s}, {:s}, "{:s}", "{:s}"\n'.format(
target_lib_name, str(result['repo_id']), str(result['repo_name']), str(result['lib_version'])))
localRedis.set('repo.result.' + str(result['repo_id']), json.dumps(result))
print('\t' + str(result))
repository_id = repo['id']
localRedis.sadd('repo_ids', repository_id)
localRedis.set('repo.' + str(repository_id), json.dumps(item))
current_page += 1
def read_json(file_path):
with open(file_path, 'r') as file:
data = file.read()
return json.loads(data)
def store_list(data):
for d in data:
localRedis.sadd(ALL_LIBS, d['lib_name'])
def run(input_file_path, start, end):
data = read_json(input_file_path)
store_list(data)
all_data = list(localRedis.smembers(ALL_LIBS))
all_data.sort()
sliced_data, counter = all_data, 1
if start is not None and end is not None:
sliced_data = all_data[start - 1: end]
counter = start
output_file = open("../data/vulnerabilities.csv", "a")
for lib_name in sliced_data:
print('Loading the library: {:s}'.format(lib_name))
key = LIB_STAT_KEY.format(lib_name)
is_loaded = localRedis.get(key)
if is_loaded is None:
is_loaded = 0
else:
is_loaded = int(is_loaded)
# 0 not loaded
# 1 on going
# 2 failed
# 3 completed
if is_loaded == 3:
print('\t{:d}. {:s} already loaded'.format(counter, lib_name))
else:
try:
localRedis.set(key, 1)
search(lib_name, output_file)
except Exception:
print("\t", end='')
traceback.print_exc()
print('\t{:d}. {:s} failed'.format(counter, lib_name))
localRedis.set(key, 2)
else:
print('\t{:d}. {:s} completed'.format(counter, lib_name))
localRedis.set(key, 3)
counter += 1
def test(lib_name):
search(lib_name, None)
if __name__ == "__main__":
# test('electron')
should_run = True
# TODO: Take git credentials from console input
if auth_user == '':
should_run = False
print('Provide git user name')
if auth_pass == '':
should_run = False
print('Provide git password')
# split = input("Do you want to load all? (y) if yes, (n) if no: ")
start_num, end_num = None, None
#if split == "y":
# start_num = int(input("Start number:"))
# end_num = int(input("End number:"))
if should_run:
run('../data/npm_advisories.json', start_num, end_num)
else:
print('Not ready to run, check messages')
| 7,098 |
reproman/distributions/singularity.py
|
kyleam/niceman
| 13 |
2171711
|
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the reproman package for the
# copyright and license terms.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""Support for Singularity distribution(s)."""
import attr
import json
import logging
import os
import tempfile
import uuid
lgr = logging.getLogger('reproman.distributions.singularity')
from .base import Package
from .base import Distribution
from .base import DistributionTracer
from .base import TypedList
from .base import _register_with_representer
from ..dochelpers import borrowdoc, exc_str
from ..utils import attrib, md5sum, chpwd
@attr.s(slots=True, frozen=True)
class SingularityImage(Package):
"""Singularity image information"""
md5 = attrib(default=attr.NOTHING)
# Optional
bootstrap = attrib()
maintainer = attrib()
deffile = attrib()
schema_version = attrib()
build_date = attrib()
build_size = attrib()
singularity_version = attrib()
base_image = attrib()
mirror_url = attrib()
url = attrib()
path = attrib()
_register_with_representer(SingularityImage)
@attr.s
class SingularityDistribution(Distribution):
"""
Class to provide commands to Singularity.
"""
images = TypedList(SingularityImage)
def initiate(self, session):
"""
Perform any initialization commands needed in the environment.
Parameters
----------
session : object
The Session to work in
"""
# Raise reproman.support.exceptions.CommandError exception if
# Singularity is not to be found.
session.execute_command(['singularity', 'selftest'])
def install_packages(self, session):
"""
Install the Singularity images associated to this distribution by the
provenance into the environment.
Parameters
----------
session : object
Session to work in
"""
# TODO: Currently we have no way to locate the image given the metadata
_register_with_representer(SingularityDistribution)
class SingularityTracer(DistributionTracer):
"""Singularity image tracer
If a given file is not identified as a singularity image, the files
are quietly passed on to the next tracer.
"""
HANDLES_DIRS = False
@borrowdoc(DistributionTracer)
def identify_distributions(self, files):
if not files:
return
images = []
remaining_files = set()
url = None
path = None
for file_path in files:
try:
if file_path.startswith('shub:/'):
# Correct file path for path normalization in retrace.py
if not file_path.startswith('shub://'):
file_path = file_path.replace('shub:/', 'shub://')
temp_path = "{}.simg".format(uuid.uuid4())
with chpwd(tempfile.gettempdir()):
msg = "Downloading Singularity image {} for tracing"
lgr.info(msg.format(file_path))
self._session.execute_command(['singularity', 'pull',
'--name', temp_path, file_path])
image = json.loads(self._session.execute_command(
['singularity', 'inspect', temp_path])[0])
url = file_path
md5 = md5sum(temp_path)
os.remove(temp_path)
else:
path = os.path.abspath(file_path)
image = json.loads(self._session.execute_command(
['singularity', 'inspect', file_path])[0])
md5 = md5sum(file_path)
images.append(SingularityImage(
md5=md5,
bootstrap=image.get(
'org.label-schema.usage.singularity.deffile.bootstrap'),
maintainer=image.get('MAINTAINER'),
deffile=image.get(
'org.label-schema.usage.singularity.deffile'),
schema_version=image.get('org.label-schema.schema-version'),
build_date=image.get('org.label-schema.build-date'),
build_size=image.get('org.label-schema.build-size'),
singularity_version=image.get(
'org.label-schema.usage.singularity.version'),
base_image=image.get(
'org.label-schema.usage.singularity.deffile.from'),
mirror_url=image.get(
'org.label-schema.usage.singularity.deffile.mirrorurl'),
url=url,
path=path
))
except Exception as exc:
lgr.debug("Probably %s is not a Singularity image: %s",
file_path, exc_str(exc))
remaining_files.add(file_path)
if not images:
return
dist = SingularityDistribution(
name="singularity",
images=images
)
yield dist, remaining_files
@borrowdoc(DistributionTracer)
def _get_packagefields_for_files(self, files):
return
@borrowdoc(DistributionTracer)
def _create_package(self, **package_fields):
return
| 5,522 |
API/views.py
|
MrAbdelaziz/GestionStoc_django
| 3 |
2169444
|
from django.contrib.auth import authenticate
from django.shortcuts import render
from rest_framework import viewsets, generics, status
from rest_framework import permissions
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import *
from .models import *
class ClientViewSet(viewsets.ModelViewSet):
queryset = Client.objects.all().order_by('nom')
serializer_class = ClientSerializer
class FournisseurViewSet(viewsets.ModelViewSet):
queryset = Fournisseur.objects.all().order_by('libelle')
serializer_class = FournisseurSerializer
class ProduitViewSet(viewsets.ModelViewSet):
queryset = Produit.objects.all().order_by('reference')
serializer_class = ProduitSerializer
filter_fields = {
'quantite': ['gte', 'lte']
}
# permission_classes = [permissions.IsAuthenticatedOrReadOnly] ss
# def destroy(self, request, *args, **kwargs):
# instance = self.get_object()
# self.perform_destroy(instance)
# return Response(status=status.HTTP_204_NO_CONTENT)
#
# def perform_destroy(self, instance):
# instance.delete()
class AchatViewSet(viewsets.ModelViewSet):
queryset = Achat.objects.all().order_by('date_Achat')
serializer_class = AchatSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all().order_by('username')
serializer_class = UserSerializer
class CountViewSet(APIView):
def get(self, request, format=None):
Produit_count = Produit.objects.all().count()
Client_count = Client.objects.all().count()
Fournisseur_count = Fournisseur.objects.all().count()
Achat_count = Achat.objects.all().count()
content = {
'produits_count': Produit_count,
'Client_count':Client_count,
'Fournisseur_count':Fournisseur_count,
'Achat_count':Achat_count
}
return Response(content)
class RiskViewSet(APIView):
def get(self, request, format=None):
countprod = request.GET.get('prodid', False)
prods = Produit.objects.filter(quantite__gt=0)
return Response(prods)
class LoginnViewSet(APIView):
def get(self, request, format=None):
username = request.GET.get('username', False)
password = request.GET.get('password', False)
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
return Response(user)
return Response(user)
| 2,595 |
api/urls_index.py
|
Samge0/UmengEventManage
| 0 |
2171974
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2021/10/26 上午10:27
# @Author : Samge
from django.conf.urls import url
from django.views.generic import RedirectView
from .views.v_key import *
# http路由
urlpatterns = [
url(r'^$', index, name='index'),
url(r'^favicon.ico$', RedirectView.as_view(url=r'static/favicon.ico')),
]
| 346 |
pcapkit/reassembly/ipv4.py
|
chellvs/PyPCAPKit
| 131 |
2169938
|
# -*- coding: utf-8 -*-
"""IPv4 fragments reassembly
:mod:`pcapkit.reassembly.ipv4` contains
:class:`~pcapkit.reassembly.ipv4.IPv4_Reassembly`
only, which reconstructs fragmented IPv4 packets back to
origin.
Glossary
--------
ipv4.packet
Data structure for **IPv4 datagram reassembly**
(:meth:`~pcapkit.reassembly.reassembly.Reassembly.reassembly`)
is as following:
.. code-block:: python
packet_dict = dict(
bufid = tuple(
ipv4.src, # source IP address
ipv4.dst, # destination IP address
ipv4.id, # identification
ipv4.proto, # payload protocol type
),
num = frame.number, # original packet range number
fo = ipv4.frag_offset, # fragment offset
ihl = ipv4.hdr_len, # internet header length
mf = ipv4.flags.mf, # more fragment flag
tl = ipv4.len, # total length, header includes
header = ipv4.header, # raw bytearray type header
payload = ipv4.payload, # raw bytearray type payload
)
ipv4.datagram
Data structure for **reassembled IPv4 datagram** (element from
:attr:`~pcapkit.reassembly.reassembly.Reassembly.datagram` *tuple*)
is as following:
.. code-block:: python
(tuple) datagram
|--> (dict) data
| |--> 'NotImplemented' : (bool) True --> implemented
| |--> 'index' : (tuple) packet numbers
| | |--> (int) original packet range number
| |--> 'packet' : (Optional[bytes]) reassembled IPv4 packet
|--> (dict) data
| |--> 'NotImplemented' : (bool) False --> not implemented
| |--> 'index' : (tuple) packet numbers
| | |--> (int) original packet range number
| |--> 'header' : (Optional[bytes]) IPv4 header
| |--> 'payload' : (Optional[tuple]) partially reassembled IPv4 payload
| |--> (Optional[bytes]) IPv4 payload fragment
|--> (dict) data ...
ipv4.buffer
Data structure for internal buffering when performing reassembly algorithms
(:attr:`~pcapkit.reassembly.reassembly.Reassembly._buffer`) is as following:
.. code-block:: python
(dict) buffer --> memory buffer for reassembly
|--> (tuple) BUFID : (dict)
| |--> ipv4.src |
| |--> ipc6.dst |
| |--> ipv4.label |
| |--> ipv4_frag.next |
| |--> 'TDL' : (int) total data length
| |--> RCVBT : (bytearray) fragment received bit table
| | |--> (bytes) b'\\x00' -> not received
| | |--> (bytes) b'\\x01' -> received
| | |--> (bytes) ...
| |--> 'index' : (list) list of reassembled packets
| | |--> (int) packet range number
| |--> 'header' : (bytearray) header buffer
| |--> 'datagram' : (bytearray) data buffer, holes set to b'\\x00'
|--> (tuple) BUFID ...
"""
from pcapkit.reassembly.ip import IP_Reassembly
__all__ = ['IPv4_Reassembly']
class IPv4_Reassembly(IP_Reassembly):
"""Reassembly for IPv4 payload.
Example:
>>> from pcapkit.reassembly import IPv4_Reassembly
# Initialise instance:
>>> ipv4_reassembly = IPv4_Reassembly()
# Call reassembly:
>>> ipv4_reassembly(packet_dict)
# Fetch result:
>>> result = ipv4_reassembly.datagram
"""
##########################################################################
# Properties.
##########################################################################
@property
def name(self):
"""Protocol of current packet.
:rtype: Literal['Internet Protocol version 4']
"""
return 'Internet Protocol version 4'
@property
def protocol(self):
"""Protocol of current reassembly object.
:rtype: Literal['IPv4']
"""
return 'IPv4'
| 4,361 |
tests/test_client.py
|
lspvic/yawxt
| 4 |
2170633
|
# -*- coding: utf-8 -*-
'''Tests for WxClient API'''
from __future__ import unicode_literals
import requests
import pytest
from yawxt import (
MaxQuotaError, User, APIError, Location,
ChangeIndustryError)
@pytest.mark.xfail(raises=MaxQuotaError)
def test_get_users(client):
openid = next(client.get_openid_iter())
assert len(openid) > 0
@pytest.mark.xfail(raises=MaxQuotaError)
def test_users_count(client):
assert client.get_user_count() > 0
@pytest.mark.xfail(raises=MaxQuotaError)
def test_get_user_info(client, openid):
user = client.get_user(openid)
assert isinstance(user, User)
assert user.nickname is not None
assert user.openid is not None
def test_user_model(client, monkeypatch):
info = {
"subscribe": 1,
"openid": "o9KLls80ReakhjsbmHUZxjbz9K8c",
"nickname": "五音盒",
"sex": 1,
"language": "zh_CN",
"city": "杭州",
"province": "浙江",
"country": "中国",
"headimgurl": (
"http://wx.qlogo.cn/mmopen/ajSDdqHZLLCXFhHOkecFpWDCW"
"l5icpYpzzwc39E4nmyfSicjfg40EWSicf0R7VEDakCySlTybGJtWH4G"
"53P01itBqA/0"),
"subscribe_time": 1440489434,
"remark": "",
"groupid": 0,
"tagid_list": []}
def mock_api_return(resp):
return info
monkeypatch.setattr(requests.Response, "json", mock_api_return)
user = client.get_user(info["openid"])
assert user.openid == info["openid"]
assert user.nickname == info["nickname"]
assert user.city == info["city"]
assert user.province == info["province"]
assert user.tagid_list == ""
assert user.tagids == info["tagid_list"]
assert user.subscribe == info["subscribe"]
assert user.sex == info["sex"]
assert user.language == info["language"]
assert user.country == info["country"]
assert user.headimgurl == info["headimgurl"]
assert user.subscribe_time == info["subscribe_time"]
assert user.remark == info["remark"]
assert user.groupid == info["groupid"]
@pytest.mark.xfail(raises=APIError)
def test_semantic_parse(client, openid):
info = client.get_user(openid)
query = "查一下明天从北京到上海的南航机票"
location = Location(23.1374665, 113.352425, openid=info.openid)
result = client.semantic_parse(query, city=info.city, location=location)
assert isinstance(result, dict)
if "type" not in result:
raise APIError(20701, str(result))
@pytest.mark.xfail(raises=MaxQuotaError)
def test_preview_message(client, openid):
text = "能看到我发消息吗?"
msg_id = client.preview_message(openid, text)
assert msg_id is None
def test_js_config(client):
url = "http://example.com"
config = client.js_sign(url, debug=False)
assert config["debug"] == "false"
assert len(config["signature"]) == 40
@pytest.mark.xfail(raises=ChangeIndustryError)
def test_template_set_industry(client):
client.set_industry(1, 24)
@pytest.mark.xfail(raises=MaxQuotaError)
def test_template_get_industry(client):
result = client.get_industry()
assert 'primary_industry' in result
assert 'first_class' in result['primary_industry']
assert 'secondary_industry' in result
assert 'second_class' in result['secondary_industry']
@pytest.mark.xfail(raises=MaxQuotaError)
def test_template_add_template(client):
template_id = client.add_sys_template('TM00015')
assert bool(template_id) is True
@pytest.mark.xfail(raises=MaxQuotaError)
def test_template_all_list(client):
result = client.get_template_list()
assert isinstance(result, list)
assert len(result) >= 1
@pytest.mark.xfail(raises=MaxQuotaError)
def test_template_send_message(client, openid):
template_id = client.get_template_list()[0]['template_id']
to_openid = openid
data = {
"first": {
"value": "恭喜你购买成功!",
"color": "#173177"},
"orderMoneySum": {
"value": "28.85",
"color": "#173177"},
"orderProductName": {
"value": "巧克力",
"color": "#173177"},
"remark": {
"value": "欢迎再次购买!",
"color": "#173177"}
}
client.send_template_message(
to_openid, template_id, data=data, url="http://qq.com/")
@pytest.mark.xfail(raises=MaxQuotaError)
def test_template_del(client):
template_id = client.get_template_list()[0]['template_id']
client.del_template(template_id)
assert template_id not in map(
lambda t: t["template_id"], client.get_template_list())
| 4,733 |
ansible-tests/validations/files/rogue_dhcp.py
|
rthallisey/clapper
| 13 |
2172028
|
#!/tmp/validations-venv/bin/python
# Disable scapy's warning to stderr:
import logging
import sys
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
def find_dhcp_servers(timeout_sec):
conf.checkIPaddr = False
fam, hw = get_if_raw_hwaddr(conf.iface)
dhcp_discover = (Ether(dst="ff:ff:ff:ff:ff:ff") /
IP(src="0.0.0.0", dst="255.255.255.255") /
UDP(sport=68, dport=67) /
BOOTP(chaddr=hw) /
DHCP(options=[("message-type", "discover"), "end"]))
ans, unans = srp(dhcp_discover, multi=True, timeout=timeout_sec, verbose=False)
return [(unicode(packet[1][IP].src), packet[1][Ether].src)
for packet in ans]
def main():
dhcp_servers = find_dhcp_servers(30)
if dhcp_servers:
sys.stderr.write('Found %d DHCP servers:' % len(dhcp_servers))
sys.stderr.write("\n".join(("* %s (%s)" % (ip, mac) for (ip, mac) in dhcp_servers)))
sys.exit(1)
else:
print "No DHCP servers found."
if __name__ == '__main__':
main()
| 1,102 |
tests/test_utils.py
|
whatsnowplaying/audio-metadata
| 45 |
2172030
|
from pathlib import Path
from ward import (
each,
raises,
test,
)
from audio_metadata.utils import (
apply_unsynchronization,
decode_bytestring,
decode_synchsafe_int,
determine_encoding,
encode_synchsafe_int,
get_image_size,
humanize_bitrate,
humanize_duration,
humanize_sample_rate,
remove_unsynchronization,
split_encoded
)
images = (Path(__file__).parent / 'image').glob('*.*')
@test(
"apply_unsynchronization",
tags=['unit', 'utils', 'apply_unsynchronization'],
)
def _(
b=each(
b'TEST',
b'\xFF',
b'\x00',
b'\xFF\xFE',
b'\xFF\x00',
b'\xFF\x00\xFF',
b'\xFF\x00\x00',
b'\xFF\x00\xFF\xFE',
),
expected=each(
b'TEST',
b'\xFF',
b'\x00',
b'\xFF\x00\xFE',
b'\xFF\x00\x00',
b'\xFF\x00\x00\xFF',
b'\xFF\x00\x00\x00',
b'\xFF\x00\x00\xFF\x00\xFE',
),
):
assert apply_unsynchronization(b) == expected
@test(
"remove_unsynchronization",
tags=['unit', 'utils', 'remove_unsynchronization'],
)
def _(
b=each(
b'TEST',
b'\xFF',
b'\x00',
b'\xFF\x00\xFE',
b'\xFF\x00\x00',
b'\xFF\x00\x00\xFF',
b'\xFF\x00\x00\x00',
b'\xFF\x00\x00\xFF\x00\xFE',
),
expected=each(
b'TEST',
b'\xFF',
b'\x00',
b'\xFF\xFE',
b'\xFF\x00',
b'\xFF\x00\xFF',
b'\xFF\x00\x00',
b'\xFF\x00\xFF\xFE',
),
):
assert remove_unsynchronization(b) == expected
@test(
"decode_synchsafe_int",
tags=['unit', 'utils', 'decode_synchsafe_int'],
)
def _(
args=each(
(b'\x00\x00\x01\x7f', 7),
(b'\x00\x00\x02\x7f', 6),
(b'\x00\x00\x01\x7f', 6),
),
expected=each(
255,
255,
191,
)
):
assert decode_synchsafe_int(*args) == expected
@test(
"Decoding too large synchsafe int raises ValueError",
tags=['unit', 'utils', 'decode_synchsafe_int'],
)
def _(
args=each(
(b'\x80\x00\x00\x00', 7),
(b'@\x00\x00\x00', 6),
)
):
with raises(ValueError):
decode_synchsafe_int(*args)
@test(
"encode_synchsafe_int",
tags=['unit', 'utils', 'encode_synchsafe_int'],
)
def _(
args=each(
(255, 7),
(255, 6),
),
expected=each(
b'\x00\x00\x01\x7f',
b'\x00\x00\x02\x7f',
),
):
assert encode_synchsafe_int(*args) == expected
@test(
"Encoding too large synchsafe int raises ValueError",
tags=['unit', 'utils', 'encode_synchsafe_int'],
)
def _(
args=each(
(268435456, 7),
(16777216, 6),
)
):
with raises(ValueError):
encode_synchsafe_int(*args)
@test(
"decode_bytestring",
tags=['unit', 'utils', 'decode_bytestring'],
)
def _(
b=each(
b'test\x00',
b'\xff\xfet\x00e\x00s\x00t\x00',
b'\xff\xfet\x00e\x00s\x00t\x00\x00',
b'\xfe\xff\x00t\x00e\x00s\x00t',
b'\xfe\xff\x00t\x00e\x00s\x00t\x00',
b'test\x00',
b'test\x00',
b''
),
encoding=each(
'iso-8859-1',
'utf-16-le',
'utf-16-le',
'utf-16-be',
'utf-16-be',
'utf-8',
None,
None,
),
expected=each(
'test',
'test',
'test',
'test',
'test',
'test',
'test',
'',
)
):
if encoding is None:
assert decode_bytestring(b) == expected
else:
assert decode_bytestring(b, encoding=encoding) == expected
@test(
"determine_encoding",
tags=['unit', 'utils', 'determine_encoding'],
)
def _(
b=each(
b'\x00',
b'\x01\xff\xfe',
b'\x01\xfe\xff',
b'\x02',
b'\x03',
b'\x04',
b'',
),
encoding=each(
'iso-8859-1',
'utf-16-le',
'utf-16-be',
'utf-16-be',
'utf-8',
'iso-8859-1',
'iso-8859-1',
),
):
assert determine_encoding(b) == encoding
@test(
"get_image_size",
tags=['unit', 'utils', 'get_image_size']
)
def test_get_image_size():
for image in images:
with image.open('rb') as f:
assert get_image_size(f) == (16, 16)
with raises(ValueError):
get_image_size(b'')
@test(
"humanize_bitrate",
tags=['unit', 'utils', 'humanize_bitrate'],
)
def _(
bitrate=each(
None,
0,
1,
100,
1000,
),
humanized=each(
None,
'0 bps',
'1 bps',
'100 bps',
'1 Kbps',
),
):
assert humanize_bitrate(bitrate) == humanized
@test(
"humanize_duration",
tags=['unit', 'utils', 'humanize_duration'],
)
def _(
duration=each(
None,
0,
1,
60,
3600,
),
humanized=each(
None,
'00:00',
'00:01',
'01:00',
'01:00:00',
),
):
assert humanize_duration(duration) == humanized
@test(
"humanize_sample_rate",
tags=['unit', 'utils', 'humanize_sample_rate'],
)
def _(
sample_rate=each(
None,
0,
1,
1000,
44100,
),
humanized=each(
None,
'0.0 Hz',
'1.0 Hz',
'1.0 KHz',
'44.1 KHz',
),
):
assert humanize_sample_rate(sample_rate) == humanized
@test(
"split_encoded ({b}, {encoding})",
tags=['unit', 'utils', 'split_encoded'],
)
def _(
b=each(
b'test\x00',
b'\xff\xfe\x00\x00\xff\xfet\x00e\x00s\x00t\x00\x00\x00',
b'\xff\xfe\x00\x00\xff\xfet\x00e\x00s\x00t\x00\x00',
b'\xff\xfet\x00e\x00s\x00t\x00\x00\x00',
b'\xfe\xff\x00t\x00e\x00s\x00t\x00\x00',
b'\xfe\xff\x00t\x00e\x00s\x00t\x00',
b'test\x00',
b'test',
),
encoding=each(
'iso-8859-1',
'utf-16-le',
'utf-16-le',
'utf-16-le',
'utf-16-be',
'utf-16-be',
'utf-8',
'iso-9959-1',
),
expected=each(
[b'test'],
[b'\xff\xfe', b'\xff\xfet\x00e\x00s\x00t\x00'],
[b'\xff\xfe', b'\xff\xfet\x00e\x00s\x00t\x00'],
[b'\xff\xfet\x00e\x00s\x00t\x00'],
[b'\xfe\xff\x00t\x00e\x00s\x00t'],
[b'\xfe\xff\x00t\x00e\x00s\x00t'],
[b'test'],
[b'test'],
),
):
assert split_encoded(b, encoding) == expected
| 5,232 |
ipredictor/tests/test_anni.py
|
zenio/ipredictor
| 1 |
2171885
|
#: -*- coding: utf-8 -*-
"""
Interval-valued data prediction Artificial Neural Network model tests
"""
import unittest
import pandas as pd
import numpy as np
from ipredictor.models import ANNI
class ANNITestCase(unittest.TestCase):
def setUp(self):
self.lookback = 2
self.data_length = self.lookback * 4
self.values = [np.array([[i+1], [i]]) for i in
range(1, self.data_length + 1)]
self.dataframe = pd.DataFrame.from_items([('values', self.values)])
self.model = ANNI(self.dataframe, lookback=self.lookback)
def test_if_neurons_amount_properly_configured(self):
self.assertEqual(self.model.input_neurons, self.lookback * 2)
self.assertEqual(self.model.hidden_neurons, self.lookback * 4)
self.assertEqual(self.model.output_neurons, 2)
def test_if_initial_data_is_flattened(self):
self.assertEqual(self.model.X.shape[0], self.data_length * 2)
#: monkey patching for data rescale
self.model.Xf = self.model.X
self.model._rescale_values()
rescaled_flat = self.model.Xf
self.assertEqual(rescaled_flat[0], self.values[0][0])
self.assertEqual(rescaled_flat[1], self.values[0][1])
def test_if_training_dataset_is_properly_configured(self):
trainX = self.model.trainingX
trainY = self.model.trainingY
self.assertEqual(len(trainX[0]), self.lookback * 2)
self.assertEqual(len(trainY), len(self.values) - self.lookback)
def test_if_can_predict_proper_values(self):
STEPS = 5
prediction = self.model.predict(steps=STEPS)
self.assertEqual(len(prediction), STEPS)
self.assertEqual(prediction['values'][0].shape, (2,1))
| 1,580 |
src/app.py
|
BureauTech/BTAlert-AI
| 1 |
2171960
|
from dotenv import load_dotenv
from flask import Flask, Response
from metrics.collector import Collector
# from slack.messenger import Messenger
# from slack.alerts.info_alert import InfoAlert
# from slack.alerts.warning_alert import WarningAlert
load_dotenv()
# messenger = Messenger()
# print(
# messenger.send_alert(WarningAlert())
# )
app = Flask(__name__)
collector = Collector()
@app.route('/metrics')
def get_metrics():
return Response(collector.get_metrics(), mimetype='text/plain')
if __name__ == '__main__':
app.run('localhost', 5050)
| 565 |
ML/Projects/Exploring_MNIST/networks/googLeNet.py
|
xuyannus/Machine-Learning-Collection
| 3,094 |
2172098
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class Inception(nn.Module):
def __init__(
self, in_channels, out1x1, out3x3reduced, out3x3, out5x5reduced, out5x5, outpool
):
super().__init__()
self.branch_1 = BasicConv2d(in_channels, out1x1, kernel_size=1, stride=1)
self.branch_2 = nn.Sequential(
BasicConv2d(in_channels, out3x3reduced, kernel_size=1),
BasicConv2d(out3x3reduced, out3x3, kernel_size=3, padding=1),
)
# Is in the original googLeNet paper 5x5 conv but in Inception_v2 it has shown to be
# more efficient if you instead do two 3x3 convs which is what I am doing here!
self.branch_3 = nn.Sequential(
BasicConv2d(in_channels, out5x5reduced, kernel_size=1),
BasicConv2d(out5x5reduced, out5x5, kernel_size=3, padding=1),
BasicConv2d(out5x5, out5x5, kernel_size=3, padding=1),
)
self.branch_4 = nn.Sequential(
nn.MaxPool2d(kernel_size=3, stride=1, padding=1),
BasicConv2d(in_channels, outpool, kernel_size=1),
)
def forward(self, x):
y1 = self.branch_1(x)
y2 = self.branch_2(x)
y3 = self.branch_3(x)
y4 = self.branch_4(x)
return torch.cat([y1, y2, y3, y4], 1)
class GoogLeNet(nn.Module):
def __init__(self, img_channel):
super().__init__()
self.first_layers = nn.Sequential(
BasicConv2d(img_channel, 192, kernel_size=3, padding=1)
)
self._3a = Inception(192, 64, 96, 128, 16, 32, 32)
self._3b = Inception(256, 128, 128, 192, 32, 96, 64)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self._4a = Inception(480, 192, 96, 208, 16, 48, 64)
self._4b = Inception(512, 160, 112, 224, 24, 64, 64)
self._4c = Inception(512, 128, 128, 256, 24, 64, 64)
self._4d = Inception(512, 112, 144, 288, 32, 64, 64)
self._4e = Inception(528, 256, 160, 320, 32, 128, 128)
self._5a = Inception(832, 256, 160, 320, 32, 128, 128)
self._5b = Inception(832, 384, 192, 384, 48, 128, 128)
self.avgpool = nn.AvgPool2d(kernel_size=8, stride=1)
self.linear = nn.Linear(1024, 10)
def forward(self, x):
out = self.first_layers(x)
out = self._3a(out)
out = self._3b(out)
out = self.maxpool(out)
out = self._4a(out)
out = self._4b(out)
out = self._4c(out)
out = self._4d(out)
out = self._4e(out)
out = self.maxpool(out)
out = self._5a(out)
out = self._5b(out)
out = self.avgpool(out)
out = out.view(out.size(0), -1)
out = self.linear(out)
return out
class BasicConv2d(nn.Module):
def __init__(self, in_channels, out_channels, **kwargs):
super().__init__()
self.conv = nn.Conv2d(in_channels, out_channels, bias=False, **kwargs)
self.bn = nn.BatchNorm2d(out_channels, eps=0.001)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
return F.relu(x, inplace=True)
def test():
net = GoogLeNet(1)
x = torch.randn(3, 1, 32, 32)
y = net(x)
print(y.size())
# test()
| 3,262 |
implement/xgboostmodel.py
|
Arun-Singh-Chauhan-09/Supply-demand-forecasting
| 59 |
2171158
|
import sys
import os
sys.path.insert(0, os.path.abspath('..'))
from preprocess.preparedata import PrepareData
import numpy as np
from utility.runtype import RunType
from utility.datafilepath import g_singletonDataFilePath
from preprocess.splittrainvalidation import HoldoutSplitMethod
import xgboost as xgb
from evaluation.sklearnmape import mean_absolute_percentage_error_xgboost
from evaluation.sklearnmape import mean_absolute_percentage_error
from utility.modelframework import ModelFramework
from utility.xgbbasemodel import XGBoostGridSearch
from evaluation.sklearnmape import mean_absolute_percentage_error_xgboost_cv
from utility.xgbbasemodel import XGBoostBase
import logging
import sys
class DidiXGBoostModel(XGBoostBase, PrepareData, XGBoostGridSearch):
def __init__(self):
PrepareData.__init__(self)
XGBoostGridSearch.__init__(self)
XGBoostBase.__init__(self)
self.best_score_colname_in_cv = 'test-mape-mean'
self.do_cross_val = False
self.train_validation_foldid = -2
if self.do_cross_val is None:
root = logging.getLogger()
root.setLevel(logging.DEBUG)
root.addHandler(logging.StreamHandler(sys.stdout))
root.addHandler(logging.FileHandler('logs/finetune_parameters.log', mode='w'))
return
def set_xgb_parameters(self):
early_stopping_rounds = 3
self.xgb_params = {'silent':1, 'colsample_bytree': 0.8, 'silent': 1, 'lambda ': 1, 'min_child_weight': 1, 'subsample': 0.8, 'eta': 0.01, 'objective': 'reg:linear', 'max_depth': 7}
# self.xgb_params = {'silent':1 }
self.xgb_learning_params = {
'num_boost_round': 200,
'callbacks':[xgb.callback.print_evaluation(show_stdv=True),xgb.callback.early_stop(early_stopping_rounds)],
'feval':mean_absolute_percentage_error_xgboost_cv}
if self.do_cross_val == False:
self.xgb_learning_params['feval'] = mean_absolute_percentage_error_xgboost
return
def get_paramgrid_1(self):
"""
This method must be overriden by derived class when its objective is not reg:linear
"""
param_grid = {'max_depth':[6], 'eta':[0.1], 'min_child_weight':[1],'silent':[1],
'objective':['reg:linear'],'colsample_bytree':[0.8],'subsample':[0.8], 'lambda ':[1]}
return param_grid
def get_paramgrid_2(self, param_grid):
"""
This method must be overriden by derived class if it intends to fine tune parameters
"""
self.ramdonized_search_enable = False
self.randomized_search_n_iter = 150
self.grid_search_display_result = True
param_grid['eta'] = [0.01] #train-mape:-0.448062+0.00334926 test-mape:-0.448402+0.00601761
# param_grid['max_depth'] = [7] #train-mape:-0.363007+0.00454276 test-mape:-0.452832+0.00321641
# param_grid['colsample_bytree'] = [0.8]
param_grid['max_depth'] = range(5,8) #train-mape:-0.363007+0.00454276 test-mape:-0.452832+0.00321641
param_grid['colsample_bytree'] = [0.6,0.8,1.0]
# param_grid['lambda'] = range(1,15)
# param_grid['max_depth'] = [3,4]
# param_grid['eta'] = [0.01,0.1] # 0.459426+0.00518875
# param_grid['subsample'] = [0.5] #0.458935+0.00522205
# param_grid['eta'] = [0.005] #0.457677+0.00526401
return param_grid
def get_learning_params(self):
"""e
This method must be overriden by derived class if it intends to fine tune parameters
"""
num_boost_round = 100
early_stopping_rounds = 5
kwargs = {'num_boost_round':num_boost_round, 'feval':mean_absolute_percentage_error_xgboost_cv,
'callbacks':[xgb.callback.print_evaluation(show_stdv=True),xgb.callback.early_stop(early_stopping_rounds)]}
return kwargs
if __name__ == "__main__":
obj= DidiXGBoostModel()
obj.run()
| 4,070 |
dump/python/multiprocessing-basics/multiprocessing_simply.py
|
zgo23/learn-programming
| 0 |
2172006
|
import multiprocessing
def worker():
"""worker function"""
print("worker")
return
if __name__ == "__main__":
jobs = []
for i in range(5):
p = multiprocessing.Process(target=worker)
jobs.append(p)
p.start()
| 253 |
api/pub_sub/pub_sub.py
|
cds-snc/scan-websites
| 5 |
2169340
|
from enum import Enum
import json
import os
from boto3wrapper.wrapper import get_session
from collections import defaultdict
from logger import log
# Import so that the application is aware of these Models
# Required so that models are initialized before they're referenced
from models.A11yReport import A11yReport # noqa: F401
from models.A11yViolation import A11yViolation # noqa: F401
from models.SecurityReport import SecurityReport # noqa: F401
from models.SecurityViolation import SecurityViolation # noqa: F401
from models.Organisation import Organisation # noqa: F401
from models.Scan import Scan # noqa: F401
from models.Template import Template # noqa: F401
from models.TemplateScan import TemplateScan # noqa: F401
from models.TemplateScanTrigger import TemplateScanTrigger # noqa: F401
from models.User import User # noqa: F401
class AvailableScans(Enum):
OWASP_ZAP = "OWASP Zap"
NUCLEI = "Nuclei"
AXE_CORE = "axe-core"
validator_list = {}
common_validations = [
"id",
"url",
"type",
"queue",
"product",
"revision",
"template_id",
]
# Append to common_validations if additional validations are required for only one template
validator_list[AvailableScans.OWASP_ZAP.value] = common_validations
validator_list[AvailableScans.NUCLEI.value] = common_validations
validator_list[AvailableScans.AXE_CORE.value] = common_validations
def validate_mandatory(payload, scan_type):
if scan_type not in validator_list:
raise ValueError("Mandatory validator not defined")
for mandatory_key in validator_list[scan_type]:
if mandatory_key not in payload:
raise ValueError(f"{mandatory_key} not defined")
def dispatch(payloads):
state_machine_queue = defaultdict(list)
for payload in payloads:
if "type" not in payload:
raise ValueError("type is not defined")
validate_mandatory(payload, payload["type"])
if payload["event"] == "sns":
send(payload["queue"], payload)
elif payload["event"] == "stepfunctions":
state_machine_queue[payload["queue"]].append(payload)
if state_machine_queue:
for queue in state_machine_queue:
execute(queue, state_machine_queue[queue])
def send(topic_arn, payload):
if topic_arn:
if os.environ.get("AWS_LOCALSTACK", False):
client = get_session().client("sns", endpoint_url="http://localstack:4566")
else:
client = get_session().client("sns")
client.publish(
TargetArn=topic_arn,
Message=json.dumps({"default": json.dumps(payload)}),
MessageStructure="json",
)
else:
log.error("Topic ARN is not defined")
def execute(state_machine, payloads):
if state_machine:
client = get_session().client("stepfunctions")
response = client.list_state_machines()
stateMachine = [
stateMachine
for stateMachine in response["stateMachines"]
if stateMachine.get("name") == state_machine
]
if stateMachine:
response = client.start_execution(
stateMachineArn=stateMachine[0]["stateMachineArn"],
input=json.dumps({"payload": payloads}),
)
else:
log.error(f"State machine: {state_machine} is not defined")
else:
log.error("State machine name is not defined")
| 3,443 |
app/app.py
|
tanaka0x/sifac_character_detect_app
| 0 |
2170324
|
import falcon
from falcon_multipart.middleware import MultipartMiddleware
from falcon_cors import CORS
from .images import Images
from .ssd import inference
cors = CORS(allow_all_origins=True, allow_all_methods=True, allow_all_headers=True)
api = application = falcon.API(middleware=[cors.middleware, MultipartMiddleware()])
api.add_route('/images', Images(infer_fn=inference))
| 378 |
demo/toga_demo/__main__.py
|
luizoti/toga
| 1,261 |
2170840
|
#!/usr/bin/env python
from toga_demo.app import main
def run():
main().main_loop()
if __name__ == '__main__':
run()
| 128 |
bot/__init__.py
|
eivl/code-jam-1
| 11 |
2171106
|
# coding=utf-8
import ast
import logging
import sys
from logging import Logger, StreamHandler
import discord.ext.commands.view
logging.TRACE = 5
logging.addLevelName(logging.TRACE, "TRACE")
def monkeypatch_trace(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'TRACE'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.trace("Houston, we have an %s", "interesting problem", exc_info=1)
"""
if self.isEnabledFor(logging.TRACE):
self._log(logging.TRACE, msg, args, **kwargs)
Logger.trace = monkeypatch_trace
# Set up logging
logging_handlers = [StreamHandler(stream=sys.stderr)]
logging.basicConfig(
format="%(asctime)s Bot: | %(name)30s | %(levelname)8s | %(message)s",
datefmt="%b %d %H:%M:%S",
level=logging.TRACE,
handlers=logging_handlers
)
log = logging.getLogger(__name__)
# Silence discord and websockets
logging.getLogger("discord.client").setLevel(logging.ERROR)
logging.getLogger("discord.gateway").setLevel(logging.ERROR)
logging.getLogger("discord.state").setLevel(logging.ERROR)
logging.getLogger("discord.http").setLevel(logging.ERROR)
logging.getLogger("websockets.protocol").setLevel(logging.ERROR)
def _skip_string(self, string: str) -> bool:
"""
Our version of the skip_string method from
discord.ext.commands.view; used to find
the prefix in a message, but allowing prefix
to ignore case sensitivity
"""
strlen = len(string)
if self.buffer.lower()[self.index:self.index + strlen] == string:
self.previous = self.index
self.index += strlen
return True
return False
def _get_word(self) -> str:
"""
Invokes the get_word method from
discord.ext.commands.view used to find
the bot command part of a message, but
allows the command to ignore case sensitivity,
and allows commands to have Python syntax.
Example of valid Python syntax calls:
------------------------------
bot.tags.set("test", 'a dark, dark night')
bot.help(tags.delete)
bot.hELP(tags.delete)
"""
pos = 0
while not self.eof:
try:
current = self.buffer[self.index + pos]
if current.isspace() or current == "(":
break
pos += 1
except IndexError:
break
self.previous = self.index
result = self.buffer[self.index:self.index + pos]
self.index += pos
next = None
# Check what's after the '('
if len(self.buffer) != self.index:
next = self.buffer[self.index + 1]
# Is it possible to parse this without syntax error?
syntax_valid = True
try:
ast.literal_eval(self.buffer[self.index:])
except SyntaxError:
log.warning("The command cannot be parsed by ast.literal_eval because it raises a SyntaxError.")
# TODO: It would be nice if this actually made the bot return a SyntaxError. ClickUp #1b12z # noqa: T000
syntax_valid = False
# Conditions for a valid, parsable command.
python_parse_conditions = (
current == "("
and next
and next != ")"
and syntax_valid
)
if python_parse_conditions:
log.debug(f"A python-style command was used. Attempting to parse. Buffer is {self.buffer}. "
"A step-by-step can be found in the trace log.")
# Parse the args
log.trace("Parsing command with ast.literal_eval.")
args = self.buffer[self.index:]
args = ast.literal_eval(args)
# Force args into container
if isinstance(args, str):
args = (args,)
# Type validate and format
new_args = []
for arg in args:
# Other types get converted to strings
if not isinstance(arg, str):
log.trace(f"{arg} is not a str, casting to str.")
arg = str(arg)
# Adding double quotes to every argument
log.trace(f"Wrapping all args in double quotes.")
new_args.append(f'"{arg}"')
# Add the result to the buffer
new_args = " ".join(new_args)
self.buffer = f"{self.buffer[:self.index]} {new_args}"
log.trace(f"Modified the buffer. New buffer is now {self.buffer}")
# Recalibrate the end since we've removed commas
self.end = len(self.buffer)
elif current == "(" and next == ")":
# Move the cursor to capture the ()'s
log.debug("User called command without providing arguments.")
pos += 2
result = self.buffer[self.previous:self.index + (pos+2)]
self.index += 2
if isinstance(result, str):
return result.lower() # Case insensitivity, baby
return result
# Monkey patch the methods
discord.ext.commands.view.StringView.skip_string = _skip_string
discord.ext.commands.view.StringView.get_word = _get_word
| 4,914 |
calculations.py
|
sirmammingtonham/efficientpicomputation
| 0 |
2172052
|
m1 = 1
digits = int(input("How many digits of pi would you like to compute?"))
m2 = 10**digits
# Mass of object at rest: m1
# Mass of moving object: m2
initVector = [0,1]
# [Velocity of m1, Velocity of m2]
currentVector = initVector
def mulA(vec):
msum = (m1 + m2)
a11 = (m1 - m2)/float(msum)
a12 = 2*m2/float(msum)
a21 = 2*m1/float(msum)
a22 = (m2 - m1)/float(msum)
v1 = a11*vec[0] + a12*vec[1]
v2 = a21*vec[0] + a22*vec[1]
return [v1, v2]
# When the lighter mass hits the wall,
# reverse its velocity but maintain velocity of larger mass
def mulW(vec):
v1 = (-1)*vec[0]
v2 = vec[1]
return [v1, v2]
# Checks if the speed of the inner/smaller mass is
# faster than the outer/larger one
def checkspeeds(v1, v2):
if (v1 <= 0 and v2 <=0):
if(abs(v1) >= abs(v2)):
return False
return True
collisioncount = 0
mtype = 'A'
while(checkspeeds(currentVector[0], currentVector[1])):
if (mtype == 'A'):
newVec = mulA(currentVector)
currentVector = newVec
collisioncount += 1 #increment counter on collision
mtype = 'W'
elif (mtype == 'W'):
newVec = mulW(currentVector)
currentVector = newVec
collisioncount += 1 #increment counter on collision
mtype = 'A'
print(f"Mass at moving initally: " )
print(f"Total number of collisions of the masses: {collisioncount}")
| 1,411 |
Build/python/mtm/ioc/IocAssertions.py
|
xjjon/Zenject
| 3,044 |
2171972
|
from mtm.util.Assert import *
import collections
def IsInstanceOf(*classes):
def test(obj):
assertThat(obj is None or isinstance(obj, classes), \
"Expected one of types '{0}' but found '{1}'".format(', '.join(map(lambda t: t.__name__, classes)), type(obj).__name__))
return test
def HasAttributes(*attributes):
def test(obj):
for each in attributes:
if not hasattr(obj, each): return False
return True
return test
def HasMethods(*methods):
def test(obj):
for methodName in methods:
assertThat(hasattr(obj, methodName), \
"Unable to find method '{0}' on object with type '{1}'".format(methodName, type(obj).__name__))
assertThat(isinstance(getattr(obj, methodName), collections.Callable))
return True
return test
| 817 |
decisionProject/vote/views.py
|
wldusdhso/likelion_ideaton2
| 0 |
2171808
|
from django.shortcuts import render, get_object_or_404, redirect
from .models import Question, Choice
from django.utils import timezone
from django.contrib.auth.models import User
# Create your views here.
def vote_list(request):
question_list = Question.objects.order_by('pub_date')
return render(request, 'vote_list.html', {'question_list': question_list})
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'detail.html', {'question': question})
def vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'vote.html', {'question': question})
def create(request):
if request.method =='POST':
new_question = Question()
new_question.title = request.POST['title']
new_question.pub_date = timezone.now()
new_question.writer = request.user
new_question.save()
for i in range(int(request.POST['count'])):
new_choice = Choice()
text = 'text'+str(i)
new_choice.question = new_question
new_choice.text = request.POST[text]
new_choice.save()
return redirect('vote:vote_list')
else :
return render(request, 'create.html')
def add_vote(request, question_id):
question = get_object_or_404(Question, pk=question_id)
question.total_votes += 1
selected_choice = question.choice_set.get(pk=request.POST['choice'])
selected_choice.votes += 1
selected_choice.save()
question.save()
return redirect('vote:detail', question_id)
def update(request, question_id):
if request.method =='POST':
upd_question = get_object_or_404(Question, pk=question_id)
upd_question.title = request.POST['title']
upd_question.pub_date = timezone.now()
upd_question.writer = request.POST['writer']
choice_set = upd_question.choice_set.all()
for elem in choice_set:
elem.delete()
upd_question.save()
# print(request.POST['count'])
for i in range(int(request.POST['count'])):
new_choice = Choice()
text = 'text'+str(i)
new_choice.question = upd_question
new_choice.text = request.POST[text]
new_choice.save()
return redirect('vote:vote_list')
else :
question = get_object_or_404(Question, pk=question_id)
return render(request, 'update.html', {'question': question})
def delete(request, question_id):
del_question = get_object_or_404(Question, pk=question_id)
del_question.delete()
return redirect('vote:vote_list')
def delete_choice(request, question_id, choice_id):
question = get_object_or_404(Question, pk=question_id)
deleted_choice = question.choice_set.get(pk=choice_id)
delete_choice.delete()
question.save()
return redirect('/')
| 2,920 |
src/models.py
|
kazqvaizer/checklistbot
| 5 |
2168627
|
from datetime import datetime, timedelta
from typing import Optional
import peewee as pw
from envparse import env
from telegram.update import Update
env.read_envfile()
db = pw.SqliteDatabase(env("DATABASE_URL"))
def _utcnow():
return datetime.utcnow()
def _get_recent_threshold():
return _utcnow() - timedelta(hours=2)
def _format_item(index: int, item: "TodoItem",) -> str:
line = f"{index}. {item.text}"
return f"<s>{line}</s>" if item.is_checked else line
class BaseModel(pw.Model):
created = pw.DateTimeField(default=_utcnow)
modified = pw.DateTimeField(null=True)
class Meta:
database = db
def save(self, *args, **kwargs):
if self.id is not None:
self.modified = _utcnow()
return super().save(*args, **kwargs)
class Chat(BaseModel):
chat_id = pw.BigIntegerField(unique=True)
chat_type = pw.CharField(null=True)
username = pw.CharField(null=True)
first_name = pw.CharField(null=True)
last_name = pw.CharField(null=True)
language_code = pw.CharField(default="en")
enabled = pw.BooleanField(default=True)
@property
def items(self) -> pw.Select:
return self.todo_items.select().order_by(TodoItem.id.asc())
@property
def has_not_checked_items(self) -> bool:
return self.items.where(TodoItem.is_checked == False).exists()
@property
def has_no_items_at_all(self) -> bool:
return not self.items.exists()
@property
def has_recently_modified_items(self) -> bool:
return self.items.where(TodoItem.modified > _get_recent_threshold()).exists()
@property
def has_recently_created_items(self) -> bool:
return self.items.where(TodoItem.created > _get_recent_threshold()).exists()
@property
def has_no_recent_activity(self) -> bool:
return not (self.has_recently_modified_items or self.has_recently_created_items)
def get_item_by_index(self, index: int) -> Optional["TodoItem"]:
return self.items.offset(index - 1).first() if index > 0 else None
def get_formatted_items(self) -> str:
return "\n".join([_format_item(*args) for args in enumerate(self.items, 1)])
def delete_items(self):
TodoItem.delete().where(TodoItem.chat == self).execute()
@classmethod
def get_or_create_from_update(cls, update: Update) -> "Chat":
chat_id = update.effective_chat.id
defaults = dict(
chat_type=update.effective_chat.type,
username=update.effective_chat.username,
first_name=update.effective_chat.first_name,
last_name=update.effective_chat.last_name,
language_code=update.effective_user.language_code or "en",
)
return cls.get_or_create(chat_id=chat_id, defaults=defaults)[0]
class Message(BaseModel):
message_id = pw.IntegerField(null=True)
chat = pw.ForeignKeyField(Chat, backref="messages")
date = pw.DateTimeField(null=True)
text = pw.CharField(null=True)
@classmethod
def create_from_update(cls, update: Update) -> "Message":
return cls.create(
chat=Chat.get_or_create_from_update(update),
message_id=update.effective_message.message_id,
date=update.effective_message.date,
text=update.effective_message.text,
)
class TodoItem(BaseModel):
chat = pw.ForeignKeyField(Chat, backref="todo_items")
is_checked = pw.BooleanField(default=False)
text = pw.CharField()
app_models = BaseModel.__subclasses__()
| 3,538 |
tuchong/tuchong/items.py
|
XuShengYuu/Tuchong
| 2 |
2171998
|
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
# import scrapy
from scrapy import Item, Field
class TuchongItem(Item):
# define the fields for your item here like:
# name = scrapy.Field()
collection = 'images'
author_id = Field()
comments = Field()
delete = Field()
favorites = Field()
image_count = Field()
images = Field()
post_id = Field()
published_at = Field()
site = Field()
tags = Field()
title = Field()
title_image = Field()
type = Field()
update = Field()
url = Field()
| 659 |
WebMirror/management/rss_parser_funcs/feed_parse_extractRisingDragons.py
|
fake-name/ReadableWebProxy
| 193 |
2169861
|
def extractRisingDragons(item):
"""
# Rising Dragons Translation
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'God and Devil World' in item['tags'] and 'Release' in item['tags']:
return buildReleaseMessageWithType(item, '<NAME>', vol, chp, frag=frag, postfix=postfix)
return False
| 400 |
preprocessing/use_cases/dialogues.py
|
MinCiencia/ECQQ
| 4 |
2172238
|
import use_cases.utils.textools as tt
from use_cases.utils.comunas import get_comunas_id
import pandas as pd
import numpy as np
import re, os
def change_valid_to_bool(x):
if x == '1':
x = True
else:
x = False
return x
def create_table_dialogues(frame, filter):
new_frame = frame.copy()
filter = filter.rename(columns={'ID_diag': 'ID'})
new_frame['Grupo'] = tt.check_nan(new_frame['Grupo'])
new_frame = pd.merge(new_frame, filter, how="inner", on=["ID"])
new_frame = new_frame[['ID Archivo', 'Fecha', 'Hora Inicio',
'Hora Termino', 'Lugar', 'Dirección',
'Comuna', 'Participantes',
'Grupo', 'Valido']]
new_frame = tt.to_unicode(new_frame)
new_frame = tt.eliminate_nrs(new_frame)
new_frame = new_frame.rename(columns={'file_id':'diag_id'})
new_frame.columns =['id', 'date', 'init_time', 'end_time',
'location', 'address', 'comuna_id', 'n_members',
'group_name', 'valid']
new_frame = new_frame.apply(lambda x: get_comunas_id(x, 'comuna_id'), 1)
new_frame['valid'] = new_frame['valid'].apply(lambda x: change_valid_to_bool(x), 1)
return new_frame
| 1,239 |
035.py
|
xianlinfeng/project_euler_python3
| 0 |
2172236
|
import eulerlib
def is_circular_prime(n):
s = str(n)
return all(eulerlib.is_prime(int(s[i:] + s[:i])) for i in range(len(s)))
def compute():
ans = sum(1 for i in range(1, 1000000) if is_circular_prime(i))
return ans
if __name__ == "__main__":
print(compute())
| 286 |
notebooks/cnn_tester.py
|
MichoelSnow/data_science
| 0 |
2171426
|
from fastai.groups.default_cnn import *
PATH = '/data/msnow/nih_cxr/'
arch = resnet34
sz = 64
bs = 64
# data = get_data(sz,bs)
# learn = ConvLearner.pretrained(arch, data)
# def get_data(sz, bs):
# tfms = tfms_from_model(arch, sz, aug_tfms=transforms_basic, max_zoom=1.05)
# return ImageClassifierData.from_csv(PATH, 'trn', f'{PATH}data_trn.csv', tfms=tfms,
# val_idxs=val_idx, test_name='tst', bs=bs, cat_separator='|')
| 452 |
backend/apps/workers/migrations/0002_rename_charge_worker_position.py
|
jorgejimenez98/backend-evaluacion-desempenno
| 0 |
2172049
|
# Generated by Django 3.2.2 on 2021-06-02 05:35
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('workers', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='worker',
old_name='charge',
new_name='position',
),
]
| 354 |
dataset.py
|
bigpo/CIFAR-ZOO
| 0 |
2171792
|
import os.path as osp
from PIL import Image
import numpy as np
from torch.utils.data import Dataset
class CustomDataset(Dataset):
def __init__(self,
ann_file,
root,
transform=None,
train=True):
# prefix of images path
self.img_prefix = root
# load annotations (and proposals)
self.img_infos = self.load_annotations(ann_file)
self.is_train = train
self.transform = transform
def __len__(self):
return len(self.img_infos)
def load_annotations(self, ann_file):
with open(ann_file) as fp:
img_infos = [line.rstrip('\n') for line in fp]
return [{'filename': line.split(' ')[0],
'label': line.split(' ')[1]} for line in img_infos]
def get_ann_info(self, idx):
return self.img_infos[idx]['label']
def _rand_another(self):
pool = range(len(self.img_infos))
return np.random.choice(pool)
def __getitem__(self, idx):
if not self.is_train:
return self.prepare_test_img(idx)
while True:
data = self.prepare_train_img(idx)
if data is None:
idx = self._rand_another()
continue
return data
def prepare_train_img(self, idx):
img_info = self.img_infos[idx]
img = Image.open(osp.join(self.img_prefix, img_info['filename']))
img = self.transform(img)
label = self.get_ann_info(idx)
return img, int(label)
def prepare_test_img(self, idx):
"""Prepare an image for testing (multi-scale and flipping)"""
img_info = self.img_infos[idx]
img = Image.open(osp.join(self.img_prefix, img_info['filename']))
img = self.transform(img)
label = self.get_ann_info(idx)
return img, int(label)
| 1,878 |
pulotu/datatables.py
|
blurks/pulotu
| 0 |
2172216
|
from sqlalchemy.orm import joinedload
from clld.db.util import get_distinct_values
from clld.db.models import common
from clld.web import datatables
from clld.web.datatables.base import LinkCol, Col, LinkToMapCol
from clld.web.datatables.parameter import Parameters
from clld.web.datatables.value import Values, ValueNameCol, RefsCol, ValueSetCol
from clldutils.misc import dict_merged, slug
from pulotu import models
class Cultures(datatables.Languages):
def get_options(self):
opts = datatables.Languages.get_options(self)
opts['iDisplayLength'] = 150
return opts
def col_defs(self):
return [
LinkCol(self, 'name'),
Col(self, 'ethonyms', model_col=models.Variety.ethonyms),
Col(self,
'latitude',
sDescription='<small>The geographic latitude</small>'),
Col(self,
'longitude',
sDescription='<small>The geographic longitude</small>'),
LinkToMapCol(self, 'm'),
]
class CategoryCol(Col):
def order(self):
return models.Feature.category_ord
class SectionCol(Col):
def order(self):
return models.Feature.section_ord
class SubsectionCol(Col):
def order(self):
return models.Feature.subsection_ord
class Questions(Parameters):
def __init__(self, req, model, **kw):
self.focus = kw.pop('focus', req.params.get('focus', None))
if self.focus:
kw['eid'] = 'dt-parameters-' + slug(self.focus)
super(Questions, self).__init__(req, model, **kw)
def xhr_query(self):
return dict_merged(super(Questions, self).xhr_query(), focus=self.focus)
def base_query(self, query):
if self.focus:
query = query.filter(models.Feature.category == self.focus)
return query
def get_options(self):
opts = super(Questions, self).get_options()
opts['aaSorting'] = [[0, 'asc'], [1, 'asc'], [2, 'asc']]
return opts
def col_defs(self):
return [
#CategoryCol(self, 'category', model_col=models.Feature.category, choices=get_distinct_values(models.Feature.category)),
SectionCol(self, 'section', model_col=models.Feature.section, choices=get_distinct_values(models.Feature.section)),
SubsectionCol(self, 'subsection', model_col=models.Feature.subsection),
LinkCol(self, 'name'),
]
class ResponseCol(ValueNameCol):
def format(self, item):
return self.get_attrs(item)['label']
class Responses(Values):
def col_defs(self):
name_col = ResponseCol(self, 'value')
if self.parameter and self.parameter.domain:
name_col.choices = [de.name for de in self.parameter.domain]
res = []
if self.parameter:
return res + [
LinkCol(self,
'language',
model_col=common.Language.name,
get_object=lambda i: i.valueset.language),
name_col,
RefsCol(self, 'source'),
LinkToMapCol(self, 'm', get_object=lambda i: i.valueset.language),
]
if self.language:
return res + [
name_col,
LinkCol(self,
'parameter',
sTitle=self.req.translate('Parameter'),
model_col=common.Parameter.name,
get_object=lambda i: i.valueset.parameter),
RefsCol(self, 'source'),
]
return res + [
name_col,
ValueSetCol(self, 'valueset', bSearchable=False, bSortable=False),
]
def includeme(config):
config.register_datatable('languages', Cultures)
config.register_datatable('parameters', Questions)
config.register_datatable('values', Responses)
| 3,913 |
declutterDesktop.py
|
goonerlagoon/Declutter-Desktop
| 0 |
2172231
|
'''
small script for organizing my desktop by clearing everything except
shortcut links and placing them in their appropriate location (i.e. "home_base").
Author: <NAME>.
Date: 12-11-2021
'''
from pathlib import Path
def main():
desktop_folder = Path.home() / 'Desktop'
home_base = Path.home() / 'Documents'
for file_obj in desktop_folder.glob('*/'):
if file_obj.is_dir():
try:
file_obj.replace(home_base / file_obj.parts[-1]) # parts[-1] grabs the file name plus ext
except IOError as err:
print(f"couldn't move {file_obj}. here's the error msg: {err}")
continue
except Exception as err:
print(f"couldnt move {file_obj}. err msg: {err}")
continue
elif file_obj.suffix == '.lnk':
continue
else:
# extract the extension of each file and make it the dir name
# if it doesnt already exist
sfx = file_obj.suffix[1:].upper() + 's'
try:
extension_dir = home_base / sfx
extension_dir.mkdir(exist_ok=True)
file_obj.replace(extension_dir / file_obj.parts[-1])
except Exception as err:
print(f"couldnt move {file_obj}. err msg: {err}")
continue
print("*" * 40)
print("PROCESS COMPLETE!")
if __name__ == '__main__':
main()
| 1,481 |
src/codersstrikeback.py
|
newlyedward/datascinece
| 2 |
2170503
|
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def get_distance(self, point):
return math.sqrt(self.get_distance2(point))
def get_distance2(self, point):
return (self.x - point.x) ** 2 + (self.y - point.y) ** 2
@property
def angle(self):
return self.get_relative_angle(Point(0, 0))
def get_relative_angle(self, point):
"""
获取输入点相对于当前点的x轴轴角度
x轴:16000 units wide y轴:9000 units high
X=0, Y=0 is the top left pixel
An angle of 0 corresponds to facing east, 90 is south,
180 west and 270 north
:param point: 指向的目标点,当前点位起点
:return:
"""
if self == point:
return 0
d = self.get_distance(point)
dx = (point.x - self.x) / d
angle = math.acos(dx) * 180 / math.pi
if self.y < point.y:
angle = 360 - angle
return angle
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __repr__(self):
return "({}, {})".format(self.x, self.y)
class Unit(Point):
def __init__(self, x, y, radius):
super().__init__(x, y)
self.radius = radius
def collision(self, unit):
pass
def bounce(self, unit):
pass
class Pod(Unit):
def __init__(self, x, y, checkpoint, radius=400):
super().__init__(x, y, radius)
self.checkpoint = checkpoint
self.radius = radius
# 假设开始就朝向目标
self.orient = self.get_relative_angle(checkpoint)
self.checkpoint_angle = 0
# 速度分解
self.vx = 0
self.vy = 0
self.timeout = 100
# def set_orient(self, checkpoint_angle):
# # 如果有checkpoint_angle 输入
# self.checkpoint_angle = checkpoint_angle
# self.orient = (self.get_relative_angle(self.checkpoint) + 180 - checkpoint_angle) % 360
def set_checkpoint(self, checkpoint):
# 改变目标后,pod的方向orient不会变,需要修改checkpoint_angle
self.checkpoint = checkpoint
self.checkpoint_angle = self.cal_checkpoint_angle()
def cal_checkpoint_angle(self):
angle = self.get_relative_angle(self.checkpoint)
# 统一顺时针(往右)转动为正值,往左转是负值,返回值为 [-180, 180]
right = angle - self.orient if self.orient <= angle else 360 - self.orient + angle
left = self.orient - angle if self.orient >= angle else self.orient + 360 - angle
if right < left:
return right
else:
return -left
def rotate(self):
"""
最大转向角度为+-18度,实际达不到,可能跟thrust有关系
:return:
"""
if self.checkpoint_angle > 18:
delta_angle = 18
elif self.checkpoint_angle < -18:
delta_angle = -18
else:
delta_angle = self.checkpoint_angle
self.orient += delta_angle
if self.orient >= 360:
self.orient -= 360
elif self.orient < 0:
self.orient += 360
def cal_velocity(self, thrust):
"""
速度有一个上限
:param thrust:
:return:
"""
radian = self.orient * math.pi / 180
self.vx += math.cos(radian) * thrust
self.vy += math.sin(radian) * thrust
def move(self, turn=1):
"""
如果有碰撞,turn设置为0.5, 一半为一个turn的移动
:param turn:
:return:
"""
self.x += self.vx * turn
self.y += self.vy * turn
def end(self):
"""
Once the pod has moved we need to apply friction and round (or truncate) the values.
:return:
"""
self.x = round(self.x)
self.y = round(self.y)
# 摩擦系数 0.85
friction = 0.85
self.vx = int(self.vx * friction)
self.vy = int(self.vy * friction)
# Don't forget that the timeout goes down by 1 each turn.
# It is reset to 100 when you pass a checkpoint
self.timeout -= 1
def simulate_a_turn(self, thrust):
self.rotate()
self.cal_velocity(thrust)
self.move()
self.end()
if __name__ == "__main__":
# from src.codersstrikeback import Unit
mypos = Point(10705, 5691)
target = Point(3571, 5202)
| 4,217 |
url_shortener/tests.py
|
wandering-tales/django-miny-tiny-url
| 1 |
2170768
|
import pytest
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from url_shortener.baseconv import base10to62
from url_shortener.models import ShortURL
from url_shortener.serializers import ShortURLSerializer
pytestmark = pytest.mark.django_db
class ShortURLTests(APITestCase):
def test_create_short_url(self):
"""
Ensure we can create a new short URL object
and that the response data matches the current object instance.
"""
# Create a short URL
url = reverse('shorturl-list')
data = {'url': 'https://en.wikipedia.org/wiki/Test-driven_development'}
response = self.client.post(url, data, format='json')
# Verify response status
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
# Check if the number of short URL instances is one
self.assertEqual(ShortURL.objects.count(), 1)
# Retrieve the first (and only) short URL instance
instance = ShortURL.objects.get()
# Check if the 'url' attribute in the response data
# matches the 'url' field of the model instance
self.assertEqual(response.data['url'], instance.url)
# Check if the 'short_url' attribute in the response data
# matches the one computed by base 10 to base 62 converter
self.assertEqual(response.data['short_url'], base10to62.from_decimal(instance.id))
# Check if the 'usage_count' attribute in the response data is equal to 0
self.assertEqual(response.data['usage_count'], 0)
def test_forward_short_url(self):
"""
Ensure a short URL call is permanently redirected to the original URL.
"""
# Create a short URL
url = reverse('shorturl-list')
data = {'url': 'http://lkml.iu.edu/hypermail/linux/kernel/1510.3/02866.html'}
response = self.client.post(url, data, format='json')
short_url = response.data['short_url']
# Call short URL
url = reverse('shorturl-detail', args=[short_url])
response = self.client.get(url)
# Verify the response status code is a 301
self.assertEqual(response.status_code, status.HTTP_301_MOVED_PERMANENTLY)
# Verify the location header is set to the target URL
self.assertEqual(response.get('location'), data['url'])
def test_info_short_url(self):
"""
Ensure the short URL info API response is the serialization of a short URL instance.
"""
# Create a short URL
url = reverse('shorturl-list')
data = {'url': 'https://uwsgi-docs.readthedocs.io/en/latest/articles/TheArtOfGracefulReloading.html'}
response = self.client.post(url, data, format='json')
short_url = response.data['short_url']
# Get short URL info
url = reverse('shorturl-info', args=[short_url])
response = self.client.get(url)
# Retrieve the first (and only) short URL instance
instance = ShortURL.objects.get()
# Serialize the short URL instance
serializer = ShortURLSerializer(instance)
# Ensure the short URL info API response is equal to the serialized data
self.assertEqual(response.data, serializer.data)
def test_usage_count(self):
"""
Ensure the usage count is increased at every call to a short URL.
"""
# Create a short URL
url = reverse('shorturl-list')
data = {'url': 'https://docs.djangoproject.com/en/2.0/ref/urlresolvers/#reverse'}
response = self.client.post(url, data, format='json')
short_url = response.data['short_url']
# Call short URL three times
url = reverse('shorturl-detail', args=[short_url])
self.client.get(url)
self.client.get(url)
self.client.get(url)
# Get short URL info
url = reverse('shorturl-info', args=[short_url])
response = self.client.get(url)
# Verify the current usage count is equal to 3
self.assertEqual(response.data['usage_count'], 3)
def test_duplicated_urls(self):
"""
Ensure it's impossible to create two short URLs for the same original URL.
"""
# Create a short URL
url = reverse('shorturl-list')
data = {'url': 'https://www.djangosnippets.org/snippets/1431/'}
response = self.client.post(url, data, format='json')
# Verify response status
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
# Create a short URL for the same URL
response = self.client.post(url, data, format='json')
# Verify response status
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
| 4,781 |
tests/modules/newsgroups/test_newsgroups.py
|
rlin0/donut
| 0 |
2172212
|
import flask
from donut.modules.newsgroups import helpers
from donut.testing.fixtures import client
from datetime import datetime
def test_get_newsgroups(client):
assert helpers.get_newsgroups() == [{
'group_name': 'Donut Devteam',
'group_id': 1
}, {
'group_name': 'IHC',
'group_id': 3
}]
def test_get_my_newsgroups(client):
assert helpers.get_my_newsgroups(5) == [{
'group_name': 'IHC',
'group_id': 3
}]
def test_get_can_send_groups(client):
assert helpers.get_my_newsgroups(5, True) == [{
'group_name': 'IHC',
'group_id': 3
}, {
'group_name':
'Donut Devteam',
'group_id':
1
}]
assert helpers.get_my_newsgroups(100, True) == [{
'group_name':
'Donut Devteam',
'group_id':
1
}]
def test_get_my_positions(client):
assert helpers.get_posting_positions(3, 5) == [{
'pos_name': 'IHC Member',
'pos_id': 5
}]
assert helpers.get_posting_positions(3, 1) == ()
def test_get_user_actions(client):
assert helpers.get_user_actions(5, 3) == {
'send': 1,
'control': 0,
'receive': 1
}
def test_email_newsgroup(client):
data = {
'group': 1,
'subject': 'Subj',
'plain': 'msg to donut',
'poster': 'Head'
}
helpers.insert_email(1, data)
res = helpers.get_past_messages(1, 1)[0]
expected = {
'subject': 'Subj',
'message': 'msg to donut',
'user_id': 1,
'post_as': 'Head'
}
for key in expected:
assert res[key] == expected[key]
expected['group_name'] = 'Donut Devteam'
expected['group_id'] = 1
res = helpers.get_post(1)
for key in expected:
assert res[key] == expected[key]
def test_subscriptions(client):
helpers.apply_subscription(5, 1)
assert helpers.get_applications(1) == [{
'user_id': 5,
'group_id': 1,
'name': '<NAME>',
'email': '<EMAIL>'
}]
helpers.remove_application(5, 1)
assert helpers.get_applications(1) == ()
def test_get_owners(client):
assert helpers.get_owners(2) == {
'President': [{
'user_id': 2,
'full_name': '<NAME>'
}, {
'user_id': 4,
'full_name': '<NAME>'
}]
}
| 2,362 |
tlx/util/cli_apps/get_aws_creds.py
|
eL0ck/tlx
| 0 |
2168195
|
#!/usr/bin/env python
from __future__ import print_function
import click
import os
import sys
from tlx.util import Session
@click.command(context_settings=dict(max_content_width=120))
@click.option('--profile', '-p', default='default', help="A profile defined in `~/.aws/credentials`. If it requires an MFA token a prompt will be given")
@click.option('--quiet', default=False, is_flag=True, help='If using the outputs directly, see --help.')
def main(profile, quiet):
"""
GET AWS CREDS (GAC):
Gets temporary AWS session from a profile (user or role). Allows you to export into your shell and run tools expecting the AWS standard environment variables. Namely:
\b
- AWS_ACCESS_KEY_ID
- AWS_SECRET_ACCESS_KEY
- AWS_SESSION_TOKEN
Your aws credentials file (default: `~/.aws/credentials`) should be configured as follows:
A Role profile would look like:
\b
[roleprofilename]
region = us-east-2
role_arn = arn:aws:iam::************:role/<IAM_Role_name>
mfa_serial = arn:aws:iam::<AccountID>:mfa/<IAM_user_name>
source_profile = default
Or a user profile might look like:
\b
[userprofilename]
aws_access_key_id = AKIA****************
aws_secret_access_key = <KEY>
mfa_serial = arn:aws:iam::<AccountID>:mfa/<IAM_user_name>
region = ap-southeast-2
Notice that the user profile contains `mfa_serial`. This is not standard aws config however it is supported by GAC. If it is available, GAC will use it to get temporary session tokens by requesting your associated MFA code. This is useful for when your user has higher account priviledges that require MFA auth.
Returns: commands to copy to your shell terminal
-------------------------- ADVANCED USAGE --------------------------------------
Consider appending the following to your `.bashrc` to have the environment variables set automatically:
\b
gac ()
{
for i in "$( get-aws-creds "$@" --quiet)";
do
eval "${i}";
done
}
Or alternatively, send the variables to a file and source them from your profile so that all terminal sessions receive the same temporary credentials:
\b
$ get-aws-creds --quiet > /tmp/awscreds
$ source /tmp/awscreds
"""
# Issue #15 - We may be trying to assume another role from a
# shell that has previously had its temporary variables populated
if 'AWS_SECRET_ACCESS_KEY' in os.environ:
del os.environ['AWS_SECRET_ACCESS_KEY']
if 'AWS_ACCESS_KEY_ID' in os.environ:
del os.environ['AWS_ACCESS_KEY_ID']
try:
session = Session(profile=profile)
creds = session.get_session_creds()
except Exception as e:
print("{}: {}".format(type(e).__name__, e))
sys.exit(1)
if not quiet:
print("Keys and token for profile: '{profile}'".format(profile=profile))
print("Paste the following into your shell:\n")
print("export AWS_ACCESS_KEY_ID={}".format(creds.access_key))
print("export AWS_SECRET_ACCESS_KEY={}".format(creds.secret_key))
# non-temporary keys are returned by the boto3.Session if the
# user is not required to use MFA token. Printing out a null
# field for this will cause malformed errors when using.
if creds.token:
print("export AWS_SESSION_TOKEN={}".format(creds.token))
| 3,610 |
2021/day21.py
|
tangarts/advent-of-code
| 0 |
2172013
|
from functools import lru_cache
from itertools import product
from advent_of_code.core import parse_input
raw = """Player 1 starting position: 4
Player 2 starting position: 8"""
test = parse_input(raw, parser=lambda s: int(s[-1]))
positions = parse_input('data/input21.txt', parser=lambda s: int(s[-1]), test=False)
def turn(position, roll):
return (position + roll) % 10
def part1(position):
# player, starting_pos
score = [0, 0]
roll = 0
j = 1
while True:
for i in [0, 1]:
roll += 3
position[i] = turn(position[i], 3 * (j + 1))
j = (j + 3) % 100
score[i] += position[i] if position[i] != 0 else 10
# when statement
if score[i] > 999:
return min(score) * roll
# part1
assert part1(positions) == 926610
all_states = [sum(x) for x in product([1, 2, 3], repeat=3)]
@lru_cache(maxsize=None)
def play(position1, position2, score1, score2):
if score1 >= 21:
return 1, 0
if score2 >= 21:
return 0, 1
win1 = win2 = 0
for state in all_states:
new_position = turn(position1, state)
new_score = score1 + (new_position if new_position else 10)
w2, w1 = play(position2, new_position, score2, new_score)
win1 += w1
win2 += w2
return win1, win2
# part2
assert max(play(6, 2, 0, 0)) == 146854918035875
| 1,395 |
server/algos/euler/tests/integration/test_euler.py
|
yizhang7210/Acre
| 2 |
2170543
|
# pylint: disable=missing-docstring
import datetime
import math
from decimal import Decimal
from algos.euler.models import training_samples as ts
from algos.euler.models import predictions, predictors
from algos.euler.runner import Euler
from core.models import instruments
from datasource.models import candles
from django.test import TestCase
from .test_setup import TestSetup
TWO_PLACES = Decimal('0.01')
class EulerAlgoTest(TestCase):
@classmethod
def setUpClass(cls):
super(EulerAlgoTest, cls).setUpClass()
TestSetup.set_up_instruments()
TestSetup.set_up_candles()
cls.set_up_predictors()
@classmethod
def set_up_predictors(cls):
params = {'max_depth': 3, 'min_samples_split': 2}
predictor = predictors.create_one(
name='treeRegressor', parameters=params, is_active=True)
predictor.save()
@classmethod
def tearDownClass(cls):
super(EulerAlgoTest, cls).tearDownClass()
predictors.delete_all()
predictions.delete_all()
ts.delete_all()
candles.delete_all()
instruments.delete_all()
def test_euler_end_of_day(self):
# Given
today = datetime.date(2017, 12, 6)
# When
euler_thread = Euler(today, cv_fold=2)
euler_thread.run()
# Then
new_predictions = predictions.get_all(['date'])
self.assertEqual(len(new_predictions), 1)
self.assertEqual(new_predictions[0].date, today)
self.assertFalse(math.isnan(new_predictions[0].score))
| 1,560 |
odoo/base-addons/account/tests/test_invoice_tax_amount_by_group.py
|
LucasBorges-Santos/docker-odoo
| 0 |
2171564
|
# -*- coding: utf-8 -*-
from odoo.addons.account.tests.account_test_savepoint import AccountTestInvoicingCommon
from odoo.tests import tagged
@tagged('post_install', '-at_install')
class TestInvoiceTaxAmountByGroup(AccountTestInvoicingCommon):
@classmethod
def setUpClass(cls, chart_template_ref=None):
super().setUpClass(chart_template_ref=chart_template_ref)
cls.tax_group1 = cls.env['account.tax.group'].create({'name': '1'})
cls.tax_group2 = cls.env['account.tax.group'].create({'name': '2'})
def assertAmountByTaxGroup(self, invoice, expected_values):
current_values = [(x[6], x[2], x[1]) for x in invoice.amount_by_group]
self.assertEqual(current_values, expected_values)
def test_multiple_tax_lines(self):
tax_10 = self.env['account.tax'].create({
'name': "tax_10",
'amount_type': 'percent',
'amount': 10.0,
'tax_group_id': self.tax_group1.id,
})
tax_20 = self.env['account.tax'].create({
'name': "tax_20",
'amount_type': 'percent',
'amount': 20.0,
'tax_group_id': self.tax_group2.id,
})
invoice = self.env['account.move'].create({
'type': 'out_invoice',
'partner_id': self.partner_a.id,
'invoice_date': '2019-01-01',
'invoice_line_ids': [
(0, 0, {
'name': 'line',
'account_id': self.company_data['default_account_revenue'].id,
'price_unit': 1000.0,
'tax_ids': [(6, 0, (tax_10 + tax_20).ids)],
}),
(0, 0, {
'name': 'line',
'account_id': self.company_data['default_account_revenue'].id,
'price_unit': 1000.0,
'tax_ids': [(6, 0, tax_10.ids)],
}),
(0, 0, {
'name': 'line',
'account_id': self.company_data['default_account_revenue'].id,
'price_unit': 1000.0,
'tax_ids': [(6, 0, tax_20.ids)],
}),
]
})
self.assertAmountByTaxGroup(invoice, [
(self.tax_group1.id, 2000.0, 200.0),
(self.tax_group2.id, 2000.0, 400.0),
])
# Same but both are sharing the same tax group.
tax_20.tax_group_id = self.tax_group1
invoice.invalidate_cache(['amount_by_group'])
self.assertAmountByTaxGroup(invoice, [
(self.tax_group1.id, 3000.0, 600.0),
])
def test_zero_tax_lines(self):
tax_0 = self.env['account.tax'].create({
'name': "tax_0",
'amount_type': 'percent',
'amount': 0.0,
})
invoice = self.env['account.move'].create({
'type': 'out_invoice',
'partner_id': self.partner_a.id,
'invoice_date': '2019-01-01',
'invoice_line_ids': [
(0, 0, {
'name': 'line',
'account_id': self.company_data['default_account_revenue'].id,
'price_unit': 1000.0,
'tax_ids': [(6, 0, tax_0.ids)],
}),
]
})
self.assertAmountByTaxGroup(invoice, [
(tax_0.tax_group_id.id, 1000.0, 0.0),
])
def test_tax_affect_base_1(self):
tax_10 = self.env['account.tax'].create({
'name': "tax_10",
'amount_type': 'percent',
'amount': 10.0,
'tax_group_id': self.tax_group1.id,
'price_include': True,
'include_base_amount': True,
})
tax_20 = self.env['account.tax'].create({
'name': "tax_20",
'amount_type': 'percent',
'amount': 20.0,
'tax_group_id': self.tax_group2.id,
})
invoice = self.env['account.move'].create({
'type': 'out_invoice',
'partner_id': self.partner_a.id,
'invoice_date': '2019-01-01',
'invoice_line_ids': [
(0, 0, {
'name': 'line',
'account_id': self.company_data['default_account_revenue'].id,
'price_unit': 1100.0,
'tax_ids': [(6, 0, (tax_10 + tax_20).ids)],
}),
(0, 0, {
'name': 'line',
'account_id': self.company_data['default_account_revenue'].id,
'price_unit': 1100.0,
'tax_ids': [(6, 0, tax_10.ids)],
}),
(0, 0, {
'name': 'line',
'account_id': self.company_data['default_account_revenue'].id,
'price_unit': 1000.0,
'tax_ids': [(6, 0, tax_20.ids)],
}),
]
})
self.assertAmountByTaxGroup(invoice, [
(self.tax_group1.id, 2000.0, 200.0),
(self.tax_group2.id, 2100.0, 420.0),
])
# Same but both are sharing the same tax group.
tax_20.tax_group_id = self.tax_group1
invoice.invalidate_cache(['amount_by_group'])
self.assertAmountByTaxGroup(invoice, [
(self.tax_group1.id, 3000.0, 620.0),
])
def test_tax_affect_base_2(self):
tax_10 = self.env['account.tax'].create({
'name': "tax_10",
'amount_type': 'percent',
'amount': 10.0,
'tax_group_id': self.tax_group1.id,
'include_base_amount': True,
})
tax_20 = self.env['account.tax'].create({
'name': "tax_20",
'amount_type': 'percent',
'amount': 20.0,
'tax_group_id': self.tax_group1.id,
})
tax_30 = self.env['account.tax'].create({
'name': "tax_30",
'amount_type': 'percent',
'amount': 30.0,
'tax_group_id': self.tax_group2.id,
'include_base_amount': True,
})
invoice = self.env['account.move'].create({
'type': 'out_invoice',
'partner_id': self.partner_a.id,
'invoice_date': '2019-01-01',
'invoice_line_ids': [
(0, 0, {
'name': 'line',
'account_id': self.company_data['default_account_revenue'].id,
'price_unit': 1000.0,
'tax_ids': [(6, 0, (tax_10 + tax_20).ids)],
}),
(0, 0, {
'name': 'line',
'account_id': self.company_data['default_account_revenue'].id,
'price_unit': 1000.0,
'tax_ids': [(6, 0, (tax_30 + tax_10).ids)],
}),
]
})
self.assertAmountByTaxGroup(invoice, [
(self.tax_group1.id, 2300.0, 450.0),
(self.tax_group2.id, 1000.0, 300.0),
])
# Same but both are sharing the same tax group.
tax_30.tax_group_id = self.tax_group1
invoice.invalidate_cache(['amount_by_group'])
self.assertAmountByTaxGroup(invoice, [
(self.tax_group1.id, 2000.0, 750.0),
])
| 7,324 |
object_detector/config.py
|
vaibhavhariaramani/Object-detector-from-HOG-Linear-SVM-framework
| 26 |
2172295
|
"""
Set config variables
"""
import configparser as cp
import json
import random
import numpy as np
config = cp.RawConfigParser()
config.read('../data/config/config.cfg')
WINDOW_SIZE = json.loads(config.get('hog', 'window_size'))
WINDOW_STEP_SIZE = config.getint('hog', 'window_step_size')
ORIENTATIONS = config.getint('hog', 'orientations')
PIXELS_PER_CELL = json.loads(config.get('hog', 'pixels_per_cell'))
CELLS_PER_BLOCK = json.loads(config.get('hog', 'cells_per_block'))
VISUALISE = config.getboolean('hog', 'visualise')
NORMALISE = config.get('hog', 'normalise')
if NORMALISE == 'None':
NORMALISE = None
THRESHOLD = config.getfloat('nms', 'threshold')
MODEL_PATH = config.get('paths', 'model_path')
PYRAMID_DOWNSCALE = config.getfloat('general', 'pyramid_downscale')
POS_SAMPLES = config.getint('general', 'pos_samples')
NEG_SAMPLES = config.getint('general', 'neg_samples')
RANDOM_STATE = 31
random.seed(RANDOM_STATE)
np.random.seed(RANDOM_STATE)
| 967 |
Desafios/desafio017.py
|
ward910/Python-Aprendizado
| 2 |
2171632
|
from math import hypot
ca = float(input('Digite cateto adjacente: '))
co = float(input('Digie cateto oposto: '))
print(f'A Hipotenusa é {hypot(ca, co):.2f}')
| 160 |
stackoversight/pipeline/pipelineobject.py
|
walker76/stackoversight
| 3 |
2171233
|
from pipeline.pipelineoutput import PipelineOutput
from taskqueue.redis_queue import RedisQueue
from taskqueue.redis_connection import RedisConnection
from redis import ConnectionError
from rq import Connection, Worker, Queue
import time
import copy
# from queue import Queue
class Pipeline(object):
__redis_initialized = False
# Steps: The pipeline steps to accomplish
# Redis_key: unknown
# Items: Initial queue of code snippets
def __init__(self, steps=None, snippets=None):
if steps is None:
steps = []
self.steps = steps
self.redis_instance = RedisConnection()
self.redis_queue = RedisQueue.get_instance()
self.__queues = []
self.__raw = snippets
for step in steps:
self.__queues.append(Queue(name=step.name, connection=self.redis_instance.redis))
# TODO: Make this asynchronous to launch multiple workers at once
def setup_workers(self):
print(self.__queues)
try:
with Connection():
workers = []
for ind, step in enumerate(self.steps):
work = Worker([self.__queues[ind]], connection=self.redis_instance.redis,
name=(self.__queues[ind].name + "_worker"))
workers.append(work)
for worker in workers:
worker.work()
print("starting worker " + worker.name)
except ConnectionError:
print("Could not connect to host")
def execute(self, items: list):
results = []
for ind, item in enumerate(items):
job = self.__queues[0].enqueue(process_in_pipeline, args=[self.steps, [item]])
print("Processing item number [" + str(ind) + "] - queue: " + self.steps[0].name)
print(" :|" + item[0:32].replace("\n", "\\n") + "...")
while job.get_status() != "finished":
time.sleep(0)
print(str(job.get_status()))
results.append(job.result)
print("Num results: " + str(len(results)))
print(results)
return PipelineOutput(results)
def get_redis_instance(self):
return self.redis_instance
def set_steps(self, steps):
self.steps = steps
# for i in range(100):
# items2.append(items.pop())
def execute_synchronous(self, items):
# Feed the item into one step, get the result, feed the
# result to the next step and so on.
self.__raw = copy.deepcopy(items)
for step in self.steps:
step.process(items)
items = step.get()
out = PipelineOutput(items, self.__raw)
return out
def process_in_pipeline(steps, item: list) -> list:
for step in steps:
item = step.process(item)
return item
| 2,849 |
functions_train.py
|
annikalang/ImageClassifier1
| 0 |
2171408
|
''' 1. Train
Train a new network on a data set with train.py
Basic usage: python train.py data_directory
Prints out training loss, validation loss, and validation accuracy as the network trains
Options:
Set directory to save checkpoints: python train.py data_dir --save_dir save_directory
Choose architecture: python train.py data_dir --arch "vgg13"
Set hyperparameters: python train.py data_dir --learning_rate 0.01 --hidden_units 512 --epochs 20
Use GPU for training: python train.py data_dir --gpu
'''
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
import torchvision
from torchvision import datasets, transforms, models
from collections import OrderedDict
import json
import time
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from torch.autograd import Variable
import argparse
# You may have one function for data pre-processing which takes a path as an argument and returns all the loaders.
def load_data(data_dir = './flowers'):
data_dir = str(data_dir).strip('[]').strip("'")
train_dir = data_dir + '/train'
valid_dir = data_dir + '/valid'
test_dir = data_dir + '/test'
# TODO: Define your transforms for the training, validation, and testing sets
# For all three sets you'll need to normalize the means [0.485, 0.456, 0.406] and standard deviations [0.229, 0.224, 0.225]
# data_transforms =
cropped_size = 224
resized_size = 255
means = [0.485, 0.456, 0.406]
stds = [0.229, 0.224, 0.225]
# random scaling, cropping, and flipping, resized to 224x224 pixels
train_transforms = transforms.Compose([transforms.RandomResizedCrop(cropped_size),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(means, stds)])
# resize then crop the images to the appropriate size
validate_transforms = transforms.Compose([transforms.RandomResizedCrop(cropped_size),
transforms.ToTensor(),
transforms.Normalize(means, stds)])
# resize then crop the images to the appropriate size
test_transforms = transforms.Compose([transforms.Resize(resized_size), # Why 255 pixels?
transforms.CenterCrop(cropped_size),
transforms.ToTensor(),
transforms.Normalize(means, stds)])
# TODO: Load the datasets with ImageFolder
train_data = datasets.ImageFolder(train_dir, transform = train_transforms)
validate_data = datasets.ImageFolder(valid_dir, transform = validate_transforms)
test_data = datasets.ImageFolder(test_dir, transform = test_transforms)
image_data = [train_data, validate_data, test_data]
# TODO: Using the image datasets and the trainforms, define the dataloaders
batch_size = 60
train_loader = torch.utils.data.DataLoader(train_data, batch_size = batch_size, shuffle = True)
validate_loader = torch.utils.data.DataLoader(validate_data, batch_size = batch_size, shuffle = True)
test_loader = torch.utils.data.DataLoader(test_data)
# train_loader
dataloaders = [train_loader, validate_loader, test_loader]
return train_loader, validate_loader, test_loader, train_data
# One function to load the pre-trained model, build the classifier and define the optimizer. The function will take the architecture name, hidden units etc.
def build_model(arch = 'vgg16', middle_features = 1024, learning_rate = 0.01, device = 'gpu'):
if arch == 'vgg16':
model = models.vgg16(pretrained=True)
elif arch == 'densenet121':
model = models.densenet121(pretrained=True)
elif arch == 'alexnet':
model = models.alexnet(pretrained = True)
else:
print("Im sorry but {} is not a valid model. Did you mean vgg16, densenet121 or alexnet?".format(arch))
for param in model.parameters():
param.requires_grad = False
input_features = 25088
# middle_features = 1024
output_number = 102
dropout_probability = 0.5
classifier = nn.Sequential(OrderedDict([
('fc1', nn.Linear(input_features, middle_features)),
('drop', nn.Dropout(p = dropout_probability)),
('relu', nn.ReLU()),
('fc2', nn.Linear(middle_features, output_number)),
('output', nn.LogSoftmax(dim = 1))
]))
model.classifier = classifier
# learning_rate = 0.01
# epochs = 10
criterion = nn.NLLLoss()
optimizer = optim.SGD(model.classifier.parameters(), lr = learning_rate)
if torch.cuda.is_available() and device == 'gpu':
model.cuda()
return model, criterion, optimizer
# One function to train the model
def train_model(model, criterion, optimizer, validate_loader, train_loader, use = 'gpu', epochs = 10):
# TODO: Using the image datasets and the trainforms, define the dataloaders
#batch_size = 60
#train_loader = torch.utils.data.DataLoader(train_data, batch_size = batch_size, shuffle = True)
#validate_loader = torch.utils.data.DataLoader(validate_data, batch_size = batch_size, shuffle = True)
#test_loader = torch.utils.data.DataLoader(test_data)
# train_loader
#dataloaders = [train_loader, validate_loader, test_loader]
running_loss = 0
steps = 0
#model.to(device)
validation = True
device = torch.device('cuda' if torch.cuda.is_available() and use == 'gpu' else 'cpu')
model.to(device)
start_time = time.time()
print('Training starts')
for epoch in range(epochs):
training_loss = 0
for images, labels in train_loader:
# Move data tensors to the default device (gpu or cpu)
images, labels = images.to(device), labels.to(device)
optimizer.zero_grad()
log_probabilities = model(images)
loss = criterion(log_probabilities, labels)
loss.backward()
optimizer.step()
training_loss += loss.item()
print('Epoch {} of {} ///'.format(epoch + 1, epochs), 'Training loss {:.3f} ///'.format(training_loss / len(train_loader)))
if validation == True:
validation_loss = 0
validation_accuracy = 0
model.eval()
# Turn off gradients for validation, saves memory and computations
with torch.no_grad():
for images, labels in validate_loader:
# Move data tensors to the default device (gpu or cpu)
images, labels = images.to(device), labels.to(device)
log_probabilities = model(images)
loss = criterion(log_probabilities, labels)
validation_loss += loss.item()
# accuracy calculation
probabilities = torch.exp(log_probabilities)
top_probability, top_class = probabilities.topk(1, dim = 1)
equals = top_class == labels.view(*top_class.shape)
validation_accuracy += torch.mean(equals.type(torch.FloatTensor)).item()
model.train()
print("Validation loss {:.3f} ///".format(validation_loss / len(validate_loader)), "Validation accuracy {:.3f} ///".format(validation_accuracy / len(validate_loader)))
end_time = time.time()
print('Training ends')
training_time = end_time - start_time
print('Training time {:.0f}m {:.0f}s'.format(training_time / 60, training_time % 60))
return model
# one function to save the checkpoint file
def save_checkpoint(model, optimizer, train_data, arch = 'vgg16', path = 'checkpoint.pth', input_features = 25088, middle_features = 1024, output_number = 102, lr = 0.01, epochs = 10, batch_size = 64):
model.class_to_idx = train_data.class_to_idx
checkpoint = {'network': 'vgg16',
'input': input_features,
'output': output_number,
'learning_rate': lr,
'batch_size': batch_size,
'classifier' : model.classifier,
'epochs': epochs,
'optimizer': optimizer.state_dict(),
'state_dict': model.state_dict(),
'class_to_idx': model.class_to_idx}
torch.save(checkpoint, path)
| 8,889 |
RLBotPack/ReliefBotFamily/README/relief_loadout_generator.py
|
L0laapk3/RLBotPack
| 13 |
2171251
|
import colorsys
from pathlib import Path
from rlbot.agents.base_loadout_generator import BaseLoadoutGenerator
from rlbot.matchconfig.loadout_config import LoadoutConfig, Color
class ReliefBotLoadoutGenerator(BaseLoadoutGenerator):
def generate_loadout(self, player_index: int, team: int) -> LoadoutConfig:
# You could start with a loadout based on a cfg file in the same directory as this generator
loadout = self.load_cfg_file(Path('relief_bot_appearance.cfg'), team)
if team == 0:
paints = [4, 5, 7]
hues = [0.55, 0.6, 0.4]
else:
paints = [1, 6, 10]
hues = [0, 0.1, 0.13]
paint_id = paints[player_index % 3]
rgb = colorsys.hsv_to_rgb(hues[player_index % 3], 1, 0.6)
loadout.primary_color_lookup = Color(float_to_byte(rgb[0]), float_to_byte(rgb[1]), float_to_byte(rgb[2]), 255)
loadout.paint_config.wheels_paint_id = paint_id
loadout.paint_config.trails_paint_id = paint_id
return loadout
def float_to_byte(value: float) -> int:
return int(value * 255)
| 1,101 |
Panda/Panda_Merg.py
|
vibwipro/Machine-Learning-Python
| 3 |
2172121
|
import pandas as pd
df1 = pd.DataFrame({
"city": ["new york","chicago","orlando"],
"temperature": [21,14,35],
})
df2 = pd.DataFrame({
"city": ["chicago","new york","orlando"],
"humidity": [65,68,75],
})
df3 = pd.merge(df1, df2, on="city")
print (df3)
#############################################################################3
######### New DF
df1 = pd.DataFrame({
"city": ["new york","chicago","orlando", "baltimore"],
"temperature": [21,14,35, 38],
})
df2 = pd.DataFrame({
"city": ["chicago","new york","san diego"],
"humidity": [65,68,71],
})
############ Inner
df3=pd.merge(df1,df2,on="city",how="inner")
print (df3)
############ outer
df3=pd.merge(df1,df2,on="city",how="outer")
print (df3)
############ left (all records of df1)
df3=pd.merge(df1,df2,on="city",how="left")
print (df3)
############ right (all records of df2)
df3=pd.merge(df1,df2,on="city",how="right")
print (df3)
########## Indicator about type of join
df3=pd.merge(df1,df2,on="city",how="outer",indicator=True)
print(df3)
######################################################################
############# Another DF
df1 = pd.DataFrame({
"city": ["new york","chicago","orlando", "baltimore"],
"temperature": [21,14,35,38],
"humidity": [65,68,71, 75]
})
df2 = pd.DataFrame({
"city": ["chicago","new york","san diego"],
"temperature": [21,14,35],
"humidity": [65,68,71]
})
########## Both DF has Humidety and temp column.
########### Suffix will ass siffix to columns
df3= pd.merge(df1,df2,on="city",how="outer", suffixes=('_first','_second'))
print(df3)
############# Set city as index and update DF
######## inplace it update DF
df1 = pd.DataFrame({
"city": ["new york","chicago","orlando"],
"temperature": [21,14,35],
})
df1.set_index('city',inplace=True)
| 1,896 |
app/main/schema/avg_fare_by_s2id_schema.py
|
abhishek9sharma/nyctaxiserver
| 0 |
2172089
|
from flask_restplus import Namespace, fields, reqparse
class AvgFareByS2ID:
""" Class to store Schema information for Average Fare for a S2ID """
ns = Namespace('avg_fare_by_s2id', 'Average Fare Per Pick Up Location (S2ID) for Level 16')
model = ns.model('avg_fare_by_s2id', {
's2id': fields.String(required = True, description = 's2id of location at level 16'),
'fare': fields.Float(required= True, description = 'average fare for the given S2ID location')
})
parser = reqparse.RequestParser(bundle_errors= True)
parser.add_argument('date', type = str, required= True, help = 'Example: 2017-01-01 (DDDD-MM-YY)', location = 'args')
| 901 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.