text
stringlengths 20
812k
| id
stringlengths 40
40
| metadata
dict |
---|---|---|
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
#Description: Tracking metrics, IOU and precision
#Date: 2021/04/11
#Author: Steven Huang, Auckland, NZ
import os
import torch
import torchvision.ops.boxes as bops
import numpy as np
import matplotlib.pyplot as plt
from predict import getFileList,parseFileName
from commonPath import pathsFiles,getFileName,deleteFile
from commonPath import getFileNameNo,createPath
from plotCommon import plotSub
import pandas as pd
import matplotlib
matplotlib.rcParams['figure.dpi'] = 200 #high resolution when save plot
"""
['GTK3Agg', 'GTK3Cairo', 'MacOSX', 'nbAgg', 'Qt4Agg', 'Qt4Cairo', \
'Qt5Agg', 'Qt5Cairo', 'TkAgg', 'TkCairo', 'WebAgg', 'WX', 'WXAgg', \
'WXCairo', 'agg', 'cairo', 'pdf', 'pgf', 'ps', 'svg', 'template']
"""
#matplotlib.use('template')
SMALL_SIZE = 6
MEDIUM_SIZE = 10
BIGGER_SIZE = 12
#plt.rc('figure.dpi', 300)
plt.rc('font', size=SMALL_SIZE) # controls default text sizes
#plt.rc('font', family='Times New Roman')
plt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title
plt.rc('axes', labelsize=SMALL_SIZE) # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize
plt.rc('figure', titlesize=SMALL_SIZE) # fontsize of the figure title
def get_iou(bb1, bb2):
"""
Calculate the Intersection over Union (IoU) of two bounding boxes.
Parameters
----------
bb1 : array
Keys: [x1, y1, w, h]
The (x1, y1) position is at the top left corner,
the (w, h) position is at the bottom right corner
bb2 : array
Keys: [x2, y2, w, h]
The (x2, y2) position is at the top left corner,
the (w, h) position is at the bottom right corner
Returns
-------
float
in [0, 1]
"""
# determine the coordinates of the intersection rectangle
x_left = max(bb1[0], bb2[0])
y_top = max(bb1[1], bb2[1])
x_right = min(bb1[0]+bb1[2], bb2[0]+bb2[2])
y_bottom = min(bb1[1]+bb1[3], bb2[1]+bb2[3])
if x_right < x_left or y_bottom < y_top:
return 0.0
# The intersection of two axis-aligned bounding boxes is always an
# axis-aligned bounding box
intersection_area = (x_right - x_left) * (y_bottom - y_top)
# compute the area of both AABBs
bb1_area = bb1[2] * bb1[3]
bb2_area = bb2[2] * bb2[3]
# compute the intersection over union by taking the intersection
# area and dividing it by the sum of prediction + ground-truth
# areas - the interesection area
iou = intersection_area / float(bb1_area + bb2_area - intersection_area)
assert iou >= 0.0
assert iou <= 1.0
return iou
def testIOU():
#bb1 = {'x1':281.0,'x2':300.0, 'y1':87.0, 'y2':275.0}
#bb2 = {'x1':282.0,'x2':300.0, 'y1':87.0, 'y2':275.0}
#iou = get_iou2(bb1,bb2)
bb1 = [281.0, 300.0, 87.0, 275.0]
bb2 = [281.0, 300.0, 87.5, 275.0]
iou = get_iou(bb1,bb2)
print('iou=', iou)
box1 = torch.tensor([[281, 300, 281+87, 300+275]], dtype=torch.float)
box2 = torch.tensor([[281, 300, 281+87.5, 300+275]], dtype=torch.float)
iou = bops.box_iou(box1, box2)
print('iou=', iou)
box1 = torch.tensor([[281, 300, 281+87, 300+275],
[281, 300, 281+87, 300+275],
[281, 300, 282, 310]], dtype=torch.float)
box2 = torch.tensor([[281, 300, 281+87.5, 300+275],
[281, 300, 281+87.5, 320+275],
[281, 300, 282, 310]], dtype=torch.float)
iou = bops.box_iou(box1, box2)
diag = torch.diagonal(iou, 0)
print('iou=', iou)
print('diag=', diag)
bops.box_area
def changeRect(rt): #from x1,y1 w,h --> x1,y1,x2,y2
rt[:,2] = rt[:,2] + rt[:,0]
rt[:,3] = rt[:,3] + rt[:,1]
return rt
def getGroundTrueAndPred(trueFile, predictFile, delimiter=None):
gt = np.loadtxt(trueFile, delimiter=delimiter, dtype=float, skiprows=0, unpack=False)
pred = np.loadtxt(predictFile)
#print('before gt=', gt)
gt = changeRect(gt)
#print('after gt=', gt)
pred = changeRect(pred)
#print('gt=', gt.shape)
#print('pred=', pred.shape)
assert(gt.shape == pred.shape)
gt = torch.from_numpy(gt)
pred = torch.from_numpy(pred)
return gt,pred
def getOTB_GTAndPred():
trueFile = r'.\data\OTB\Crossing\groundtruth_rect.txt' #
predictFile = r'.\res\data\OTB\Crossing\CrossingPredict.txt'
#trueFile = r'.\res\imgRt.txt' #
#predictFile = r'.\res\imgRt.txt' #
deli = None #','
return getGroundTrueAndPred(trueFile, predictFile, delimiter=deli)
def Tracking_IOU_OTB():
gt,pred = getOTB_GTAndPred()
Tracking_IOU(gt,pred)
def Tracking_IOU(gt,pred, plot=True): #sucess rate
iou = bops.box_iou(gt, pred)
iou = torch.diagonal(iou, 0)
#print('iou=', iou)
#print('iou=', iou.shape)
if plot:
plotIOU_SR(iou.numpy())
return iou.numpy()
def centerRect(rt): #from x1,y1 w,h --> xc,yc
xc = (rt[:,0] + rt[:,2])/2
yc = (rt[:,1] + rt[:,3])/2
xc = xc.reshape([-1,1])
yc = yc.reshape([-1,1])
#print(xc)
#print(yc)
return torch.cat((xc, yc), 1)
def Tracking_Precision_OTB():
gt,pred = getOTB_GTAndPred()
return Tracking_Precision(gt,pred)
def Tracking_Precision(gt, pred, plot=True): #sucess rate
#print('before gt=', gt)
gt = centerRect(gt)
pred = centerRect(pred)
#print('after gt=', gt)
#print('after pred=', pred)
dis = torch.cdist(gt, pred)
#print('dis=', dis)
#print('dis=', dis.shape)
dis = torch.diagonal(dis, 0)
#print('dis=', dis)
#print('dis=', dis.shape)
if plot:
plotPrecision(dis)
return dis.numpy()
def getIoUXY(iou,N=200):
def SuccessRate(k):
res = np.where(iou > k, 1, 0)
return np.sum(res)/len(iou)
x = np.linspace(0,1,num=N)
y = list(map(SuccessRate, [i for i in x]))
#AUC
auc = np.sum(np.array(y)/N)
#print(auc,type(auc))
return x, y, auc, y[N//2]
def getPrecisionXY(dis,N=200):
def Precision(k):
res = np.where(dis < k, 1, 0)
return np.sum(res)/len(dis)
x = np.linspace(0,50,num=N)
y = list(map(Precision, [i for i in x]))
pre = y[N*30//50] #get pre when dis=30
#print('y=', y, ' pre=', pre)
return x,y,pre
def plotIOU_SR(iou, title='', dstPath=None, show=False):
def plotXY(x,y,name): #Success rate
plt.clf()
plt.title(name)
plt.plot(x,y,label='SiamFC')
plt.xlabel('Overlap threshold')
plt.ylabel('Success rate')
plt.xlim((0,1))
plt.ylim((0,1))
plt.grid(linestyle='-.') #'-', '--', '-.', ':', '',
#plt.legend(loc='lower left')
if dstPath is None:
plt.savefig(r'.\res\IoUMetric.png', dpi=300)
else:
plt.savefig(dstPath, dpi=300)
if show:
plt.show()
x,y,_,_ = getIoUXY(iou)
plotXY(x, y, title) #'Success plots of OPE'
def plotPrecision(dis, title='', dstPath=None,show=False):
def plotXY(x,y,name): #Success rate
plt.clf()
plt.title(name)
plt.plot(x,y,label='SiamFC')
plt.xlabel('Location error threshold')
plt.ylabel('Precision')
plt.xlim((0,50))
plt.ylim((0,1))
plt.grid(linestyle='-.') #'-', '--', '-.', ':', '',
#plt.legend(loc='lower right')
if dstPath is None:
plt.savefig(r'.\res\DisMetric.png', dpi=300)
else:
plt.savefig(dstPath, dpi=300)
if show:
plt.show()
x,y,_ = getPrecisionXY(dis)
plotXY(x, y, title) #'Precision plots of OPE'
def plotIOUs(iou, title='', dstPath=None, show=False):
def plotXY(x,y,name): #Success rate
plt.clf()
plt.title(name)
plt.plot(x,y,label='SiamFC')
plt.xlabel('Frames')
plt.ylabel('IoUs')
#plt.xlim((0,1))
#plt.ylim((0,1))
plt.grid(linestyle='-.') #'-', '--', '-.', ':', '',
#plt.legend(loc='lower left')
if dstPath is None:
plt.savefig(r'.\res\IoUs.png', dpi=300)
else:
plt.savefig(dstPath, dpi=300)
if show:
plt.show()
print('iou=', iou,type(iou),iou.shape)
x,y = np.arange(len(iou)), iou
plotXY(x, y, title)
def plotDistances(dis, title='', dstPath=None,show=False):
def plotXY(x,y,name): #Success rate
plt.clf()
plt.title(name)
plt.plot(x,y,label='SiamFC')
plt.xlabel('Frames')
plt.ylabel('Distance')
#plt.xlim((0,50))
#plt.ylim((0,1))
plt.grid(linestyle='-.') #'-', '--', '-.', ':', '',
#plt.legend(loc='lower right')
if dstPath is None:
plt.savefig(r'.\res\DisMetric.png', dpi=300)
else:
plt.savefig(dstPath, dpi=300)
if show:
plt.show()
x,y = np.arange(len(dis)), dis
plotXY(x, y, title)
##################### MOT7 ###################
def loadLines2Numpy(file):
data = np.loadtxt(file)
#print('data=', type(data), data, data.shape)
#data = data[data != 0]
#print('after data=', type(data), data, data.shape)
return data
def plotAllIoU_SR(iouFile,dstPath=None,show=False):
#base = r'.\data\MOT\MOT17_GT_Jason\MOT17-04-FRCNN'
#iouFile = base + '\\IoU_alexnet_e754\\IoU.txt'
plotIOU_SR(loadLines2Numpy(iouFile), dstPath=dstPath,show=show)
def plotAllPrecision(disFile, dstPath=None,show=False):
#base = r'.\data\MOT\MOT17_GT_Jason\MOT17-04-FRCNN'
#disFile = base + '\\IoU_alexnet_e754\\dis.txt'
plotPrecision(loadLines2Numpy(disFile), dstPath=dstPath,show=show)
def plotAllIoUs(iouFile,dstPath=None,show=False):
plotIOUs(loadLines2Numpy(iouFile), dstPath=dstPath,show=show)
def plotAllDis(disFile, dstPath=None,show=False):
plotDistances(loadLines2Numpy(disFile), dstPath=dstPath,show=show)
def testPlot():
N=500
#iou = np.random.rand(N)
iou = np.random.uniform(low=0, high=1, size=(N,))
plotIOU_SR(iou)
#plotPrecision()
def plotCompareIoU(base):
iouFile1 = base + '\\IoU_siamfc_alexnet_e754\\IoU.txt'
label1 = 'SiamFC_Alexnet'
iouFile2 = base + '\\IoU_siamfc_Con2Net_BalancedLoss_e\\IoU.txt'
label2 = 'SiamFC_Con2Net'
iouFile3 = base + '\\IoU_siamfc_Sequential_vgg19_BalancedLoss_e\\IoU.txt'
#iouFile3 = base + '\\IoU_siamfc_Sequential_vgg19_FocalLoss_e\\IoU.txt'
label3 = 'SiamFC_Vgg19'
#iouFile4 = base + '\\IoU_siamfc_Sequential_MobileNet_BalancedLoss_e\\IoU.txt'
iouFile4 = base + '\\IoU_siamfc_Sequential_MobileNet_FocalLoss_e\\IoU.txt'
label4 = 'SiamFC_MobileNetV2'
plt.clf()
ax = plt.subplot(1,1,1)
x,y,auc,sr = getIoUXY(loadLines2Numpy(iouFile1))
plotSub(x, y, ax, label=label1, color='b')
print(label1, ' AUC=', auc, ' sr=', sr)
x,y,auc,sr = getIoUXY(loadLines2Numpy(iouFile2))
plotSub(x, y, ax, label=label2, color='r', linestyle='dashed')
print(label2, ' AUC=', auc, ' sr=', sr)
x,y,auc,sr = getIoUXY(loadLines2Numpy(iouFile3))
plotSub(x, y, ax, label=label3, color='g', linestyle='dotted')
print(label3, ' AUC=', auc, ' sr=', sr)
x,y,auc,sr = getIoUXY(loadLines2Numpy(iouFile4))
plotSub(x, y, ax, label=label4, color='k', linestyle='dashdot')
print(label4, ' AUC=', auc, ' sr=', sr)
#plt.axis('square')
plt.xlabel('Overlap threshold')
plt.ylabel('Success rate')
plt.xlim((0,1))
plt.ylim((0,1))
plt.grid(linestyle='-.') #'-', '--', '-.', ':', '',
plt.legend(loc='upper right')
#plt.legend()
plt.savefig(r'.\res\IoUPlot.png', dpi=300)
plt.show()
def plotComparePrecision(base):
#base = r'.\data\MOT\MOT17_GT_Jason\MOT17-04-FRCNN'
disFile1 = base + '\\IoU_siamfc_alexnet_e754\\dis.txt'
label1 = 'SiamFC_Alexnet'
disFile2 = base + '\\IoU_siamfc_Con2Net_BalancedLoss_e\\dis.txt'
label2 = 'SiamFC_Con2Net'
disFile3 = base + '\\IoU_siamfc_Sequential_vgg19_BalancedLoss_e\\dis.txt'
label3 = 'SiamFC_Vgg19'
#disFile4 = base + '\\IoU_siamfc_Sequential_MobileNet_BalancedLoss_e\\dis.txt'
disFile4 = base + '\\IoU_siamfc_Sequential_MobileNet_FocalLoss_e\\dis.txt'
label4 = 'SiamFC_MobileNetV2'
plt.clf()
ax = plt.subplot(1,1,1)
x,y,pre = getPrecisionXY(loadLines2Numpy(disFile1))
plotSub(x, y, ax, label=label1, color='b')
print(label1, 'final pre=', pre)
x,y,pre = getPrecisionXY(loadLines2Numpy(disFile2))
plotSub(x, y, ax, label=label2, color='r', linestyle='dashed')
print(label2, 'final pre=', pre)
x,y,pre = getPrecisionXY(loadLines2Numpy(disFile3))
plotSub(x, y, ax, label=label3, color='g', linestyle='dotted')
print(label3, 'final pre=', pre)
x,y,pre = getPrecisionXY(loadLines2Numpy(disFile4))
plotSub(x, y, ax, label=label4, color='k', linestyle='dashdot')
print(label4, 'final pre=', pre)
#plt.axis('square')
plt.xlabel('Location error threshold')
plt.ylabel('Precision')
plt.xlim((0,50))
plt.ylim((0,1))
plt.grid(linestyle='-.') #'-', '--', '-.', ':', '',
plt.legend(loc='upper right')
#plt.legend()
plt.savefig(r'.\res\PrecisonPlot.png', dpi=300)
plt.show()
def getMOT_GTAndPredAll(trueFile, predictPath, IoUPath, objIDFilters=[]): #get Iou&Distance to one file from all predciton files
# base = r'.\data\MOT\MOT17_GT_Jason\MOT17-04-FRCNN'
# trueFile = base
# predictPath = base + '\\predBoxFiles'
# IoUPath = base + '\\IoU'
createPath(IoUPath)
ioufilesPath = os.path.join(IoUPath,'resIoU')
createPath(ioufilesPath)
disfilesPath = os.path.join(IoUPath,'resDis')
createPath(disfilesPath)
gtFiles = getFileList(trueFile, 'txt')
iouAll = None
disAll = None
df = pd.DataFrame()
for i, gtFile in enumerate(gtFiles):
objId,start,stop = parseFileName(getFileNameNo(gtFile))
if objIDFilters != [] and objId in objIDFilters:
continue
predictFile = os.path.join(predictPath, getFileNameNo(gtFile) + '_pred.txt')
print(str(i)+'/'+str(len(gtFiles)), getFileName(gtFile), predictFile, objId,start,stop)
IouFile = os.path.join(ioufilesPath, getFileNameNo(gtFile) + '_IoU.txt')
disFile = os.path.join(disfilesPath, getFileNameNo(gtFile) + '_dis.txt')
if not os.path.exists(predictFile):
print('warning: file not exist! ', predictFile)
continue
gt,pred = getGroundTrueAndPred(gtFile, predictFile, delimiter=',')
iou = Tracking_IOU(gt, pred, plot=False)
if iouAll is None:
iouAll = iou
else:
iouAll = np.hstack((iouAll,iou))
dis = Tracking_Precision(gt,pred,plot=False)
if disAll is None:
disAll = dis
else:
disAll = np.hstack((disAll,dis))
#torch.save(iou, IouFile)
np.savetxt(IouFile, iou, fmt='%f')
np.savetxt(disFile, dis, fmt='%f')
#print('iou=\n', iou, np.mean(iou))
#print('dis=\n', dis, np.mean(dis))
line = pd.DataFrame([[objId, np.mean(iou), np.mean(dis)]], columns=['objId','meanIoU','meanDis'])
df = df.append(line)
#break
IouFile = os.path.join(IoUPath, 'IoU.txt')
print('iouAll=', type(iouAll), iouAll.shape)
np.savetxt(IouFile, iouAll, fmt='%f')
#plotIOU_SR(iouAll)
disFile = os.path.join(IoUPath, 'dis.txt')
print('disAll=', type(disAll), disAll.shape)
np.savetxt(disFile, disAll, fmt='%f')
#plotPrecision(disAll)
print('df=\n', df)
df.set_index(["objId"], inplace=True)
df.to_csv(os.path.join(IoUPath, 'statits.csv'),index=True)
def getMOT_GTAndPred():
base = r'.\res\data\MOT17\MOT17-04-FRCNN_ID_1\\'
trueFile = base + 'groundtruth_rect.txt' #
predictFile = base + 'pred.txt'
return getGroundTrueAndPred(trueFile, predictFile, delimiter=',')
def removeSomeIoU(base):
def checkFile(path):
for f in pathsFiles(path,'txt'):
objId,start,stop = parseFileName(getFileNameNo(f))
iou = loadLines2Numpy(f)
if iou[1] == 0:
print('pred=0 ', getFileNameNo(f), objId,start,stop)
#print(f, iou[1])
def removeObjFiles(path,objIds):
for f in pathsFiles(path,'txt'):
objId,start,stop = parseFileName(getFileNameNo(f))
if objId in objIds:
print('delete', f)
deleteFile(f)
objIds = [107,108,109,110,111,112,113,114,117,118,119,\
121,124,125,126,127,128,129,130,131,132,133,134,\
135,138,13,14,15,19,20,2,38,39,41,42,47,51,53,60,\
63,66,67,68,69,70,71,72,73,75,76,77,78,80,82,84,85,\
87,88,89,90,91,92,93,94,95,97,98,99]
pathAll =[]
pathAll.append(os.path.join(base, 'IoU_siamfc_alexnet_e754'))
pathAll.append(os.path.join(base, 'IoU_siamfc_Con2Net_BalancedLoss_e'))
pathAll.append(os.path.join(base, 'IoU_siamfc_Sequential_vgg19_BalancedLoss_e'))
pathAll.append(os.path.join(base, 'IoU_siamfc_Sequential_MobileNet_FocalLoss_e'))
for i in pathAll:
disPath = os.path.join(i, 'resDis')
iouPath = os.path.join(i, 'resIoU')
#removeObjFiles(disPath,objIds)
#removeObjFiles(iouPath,objIds)
print('iouPath=\n', iouPath)
checkFile(iouPath)
#break
def Tracking_All_MOT7():
#gt,pred = getMOT_GTAndPred() #one gt and pred
#Tracking_IOU(gt,pred)
base = os.path.abspath(r'data/MOT/MOT17_GT_Jason/MOT17-04-FRCNN')
#base = os.path.expanduser(r'data/MOT/MOT17_GT_Jason/MOT17-04-FRCNN')
#base = os.path.abspath(r'data/MOT/MOT17_GT_Jason/MOT17-13-FRCNN')
#base = os.path.expanduser(r'data/MOT/MOT17_GT_Jason/MOT17-02-FRCNN')
trueFile = base
name = 'alexnet_e754'
name = 'siamfc_Sequential_vgg19_BalancedLoss_e'
name = 'siamfc_Sequential_vgg19_FocalLoss_e'
name = 'siamfc_Sequential_MobileNet_BalancedLoss_e'
name = 'siamfc_Sequential_AlexNet_BalancedLoss_e'
name = 'siamfc_Sequential_MobileNet_FocalLoss_e'
name = 'siamfc_Con2Net__BalancedLoss_e' #02-frcnn,04
# name = 'siamfc_Sequential_AlexNetOO_FocalLoss_e'
#name = 'siamfc_Con2Net_BalancedLoss_e860'
#name = 'siamfc_alexnet_e654'
#name = 'siamfc_AlexNetV1_FocalLoss_e713'
# name = 'siamfc_Sequential_AlexNet_FocalLoss_e'
# name = 'siamfc_alexnet_e554'
# #name = 'siamfc_alexnet_e50'
#name = 'old'
# name = 'siamfc_alexnet_e754'
# name = 'siamfc_Con2Net_BalancedLoss_e'
# name = 'siamfc_Sequential_vgg19_BalancedLoss_e'
# name = 'siamfc_Sequential_MobileNet_FocalLoss_e'
predictPath = os.path.join(base, 'predBoxFiles_'+name)
IoUPath = os.path.join(base, 'IoU_' + name)
"""
# MOT17-04-FRCNN siamfc_alexnet_e754
objIds = [107,108,109,110,111,112,113,114,117,118,119,\
121,124,125,126,127,128,129,130,131,132,133,134,\
135,138,13,14,15,19,20,2,38,39,41,42,47,51,53,60,\
63,66,67,68,69,70,71,72,73,75,76,77,78,80,82,84,85,\
87,88,89,90,91,92,93,94,95,97,98,99]
# MOT17-04-FRCNN siamfc_Con2Net_BalancedLoss_e
objIds = [115,128]
# MOT17-04-FRCNN siamfc_Sequential_vgg19_BalancedLoss_e
objIds = [107,108,109,110,111,112,113,114,115,117,118,\
121,124,125,126,127,128,129,130,131,132,133,134,135,\
138,13,14,15,16,19,20,2,38,40,41,42,47,4,51,53,60,66,\
67,68,69,70,71,72,73,75,76,77,78,80,84,85,87,88,89,90,\
91,98,99]
# MOT17-04-FRCNN siamfc_Sequential_MobileNet_FocalLoss_e
objIds = [102,103,105,107,108,109,110,112,113,114,115,117,\
118,121,126,127,128,135,138,13,15,21,25,28,33,37,38,39,\
41,44,4,51,53,5,60,62,66,67,68,70,71,72,73,82,84,85,88,92,9]
"""
objIds=[]
#getMOT_GTAndPredAll(trueFile, predictPath, IoUPath, objIDFilters=objIds)#filter excluded objs
#MOT17-13-FRCNN no pedestrain objs
objIdFilters = [1,3,12,29,30,41,76,80,82,85,104,105,116,\
106,81,125,92,130101,184,107,108,89,179,90,91,177,93,\
162,99,182,150,109,181,175,183,138,176,146,96,141,185,\
75,65,94,95,110,161,103,121,88,97,131,83,87,79,86,111,\
172,112,174,113,27,117,114,173,118,98,115,77,130,84,78] #no pedestrains
#MOT17-04-FRCNN no pedestrain objs
objIdFilters = [7,8,9,10,11,12,13,14,15,16,17,18,19,\
20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,\
36,37,38,39,40,41,42,43,44,47,48,49,50,51,52,53,54,\
55,56,57,58,59,64,78, 137,] #no pedestrains
#MOT17-02-FRCNN no pedestrain objs
#objIdFilters = [4,50,51,52,53,79,75] #no pedestrains
analyseMetrics(base, 'IoU_'+name, noPedObjs=objIdFilters)
#removeSomeIoU(base)
#plotCompareIoU(base)
#plotComparePrecision(base)
def Tracking_Precision_MOT17():
gt,pred = getMOT_GTAndPred()
return Tracking_Precision(gt,pred)
def readCsv(file):
df = pd.read_csv(file)
#print(df.describe().transpose())
print(df.head())
print('df.columns=',df.columns)
#print('df.dtypes = ',df.dtypes)
#print('df.dtypes = ',df.dtypes)
return df
def analysisTrecking(df):
num = 10
#best iou
df = df.sort_values(by=['meanIoU'], ascending=False)
print('best iou=\n', df[:num])
#print(df[:num]['objId'])
#best distance
df = df.sort_values(by=['meanDis'], ascending=True)
print('best distance=\n', df[:num])
#worst iou
df = df.sort_values(by=['meanIoU'], ascending=True)
print('worst iou=\n', df[:num])
#worst distance
df = df.sort_values(by=['meanDis'], ascending=False)
print('worst distance=\n', df[:num])
def analyseMetrics(base, name, noPedObjs):
def filtersNoPed(df, noPedObjs):
#print('df=', df, df.shape, '\n')
#print('noPedObjs=', noPedObjs, len(noPedObjs), '\n')
for i, row in enumerate(df.iterrows()):
#print(i, 'row[1]=', row[1][0], type(row[1][0]))
if int(row[1][0]) in noPedObjs:
df = df.drop(i)
#print('df=', df, df.shape, '\n')
return df
dstPath = os.path.join(base, name)
iouFile = os.path.join(dstPath, 'IoU.txt')
disFile = os.path.join(dstPath, 'dis.txt')
plotAllIoU_SR(iouFile, os.path.join(dstPath, 'IoU.png'))
plotAllPrecision(disFile, os.path.join(dstPath, 'pre.png'))
csvFile = os.path.join(base, name,'statits.csv')
df = readCsv(csvFile)
if noPedObjs:
df = filtersNoPed(df,noPedObjs)
analysisTrecking(df)
def analyseIoU(path, objFilters = None, fromZero=False):
iouFiles = []
iouFilesAll=pathsFiles(path,'txt')
for i in iouFilesAll:
objId,start,stop = parseFileName(getFileNameNo(i))
iou = loadLines2Numpy(i)
#print(i, objId,start,stop, iou.shape)
if objFilters is None:
iouFiles.append(i)
else:
if objId in objFilters:
iouFiles.append(i)
#start draw
plt.clf()
ax = plt.subplot(1,1,1)
for i in iouFiles:
objId,start,stop = parseFileName(getFileNameNo(i))
iou = loadLines2Numpy(i)
if fromZero:
x = np.arange(len(iouFiles))
else:
x = np.arange(start,stop+1)
y = iou
ls = 'obj:'+str(objId)+', From '+str(start)+' To '+str(stop)
plotSub(x, y, ax, label=ls)
#plt.axis('square')
plt.xlabel('Frames')
plt.ylabel('IoU')
#plt.xlim((0,1))
#plt.ylim((0,1))
plt.grid(linestyle='-.') #'-', '--', '-.', ':', '',
plt.legend(loc='lower right') #upper
#plt.legend()
#plt.savefig(r'.\res\IoUObjs.png', dpi=300)
plt.show()
def analyseDis(path, objFilters = None, fromZero=False):
disFiles = []
disFilesAll=pathsFiles(path,'txt')
for i in disFilesAll:
objId,start,stop = parseFileName(getFileNameNo(i))
iou = loadLines2Numpy(i)
#print(i, objId,start,stop, iou.shape)
if objFilters is None:
disFiles.append(i)
else:
if objId in objFilters:
disFiles.append(i)
#start draw
plt.clf()
ax = plt.subplot(1,1,1)
for i in disFiles:
objId,start,stop = parseFileName(getFileNameNo(i))
iou = loadLines2Numpy(i)
if fromZero:
x = np.arange(len(disFiles))
else:
x = np.arange(start,stop+1)
y = iou
ls = 'obj:'+str(objId)+', From '+str(start)+' To '+str(stop)
plotSub(x, y, ax, label=ls)
#plt.axis('square')
plt.xlabel('Frames')
plt.ylabel('Distance')
#plt.xlim((0,1))
#plt.ylim((0,1))
plt.grid(linestyle='-.') #'-', '--', '-.', ':', '',
plt.legend(loc='upper right') #
#plt.legend()
#plt.savefig(r'.\res\analyseDis.png', dpi=300)
plt.show()
def analyseObjTracking():
base = r'.\data\MOT\MOT17_GT_Jason\MOT17-04-FRCNN'
name = 'IoU_siamfc_alexnet_e754'
iousPath = os.path.join(base, name, 'resIoU')
disPath = os.path.join(base, name, 'resDis')
bestIoUObjs = [48,7,55]#None # 116,34,6,16
bestDisObjs = [9,7,48,25,29,55,116,16,136,34]
worstIoUObjs = [38,90,53,15,95]
worstDisObjs = [89,66,2,99,71,80,84,85,111,119,120,121,122,141]
worstDisObjs = [89,66,2,80,84,120,121,122,141]
#observeObjIds = [6,7,9,12,16,100,101,106,116,123,137]#[1,3,4,5,6,7,9,12,16,100,101,106,116,123,137]
#observeObjIds = [100,101,106,116,123]
#observeObjIds = [6,7,9,16,137,139,140,81]
#observeObjIds = [48,7,9,29,55]
#observeObjIds = [38,90,53,15,95]
#observeObjIds = [7,9,48,25,29]
#observeObjIds = [89,66,2,99,71]
#analyseIoU(iousPath,objFilters=bestIoUObjs,fromZero=False)
#analyseIoU(iousPath,objFilters=observeObjIds,fromZero=False)
#analyseDis(disPath,objFilters=bestDisObjs,fromZero=False)
analyseDis(disPath,objFilters=worstDisObjs,fromZero=False)
def analyseObjTracking2():
base = r'.\data\MOT\MOT17_GT_Jason\MOT17-13-FRCNN'
name = 'IoU_siamfc_Con2Net__BalancedLoss_e'
iousPath = os.path.join(base, name, 'resIoU')
disPath = os.path.join(base, name, 'resDis')
bestIoUObjs = [175,140,185,108,99,116,44,107,101,109]#None # 116,34,6,16
bestDisObjs = [107,140,44,175,116,108,101,185,118,99]
worstIoUObjs = [82,29,130,39,28,41,7,86,85,36]
worstDisObjs = [125,81,18,139,78,83,84,131,79,20]
#observeObjIds = [38,90,53,15,95]
#observeObjIds = [7,9,48,25,29]
#observeObjIds = [89,66,2,99,71]
#analyseIoU(iousPath,objFilters=worstIoUObjs,fromZero=False)
#analyseIoU(iousPath,objFilters=observeObjIds,fromZero=False)
analyseDis(disPath,objFilters=worstDisObjs,fromZero=False)
#analyseDis(disPath,objFilters=worstDisObjs,fromZero=False)
def main():
#testIOU()
#Tracking_IOU_OTB()
#Tracking_Precision_OTB()
#Tracking_Precision_MOT17()
Tracking_All_MOT7() #estimate prediction
#analyseObjTracking()
#analyseObjTracking2()
#testPlot()
if __name__=="__main__":
main()
"""
SiamFC_Alexnet AUC= 0.22647158218125962 sr= 0.24445907395216152
SiamFC_Con2Net AUC= 0.4699662052682746 sr= 0.5392157770473589
SiamFC_Vgg19 AUC= 0.03386087338161071 sr= 0.013605442176870748
SiamFC_MobileNetV2 AUC= 0.040632556736136555 sr= 0.026476863725511324
SiamFC_Alexnet final pre= 0.2869870528856704
SiamFC_Con2Net final pre= 0.5615110411555021
SiamFC_Vgg19 final pre= 0.039850779021285934
SiamFC_MobileNetV2 final pre= 0.03467747149723054
#MOT17-13-FRCNN
best iou=
objId meanIoU meanDis
44 140 0.744940 3.333242
123 44 0.670073 3.573572
1 101 0.612425 7.748514
64 159 0.519107 10.891508
147 66 0.478441 24.586643
156 74 0.421749 13.709427
37 134 0.351134 38.254512
109 31 0.333333 47.203192
22 120 0.329446 27.743734
63 158 0.311724 16.069593
best distance=
objId meanIoU meanDis
44 140 0.744940 3.333242
123 44 0.670073 3.573572
1 101 0.612425 7.748514
64 159 0.519107 10.891508
156 74 0.421749 13.709427
63 158 0.311724 16.069593
147 66 0.478441 24.586643
2 102 0.209580 26.030343
22 120 0.329446 27.743734
148 67 0.075157 29.521161
worst iou=
objId meanIoU meanDis
117 39 0.002525 119.888764
105 28 0.004893 326.000158
162 7 0.005563 158.768482
114 36 0.006944 163.908735
133 53 0.007194 502.518385
65 15 0.007353 182.560378
76 16 0.007634 192.181803
112 34 0.007856 338.214887
54 14 0.008065 274.837277
143 62 0.008323 128.246074
worst distance=
objId meanIoU meanDis
94 18 0.031843 681.014532
42 139 0.011026 642.637283
97 20 0.021491 513.078423
133 53 0.007194 502.518385
100 23 0.032247 483.226457
21 11 0.034483 426.437242
10 10 0.050000 386.852936
51 147 0.049168 377.183754
62 157 0.016165 369.557535
36 133 0.143637 354.565719
#MOT17-02-FRCNN
best iou=
objId meanIoU meanDis
64 69 0.523023 10.284808
63 68 0.420504 10.739003
77 80 0.250000 64.696268
58 63 0.228288 13.149068
76 7 0.141833 93.798218
70 74 0.132100 37.905375
6 16 0.085401 680.402234
73 77 0.083333 105.672327
5 15 0.078630 80.205857
69 73 0.061554 70.271700
best distance=
objId meanIoU meanDis
64 69 0.523023 10.284808
63 68 0.420504 10.739003
58 63 0.228288 13.149068
59 64 0.027940 24.319440
70 74 0.132100 37.905375
49 55 0.023414 63.730792
77 80 0.250000 64.696268
69 73 0.061554 70.271700
67 71 0.017988 74.715707
5 15 0.078630 80.205857
worst iou=
objId meanIoU meanDis
0 10 0.001667 149.903178
65 6 0.001667 262.743045
79 9 0.001667 240.124555
7 17 0.001667 127.141091
23 31 0.001667 215.524640
22 30 0.001667 234.558863
14 23 0.001809 690.585629
32 3 0.001845 756.147893
61 66 0.001880 97.942085
9 19 0.001992 736.207826
worst distance=
objId meanIoU meanDis
21 2 0.017857 1171.805309
29 37 0.003584 763.914744
32 3 0.001845 756.147893
9 19 0.001992 736.207826
14 23 0.001809 690.585629
11 20 0.003106 689.214030
6 16 0.085401 680.402234
33 40 0.002322 608.223009
26 34 0.004032 572.425666
25 33 0.003759 567.760812
#MOT17-04-FRCNN
best iou=
objId meanIoU meanDis
40 139 0.956434 1.611293
31 130 0.874320 4.243345
42 140 0.860584 4.142638
77 45 0.857875 5.294055
16 116 0.780172 7.360580
78 46 0.765151 7.803975
104 6 0.731514 8.564759
111 76 0.696620 22.035732
82 4 0.677235 13.831328
29 129 0.661909 15.556965
best distance=
objId meanIoU meanDis
40 139 0.956434 1.611293
42 140 0.860584 4.142638
31 130 0.874320 4.243345
77 45 0.857875 5.294055
16 116 0.780172 7.360580
78 46 0.765151 7.803975
104 6 0.731514 8.564759
82 4 0.677235 13.831328
117 81 0.613992 15.399903
114 79 0.548472 15.453990
worst iou=
objId meanIoU meanDis
100 66 0.007195 727.575577
12 111 0.007195 331.754863
34 133 0.008089 313.329831
7 107 0.010172 470.197604
110 75 0.010475 575.124912
109 74 0.012657 605.279244
61 2 0.014697 428.098206
135 98 0.016238 436.192008
101 67 0.017782 377.082967
25 124 0.022999 332.224132
worst distance=
objId meanIoU meanDis
100 66 0.007195 727.575577
125 89 0.051858 688.266325
109 74 0.012657 605.279244
110 75 0.010475 575.124912
6 106 0.040529 559.555941
99 65 0.025292 499.430517
136 99 0.115143 496.416125
7 107 0.010172 470.197604
97 63 0.056926 461.098358
24 123 0.040404 456.121002
"""
|
003187c6c2e5809c25fc3a1e37fe99c95447ce7a
|
{
"blob_id": "003187c6c2e5809c25fc3a1e37fe99c95447ce7a",
"branch_name": "refs/heads/main",
"committer_date": "2021-07-28T02:16:46",
"content_id": "c42209e9b578f4969dc4f36deb712be8e5f4ae9e",
"detected_licenses": [
"MIT"
],
"directory_id": "fbba898dfe1e9a234448e25433dfe294f6ef7eb6",
"extension": "py",
"filename": "metrics.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 303598447,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 32538,
"license": "MIT",
"license_type": "permissive",
"path": "/src/metrics.py",
"provenance": "stack-edu-0062.json.gz:173384",
"repo_name": "StevenHuang2020/SiameseFc_PyTorch",
"revision_date": "2021-07-28T02:16:46",
"revision_id": "43f214a59e5841668f8b1fbadebd47384f8d4bf5",
"snapshot_id": "6d9cf27b47493c3204de22d04ce3b53cb5b19d90",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/StevenHuang2020/SiameseFc_PyTorch/43f214a59e5841668f8b1fbadebd47384f8d4bf5/src/metrics.py",
"visit_date": "2023-06-23T19:22:08.531252",
"added": "2024-11-19T01:55:36.759906+00:00",
"created": "2021-07-28T02:16:46",
"int_score": 3,
"score": 2.6875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0080.json.gz"
}
|
/**
* Шаблон ресурсов для отображения в виде списка.
*
* @author [email protected] <Suvorov Andrey M.>
*/
Ext.define(
'FBEditor.view.panel.resources.tpl.ListResource',
{
extend: 'Ext.XTemplate',
constructor: function ()
{
var me = this;
me.html = '<tpl for=".">' +
'<div class="resource-thumb-wrap resource-list-thumb">' +
'<span class="resource-thumb-img resource-thumb-img-{extension} fa fa-lg" /></span>' +
'<span class="resource-thumb-name" title="{name}">{baseName}</span>' +
'</div>' +
'</tpl>';
}
}
);
|
eb537d437917ebbf05a7cf7e807091853d0190e8
|
{
"blob_id": "eb537d437917ebbf05a7cf7e807091853d0190e8",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-23T10:28:58",
"content_id": "2c5ae54371c6f96c5f7adbcb24de1efc2821c9c4",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "322ce8248d775aa59aa0b3378db540db1df629c2",
"extension": "js",
"filename": "ListResource.js",
"fork_events_count": 11,
"gha_created_at": "2014-08-05T12:26:08",
"gha_event_created_at": "2023-07-14T18:23:59",
"gha_language": "JavaScript",
"gha_license_id": "BSD-2-Clause",
"github_id": 22642506,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 634,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/Frontend/app/view/panel/resources/tpl/ListResource.js",
"provenance": "stack-edu-0042.json.gz:103482",
"repo_name": "Litres/FB3Editor",
"revision_date": "2023-06-23T10:28:58",
"revision_id": "00f2bcf566e68d76069db98643b3ae7e4f1d6588",
"snapshot_id": "881c0ab6204dd82027d3176835e1d484f6b79a2a",
"src_encoding": "UTF-8",
"star_events_count": 26,
"url": "https://raw.githubusercontent.com/Litres/FB3Editor/00f2bcf566e68d76069db98643b3ae7e4f1d6588/Frontend/app/view/panel/resources/tpl/ListResource.js",
"visit_date": "2023-07-19T21:37:32.123294",
"added": "2024-11-18T23:38:32.334345+00:00",
"created": "2023-06-23T10:28:58",
"int_score": 2,
"score": 2.046875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0060.json.gz"
}
|
<?php
if (php_sapi_name() != "cli") die("Can only be run from command line!");
require("/home/uesp/secrets/esolog.secrets");
require("esoCommon.php");
class CEsoTrimOldMinedItems
{
public $db = null;
public $version = "";
public $itemsLoaded = 0;
public $itemsTrimmed = 0;
public $itemsCopied = 0;
// Keep all potions at itemId 1/2
public $START_ITEMID = 10;
public $END_ITEMID = 220000;
public $TEMP_TABLE_NAME = "minedItemTrimTmp";
// InternalLevel:InternalSubtype for mined items to keep
public $VALID_ITEMS = [
"1:1" => true,
"1:2" => true,
"50:364" => true,
"50:366" => true,
"50:367" => true,
"50:368" => true,
"50:369" => true,
"50:370" => true,
];
public function __construct()
{
print("Removes all items from a minedItem table except specific levels (1:1, 1:2, 50:364, and 50:366-370).\n\n");
$this->ParseCommandLineArgs();
$this->InitDatabase();
}
protected function InitDatabase()
{
global $uespEsoLogWriteDBHost, $uespEsoLogWriteUser, $uespEsoLogWritePW, $uespEsoLogDatabase;
$this->db = new mysqli($uespEsoLogWriteDBHost, $uespEsoLogWriteUser, $uespEsoLogWritePW, $uespEsoLogDatabase);
if ($this->db->connect_error) exit("Error: Could not connect to mysql database!");
return true;
}
protected function ParseCommandLineArgs()
{
global $argv;
if (count($argv) <= 1) die("Error: No version specified on command line!\n");
for ($i = 1; $i < count($argv); $i++)
{
$arg = $argv[$i];
$this->version = strtolower(trim($arg));
}
if (!preg_match('/^\d+(?:pts(?:\d+)?)?$/', $this->version)) die("Error: Version does not match the expected format (38, 38pts, 38pts1)!\n");
}
protected function TrimItems()
{
$table = "minedItem" . GetEsoItemTableSuffix($this->version);
$tmpTable = $this->TEMP_TABLE_NAME;
$query = "CREATE TABLE `$tmpTable` LIKE `$table`;";
$result = $this->db->query($query);
if (!$result) die("Error: Failed to create temporary table '$tmpTable'!\n");
for ($itemId = $this->START_ITEMID; $itemId <= $this->END_ITEMID; ++$itemId)
{
if ($itemId % 10000 == 0) print("\t$itemId) Trimming...(loaded {$this->itemsLoaded} records, trimmed {$this->itemsTrimmed})\n");
$query = "SELECT id, internalLevel, internalSubtype FROM `$table` WHERE itemId='$itemId';";
$result = $this->db->query($query);
if (!$result)
{
print("Error: Failed to load items for ID #$itemId from database!\n");
continue;
}
$idsToRemove = [];
$idsToCopy = [];
while ($item = $result->fetch_assoc())
{
$intLevel = intval($item['internalLevel']);
$intSubtype = intval($item['internalSubtype']);
$levelId = "$intLevel:$intSubtype";
++$this->itemsLoaded;
if ($this->VALID_ITEMS[$levelId] === true)
{
++$this->itemsCopied;
$idsToCopy[] = intval($item['id']);
continue;
}
$idsToRemove[] = intval($item['id']);
++$this->itemsTrimmed;
}
if (count($idsToCopy) == 0) continue;
$ids = "'" . implode("','", $idsToCopy) . "'";
$query = "INSERT INTO `$tmpTable` SELECT * FROM `$table` WHERE id IN($ids);";
$result = $this->db->query($query);
if (!$result) print("Error: Failed to copy itemId #$itemId to temporary database!\n\t" . $this->db->error . "\n");
/*
* Deleting records is slower than copying and in order to reclaim table space you must run a lengthy "OPTIMIZE TABLE..." query afterwards
if (count($idsToRemove) == 0) continue;
$ids = "'" . implode("','", $idsToRemove) . "'";
$query = "DELETE FROM `$table` WHERE id IN($ids);";
$result = $this->db->query($query);
if (!$result) print("Error: Failed to trim itemId #$itemId from database!\n");
*/
}
print("Finished copying {$this->itemsCopied} items to temporary table $tmpTable!\n");
$query = "DROP TABLE `$table`;";
$result = $this->db->query($query);
if (!$result) die("Error: Failed to delete old '$table'!\n\t" . $this->db->error . "\n");
$query = "RENAME TABLE `$tmpTable` to `$table`;";
$result = $this->db->query($query);
if (!$result) die("Error: Failed to rename temporary table '$tmpTable' to '$table'!\n\t" . $this->db->error . "\n");
return true;
}
public function Run()
{
$suffix = GetEsoItemTableSuffix($this->version);
if ($suffix == "") die("Error: Unknown table suffix for version {$this->version}!\n");
print("WARNING: Trimming table minedItem$suffix for version {$this->version}. This is not reversible!\n");
print("Are you sure you wish to continue (Y/N)? ");
$input = strtolower(fgetc(STDIN));
if ($input !== 'y') die("\tAborting...\n");
$this->TrimItems();
print("\n");
}
};
$trim = new CEsoTrimOldMinedItems();
$trim->Run();
|
ce8567da12248718c9fa8add5497fe2bedd1f0b1
|
{
"blob_id": "ce8567da12248718c9fa8add5497fe2bedd1f0b1",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-09T15:14:22",
"content_id": "57a989f46a12d94b50671d79f86d90751e7e135f",
"detected_licenses": [
"MIT"
],
"directory_id": "5048cddef534d7e8e16a5ef18f04060f748f22d1",
"extension": "php",
"filename": "trimOldMinedItems.php",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 252250231,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 4791,
"license": "MIT",
"license_type": "permissive",
"path": "/trimOldMinedItems.php",
"provenance": "stack-edu-0051.json.gz:927526",
"repo_name": "uesp/uesp-esolog",
"revision_date": "2023-06-09T15:14:22",
"revision_id": "8589a0dd96284d22376453c0abe9f3e88e60cd5e",
"snapshot_id": "7e832c6d5b2d435466b1e2790753ca1018320191",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/uesp/uesp-esolog/8589a0dd96284d22376453c0abe9f3e88e60cd5e/trimOldMinedItems.php",
"visit_date": "2023-06-24T16:00:53.480295",
"added": "2024-11-19T01:09:49.345651+00:00",
"created": "2023-06-09T15:14:22",
"int_score": 3,
"score": 2.75,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0069.json.gz"
}
|
using System.Threading;
using Nito.Async;
namespace BotBits
{
public sealed class BotBitsSynchronizationContext : SynchronizationContext
{
/// <summary>
/// Initializes a new instance of the <see cref="BotBitsSynchronizationContext" /> class by using the
/// specified <see cref="BotBitsSynchronizationContext.ActionDispatcher" />.
/// </summary>
/// <param name="actionDispatcher">The action queue to associate with this <see cref="BotBits" />.</param>
internal BotBitsSynchronizationContext(ActionDispatcher actionDispatcher)
{
this.ActionDispatcher = actionDispatcher;
}
/// <summary>
/// Gets or sets the action queue for the thread to synchronize with.
/// </summary>
internal ActionDispatcher ActionDispatcher { get; set; }
/// <summary>
/// Creates a copy of this <see cref="BotBitsSynchronizationContext" />.
/// </summary>
/// <returns>The copy of this synchronization context.</returns>
/// <threadsafety>This method may be called by any thread at any time.</threadsafety>
public override SynchronizationContext CreateCopy()
{
return new BotBitsSynchronizationContext(this.ActionDispatcher);
}
/// <summary>
/// Invokes the callback in the synchronization context asynchronously. The callback is placed in the action queue.
/// </summary>
/// <param name="d">The delegate to call.</param>
/// <param name="state">The object passed to the delegate.</param>
/// <threadsafety>This method may be called by any thread at any time.</threadsafety>
public override void Post(SendOrPostCallback d, object state)
{
this.ActionDispatcher.QueueAction(() => d(state));
}
/// <summary>
/// Invokes the callback in the synchronization context synchronously. The callback is placed in the action queue.
/// </summary>
/// <param name="d">The delegate to call.</param>
/// <param name="state">The object passed to the delegate.</param>
/// <remarks>
/// <para>
/// This method cannot be called from the thread running the action queue associated with this synchronization
/// context.
/// </para>
/// </remarks>
public override void Send(SendOrPostCallback d, object state)
{
// ReSharper disable once AccessToDisposedClosure
using (var evt = new ManualResetEvent(false))
{
this.ActionDispatcher.QueueAction(() =>
{
d(state);
evt.Set();
});
evt.WaitOne();
}
}
}
}
|
856e6a0c86140c3f5d8f75f90202dd1c9e65a1e5
|
{
"blob_id": "856e6a0c86140c3f5d8f75f90202dd1c9e65a1e5",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-07T22:12:35",
"content_id": "6a64bf181a849e035c91c3023a6e71af5d767a22",
"detected_licenses": [
"MIT"
],
"directory_id": "91fca7a8c794fa5dd53ec1aba5c29541f48b1920",
"extension": "cs",
"filename": "BotBitsSynchronizationContext.cs",
"fork_events_count": 26,
"gha_created_at": "2015-02-02T21:38:16",
"gha_event_created_at": "2020-08-07T22:12:36",
"gha_language": "C#",
"gha_license_id": "MIT",
"github_id": 30210041,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 2857,
"license": "MIT",
"license_type": "permissive",
"path": "/BotBits/Helpers/BotBitsSynchronizationContext.cs",
"provenance": "stack-edu-0014.json.gz:652988",
"repo_name": "Yonom/BotBits",
"revision_date": "2020-08-07T22:12:35",
"revision_id": "79c3e8a4c0a0e8e783153380f350310908d11b60",
"snapshot_id": "4ca04d2c0464eda8dc84826a25818d6371e0cdae",
"src_encoding": "UTF-8",
"star_events_count": 18,
"url": "https://raw.githubusercontent.com/Yonom/BotBits/79c3e8a4c0a0e8e783153380f350310908d11b60/BotBits/Helpers/BotBitsSynchronizationContext.cs",
"visit_date": "2021-01-17T00:52:13.287709",
"added": "2024-11-19T01:00:51.698369+00:00",
"created": "2020-08-07T22:12:35",
"int_score": 3,
"score": 2.96875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0032.json.gz"
}
|
/*
Copyright (c) 2019. Vladimir Ulitin, Partners Healthcare and members of Forome Association
Developed by Vladimir Ulitin and Michael Bouzinier
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.
*/
package org.forome.annotation.utils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Map;
public class RuntimeExec {
public static class Result {
public final int exitCode;
public final String out;
public final String outError;
private Result(int exitCode, String out, String outError) {
this.exitCode = exitCode;
this.out = out;
this.outError = outError;
}
}
public static Result runCommand(String command) throws Exception{
return runCommand(command, null);
}
public static Result runCommand(String command, Map<String, String> args) throws Exception{
return runCommand(command, args, null, null);
}
public static Result runCommand(String command, Map<String, String> args, Map<String, String> environment, InputStream stdin) throws Exception{
//Строим запускаемую команду
String cmd = command;
if (args!=null) {
for(String key: args.keySet()) {
cmd = cmd.replaceAll("\\$\\{" + key + "\\}", args.get(key));
}
}
final ProcessBuilder processBuilder = new ProcessBuilder(cmd.split(" "));
final Map<String, String> processBuilderEnvironment = processBuilder.environment();
if (environment!=null) {
for (String key: environment.keySet()) {
processBuilderEnvironment.put(key, environment.get(key));
}
}
//Выполняем
Process process = processBuilder.start();
//Возможно мы хотим писать во входной поток приложению
if (stdin!=null) {
OutputStream os = process.getOutputStream();
int iByte;
while ((iByte = stdin.read()) != -1) {
os.write(iByte);
}
os.flush();
os.close();
}
//Считываем выходной поток данных
StringBuilder out = new StringBuilder();
String line;
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((line = in.readLine()) != null) {
out.append(line);
}
in.close();
//Считываем выходной поток ошибочных данных
StringBuilder outError = new StringBuilder();
BufferedReader inError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((line = inError.readLine()) != null) {
outError.append(line);
}
inError.close();
int exitCode = process.waitFor();//Ожидаем завершения
return new Result(
exitCode,
out.toString(),
outError.toString()
);
}
}
|
707ca0a8c9a11d8bb4c1e4f9c5f5840100caf3dd
|
{
"blob_id": "707ca0a8c9a11d8bb4c1e4f9c5f5840100caf3dd",
"branch_name": "refs/heads/master",
"committer_date": "2022-12-17T21:59:08",
"content_id": "ebc2f78cadd9319c5b0f912fcfcbec3fcc0a56d8",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "b27e59eaa61fe0861baecee47f4b3ac59267c93f",
"extension": "java",
"filename": "RuntimeExec.java",
"fork_events_count": 5,
"gha_created_at": "2019-02-15T22:47:00",
"gha_event_created_at": "2022-06-13T06:45:43",
"gha_language": "Java",
"gha_license_id": "Apache-2.0",
"github_id": 170938347,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3215,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/annotation-service/src/main/java/org/forome/annotation/utils/RuntimeExec.java",
"provenance": "stack-edu-0020.json.gz:524268",
"repo_name": "ForomePlatform/Anfisa-Annotations",
"revision_date": "2022-12-17T21:59:08",
"revision_id": "35b428f3348284237296c80b23c982e5dc29de62",
"snapshot_id": "1eea8cb42d05cfee6d93d6d4ad1949cb394c95ca",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ForomePlatform/Anfisa-Annotations/35b428f3348284237296c80b23c982e5dc29de62/annotation-service/src/main/java/org/forome/annotation/utils/RuntimeExec.java",
"visit_date": "2022-12-25T11:25:04.576220",
"added": "2024-11-18T18:52:39.761826+00:00",
"created": "2022-12-17T21:59:08",
"int_score": 3,
"score": 2.640625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0038.json.gz"
}
|
use crate::app::State;
use crate::render::mesh::non_skinned_mesh::MeshRenderOpts;
use crate::render::Render;
use crate::render::TextureUnit;
use crate::shader::Shader;
use crate::shader::ShaderKind;
use blender_armature::ActionSettings;
use blender_armature::BlenderArmature;
use blender_armature::InterpolationSettings;
use blender_mesh::BlenderMesh;
use nalgebra;
use nalgebra::{Isometry3, Vector3};
use web_sys::WebGlRenderingContext as GL;
use web_sys::*;
pub struct SkinnedMesh<'a> {
pub mesh: &'a BlenderMesh,
pub armature: &'a BlenderArmature,
pub shader: &'a Shader,
pub opts: &'a MeshRenderOpts,
}
impl<'a> Render<'a> for SkinnedMesh<'a> {
fn shader_kind() -> ShaderKind {
ShaderKind::SkinnedMesh
}
fn shader(&'a self) -> &'a Shader {
&self.shader
}
fn buffer_attributes(&self, gl: &WebGlRenderingContext) {
let shader = self.shader();
let mesh = self.mesh;
let pos_attrib = gl.get_attrib_location(&shader.program, "position");
let normal_attrib = gl.get_attrib_location(&shader.program, "normal");
let uv_attrib = gl.get_attrib_location(&shader.program, "uvs");
gl.enable_vertex_attrib_array(pos_attrib as u32);
gl.enable_vertex_attrib_array(normal_attrib as u32);
gl.enable_vertex_attrib_array(uv_attrib as u32);
let joint_indices_attrib = gl.get_attrib_location(&shader.program, "jointIndices");
let joint_weights_attrib = gl.get_attrib_location(&shader.program, "jointWeights");
gl.enable_vertex_attrib_array(joint_indices_attrib as u32);
gl.enable_vertex_attrib_array(joint_weights_attrib as u32);
SkinnedMesh::buffer_u8_data(
&gl,
&mesh.vertex_group_indices.as_ref().expect("Group indices")[..],
joint_indices_attrib as u32,
4,
);
SkinnedMesh::buffer_f32_data(
&gl,
&mesh.vertex_group_weights.as_ref().expect("Group weights")[..],
joint_weights_attrib as u32,
4,
);
SkinnedMesh::buffer_f32_data(&gl, &mesh.vertex_positions[..], pos_attrib as u32, 3);
SkinnedMesh::buffer_f32_data(&gl, &mesh.vertex_normals[..], normal_attrib as u32, 3);
SkinnedMesh::buffer_f32_data(
&gl,
&mesh.vertex_uvs.as_ref().expect("Mesh uvs")[..],
uv_attrib as u32,
2,
);
SkinnedMesh::buffer_u16_indices(&gl, &mesh.vertex_position_indices[..]);
}
fn render(&self, gl: &WebGlRenderingContext, state: &State) {
let shader = self.shader();
let mesh = self.mesh;
let opts = self.opts;
let pos = opts.pos;
let model_uni = shader.get_uniform_location(gl, "model");
let view_uni = shader.get_uniform_location(gl, "view");
let camera_pos_uni = shader.get_uniform_location(gl, "cameraPos");
let perspective_uni = shader.get_uniform_location(gl, "perspective");
let clip_plane_uni = shader.get_uniform_location(gl, "clipPlane");
let mesh_texture_uni = shader.get_uniform_location(gl, "meshTexture");
gl.uniform4fv_with_f32_array(clip_plane_uni.as_ref(), &mut opts.clip_plane.clone()[..]);
let mut view = if opts.flip_camera_y {
state.camera().view_flipped_y()
} else {
state.camera().view()
};
gl.uniform_matrix4fv_with_f32_array(view_uni.as_ref(), false, &mut view);
let model = Isometry3::new(Vector3::new(pos.0, pos.1, pos.2), nalgebra::zero());
let mut model_array = [0.; 16];
model_array.copy_from_slice(model.to_homogeneous().as_slice());
gl.uniform_matrix4fv_with_f32_array(model_uni.as_ref(), false, &mut model_array);
let mut perspective = state.camera().projection();
gl.uniform_matrix4fv_with_f32_array(perspective_uni.as_ref(), false, &mut perspective);
let camera_pos = state.camera().get_eye_pos();
let mut camera_pos = [camera_pos.x, camera_pos.y, camera_pos.z];
gl.uniform3fv_with_f32_array(camera_pos_uni.as_ref(), &mut camera_pos);
gl.uniform1i(mesh_texture_uni.as_ref(), TextureUnit::Stone.texture_unit());
self.set_armature_uniforms(gl, state);
let num_indices = mesh.vertex_position_indices.len();
gl.draw_elements_with_i32(GL::TRIANGLES, num_indices as i32, GL::UNSIGNED_SHORT, 0);
}
}
impl<'a> SkinnedMesh<'a> {
fn set_armature_uniforms(&self, gl: &WebGlRenderingContext, state: &State) {
let shader = self.shader();
let armature = &self.armature;
let clock = state.clock();
let current_time_secs = clock / 1000.0;
let interp_opts = InterpolationSettings {
current_time: current_time_secs,
joint_indices: vec![0, 1, 2, 3, 4, 5, 6, 7, 8],
blend_fn: None,
current_action: ActionSettings::new("Fly.001", 0.0, true),
previous_action: None,
};
let bones = armature.interpolate_bones(&interp_opts);
let bone_count = bones.len() as u8;
for index in 0..bone_count {
let bone = bones.get(&index).expect("Interpolated bone");
let bone = bone.as_slice();
let (rot_quat, trans_quat) = bone.split_at(4);
let (rq, tq) = (rot_quat, trans_quat);
let rot_quat_uni =
shader.get_uniform_location(gl, &format!("boneRotQuaternions[{}]", index));
gl.uniform4f(rot_quat_uni.as_ref(), rq[0], rq[1], rq[2], rq[3]);
let trans_quat_uni =
shader.get_uniform_location(gl, &format!("boneTransQuaternions[{}]", index));
gl.uniform4f(trans_quat_uni.as_ref(), tq[0], tq[1], tq[2], tq[3]);
}
}
}
|
302cb0275b4140128b8bf2a1c8305042d614d80c
|
{
"blob_id": "302cb0275b4140128b8bf2a1c8305042d614d80c",
"branch_name": "refs/heads/master",
"committer_date": "2022-06-20T17:23:33",
"content_id": "ac36347b0b6fd8c32d7d296b36afb2232ac19eeb",
"detected_licenses": [
"MIT",
"Apache-2.0"
],
"directory_id": "778bea80fb09c59bb85e7b6f5c96ac38e5cdee80",
"extension": "rs",
"filename": "skinned_mesh.rs",
"fork_events_count": 44,
"gha_created_at": "2018-12-31T20:06:19",
"gha_event_created_at": "2022-06-20T17:23:34",
"gha_language": "Rust",
"gha_license_id": "Apache-2.0",
"github_id": 163694762,
"is_generated": false,
"is_vendor": false,
"language": "Rust",
"length_bytes": 5791,
"license": "MIT,Apache-2.0",
"license_type": "permissive",
"path": "/src/render/mesh/skinned_mesh.rs",
"provenance": "stack-edu-0068.json.gz:309248",
"repo_name": "chinedufn/webgl-water-tutorial",
"revision_date": "2022-06-20T17:23:33",
"revision_id": "99a02acc9cb569c623ac4b5a16e0de246e5a98bf",
"snapshot_id": "98f034dad7733fe604b347ff46865d38c10b976f",
"src_encoding": "UTF-8",
"star_events_count": 481,
"url": "https://raw.githubusercontent.com/chinedufn/webgl-water-tutorial/99a02acc9cb569c623ac4b5a16e0de246e5a98bf/src/render/mesh/skinned_mesh.rs",
"visit_date": "2022-07-08T10:07:06.236330",
"added": "2024-11-19T02:18:25.453441+00:00",
"created": "2022-06-20T17:23:33",
"int_score": 2,
"score": 2.125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0086.json.gz"
}
|
using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using Res = WPF.Properties.Resources;
using WPF.ServiceDALReference;
using DALService = WPF.ServiceDALReference.ServiceDALClient;
namespace WPF
{
public partial class MainWindow
{
private readonly DALService _service = new DALService();
public ObservableCollection<Person> People = new ObservableCollection<Person>();
static MainWindow()
{
CultureInfo currentCulture = CultureInfo.CurrentCulture;
Thread.CurrentThread.CurrentCulture = currentCulture;
Thread.CurrentThread.CurrentUICulture = currentCulture;
}
public MainWindow()
{
InitializeComponent();
this._service.Open();
LoadPeople();
}
private void LoadPeople()
{
this.ListView.Items.Clear();
foreach (Person person in this._service.GetPeople())
{
person.Password = "********";
this.ListView.Items.Add(person);
}
}
private void LoginButton_Click(object sender, RoutedEventArgs e)
{
string username = this.LoginUsernameTextBox.Text,
password = this.LoginPasswordTextBox.Text;
Person person = this._service.Find(username, password);
if (person != null)
{
this.LoginTextBlock.Text = person.Name;
this.StatusBarItem.Content = Res.Ready;
}
else
{
this.LoginTextBlock.Text = string.Empty;
this.StatusBarItem.Content = Res.UserNotFound;
}
}
private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if ((sender as ListView)?.SelectedItem is Person person)
{
this.UsernameTextBox.Text = person.Username;
this.PasswordTextBox.Text = string.Empty;
this.NameTextBox.Text = person.Name;
}
}
private void AddButton_Click(object sender, RoutedEventArgs e)
{
string username = this.UsernameTextBox.Text,
password = this.PasswordTextBox.Text,
name = this.NameTextBox.Text;
if (!string.IsNullOrEmpty(username)
&& !string.IsNullOrEmpty(password)
&& !string.IsNullOrEmpty(this.NameTextBox.Text))
{
Person person = this._service.Find(username, null);
if (person == null)
{
if (this._service.AddPerson(new Person
{
Username = username,
Password = password,
Name = name
}))
{
LoadPeople();
this.StatusBarItem.Content = Res.Ready;
}
else
{
this.StatusBarItem.Content = Res.UserExists;
}
}
}
}
private void EditButton_Click(object sender, RoutedEventArgs e)
{
if ((this.ListView.SelectedIndex != -1) && !string.IsNullOrEmpty(this.PasswordTextBox.Text))
{
var person = (Person) this.ListView.SelectedItem;
string username = this.UsernameTextBox.Text,
password = this.PasswordTextBox.Text,
name = this.NameTextBox.Text;
person.Username = username;
person.Password = password;
person.Name = name;
if (this._service.EditPerson(person))
{
LoadPeople();
this.StatusBarItem.Content = Res.Ready;
}
else
{
this.StatusBarItem.Content = Res.UserNotFound;
}
}
}
private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
if (this.ListView.SelectedIndex != -1)
{
var person = (Person) this.ListView.SelectedItem;
if (this._service.RemovePerson(person.Id))
{
LoadPeople();
this.StatusBarItem.Content = Res.Ready;
}
}
}
protected override void OnClosed(EventArgs e)
{
this._service.Close();
base.OnClosed(e);
}
}
}
|
b255fd5c410a1aeb9b5c64a6da2de3ec30d215b4
|
{
"blob_id": "b255fd5c410a1aeb9b5c64a6da2de3ec30d215b4",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-17T13:04:27",
"content_id": "ef22b5eaa3e4398012fcfd39ccfda428e1260014",
"detected_licenses": [
"MIT"
],
"directory_id": "ada949b370e332982763dca2164361c69f209549",
"extension": "cs",
"filename": "MainWindow.xaml.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 108903990,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 3556,
"license": "MIT",
"license_type": "permissive",
"path": "/Lab05Solution/WPF/MainWindow.xaml.cs",
"provenance": "stack-edu-0011.json.gz:438730",
"repo_name": "tmikuczewski/AEiI-SSM-Inf-SemII-P.NET",
"revision_date": "2018-02-17T13:04:27",
"revision_id": "99c05976d654b67fed231af2584a8c25645a0658",
"snapshot_id": "8cd2d20296dbaff7640f899117193695bd39037d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/tmikuczewski/AEiI-SSM-Inf-SemII-P.NET/99c05976d654b67fed231af2584a8c25645a0658/Lab05Solution/WPF/MainWindow.xaml.cs",
"visit_date": "2021-09-07T04:24:59.216940",
"added": "2024-11-19T01:37:16.140400+00:00",
"created": "2018-02-17T13:04:27",
"int_score": 2,
"score": 2.4375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0029.json.gz"
}
|
"""
@author: Thomas PERROT
Contains serializers for stats app
"""
from rest_framework import serializers
from .models import Price, Statistics
class PriceSerializer(serializers.HyperlinkedModelSerializer):
card_id = serializers.ReadOnlyField(source='card.id')
class Meta:
model = Price
fields = ('card_id', 'date', 'available_items', 'min_price', 'mean_price', 'available_foils', 'min_foil')
class StatisticsSerializer(serializers.HyperlinkedModelSerializer):
card_id = serializers.ReadOnlyField(source='card.id')
card_name = serializers.ReadOnlyField(source='card.name.name')
card_set = serializers.ReadOnlyField(source='card.set.name')
class Meta:
model = Statistics
fields = ('card_id', 'card_name', 'card_set', 'date', 'predicted_price', 'price_ratio', 'playing_ratio')
|
a0a8586f145ef79c5153b390641693423833e18d
|
{
"blob_id": "a0a8586f145ef79c5153b390641693423833e18d",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-09T17:30:14",
"content_id": "2115e63742bb76344ac445ed30c50f06708211b4",
"detected_licenses": [
"MIT"
],
"directory_id": "9f67b5652ce8bd626f75eb9b225163651955b7f1",
"extension": "py",
"filename": "serializers.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 840,
"license": "MIT",
"license_type": "permissive",
"path": "/mtg/stats/serializers.py",
"provenance": "stack-edu-0059.json.gz:36239",
"repo_name": "kyle-crews/MTGTrader",
"revision_date": "2017-07-09T17:30:14",
"revision_id": "36c2d4992bb5cfff48e36aeb48c0fc8122d8a8b0",
"snapshot_id": "58738f42af3f589f206ce3d936ba3a0aa62768c0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kyle-crews/MTGTrader/36c2d4992bb5cfff48e36aeb48c0fc8122d8a8b0/mtg/stats/serializers.py",
"visit_date": "2020-08-19T09:50:28.817616",
"added": "2024-11-19T00:37:03.233902+00:00",
"created": "2017-07-09T17:30:14",
"int_score": 2,
"score": 2.359375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0077.json.gz"
}
|
using Microsoft.Diagnostics.Runtime;
using Microsoft.Diagnostics.Runtime.Implementation;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
namespace ParallelStressTest
{
static class Program
{
const bool BackgroundClear = true;
const int Iterations = int.MaxValue;
const int Threads = 8;
static readonly object _sync = new object();
private static ClrObject[] _expectedObjects;
private static ClrSegment[] _segments;
private static readonly ManualResetEvent _event = new ManualResetEvent(initialState: false);
private static volatile ClrRuntime _runtimeForClearing;
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("Must specify a crash dump to inspect.");
if (Debugger.IsAttached)
Debugger.Break();
Environment.Exit(1);
}
using DataTarget dt = DataTarget.LoadDump(args[0]);
using (ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime())
{
_expectedObjects = runtime.Heap.EnumerateObjects().ToArray();
_segments = runtime.Heap.Segments.ToArray();
}
if (BackgroundClear)
{
Thread t = new Thread(ClearThreadProc);
t.Start();
}
TimeSpan elapsed = default;
for (int i = 0; i < Iterations; i++)
{
Console.Write($"\rIteration: {i + 1:n0} {elapsed}");
dt.DataReader.FlushCachedData();
using ClrRuntime runtime = dt.ClrVersions.Single().CreateRuntime();
lock (_sync)
_runtimeForClearing = runtime;
Thread[] threads = new Thread[Threads];
for (int j = 0; j < Threads; j++)
threads[j] = CreateAndStartThread(runtime);
Stopwatch sw = new Stopwatch();
sw.Start();
_event.Set();
foreach (Thread thread in threads)
thread.Join();
sw.Stop();
elapsed = sw.Elapsed;
lock (_sync)
_runtimeForClearing = null;
_event.Reset();
}
}
private static void ClearThreadProc()
{
while (true)
{
lock (_sync)
{
if (_runtimeForClearing != null)
_runtimeForClearing.FlushCachedData();
}
Thread.Sleep(500);
}
}
private static Thread CreateAndStartThread(ClrRuntime runtime)
{
Thread t = new Thread(() => WorkerThread(runtime));
t.Start();
return t;
}
private static void WorkerThread(ClrRuntime runtime)
{
//ClrmdHeap.LogHeapWalkSteps(32);
_event.WaitOne();
if (_segments.Length != runtime.Heap.Segments.Length)
{
Fail(false, $"Segment count mismatch. Expected {_segments.Length} segments, found {runtime.Heap.Segments.Length}.");
}
for (int i = 0; i < _segments.Length; i++)
if (runtime.Heap.Segments[i].ObjectRange.Start != _segments[i].ObjectRange.Start)
Fail(false, $"Segment[{i}] range {runtime.Heap.Segments[i].ObjectRange}, expected {_segments[i].ObjectRange}");
int count = 0;
IEnumerator<ClrObject> enumerator = runtime.Heap.EnumerateObjects().GetEnumerator();
while (enumerator.MoveNext())
{
ClrObject curr = enumerator.Current;
if (curr.Address != _expectedObjects[count].Address)
Fail(true, $"Object {count} was incorrect address: Expected {_expectedObjects[count].Address:x12}, got {curr.Address:x12}");
if (curr.Type != _expectedObjects[count].Type)
Fail(true, $"Object {count} was incorrect type: Expected {_expectedObjects[count].Type.Name}, got {curr.Type?.Name ?? ""}");
count++;
}
if (count != _expectedObjects.Count())
Fail(true, $"Expected {_expectedObjects.Length:n0} objects, found {count:n0}.");
}
private static void Fail(bool printHeapSteps, string reason)
{
lock (_sync)
{
Console.WriteLine();
Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId:x}");
Console.WriteLine(reason);
//if (printHeapSteps)
//{
// int i = ClrmdHeap.Step;
// do
// {
// i = (i + 1) % ClrmdHeap.Steps.Count;
// HeapWalkStep step = ClrmdHeap.Steps[i];
// Console.WriteLine($"obj:{step.Address:x12} mt:{step.MethodTable:x12} base:{step.BaseSize:x8} comp:{step.ComponentSize:x8} count:{step.Count:x8}");
// } while (i != ClrmdHeap.Step);
//}
}
Break();
}
private static void Break()
{
if (Debugger.IsAttached)
Debugger.Break();
while (!Debugger.IsAttached)
Thread.Sleep(1000);
}
}
}
|
a4314c9aa0d4517b0133013c1b372c67e23e0f2d
|
{
"blob_id": "a4314c9aa0d4517b0133013c1b372c67e23e0f2d",
"branch_name": "refs/heads/master",
"committer_date": "2023-01-05T20:35:04",
"content_id": "9f18cfadb56a98e3bd2715d7fec4c2ef8955cf4f",
"detected_licenses": [
"MIT"
],
"directory_id": "9477578d1cdcb5d914b2514ef28a40f3fb915e97",
"extension": "cs",
"filename": "Program.cs",
"fork_events_count": 5,
"gha_created_at": "2017-04-26T15:34:46",
"gha_event_created_at": "2023-04-07T17:26:30",
"gha_language": "C#",
"gha_license_id": "MIT",
"github_id": 89497906,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 5564,
"license": "MIT",
"license_type": "permissive",
"path": "/src/LongRunningTests/ParallelStressTest/Program.cs",
"provenance": "stack-edu-0009.json.gz:846244",
"repo_name": "JetBrains/clrmd",
"revision_date": "2023-01-05T20:35:04",
"revision_id": "8a56bfb39c3a8361f278a092cebce3f8ac0040cc",
"snapshot_id": "da26f8929c746fbc819701fb99712dd75107da97",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/JetBrains/clrmd/8a56bfb39c3a8361f278a092cebce3f8ac0040cc/src/LongRunningTests/ParallelStressTest/Program.cs",
"visit_date": "2023-09-03T20:59:42.903866",
"added": "2024-11-18T19:26:34.695970+00:00",
"created": "2023-01-05T20:35:04",
"int_score": 2,
"score": 2.5,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0027.json.gz"
}
|
package k8s
import (
"context"
"github.com/cybozu-go/cke"
"github.com/cybozu-go/cke/op"
"github.com/cybozu-go/cke/op/common"
"k8s.io/client-go/tools/clientcmd"
)
type schedulerBootOp struct {
nodes []*cke.Node
cluster string
params cke.SchedulerParams
step int
files *common.FilesBuilder
}
// SchedulerBootOp returns an Operator to bootstrap kube-scheduler
func SchedulerBootOp(nodes []*cke.Node, cluster string, params cke.SchedulerParams) cke.Operator {
return &schedulerBootOp{
nodes: nodes,
cluster: cluster,
params: params,
files: common.NewFilesBuilder(nodes),
}
}
func (o *schedulerBootOp) Name() string {
return "kube-scheduler-bootstrap"
}
func (o *schedulerBootOp) NextCommand() cke.Commander {
switch o.step {
case 0:
o.step++
return common.ImagePullCommand(o.nodes, cke.KubernetesImage)
case 1:
o.step++
return prepareSchedulerFilesCommand{o.cluster, o.files, o.params}
case 2:
o.step++
return o.files
case 3:
o.step++
return common.RunContainerCommand(o.nodes, op.KubeSchedulerContainerName, cke.KubernetesImage,
common.WithParams(SchedulerParams()),
common.WithExtra(o.params.ServiceParams))
default:
return nil
}
}
func (o *schedulerBootOp) Targets() []string {
ips := make([]string, len(o.nodes))
for i, n := range o.nodes {
ips[i] = n.Address
}
return ips
}
type prepareSchedulerFilesCommand struct {
cluster string
files *common.FilesBuilder
params cke.SchedulerParams
}
func (c prepareSchedulerFilesCommand) Run(ctx context.Context, inf cke.Infrastructure, _ string) error {
storage := inf.Storage()
ca, err := storage.GetCACertificate(ctx, cke.CAKubernetes)
if err != nil {
return err
}
g := func(ctx context.Context, n *cke.Node) ([]byte, error) {
crt, key, err := cke.KubernetesCA{}.IssueForScheduler(ctx, inf)
if err != nil {
return nil, err
}
cfg := schedulerKubeconfig(c.cluster, ca, crt, key)
return clientcmd.Write(*cfg)
}
err = c.files.AddFile(ctx, op.SchedulerKubeConfigPath, g)
if err != nil {
return err
}
return c.files.AddFile(ctx, op.SchedulerConfigPath, func(ctx context.Context, n *cke.Node) ([]byte, error) {
cfg := GenerateSchedulerConfiguration(c.params)
return encodeToYAML(cfg)
})
}
func (c prepareSchedulerFilesCommand) Command() cke.Command {
return cke.Command{
Name: "prepare-scheduler-files",
}
}
// SchedulerParams returns parameters for kube-scheduler.
func SchedulerParams() cke.ServiceParams {
args := []string{
"kube-scheduler",
"--config=" + op.SchedulerConfigPath,
"--authentication-kubeconfig=" + op.SchedulerKubeConfigPath,
"--authorization-kubeconfig=" + op.SchedulerKubeConfigPath,
// for healthz service
"--tls-cert-file=" + op.K8sPKIPath("apiserver.crt"),
"--tls-private-key-file=" + op.K8sPKIPath("apiserver.key"),
}
return cke.ServiceParams{
ExtraArguments: args,
ExtraBinds: []cke.Mount{
{
Source: "/etc/machine-id",
Destination: "/etc/machine-id",
ReadOnly: true,
Propagation: "",
Label: "",
},
{
Source: "/etc/kubernetes",
Destination: "/etc/kubernetes",
ReadOnly: true,
Propagation: "",
Label: cke.LabelShared,
},
},
}
}
|
ed7e7b7f26d9beb6ecc521ef9d0975dae258a662
|
{
"blob_id": "ed7e7b7f26d9beb6ecc521ef9d0975dae258a662",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-17T09:37:00",
"content_id": "2c63126ecbf6b2bc06f9da8b5669e0a3e2a69c68",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "4e982b94a4c71f9c90cd5da6aec413c532962e8f",
"extension": "go",
"filename": "scheduler_boot.go",
"fork_events_count": 14,
"gha_created_at": "2018-07-09T09:15:12",
"gha_event_created_at": "2023-09-13T08:21:58",
"gha_language": "Go",
"gha_license_id": "Apache-2.0",
"github_id": 140261100,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 3212,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/op/k8s/scheduler_boot.go",
"provenance": "stack-edu-0017.json.gz:449888",
"repo_name": "cybozu-go/cke",
"revision_date": "2023-08-17T09:37:00",
"revision_id": "c798e29376bfbb00a3fb98261f4359346e35f972",
"snapshot_id": "e4a45a15f5c88660731ac1b36957fe99b04960f5",
"src_encoding": "UTF-8",
"star_events_count": 174,
"url": "https://raw.githubusercontent.com/cybozu-go/cke/c798e29376bfbb00a3fb98261f4359346e35f972/op/k8s/scheduler_boot.go",
"visit_date": "2023-08-17T21:14:18.763225",
"added": "2024-11-18T21:05:57.280982+00:00",
"created": "2023-08-17T09:37:00",
"int_score": 2,
"score": 2.125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0035.json.gz"
}
|
import unittest
import os
from ansiblevars.project import Project
class TestProject(unittest.TestCase):
def setUp(self):
path = os.getcwd() + "/test/artifacts"
self.sut = Project(path, None)
def test_getPlaybooks_includesPlaybook1(self):
name = "playbook1"
playbook = self.sut.get_playbook(name)
self.assertIsNotNone(playbook)
self.assertEqual(name, playbook.get_name())
def test_getRoles_includesRole1(self):
name = "role1"
role = self.sut.get_role(name)
self.assertIsNotNone(role)
self.assertEqual(name, role.get_role_name())
if __name__ == '__main__':
unittest.main()
|
78c687ee44991835cf063305f52cf68330a51828
|
{
"blob_id": "78c687ee44991835cf063305f52cf68330a51828",
"branch_name": "refs/heads/master",
"committer_date": "2017-11-19T18:02:55",
"content_id": "aa2f669812b0995cc9fd6ca6b808dd4b97bb78f3",
"detected_licenses": [
"Unlicense"
],
"directory_id": "f39f4296998cc76708f6a12baf98d31564697b14",
"extension": "py",
"filename": "TestProject.py",
"fork_events_count": 0,
"gha_created_at": "2017-06-04T16:29:25",
"gha_event_created_at": "2017-07-07T23:04:14",
"gha_language": "Python",
"gha_license_id": null,
"github_id": 93326412,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 673,
"license": "Unlicense",
"license_type": "permissive",
"path": "/test/TestProject.py",
"provenance": "stack-edu-0058.json.gz:414375",
"repo_name": "lostbearlabs/ansible-vars",
"revision_date": "2017-11-19T18:02:55",
"revision_id": "3ca5e9acb4a30aee2400217667df32b5d7873080",
"snapshot_id": "4e79a54c6461eb64be18dba1db9ad01ed28fab1c",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/lostbearlabs/ansible-vars/3ca5e9acb4a30aee2400217667df32b5d7873080/test/TestProject.py",
"visit_date": "2021-01-24T06:49:43.519330",
"added": "2024-11-18T19:38:33.489531+00:00",
"created": "2017-11-19T18:02:55",
"int_score": 2,
"score": 2.5,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0076.json.gz"
}
|
"""Try to replicate my bash environment"""
from pysyte.paths import environ_path
def _environ_dir(name):
"""Find the path in environment and convert to a Path
or None if nnot found
>>> _environ_dir('HOME').isdir()
True
"""
try:
result = environ_path(name)
except KeyError:
return None
if not (result.isdir() or result.isfile()):
return None
return result
def _load_environment_paths():
"""Look for expected paths in environment
Put them in module globals
"""
jab_paths = [
'HOME', 'PYTHON']
for _ in jab_paths:
globals()[_] = _environ_dir(_)
try:
_ = HOME # pylint: disable=undefined-variable
except NameError:
_load_environment_paths()
|
768a138fee74673b057be0fd6098949976a533cc
|
{
"blob_id": "768a138fee74673b057be0fd6098949976a533cc",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-02T09:48:36",
"content_id": "cb2959651dfcce4f3c731ca27be2b2f416614151",
"detected_licenses": [
"MIT"
],
"directory_id": "d9206bf446af15299b67ed2ed721adefb68ca0a6",
"extension": "py",
"filename": "environ.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 752,
"license": "MIT",
"license_type": "permissive",
"path": "/src/python/pyjab/jab/environ.py",
"provenance": "stack-edu-0063.json.gz:445299",
"repo_name": "Zeroundefined/jab",
"revision_date": "2018-11-02T09:48:32",
"revision_id": "af78b9e91bd51505705b2387a9d4a5ac5f4be671",
"snapshot_id": "a19062dd5403d38fb7200bec6879ca6c66de0315",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Zeroundefined/jab/af78b9e91bd51505705b2387a9d4a5ac5f4be671/src/python/pyjab/jab/environ.py",
"visit_date": "2020-04-09T16:13:50.428723",
"added": "2024-11-19T00:17:37.385028+00:00",
"created": "2018-11-02T09:48:32",
"int_score": 3,
"score": 2.984375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0081.json.gz"
}
|
using System.Collections.Generic;
using Codelyzer.Analysis;
using CTA.Rules.Config;
namespace CTA.Rules.Metrics
{
public class MetricsContext
{
public string SolutionPath { get; set; }
public string SolutionPathHash { get; set; }
public Dictionary<string, string> ProjectGuidMap { get; set; }
public MetricsContext(string solutionPath, IEnumerable<AnalyzerResult> analyzerResults)
{
SolutionPath = solutionPath;
SolutionPathHash = EncryptionHelper.ConvertToSHA256Hex(solutionPath);
SetProjectGuidMap(analyzerResults);
}
private void SetProjectGuidMap(IEnumerable<AnalyzerResult> analyzerResults)
{
ProjectGuidMap = new Dictionary<string, string>();
foreach (var analyzerResult in analyzerResults)
{
var projectName = analyzerResult.ProjectResult.ProjectFilePath;
var projectGuid = analyzerResult.ProjectResult.ProjectGuid;
ProjectGuidMap[projectName] = projectGuid;
}
}
}
}
|
7ab262631476925367d7719ede60df9e2f98065c
|
{
"blob_id": "7ab262631476925367d7719ede60df9e2f98065c",
"branch_name": "refs/heads/main",
"committer_date": "2021-07-02T17:46:56",
"content_id": "32cb59dd4b6ff883bc1e222908ec99780c5250a9",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "83e1e3070f09ebb9ee815ec58db5308c06e7c13c",
"extension": "cs",
"filename": "MetricsContext.cs",
"fork_events_count": 0,
"gha_created_at": "2021-07-10T14:06:03",
"gha_event_created_at": "2021-07-10T14:06:04",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 384712405,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1096,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/CTA.Rules.Metrics/Models/MetricsContext.cs",
"provenance": "stack-edu-0012.json.gz:844082",
"repo_name": "QPC-database/cta",
"revision_date": "2021-07-02T17:46:56",
"revision_id": "e0543467594952bb70707876647a6b6802f5a3d0",
"snapshot_id": "17918683b3f4b76845a673c31b339b73c71f0ce8",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/QPC-database/cta/e0543467594952bb70707876647a6b6802f5a3d0/src/CTA.Rules.Metrics/Models/MetricsContext.cs",
"visit_date": "2023-06-12T11:34:52.130181",
"added": "2024-11-19T01:50:29.533390+00:00",
"created": "2021-07-02T17:46:56",
"int_score": 2,
"score": 2.203125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0030.json.gz"
}
|
import { LineCoordsProviderBase } from './line-coords-provider-base';
export class DiamondLineCoordsProvider extends LineCoordsProviderBase {
constructor(source: { x: number, y: number }, target: { x: number, y: number }, private dimension: number) {
super(source, target);
}
protected getLineStart(): {x: number, y: number} {
let x: number = this.x(this.target, this.source);
let y: number = this.y(this.target, this.source);
return {
x: this.source.x + x,
y: this.source.y + y
};
}
protected getLineEnd(): {x: number, y: number} {
let x: number = this.x(this.source, this.target);
let y: number = this.y(this.source, this.target);
return {
x: this.target.x + x,
y: this.target.y + y
};
}
private a1(source: {x: number, y: number}, target: {x: number, y: number}): number {
if (this.q1(source, target) || this.q3(source, target)) {
return 1;
}
return -1;
}
private c1(source: {x: number, y: number}, target: {x: number, y: number}): number {
if (this.q1(source, target) || this.q2(source, target)) {
return this.dimension;
}
return -this.dimension;
}
private a2(source: {x: number, y: number}, target: {x: number, y: number}): number {
return (source.y - target.y) / (source.x - target.x);
}
private c2(source: {x: number, y: number}, target: {x: number, y: number}): number {
return 0;
}
private x(source: {x: number, y: number}, target: {x: number, y: number}): number {
return (this.c2(source, target) - this.c1(source, target)) / (this.a1(source, target) - this.a2(source, target));
}
private y(source: {x: number, y: number}, target: {x: number, y: number}): number {
return this.a1(source, target) * this.x(source, target) + this.c1(source, target);
}
private q1(source: {x: number, y: number}, target: {x: number, y: number}): boolean {
return source.x <= target.x && source.y > target.y;
}
private q2(source: {x: number, y: number}, target: {x: number, y: number}): boolean {
return source.x > target.x && source.y >= target.y;
}
private q3(source: {x: number, y: number}, target: {x: number, y: number}): boolean {
return source.x >= target.x && source.y < target.y;
}
private q4(source: {x: number, y: number}, target: {x: number, y: number}): boolean {
return source.x < target.x && source.y <= target.y;
}
}
|
b271091207c931fdab267ca1f424c115df253a7c
|
{
"blob_id": "b271091207c931fdab267ca1f424c115df253a7c",
"branch_name": "refs/heads/develop",
"committer_date": "2019-08-29T07:04:21",
"content_id": "572edddbfa1af69ad1bfab09b90a76be303f95bf",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c7f5371fb132415d3a070a8859435eac5e1873d9",
"extension": "ts",
"filename": "diamond-line-coords-provider.ts",
"fork_events_count": 41,
"gha_created_at": "2016-12-21T12:10:02",
"gha_event_created_at": "2019-10-30T07:31:13",
"gha_language": "Java",
"gha_license_id": "Apache-2.0",
"github_id": 77048443,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 2667,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/web/src/app/modules/views/main/editors/modules/graphical-editor/providers/coordinates/diamond-line-coords-provider.ts",
"provenance": "stack-edu-0073.json.gz:530647",
"repo_name": "junkerm/specmate",
"revision_date": "2019-08-29T07:04:21",
"revision_id": "fd34097fcecfb74aefc1371e94d8a14915cefa22",
"snapshot_id": "73bb0791ca1373737c3a0c0d781a31cfa747ee28",
"src_encoding": "UTF-8",
"star_events_count": 13,
"url": "https://raw.githubusercontent.com/junkerm/specmate/fd34097fcecfb74aefc1371e94d8a14915cefa22/web/src/app/modules/views/main/editors/modules/graphical-editor/providers/coordinates/diamond-line-coords-provider.ts",
"visit_date": "2021-01-13T11:29:33.949235",
"added": "2024-11-18T19:35:11.659471+00:00",
"created": "2019-08-29T07:04:21",
"int_score": 3,
"score": 3.09375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0091.json.gz"
}
|
"""Parsing logic for RepoBee's primary parser.
This is separated into its own module as it is a relatively complex affair.
Any non-trivial parsing logic should go in here, whereas definitions of
the primary parser should go int :py:mod:`_repobee.cli.mainparser`.
.. module:: parsing
:synopsis: Parsing logic for RepoBee's primary parser.
.. moduleauthor:: Simon Larsén
"""
import argparse
import logging
import os
import pathlib
import re
import sys
import enum
from typing import Iterable, Optional, List, Tuple
import argcomplete # type: ignore
import daiquiri # type: ignore
import repobee_plug as plug
from repobee_plug.cli import categorization
import _repobee
import _repobee.cli.mainparser
import _repobee.cli.preparser
from _repobee import fileutil, exception, constants, cli, git
from _repobee.command import progresswrappers
class _ArgsProcessing(enum.Enum):
"""Enum for selecting the type of processing for args."""
NONE = "none"
CORE = "core"
EXT = "ext"
def handle_args(
sys_args: Iterable[str], config: plug.Config
) -> Tuple[argparse.Namespace, Optional[plug.PlatformAPI]]:
"""Parse and process command line arguments and instantiate the platform
API (if it's needed).
Args:
sys_args: Raw command line arguments for the primary parser.
config: RepoBee's configuration.
Returns:
A tuple of a namespace with parsed and processed arguments, and an
instance of the platform API if it is required for the command.
"""
args, processing = _parse_args(sys_args, config)
plug.manager.hook.handle_parsed_args(args=args)
if processing == _ArgsProcessing.CORE:
return _process_args(args)
elif processing == _ArgsProcessing.EXT:
return _process_ext_args(args)
return args, None
def _parse_args(
sys_args: Iterable[str], config: plug.Config
) -> Tuple[argparse.Namespace, _ArgsProcessing]:
"""Parse the command line arguments with some light processing. Any
processing that requires external resources (such as a network connection)
must be performed by the :py:func:`_process_args` function.
Args:
sys_args: A list of command line arguments.
config: RepoBee's configuration.
Returns:
A namespace of parsed arpuments and a boolean that specifies whether or
not further processing is required.
"""
parser = cli.mainparser.create_parser(config)
argcomplete.autocomplete(parser)
args = parser.parse_args(_handle_deprecation(sys_args))
cli.preparser.clean_arguments(args)
if "_extension_command" in args and not getattr(
args._extension_command, "_is_core_command", False
):
return args, _ArgsProcessing.EXT
if "base_url" in args:
_validate_tls_url(args.base_url)
args_dict = vars(args)
args_dict["students"] = _extract_groups(args)
args_dict["issue"] = (
fileutil.read_issue_from_file(args.issue)
if "issue" in args and args.issue
else None
)
args_dict.setdefault("template_org_name", None)
args_dict.setdefault("title_regex", None)
args_dict.setdefault("state", None)
args_dict.setdefault("show_body", None)
args_dict.setdefault("author", None)
args_dict.setdefault("num_reviews", None)
args_dict.setdefault("user", None)
args_dict["action"] = (
args.action
if isinstance(args.action, categorization.Action)
else plug.cli.CoreCommand(args.category)[args.action]
)
args_dict["category"] = (
args.category
if isinstance(args.category, categorization.Category)
else plug.cli.CoreCommand(args.category)
)
requires_processing = _resolve_requires_processing(args)
return argparse.Namespace(**args_dict), requires_processing
def _resolve_requires_processing(args: argparse.Namespace) -> _ArgsProcessing:
"""Figure out if further processing of the parsed args is required.
This is primarily decided on whether or not the platform API is required,
as that implies further processing.
"""
if args.action in [
plug.cli.CoreCommand.config.verify,
plug.cli.CoreCommand.config.show,
]:
return _ArgsProcessing.NONE
return _ArgsProcessing.CORE
def _process_args(
args: argparse.Namespace,
) -> Tuple[argparse.Namespace, plug.PlatformAPI]:
"""Process parsed command line arguments.
Args:
"""
api = _connect_to_api(args.base_url, args.token, args.org_name, args.user)
template_org_name = args.org_name
if "template_org_name" in args and args.template_org_name is not None:
template_org_name = args.template_org_name
repos = master_names = master_urls = None
if "discover_repos" in args and args.discover_repos:
repos = _discover_repos(args.students, api)
elif "assignments" in args:
master_names = args.assignments
remote_urls, local_uris = _repo_names_to_urls(
master_names, template_org_name, api
)
if local_uris and not getattr(args, "allow_local_templates", True):
locals_str = " ".join([f"'{uri}'" for uri in local_uris])
raise exception.ParseError(
f"found local templates in workdir: {locals_str}, "
"use `--allow-local-templates` to allow locals or change "
"directory to use remotes only"
)
master_urls = remote_urls + local_uris
repos = _repo_tuple_generator(master_names, args.students, api)
assert master_urls and master_names
args_dict = vars(args)
args_dict["template_repo_urls"] = master_urls
args_dict["assignments"] = master_names
args_dict["repos"] = repos
# marker for functionality that relies on fully processed args
args_dict["_repobee_processed"] = True
return argparse.Namespace(**args_dict), api
def _discover_repos(
student_teams: List[plug.StudentTeam], api: plug.PlatformAPI
) -> Iterable[plug.StudentRepo]:
student_teams_dict = {t.name: t for t in student_teams}
fetched_teams = progresswrappers.get_teams(
student_teams, api, desc="Discovering team repos"
)
for team in fetched_teams:
repos = api.get_team_repos(team)
yield from (
plug.StudentRepo(
name=repo.name,
url=repo.url,
team=student_teams_dict[team.name],
)
for repo in repos
)
def _repo_tuple_generator(
assignment_names: List[str],
teams: List[plug.StudentTeam],
api: plug.PlatformAPI,
) -> Iterable[plug.StudentRepo]:
for assignment_name in assignment_names:
for team in teams:
url, *_ = api.get_repo_urls(
[assignment_name], team_names=[team.name]
)
name = plug.generate_repo_name(team, assignment_name)
yield plug.StudentRepo(name=name, url=url, team=team)
def _validate_tls_url(url):
"""Url must use the https protocol."""
if not url.startswith("https://"):
raise exception.ParseError(
f"unsupported protocol in {url}: "
f"for security reasons, only https is supported"
)
def _handle_deprecation(sys_args: Iterable[str]) -> List[str]:
"""If the first argument on the arglist is a deprecated command, replace it
with the corresponding current command and issue a warning.
Returns:
The sys_args list with any deprecated command replaced with the current
one.
"""
# FIXME Deprecation needs to be re-implemented
return list(sys_args)
def _extract_groups(args: argparse.Namespace) -> List[plug.StudentTeam]:
"""Extract groups from args namespace.`
Args:
args: A namespace object.
Returns:
a list of student usernames, or None of neither `students` or
`students_file` is in the namespace.
"""
if "students" in args and args.students:
students = [plug.StudentTeam(members=[s]) for s in args.students]
elif "students_file" in args and args.students_file:
students_file = pathlib.Path(args.students_file).resolve()
if not students_file.is_file():
raise exception.FileError(f"'{students_file}' is not a file")
if not students_file.stat().st_size:
raise exception.FileError(f"'{students_file}' is empty")
students = list(
plug.manager.hook.parse_students_file(students_file=students_file)
)
else:
students = []
return students
def _connect_to_api(
base_url: str, token: str, org_name: str, user: str
) -> plug.PlatformAPI:
"""Return an API instance connected to the specified API endpoint."""
required_args = plug.manager.hook.api_init_requires()
kwargs = {}
if "base_url" in required_args:
kwargs["base_url"] = base_url
if "token" in required_args:
kwargs["token"] = token
if "org_name" in required_args:
kwargs["org_name"] = org_name
if "user" in required_args:
kwargs["user"] = user
api_class = plug.manager.hook.get_api_class()
try:
return api_class(**kwargs)
except plug.NotFoundError:
# more informative message
raise plug.NotFoundError(
f"either organization {org_name} could not be found, "
f"or the base url '{base_url}' is incorrect"
)
def _repo_names_to_urls(
repo_names: Iterable[str], org_name: str, api: plug.PlatformAPI
) -> Tuple[List[str], List[str]]:
"""Use the repo_names to extract urls to the repos. Look for git
repos with the correct names in the local directory and create local uris
for them. For the rest, create urls to the repos assuming they are in the
target organization. Do note that there is _no_ guarantee that the remote
repos exist as checking this takes too much time with the REST API.
A possible improvement would be to use the GraphQL API for this function.
Args:
repo_names: names of repositories.
org_name: Name of the organization these repos are expected in.
api: An API instance.
Returns:
A tuple of lists with (non_local_urls, local_uris).
Raises:
ParseError: If local templates are found, but allow_local is False.
"""
local = [
name for name in repo_names if git.is_git_repo(os.path.abspath(name))
]
non_local = [name for name in repo_names if name not in local]
non_local_urls = api.get_repo_urls(non_local, org_name)
local_uris = [
pathlib.Path(os.path.abspath(repo_name)).as_uri()
for repo_name in local
]
return non_local_urls, local_uris
def _process_ext_args(
args: argparse.Namespace,
) -> Tuple[argparse.Namespace, Optional[plug.PlatformAPI]]:
ext_cmd = args._extension_command
assert ext_cmd
api = None
if ext_cmd.__requires_api__():
_validate_tls_url(args.base_url)
api = _connect_to_api(
args.base_url,
args.token,
args.org_name,
args.user if "user" in args else None,
)
args_dict = vars(args)
req_parsers = ext_cmd.__settings__.base_parsers or []
bp = plug.BaseParser
if bp.STUDENTS in req_parsers:
args_dict["students"] = _extract_groups(args)
if bp.REPO_DISCOVERY in req_parsers and args.discover_repos:
assert api is not None
args_dict["repos"] = _discover_repos(args_dict["students"], api)
return argparse.Namespace(**args_dict), api
def _filter_tokens():
"""Filter out any secure tokens from log output."""
old_factory = logging.getLogRecordFactory()
def record_factory(*args, **kwargs):
record = old_factory(*args, **kwargs)
# from URLS (e.g. git error messages)
record.msg = re.sub("https://.*?@", "https://", record.msg)
# from show-config output
record.msg = re.sub(r"token\s*=\s*.*", "token = xxxxxxxxx", record.msg)
return record
logging.setLogRecordFactory(record_factory)
def setup_logging(terminal_level: int = logging.WARNING) -> None:
"""Setup logging by creating the required log directory and setting up
the logger.
Args:
terminal_level: The logging level to use for printing to stderr.
"""
logfile = constants.LOG_DIR / f"{_repobee._external_package_name}.log"
_ensure_size_less(logfile, max_size=constants.MAX_LOGFILE_SIZE)
try:
os.makedirs(str(constants.LOG_DIR), exist_ok=True)
except Exception as exc:
raise exception.FileError(
f"can't create log directory at {constants.LOG_DIR}"
) from exc
daiquiri.setup(
level=logging.DEBUG,
outputs=(
daiquiri.output.Stream(
sys.stderr,
formatter=daiquiri.formatter.ColorFormatter(
fmt="%(color)s[%(levelname)s] %(message)s%(color_stop)s"
),
level=terminal_level,
),
daiquiri.output.File(
filename=str(logfile),
formatter=daiquiri.formatter.ColorFormatter(
fmt="%(asctime)s [PID %(process)d] [%(levelname)s] "
"%(name)s -> %(message)s"
),
level=logging.DEBUG,
),
),
)
_filter_tokens()
def _ensure_size_less(path: pathlib.Path, max_size: int) -> None:
if not path.exists():
return
file_size = path.stat().st_size
if file_size >= max_size:
target = file_size - max_size // 2
with open(path, mode="rb") as f:
cur = target
f.seek(cur)
while f.read(1) != b"\n" and cur < file_size:
cur += 1
f.seek(cur)
with open(
path.parent / (path.name + ".tmp"), mode="wb"
) as tmp_file:
for line in f.readlines():
tmp_file.write(line)
path.unlink()
pathlib.Path(tmp_file.name).rename(path)
|
18c8ab2f12c8e891104fb8179328c76bb9925784
|
{
"blob_id": "18c8ab2f12c8e891104fb8179328c76bb9925784",
"branch_name": "refs/heads/master",
"committer_date": "2023-04-16T19:42:21",
"content_id": "6f402084f97484d01f074eecf53c5c1327e5789d",
"detected_licenses": [
"MIT"
],
"directory_id": "ba3061e915bf6dc1f7078eaec6fe15086672ba19",
"extension": "py",
"filename": "parsing.py",
"fork_events_count": 21,
"gha_created_at": "2018-06-15T16:27:00",
"gha_event_created_at": "2023-09-13T06:23:38",
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 137509687,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14066,
"license": "MIT",
"license_type": "permissive",
"path": "/src/_repobee/cli/parsing.py",
"provenance": "stack-edu-0060.json.gz:490568",
"repo_name": "repobee/repobee",
"revision_date": "2023-04-16T19:42:21",
"revision_id": "5db5e78a9eba685a85211a31e3b2033338e03ab5",
"snapshot_id": "8bb092b7a3db682ec5e0302765c44c870b76507c",
"src_encoding": "UTF-8",
"star_events_count": 62,
"url": "https://raw.githubusercontent.com/repobee/repobee/5db5e78a9eba685a85211a31e3b2033338e03ab5/src/_repobee/cli/parsing.py",
"visit_date": "2023-07-23T20:26:26.550110",
"added": "2024-11-18T22:25:57.200212+00:00",
"created": "2023-04-16T19:42:21",
"int_score": 2,
"score": 2.203125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0078.json.gz"
}
|
"""
emr.py
Preprocesses EMR data files. Files should have 1 case per line and be space
delimited; each case begins with the age, ethnicity class, gender, then
subsequent ICD9 codes. Does not perform vectorization (e.g., one-hot or binary
encoding).
Author: Ji-Sung Kim (Rzhetksy Lab)
Copyright: 2016, all rights reserved
"""
from __future__ import print_function
from collections import Counter
from . import utils
import numpy as np
# --------------------------------- SETTINGS --------------------------------- #
# column information
RAW_AGE_COL, RAW_CLASS_COL, RAW_GENDER_COL, RAW_FIRST_ICD9_COL = 0, 1, 2, 3
X_AGE_COL, X_GENDER_COL, X_FIRST_ICD9_COL = 0, 1, 2
# ---------------------------- HELPER FUNCTIONS ------------------------------ #
'''
* Reads in a file.
* Expects:
- path = string filepath of the file to be loaded
* Returns:
- list of string lines from file.
'''
def read_file(path):
with open(path) as f:
data = f.read().splitlines()
return data
'''
* Cleans up and annotates data; converts data into standard (X, y) form.
* Expects:
- data = list of string lines
e.g., ['8 H M 31:8 V72.3:4', '55 O F 31:18']
- icd9_descript_dict = dictionary mapping ICD9 codes to their descriptions
- no_onset_age = boolean for whether to discard onset age information
* Returns:
- X which is a list of list of features; outer list represents samples
e.g., ['age_8', 'gender_M', '31', 'V72.3'], ['age_55', 'gender_F', '31']]
- y which is a list of true classes
e.g., ['H', 'O']
'''
def clean_data(data, icd9_descript_dict, no_onset_age=True):
X, y = [], []
count = 0
for idx, line in enumerate(data):
line = line.split()
try:
features = []
features.append('age_' + line[RAW_AGE_COL])
features.append('gender_' + line[RAW_GENDER_COL])
icd9s = [i.split(':') for i in line[RAW_FIRST_ICD9_COL:]]
# filter invalid icd9s and sort by onset age in place
icd9s = [i for i in icd9s if i[0] in icd9_descript_dict]
icd9s.sort(key = lambda i: int(i[1]))
if no_onset_age: icd9s = [i[0] for i in icd9s] # remove onset age
else: icd9s = [':'.join(i) for i in icd9s]
features.extend(icd9s)
X.append(features)
y.append(line[RAW_CLASS_COL]) # extract class
except:
print('WARNING: error on line #{} with case:'.format(idx))
print(' '.join(line))
raise
assert len(X) == len(y)
return X, y
'''
* Randomly removes some proportion of feature data for the purpose of
simulating randomly missing data.
* Expects:
- X = list of list of features; outer list represents samples
e.g., ['age_8', 'gender_M', '31', 'V72.3'], ['age_55', 'gender_F', '31']]
- prop = float for the proportion of data to be removed
* Returns:
- X which is a list of list of features
e.g., ['age_8', 'gender_M', '31'], ['age_55', '31']]
'''
def simulate_missing_data(X, prop):
print(X[0])
if prop < 0:
raise ValueError('prop for simulating missing data is negative')
if prop == 0.0: return X
indices = [[(row_idx, col_idx) for col_idx in range(len(x))] \
for row_idx, x in enumerate(X)]
indices = [i for r in indices for i in r] # flatten
np.random.shuffle(indices)
nb_to_remove = int(len(indices) * prop)
indices_to_remove = indices[:int(len(indices) * prop)]
# need to sort these so that deletion works and doesn't screw up indices
indices_to_remove = sorted(indices_to_remove, key=lambda x: (x[0], x[1]),
reverse=True)
for row_idx, col_idx in indices_to_remove:
X[row_idx].pop(col_idx)
# check number of removals
lengths = [len(x) for x in X]
assert sum(lengths) == len(indices) - nb_to_remove
print('Randomly deleted {} feature occurrences'.format(nb_to_remove))
return X
'''
* Maps features and classes to integer values, "indices". More frequent values
are assigned lower indices.
* Expects:
- X = list of list of features; outer list represents samples
e.g., ['age_8', 'gender_M', '31', 'V72.3'], ['age_55', 'gender_F', '31']]
- y = list of true classes
e.g., ['H', 'O']
* Returns:
- dictionary mapping feature names to feature indices
- dictionary mapping feature indices to feature names
- dictionary mapping class names to class indices
- dictionary mapping class indices to class names
'''
def get_dicts(X, y):
feat_counts = Counter()
class_counts = Counter(y)
def count_feat(f):
feat_counts[f] += 1
map(count_feat, [f for line in X for f in line])
feat_idx_dict, idx_feat_dict, class_idx_dict, idx_class_dict = {}, {}, {}, {}
for idx, (c, count) in enumerate(class_counts.most_common()):
class_idx_dict[c] = idx
idx_class_dict[idx] = c
for idx, (feat, count) in enumerate(feat_counts.most_common()):
feat_idx_dict[feat] = idx
idx_feat_dict[idx] = feat
return feat_idx_dict, idx_feat_dict, class_idx_dict, idx_class_dict
'''
* Encodes features and classes to integer indices, based on given dictionaries.
* Expects:
- X = list of list of features; outer list represents samples
e.g., ['age_8', 'gender_M', '31', 'V72.3'], ['age_55', 'gender_F', '31']]
- y = list of true classes
e.g., ['H', 'O']
- feat_idx_dict = dictionary mapping feature names to feature indices
- class_idx_dict = dictionary mapping class names to class indices
* Returns:
- encoded X which is a list of list of feature indices
e.g., [[0, 3, 1, 2], [4, 5, 1]]
- encoded y which is a list of list of class indices
e.g., [0, 1]
'''
def encode(X, y, feat_idx_dict, class_idx_dict):
X = [[feat_idx_dict[feat] for feat in line] for line in X]
y = [class_idx_dict[c] for c in y]
assert len(X) == len(y)
return X, y
'''
* Gets EMR data in standard (features, target) format. Does not perform
vectorization.
* Expects:
- path = string filepath of the file to be loaded
- icd9s_only = boolean for whether to keep only ICD9 codes as features
- no_onset_age = boolean for whether to discard onset age information
- prop_missing = float for the proportion of data to be removed
* Returns:
- X which is the feature data as a list of list of feature indices
- y which is the class data as a list of list of class indices
- dictionary mapping feature indices to feature names
- dictionary mapping class indices to class names
'''
def get_data(path, icd9_descript_dict, icd9s_only=False,
no_onset_age=True, prop_missing=0.0):
data = read_file(path)
X, y = clean_data(data, icd9_descript_dict=icd9_descript_dict,
no_onset_age=no_onset_age)
if prop_missing != 0.0:
X = simulate_missing_data(X, prop=prop_missing)
feat_idx_dict, idx_feat_dict, class_idx_dict, idx_class_dict = \
get_dicts(X, y)
X, y = encode(X, y, feat_idx_dict, class_idx_dict)
return X, y, idx_feat_dict, idx_class_dict
# ---------------------------- PUBLIC FUNCTIONS ------------------------------ #
'''
* Splits data into training, validation, and testing sets based on k-fold
partitioning.
* Expects:
- X = feature data as a list of list of feature indices
e.g., [[0, 3, 1, 2], [4, 5, 1]]
- y = class data as a list of list of class indices
e.g., [0, 1]
- k_idx = index of the selected partition
- k = number of partitions
- perm_indices = list of randomly shuffled indices from 0 to nb_samples
e.g., [3, 1, 2, 0]
* Returns:
- data partition as a dictionary with 6 keys for each subset: 'X_train',
'y_train', 'X_val, 'y_val', 'X_test', 'y_test'
'''
def get_k_fold_partition(X, y, k_idx, k, perm_indices):
(X_train, y_train), (X_test, y_test) = utils.split_data(X, y, k_idx=k_idx,
k=k, perm_indices=perm_indices)
# typically, 10% of training data => validation (so k = 10)\
val_perm_indices = perm_indices[perm_indices < len(X_train)]
(X_train, y_train), (X_val, y_val) = utils.split_data(X_train, y_train,
k_idx=0, k=10, perm_indices=val_perm_indices)
assert len(X_train) + len(X_val) + len(X_test) == len(X)
return {'X_train': X_train, 'y_train':y_train, 'X_val':X_val, 'y_val':y_val,
'X_test':X_test, 'y_test':y_test}
'''
* Creates a dictionary mapping ICD9 codes to their descriptions.
* Expects:
- path = string filepath of the file to be loaded
* Returns:
- dictionary mapping ICD9 codes to their descriptions
'''
def get_icd9_descript_dict(path):
lines = read_file(path)
icd9_descript_dict = {}
for l in lines[1:]: # ignore first line which is column names
elems = l.split('\t')
try:
assert len(elems) == 8 # number of columns should be 8
except:
print('Problem with following line while loading icd9_descript_dict:')
print(l)
raise
icd9 = elems[0] # ICD9 code should be in the first column
descript = elems[1] # description should be in the second column
# check if the ICD9 code is a category and if so, append a label
is_category = len(icd9.split('.')) == 1
if is_category: descript = descript + ' (category)'
icd9_descript_dict[icd9] = descript
return icd9_descript_dict
|
c70da0e183822ff48a39945f1cd9e240952926fa
|
{
"blob_id": "c70da0e183822ff48a39945f1cd9e240952926fa",
"branch_name": "refs/heads/master",
"committer_date": "2017-08-02T01:41:30",
"content_id": "43ff3b3b9d7fafe7b317c7138559f208c1adbafc",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "9fd2e1e7850dd3a6f886ea6a8622eb38217e811e",
"extension": "py",
"filename": "emr.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9490,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/riddle/emr.py",
"provenance": "stack-edu-0064.json.gz:456039",
"repo_name": "girish8050517990/RIDDLE",
"revision_date": "2017-08-02T01:41:30",
"revision_id": "a0b8aeebf1f61880259da6552001098f94e0be31",
"snapshot_id": "8632194d5ed8c05bdb1a4a73490ce7aa67e6b446",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/girish8050517990/RIDDLE/a0b8aeebf1f61880259da6552001098f94e0be31/riddle/emr.py",
"visit_date": "2021-06-20T20:04:09.990641",
"added": "2024-11-19T02:37:04.936753+00:00",
"created": "2017-08-02T01:41:30",
"int_score": 3,
"score": 3.125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0082.json.gz"
}
|
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <headingcell level=1>
# Goal
# <markdowncell>
# Let's get set up to use the US Census API:
#
# http://www.census.gov/developers/
# <markdowncell>
# Things we'd like to be able to do:
#
# * calculate the population of California.
# * then calculate the population of every geographic entity going down to census block if possible.
# * for a given geographic unit, can we get the racial/ethnic breakdown?
#
# It's useful to make ties to the county-type calculation we do with the downloaded census files.
# <headingcell level=1>
# Installing census, a useful Python module
# <markdowncell>
# Dependency: to start with -- let's use the Python module: https://pypi.python.org/pypi/census/
#
# pip install -U census
# <headingcell level=1>
# Getting and activating an API key
# <markdowncell>
# To use the census API, you will need an API key
#
# * fill out form at http://www.census.gov/developers/tos/key_request.html
#
# "Your request for a new API key has been successfully submitted. Please check your email. In a few minutes you should receive a message with instructions on how to activate your new key."
#
# * click on link you'll get a link of the form http://api.census.gov/data/KeySignup?validate={key} -- where {key} is the one the Census Bureau will send you.
#
# Then create a settings.py in the same directory as this notebook (or somewhere else in your Python path) to hold `settings.CENSUS_KEY`. (I prefer this approach over directly exposing your API key in the notebook code.)
# <codecell>
# This cell should run successfully if you have a string set up to represent your census key
try:
import settings
assert type(settings.CENSUS_KEY) == str or type(settings.CENSUS_KEY) == unicode
except Exception as e:
print "error in importing settings to get at settings.CENSUS_KEY", e
# <headingcell level=1>
# us.states module
# <codecell>
# let's figure out a bit about the us module, in particular, us.states
# https://github.com/unitedstates/python-us
from us import states
assert states.CA.fips == u'06'
# <codecell>
# set up your census object
# example from https://github.com/sunlightlabs/census
from census import Census
from us import states
c = Census(settings.CENSUS_KEY)
# <codecell>
for (i, state) in enumerate(states.STATES):
print i, state.name, state.fips
# <headingcell level=1>
# Formulating URL requests to the API explicitly
# <codecell>
import requests
# <codecell>
# get the total population of all states
url = "http://api.census.gov/data/2010/sf1?key={key}&get=P0010001,NAME&for=state:*".format(key=settings.CENSUS_KEY)
# <codecell>
r = requests.get(url)
# <headingcell level=1>
# EXERCISE
# <markdowncell>
# Show how to calculate the total population of the USA, including and excluding Puerto Rico. (I don't know why Puerto Rico is included but not other [unincorporated territories](https://en.wikipedia.org/wiki/Unincorporated_territories_of_the_United_States)
# <codecell>
# FILL IN WITH YOUR CODE
# <headingcell level=1>
# Next Steps: Focusing on sf1 + census
# <markdowncell>
# How to map out the geographical hierachy and pull out total population figures?
#
# 1. Nation
# 1. Regions
# 1. Divisions
# 1. State
# 1. County
# 1. Census Tract
# 1. Block Group
# 1. Census Block
#
# Questions
#
# * What identifiers are used for these various geographic entities?
# * Can we get an enumeration of each of these entities?
# * How to figure out which census tract, block group, census block one is in?
#
# <headingcell level=2>
# Total Population of California
# <markdowncell>
# [2010 Census Summary File 1](http://www.census.gov/prod/cen2010/doc/sf1.pdf)
#
# P0010001 is found in [2010 SF1 API Variables \[XML\]](http://www.census.gov/developers/data/sf1.xml) = "total population"
# <codecell>
c.sf1.get(('NAME', 'P0010001'), {'for': 'state:%s' % states.CA.fips})
# <codecell>
"population of California: {0}".format(
int(c.sf1.get(('NAME', 'P0010001'), {'for': 'state:%s' % states.CA.fips})[0]['P0010001']))
|
f126ba3d1dbcbc2eef847db7b14dcd1efe2bceb4
|
{
"blob_id": "f126ba3d1dbcbc2eef847db7b14dcd1efe2bceb4",
"branch_name": "refs/heads/master",
"committer_date": "2016-03-29T14:24:00",
"content_id": "fd931909e8b5a30f8c37aa8dc4442c89f62629fa",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "8d764c0d5d05b108999898da26f0b1d8d0fec986",
"extension": "py",
"filename": "Day_02_A_US_Census_API.py",
"fork_events_count": 0,
"gha_created_at": "2016-03-29T14:23:09",
"gha_event_created_at": "2016-03-29T14:23:09",
"gha_language": null,
"gha_license_id": null,
"github_id": 54982268,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4114,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/notebooks/Day_02_A_US_Census_API.py",
"provenance": "stack-edu-0059.json.gz:115719",
"repo_name": "rwzhao/working-open-data-2014",
"revision_date": "2016-03-29T14:24:00",
"revision_id": "38e05c5f860066484002682369a2805a2c7873b7",
"snapshot_id": "59535afe3ae58550e4eb75ac6600574e4cf5a061",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rwzhao/working-open-data-2014/38e05c5f860066484002682369a2805a2c7873b7/notebooks/Day_02_A_US_Census_API.py",
"visit_date": "2021-05-31T04:39:33.841949",
"added": "2024-11-19T02:18:06.688200+00:00",
"created": "2016-03-29T14:24:00",
"int_score": 3,
"score": 3.390625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0077.json.gz"
}
|
<?php
namespace Entity;
class Custom
{
private $id_custom;
/**
* @var string
*/
private $titre_custom;
/**
* @var int
*/
private $tissu_id;
/**
* @var int
*/
private $bouton_id;
/**
* @var int
*/
private $col_id;
/**
* @var int
*/
private $coupe_id;
/**
* @var int
*/
private $prix;
/**
* @var int
*/
private $quantite;
private $produitOrCustom; //booleen
//Constructeur ///Rajoute par Edouard
public function __construct()
{
$this->setProduitOrCustom('custom');
}
/**********GETTERS****************/
/**
* @return int
*/
function getId_custom() {
return $this->id_custom;
}
/**
* @return string
*/
public function getTitre_custom() {
return $this->titre_custom;
}
/**
* @return int
*/
function getTissu_id() {
return $this->tissu_id;
}
/**
* @return int
*/
function getBouton_id() {
return $this->bouton_id;
}
/**
* @return int
*/
function getCol_id() {
return $this->col;
}
/**
* @return int
*/
function getCoupe_id() {
return $this->coupe;
}
/**
* @return int
*/
function getPrix() {
return $this->prix;
}
//Rajouté par Edouard
/**
* @return int
*/
public function getQuantite() {
return $this->quantite;
}
public function getProduitOrCustom()
{
return $this->produitOrCustom;
}
/**********SETTERS****************/
/**
* @param type $id_custom
* @return Custom
*/
function setId_custom($id_custom) {
$this->id_custom = $id_custom;
return $this;
}
/**
* @param type $titre_custom
* @return Custom
*/
public function setTitre_custom($titre_custom) {
$this->titre_custom = $titre_custom;
return $this;
}
/**
* @param type $tissu_id
* @return Custom
*/
function setTissu_id($tissu_id) {
$this->tissu_id = $tissu_id;
return $this;
}
/**
* @param type $bouton_id
* return Custom
*/
function setBouton_id($bouton_id) {
$this->bouton_id = $bouton_id;
return $this;
}
/**
* @param type $col
* @return Custom
*/
function setCol_id($col) {
$this->col = $col;
return $this;
}
/**
* @param type $coupe
* @return Custom
*/
function setCoupe_id($coupe) {
$this->coupe = $coupe;
return $this;
}
/**
* @param type $prix
* @return Custom
*/
function setPrix($prix) {
$this->prix = $prix;
return $this;
}
//Rajouté par Edouard
/**
* @param type $quantite
* @return Custom
*/
public function setQuantite($quantite) {
$this->quantite = $quantite;
}
public function setProduitOrCustom($produitOrCustom)
{
$this->produitOrCustom = $produitOrCustom;
}
}
|
fa2928fccd24152dfa070304b5e5bb5f01714007
|
{
"blob_id": "fa2928fccd24152dfa070304b5e5bb5f01714007",
"branch_name": "refs/heads/master",
"committer_date": "2017-08-04T10:12:42",
"content_id": "9e205e4e177691ef1621e28a9667a86e690b0e46",
"detected_licenses": [
"MIT"
],
"directory_id": "253460020290f89969a2991ff62f995e0ff9cacd",
"extension": "php",
"filename": "Custom.php",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 99330890,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 3252,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Entity/Custom.php",
"provenance": "stack-edu-0046.json.gz:348018",
"repo_name": "IronMdn/Custom-Shirt",
"revision_date": "2017-08-04T10:12:42",
"revision_id": "c24228c169b9569a812f3fc20d02ee0f8d2ded06",
"snapshot_id": "8c25c624fb8c25c020694ca678bdd4fe1e3b81ea",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/IronMdn/Custom-Shirt/c24228c169b9569a812f3fc20d02ee0f8d2ded06/src/Entity/Custom.php",
"visit_date": "2021-01-02T22:30:24.235213",
"added": "2024-11-18T22:25:53.528846+00:00",
"created": "2017-08-04T10:12:42",
"int_score": 3,
"score": 3,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0064.json.gz"
}
|
package memento.demo;
import lombok.extern.java.Log;
import memento.CareTaker;
import memento.Originator;
@Log
public class PatternDemo {
public static void main(String[] args) {
var originator = new Originator();
var careTaker = new CareTaker();
originator.setState("state 1");
originator.setState("state 2");
careTaker.add(originator.saveStateToMemento());
originator.setState("state 3");
careTaker.add(originator.saveStateToMemento());
originator.setState("state 4");
log.info("Current state: " + originator.getState());
var mementos = careTaker.getMementos();
log.info("Stored Snapshots are: " + mementos);
}
}
|
d724717797cd44780794924490edd759a5fd4a95
|
{
"blob_id": "d724717797cd44780794924490edd759a5fd4a95",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-29T17:09:52",
"content_id": "6101a02e16ff9d7c507897b0c2a4fc50bf5d2dfd",
"detected_licenses": [
"MIT"
],
"directory_id": "e62f1b994d95313fcf890744ee0491b67108ca17",
"extension": "java",
"filename": "PatternDemo.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 148943759,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 719,
"license": "MIT",
"license_type": "permissive",
"path": "/gang-of-four-patterns/behavioral/memento/src/main/java/memento/demo/PatternDemo.java",
"provenance": "stack-edu-0028.json.gz:100538",
"repo_name": "alexandr-efimov/java-design-patterns",
"revision_date": "2019-01-29T17:09:52",
"revision_id": "e7a0c5e7be4806df574896e5611dbe9ce656c6c4",
"snapshot_id": "3e70d86473eefa2ac316e92227d2c32acc1b006c",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/alexandr-efimov/java-design-patterns/e7a0c5e7be4806df574896e5611dbe9ce656c6c4/gang-of-four-patterns/behavioral/memento/src/main/java/memento/demo/PatternDemo.java",
"visit_date": "2020-03-28T19:05:47.609342",
"added": "2024-11-18T21:19:03.346488+00:00",
"created": "2019-01-29T17:09:52",
"int_score": 3,
"score": 2.828125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0046.json.gz"
}
|
<?php
/**
* Created by PhpStorm.
* User: Nikolas
* Date: 10.04.2017
* Time: 20:36
*/
namespace CoreBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
class Profile
{
private $id;
private $sectionId;
private $name;
private $entrys;
private $users;
private $section;
/**
* @var \DateTime
*/
private $createdAt;
/**
* @var \DateTime
*/
private $updatedAt;
/**
* Record constructor.
*/
public function __construct()
{
$this->entrys = new ArrayCollection();
$this->users = new ArrayCollection();
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getSectionId()
{
return $this->sectionId;
}
/**
* @param mixed $sectionId
*/
public function setSectionId($sectionId)
{
$this->sectionId = $sectionId;
}
/**
* @return mixed
*/
public function getName()
{
return $this->name;
}
/**
* @param mixed $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* FIXME: bidirectional relationship
* @param User $user
*/
public function addUser(User $user)
{
$this->users->add($user);
}
/**
* @param User $user
*/
public function removeUser(User $user)
{
$this->users->removeElement($user);
}
/**
* @return ArrayCollection|Collection
*/
public function getUsers()
{
return $this->users;
}
/**
* FIXME: bidirectional relationship
* @param Entry $entry
*/
public function addEntry(Entry $entry)
{
$this->entrys->add($entry);
}
/**
* @param Entry $entry
*/
public function removeEntry(Entry $entry)
{
$this->entrys->removeElement($entry);
}
/**
* @return ArrayCollection|Collection
*/
public function getEntrys()
{
return $this->entrys;
}
/**
* @return mixed
*/
public function getSection()
{
return $this->section;
}
/**
* @param mixed $section
*/
public function setSection($section)
{
$this->section = $section;
}
/**
* @return mixed
*/
public function getCreatedAt()
{
return $this->createdAt->format('Y-m-d H:i:s');
}
/**
* @param mixed $createdAt
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
}
/**
* @return mixed
*/
public function getUpdatedAt()
{
return $this->updatedAt->format('Y-m-d H:i:s');
}
/**
* @param mixed $updatedAt
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
}
public function fillCreatedAt()
{
$this->createdAt = new \DateTime();
}
public function fillUpdatedAt()
{
$this->updatedAt = new \DateTime();
}
}
|
f700eff5ed1d9f8e782f40852a82311c2d6cdaf2
|
{
"blob_id": "f700eff5ed1d9f8e782f40852a82311c2d6cdaf2",
"branch_name": "refs/heads/master",
"committer_date": "2017-05-09T01:10:26",
"content_id": "0af69f2e9c472648c235837c1591c03737b6d83c",
"detected_licenses": [
"BSD-3-Clause",
"MIT"
],
"directory_id": "998e2f328e37ad8e206862346ef546c1daaea7c9",
"extension": "php",
"filename": "Profile.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 90176439,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 3271,
"license": "BSD-3-Clause,MIT",
"license_type": "permissive",
"path": "/src/CoreBundle/Entity/Profile.php",
"provenance": "stack-edu-0046.json.gz:437629",
"repo_name": "NikolasJanec/Bakalarka",
"revision_date": "2017-05-09T01:10:26",
"revision_id": "5fe355f253efa74b3fbb9adfa98d1da18ec39d21",
"snapshot_id": "053995acc550b1c9282ece4196644600965185e1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/NikolasJanec/Bakalarka/5fe355f253efa74b3fbb9adfa98d1da18ec39d21/src/CoreBundle/Entity/Profile.php",
"visit_date": "2021-01-20T08:40:51.277632",
"added": "2024-11-18T22:39:05.999918+00:00",
"created": "2017-05-09T01:10:26",
"int_score": 3,
"score": 2.796875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0064.json.gz"
}
|
package org.sjbanerjee.musicplayer;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import java.nio.file.Paths;
import java.util.concurrent.Callable;
public class MediaPlayingTask implements Callable {
private static MediaPlayer player = null;
private final String mediaFile;
private static String currentPlayingMedia = null;
public MediaPlayingTask(String mediaFile) {
this.mediaFile = mediaFile;
}
@Override
public MediaPlayer call() {
System.out.println("Playing media on thread : " + Thread.currentThread().getName());
player = new MediaPlayer(new Media(Paths.get(mediaFile).toUri().toString()));
play();
return player;
}
private synchronized void play() {
try {
Thread.sleep(5000); //FIXME - HACK - Wait for the player to initialize
System.out.println("Playing media " + mediaFile);
currentPlayingMedia = mediaFile;
player.play();
//Blocking player
while (player.getCurrentTime().toMillis() < player.getTotalDuration().toMillis()) {
Thread.sleep(5000); //Check after 5 seconds
System.out.println("Current time: " + player.getCurrentTime());
}
player.stop();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public double getTimeForCurrentMedia() {
if (player != null) {
return player.getCurrentTime().toMillis();
} else {
return 0.0;
}
}
public String getCurrentMediaFile() {
return currentPlayingMedia;
}
}
|
602034898bc29f4c5d861efc90e2f3ecbf3cbec4
|
{
"blob_id": "602034898bc29f4c5d861efc90e2f3ecbf3cbec4",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-06T17:57:57",
"content_id": "cb1c219490b6c33c9d1fd4f19a0911c47d900d92",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "24541540e5115d632e18c5c921a8ae7f887371d2",
"extension": "java",
"filename": "MediaPlayingTask.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 146781336,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1734,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/main/java/org/sjbanerjee/musicplayer/MediaPlayingTask.java",
"provenance": "stack-edu-0024.json.gz:565318",
"repo_name": "talk2sjb/music-broadcast",
"revision_date": "2018-09-06T17:57:57",
"revision_id": "6e9213e1342eba024a26912b515129379b21bf88",
"snapshot_id": "f4b7219d14868379d1c066b644b28f50db96865e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/talk2sjb/music-broadcast/6e9213e1342eba024a26912b515129379b21bf88/src/main/java/org/sjbanerjee/musicplayer/MediaPlayingTask.java",
"visit_date": "2020-03-27T16:25:20.668601",
"added": "2024-11-18T23:56:44.843911+00:00",
"created": "2018-09-06T17:57:57",
"int_score": 3,
"score": 3.140625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz"
}
|
const { Sema } = require(`async-sema`)
const fetch = require(`node-fetch`)
const _ = require(`lodash`)
const fs = require(`fs`)
const path = require(`path`)
const baseUrl = `http://www.splashbase.co/api/v1/images/`
const s = new Sema(
10, // Allow 10 concurrent async calls
{
capacity: 100, // Prealloc space for 100 tokens
}
)
async function fetchData(x) {
await s.acquire()
try {
return await fetch(`${baseUrl}${x}`).then(res => res.json())
} finally {
s.release()
}
}
const main = async () => {
let data = await Promise.all(_.range(2000).map(fetchData))
data = data.filter(d => d.url).map(d => d.url)
data = data.map(d => {
return {
url: d,
parsed: path.parse(d),
}
})
data = data.filter(d => d.parsed.ext.toLowerCase().slice(0, 4) === `.jpg`)
data = data.map(d => d.url)
// console.log(data)
console.log(`total: ${data.length}`)
fs.writeFileSync(`./urls.json`, JSON.stringify(data, null, 4))
}
main()
|
be7da730cbc116e51dce5d40083745b1a7f542f4
|
{
"blob_id": "be7da730cbc116e51dce5d40083745b1a7f542f4",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-26T08:50:45",
"content_id": "09fd37fa4b007e07926d820087555f1e593ed386",
"detected_licenses": [
"MIT"
],
"directory_id": "aee96abd7003f36f7bc156a33779371dbaabc25a",
"extension": "js",
"filename": "fetch-image-urls.js",
"fork_events_count": 16208,
"gha_created_at": "2015-05-21T22:43:05",
"gha_event_created_at": "2023-09-14T16:45:01",
"gha_language": "JavaScript",
"gha_license_id": "MIT",
"github_id": 36040894,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 974,
"license": "MIT",
"license_type": "permissive",
"path": "/benchmarks/image-processing/plugins/gatsby-source-remote-images/fetch-image-urls.js",
"provenance": "stack-edu-0033.json.gz:437211",
"repo_name": "gatsbyjs/gatsby",
"revision_date": "2023-07-26T08:50:45",
"revision_id": "fd8de341684df7aa5fcd911a25786beac471925c",
"snapshot_id": "785945b3e01340b3974c1ef997899f37e064181f",
"src_encoding": "UTF-8",
"star_events_count": 61117,
"url": "https://raw.githubusercontent.com/gatsbyjs/gatsby/fd8de341684df7aa5fcd911a25786beac471925c/benchmarks/image-processing/plugins/gatsby-source-remote-images/fetch-image-urls.js",
"visit_date": "2023-08-18T01:18:23.199219",
"added": "2024-11-18T20:38:41.332523+00:00",
"created": "2023-07-26T08:50:45",
"int_score": 3,
"score": 2.640625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0051.json.gz"
}
|
// src / routes / categories.js
'use strict';
// Imports
const express = require('express');
const passport = require('passport');
const validUrl = require('valid-url');
const MetaInspector = require('node-metainspector');
// App Imports
require('../authentication/jwt');
// Common error responses
const noUrlResponse = {
success: false,
errors: [{ type: 'critical', 'message': "No URL." }],
data: {}
};
const invalidUrlResponse = {
success: false,
errors: [{ type: 'critical', 'message': "Invalid URL." }],
data: {}
};
// Common Routes
let scraperRoutes = express.Router();
// Authentication middleware
scraperRoutes.use(passport.authenticate('jwt', { session: false }));
const getUrlResponse = (url) => {
return new Promise((resolve, reject) => {
const http = require('http'),
https = require('https');
let client = http;
if (url.toString().indexOf("https") === 0) {
client = https;
}
client.get(url, (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
resolve(data);
});
}).on("error", (err) => {
reject(err);
});
});
};
// Scrape (GET /scraper)
scraperRoutes.get('/fetch', (request, response) => {
if (!validUrl.isWebUri(request.query.url)) {
response.status(400).json(invalidUrlResponse);
} else {
getUrlResponse(request.query.url)
.then(data => {
response.json({ success: true, data: data, errors: [] });
})
.catch(error => {
response.status(400).json({
success: false,
errors: [{ type: 'critical', message: error }]
});
});
}
});
scraperRoutes.get('/scrape', (request, response) => {
let responseData = {
success: false,
data: {},
errors: []
};
if (!request.query.url) {
response.status(400).json(noUrlResponse);
} else if (!validUrl.isWebUri(request.query.url)) {
response.status(400).json(invalidUrlResponse);
} else {
const client = new MetaInspector(request.query.url, { timeout: 5000 });
client.on("fetch", function () {
let metadata = {};
if (client.title)
metadata.title = client.title.trim();
else if (client.ogTitle)
metadata.title = client.ogTitle.trim();
if (client.description)
metadata.description = client.description.trim();
else if (client.ogDescription)
metadata.description = client.ogDescription.trim();
if (client.keywords)
metadata.categories = client.keywords.map(kw => kw.trim())
if (client.image)
metadata.thumbnails = [client.image];
responseData.data = metadata;
responseData.success = true;
response.json(responseData);
});
client.on("error", function (err) {
responseData.errors.push({ message: 'Failed to scrape' });
response.status(400).json(responseData);
});
client.fetch();
}
})
// Export
module.exports = scraperRoutes;
|
2ee4606bf29079b7af0f85f8d97e19f684f8c3b0
|
{
"blob_id": "2ee4606bf29079b7af0f85f8d97e19f684f8c3b0",
"branch_name": "refs/heads/master",
"committer_date": "2018-04-13T19:47:22",
"content_id": "6431173f17652684c1e87b0d978d7cd557a94637",
"detected_licenses": [
"MIT"
],
"directory_id": "2b87e0451e8bb4400d22732d3a0a5d060fc0c1fd",
"extension": "js",
"filename": "scraper.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 125429198,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 3519,
"license": "MIT",
"license_type": "permissive",
"path": "/api/src/routes/scraper.js",
"provenance": "stack-edu-0036.json.gz:170965",
"repo_name": "memo-app/web-app",
"revision_date": "2018-04-13T19:47:22",
"revision_id": "0297de40c462aa8b2716f4eec3bdfe32d75786e8",
"snapshot_id": "271a46ad18e875c7a8c8908627babc4e9e60bce3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/memo-app/web-app/0297de40c462aa8b2716f4eec3bdfe32d75786e8/api/src/routes/scraper.js",
"visit_date": "2021-04-09T10:20:04.115752",
"added": "2024-11-19T02:07:03.602072+00:00",
"created": "2018-04-13T19:47:22",
"int_score": 3,
"score": 2.59375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0054.json.gz"
}
|
// Generated by OABuilder
package com.remodel.model.oa.propertypath;
import java.io.Serializable;
import com.remodel.model.oa.*;
public class DatabaseTypePPx implements PPxInterface, Serializable {
private static final long serialVersionUID = 1L;
public final String pp; // propertyPath
public DatabaseTypePPx(String name) {
this(null, name);
}
public DatabaseTypePPx(PPxInterface parent, String name) {
String s = null;
if (parent != null) {
s = parent.toString();
}
if (s == null) s = "";
if (name != null && name.length() > 0) {
if (s.length() > 0 && name.charAt(0) != ':') s += ".";
s += name;
}
pp = s;
}
public ColumnTypePPx columnTypes() {
ColumnTypePPx ppx = new ColumnTypePPx(this, DatabaseType.P_ColumnTypes);
return ppx;
}
public DatabasePPx databases() {
DatabasePPx ppx = new DatabasePPx(this, DatabaseType.P_Databases);
return ppx;
}
public String id() {
return pp + "." + DatabaseType.P_Id;
}
public String created() {
return pp + "." + DatabaseType.P_Created;
}
public String name() {
return pp + "." + DatabaseType.P_Name;
}
public String description() {
return pp + "." + DatabaseType.P_Description;
}
public String driverName() {
return pp + "." + DatabaseType.P_DriverName;
}
public String jdbcUrl() {
return pp + "." + DatabaseType.P_JdbcUrl;
}
public String type() {
return pp + "." + DatabaseType.P_Type;
}
@Override
public String toString() {
return pp;
}
public String pp() {
return pp;
}
}
|
21d7252f0aa518442691a0868d6d49f2043d879f
|
{
"blob_id": "21d7252f0aa518442691a0868d6d49f2043d879f",
"branch_name": "refs/heads/master",
"committer_date": "2022-12-26T21:45:22",
"content_id": "b07d508eb04020324e3e6b78b23c34dffe25b112",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "94ab5579518876367c41fd0cc5016a65c447e52b",
"extension": "java",
"filename": "DatabaseTypePPx.java",
"fork_events_count": 0,
"gha_created_at": "2019-04-07T23:21:08",
"gha_event_created_at": "2022-12-25T18:39:54",
"gha_language": "Java",
"gha_license_id": "Apache-2.0",
"github_id": 180035642,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1761,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/test/java/com/remodel/model/oa/propertypath/DatabaseTypePPx.java",
"provenance": "stack-edu-0022.json.gz:543302",
"repo_name": "ViaOA/oa-core",
"revision_date": "2022-12-26T21:45:22",
"revision_id": "a30ce92c6eb1d9557cd1145353717043b4cd0e23",
"snapshot_id": "31688eb10f304944054fa9b7372e95da927d2123",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ViaOA/oa-core/a30ce92c6eb1d9557cd1145353717043b4cd0e23/src/test/java/com/remodel/model/oa/propertypath/DatabaseTypePPx.java",
"visit_date": "2023-08-17T10:27:38.649812",
"added": "2024-11-18T21:39:35.090233+00:00",
"created": "2022-12-26T21:45:22",
"int_score": 2,
"score": 2.21875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz"
}
|
package com.seguetech.zippy.ui;
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.style.MetricAffectingSpan;
public class TypeManagedSpan extends MetricAffectingSpan {
private final String typeFaceName;
private final Context context;
public TypeManagedSpan(Context context, String typeFaceName) {
this.context = context.getApplicationContext();
this.typeFaceName = typeFaceName;
}
@Override
public void updateDrawState(final TextPaint drawState) {
apply(drawState);
}
@Override
public void updateMeasureState(final TextPaint paint) {
apply(paint);
}
private void apply(final Paint paint) {
final Typeface oldTypeface = paint.getTypeface();
final int oldStyle = oldTypeface != null ? oldTypeface.getStyle() : 0;
Typeface tf = TypeManager.getInstance(context).get(typeFaceName, oldStyle);
if (tf == null) return;
final int fakeStyle = oldStyle & ~tf.getStyle();
if ((fakeStyle & Typeface.BOLD) != 0) {
paint.setFakeBoldText(true);
}
if ((fakeStyle & Typeface.ITALIC) != 0) {
paint.setTextSkewX(-0.25f);
}
paint.setTypeface(tf);
}
}
|
a0fb402d71dc1da530fa3d74fadcb9caeb23205c
|
{
"blob_id": "a0fb402d71dc1da530fa3d74fadcb9caeb23205c",
"branch_name": "refs/heads/master",
"committer_date": "2015-07-06T22:07:04",
"content_id": "9d689d6203f890f9698a790961d5bafdae413f18",
"detected_licenses": [
"CC0-1.0"
],
"directory_id": "7cce1a4a898e94d66ad1beb25d0ca5d4ac856ec2",
"extension": "java",
"filename": "TypeManagedSpan.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 38619868,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1324,
"license": "CC0-1.0",
"license_type": "permissive",
"path": "/Android/app/src/main/java/com/seguetech/zippy/ui/TypeManagedSpan.java",
"provenance": "stack-edu-0023.json.gz:550718",
"repo_name": "seguemodev/Meducated-Ninja",
"revision_date": "2015-07-06T22:07:04",
"revision_id": "cc7bb88f20bac0f66f2e00b69d7c18342ca8d413",
"snapshot_id": "174b783ca31d36046bdf3d0a4d753363a0cde05a",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/seguemodev/Meducated-Ninja/cc7bb88f20bac0f66f2e00b69d7c18342ca8d413/Android/app/src/main/java/com/seguetech/zippy/ui/TypeManagedSpan.java",
"visit_date": "2016-09-06T21:53:54.150015",
"added": "2024-11-18T23:12:49.297699+00:00",
"created": "2015-07-06T22:07:04",
"int_score": 2,
"score": 2.265625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz"
}
|
using OsuParsers.Storyboards.Interfaces;
namespace OsuParsers.Storyboards.Commands
{
public class TriggerCommand : IHasCommands
{
public string TriggerName;
public int TriggerStartTime;
public int TriggerEndTime;
public int GroupNumber;
public CommandGroup Commands { get; } = new CommandGroup();
public TriggerCommand(string triggerName, int startTime, int endTime, int groupNumber)
{
TriggerName = triggerName;
TriggerStartTime = startTime;
TriggerEndTime = endTime;
GroupNumber = groupNumber;
}
}
}
|
d4f1e663c73f883df62d34c03bc933a025952c00
|
{
"blob_id": "d4f1e663c73f883df62d34c03bc933a025952c00",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-02T01:52:07",
"content_id": "c08e7a63b5bdbffb4dc3b9176b74b7a99d30c90e",
"detected_licenses": [
"MIT"
],
"directory_id": "bf700e01a988782d4fb41a6f65acaf21167b21d2",
"extension": "cs",
"filename": "TriggerCommand.cs",
"fork_events_count": 0,
"gha_created_at": "2021-02-28T17:48:01",
"gha_event_created_at": "2021-03-02T01:40:38",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 343172278,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 632,
"license": "MIT",
"license_type": "permissive",
"path": "/OsuParsers/Storyboards/Commands/TriggerCommand.cs",
"provenance": "stack-edu-0010.json.gz:783398",
"repo_name": "WWRS/OsuParsers",
"revision_date": "2021-03-02T01:52:07",
"revision_id": "82b341effa5b105d70e93a89f9046aad855c54e7",
"snapshot_id": "c4c3f642dbf2e23f9a580488cb49025a89ed065d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/WWRS/OsuParsers/82b341effa5b105d70e93a89f9046aad855c54e7/OsuParsers/Storyboards/Commands/TriggerCommand.cs",
"visit_date": "2023-03-11T05:06:01.466748",
"added": "2024-11-19T00:51:25.298832+00:00",
"created": "2021-03-02T01:52:07",
"int_score": 2,
"score": 2.453125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0028.json.gz"
}
|
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
// all nodes on left less than root val
bool leftIsCool(int val, TreeNode* node) {
if (node == nullptr) return true;
if (val <= node->val) return false;
if ((leftIsCool(val, node->left) and leftIsCool(val, node->right)) == false) return false;
return true;
}
// all nodes on right greater than root val
bool rightIsCool(int val, TreeNode* node) {
if (node == nullptr) return true;
if (val >= node->val) return false;
if ((rightIsCool(val, node->left) and rightIsCool(val, node->right)) == false) return false;
return true;
}
bool isValidBST(TreeNode* root) {
if (root == nullptr)
return true;
if (leftIsCool(root->val, root->left) == false) return false;
if(isValidBST(root->left) == false) return false;
if (rightIsCool(root->val, root->right) == false) return false;
if(isValidBST(root->right) == false) return false;
return true;
}
};
|
df6ee4986878449fb8294e60f003afffcf673389
|
{
"blob_id": "df6ee4986878449fb8294e60f003afffcf673389",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-13T18:39:09",
"content_id": "7d7ee32cd86da5164abc344043280db4cad3fcb4",
"detected_licenses": [
"MIT"
],
"directory_id": "b819584ae7377f0d0b00414430491af95c5b7337",
"extension": "cpp",
"filename": "validate-binary-tree.cpp",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 373748713,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1418,
"license": "MIT",
"license_type": "permissive",
"path": "/medium/validate-binary-tree.cpp",
"provenance": "stack-edu-0007.json.gz:56550",
"repo_name": "kaushalvivek/leetcode-solutions",
"revision_date": "2021-08-13T18:39:09",
"revision_id": "739c5dfbde99239bede460faeb9b0f0d5bc338e9",
"snapshot_id": "3525c171ca54e45559697c6fa5ffb8ea03ea1c91",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/kaushalvivek/leetcode-solutions/739c5dfbde99239bede460faeb9b0f0d5bc338e9/medium/validate-binary-tree.cpp",
"visit_date": "2023-07-08T15:29:30.188498",
"added": "2024-11-18T22:25:28.335129+00:00",
"created": "2021-08-13T18:39:09",
"int_score": 3,
"score": 3.296875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0025.json.gz"
}
|
package main
import (
"context"
"encoding/json"
"flag"
"log"
"math/rand"
"net"
"os"
"sort"
"strings"
"time"
"github.com/isucon/isucon9-qualify/bench/asset"
"github.com/isucon/isucon9-qualify/bench/fails"
"github.com/isucon/isucon9-qualify/bench/scenario"
"github.com/isucon/isucon9-qualify/bench/server"
"github.com/isucon/isucon9-qualify/bench/session"
)
type Output struct {
Pass bool `json:"pass"`
Score int64 `json:"score"`
Campaign int `json:"campaign"`
Language string `json:"language"`
Messages []string `json:"messages"`
}
type Config struct {
TargetURLStr string
TargetHost string
ShipmentURL string
PaymentURL string
PaymentPort int
ShipmentPort int
AllowedIPs []net.IP
}
func init() {
rand.Seed(time.Now().UnixNano())
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
}
func main() {
flags := flag.NewFlagSet("isucon9q", flag.ContinueOnError)
flags.SetOutput(os.Stderr)
conf := Config{}
allowedIPStr := ""
dataDir := ""
staticDir := ""
flags.StringVar(&conf.TargetURLStr, "target-url", "http://127.0.0.1:8000", "target url")
flags.StringVar(&conf.TargetHost, "target-host", "isucon9.catatsuy.org", "target host")
flags.StringVar(&conf.PaymentURL, "payment-url", "http://localhost:5555", "payment url")
flags.StringVar(&conf.ShipmentURL, "shipment-url", "http://localhost:7000", "shipment url")
flags.IntVar(&conf.PaymentPort, "payment-port", 5555, "payment service port")
flags.IntVar(&conf.ShipmentPort, "shipment-port", 7000, "shipment service port")
flags.StringVar(&dataDir, "data-dir", "initial-data", "data directory")
flags.StringVar(&staticDir, "static-dir", "webapp/public/static", "static file directory")
flags.StringVar(&allowedIPStr, "allowed-ips", "", "allowed ips (comma separated)")
err := flags.Parse(os.Args[1:])
if err != nil {
log.Fatal(err)
}
if allowedIPStr != "" {
for _, str := range strings.Split(allowedIPStr, ",") {
aip := net.ParseIP(str)
if aip == nil {
log.Fatalf("allowed-ips: %s cannot be parsed", str)
}
conf.AllowedIPs = append(conf.AllowedIPs, aip)
}
}
// 外部サービスの起動
sp, ss, err := server.RunServer(conf.PaymentPort, conf.ShipmentPort, dataDir, conf.AllowedIPs)
if err != nil {
log.Fatal(err)
}
scenario.SetShipment(ss)
scenario.SetPayment(sp)
err = session.SetShareTargetURLs(
conf.TargetURLStr,
conf.TargetHost,
conf.PaymentURL,
conf.ShipmentURL,
)
if err != nil {
log.Fatal(err)
}
// 初期データの準備
asset.Initialize(dataDir, staticDir)
scenario.InitSessionPool()
log.Print("=== initialize ===")
// 初期化:/initialize にリクエストを送ることで、外部リソースのURLを指定する・DBのデータを初期データのみにする
campaign, language := scenario.Initialize(context.Background(), session.ShareTargetURLs.PaymentURL.String(), session.ShareTargetURLs.ShipmentURL.String())
eMsgs := fails.ErrorsForCheck.GetMsgs()
if len(eMsgs) > 0 {
log.Print("cause error!")
output := Output{
Pass: false,
Score: 0,
Campaign: campaign,
Language: language,
Messages: eMsgs,
}
json.NewEncoder(os.Stdout).Encode(output)
return
}
log.Print("=== verify ===")
// 初期チェック:正しく動いているかどうかを確認する
// 明らかにおかしいレスポンスを返しているアプリケーションはさっさと停止させることで、運営側のリソースを使い果たさない・他サービスへの攻撃に利用されるを防ぐ
scenario.Verify(context.Background())
eMsgs = fails.ErrorsForCheck.GetMsgs()
if len(eMsgs) > 0 {
log.Print("cause error!")
output := Output{
Pass: false,
Score: 0,
Campaign: campaign,
Language: language,
Messages: eMsgs,
}
json.NewEncoder(os.Stdout).Encode(output)
return
}
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(scenario.ExecutionSeconds*time.Second))
defer cancel()
log.Print("=== validation ===")
// 外部サービスのレイテンシを追加
// verify時にもレイテンシを入れていると時間がかかるので、Validationで入れる
ss.SetDelay(800 * time.Millisecond)
sp.SetDelay(800 * time.Millisecond)
// 一番大切なメイン処理:checkとloadの大きく2つの処理を行う
// checkはアプリケーションが正しく動いているか常にチェックする
// 理想的には全リクエストはcheckされるべきだが、それをやるとパフォーマンスが出し切れず、最適化されたアプリケーションよりも遅くなる
// checkとloadは区別がつかないようにしないといけない。loadのリクエストはログアウト状態しかなかったので、ログアウト時のキャッシュを強くするだけでスコアがはねる問題が過去にあった
// 今回はほぼ全リクエストがログイン前提になっているので、checkとloadの区別はできないはず
scenario.Validation(ctx, campaign)
// context.Canceledのエラーは直後に取れば基本的には入ってこない
eMsgs, cCnt, aCnt, tCnt := fails.ErrorsForCheck.Get()
// critical errorは1つでもあれば、application errorは10回以上で失格
if cCnt > 0 || aCnt >= 10 {
log.Print("cause error!")
output := Output{
Pass: false,
Score: 0,
Campaign: campaign,
Language: language,
Messages: uniqMsgs(eMsgs),
}
json.NewEncoder(os.Stdout).Encode(output)
return
}
<-time.After(1 * time.Second)
log.Print("=== final check ===")
// 最終チェック:ベンチマーカーの記録とアプリケーションの記録を突き合わせて、最終的なスコアを算出する
score := scenario.FinalCheck(context.Background())
// application errorだけが発生する
fMsgs, _, faCnt, _ := fails.ErrorsForFinal.Get()
msgs := append(uniqMsgs(eMsgs), fMsgs...)
aCnt += faCnt
// application errorは10回以上で失格
if aCnt >= 10 {
output := Output{
Pass: false,
Score: 0,
Campaign: campaign,
Language: language,
Messages: msgs,
}
json.NewEncoder(os.Stdout).Encode(output)
return
}
// application errorは1回で500点減点
penalty := int64(500 * aCnt)
if tCnt > 200 {
// trivial errorは200回を超えたら100回毎に5000点減点
penalty += int64(5000 * (1 + (tCnt-200)/100))
}
log.Print(score, penalty)
score -= penalty
// 0点以下なら失格
if score <= 0 {
output := Output{
Pass: false,
Score: 0,
Campaign: campaign,
Language: language,
Messages: msgs,
}
json.NewEncoder(os.Stdout).Encode(output)
return
}
output := Output{
Pass: true,
Score: score,
Campaign: campaign,
Language: language,
Messages: msgs,
}
json.NewEncoder(os.Stdout).Encode(output)
}
func uniqMsgs(allMsgs []string) []string {
sort.Strings(allMsgs)
msgs := make([]string, 0, len(allMsgs))
tmp := ""
// 適当にuniqする
for _, m := range allMsgs {
if tmp != m {
tmp = m
msgs = append(msgs, m)
}
}
return msgs
}
|
ca5b75d6a92ca7201f62615824e67ea25fbeb5c2
|
{
"blob_id": "ca5b75d6a92ca7201f62615824e67ea25fbeb5c2",
"branch_name": "refs/heads/master",
"committer_date": "2020-08-08T11:57:10",
"content_id": "f8e9c1d3dc4199aae9eb4128a74a95cc11075100",
"detected_licenses": [
"MIT"
],
"directory_id": "54ae2565eeb5573bddbe4e2e5e42c5b5ca69eed9",
"extension": "go",
"filename": "main.go",
"fork_events_count": 1,
"gha_created_at": "2020-08-08T02:19:30",
"gha_event_created_at": "2020-08-31T10:52:17",
"gha_language": "Go",
"gha_license_id": "MIT",
"github_id": 285956900,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 7090,
"license": "MIT",
"license_type": "permissive",
"path": "/cmd/bench/main.go",
"provenance": "stack-edu-0017.json.gz:333676",
"repo_name": "ryo628/isucon9-qualify",
"revision_date": "2020-08-08T11:57:10",
"revision_id": "ab767ec40ebcf7373eea881675b7a857de64f5dd",
"snapshot_id": "0fd16efc6b69afdb4ab31b21a29ee63dea57522b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ryo628/isucon9-qualify/ab767ec40ebcf7373eea881675b7a857de64f5dd/cmd/bench/main.go",
"visit_date": "2022-12-14T02:58:27.383984",
"added": "2024-11-18T23:36:52.011643+00:00",
"created": "2020-08-08T11:57:10",
"int_score": 2,
"score": 2.234375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0035.json.gz"
}
|
/*
* Copyright 2004, Hajo Kirchhoff - Lit Window Productions, http://www.litwindow.com
* This file is part of the Lit Window Library. All use of this material - copying
* in full or part, including in other works, using in non-profit or for-profit work
* and other uses - is governed by the licence contained in the Lit Window Library
* distribution, file LICENCE.TXT
* $Id: check.hpp,v 1.5 2006/11/28 13:44:03 Hajo Kirchhoff Exp $
*/
#ifndef _CHECK_HPP
#define _CHECK_HPP
#ifdef _MSC_VER
#pragma once
#endif
#include <stdexcept>
#include <map>
#include <string>
#ifndef ASSERT
#include <assert.h>
#define ASSERT assert
#endif
#include "lwbase.hpp"
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/stringize.hpp>
namespace litwindow {
namespace checks {
class LWBASE_API __c_ContextObject
{
public:
typedef std::map<std::string, std::string> attributes_t;
__c_ContextObject(char* text);
~__c_ContextObject();
std::string &operator[](const char *name)
{
if (m_attributes==0) m_attributes=new attributes_t;
return (*m_attributes)[name];
}
const char *context;
attributes_t *m_attributes;
static __c_ContextObject *get_top() { return top; }
protected:
__c_ContextObject *previous;
static __c_ContextObject *top;
};
inline __c_ContextObject& Context() { return *__c_ContextObject::get_top(); }
inline void AddContext(const char* name, const char *value) { Context()[name]=value; }
typedef __c_ContextObject context_t;
#define LWL_CONTEXT(a) litwindow::checks::__c_ContextObject BOOST_PP_CAT(__c_obj, __LINE__)(a)
#define LWLCHECK litwindow::checks::__c_ContextObject BOOST_PP_CAT(__c_obj, __LINE__)(__FILE__ ":" BOOST_PP_STRINGIZE(__LINE__)"(" __FUNCTION__ ")")
//#define CONTEXT(a) __c_ContextObject __c_obj(a)
#define AssertRange(idx, vec, msg) Verify((idx)>=0 && (idx)<sizeof (vec)/sizeof (*(vec)), msg)
class assertion_failed : public std::runtime_error {
public:
assertion_failed(const std::string& message):std::runtime_error(message) {}
};
class precondition_violated : public std::logic_error {
public:
precondition_violated(const std::string& message):std::logic_error(message) {}
};
class invariant_violated : public std::logic_error {
public:
invariant_violated(const std::string& message):std::logic_error(message) {}
};
class abort_on : public std::runtime_error {
public:
abort_on(const std::string& message):std::runtime_error(message) {}
};
//////////////////////////////////////////////////////////////////////////
inline void AbortOn(bool condition, const char* text)
{
if (condition)
throw abort_on(text);
}
inline void Verify(bool condition, /*const char* str_condition, */const char* text="")
{
if (!condition) {
throw assertion_failed(text);
}
}
inline void Precondition(bool condition, /*const char* str_condition, */const char* text)
{
if (!condition) {
// throw an error
throw precondition_violated(text);
}
}
inline void Invariant(bool condition, const char* text="Invariant violated")
{
if (!condition) {
throw invariant_violated(text);
}
}
inline void Fail(const char* text)
{
// throw an error
throw std::runtime_error(text);
}
//////////////////////////////////////////////////////////////////////////
//#define Precondition(a, b) _Precondition(a, #a, b)
//#define Verify(a, b) _Assure(a, #a, b)
std::string LWBASE_API GetErrorMessage(std::exception &e);
std::string LWBASE_API GetErrorMessage(const char *);
std::string LWBASE_API GetExceptionContext(bool resetContext=true);
class try_op_base_t
{
public:
virtual void operator() () = 0;
};
template <class Result, class T>
class try_mem_fun_t:public try_op_base_t
{
public:
try_mem_fun_t(T* pThis, Result (T::*pMemFun)()):thisPtr(pThis), memFunPtr(pMemFun) {}
void operator() ()
{
rc=(thisPtr->*memFunPtr)();
}
T* thisPtr;
Result (T::*memFunPtr)();
Result rc;
};
template <class Result, class T>
try_mem_fun_t<Result, T> try_mem_fun(T* pThis, Result (T::*pMemFun)())
{
return try_mem_fun_t<Result, T>(pThis, pMemFun);
}
int LWBASE_API TryOperation(try_op_base_t& tryOperation);
template <class Result, class T>
std::pair<int, Result> TryOperation(try_mem_fun_t<Result, T>& tryOperation)
{
int rc=TryOperation(static_cast<try_op_base_t&>(tryOperation));
return make_pair(rc, tryOperation.rc);
}
};
using namespace checks;
//namespace check = checks;
#define MemFun(a) try_mem_fun(this, a)
}
#endif
|
c6603190a80713f6120546ebba60897e139bff93
|
{
"blob_id": "c6603190a80713f6120546ebba60897e139bff93",
"branch_name": "refs/heads/master",
"committer_date": "2016-12-28T18:16:58",
"content_id": "0dcfc7c0b5fc970b6037c4a0cc5e33ecfc050165",
"detected_licenses": [
"MIT",
"BSD-3-Clause"
],
"directory_id": "ae7ec837eb954d7be7878f367aa7afb70d1a3897",
"extension": "hpp",
"filename": "check.hpp",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 77551164,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4603,
"license": "MIT,BSD-3-Clause",
"license_type": "permissive",
"path": "/litwindow/check.hpp",
"provenance": "stack-edu-0006.json.gz:59512",
"repo_name": "hajokirchhoff/litwindow",
"revision_date": "2016-12-28T18:16:58",
"revision_id": "7f574d4e80ee8339ac11c35f075857c20391c223",
"snapshot_id": "0387bd1e59200eddb77784c665ba921089589026",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hajokirchhoff/litwindow/7f574d4e80ee8339ac11c35f075857c20391c223/litwindow/check.hpp",
"visit_date": "2022-06-18T20:15:21.475921",
"added": "2024-11-18T23:05:33.758393+00:00",
"created": "2016-12-28T18:16:58",
"int_score": 2,
"score": 2.25,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0024.json.gz"
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace Com.Synopsys.Integration.Nuget.Model
{
public class PackageSetBuilder
{
private Dictionary<PackageId, PackageSet> packageSets = new Dictionary<PackageId, PackageSet>();
private Dictionary<PackageId, VersionPair> versions = new Dictionary<PackageId, VersionPair>();
public bool DoesPackageExist(PackageId id)
{
return packageSets.ContainsKey(id);
}
public PackageSet GetOrCreatePackageSet(PackageId package)
{
PackageSet set;
if (packageSets.TryGetValue(package, out set))
{
return set;
}
else
{
set = new PackageSet();
set.PackageId = package;
set.Dependencies = new HashSet<PackageId>();
packageSets[package] = set;
NuGet.Versioning.NuGetVersion version = null;
NuGet.Versioning.NuGetVersion.TryParse(package.Version, out version);
versions[package] = new VersionPair() { rawVersion = package.Version, version = version };
return set;
}
}
public void AddOrUpdatePackage(PackageId id)
{
var set = GetOrCreatePackageSet(id);
}
public void AddOrUpdatePackage(PackageId id, PackageId dependency)
{
var set = GetOrCreatePackageSet(id);
set.Dependencies.Add(dependency);
}
public void AddOrUpdatePackage(PackageId id, HashSet<PackageId> dependencies)
{
var set = GetOrCreatePackageSet(id);
set.Dependencies.UnionWith(dependencies);
}
public List<PackageSet> GetPackageList()
{
return packageSets.Values.ToList();
}
private class VersionPair
{
public string rawVersion;
public NuGet.Versioning.NuGetVersion version;
}
public string GetBestVersion(string name, NuGet.Versioning.VersionRange range)
{
var allVersions = versions.Keys.Where(key => key.Name == name).Select(key => versions[key]);
var best = range.FindBestMatch(allVersions.Select(ver => ver.version));
foreach (var pair in versions)
{
if (pair.Key.Name == name && pair.Value.version == best) return pair.Key.Version;
}
return null;
}
}
}
|
ac0f7df6b226bb96ca2bd287cef764f7e3dc5acf
|
{
"blob_id": "ac0f7df6b226bb96ca2bd287cef764f7e3dc5acf",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-09T16:36:41",
"content_id": "446acbbf4518a3664280b1e8d812e6109988f066",
"detected_licenses": [
"MIT"
],
"directory_id": "32fb3932a6a5bae0ae2d65ab733f1503e876cb33",
"extension": "cs",
"filename": "PackageSetBuilder.cs",
"fork_events_count": 1,
"gha_created_at": "2018-09-27T18:28:31",
"gha_event_created_at": "2020-06-29T04:25:23",
"gha_language": "C#",
"gha_license_id": "MIT",
"github_id": 150630892,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 2551,
"license": "MIT",
"license_type": "permissive",
"path": "/BlackduckNugetInspector/Model/PackageSetBuilder.cs",
"provenance": "stack-edu-0011.json.gz:229989",
"repo_name": "blackducksoftware/blackduck-nuget-inspector",
"revision_date": "2021-09-09T16:36:41",
"revision_id": "a4fe95f2736b65bc15acce08a7e66d386bd856e0",
"snapshot_id": "1e0fddc7b6dab0c6ac1c1360fb7503492a64c2e8",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/blackducksoftware/blackduck-nuget-inspector/a4fe95f2736b65bc15acce08a7e66d386bd856e0/BlackduckNugetInspector/Model/PackageSetBuilder.cs",
"visit_date": "2022-03-08T15:08:58.416860",
"added": "2024-11-18T22:13:35.549143+00:00",
"created": "2021-09-09T16:36:41",
"int_score": 3,
"score": 2.734375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0029.json.gz"
}
|
using NJsonSchema;
using NJsonSchema.CodeGeneration.CSharp;
using NSwag;
using NSwag.CodeGeneration.CSharp;
using NSwag.CodeGeneration.CSharp.Models;
using System.Text.RegularExpressions;
namespace WebApiClientCore.OpenApi.SourceGenerator
{
/// <summary>
/// 表示WebApiClient的请求方法数据模型
/// </summary>
public class HttpApiMethod : CSharpOperationModel
{
/// <summary>
/// WebApiClient的请求方法数据模型
/// </summary>
/// <param name="operation">Swagger操作</param>
/// <param name="settings">设置项</param>
/// <param name="generator">代码生成器</param>
/// <param name="resolver">语法解析器</param>
public HttpApiMethod(OpenApiOperation operation, CSharpGeneratorBaseSettings settings, CSharpGeneratorBase generator, CSharpTypeResolver resolver)
: base(operation, settings, generator, resolver)
{
}
/// <summary>
/// 获取方法的返回类型
/// 默认使用ITask
/// </summary>
public override string ResultType
{
get
{
return this.SyncResultType == "void"
? "Task"
: $"ITask<{this.SyncResultType}>";
}
}
/// <summary>
/// 获取方法好友名称
/// </summary>
public override string ActualOperationName
{
get
{
var name = base.ActualOperationName;
if (Regex.IsMatch(name, @"^\d") == false)
{
return name;
}
name = Regex.Match(this.Id, @"\w*").Value;
if (string.IsNullOrEmpty(name))
{
name = "unnamed";
}
var names = name.ToCharArray();
names[0] = char.ToUpper(names[0]);
return new string(names);
}
}
/// <summary>
/// 解析参数名称
/// 将文件参数声明为MulitpartFile
/// </summary>
/// <param name="parameter">参数</param>
/// <returns></returns>
protected override string ResolveParameterType(OpenApiParameter parameter)
{
var isFileParameter = IsFileParameter(parameter) || IsFileParameter(parameter.Schema);
if (isFileParameter)
{
var isArrayParameter = IsArrayParameter(parameter) || IsArrayParameter(parameter.Schema);
return isArrayParameter ? "IEnumerable<FormDataFile>" : "FormDataFile";
}
return base.ResolveParameterType(parameter);
}
private static bool IsFileParameter(JsonSchema parameter)
{
if (parameter == null)
{
return false;
}
if (parameter.IsBinary)
{
return true;
}
return parameter.IsArray && parameter.Item?.IsBinary == true;
}
private static bool IsArrayParameter(JsonSchema parameter)
{
if (parameter == null)
{
return false;
}
if (parameter.Type.HasFlag(JsonObjectType.Array))
{
return true;
}
if (parameter is OpenApiParameter apiParameter)
{
return apiParameter.CollectionFormat == OpenApiParameterCollectionFormat.Multi;
}
return false;
}
}
}
|
711f74231bb25c733289c2a5f1a24418e3aad097
|
{
"blob_id": "711f74231bb25c733289c2a5f1a24418e3aad097",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-01T06:36:58",
"content_id": "87742037469738db71f795c951dc16efff4ceba2",
"detected_licenses": [
"MIT"
],
"directory_id": "4c657803e179ba0a06f70a34467f11b1eae12a5d",
"extension": "cs",
"filename": "HttpApiMethod.cs",
"fork_events_count": 414,
"gha_created_at": "2017-03-28T05:24:45",
"gha_event_created_at": "2023-09-06T11:37:01",
"gha_language": "C#",
"gha_license_id": "MIT",
"github_id": 86418275,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 3613,
"license": "MIT",
"license_type": "permissive",
"path": "/WebApiClientCore.OpenApi.SourceGenerator/HttpApiMethod.cs",
"provenance": "stack-edu-0011.json.gz:108657",
"repo_name": "dotnetcore/WebApiClient",
"revision_date": "2023-08-01T06:36:58",
"revision_id": "ce35e624f2f235c6906137e78c9dcf649a16bc0e",
"snapshot_id": "7313ed7c45fe99bf9ab5f87f06c5fe2ed166281c",
"src_encoding": "UTF-8",
"star_events_count": 1923,
"url": "https://raw.githubusercontent.com/dotnetcore/WebApiClient/ce35e624f2f235c6906137e78c9dcf649a16bc0e/WebApiClientCore.OpenApi.SourceGenerator/HttpApiMethod.cs",
"visit_date": "2023-08-25T13:53:17.712990",
"added": "2024-11-19T00:50:32.641105+00:00",
"created": "2023-08-01T06:36:58",
"int_score": 2,
"score": 2.40625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0029.json.gz"
}
|
import yaml
from devops.cicd.applications.generators.base_generator import BaseGenerator
class JenkinsGenerator(BaseGenerator):
def get_content(self):
obj = self.cfg
proj_obj = obj["project"]
project = proj_obj["name"]
desc = proj_obj["description"]
header = """
jenkins:
systemMessage: "{description}"
tool:
git:
installations:
- home: "git"
name: "Default"
maven:
installations:
- name: "Maven 3"
properties:
- installSource:
installers:
- maven:
id: "3.5.4"
jobs:
""".format(description=project)
script_block = '''
- script: >
multibranchPipelineJob("{name}")
{{
displayName("{name}")
branchSources {{
git {{
id('{name}')
remote('{url}')
credentialsId('{credential}')
includes('{branches_include}')
excludes('release/*')
}}
}}
triggers {{
periodic({trigger_period})
}}
}}
'''
repositories = obj["repositories"]
jenkins_jobs = obj["jenkins_jobs"]
blocks = ""
for job in jenkins_jobs:
repo_name = job["repository"]
repo = self.lookup_repo(repositories, repo_name)
blocks = blocks + script_block.format(
name=job["name"],
branches_include=job["branches_include"],
trigger_period=job["trigger_period"],
credential=repo["credential"],
url=repo["url"])
content = header + blocks
return content
def lookup_repo(self, repositories, repo):
for rp in repositories:
if rp["name"] == repo:
return rp
dummy = {'url': 'ERROR! - URL not found', 'credential': 'ERROR!!'}
return dummy
|
42b048e21ae11e7134968c00b3ebe0b410facc25
|
{
"blob_id": "42b048e21ae11e7134968c00b3ebe0b410facc25",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-20T13:12:24",
"content_id": "00dbe02d577833cf8c358092dcdfc48d3c9adb8f",
"detected_licenses": [
"MIT"
],
"directory_id": "21c0286de883365292afa0462154dd46591eeb6a",
"extension": "py",
"filename": "jeninks_generator.py",
"fork_events_count": 0,
"gha_created_at": "2019-10-19T13:03:29",
"gha_event_created_at": "2019-10-20T13:12:24",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 216207398,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2034,
"license": "MIT",
"license_type": "permissive",
"path": "/src/devops/cicd/applications/generators/jeninks_generator.py",
"provenance": "stack-edu-0060.json.gz:375379",
"repo_name": "pjamenaja/pipeline_configs",
"revision_date": "2019-10-20T13:12:24",
"revision_id": "eea80115ef990ebefaa7dc461cb493cae3922e49",
"snapshot_id": "a3829004c9c0af112e7842e14766d97c772cb899",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/pjamenaja/pipeline_configs/eea80115ef990ebefaa7dc461cb493cae3922e49/src/devops/cicd/applications/generators/jeninks_generator.py",
"visit_date": "2020-08-21T17:20:38.033728",
"added": "2024-11-18T21:49:03.010699+00:00",
"created": "2019-10-20T13:12:24",
"int_score": 2,
"score": 2.109375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0078.json.gz"
}
|
# 1999
[We could all die any day 1999 /
I don't wanna die /
I'd rather dance my life away 1999 /
Listen to what I'm tryin' to say...](https://genius.com/3870836/Prince-1999/We-could-all-die-any-day-1999-i-dont-wanna-die-id-rather-dance-my-life-away-1999-listen-to-what-im-tryin-to-say)
A simple copycat web app that will listen for what you say and repeat it back.
## Run
```
npm install
npm start
```
## Motivation
The experiment had a two-fold purpose:
1. Proof of concept for in-browser companion voice support using react.
2. Explore built-in browser support for Web Speech API vis-á-vis a single controlled implementation.
## Web Speech API Support
Browser | OS | ASR | TTS | Status
--- | --- | --- | ------ | -------
Safari | macOS | ❌ | ✅ | [Partial Supported](https://developer.apple.com/safari/features/#morefeatures)
Safari | iOS | ❌ | ✅ | Partial Supported
Chrome | macOS | ✅ | ✅ | Fully Supported
Chrome | iOS | ❌ | ✅ | Partial Supported
Chrome | Android | ❌ | ✅ | Partially Supported
Firefox | macOS | ❌ | ✅ | [Partial Supported](https://bugzilla.mozilla.org/show_bug.cgi?id=1244460)
Silk | FireOS | ❌ | ✅ | Partial Supported
### Notes
https://caniuse.com/#feat=speech-recognition is the most accurate browser support matrix, but it's incomplete for mobile browsers.
Safari docs say that Web Speech API is fully supported, but that is a lie.
Most places say Firefox supports Web Speech API, but that is a lie too.
Chrome [probably uses a Google ASR service](https://www.chromium.org/developers/how-tos/api-keys). However, a Chromium contributor warns that there is discussion about [deprecating Web Speech API](https://groups.google.com/a/chromium.org/d/msg/chromium-dev/mUe4NM5xEzk/fL0pIvEACQAJ).
Chrome on Android/FireOS probably works, but more debugging needed.
## Backend
[Web Speech API](https://w3c.github.io/speech-api/speechapi.html), cf https://developer.mozilla.org/en-US/docs/Web/API/Web_Speech_API
### NLU
Unimplemented
### ASR
Browser-specific, but only Chrome supports ASR, and it's ASR service is obfuscated but [probably uses Google Speech API](https://groups.google.com/a/chromium.org/d/msg/chromium-dev/KMY5Z9qSyOA/Ali77Ebd64MJ)
### TTS
Browser-specific, but all that I checked use the platform OS TTS service.
## Frontend
React, using [React Voice Components](https://github.com/grvcoelho/react-voice-components/)
## Alternatives
- [Annyang](https://github.com/TalAter/annyang) is a HTML5 wrapper around Web Speech API.
- [Artyom](https://github.com/sdkcarlos/artyom.js) is a HTML5 wrapper around Web Speech API.
- [Google Cloud Speech API](https://cloud.google.com/speech/) offers the ability to do ASR directly, using a custom React component. Requires API key, $ per-request. There is a [reference implementation in Node](https://github.com/googleapis/nodejs-speech/tree/master/samples#speech-recognition).
## License
Copyright 2018 Pylon, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
|
9c32ea6f4a7f5f91ab05afd14427954206597be1
|
{
"blob_id": "9c32ea6f4a7f5f91ab05afd14427954206597be1",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-17T20:47:59",
"content_id": "53ac2ac6d20bd292e74d0e9fa91c948b17ab7fe8",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "7011efec8b1190b0432c6c7d4c0b4902906f649e",
"extension": "md",
"filename": "README.md",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 116716161,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3477,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/README.md",
"provenance": "stack-edu-markdown-0012.json.gz:182562",
"repo_name": "pylon/1999",
"revision_date": "2018-05-17T20:47:59",
"revision_id": "1f824965f61903acd8217a00420c9f55c68a2bb4",
"snapshot_id": "81bc1e8a5750db7a2c75af63aafc2e2b276b0e6b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/pylon/1999/1f824965f61903acd8217a00420c9f55c68a2bb4/README.md",
"visit_date": "2021-03-27T09:31:04.172609",
"added": "2024-11-19T00:17:30.224855+00:00",
"created": "2018-05-17T20:47:59",
"int_score": 3,
"score": 3.484375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0012.json.gz"
}
|
public class Cell {
int x=0,y=0;
boolean isFilled=false;
public Cell(int x,int y){
this.x=x;
this.y=y;
isFilled=false;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public boolean isFilled() {
return isFilled;
}
public void setFilled(boolean isFilled) {
this.isFilled = isFilled;
}
}
|
426341da497266077378b8846ccd712cc760ee92
|
{
"blob_id": "426341da497266077378b8846ccd712cc760ee92",
"branch_name": "refs/heads/master",
"committer_date": "2016-01-20T13:15:13",
"content_id": "f16398e13565e87f38b7fed4bf0b4a33a49e8e55",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "2106d33bada10f1a5cdbfc4e458ed3ee5bb448e2",
"extension": "java",
"filename": "Cell.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 50030819,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 434,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/TetrisGame/src/Cell.java",
"provenance": "stack-edu-0026.json.gz:383401",
"repo_name": "oguzozturk/TetrisGame",
"revision_date": "2016-01-20T13:15:13",
"revision_id": "73aac333a795895b6692746744387673d7d358ef",
"snapshot_id": "b83a55b0d0b013d737649f61b5366c4ec6bfd0d6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/oguzozturk/TetrisGame/73aac333a795895b6692746744387673d7d358ef/TetrisGame/src/Cell.java",
"visit_date": "2021-01-10T05:55:55.365543",
"added": "2024-11-18T21:37:48.610693+00:00",
"created": "2016-01-20T13:15:13",
"int_score": 3,
"score": 3.234375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0044.json.gz"
}
|
#!/usr/bin/env python3
'''
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?
'''
def add_up_to(list_in, k):
complements = set()
for v in list_in:
if v in complements:
return True
complements.add(k-v)
return False
assert add_up_to([10, 15, 3, 7], 17)
assert not add_up_to([10, 15, 3], 17)
|
1af266f7c7cbe9396fc8f0e8696381b05799b703
|
{
"blob_id": "1af266f7c7cbe9396fc8f0e8696381b05799b703",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-13T20:16:32",
"content_id": "218460299ed4d94de92d19105ef16d1e6ad31650",
"detected_licenses": [
"MIT"
],
"directory_id": "29aeb689ad10596a12a97745b537ee2fe12df8ea",
"extension": "py",
"filename": "Problem_1.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 163434188,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 497,
"license": "MIT",
"license_type": "permissive",
"path": "/DailyCodingProblem/Problem_1.py",
"provenance": "stack-edu-0057.json.gz:191795",
"repo_name": "byarmis/DailyCodingProblem",
"revision_date": "2019-05-13T20:16:32",
"revision_id": "cb795dcacfde139d8d33ef6e589abaf97a14dad3",
"snapshot_id": "da6598a0890ac8e069cb0139ab0a6cd83db1a951",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/byarmis/DailyCodingProblem/cb795dcacfde139d8d33ef6e589abaf97a14dad3/DailyCodingProblem/Problem_1.py",
"visit_date": "2020-04-13T20:36:45.092069",
"added": "2024-11-18T20:59:58.168285+00:00",
"created": "2019-05-13T20:16:32",
"int_score": 4,
"score": 3.9375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0075.json.gz"
}
|
package es.ucm.fdi.tp.extra.jcolor;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
import javax.swing.table.TableCellRenderer;
@SuppressWarnings("serial")
public class ColorChooserExample extends JFrame {
private JTextField name;
private MyTableModel tModel;
private Map<Integer, Color> colors; // Line -> Color
private ColorChooser colorChooser;
public ColorChooserExample() {
super("[=] ColorChooser Example ! [=]");
initGUI();
}
private void initGUI() {
JPanel mainPanel = new JPanel(new BorderLayout());
colors = new HashMap<>();
colorChooser = new ColorChooser(new JFrame(), "Choose Line Color", Color.BLACK);
// names table
tModel = new MyTableModel();
tModel.getRowCount();
final JTable table = new JTable(tModel) { // LE HE PUESTO YO EL FINAL, NO VENÍA Y DABA ERRORES
private static final long serialVersionUID = 1L;
// THIS IS HOW WE CHANGE THE COLOR OF EACH ROW
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
Component comp = super.prepareRenderer(renderer, row, col);
// the color of row 'row' is taken from the colors table, if
// 'null' setBackground will use the parent component color.
if (col == 1)
comp.setBackground(colors.get(row));
else
comp.setBackground(Color.WHITE);
comp.setForeground(Color.BLACK);
return comp;
}
};
table.setToolTipText("Click on a row to change the color of a player");
table.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
int row = table.rowAtPoint(evt.getPoint());
int col = table.columnAtPoint(evt.getPoint());
if (row >= 0 && col >= 0) {
changeColor(row);
}
}
});
mainPanel.add(new JScrollPane(table), BorderLayout.CENTER);
JPanel ctrlPabel = new JPanel(new FlowLayout(FlowLayout.LEFT));
mainPanel.add(ctrlPabel, BorderLayout.PAGE_START);
// name text box and corresponding button
ctrlPabel.add(new JLabel("Name"));
name = new JTextField(15);
ctrlPabel.add(name);
JButton addName = new JButton("Add");
addName.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String s = name.getText().trim();
if (!s.equals("")) {
tModel.addName(name.getText());
}
name.setText("");
}
});
ctrlPabel.add(addName);
mainPanel.add(new JLabel("Click on a row, in the table above, to chaneg its background color"), BorderLayout.PAGE_END);
mainPanel.setOpaque(true);
this.setContentPane(mainPanel);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800, 500);
this.setVisible(true);
}
private void changeColor(int row) {
colorChooser.setSelectedColorDialog(colors.get(row));
colorChooser.openDialog();
if (colorChooser.getColor() != null) {
colors.put(row, colorChooser.getColor());
repaint();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ColorChooserExample();
}
});
}
}
|
1a801ef1aaab80eeb53a89a23a39213ad1b979d4
|
{
"blob_id": "1a801ef1aaab80eeb53a89a23a39213ad1b979d4",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-26T13:16:29",
"content_id": "2f39da1c6a9b9ba05c75f00ab26b058a05a5bfba",
"detected_licenses": [
"MIT"
],
"directory_id": "793e34599c0b6b13ac777d1e13be3717f049f3d7",
"extension": "java",
"filename": "ColorChooserExample.java",
"fork_events_count": 0,
"gha_created_at": "2017-10-20T11:44:02",
"gha_event_created_at": "2017-10-20T12:06:49",
"gha_language": null,
"gha_license_id": null,
"github_id": 107671392,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3284,
"license": "MIT",
"license_type": "permissive",
"path": "/src/main/java/es/ucm/fdi/tp/extra/jcolor/ColorChooserExample.java",
"provenance": "stack-edu-0023.json.gz:552814",
"repo_name": "paulamlago/TP",
"revision_date": "2018-02-26T13:16:29",
"revision_id": "417df1d10a54462a825251d3ce4054ff091db8d6",
"snapshot_id": "695c9599c07e8bb06a11f455f5a100ed48aef08c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/paulamlago/TP/417df1d10a54462a825251d3ce4054ff091db8d6/src/main/java/es/ucm/fdi/tp/extra/jcolor/ColorChooserExample.java",
"visit_date": "2021-09-24T23:52:24.163494",
"added": "2024-11-18T22:00:26.354302+00:00",
"created": "2018-02-26T13:16:29",
"int_score": 3,
"score": 3.125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz"
}
|
<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');
require(__DIR__ . '/../../vendor/autoload.php');
require(__DIR__ . '/../../vendor/yiisoft/yii2/Yii.php');
$config = yii\helpers\ArrayHelper::merge(
require(__DIR__ . '/../../backend/config/main.php'),
require(__DIR__ . '/../../backend/config/main-local.php'),
require(__DIR__ . '/../config/main.php'),
require(__DIR__ . '/../config/main-local.php')
);
$application = new yii\web\Application($config);
$application->run();
use Yii;
use yii\db\Query;
use common\models\Users;
$time = strtotime('now -10 days ');
$date = date("Y-m-d", $time);
$today = strtotime('now');
$todayDate = date("Y-m-d", $today);
//diffrence between actual date and $time
$diff = $today - $time;
$interval = floor($diff/(60*60*24));
$command = \Yii::$app->db->createCommand(
"
select
p.product_name ,
c.client_name as client,
p.expiry_date,
pp.purchase_id,
pu.created_at,
(p.expiry_date - DATEDIFF(CURDATE(),pu.created_at)) as expire ,
DATEDIFF(CURDATE(),pu.created_at) as datediff,
u.user_name as 'user',
u.user_email as email,
date(pu.created_at) as day
from products p
join purchase_product pp on p.product_id = pp.product_id
join purchases pu on pu.purchase_id=pp.purchase_id
join users u on u.id = pu.user_id
join clients c on c.id = pu.client_id
where pu.created_at like '".$date."%'
and (p.expiry_date - ".$interval.") < 4
GROUP by email,client,product_name
");
$products = $command->queryAll();
$data = array();
foreach ($products as $item) {
$data[$item['email']][$item['client']][] = $item['product_name'];
/*$mail = \Yii::$app->mailer->compose()
->setFrom(['[email protected]'=> 'Expire product'])
->setTo($item['email'])
->setSubject("Don't forget about your clients")
->setTextBody('yeah');
*/
//echo $item['product_name'].' '.$item['user']."\n";
}
foreach ($data as $email => $clients) {
//echo $email."\n";
//$setTo = $email;
$user = Users::findByEmail($email);
$content = 'Hey '.$user->user_name." do not forget about your clients!\n\n";
foreach ($clients as $client => $products) {
$content = $content.'Client: '.$client." ordered this products which probably expired: \n\n";
//echo $client."\n";
foreach ($products as $i => $product) {
$content = $content.$i.". ".$product."\n";
//echo $product."\n";
}
}
$mail = \Yii::$app->mailer->compose()
->setFrom(['[email protected]'=> 'Reminder'])
->setTo($email)
->setSubject("Don't forget about your clients")
->setTextBody($content)
->send();
echo $content."\n\n";
}
|
767d4af2575061284978cf5fbc0d70a39a3d7ff1
|
{
"blob_id": "767d4af2575061284978cf5fbc0d70a39a3d7ff1",
"branch_name": "refs/heads/master",
"committer_date": "2016-09-25T13:24:49",
"content_id": "e79412825c4af42897789e1c13baf82045337a62",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "2e958f74ea4ed8cfd2562c3474afd356ecd1522a",
"extension": "php",
"filename": "check_products.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 69162789,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 3027,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/common/cronjobs/check_products.php",
"provenance": "stack-edu-0049.json.gz:511637",
"repo_name": "qyqax/repshub",
"revision_date": "2016-09-25T13:24:49",
"revision_id": "ff325c1a8b6e33fa6d8d8b090b376469293859bc",
"snapshot_id": "7a83f19f193a342f4b7dfa61e0f3da36b66e906e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/qyqax/repshub/ff325c1a8b6e33fa6d8d8b090b376469293859bc/common/cronjobs/check_products.php",
"visit_date": "2021-01-13T10:18:51.737880",
"added": "2024-11-18T21:51:29.013063+00:00",
"created": "2016-09-25T13:24:49",
"int_score": 2,
"score": 2.40625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0067.json.gz"
}
|
# C Programs For Everybody To Try!
_`Last Updated: June 11' 2021`_
## Introduction:
Here are programs that every budding programmer who is learning to code in C should start with.
These programs are a compilation of many different types of programs and levels of programming you should try.
You can use the table in Order Of Programs file to find the order in which it is best to program in.
## Pre-Requisites:
1. A coding IDE or just use the CMD/Terminal on your Windows Pc/Mac respectively (I used VS Code for this).
2. Check that C/C++ Extension is properly installed in your system/VS Code and the Path to C/C++ is integratively set in your system.
3. Start by trying to create the program by yourself if you encounter any problems refer to the code in the program file,
if the problem still persist then create a issue or use Google/Stack Overlflow for help.
4. Done! You have successfully created the program in C by your own.
Note: All the exe files are provided to make sure the program code runs when I create them (Tested on Windows 10).
## [License](https://github.com/psavarmattas/C-Projects/blob/master/LICENSE):
Copyright (c) 2021 PSMForums. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
|
a9d59c8d4cbc18e03268ebb3dc29b5fdcae18ca5
|
{
"blob_id": "a9d59c8d4cbc18e03268ebb3dc29b5fdcae18ca5",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-17T04:54:31",
"content_id": "115e38ee35a3c3083b43c528f67fc00affcd417f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "eec76bb687da1619b92b9f1fb301de53a9b9c790",
"extension": "md",
"filename": "README.md",
"fork_events_count": 1,
"gha_created_at": "2021-04-25T09:59:20",
"gha_event_created_at": "2021-06-23T23:53:06",
"gha_language": "C",
"gha_license_id": "Apache-2.0",
"github_id": 361391591,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1707,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/README.md",
"provenance": "stack-edu-markdown-0006.json.gz:239274",
"repo_name": "psavarmattas/C-Projects",
"revision_date": "2021-06-17T04:54:31",
"revision_id": "335cdc752051f73868464df9e41ddffbc866be18",
"snapshot_id": "ebd860a4b8226d7492e86c8094b1382a94529b4d",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/psavarmattas/C-Projects/335cdc752051f73868464df9e41ddffbc866be18/README.md",
"visit_date": "2023-06-02T12:12:07.612597",
"added": "2024-11-19T00:40:53.836516+00:00",
"created": "2021-06-17T04:54:31",
"int_score": 3,
"score": 2.765625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0006.json.gz"
}
|
""" Responsável por formatar as menssagens e enviar """
import logging
from telegram import Bot
from score_bing.team import Team # type: ignore
logger = logging.getLogger(__name__)
SOCCER_BALL: str = "\U000026BD"
CORNER: str = "\U000026F3"
class Message:
def __init__(
self,
major: Team,
minor: Team,
message_type: str,
league: str,
status: str,
bot: Bot,
) -> None:
_types: dict = {
"corners": "Oportunidades em escanteios",
"goals": "Oportunidades em gol",
}
self.major = major
self.minor = minor
self.message_type = _types[message_type]
self.league = league
self.status = status
self.bot = bot
@property
def mount_message(self) -> str:
message: str = f"""
<b>{self.message_type}: {self.major.name}</b>
Liga: {self.league}
{self.major.name} {self.major.goals} x {self.minor.goals} {self.minor.name}
{self.major.danger_attack} ataques perigosos em {self.status} minútos.
{self.major.on_target} chutes a gol {SOCCER_BALL}
{self.major.off_target} chutes fora {SOCCER_BALL}
{self.major.corners} cantos (escanteios) {CORNER}
Posse de bola {self.major.possession}% x {self.minor.possession}%
APM: {self.major.apm: .2f}
chance de gol: {self.major.opportunity_goals}
"""
return message
def send(self, chat_id: str) -> None:
logger.info(f"Menssagem do tipo {self.message_type}.")
self.bot.send_message(
chat_id=chat_id, text=self.mount_message, parse_mode="HTML"
)
|
08ecec7335fc9865ed7f3ecc80c2f24e176e86ca
|
{
"blob_id": "08ecec7335fc9865ed7f3ecc80c2f24e176e86ca",
"branch_name": "refs/heads/main",
"committer_date": "2021-05-17T14:35:34",
"content_id": "846436d21a779333089a369e5fcdd0a7fefd7e86",
"detected_licenses": [
"MIT"
],
"directory_id": "8b223cabccdec3ef4ba4843de8f7ff77ae589ffb",
"extension": "py",
"filename": "message.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1635,
"license": "MIT",
"license_type": "permissive",
"path": "/score_bing/message.py",
"provenance": "stack-edu-0060.json.gz:522945",
"repo_name": "HSSANT/Bot-apostas",
"revision_date": "2021-05-17T14:35:34",
"revision_id": "dd8cbbca1cd9754899264dd6a9500ae5cf751d66",
"snapshot_id": "828cd9e3963f2768416e51cff64c67fcfac57a78",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/HSSANT/Bot-apostas/dd8cbbca1cd9754899264dd6a9500ae5cf751d66/score_bing/message.py",
"visit_date": "2023-04-28T19:26:32.684528",
"added": "2024-11-19T03:10:34.277511+00:00",
"created": "2021-05-17T14:35:34",
"int_score": 3,
"score": 2.9375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0078.json.gz"
}
|
import React, { Component } from "react";
import {
Form,
Icon,
Input,
Button,
Checkbox,
Select,
Row,
Col,
Card,
notification
} from "antd";
import { inject, observer } from "mobx-react";
const FormItem = Form.Item;
const electron = window.require("electron");
const { ipcRenderer } = electron;
const { Option } = Select;
@inject("myStore")
@observer
class NormalLoginForm extends Component {
componentDidMount() {
ipcRenderer.send("getWatchList");
ipcRenderer.on("response::getWatchList", (event, data) => {
this.props.myStore.series = data;
});
ipcRenderer.on("response::checkUserPassword", (event, data) => {
if (data.access) this.props.myStore.isLoggedIn = true;
});
}
componentWillUnmount() {
ipcRenderer.removeAllListeners("response::getWatchList");
ipcRenderer.removeAllListeners("response::checkUserPassword");
}
handleSubmit = e => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
console.log("Received values of form: ", values);
const { password } = values;
if (values.password) {
ipcRenderer.send("setUserPassword", { password });
}
notification.success({
message: "Success"
});
}
});
};
render() {
const { getFieldDecorator } = this.props.form;
return (
<Row type="flex" justify="center">
<Col span="24" lg={{ span: 8 }} md={{ span: 12 }}>
<Card title="Change Password">
<Form onSubmit={this.handleSubmit}>
<FormItem>
{getFieldDecorator("password")(
<Input
prefix={
<Icon type="lock" style={{ color: "rgba(0,0,0,.25)" }} />
}
type="password"
placeholder="Type New Password"
/>
)}
</FormItem>
<FormItem>
<Button type="primary" htmlType="submit">
Change Password
</Button>
</FormItem>
</Form>
</Card>
</Col>
</Row>
);
}
}
export default Form.create()(NormalLoginForm);
|
7c37b154d63100f2f8c7f48525ff841c87b96b7c
|
{
"blob_id": "7c37b154d63100f2f8c7f48525ff841c87b96b7c",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-21T07:32:13",
"content_id": "51e10e642d6f17617dfd4ec0cd011fe3e8be177d",
"detected_licenses": [
"MIT"
],
"directory_id": "bf364ad9f1d914467381d0c71cbe93eb58923734",
"extension": "jsx",
"filename": "Settings.jsx",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 126205991,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2246,
"license": "MIT",
"license_type": "permissive",
"path": "/src/components/Settings.jsx",
"provenance": "stack-edu-0045.json.gz:124376",
"repo_name": "rednithin/Slyther",
"revision_date": "2018-05-21T07:32:13",
"revision_id": "2ddd348adb80f74160f883fe7a5b053e7d3882f2",
"snapshot_id": "95e1f17d4846ef13d0bf0d510765026469bad996",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rednithin/Slyther/2ddd348adb80f74160f883fe7a5b053e7d3882f2/src/components/Settings.jsx",
"visit_date": "2021-04-15T08:23:14.877690",
"added": "2024-11-18T23:52:50.809445+00:00",
"created": "2018-05-21T07:32:13",
"int_score": 2,
"score": 2.328125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0063.json.gz"
}
|
<?php
use Migrations\AbstractMigration;
class AddTagCountToScenes extends AbstractMigration
{
/**
* Change Method.
*
* More information on this method is available here:
* http://docs.phinx.org/en/latest/migrations.html#the-change-method
* @return void
*/
public function up()
{
$tagsTable = $this->table('tags');
if ($tagsTable->exists()) {
$tagsTable->drop();
}
$taggedTable = $this->table('tagged');
if ($taggedTable->exists()) {
$taggedTable->drop();
}
$table = $this->table('scenes');
$table->addColumn('tag_count', 'integer', [
'signed' => false,
'null' => false,
'default' => 0
]);
$table->update();
}
public function down()
{
$table = $this->table('scenes');
$table->removeColumn('tag_count');
$table->update();
}
}
|
ee78d83e5918b4098d705194ee8c8c458ebd1fe9
|
{
"blob_id": "ee78d83e5918b4098d705194ee8c8c458ebd1fe9",
"branch_name": "refs/heads/master",
"committer_date": "2021-12-26T20:03:47",
"content_id": "a56a5d941606af8fe1b30ebfb3b6e2540f302325",
"detected_licenses": [
"MIT"
],
"directory_id": "83e3b5b7a2c07f5096b6552137a2a16336c22031",
"extension": "php",
"filename": "20180417160019_AddTagCountToScenes.php",
"fork_events_count": 1,
"gha_created_at": "2013-11-18T03:40:21",
"gha_event_created_at": "2021-12-26T20:09:43",
"gha_language": "PHP",
"gha_license_id": "MIT",
"github_id": 14481918,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 950,
"license": "MIT",
"license_type": "permissive",
"path": "/config/Migrations/20180417160019_AddTagCountToScenes.php",
"provenance": "stack-edu-0052.json.gz:318401",
"repo_name": "JeffVandenberg/wantonwicked",
"revision_date": "2021-12-26T20:03:47",
"revision_id": "e0eec4623da9da2fcabd4c83f5b99be0cd635e1a",
"snapshot_id": "bbff7d8bd91637b05903c258b9a4d11555fecefb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/JeffVandenberg/wantonwicked/e0eec4623da9da2fcabd4c83f5b99be0cd635e1a/config/Migrations/20180417160019_AddTagCountToScenes.php",
"visit_date": "2021-12-28T22:48:00.172123",
"added": "2024-11-18T19:44:01.835198+00:00",
"created": "2021-12-26T20:03:47",
"int_score": 3,
"score": 2.671875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz"
}
|
#include <iostream>
#include <windows.h>
#include <ddraw.h>
#include <paths.h>
int main(int argc, char ** argv)
{
using DirectDrawCreateType = HRESULT WINAPI __stdcall (*)(GUID FAR * lpGuid, LPDIRECTDRAW * lplpDD, IUnknown FAR * pUnkOuter);
HMODULE hdll;
DirectDrawCreateType directDrawCreate;
hdll = LoadLibrary(argc > 1 ? argv[1] : DDRAW_DEFAULT_PATH);
if (hdll == nullptr)
{
std::cout << "LoadLibrary() failed.\n";
return 6;
}
directDrawCreate = reinterpret_cast<DirectDrawCreateType>(GetProcAddress(hdll, "DirectDrawCreate"));
if (directDrawCreate == nullptr)
{
std::cout << "GetProcAddress() failed.\n";
return 7;
}
IDirectDraw * dd;
HRESULT result = directDrawCreate(nullptr, &dd, nullptr);
if (result != DD_OK)
{
std::cout << "DirectDrawCreate() failed.\n";
return 1;
}
DDSURFACEDESC DDSurfaceDesc = { 0 };
DDSurfaceDesc.dwSize = sizeof(DDSurfaceDesc);
DDSurfaceDesc.dwFlags = DDSD_CAPS;
DDSurfaceDesc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
LPDIRECTDRAWSURFACE dds = nullptr;
HWND hwnd = GetConsoleWindow();
result = dd->SetCooperativeLevel(hwnd, DDSCL_NORMAL);
if (result != DD_OK)
{
std::cout << "SetCooperativeLevel() failed.\n";
return 2;
}
result = dd->CreateSurface(&DDSurfaceDesc, &dds, nullptr);
if (result != DD_OK)
{
std::cout << "CreateSurface() failed.\n";
return 3;
}
result = dds->Lock(nullptr, &DDSurfaceDesc, 0, nullptr);
if (result != DD_OK)
{
std::cout << "Lock() failed.\n";
return 4;
}
result = dds->Unlock(DDSurfaceDesc.lpSurface);
if (result != DD_OK)
{
std::cout << "Unlock() failed.\n";
return 5;
}
ULONG ref_count = dds->Release();
if (ref_count != 0)
{
std::cout << "DirectDrawSurface::Release() failed.\n";
return 8;
}
ref_count = dd->Release();
if (ref_count != 0)
{
std::cout << "DirectDraw::Release() failed.\n";
return 9;
}
/// Won't call FreeLibrary().
return 0;
}
|
15ea52b9f33f35ed893a34909bba1a6cee3657a9
|
{
"blob_id": "15ea52b9f33f35ed893a34909bba1a6cee3657a9",
"branch_name": "refs/heads/master",
"committer_date": "2018-12-23T14:51:38",
"content_id": "e781f5e47c6b01f20f7f8fd2595a5af54ac958bc",
"detected_licenses": [
"MIT"
],
"directory_id": "c8cf18a0e4011bd6a879bdbe29ae73168a847bbf",
"extension": "cpp",
"filename": "simple.cpp",
"fork_events_count": 3,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 108602438,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2146,
"license": "MIT",
"license_type": "permissive",
"path": "/src/tests/simple.cpp",
"provenance": "stack-edu-0003.json.gz:21570",
"repo_name": "excitoon/ddraw",
"revision_date": "2018-12-23T14:51:38",
"revision_id": "d6c3e214cbb262e1720a37b5f28f26318181274d",
"snapshot_id": "ab07f7cac8daa0ddc5f65a2d3740e0faa630f160",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/excitoon/ddraw/d6c3e214cbb262e1720a37b5f28f26318181274d/src/tests/simple.cpp",
"visit_date": "2021-10-09T07:14:21.118002",
"added": "2024-11-18T23:31:07.585545+00:00",
"created": "2018-12-23T14:51:38",
"int_score": 2,
"score": 2.46875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0021.json.gz"
}
|
using BenchmarkDotNet.Plugins;
using BenchmarkDotNet.Plugins.Loggers;
using BenchmarkDotNet.Tasks;
using System;
using Xunit;
namespace BenchmarkDotNet.IntegrationTests
{
// See https://github.com/PerfDotNet/BenchmarkDotNet/issues/55
// https://github.com/PerfDotNet/BenchmarkDotNet/issues/59 is also related
public class InnerClassTest
{
[Fact]
public void Test()
{
var logger = new BenchmarkAccumulationLogger();
var plugins = BenchmarkPluginBuilder.CreateDefault().AddLogger(logger).Build();
var reports = new BenchmarkRunner(plugins).Run<InnerClassTest>();
var testLog = logger.GetLog();
Assert.Contains("// ### BenchmarkInnerClass method called ###" + Environment.NewLine, testLog);
Assert.Contains("// ### BenchmarkGenericInnerClass method called ###" + Environment.NewLine, testLog);
Assert.DoesNotContain("No benchmarks found", logger.GetLog());
}
[Benchmark]
[BenchmarkTask(mode: BenchmarkMode.SingleRun, processCount: 1, warmupIterationCount: 1, targetIterationCount: 1)]
public Tuple<Outer, Outer.Inner> BenchmarkInnerClass()
{
Console.WriteLine("// ### BenchmarkInnerClass method called ###");
return Tuple.Create(new Outer(), new Outer.Inner());
}
[Benchmark]
[BenchmarkTask(mode: BenchmarkMode.SingleRun, processCount: 1, warmupIterationCount: 1, targetIterationCount: 1)]
public Tuple<Outer, Outer.InnerGeneric<string>> BenchmarkGenericInnerClass()
{
Console.WriteLine("// ### BenchmarkGenericInnerClass method called ###");
return Tuple.Create(new Outer(), new Outer.InnerGeneric<string>());
}
}
public class Outer
{
public class Inner
{
}
public class InnerGeneric<T>
{
}
}
}
|
f56e4e4a535160094198dbce91818e79c6eecfa3
|
{
"blob_id": "f56e4e4a535160094198dbce91818e79c6eecfa3",
"branch_name": "refs/heads/master",
"committer_date": "2016-01-08T12:13:18",
"content_id": "e459a4433b8db141df97d4f41a0e72dc622bc6de",
"detected_licenses": [
"MIT"
],
"directory_id": "50256c6a08bb1996dea9d7aa1ae7710c829a11ac",
"extension": "cs",
"filename": "InnerClassTest.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1925,
"license": "MIT",
"license_type": "permissive",
"path": "/BenchmarkDotNet.IntegrationTests/InnerClassTest.cs",
"provenance": "stack-edu-0012.json.gz:879393",
"repo_name": "ActivePHOENiX/BenchmarkDotNet",
"revision_date": "2016-01-08T12:13:18",
"revision_id": "719391f9930896f2eda43a96372245bcee023d2d",
"snapshot_id": "28c70947f823d40ddcc4e2727780c8dc8a43305e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ActivePHOENiX/BenchmarkDotNet/719391f9930896f2eda43a96372245bcee023d2d/BenchmarkDotNet.IntegrationTests/InnerClassTest.cs",
"visit_date": "2021-01-12T22:39:32.528183",
"added": "2024-11-19T00:59:14.284951+00:00",
"created": "2016-01-08T12:13:18",
"int_score": 2,
"score": 2.28125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0030.json.gz"
}
|
(function () {
'use strict';
var app = angular.module('Fablab');
app.factory('UserService', function ($log, $resource, $http) {
var User = $resource(App.API.USER_API + "/:id", {id: '@id'});
var getData = function(successFn){
return function(response){
successFn(response.data);
}
};
return {
updatePassword: function (user, successFn) {
$http({
method: 'POST',
url: App.API.USER_API + "/password",
data: user
}).then(getData(successFn));
},
list: function (successFn) {
$http({
method: 'GET',
url: App.API.USER_API,
}).then(getData(successFn));
},
remove: function (id, successFn) {
User.remove({id: id}, successFn);
},
save: function (user, successFn, errorFn) {
var saved = User.save(user, successFn, errorFn);
return saved;
},
get: function (id, successFn) {
var prj = User.get({id: id}, successFn);
return prj;
},
updateMailingList: function (successFn) {
$http({
method: 'GET',
url: App.API.USER_API + "/updateMailingList",
}).then(getData(successFn));
},
membershipTypeList: function (successFn) {
$http({
method: 'GET',
url: App.API.USER_API + "/membershipType",
}).then(getData(successFn));
}
};
});
app.factory('GroupService', function ($log, $resource, $http) {
var Group = $resource(App.API.GROUP_API + "/:id", {id: '@id'});
var getData = function(successFn){
return function(response){
successFn(response.data);
}
};
return {
list: function (successFn) {
$http(
{
method: 'GET',
url: App.API.GROUP_API,
}
).then(getData(successFn));
},
// remove: function (id, successFn) {
// $log.debug("UserService: remove...");
// User.remove({id: id}, successFn);
// $log.debug("UserService: remove done.");
// },
// save: function (user, successFn, errorFn) {
// $log.debug("UserService: save...");
// var saved = User.save(user, successFn, errorFn);
// $log.debug("UserService: save done.");
// return saved;
// },
// get: function (id, successFn) {
// $log.debug("UserService: get...");
// var prj = User.get({id: id}, successFn);
// $log.debug("UserService: get done.");
// return prj;
// },
};
});
}());
|
5326a73cc31c80015c7874d6659866bb7b9904e5
|
{
"blob_id": "5326a73cc31c80015c7874d6659866bb7b9904e5",
"branch_name": "refs/heads/develop",
"committer_date": "2020-01-02T15:28:30",
"content_id": "e67b9c43eaf787f41fa5bb9ae1a993c94728fdbb",
"detected_licenses": [
"MIT"
],
"directory_id": "8ca2fecb8a00cf6123f6aa50f40dc429dc6c5c45",
"extension": "js",
"filename": "user-service.js",
"fork_events_count": 8,
"gha_created_at": "2014-10-23T17:38:39",
"gha_event_created_at": "2020-06-18T14:33:50",
"gha_language": "Java",
"gha_license_id": "MIT",
"github_id": 25649580,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2305,
"license": "MIT",
"license_type": "permissive",
"path": "/src/main/webapp/components/services/user-service.js",
"provenance": "stack-edu-0032.json.gz:774818",
"repo_name": "gaetancollaud/fablab-manager",
"revision_date": "2020-01-02T15:28:30",
"revision_id": "570e8f58f29e89f668b2a4dde652937a0d41e59d",
"snapshot_id": "b877a30f5194fb4ce46fc231927d7ec989833ed0",
"src_encoding": "UTF-8",
"star_events_count": 19,
"url": "https://raw.githubusercontent.com/gaetancollaud/fablab-manager/570e8f58f29e89f668b2a4dde652937a0d41e59d/src/main/webapp/components/services/user-service.js",
"visit_date": "2021-01-17T01:07:11.832530",
"added": "2024-11-19T01:55:32.586285+00:00",
"created": "2020-01-02T15:28:30",
"int_score": 2,
"score": 2.3125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0050.json.gz"
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using BookFast.Business.Data;
using BookFast.Data.Commands;
using BookFast.Data.Models;
using BookFast.Data.Queries;
using Accommodation = BookFast.Contracts.Models.Accommodation;
namespace BookFast.Data
{
internal class AccommodationDataSource : IAccommodationDataSource
{
private readonly BookFastContext context;
private readonly IAccommodationMapper mapper;
public AccommodationDataSource(BookFastContext context, IAccommodationMapper mapper)
{
this.context = context;
this.mapper = mapper;
}
public Task<List<Accommodation>> ListAsync(Guid facilityId)
{
var query = new ListAccommodationsQuery(facilityId, mapper);
return query.ExecuteAsync(context);
}
public Task<Accommodation> FindAsync(Guid accommodationId)
{
var query = new FindAccommodationQuery(accommodationId, mapper);
return query.ExecuteAsync(context);
}
public Task CreateAsync(Accommodation accommodation)
{
var command = new CreateAccommodationCommand(accommodation, mapper);
return command.ApplyAsync(context);
}
public Task UpdateAsync(Accommodation accommodation)
{
var command = new UpdateAccommodationCommand(accommodation, mapper);
return command.ApplyAsync(context);
}
public Task DeleteAsync(Guid accommodationId)
{
var command = new DeleteAccommodationCommand(accommodationId);
return command.ApplyAsync(context);
}
public Task<bool> ExistsAsync(Guid accommodationId)
{
var query = new DoesAccommodationExistQuery(accommodationId);
return query.ExecuteAsync(context);
}
}
}
|
708e24fbf1c60d6e13801ec30d68400da8f666d0
|
{
"blob_id": "708e24fbf1c60d6e13801ec30d68400da8f666d0",
"branch_name": "refs/heads/master",
"committer_date": "2016-08-10T18:26:00",
"content_id": "ae5d9027558c3c9195edbf7dc541807d4ed6380d",
"detected_licenses": [
"MIT"
],
"directory_id": "dcb32962e573bae4aa2c2c5b961d9b304a09ede1",
"extension": "cs",
"filename": "AccommodationDataSource.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 1905,
"license": "MIT",
"license_type": "permissive",
"path": "/src/BookFast.Data/AccommodationDataSource.cs",
"provenance": "stack-edu-0009.json.gz:527439",
"repo_name": "texervn/book-fast-api",
"revision_date": "2016-08-10T18:26:00",
"revision_id": "2f20df8e1fb663c3913c33973fedd1526d00326d",
"snapshot_id": "56c9be4da313bfcf3d74b2312a022b22fabc73cc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/texervn/book-fast-api/2f20df8e1fb663c3913c33973fedd1526d00326d/src/BookFast.Data/AccommodationDataSource.cs",
"visit_date": "2021-06-03T15:00:03.089332",
"added": "2024-11-19T02:39:48.937595+00:00",
"created": "2016-08-10T18:26:00",
"int_score": 2,
"score": 2.484375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0027.json.gz"
}
|
//
// media_type.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2011 Steven Siloti ([email protected])
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef HTTP_MEDIA_TYPE_HPP
#define HTTP_MEDIA_TYPE_HPP
#include <boost/fusion/include/adapt_struct.hpp>
#include <string>
#include <map>
namespace http {
typedef std::map<std::string, std::string> parameters_t;
struct media_type
{
void clear()
{
type.clear();
subtype.clear();
parameters.clear();
}
media_type() {}
media_type(const std::string& type, const std::string& subtype)
: type(type), subtype(subtype)
{}
inline media_type& operator=(const std::string&);
std::string type, subtype;
parameters_t parameters;
};
}
BOOST_FUSION_ADAPT_STRUCT(
http::media_type,
(std::string, type)
(std::string, subtype)
(http::parameters_t, parameters)
)
#endif
|
028c492442573c1e640623ea3fb5bf9079da1e61
|
{
"blob_id": "028c492442573c1e640623ea3fb5bf9079da1e61",
"branch_name": "refs/heads/master",
"committer_date": "2011-11-07T19:29:22",
"content_id": "8e141f0c4e0c3c6c49a21172f8dda29e793d00e8",
"detected_licenses": [
"BSL-1.0"
],
"directory_id": "cb621dee2a0f09a9a2d5d14ffaac7df0cad666a0",
"extension": "hpp",
"filename": "media_type.hpp",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 1021325,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1064,
"license": "BSL-1.0",
"license_type": "permissive",
"path": "/http/media_type.hpp",
"provenance": "stack-edu-0007.json.gz:626833",
"repo_name": "ssiloti/http",
"revision_date": "2011-11-07T19:29:22",
"revision_id": "9cdeaa5cf2ef2848238c6e4c499ebf80e136ba7e",
"snapshot_id": "a15fb43c94c823779f11fb02e147f023ca77c932",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ssiloti/http/9cdeaa5cf2ef2848238c6e4c499ebf80e136ba7e/http/media_type.hpp",
"visit_date": "2021-01-01T19:10:36.886248",
"added": "2024-11-18T23:24:59.626543+00:00",
"created": "2011-11-07T19:29:22",
"int_score": 2,
"score": 2.3125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0025.json.gz"
}
|
import * as commentsParser from '../scripts/finderParser/commentsParser';
describe('parsing of comments', () => {
let sections;
let createdTestSection;
beforeEach(() => {
sections = {
level: 0
};
});
describe('a single line comment', () => {
beforeEach(() => {
const minimalComment = {
comment: '/* Just a Comment */',
srcPath: 'doesNotExist/pathIsJustForTesting'
};
createdTestSection = commentsParser.getSectionObjectOfComment(minimalComment, sections);
});
it('should be ignored', () => {
expect(createdTestSection).toBe(-1);
});
});
describe('a minimal comment', () => {
beforeEach(() => {
const minimalComment = {
comment: '/*\nTitle \nStyleguide testSection \n*/',
srcPath: 'doesNotExist/pathIsJustForTesting'
};
createdTestSection = commentsParser.getSectionObjectOfComment(minimalComment, sections);
});
it('should create a section object', () => {
expect(createdTestSection).not.toEqual(-1);
});
it('should have a title', () => {
expect(createdTestSection.sectionTitle).toEqual('Title');
});
it('should have a sectionName', () => {
expect(createdTestSection.sectionName).toEqual('testsection');
});
it('should have a srcPath', () => {
expect(createdTestSection.srcPath).toEqual('doesNotExist/pathIsJustForTesting');
});
});
describe('a comment with description', () => {
beforeEach(() => {
const commentWithDescription = {
comment: '/*\nTitle\nA Test Description \nStyleguide testSection \n*/',
srcPath: 'doesNotExist/pathIsJustForTesting'
};
createdTestSection = commentsParser.getSectionObjectOfComment(commentWithDescription, sections);
});
it('should have a title', () => {
expect(createdTestSection.sectionTitle).toEqual('Title');
});
it('should have a sectionName', () => {
expect(createdTestSection.sectionName).toEqual('testsection');
});
it('should have a description', () => {
expect(createdTestSection.description).toEqual('A Test Description');
});
});
describe('a comment with multi line description', () => {
beforeEach(() => {
const commentWithDescription = {
comment: '/*\nTitle\nA Test Description\nDescription Line 2\nLine 3 \nStyleguide testSection \n*/',
srcPath: 'doesNotExist/pathIsJustForTesting'
};
createdTestSection = commentsParser.getSectionObjectOfComment(commentWithDescription, sections);
});
it('should have a multi line description', () => {
expect(createdTestSection.description).toEqual('A Test Description \nDescription Line 2 \nLine 3');
});
});
describe('a comment with hbs file as markup', () => {
beforeEach(() => {
const commentWithDescription = {
comment: '/*\nTitle\nA Test Description\nDescription Line 2\nLine 3\nMarkup: test.hbs\nStyleguide testSection \n*/',
srcPath: 'doesNotExist/pathIsJustForTesting'
};
createdTestSection = commentsParser.getSectionObjectOfComment(commentWithDescription, sections);
});
it('should have a title', () => {
expect(createdTestSection.sectionTitle).toEqual('Title');
});
it('should have a multi line description', () => {
expect(createdTestSection.description).toEqual('A Test Description \nDescription Line 2 \nLine 3');
});
it('should have a markup', () => {
expect(createdTestSection.markup).toEqual('test.hbs');
});
});
describe('a comment with multiline html as markup', () => {
beforeEach(() => {
const commentWithDescription = {
comment: '/*\nTitle\nA Test Description\nDescription Line 2\nLine 3\nMarkup: <div><p>first line</p>\n<span>second line</span></div>\nStyleguide testSection \n*/',
srcPath: 'doesNotExist/pathIsJustForTesting'
};
createdTestSection = commentsParser.getSectionObjectOfComment(commentWithDescription, sections);
});
it('should have a title', () => {
expect(createdTestSection.sectionTitle).toEqual('Title');
});
it('should have a multi line description', () => {
expect(createdTestSection.description).toEqual('A Test Description \nDescription Line 2 \nLine 3');
});
it('should have a markup', () => {
expect(createdTestSection.markup).toEqual('<div><p>first line</p>\n<span>second line</span></div>');
});
});
describe('a comment with one variation class', () => {
beforeEach(() => {
const commentWithDescription = {
comment: '/*\nTitle\nA Test Description\nDescription Line 2\nLine 3\nMarkup: test.hbs\n\n.test-class - Variation Description \nStyleguide testSection \n*/',
srcPath: 'doesNotExist/pathIsJustForTesting'
};
createdTestSection = commentsParser.getSectionObjectOfComment(commentWithDescription, sections);
});
it('should have a title', () => {
expect(createdTestSection.sectionTitle).toEqual('Title');
});
it('should have a sectionName', () => {
expect(createdTestSection.sectionName).toEqual('testsection');
});
it('should have a multi line description', () => {
expect(createdTestSection.description).toEqual('A Test Description \nDescription Line 2 \nLine 3');
});
it('should have a markup', () => {
expect(createdTestSection.markup).toEqual('test.hbs');
});
it('should have a variation', () => {
expect(createdTestSection.variations).toEqual([{
variationName: '.test-class',
variationDescription: 'Variation Description',
variationClass: ['test-class']
}]);
});
});
describe('a comment with multiple variation classes', () => {
beforeEach(() => {
const commentWithDescription = {
comment: '/*\nTitle\nA Test Description\nDescription Line 2\nLine 3\nMarkup: test.hbs\n.test-class - Variation Description\n.test-class2.test-class--modifier - Variation Description2 \nStyleguide testSection \n*/',
srcPath: 'doesNotExist/pathIsJustForTesting'
};
createdTestSection = commentsParser.getSectionObjectOfComment(commentWithDescription, sections);
});
it('should have a title', () => {
expect(createdTestSection.sectionTitle).toEqual('Title');
});
it('should have a sectionName', () => {
expect(createdTestSection.sectionName).toEqual('testsection');
});
it('should have a multi line description', () => {
expect(createdTestSection.description).toEqual('A Test Description \nDescription Line 2 \nLine 3');
});
it('should have a markup', () => {
expect(createdTestSection.markup).toEqual('test.hbs');
});
it('should have variations', () => {
expect(createdTestSection.variations).toEqual([
{
variationName: '.test-class',
variationDescription: 'Variation Description',
variationClass: ['test-class']
},
{
variationName: '.test-class2.test-class--modifier',
variationDescription: 'Variation Description2',
variationClass: ['test-class2', 'test-class--modifier']
}
]);
});
});
describe('a comment with variation classes and states (hover, focus) in one line', () => {
beforeEach(() => {
const commentWithDescription = {
comment: '/*\nTitle\nA Test Description\nDescription Line 2\nLine 3\nMarkup: test.hbs\n\n.test-class2.test-class--modifier - Variation Description2\n:focus.test-class3 - focusState \n.test-class2.test-class--modifier:active - Variation Description2 \nStyleguide testSection \n*/',
srcPath: 'doesNotExist/pathIsJustForTesting'
};
createdTestSection = commentsParser.getSectionObjectOfComment(commentWithDescription, sections);
});
it('should have a title', () => {
expect(createdTestSection.sectionTitle).toEqual('Title');
});
it('should have a sectionName', () => {
expect(createdTestSection.sectionName).toEqual('testsection');
});
it('should have a multi line description', () => {
expect(createdTestSection.description).toEqual('A Test Description \nDescription Line 2 \nLine 3');
});
it('should have a markup', () => {
expect(createdTestSection.markup).toEqual('test.hbs');
});
it('should have variations with states', () => {
expect(createdTestSection.variations).toEqual([
{
variationName: '.test-class2.test-class--modifier',
variationDescription: 'Variation Description2',
variationClass: ['test-class2', 'test-class--modifier']
},
{
variationName: ':focus.test-class3',
variationDescription: 'focusState',
variationClass: ['pseudo-class-focus', 'test-class3']
},
{
variationName: '.test-class2.test-class--modifier:active',
variationDescription: 'Variation Description2',
variationClass: ['test-class2', 'test-class--modifier', 'pseudo-class-active']
}
]);
});
});
describe('a comment with one variation and variation classes with states (hover, focus) in one line', () => {
beforeEach(() => {
const commentWithDescription = {
comment: '/*\nTitle\nA Test Description\nDescription Line 2\nLine 3\nMarkup: test.hbs\n\n.test-class - Variation Description\n:hover - hoverState\n.test-class2.test-class--modifier - Variation Description2\n:focus.test-class3 - focusState \n.test-class2.test-class--modifier:active - Variation Description2 \nStyleguide testSection \n*/',
srcPath: 'doesNotExist/pathIsJustForTesting'
};
createdTestSection = commentsParser.getSectionObjectOfComment(commentWithDescription, sections);
});
it('should have a title', () => {
expect(createdTestSection.sectionTitle).toEqual('Title');
});
it('should have a sectionName', () => {
expect(createdTestSection.sectionName).toEqual('testsection');
});
it('should have a multi line description', () => {
expect(createdTestSection.description).toEqual('A Test Description \nDescription Line 2 \nLine 3');
});
it('should have a markup', () => {
expect(createdTestSection.markup).toEqual('test.hbs');
});
it('should have variations with states', () => {
expect(createdTestSection.variations).toEqual([
{ variationName: '.test-class', variationDescription: 'Variation Description', variationClass: ['test-class'] },
{ variationName: ':hover', variationDescription: 'hoverState', variationClass: ['pseudo-class-hover'] },
{
variationName: '.test-class2.test-class--modifier',
variationDescription: 'Variation Description2',
variationClass: ['test-class2', 'test-class--modifier']
},
{
variationName: ':focus.test-class3',
variationDescription: 'focusState',
variationClass: ['pseudo-class-focus', 'test-class3']
},
{
variationName: '.test-class2.test-class--modifier:active',
variationDescription: 'Variation Description2',
variationClass: ['test-class2', 'test-class--modifier', 'pseudo-class-active']
}
]);
});
});
describe('a comment with one variation consists of classes and state', () => {
beforeEach(() => {
const commentWithDescription = {
comment: '/*\nTitle\nA Test Description\nDescription Line 2\nLine 3\nMarkup: test.hbs\n\n.test-class.test-class2:hover - Variation Description \n\n:hover - hoverState\n:focus - focusState \nStyleguide testSection \n*/',
srcPath: 'doesNotExist/pathIsJustForTesting'
};
createdTestSection = commentsParser.getSectionObjectOfComment(commentWithDescription, sections);
});
it('should have a title', () => {
expect(createdTestSection.sectionTitle).toEqual('Title');
});
it('should have a sectionName', () => {
expect(createdTestSection.sectionName).toEqual('testsection');
});
it('should have a multi line description', () => {
expect(createdTestSection.description).toEqual('A Test Description \nDescription Line 2 \nLine 3');
});
it('should have a markup', () => {
expect(createdTestSection.markup).toEqual('test.hbs');
});
it('should have variations with states', () => {
expect(createdTestSection.variations).toEqual([{
variationName: '.test-class.test-class2:hover',
variationDescription: 'Variation Description',
variationClass: ['test-class', 'test-class2', 'pseudo-class-hover']
}, {
variationClass: ['pseudo-class-hover'],
variationDescription: 'hoverState',
variationName: ':hover'
}, {
variationClass: ['pseudo-class-focus'],
variationDescription: 'focusState',
variationName: ':focus'
}
]);
});
});
describe('a comment with property wrapper-classes', () => {
beforeEach(() => {
const commentWithDescription = {
comment: '/*\nTitle\nA Test Description\n\n\nMarkup: test.hbs\n\nwrapper-classes: background-dark \n\n\nStyleguide testSection \n*/',
srcPath: 'doesNotExist/pathIsJustForTesting'
};
createdTestSection = commentsParser.getSectionObjectOfComment(commentWithDescription, sections);
});
it('should have a title', () => {
expect(createdTestSection.sectionTitle).toEqual('Title');
});
it('should have a sectionName', () => {
expect(createdTestSection.sectionName).toEqual('testsection');
});
it('should have a description', () => {
expect(createdTestSection.description).toEqual('A Test Description');
});
it('should have a markup', () => {
expect(createdTestSection.markup).toEqual('test.hbs');
});
it('should have a property wrapper-classes', () => {
expect(createdTestSection.properties).toEqual(
{
'wrapper-classes': ['background-dark']
}
);
});
});
describe('a comment with multiple property', () => {
beforeEach(() => {
const commentWithDescription = {
comment: '/*\nTitle\nA Test Description\n\n\nMarkup: test.hbs\n\nwrapper-classes: background-dark, min-height , overflow \nWeight: -12 \n\n\nStyleguide testSection \n*/',
srcPath: 'doesNotExist/pathIsJustForTesting'
};
createdTestSection = commentsParser.getSectionObjectOfComment(commentWithDescription, sections);
});
it('should have a title', () => {
expect(createdTestSection.sectionTitle).toEqual('Title');
});
it('should have a sectionName', () => {
expect(createdTestSection.sectionName).toEqual('testsection');
});
it('should have a description', () => {
expect(createdTestSection.description).toEqual('A Test Description');
});
it('should have a markup', () => {
expect(createdTestSection.markup).toEqual('test.hbs');
});
it('should have properties', () => {
expect(createdTestSection.properties).toEqual(
{
'wrapper-classes': ['background-dark', 'min-height', 'overflow'],
'weight': ['-12']
}
);
});
});
describe('a comment with markup, variations, states and properties', () => {
beforeEach(() => {
const commentWithDescription = {
comment: '/*\nTitle\nA Test Description\n\n\nMarkup: test.hbs\n.test-class - Variation Description\n.test-class2 - Variation Description2\n:hover - hoverState\n:focus - focusState \n\nwrapper-classes: background-dark, min-height , overflow \nWeight: -12 \n\n\nStyleguide testSection \n*/',
srcPath: 'doesNotExist/pathIsJustForTesting'
};
createdTestSection = commentsParser.getSectionObjectOfComment(commentWithDescription, sections);
});
it('should have a title', () => {
expect(createdTestSection.sectionTitle).toEqual('Title');
});
it('should have a sectionName', () => {
expect(createdTestSection.sectionName).toEqual('testsection');
});
it('should have a description', () => {
expect(createdTestSection.description).toEqual('A Test Description');
});
it('should have a markup', () => {
expect(createdTestSection.markup).toEqual('test.hbs');
});
it('should have variations with states', () => {
expect(createdTestSection.variations).toEqual([
{ variationName: '.test-class', variationDescription: 'Variation Description', variationClass: ['test-class'] },
{ variationName: '.test-class2', variationDescription: 'Variation Description2', variationClass: ['test-class2'] },
{ variationName: ':hover', variationDescription: 'hoverState', variationClass: ['pseudo-class-hover'] },
{ variationName: ':focus', variationDescription: 'focusState', variationClass: ['pseudo-class-focus'] }
]);
});
it('should have properties', () => {
expect(createdTestSection.properties).toEqual(
{
'wrapper-classes': ['background-dark', 'min-height', 'overflow'],
'weight': ['-12']
}
);
});
});
describe('a comment with only title, name and property', () => {
beforeEach(() => {
const commentWithDescription = {
comment: '/*\nTitle \nWeight: -12 \nStyleguide testSection \n*/',
srcPath: 'doesNotExist/pathIsJustForTesting'
};
createdTestSection = commentsParser.getSectionObjectOfComment(commentWithDescription, sections);
});
it('should have a title', () => {
expect(createdTestSection.sectionTitle).toEqual('Title');
});
it('should have a sectionName', () => {
expect(createdTestSection.sectionName).toEqual('testsection');
});
it('should have a property', () => {
expect(createdTestSection.properties).toEqual(
{ weight: ['-12'] }
);
});
});
describe('a comment with angular-markup, variations, states and angular-properties', () => {
beforeEach(() => {
const commentWithDescription = {
comment: '/*\nTitle\nA Test Description\n\nangular-markup: test.html\n\n.test-class - Variation Description\n.test-class2 - Variation Description2\n:hover - hoverState\n:focus - focusState \n\nangular-wrapper: test,test\nwrapper-classes: background-dark, min-height , overflow \nWeight: -12 \n\n\nStyleguide testSection \n*/',
srcPath: 'doesNotExist/pathIsJustForTesting'
};
createdTestSection = commentsParser.getSectionObjectOfComment(commentWithDescription, sections);
});
it('should have a title', () => {
expect(createdTestSection.sectionTitle).toEqual('Title');
});
it('should have a sectionName', () => {
expect(createdTestSection.sectionName).toEqual('testsection');
});
it('should have a description', () => {
expect(createdTestSection.description).toEqual('A Test Description');
});
/*
cannot be tested here because the test.html sourcefile does not exist
it('should have a angular-markup', () =>
{
createdTestSection.should.have.property('angularMarkup');
});*/
it('should have variations with states', () => {
expect(createdTestSection.variations).toEqual([
{ variationName: '.test-class', variationDescription: 'Variation Description', variationClass: ['test-class'] },
{ variationName: '.test-class2', variationDescription: 'Variation Description2', variationClass: ['test-class2'] },
{ variationName: ':hover', variationDescription: 'hoverState', variationClass: ['pseudo-class-hover'] },
{ variationName: ':focus', variationDescription: 'focusState', variationClass: ['pseudo-class-focus'] }
]);
});
it('should have properties', () => {
expect(createdTestSection.properties).toEqual(
{
'angular-wrapper': ['test', 'test'],
'wrapper-classes': ['background-dark', 'min-height', 'overflow'],
'weight': ['-12']
}
);
});
});
describe('a comment with angular-markup,angular-properties', () => {
beforeEach(() => {
const commentWithDescription = {
comment: '/*\nTitle\nA Test Description\n\nangular-markup: test.html\n\nangular-wrapper: test,test\nwrapper-classes: background-dark, min-height , overflow \nWeight: -12 \n\n\nStyleguide testSection \n*/',
srcPath: 'doesNotExist/pathIsJustForTesting'
};
createdTestSection = commentsParser.getSectionObjectOfComment(commentWithDescription, sections);
});
it('should have a title', () => {
expect(createdTestSection.sectionTitle).toEqual('Title');
});
it('should have a sectionName', () => {
expect(createdTestSection.sectionName).toEqual('testsection');
});
it('should have a description', () => {
expect(createdTestSection.description).toEqual('A Test Description');
});
/*
cannot be tested here because the test.html sourcefile does not exist
it('should have a angular-markup', () =>
{
createdTestSection.should.have.property('angularMarkup');
});*/
it('should have properties', () => {
expect(createdTestSection.properties).toEqual(
{
'angular-wrapper': ['test', 'test'],
'wrapper-classes': ['background-dark', 'min-height', 'overflow'],
'weight': ['-12']
}
);
});
});
describe('a comment with angular-markup', () => {
beforeEach(() => {
const commentWithDescription = {
comment: '/*\nTitle\nA Test Description\n\nangular-markup: test.html\n\nStyleguide testSection \n*/',
srcPath: 'doesNotExist/pathIsJustForTesting'
};
createdTestSection = commentsParser.getSectionObjectOfComment(commentWithDescription, sections);
});
it('should have a title', () => {
expect(createdTestSection.sectionTitle).toEqual('Title');
});
it('should have a sectionName', () => {
expect(createdTestSection.sectionName).toEqual('testsection');
});
it('should have a description', () => {
expect(createdTestSection.description).toEqual('A Test Description');
});
});
describe('a comment in a sub-section', () => {
beforeEach(() => {
const commentWithDescription = {
comment: '/*\nTitle\nA Test Description\n\nangular-markup: test.html\n\nStyleguide testSection.sectionABC \n*/',
srcPath: 'doesNotExist/pathIsJustForTesting'
};
createdTestSection = commentsParser.getSectionObjectOfComment(commentWithDescription, sections);
});
it('should have a title', () => {
expect(createdTestSection.sectionTitle).toEqual('Title');
});
it('should have a sectionName', () => {
expect(createdTestSection.sectionName).toEqual('sectionabc');
});
it('should be level 2', () => {
expect(createdTestSection.level).toBe(2);
});
it('should have a description', () => {
expect(createdTestSection.description).toEqual('A Test Description');
});
});
});
|
f95dd12e0dfeacb3232a837dd0232b164f834c34
|
{
"blob_id": "f95dd12e0dfeacb3232a837dd0232b164f834c34",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-10T07:41:01",
"content_id": "9a3160fb0166d2e0bf27c0973890a3815d90c522",
"detected_licenses": [
"MIT"
],
"directory_id": "ca85b8c49c0d4970d2ac39e13070159903c6539a",
"extension": "ts",
"filename": "parser.test.ts",
"fork_events_count": 0,
"gha_created_at": "2019-08-06T07:30:41",
"gha_event_created_at": "2022-12-30T18:31:41",
"gha_language": "HTML",
"gha_license_id": "MIT",
"github_id": 200800050,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 23084,
"license": "MIT",
"license_type": "permissive",
"path": "/test/parser.test.ts",
"provenance": "stack-edu-0073.json.gz:91682",
"repo_name": "Ergosign/ux-library-generator",
"revision_date": "2020-03-10T07:41:01",
"revision_id": "8a3b2423c4d3cde5bb89cf825a28e6956160a421",
"snapshot_id": "15802b46883099f85a970b604a0e9e200b6d1d6b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Ergosign/ux-library-generator/8a3b2423c4d3cde5bb89cf825a28e6956160a421/test/parser.test.ts",
"visit_date": "2023-01-09T01:08:31.638012",
"added": "2024-11-19T01:22:44.923307+00:00",
"created": "2020-03-10T07:41:01",
"int_score": 3,
"score": 2.75,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0091.json.gz"
}
|
package com.splunk.cloudfwd.test.integration;
import com.splunk.cloudfwd.Connection;
import com.splunk.cloudfwd.PropertyKeys;
import com.splunk.cloudfwd.error.HecConnectionTimeoutException;
import org.junit.Test;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeoutException;
public class SplunkEventFieldsIT extends AbstractReconciliationTest {
@Override
protected int getNumEventsToSend() {
return 10;
}
@Override
protected Properties getProps() {
Properties p = super.getProps();
p.put(PropertyKeys.TOKEN, createTestToken(null));
return p;
}
@Override
protected String getSearchString() {
String searchString = "search";
if (!connection.getSettings().getHost().isEmpty()) {
searchString = searchString + " host=" + connection.getSettings().getHost();
}
if (!connection.getSettings().getIndex().isEmpty()) {
searchString = searchString + " index=" + connection.getSettings().getIndex();
} else {
searchString = searchString + " index=" + INDEX_NAME;
}
if (!connection.getSettings().getSource().isEmpty()) {
searchString = searchString + " source=" + connection.getSettings().getSource();
}
if (!connection.getSettings().getSourcetype().isEmpty()) {
searchString = searchString + " sourcetype=" + connection.getSettings().getSourcetype();
}
return searchString;
}
private String getLocalHost() {
String host = null;
try {
host = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
//e.printStackTrace();
LOG.error("{}", e.getMessage());
}
return host;
}
private String getSource() {
return getClass().getName();
}
@Test
public void sendEventsWithDefaultFieldsToRaw() throws InterruptedException, TimeoutException, HecConnectionTimeoutException, UnknownHostException {
LOG.info("test: sendEventsWithDefaultFieldsToRaw");
super.sendEvents();
LOG.warn("SEARCH STRING: " + getSearchString());
Set<String> results = getEventsFromSplunk();
verifyResults(getSentEvents(), results);
}
@Test
public void sendEventsWithCustomFieldsToRaw() throws InterruptedException, TimeoutException, HecConnectionTimeoutException, UnknownHostException {
LOG.info("test: sendEventsWithCustomFieldsToRaw");
connection.getSettings().setIndex(INDEX_NAME);
connection.getSettings().setHost(getLocalHost());
connection.getSettings().setSource(getSource());
connection.getSettings().setSourcetype(getSource());
super.sendEvents();
LOG.warn("SEARCH STRING: " + getSearchString());
Set<String> results = getEventsFromSplunk();
verifyResults(getSentEvents(), results);
}
@Test
public void sendEventsWithDefaultFieldsToEvent() throws InterruptedException, TimeoutException, HecConnectionTimeoutException, UnknownHostException {
LOG.info("test: sendEventsWithDefaultFieldsToEvent");
connection.getSettings().setHecEndpointType(Connection.HecEndpoint.STRUCTURED_EVENTS_ENDPOINT);
super.sendEvents();
LOG.warn("SEARCH STRING: " + getSearchString());
Set<String> results = getEventsFromSplunk();
verifyResults(getSentEvents(), results);
}
@Test
public void sendEventsWithCustomFieldsToEvent() throws InterruptedException, TimeoutException, HecConnectionTimeoutException, UnknownHostException {
LOG.info("test: sendEventsWithCustomFieldsToEvent");
connection.getSettings().setHecEndpointType(Connection.HecEndpoint.STRUCTURED_EVENTS_ENDPOINT);
connection.getSettings().setIndex(INDEX_NAME);
connection.getSettings().setHost(getLocalHost());
connection.getSettings().setSource(getSource());
connection.getSettings().setSourcetype(getSource());
super.sendEvents();
LOG.warn("SEARCH STRING: " + getSearchString());
Set<String> results = getEventsFromSplunk();
verifyResults(getSentEvents(), results);
}
}
|
d303d9e206c64288897239fd6411197262ace53d
|
{
"blob_id": "d303d9e206c64288897239fd6411197262ace53d",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-12T22:22:52",
"content_id": "d8ff279a4cdd70163726f6f47c1ba9d9e5c572be",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "14705f4c2c398a87d896c70b7a9b54a842712772",
"extension": "java",
"filename": "SplunkEventFieldsIT.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 4307,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/test/java/com/splunk/cloudfwd/test/integration/SplunkEventFieldsIT.java",
"provenance": "stack-edu-0022.json.gz:254711",
"repo_name": "zmutabanna/cloudfwd",
"revision_date": "2017-12-12T22:22:52",
"revision_id": "a8aa199e2e7fa31c89f8d7a93ad126c479578fad",
"snapshot_id": "74f830d68fad794da20a697ed173cec7ef2dc120",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zmutabanna/cloudfwd/a8aa199e2e7fa31c89f8d7a93ad126c479578fad/src/test/java/com/splunk/cloudfwd/test/integration/SplunkEventFieldsIT.java",
"visit_date": "2021-05-12T02:54:43.078870",
"added": "2024-11-19T02:48:16.713253+00:00",
"created": "2017-12-12T22:22:52",
"int_score": 2,
"score": 2.03125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz"
}
|
package sandro;
import org.junit.Test;
import sandro.service.UserService;
import sandro.entity.User;
import java.util.List;
import static org.assertj.core.api.Assertions.*;
public class UserServiceTest {
UserService service = new UserService();
@Test
public void testSaveRecord() throws Exception {
User user = new User();
user.setEmail("[email protected]");
user.setLogin("chupak");
user.setPassword("kapa");
User userFromDB = service.add(user);
assertThat(userFromDB).isNotNull();
service.delete(userFromDB.getId());
}
@Test
public void testDeleteRecord() throws Exception {
User user = new User();
user.setEmail("[email protected]");
user.setLogin("izya");
user.setPassword("izya");
User userFromDB = service.add(user);
int id = userFromDB.getId();
service.delete(id);
assertThat(service.get(id)).isNull();
}
@Test
public void testSelect() throws Exception {
User user1 = new User();
user1.setEmail("[email protected]");
user1.setLogin("minis");
user1.setPassword("kjho");
User userFromDB = service.add(user1);
int id = userFromDB.getId();
User userFromDBSel = service.get(id);
assertThat(userFromDB).isEqualTo(userFromDBSel);
service.delete(userFromDB.getId());
userFromDBSel = service.get(id);
assertThat(userFromDBSel).isNull();
}
@Test
public void testUpdate() throws Exception {
User user = new User();
user.setEmail("[email protected]");
user.setLogin("bronf");
user.setPassword("man");
user = service.add(user);
user.setEmail("[email protected]");
service.update(user);
User userFromDB = service.get(user.getId());
assertThat(userFromDB).isEqualTo(user);
service.delete(user.getId());
}
@Test
public void testGetAll() {
User user0 = new User();
user0.setEmail("[email protected]");
user0.setLogin("dead");
user0.setPassword("shot");
User userFromDB0 = service.add(user0);
service.delete(userFromDB0.getId());
User user1 = new User();
user1.setEmail("[email protected]");
user1.setLogin("pundik");
user1.setPassword("squad");
User user2 = new User();
user2.setEmail("[email protected]");
user2.setLogin("harley");
user2.setPassword("pudding");
User userFromDB1 = service.add(user1);
User userFromDB2 = service.add(user2);
List<User> users = service.getAll();
assertThat(users).contains(userFromDB1, userFromDB2);
assertThat(users.contains(userFromDB0)).isEqualTo(false);
service.delete(userFromDB1.getId());
service.delete(userFromDB2.getId());
}
}
|
d0291d4d40154bcf4b7c0f61754b6d6faca94e8f
|
{
"blob_id": "d0291d4d40154bcf4b7c0f61754b6d6faca94e8f",
"branch_name": "refs/heads/master",
"committer_date": "2016-11-14T22:33:42",
"content_id": "3c1219fd3a7baac403eb0df560fc5f8f57a4077f",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "53ffe0e68e0f996e37d5db2d9d149d6191c0a4e3",
"extension": "java",
"filename": "UserServiceTest.java",
"fork_events_count": 0,
"gha_created_at": "2016-09-17T16:35:14",
"gha_event_created_at": "2016-11-14T22:33:42",
"gha_language": "Java",
"gha_license_id": null,
"github_id": 68464268,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2991,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/test/java/sandro/UserServiceTest.java",
"provenance": "stack-edu-0020.json.gz:313579",
"repo_name": "DevilsWorkshop/lab1",
"revision_date": "2016-11-14T22:33:42",
"revision_id": "a6edff6dac029a698e666cf9f5e8b9d28db1c5fa",
"snapshot_id": "ca14e95b7684bdd0f3f9117d683ebf2f9bc9987d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/DevilsWorkshop/lab1/a6edff6dac029a698e666cf9f5e8b9d28db1c5fa/src/test/java/sandro/UserServiceTest.java",
"visit_date": "2020-12-03T00:05:24.412354",
"added": "2024-11-18T23:41:05.203615+00:00",
"created": "2016-11-14T22:33:42",
"int_score": 2,
"score": 2.46875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0038.json.gz"
}
|
const create_filled_array = predicate => times => ( new Array(times) ).fill('').map((_,i)=>predicate(i))
module.exports = create_filled_array
|
9aa4d097dcba12a7ea390bcd8c1babaaa33416e3
|
{
"blob_id": "9aa4d097dcba12a7ea390bcd8c1babaaa33416e3",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-23T15:24:45",
"content_id": "902d3a016dbd0d99f6e40c391d7ed75189d18121",
"detected_licenses": [
"Unlicense"
],
"directory_id": "9f5471232ba649da17c4a2521fb46b776b512139",
"extension": "js",
"filename": "create_filled_array.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 121834309,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 142,
"license": "Unlicense",
"license_type": "permissive",
"path": "/src/utils/create_filled_array.js",
"provenance": "stack-edu-0043.json.gz:641815",
"repo_name": "Xananax/codi-discord-bot",
"revision_date": "2018-02-23T15:24:45",
"revision_id": "b74d5350df201253daa7aa92bf5ffbed0d0f5024",
"snapshot_id": "df4664d7dc052a6f05e60be0e16ababe05dee537",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Xananax/codi-discord-bot/b74d5350df201253daa7aa92bf5ffbed0d0f5024/src/utils/create_filled_array.js",
"visit_date": "2021-04-29T00:40:40.085990",
"added": "2024-11-19T00:50:43.472871+00:00",
"created": "2018-02-23T15:24:45",
"int_score": 2,
"score": 2.3125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0061.json.gz"
}
|
/*
* Copyright: (c) 2004-2011 Mayo Foundation for Medical Education and
* Research (MFMER). All rights reserved. MAYO, MAYO CLINIC, and the
* triple-shield Mayo logo are trademarks and service marks of MFMER.
*
* Except as contained in the copyright notice above, or as used to identify
* MFMER as the author of this software, the trade names, trademarks, service
* marks, or product names of the copyright holder shall not be used in
* advertising, promotion or otherwise in connection with this software without
* prior written authorization of the copyright holder.
*
* 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.
*/
package edu.mayo.cts2.framework.model.command;
/**
* A request for a 'page' of CTS2 resources.
*
* @author <a href="mailto:[email protected]">Kevin Peterson</a>
*/
public class Page implements Cloneable {
private int DEFAULT_PAGE_SIZE = 50;
private int DEFAULT_PAGE = 0;
private int page = DEFAULT_PAGE;
private int maxtoreturn = DEFAULT_PAGE_SIZE;
public Page(){
this.maxtoreturn = DEFAULT_PAGE_SIZE;
}
public Page(int maxtoreturn){
this.maxtoreturn = maxtoreturn;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getMaxToReturn() {
return maxtoreturn;
}
public void setMaxToReturn(int maxtoreturn) {
if(maxtoreturn == 0){
throw new IllegalArgumentException("Cannot ask for zero results.");
}
this.maxtoreturn = maxtoreturn;
}
/* (non-Javadoc)
* @see java.lang.Object#clone()
*/
@Override
public Page clone() throws CloneNotSupportedException {
Page page = new Page(maxtoreturn);
page.setPage(this.getPage());
page.setMaxToReturn(this.getMaxToReturn());
return page;
}
public int getStart(){
return this.getPage() * this.getMaxToReturn();
}
public int getEnd(){
return (this.getPage() + 1) * this.getMaxToReturn();
}
}
|
623e6f9addaba72c52f1b54b7a6c926fffd61c29
|
{
"blob_id": "623e6f9addaba72c52f1b54b7a6c926fffd61c29",
"branch_name": "refs/heads/master",
"committer_date": "2022-03-25T15:37:21",
"content_id": "756251848323341e3353ac3638a8dbb9dc539590",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "39da51877a494cd3f4796a906dfff8a5942bebe8",
"extension": "java",
"filename": "Page.java",
"fork_events_count": 3,
"gha_created_at": "2016-10-04T14:31:49",
"gha_event_created_at": "2022-02-17T15:43:06",
"gha_language": "Java",
"gha_license_id": "Apache-2.0",
"github_id": 69973427,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2404,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/cts2-model/src/main/java/edu/mayo/cts2/framework/model/command/Page.java",
"provenance": "stack-edu-0024.json.gz:346381",
"repo_name": "lexevs/cts2-framework",
"revision_date": "2022-03-25T15:37:21",
"revision_id": "71f3e47e407df9a67747fca110202c0d03d20970",
"snapshot_id": "93d449c56d9dd23e7d3b445470a11f85bd012560",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lexevs/cts2-framework/71f3e47e407df9a67747fca110202c0d03d20970/cts2-model/src/main/java/edu/mayo/cts2/framework/model/command/Page.java",
"visit_date": "2022-08-06T16:36:00.454355",
"added": "2024-11-19T03:42:09.507320+00:00",
"created": "2022-03-25T15:37:21",
"int_score": 2,
"score": 2.265625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz"
}
|
package com.randy073.findmehere;
/**
* Created by randyyang on 7/29/16.
*/
public class UserLocation {
private String uId;
public String getuId() {
return uId;
}
public void setuId(String uId) {
this.uId = uId;
}
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLng() {
return lng;
}
public void setLng(double lng) {
this.lng = lng;
}
private double lat;
private double lng;
public UserLocation(){
}
public UserLocation(String uid, double lat, double lng){
this.uId = uid;
this.lat = lat;
this.lng = lng;
}
}
|
9b233bdca4e11599bee35f54e1996c445705f43a
|
{
"blob_id": "9b233bdca4e11599bee35f54e1996c445705f43a",
"branch_name": "refs/heads/master",
"committer_date": "2016-07-29T05:55:56",
"content_id": "2c6b41f0f18bf26bb909a34b4fb5611e7c34849e",
"detected_licenses": [
"MIT"
],
"directory_id": "12ad334580c01c1c348812973469d5455fe8afdc",
"extension": "java",
"filename": "UserLocation.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 64449759,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 728,
"license": "MIT",
"license_type": "permissive",
"path": "/app/src/main/java/com/randy073/findmehere/UserLocation.java",
"provenance": "stack-edu-0030.json.gz:856235",
"repo_name": "randy073/FindMeHere",
"revision_date": "2016-07-29T05:55:56",
"revision_id": "e4620a5860f7cadad06bc32bb68d7b71d929f5f0",
"snapshot_id": "ee9097c808ef2a5dc3b12d7e8a0e896b60353718",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/randy073/FindMeHere/e4620a5860f7cadad06bc32bb68d7b71d929f5f0/app/src/main/java/com/randy073/findmehere/UserLocation.java",
"visit_date": "2021-01-17T13:21:19.497417",
"added": "2024-11-19T00:41:33.276149+00:00",
"created": "2016-07-29T05:55:56",
"int_score": 2,
"score": 2.375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0048.json.gz"
}
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use Session;
use Cart;
use Illuminate\Support\Facades\Redirect;
Session_start();
use App\Models\Shipping;
use App\Models\Order;
use App\Models\OrderDetails;
class CheckoutController extends Controller
{
public function Kiemtralogin(){
$admin_id=Session::get('admin_id');
if($admin_id){
return Redirect::to('dashboard');
}
else{
return Redirect::to('admin')->send();
}
}
public function login_checkout(){
$all_banner=DB::table('tbl_banner')->where('banner_status','1')->orderby('banner_id','ASC')->get();
$cate_product=DB::table('tbl_category_product')->where('category_status','0')->orderby('category_id','desc')->get();
$brand_product=DB::table('tbl_brand')->where('brand_status','0')->orderby('brand_id','desc')->get();
return view('pages.checkout.login_checkout')->with('category',$cate_product)->with('brand',$brand_product)->with('all_banner',$all_banner);
}
public function add_customer(Request $request){
$data=array();
$data['customers_name']=$request->customers_name;
$data['customers_email']=$request->customers_email;
$data['customers_password']=md5($request->customers_password);
$data['customers_phone']=$request->customers_phone;
$customers_id =DB::table('tbl_customers')->insertGetId($data);
Session::put('customers_id',$customers_id);
Session::put('customers_name',$request->customers_name);
return redirect('/checkout');
}
public function checkout(){
$all_banner=DB::table('tbl_banner')->where('banner_status','1')->orderby('banner_id','ASC')->get();
$cate_product=DB::table('tbl_category_product')->where('category_status','0')->orderby('category_id','desc')->get();
$brand_product=DB::table('tbl_brand')->where('brand_status','0')->orderby('brand_id','desc')->get();
return view('pages.checkout.show_checkout')->with('category',$cate_product)->with('brand',$brand_product)->with('all_banner',$all_banner);
}
public function save_checkout_customers(Request $request){
// $data=array();
// $data['shipping_name']=$request->shipping_name;
// $data['shipping_address']=$request->shipping_address;
// $data['shipping_phone']=$request->shipping_phone;
// $data['shipping_email']=$request->shipping_email;
// $data['shipping_note']=$request->shipping_note;
// $shipping_id =DB::table('tbl_shipping')->insertGetId($data);
// Session::put('shipping_id',$shipping_id);
// return redirect('/payment');
}
public function payment(){
$all_banner=DB::table('tbl_banner')->where('banner_status','1')->orderby('banner_id','ASC')->get();
$cate_product=DB::table('tbl_category_product')->where('category_status','0')->orderby('category_id','desc')->get();
$brand_product=DB::table('tbl_brand')->where('brand_status','0')->orderby('brand_id','desc')->get();
return view('pages.checkout.payment')->with('category',$cate_product)->with('brand',$brand_product)->with('all_banner',$all_banner);
}
public function logout_checkout(){
Session::flush();
return redirect('/login-checkout');
}
public function login_customer(Request $request){
$email=$request->email_acc;
$pass=md5($request->pass_acc);
$result=DB::table('tbl_customers')->where('customers_email',$email)->where('customers_password',$pass)->first();
if($result){
Session::put('customers_id',$result->customers_id);
Session::put('customers_name',$result->customers_name);
return redirect('/checkout');
}else{
Session::put('messages','Mật khẩu hoặc tên đăng nhập không đúng');
return redirect('/login-checkout');
}
}
public function order_play(Request $request){
//ínsertpayment
$data=array();
$data['payment_method']=$request->payment_option;
$data['payment_status']='Đang chờ xử lý';
$payment_id =DB::table('tbl_payment')->insertGetId($data);
//insertorder
$order_data=array();
$order_data['customer_id']=Session::get('customers_id');
$order_data['shipping_id']=Session::get('shipping_id');
$order_data['payment_id']=$payment_id;
$order_data['order_total']=Cart::total();
$order_data['order_status']='Đang chờ xử lý';
$order_id =DB::table('tbl_order')->insertGetId($order_data);
//insert_order_details
$content=Cart::content();
foreach($content as $v_content){
$order_details_data['order_id']=$order_id;
$order_details_data['product_id']=$v_content->id;
$order_details_data['product_name']=$v_content->name;
$order_details_data['product_price']=$v_content->price;
$order_details_data['product_sales_quantity']=$v_content->qty;
DB::table('tbl_order_details')->insert($order_details_data);
}
if($data['payment_method']==0){
echo 'Thanh toán online';
}else{
Cart::destroy();
$all_banner=DB::table('tbl_banner')->where('banner_status','1')->orderby('banner_id','ASC')->get();
$cate_product=DB::table('tbl_category_product')->where('category_status','0')->orderby('category_id','desc')->get();
$brand_product=DB::table('tbl_brand')->where('brand_status','0')->orderby('brand_id','desc')->get();
return view('pages.checkout.handcash')->with('category',$cate_product)->with('brand',$brand_product)->with('all_banner',$all_banner);
}
//return redirect('/payment');
}
public function manage_order(){
$this->Kiemtralogin();
$all_order=DB::table('tbl_order')
->join('tbl_customers','tbl_order.customer_id','=','tbl_customers.customers_id')
->select('tbl_order.*','tbl_customers.customers_name')
->orderby('tbl_order.order_id','desc')->get();
$manage_order=view('admin.manage_order')->with('all_order',$all_order);
return view('admin_layout')->with('admin.manage_order',$manage_order);
}
public function view_order($orderId){
$this->Kiemtralogin();
$order_by_id=DB::table('tbl_order')
->join('tbl_customers','tbl_order.customer_id','=','tbl_customers.customers_id')
->join('tbl_shipping','tbl_order.shipping_id','=','tbl_shipping.shipping_id')
->join('tbl_order_details','tbl_order.order_id','=','tbl_order_details.order_id')
->select('tbl_order.*','tbl_customers.*','tbl_shipping.*','tbl_order_details.*')
->first();
$manage_order_by_id=view('admin.view_order')->with('order_by_id',$order_by_id);
return view('admin_layout')->with('admin.view_order',$manage_order_by_id);
}
public function insert_shipping(Request $request){
$data=array();
$data['shipping_name']=$request->shipping_name;
$data['shipping_address']=$request->shipping_address;
$data['shipping_phone']=$request->shipping_phone;
$data['shipping_email']=$request->shipping_email;
$data['shipping_note']=$request->shipping_note;
$data['shipping_method']=$request->shipping_method;
$shipping_id =DB::table('tbl_shipping')->insertGetId($data);
Session::put('shipping_id',$shipping_id);
$checkout_code=substr(md5(microtime()),rand(0,26),5);
$order=array();
$order['customer_id']=Session::get('customers_id');
$order['shipping_id']=$shipping_id;
$order['order_status']=1;
$order['order_code']=$checkout_code;
$order['created_at']=now();
$order_id=DB::table('tbl_order')->insertGetId($order);
if(Session::get('cart')){
foreach(Session::get('cart') as $key =>$cart){
$order_detail=array();
$order_detail['order_code']=$checkout_code;
$order_detail['product_id']=$cart['product_id'];
$order_detail['product_name']=$cart['product_name'];
$order_detail['product_price']=$cart['product_gia'];
$order_detail['product_sales_quantity']=$cart['product_qty'];
$order_detail['created_at']=now();
DB::table('tbl_order_details')->insert($order_detail);
}
}
Session::forget('cart');
}
}
|
18bf3ea8ce9bd955a91c7faca860f34ee6c41bc8
|
{
"blob_id": "18bf3ea8ce9bd955a91c7faca860f34ee6c41bc8",
"branch_name": "refs/heads/master",
"committer_date": "2021-11-06T09:55:47",
"content_id": "96a83c3cf407a9c82f33f56582a3190165a3e175",
"detected_licenses": [
"MIT"
],
"directory_id": "b42f3fe7ab2fa6b999959c75f529f8a9a9d89316",
"extension": "php",
"filename": "CheckoutController.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 425206562,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 8689,
"license": "MIT",
"license_type": "permissive",
"path": "/app/Http/Controllers/CheckoutController.php",
"provenance": "stack-edu-0049.json.gz:300949",
"repo_name": "vucongminh0910/Laravel-",
"revision_date": "2021-11-06T09:55:47",
"revision_id": "c4de14a3178b7673504583861764b3d262336991",
"snapshot_id": "83212d51936005d814874e124871fade89e23e2f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vucongminh0910/Laravel-/c4de14a3178b7673504583861764b3d262336991/app/Http/Controllers/CheckoutController.php",
"visit_date": "2023-09-02T20:04:32.705290",
"added": "2024-11-19T02:44:50.088536+00:00",
"created": "2021-11-06T09:55:47",
"int_score": 2,
"score": 2.109375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0067.json.gz"
}
|
package org.tiling.s3map;
/**
* Thrown if there is a problem communicating with Amazon S3.
*/
public class S3Exception extends RuntimeException {
public S3Exception(String message, Object... args) {
super(String.format(message, args));
}
public S3Exception(Throwable t) {
super(t);
}
}
|
5eff85afb83330eba2ca9d434b21a0b4ea3d2e17
|
{
"blob_id": "5eff85afb83330eba2ca9d434b21a0b4ea3d2e17",
"branch_name": "refs/heads/master",
"committer_date": "2011-11-25T22:28:13",
"content_id": "df12280281d5aa157dab60107cbd698087f56422",
"detected_licenses": [
"ADSL",
"Apache-2.0"
],
"directory_id": "40951c70fe10c3796f249b640dc93739f4da1ea3",
"extension": "java",
"filename": "S3Exception.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 300,
"license": "ADSL,Apache-2.0",
"license_type": "permissive",
"path": "/s3map/src/main/java/org/tiling/s3map/S3Exception.java",
"provenance": "stack-edu-0022.json.gz:750092",
"repo_name": "RGowdhaman/articles",
"revision_date": "2011-11-25T22:28:13",
"revision_id": "7b7eef0de40be0a0431e087115f331fb415b336d",
"snapshot_id": "49c7e0786750c4531798be9cdbd3e12dea3b5621",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/RGowdhaman/articles/7b7eef0de40be0a0431e087115f331fb415b336d/s3map/src/main/java/org/tiling/s3map/S3Exception.java",
"visit_date": "2021-01-01T06:09:12.654317",
"added": "2024-11-19T00:23:51.223937+00:00",
"created": "2011-11-25T22:28:13",
"int_score": 3,
"score": 2.546875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz"
}
|
import articleApi from "@/core/api/article";
export const state = () => {
return {
articleList: [],
categoryList: []
};
};
export const mutations = {
SET_ARTICLE_LIST: (state, list) => {
state.articleList = list;
},
PUSH_ARTICLE_LIST: (state, list) => {
state.articleList.push(...list);
},
SET_CATEGORY_LIST: (state, list) => {
state.categoryList = list;
}
};
export const actions = {
getArticleList: async ({ commit }, data) => {
try {
const res = await articleApi.getArticleList(data);
commit("SET_ARTICLE_LIST", res.data);
return Promise.resolve(1);
} catch (error) {
return Promise.reject(error);
}
},
pushArticleList: async ({ commit }, page, category_id) => {
let params = {
total: 10,
page,
category_id
};
// debugger
if (!category_id) delete params.category_id;
try {
const res = await articleApi.getArticleList(params);
commit("PUSH_ARTICLE_LIST", res.data);
return Promise.resolve(res.data.length);
} catch (error) {
return Promise.reject(error);
}
},
getCategoryList: async ({ commit }) => {
const res = await articleApi.getCategory();
commit("SET_CATEGORY_LIST", res.data);
}
};
|
e5247eee2e964ba26d0b6cd337a895f48917d6e9
|
{
"blob_id": "e5247eee2e964ba26d0b6cd337a895f48917d6e9",
"branch_name": "refs/heads/master",
"committer_date": "2018-05-14T10:14:39",
"content_id": "dbb21db99eebbb663748dc262096d0759f4101cf",
"detected_licenses": [
"MIT"
],
"directory_id": "076f87e6fe7b33c56791877dc49a5d834b73d14d",
"extension": "js",
"filename": "article.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1418,
"license": "MIT",
"license_type": "permissive",
"path": "/store/article.js",
"provenance": "stack-edu-0045.json.gz:285813",
"repo_name": "jianjunx/blog-pwa",
"revision_date": "2018-05-14T10:14:39",
"revision_id": "c345213a4ad8b298b27f6d013a1b43697e1a8cca",
"snapshot_id": "1dda8ba531ef1d095b927ae8b906427931591b42",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jianjunx/blog-pwa/c345213a4ad8b298b27f6d013a1b43697e1a8cca/store/article.js",
"visit_date": "2021-09-14T13:25:10.645857",
"added": "2024-11-19T00:53:06.944427+00:00",
"created": "2018-05-14T10:14:39",
"int_score": 2,
"score": 2.375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0063.json.gz"
}
|
$(".claim_detail").click(function() {
var claim_id = $(this).attr("name");
var claim_info_url = '/front/claim_detail/?id=' + claim_id;
$.get( claim_info_url, function( data ) {
$("#claim_detail").html(data);
$("#claim_detail_box").modal()
});
});
function send_tender_button() {
var claim_id = $('#claim_id')[0].innerText;
var user_id = $('#user_id')[0].innerText;
var check_user_info = $('#check_user_info')[0].innerText;
var bank_profile = $('#bank_profile')[0].innerText;
var subscription_value = $('#subscription_value')[0].innerText;
if(check_user_info !== ''){ // 檢查用戶資訊是否完整填寫
swal(check_user_info, "", "error");
return false;
}
if(subscription_value >= 100 ) {
swal('此債權已完成認購,請勿再投標。', "", "error");
return false;
}
if(bank_profile == 0){
swal('您的銀行帳戶尚未提交審核,或審核尚未通過', "", "error");
return false;
}
window.location.href = "/front/tender?id="+claim_id;
};
|
db63e7b68ffdc55a5198faaaad5919f9e7568809
|
{
"blob_id": "db63e7b68ffdc55a5198faaaad5919f9e7568809",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-17T06:13:57",
"content_id": "1fb35fb3ba6ba1d62db1a29e83d67f2d64b09cf2",
"detected_licenses": [
"MIT"
],
"directory_id": "99b8f8f55e4dcb91797c6443255588bdac6fbc02",
"extension": "js",
"filename": "favorite-1c9fe5b7ca4c58767355085a7dec3f71db3ebfb3fe1dd096bf0b321153081333.js",
"fork_events_count": 0,
"gha_created_at": "2019-12-09T09:55:04",
"gha_event_created_at": "2023-01-05T02:37:35",
"gha_language": "HTML",
"gha_license_id": null,
"github_id": 226838839,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1087,
"license": "MIT",
"license_type": "permissive",
"path": "/public/assets/users/favorite-1c9fe5b7ca4c58767355085a7dec3f71db3ebfb3fe1dd096bf0b321153081333.js",
"provenance": "stack-edu-0044.json.gz:398706",
"repo_name": "littlerock1215/ddonline_new",
"revision_date": "2019-12-17T06:13:57",
"revision_id": "fd54f5e98e5c4d94dc8c2ed5f2a384d421dd919a",
"snapshot_id": "4d169014f8698057fa5746373b6b2b625a79830e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/littlerock1215/ddonline_new/fd54f5e98e5c4d94dc8c2ed5f2a384d421dd919a/public/assets/users/favorite-1c9fe5b7ca4c58767355085a7dec3f71db3ebfb3fe1dd096bf0b321153081333.js",
"visit_date": "2023-01-05T21:44:10.259451",
"added": "2024-11-19T01:11:15.763638+00:00",
"created": "2019-12-17T06:13:57",
"int_score": 2,
"score": 2.171875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0062.json.gz"
}
|
namespace Chocolatey.Web.Actions.Package
{
using System.Collections.Generic;
using Domain;
using FubuMVC.Core.View;
using Infrastructure.Persistence;
public class ListAction
{
private readonly IRepository _repository;
public ListAction(IRepository repository)
{
_repository = repository;
}
public PackageListResponse Get(PackageListRequest request)
{
var list = _repository.Find<NugetPackage>();
return new PackageListResponse
{
Packages = list
};
}
}
public class PackageListRequest {}
public class PackageListResponse
{
public IEnumerable<NugetPackage> Packages { get; set; }
}
public class List : FubuPage<PackageListResponse>
{
}
}
|
203e484425af351eb6f00b6059cb92a143157b9f
|
{
"blob_id": "203e484425af351eb6f00b6059cb92a143157b9f",
"branch_name": "refs/heads/master",
"committer_date": "2020-05-27T20:33:26",
"content_id": "253fb1478ed5fc50bb4756f9866782a1ce91123d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "0906fac4135f3d964c708512ef02dce16cf2af8e",
"extension": "cs",
"filename": "ListAction.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 261824962,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 881,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/chocolatey.web/src/Chocolatey.Web/Actions/Package/ListAction.cs",
"provenance": "stack-edu-0009.json.gz:297140",
"repo_name": "WeilerWebServices/Chocolatey",
"revision_date": "2020-05-27T20:33:26",
"revision_id": "369f9c9c7f3d40f925d4e49af1d2fe64370b871b",
"snapshot_id": "7d9e19b373ef147c027a4433a8d5d23ac2d46685",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/WeilerWebServices/Chocolatey/369f9c9c7f3d40f925d4e49af1d2fe64370b871b/chocolatey.web/src/Chocolatey.Web/Actions/Package/ListAction.cs",
"visit_date": "2022-08-07T09:14:59.066122",
"added": "2024-11-19T02:14:32.137278+00:00",
"created": "2020-05-27T20:33:26",
"int_score": 2,
"score": 2.0625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0027.json.gz"
}
|
package org.basex.query.var;
import static org.basex.query.QueryError.*;
import static org.basex.query.QueryText.*;
import org.basex.query.*;
import org.basex.query.expr.*;
import org.basex.query.expr.Expr.Flag;
import org.basex.query.func.fn.*;
import org.basex.query.util.*;
import org.basex.query.value.*;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;
import org.basex.query.value.type.*;
import org.basex.util.*;
/**
* Static variable to which an expression can be assigned.
*
* @author BaseX Team 2005-15, BSD License
* @author Leo Woerteler
*/
public final class StaticVar extends StaticDecl {
/** Annotation for lazy evaluation. */
private static final QNm LAZY = new QNm(QueryText.LAZY, BASEX_URI);
/** If this variable can be bound from outside the query. */
private final boolean external;
/** Flag for lazy evaluation. */
private final boolean lazy;
/** Bound value. */
Value val;
/**
* Constructor for a variable declared in a query.
* @param sc static context
* @param scope variable scope
* @param ann annotations
* @param name variable name
* @param type declared variable type
* @param expr expression to be bound
* @param external external flag
* @param doc current xqdoc cache
* @param info input info
*/
StaticVar(final StaticContext sc, final VarScope scope, final Ann ann, final QNm name,
final SeqType type, final Expr expr, final boolean external, final String doc,
final InputInfo info) {
super(sc, ann, name, type, scope, doc, info);
this.expr = expr;
this.external = external;
lazy = ann != null && ann.contains(LAZY);
}
@Override
public void compile(final QueryContext qc) throws QueryException {
if(expr == null) throw VAREMPTY_X.get(info, '$' + Token.string(name.string()));
if(dontEnter) throw circVarError(this);
if(!compiled) {
dontEnter = true;
try {
expr = expr.compile(qc, scope);
} catch(final QueryException qe) {
compiled = true;
if(lazy) {
expr = FnError.get(qe, expr.seqType());
return;
}
throw qe.notCatchable();
} finally {
scope.cleanUp(this);
dontEnter = false;
}
compiled = true;
if(!lazy || expr.isValue()) bind(value(qc));
}
}
/**
* Evaluates this variable lazily.
* @param qc query context
* @return value of this variable
* @throws QueryException query exception
*/
Value value(final QueryContext qc) throws QueryException {
if(dontEnter) throw circVarError(this);
if(lazy) {
if(!compiled) throw Util.notExpected(this + " was not compiled.");
if(val != null) return val;
dontEnter = true;
final int fp = scope.enter(qc);
try {
return bind(expr.value(qc));
} catch(final QueryException qe) {
throw qe.notCatchable();
} finally {
scope.exit(qc, fp);
dontEnter = false;
}
}
if(val != null) return val;
if(expr == null) throw VAREMPTY_X.get(info, this);
dontEnter = true;
final int fp = scope.enter(qc);
try {
return bind(expr.value(qc));
} finally {
scope.exit(qc, fp);
dontEnter = false;
}
}
/**
* Checks for the correct placement of updating expressions in this variable.
* @throws QueryException query exception
*/
void checkUp() throws QueryException {
if(expr != null && expr.has(Flag.UPD)) throw UPNOT_X.get(info, description());
}
/**
* Binds an expression to this variable from outside the query.
* @param value value to bind
* @param qc query context
* @throws QueryException query exception
*/
void bind(final Value value, final QueryContext qc) throws QueryException {
if(!external || compiled) return;
bind(declType == null || declType.instance(value) ? value : declType.cast(value, qc, sc, info));
}
/**
* Binds the specified value to the variable.
* @param value value to be set
* @return self reference
* @throws QueryException query exception
*/
private Value bind(final Value value) throws QueryException {
expr = value;
val = value;
if(declType != null) declType.treat(value, info);
return val;
}
@Override
public void plan(final FElem plan) {
final FElem e = planElem(NAM, name.string());
if(expr != null) expr.plan(e);
plan.add(e);
}
@Override
public boolean visit(final ASTVisitor visitor) {
return expr == null || expr.accept(visitor);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder(DECLARE).append(' ');
if(!ann.isEmpty()) sb.append(ann);
sb.append(VARIABLE).append(' ').append(DOLLAR).append(
Token.string(name.string())).append(' ');
if(declType != null) sb.append(AS).append(' ').append(declType).append(' ');
if(expr != null) sb.append(ASSIGN).append(' ').append(expr);
else sb.append(EXTERNAL);
return sb.append(';').toString();
}
@Override
public byte[] id() {
return Token.concat(new byte[] { '$' }, name.id());
}
/**
* Checks if the expression bound to this variable has the given flag.
* @param flag flag to check for
* @return {@code true} if the expression has the given flag, {@code false} otherwise
*/
boolean has(final Flag flag) {
if(dontEnter || expr == null) return false;
dontEnter = true;
final boolean res = expr.has(flag);
dontEnter = false;
return res;
}
}
|
8996972bad9642761427f9759e7125d14e6ff437
|
{
"blob_id": "8996972bad9642761427f9759e7125d14e6ff437",
"branch_name": "refs/heads/master",
"committer_date": "2015-01-14T14:52:24",
"content_id": "ca605f07ec707e4adb62c0e101e4e58e10aa919c",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "2224ba5c420fcba8157bde3ab63c878d0504fca7",
"extension": "java",
"filename": "StaticVar.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 19237997,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 5520,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/basex-core/src/main/java/org/basex/query/var/StaticVar.java",
"provenance": "stack-edu-0023.json.gz:845441",
"repo_name": "PrakashThapa/basex",
"revision_date": "2015-01-14T14:52:24",
"revision_id": "b444e89eb055ecfb0cb101352dd73a9fb6d6744d",
"snapshot_id": "8a3e90cf78f02f67ef80d8ca026d9ffe19557e63",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/PrakashThapa/basex/b444e89eb055ecfb0cb101352dd73a9fb6d6744d/basex-core/src/main/java/org/basex/query/var/StaticVar.java",
"visit_date": "2021-01-18T20:34:03.507907",
"added": "2024-11-19T00:38:14.671272+00:00",
"created": "2015-01-14T14:52:24",
"int_score": 2,
"score": 2.234375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz"
}
|
package vitualmachine.chapter5;
import java.util.HashMap;
import java.util.Map;
/**
* -Xmx32m -Xms32m -XX:+UseSerialGC -XX:+PrintGCDetails
* -Xmx32m -Xms32m -XX:+UseSerialGC -XX:+PrintGCDetails -XX:PretenureSizeThreshold=1000
* @author sy
*
*/
public class PretenureSizeThreshold {
public static final int _1K = 1024;
public static void main(String[] args) {
Map<Integer, byte[]> map = new HashMap<Integer, byte[]>();
for(int i=0; i<5*_1K; i++){
byte[] b = new byte[_1K];
map.put(i, b);
}
}
}
|
670cd9b28f76e27afdf5ce98a56cf75343ba76b5
|
{
"blob_id": "670cd9b28f76e27afdf5ce98a56cf75343ba76b5",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-24T01:26:19",
"content_id": "f56c4c0543d858f8ef26beb5b3f06458b0c6697a",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "1b98ca0a3b21e7d468600472a218d4ec30d42064",
"extension": "java",
"filename": "PretenureSizeThreshold.java",
"fork_events_count": 0,
"gha_created_at": "2017-11-14T23:37:47",
"gha_event_created_at": "2020-10-13T03:13:57",
"gha_language": "JavaScript",
"gha_license_id": "Apache-2.0",
"github_id": 110757618,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 516,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/main/java/vitualmachine/chapter5/PretenureSizeThreshold.java",
"provenance": "stack-edu-0031.json.gz:635816",
"repo_name": "qingziguanjun/StudyAndTest",
"revision_date": "2020-07-24T01:26:19",
"revision_id": "b1700d4543647ce152a5ccda01c1faef33ee2687",
"snapshot_id": "96e2bb88b7a1c386a41810aac7926b3911b30f79",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/qingziguanjun/StudyAndTest/b1700d4543647ce152a5ccda01c1faef33ee2687/src/main/java/vitualmachine/chapter5/PretenureSizeThreshold.java",
"visit_date": "2022-12-26T12:10:22.338109",
"added": "2024-11-18T22:07:31.151870+00:00",
"created": "2020-07-24T01:26:19",
"int_score": 2,
"score": 2.5,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0049.json.gz"
}
|
// Copyright © 2019 Sparebanken Vest
//
// 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.
//
// Note: Code is based on bank-vaults from Banzai Cloud
// (https://github.com/banzaicloud/bank-vaults)
package main
import (
"crypto"
"crypto/rsa"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"strings"
"syscall"
"time"
"github.com/SparebankenVest/azure-key-vault-to-kubernetes/pkg/akv2k8s/transformers"
vault "github.com/SparebankenVest/azure-key-vault-to-kubernetes/pkg/azurekeyvault/client"
akv "github.com/SparebankenVest/azure-key-vault-to-kubernetes/pkg/k8s/apis/azurekeyvault/v1"
clientset "github.com/SparebankenVest/azure-key-vault-to-kubernetes/pkg/k8s/client/clientset/versioned"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/rest"
)
const (
envLookupKey = "@azurekeyvault"
)
type injectorConfig struct {
namespace string
podName string
retryTimes int
waitTimeBetweenRetries int
useAuthService bool
skipArgsValidation bool
}
var config injectorConfig
var logger *log.Entry
type stop struct {
error
}
func formatLogger() {
log.SetFormatter(&log.TextFormatter{
DisableColors: true,
FullTimestamp: true,
})
logger = log.WithFields(log.Fields{
"component": "akv2k8s",
"application": "env-injector",
})
}
// Retry will wait for a duration, retry n times, return if succeed or fails
// Thanks to Nick Stogner: https://upgear.io/blog/simple-golang-retry-function/
func retry(attempts int, sleep time.Duration, fn func() error) error {
if err := fn(); err != nil {
if s, ok := err.(stop); ok {
// Return the original error for later checking
return s.error
}
if attempts--; attempts > 0 {
time.Sleep(sleep)
return retry(attempts, 2*sleep, fn)
}
return err
}
return nil
}
func getSecretFromKeyVault(azureKeyVaultSecret *akv.AzureKeyVaultSecret, query string, vaultService vault.Service) (string, error) {
var secretHandler EnvSecretHandler
switch azureKeyVaultSecret.Spec.Vault.Object.Type {
case akv.AzureKeyVaultObjectTypeSecret:
transformator, err := transformers.CreateTransformator(&azureKeyVaultSecret.Spec.Output)
if err != nil {
return "", err
}
secretHandler = NewAzureKeyVaultSecretHandler(azureKeyVaultSecret, query, *transformator, vaultService)
case akv.AzureKeyVaultObjectTypeCertificate:
secretHandler = NewAzureKeyVaultCertificateHandler(azureKeyVaultSecret, query, vaultService)
case akv.AzureKeyVaultObjectTypeKey:
secretHandler = NewAzureKeyVaultKeyHandler(azureKeyVaultSecret, query, vaultService)
case akv.AzureKeyVaultObjectTypeMultiKeyValueSecret:
secretHandler = NewAzureKeyVaultMultiKeySecretHandler(azureKeyVaultSecret, query, vaultService)
default:
return "", fmt.Errorf("azure key vault object type '%s' not currently supported", azureKeyVaultSecret.Spec.Vault.Object.Type)
}
return secretHandler.Handle()
}
type oauthToken struct {
Token string `json:"token"`
}
func createHTTPClientWithTrustedCA(host string) (*http.Client, error) {
caURL := fmt.Sprintf("http://%s/ca", host)
client := &http.Client{
Timeout: time.Second * 10,
}
res, err := client.Get(caURL)
if err != nil {
return nil, err
}
defer res.Body.Close()
caCert, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsConf := &tls.Config{
RootCAs: caCertPool,
}
tlsConf.BuildNameToCertificate()
tlsClient := &http.Client{
Timeout: time.Second * 10,
Transport: &http.Transport{
TLSClientConfig: tlsConf,
},
}
return tlsClient, nil
}
func getCredentials(useAuthService bool) (vault.AzureKeyVaultCredentials, error) {
if useAuthService {
authServiceAddress := viper.GetString("env_injector_auth_service")
if authServiceAddress == "" {
logger.Fatal(fmt.Errorf("cannot call auth service: env var ENV_INJECTOR_AUTH_SERVICE does not exist"))
}
caCertAddress := viper.GetString("env_injector_ca_cert")
if caCertAddress == "" {
logger.Fatal(fmt.Errorf("cannot get ca cert: env var ENV_INJECTOR_CA_CERT does not exist"))
}
client, err := createHTTPClientWithTrustedCA(caCertAddress)
if err != nil {
logger.Fatalf("failed to download ca cert, error: %+v", err)
}
url := fmt.Sprintf("https://%s/auth/%s/%s", authServiceAddress, config.namespace, config.podName)
logger.Infof("requesting azure key vault oauth token from %s", url)
res, err := client.Get(url)
if err != nil {
logger.Fatalf("request token failed from %s, error: %+v", url, err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to get credentials, %s", res.Status)
}
var creds vault.AzureKeyVaultOAuthCredentials
err = json.NewDecoder(res.Body).Decode(&creds)
if err != nil {
return nil, fmt.Errorf("failed to decode body, error %+v", err)
}
return creds, nil
}
creds, err := vault.NewAzureKeyVaultCredentialsFromEnvironment()
if err != nil {
return nil, fmt.Errorf("failed to get credentials for azure key vault, error %+v", err)
}
return creds, nil
}
func verifyPKCS(signature string, plaintext string, pubkey rsa.PublicKey) bool {
sig, _ := base64.StdEncoding.DecodeString(signature)
hashed := sha256.Sum256([]byte(plaintext))
err := rsa.VerifyPKCS1v15(&pubkey, crypto.SHA256, hashed[:], sig)
return err == nil
}
func parseRsaPublicKey(pubPem string) (*rsa.PublicKey, error) {
block, _ := pem.Decode([]byte(pubPem))
if block == nil {
return nil, fmt.Errorf("failed to parse PEM block containing public signing key")
}
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
switch pub := pub.(type) {
case *rsa.PublicKey:
return pub, nil
default:
break // fall through
}
return nil, fmt.Errorf("Key type is not RSA")
}
func validateArgsSignature(origArgs string) {
signatureB64 := viper.GetString("env_injector_args_signature")
if signatureB64 == "" {
logger.Fatalf("failed to get ENV_INJECTOR_ARGS_SIGNATURE")
}
signatureArray, err := base64.StdEncoding.DecodeString(signatureB64)
if err != nil {
logger.Fatalf("failed to decode base64 signature string, error: %+v", err)
}
signature := string(signatureArray)
pubKeyBase64 := viper.GetString("env_injector_args_key")
if pubKeyBase64 == "" {
logger.Fatalf("failed to get ENV_INJECTOR_ARGS_KEY, error: %+v", err)
}
bPubKey, err := base64.StdEncoding.DecodeString(pubKeyBase64)
if err != nil {
logger.Fatalf("failed to decode base64 public key string, error: %+v", err)
}
pubKey := string(bPubKey)
pubRsaKey, err := parseRsaPublicKey(pubKey)
if err != nil {
logger.Fatalf("failed to parse rsa public key to verify args: %+v", err)
}
if !verifyPKCS(signature, origArgs, *pubRsaKey) {
logger.Fatal("args does not match original args defined by env-injector")
}
}
func initConfig() {
viper.SetDefault("env_injector_retries", 3)
viper.SetDefault("env_injector_wait_before_retry", 3)
viper.SetDefault("env_injector_custom_auth", false)
viper.SetDefault("env_injector_use_auth_service", true)
viper.SetDefault("env_injector_skip_args_validation", false)
viper.AutomaticEnv()
}
func setLogLevel(logLevel string) {
if logLevel == "" {
logLevel = log.InfoLevel.String()
}
logrusLevel, err := log.ParseLevel(logLevel)
if err != nil {
log.Errorf("error setting log level: %s", err.Error())
}
log.SetLevel(logrusLevel)
}
func main() {
initConfig()
var origCommand string
var origArgs []string
var err error
logLevel := viper.GetString("env_injector_log_level")
setLogLevel(logLevel)
formatLogger()
logger.Debugf("azure key vault env injector initializing")
config = injectorConfig{
namespace: viper.GetString("env_injector_pod_namespace"),
podName: viper.GetString("HOSTNAME"),
retryTimes: viper.GetInt("env_injector_retries"),
waitTimeBetweenRetries: viper.GetInt("env_injector_wait_before_retry"),
useAuthService: viper.GetBool("env_injector_use_auth_service"),
skipArgsValidation: viper.GetBool("env_injector_skip_args_validation"),
}
if config.namespace == "" {
logger.Fatalf("current namespace not provided in environment variable ENV_INJECTOR_POD_NAMESPACE")
}
logger = logger.WithFields(log.Fields{
"namespace": config.namespace,
})
if config.useAuthService {
logger.Info("using sentralized akv2k8s auth service for authentiction with azure key vault")
} else {
logger.Debug("akv2k8s auth service not enabled - will look for azure key vault credentials locally")
}
if len(os.Args) == 1 {
logger.Fatal("no command is given, currently vault-env can't determine the entrypoint (command), please specify it explicitly")
} else {
origCommand, err = exec.LookPath(os.Args[1])
if err != nil {
logger.Fatalf("binary not found: %+v", err)
}
origArgs = os.Args[1:]
if !config.skipArgsValidation {
validateArgsSignature(strings.Join(origArgs, " "))
}
logger.Infof("found original container command to be %s %s", origCommand, origArgs)
}
creds, err := getCredentials(config.useAuthService)
if err != nil {
log.Fatalf("failed to get credentials, error: %+v", err)
}
vaultService := vault.NewService(creds)
logger.Debug("reading azurekeyvaultsecret's referenced in env variables")
cfg, err := rest.InClusterConfig()
if err != nil {
logger.Fatalf("error building kubeconfig: %s", err.Error())
}
azureKeyVaultSecretClient, err := clientset.NewForConfig(cfg)
if err != nil {
logger.Fatalf("error building azurekeyvaultsecret clientset: %+v", err)
}
environ := os.Environ()
for i, env := range environ {
split := strings.SplitN(env, "=", 2)
name := split[0]
value := split[1]
// e.g. my-akv-secret-name@azurekeyvault?some-sub-key
if strings.Contains(value, envLookupKey) {
// e.g. my-akv-secret-name?some-sub-key
logger.Debugf("found env var '%s' to get azure key vault secret for", name)
secretName := strings.Join(strings.Split(value, envLookupKey), "")
if secretName == "" {
logger.Fatalf("error extracting secret name from env variable '%s' with lookup value '%s' - not properly formatted", name, value)
}
var secretQuery string
if query := strings.Split(secretName, "?"); len(query) > 1 {
if len(query) > 2 {
logger.Fatalf("error extracting secret query from '%s' - has multiple query elements defined with '?' - only one supported", secretName)
}
secretName = query[0]
secretQuery = query[1]
logger.Debugf("found query in env var '%s', '%s'", value, secretQuery)
}
logger.Debugf("getting azurekeyvaultsecret resource '%s' from kubernetes", secretName)
keyVaultSecretSpec, err := azureKeyVaultSecretClient.AzurekeyvaultV1().AzureKeyVaultSecrets(config.namespace).Get(secretName, v1.GetOptions{})
if err != nil {
logger.Errorf("error getting azurekeyvaultsecret resource '%s', error: %s", secretName, err.Error())
logger.Infof("will retry getting azurekeyvaultsecret resource up to %d times, waiting %d seconds between retries", config.retryTimes, config.waitTimeBetweenRetries)
err = retry(config.retryTimes, time.Second*time.Duration(config.waitTimeBetweenRetries), func() error {
keyVaultSecretSpec, err = azureKeyVaultSecretClient.AzurekeyvaultV1().AzureKeyVaultSecrets(config.namespace).Get(secretName, v1.GetOptions{})
if err != nil {
logger.Errorf("error getting azurekeyvaultsecret resource '%s', error: %+v", secretName, err)
return err
}
logger.Infof("succeded getting azurekeyvaultsecret resource '%s'", secretName)
return nil
})
if err != nil {
logger.Fatalf("error getting azurekeyvaultsecret resource '%s', error: %s", secretName, err.Error())
}
}
logger.Debugf("getting secret value for '%s' from azure key vault, to inject into env var %s", keyVaultSecretSpec.Spec.Vault.Object.Name, name)
secret, err := getSecretFromKeyVault(keyVaultSecretSpec, secretQuery, vaultService)
if err != nil {
logger.Fatalf("failed to read secret '%s', error %+v", keyVaultSecretSpec.Spec.Vault.Object.Name, err)
}
if secret == "" {
logger.Fatalf("secret not found in azure key vault: %s", keyVaultSecretSpec.Spec.Vault.Object.Name)
} else {
logger.Infof("secret %s injected into env var %s for executable %s", keyVaultSecretSpec.Spec.Vault.Object.Name, name, origCommand)
environ[i] = fmt.Sprintf("%s=%s", name, secret)
}
}
}
logger.Infof("starting process %s %v with secrets in env vars", origCommand, origArgs)
err = syscall.Exec(origCommand, origArgs, environ)
if err != nil {
logger.Fatalf("failed to exec process '%s': %s", origCommand, err.Error())
}
logger.Info("azure key vault env injector successfully injected env variables with secrets")
}
|
460ddb1396f7d5d97b38a426024961ff2cc9d31e
|
{
"blob_id": "460ddb1396f7d5d97b38a426024961ff2cc9d31e",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-28T08:56:58",
"content_id": "2332baab523b66949f0a56ce445a6a6a8b4cc1a8",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d861b3fe6f09c79e553092998bd9033db5fea0f9",
"extension": "go",
"filename": "main.go",
"fork_events_count": 0,
"gha_created_at": "2020-05-11T08:58:45",
"gha_event_created_at": "2020-05-11T08:58:46",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 262990570,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 13468,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/cmd/azure-keyvault-env/main.go",
"provenance": "stack-edu-0015.json.gz:668039",
"repo_name": "howardjones/azure-key-vault-to-kubernetes",
"revision_date": "2020-04-21T11:10:55",
"revision_id": "f5a1741046688e472781da3daf3154253999f57a",
"snapshot_id": "aad76f3ea70900d50ab7a4838b4dfc906a411446",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/howardjones/azure-key-vault-to-kubernetes/f5a1741046688e472781da3daf3154253999f57a/cmd/azure-keyvault-env/main.go",
"visit_date": "2022-07-14T11:30:37.077396",
"added": "2024-11-18T21:32:59.238962+00:00",
"created": "2020-04-21T11:10:55",
"int_score": 2,
"score": 2.046875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0033.json.gz"
}
|
/*****************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
****************************************************************/
package org.apache.cayenne.conn;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.logging.Logger;
import javax.sql.ConnectionEvent;
import javax.sql.ConnectionEventListener;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.DataSource;
import javax.sql.PooledConnection;
import org.apache.cayenne.CayenneRuntimeException;
import org.apache.cayenne.di.ScopeEventListener;
import org.apache.cayenne.log.JdbcEventLogger;
/**
* PoolManager is a Cayenne implementation of a pooling DataSource.
*/
public class PoolManager implements ScopeEventListener, DataSource,
ConnectionEventListener {
/**
* Defines a maximum time in milliseconds that a connection request could wait in the
* connection queue. After this period expires, an exception will be thrown in the
* calling method.
*/
public static final int MAX_QUEUE_WAIT_DEFAULT = 20000;
/**
* An exception indicating that a connection request waiting in the queue
* timed out and was unable to obtain a connection.
*/
public static class ConnectionUnavailableException extends SQLException {
private static final long serialVersionUID = 1063973806941023165L;
public ConnectionUnavailableException(String message) {
super(message);
}
}
protected ConnectionPoolDataSource poolDataSource;
protected int minConnections;
protected int maxConnections;
protected String dataSourceUrl;
protected String jdbcDriver;
protected String password;
protected String userName;
protected List<PooledConnection> unusedPool;
protected List<PooledConnection> usedPool;
private PoolMaintenanceThread poolMaintenanceThread;
private boolean shuttingDown;
private long maxQueueWaitTime;
/**
* Creates new PoolManager using org.apache.cayenne.conn.PoolDataSource for an
* underlying ConnectionPoolDataSource.
*
* @deprecated since 4.0 This constructor causes implicit class loading that should avoided.
*/
@Deprecated
public PoolManager(String jdbcDriver, String dataSourceUrl, int minCons, int maxCons,
String userName, String password) throws SQLException {
this(jdbcDriver, dataSourceUrl, minCons, maxCons, userName, password, null, MAX_QUEUE_WAIT_DEFAULT);
}
/**
* @deprecated since 4.0 This constructor causes implicit class loading that should avoided.
*/
@Deprecated
public PoolManager(String jdbcDriver, String dataSourceUrl, int minCons, int maxCons,
String userName, String password, JdbcEventLogger logger, long maxQueueWaitTime) throws SQLException {
if (logger != null) {
DataSourceInfo info = new DataSourceInfo();
info.setJdbcDriver(jdbcDriver);
info.setDataSourceUrl(dataSourceUrl);
info.setMinConnections(minCons);
info.setMaxConnections(maxCons);
info.setUserName(userName);
info.setPassword(password);
logger.logPoolCreated(info);
}
this.jdbcDriver = jdbcDriver;
this.dataSourceUrl = dataSourceUrl;
DriverDataSource driverDS = new DriverDataSource(jdbcDriver, dataSourceUrl);
driverDS.setLogger(logger);
PoolDataSource poolDS = new PoolDataSource(driverDS);
init(poolDS, minCons, maxCons, userName, password, maxQueueWaitTime);
}
/**
* Creates new PoolManager with the specified policy for connection pooling and a
* ConnectionPoolDataSource object.
*
* @param poolDataSource data source for pooled connections
* @param minCons Non-negative integer that specifies a minimum number of open
* connections to keep in the pool at all times
* @param maxCons Non-negative integer that specifies maximum number of simultaneuosly
* open connections
* @throws SQLException if pool manager can not be created.
* @deprecated since 4.0 use {@link #PoolManager(ConnectionPoolDataSource, int, int, String, String, long)}
*/
public PoolManager(ConnectionPoolDataSource poolDataSource, int minCons, int maxCons,
String userName, String password) throws SQLException {
this(poolDataSource, minCons, maxCons, userName, password, PoolManager.MAX_QUEUE_WAIT_DEFAULT);
}
/**
* Creates new PoolManager with the specified policy for connection pooling and a
* ConnectionPoolDataSource object.
*
* @param poolDataSource data source for pooled connections
* @param minCons Non-negative integer that specifies a minimum number of open
* connections to keep in the pool at all times
* @param maxCons Non-negative integer that specifies maximum number of simultaneuosly
* open connections
* @throws SQLException if pool manager can not be created.
* @since 4.0
*/
public PoolManager(ConnectionPoolDataSource poolDataSource, int minCons, int maxCons,
String userName, String password, long maxQueueWaitTime) throws SQLException {
init(poolDataSource, minCons, maxCons, userName, password, maxQueueWaitTime);
}
/** Initializes pool. Normally called from constructor. */
protected void init(
ConnectionPoolDataSource poolDataSource,
int minCons,
int maxCons,
String userName,
String password,
long maxQueueWaitTime) throws SQLException {
// do sanity checks...
if (maxConnections < 0) {
throw new SQLException("Maximum number of connections can not be negative ("
+ maxCons
+ ").");
}
if (minConnections < 0) {
throw new SQLException("Minimum number of connections can not be negative ("
+ minCons
+ ").");
}
if (minConnections > maxConnections) {
throw new SQLException(
"Minimum number of connections can not be bigger then maximum.");
}
// init properties
this.userName = userName;
this.password = password;
this.minConnections = minCons;
this.maxConnections = maxCons;
this.poolDataSource = poolDataSource;
this.maxQueueWaitTime = maxQueueWaitTime;
// init pool... use linked lists to use the queue in the FIFO manner
usedPool = new LinkedList<PooledConnection>();
unusedPool = new LinkedList<PooledConnection>();
growPool(minConnections, userName, password);
startMaintenanceThread();
}
protected synchronized void startMaintenanceThread() {
disposeOfMaintenanceThread();
this.poolMaintenanceThread = new PoolMaintenanceThread(this);
this.poolMaintenanceThread.start();
}
/**
* Creates and returns new PooledConnection object, adding itself as a listener for
* connection events.
*/
protected PooledConnection newPooledConnection(String userName, String password)
throws SQLException {
PooledConnection connection = (userName != null) ? poolDataSource
.getPooledConnection(userName, password) : poolDataSource
.getPooledConnection();
connection.addConnectionEventListener(this);
return connection;
}
/**
* Closes all existing connections, drains the pool and stops the maintenance thread.
*
* @since 3.1
*/
public synchronized void shutdown() throws SQLException {
// disposing maintenance thread first to avoid any changes to pools
// during shutdown
disposeOfMaintenanceThread();
// using boolean variable instead of locking PoolManager instance due to
// possible deadlock during shutdown when one of connections locks its
// event listeners list trying to invoke locked PoolManager's listener methods
shuttingDown = true;
ListIterator<PooledConnection> unusedIterator = unusedPool.listIterator();
while (unusedIterator.hasNext()) {
PooledConnection con = unusedIterator.next();
// close connection
con.close();
// remove connection from the list
unusedIterator.remove();
}
// clean used connections
ListIterator<PooledConnection> usedIterator = usedPool.listIterator();
while (usedIterator.hasNext()) {
PooledConnection con = usedIterator.next();
// stop listening for connection events
con.removeConnectionEventListener(this);
// close connection
con.close();
// remove connection from the list
usedIterator.remove();
}
}
/**
* An implementation of {@link ScopeEventListener} that simply calls
* {@link #shutdown()}.
*
* @since 3.1
*/
public void beforeScopeEnd() {
try {
shutdown();
}
catch (SQLException e) {
throw new CayenneRuntimeException("Error while shutting down");
}
}
protected void disposeOfMaintenanceThread() {
if (poolMaintenanceThread != null) {
poolMaintenanceThread.shutdown();
poolMaintenanceThread = null;
}
}
/**
* @return true if at least one more connection can be added to the pool.
*/
protected synchronized boolean canGrowPool() {
return getPoolSize() < maxConnections;
}
/**
* Increases connection pool by the specified number of connections.
*
* @return the actual number of created connections.
* @throws SQLException if an error happens when creating a new connection.
*/
protected synchronized int growPool(
int addConnections,
String userName,
String password) throws SQLException {
int i = 0;
int startPoolSize = getPoolSize();
for (; i < addConnections && startPoolSize + i < maxConnections; i++) {
PooledConnection newConnection = newPooledConnection(userName, password);
unusedPool.add(newConnection);
}
return i;
}
protected synchronized void shrinkPool(int closeConnections) {
int idleSize = unusedPool.size();
for (int i = 0; i < closeConnections && i < idleSize; i++) {
PooledConnection con = unusedPool.remove(i);
try {
con.close();
}
catch (SQLException ex) {
// ignore
}
}
}
/**
* Returns maximum number of connections this pool can keep. This parameter when
* configured allows to limit the number of simultaneously open connections.
*/
public int getMaxConnections() {
return maxConnections;
}
public void setMaxConnections(int maxConnections) {
this.maxConnections = maxConnections;
}
/**
* Returns the absolute minimum number of connections allowed in this pool at any
* moment in time.
*/
public int getMinConnections() {
return minConnections;
}
public void setMinConnections(int minConnections) {
this.minConnections = minConnections;
}
/**
* Returns a database URL used to initialize this pool. Will return null if the pool
* was initialized with ConnectionPoolDataSource.
*/
public String getDataSourceUrl() {
return dataSourceUrl;
}
/**
* Returns a name of a JDBC driver used to initialize this pool. Will return null if
* the pool was initialized with ConnectionPoolDataSource.
*/
public String getJdbcDriver() {
return jdbcDriver;
}
/** Returns a data source password used to initialize this pool. */
public String getPassword() {
return password;
}
/** Returns a data source user name used to initialize this pool. */
public String getUserName() {
return userName;
}
/**
* Returns current number of connections.
*/
public synchronized int getPoolSize() {
return usedPool.size() + unusedPool.size();
}
/**
* Returns the number of connections obtained via this DataSource that are currently
* in use by the DataSource clients.
*/
public synchronized int getCurrentlyInUse() {
return usedPool.size();
}
/**
* Returns the number of connections maintained in the pool that are currently not
* used by any clients and are available immediately via <code>getConnection</code>
* method.
*/
public synchronized int getCurrentlyUnused() {
return unusedPool.size();
}
/**
* Returns connection from the pool using internal values of user name and password.
* Equivalent to calling:
* <p>
* <code>ds.getConnection(ds.getUserName(), ds.getPassword())</code>
* </p>
*/
public Connection getConnection() throws SQLException {
return getConnection(userName, password);
}
/** Returns connection from the pool. */
public synchronized Connection getConnection(String userName, String password)
throws SQLException {
if (shuttingDown) {
throw new SQLException("Pool manager is shutting down.");
}
PooledConnection pooledConnection = uncheckPooledConnection(userName, password);
try {
return uncheckConnection(pooledConnection);
}
catch (SQLException ex) {
try {
pooledConnection.close();
}
catch (SQLException ignored) {
}
// do one reconnect attempt...
pooledConnection = uncheckPooledConnection(userName, password);
try {
return uncheckConnection(pooledConnection);
}
catch (SQLException reconnectEx) {
try {
pooledConnection.close();
}
catch (SQLException ignored) {
}
throw reconnectEx;
}
}
}
private Connection uncheckConnection(PooledConnection pooledConnection)
throws SQLException {
Connection c = pooledConnection.getConnection();
// only do that on successfully unchecked connection...
usedPool.add(pooledConnection);
return c;
}
private PooledConnection uncheckPooledConnection(String userName, String password)
throws SQLException {
// wait for returned connections or the maintenance thread
// to bump the pool size...
if (unusedPool.size() == 0) {
// first try to open a new connection
if (canGrowPool()) {
return newPooledConnection(userName, password);
}
// can't open no more... will have to wait for others to return a connection
// note that if we were woken up
// before the full wait period expired, and no connections are
// available yet, go back to sleep. Otherwise we don't give a maintenance
// thread a chance to increase pool size
long waitTill = System.currentTimeMillis() + maxQueueWaitTime;
do {
try {
wait(maxQueueWaitTime);
}
catch (InterruptedException iex) {
// ignoring
}
} while (unusedPool.size() == 0 && (maxQueueWaitTime == 0 || waitTill > System.currentTimeMillis()));
if (unusedPool.size() == 0) {
throw new ConnectionUnavailableException(
"Can't obtain connection. Request timed out. Total used connections: "
+ usedPool.size());
}
}
// get first connection... lets cycle them in FIFO manner
return unusedPool.remove(0);
}
public int getLoginTimeout() throws java.sql.SQLException {
return poolDataSource.getLoginTimeout();
}
public void setLoginTimeout(int seconds) throws java.sql.SQLException {
poolDataSource.setLoginTimeout(seconds);
}
public PrintWriter getLogWriter() throws java.sql.SQLException {
return poolDataSource.getLogWriter();
}
public void setLogWriter(PrintWriter out) throws java.sql.SQLException {
poolDataSource.setLogWriter(out);
}
/**
* Returns closed connection to the pool.
*/
public synchronized void connectionClosed(ConnectionEvent event) {
if (shuttingDown) {
return;
}
// return connection to the pool
PooledConnection closedConn = (PooledConnection) event.getSource();
// remove this connection from the list of connections
// managed by this pool...
int usedInd = usedPool.indexOf(closedConn);
if (usedInd >= 0) {
usedPool.remove(usedInd);
unusedPool.add(closedConn);
// notify threads waiting for connections
notifyAll();
}
// else ....
// other possibility is that this is a bad connection, so just ignore its closing
// event,
// since it was unregistered in "connectionErrorOccurred"
}
/**
* Removes connection with an error from the pool. This method is called by
* PoolManager connections on connection errors to notify PoolManager that connection
* is in invalid state.
*/
public synchronized void connectionErrorOccurred(ConnectionEvent event) {
if (shuttingDown) {
return;
}
// later on we should analyze the error to see if this
// is fatal... right now just kill this PooledConnection
PooledConnection errorSrc = (PooledConnection) event.getSource();
// remove this connection from the list of connections
// managed by this pool...
int usedInd = usedPool.indexOf(errorSrc);
if (usedInd >= 0) {
usedPool.remove(usedInd);
}
else {
int unusedInd = unusedPool.indexOf(errorSrc);
if (unusedInd >= 0)
unusedPool.remove(unusedInd);
}
// do not close connection,
// let the code that catches the exception handle it
// ....
}
static class PoolMaintenanceThread extends Thread {
private boolean shouldDie;
private PoolManager pool;
PoolMaintenanceThread(PoolManager pool) {
super.setName("PoolManagerCleanup-" + pool.hashCode());
super.setDaemon(true);
this.pool = pool;
}
@Override
public void run() {
// periodically wakes up to check if the pool should grow or shrink
while (true) {
try {
// don't do it too often
sleep(600000);
}
catch (InterruptedException iex) {
// ignore...
}
synchronized (pool) {
// TODO: implement a smarter algorithm for pool management...
// right now it will simply close one connection if the count is
// above median and there are any idle connections.
if (shouldDie) {
break;
}
int unused = pool.getCurrentlyUnused();
int used = pool.getCurrentlyInUse();
int total = unused + used;
int median = pool.minConnections
+ 1
+ (pool.maxConnections - pool.minConnections)
/ 2;
if (unused > 0 && total > median) {
pool.shrinkPool(1);
}
}
}
}
/**
* Stops the maintenance thread.
*/
void shutdown() {
shouldDie = true;
interrupt();
}
}
/**
* @since 3.0
*/
// JDBC 4 compatibility under Java 1.5
public boolean isWrapperFor(Class<?> iface) throws SQLException {
throw new UnsupportedOperationException();
}
/**
* @since 3.0
*/
// JDBC 4 compatibility under Java 1.5
public <T> T unwrap(Class<T> iface) throws SQLException {
throw new UnsupportedOperationException();
}
/**
* @since 3.1 JDBC 4.1 compatibility under Java 1.5
*/
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
throw new UnsupportedOperationException();
}
}
|
99ae30b326da97d8f42b762230c4a62a87d24878
|
{
"blob_id": "99ae30b326da97d8f42b762230c4a62a87d24878",
"branch_name": "refs/heads/master",
"committer_date": "2015-02-19T14:22:00",
"content_id": "1a71024648bd5d88f04d09ff0b011313d3792b21",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "df7a13d9f7dcfa3119146841708ad8f4495436fa",
"extension": "java",
"filename": "PoolManager.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 21986,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/cayenne-server/src/main/java/org/apache/cayenne/conn/PoolManager.java",
"provenance": "stack-edu-0031.json.gz:298468",
"repo_name": "BereX/cayenne",
"revision_date": "2015-02-19T14:22:00",
"revision_id": "cb17347f7d57c9c7b3feb6afb6458eb6c1df1c81",
"snapshot_id": "555034cd6155130c261a6185a1e2f714ba5741a3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/BereX/cayenne/cb17347f7d57c9c7b3feb6afb6458eb6c1df1c81/cayenne-server/src/main/java/org/apache/cayenne/conn/PoolManager.java",
"visit_date": "2021-01-18T01:57:15.472155",
"added": "2024-11-18T22:41:14.346341+00:00",
"created": "2015-02-19T14:22:00",
"int_score": 2,
"score": 2.203125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0049.json.gz"
}
|
# The Gap on Gap: Tackling the Problem of Differing Data Distributions in Bias-Measuring Datasets
Code and data for the paper "The Gap on Gap: Tackling the Problem of Differing Data Distributions in Bias-Measuring Datasets"
Work has been accepted to AAAI 2021 conference and AFCI workshop at NeurIPS 2020 and can be found on [ArXiv](https://arxiv.org/abs/2011.01837).
For the full GAP dataset, please refer to the [original repository](https://github.com/google-research-datasets/gap-coreference).
Here, we follow their formatting and evaluation setup.
## Motivation
[Webster et al. 2018](https://arxiv.org/abs/1810.05201) observe that certain unbiased baselines obtain GAP bias scores significantly different from 1.0, the unbiased score. We identify the patterns within the dataset that cause this and propose an alternative weighted Wt-Bias metric that alleviates this data imbalance that might affect evaluated models. For details, please refer to our [paper](https://arxiv.org/abs/2011.01837).
## How to use
To evaluate your GAP outputs with Wt-bias metric, use the following command:
```python gap_scorer.py --gold_tsv gap-test.tsv --system_tsv [your output file] --weights linear_weights_trimmed.json```
```linear_weights_trimmed.json``` can be replaced with ```linear_weights.json``` to evaluate on W-bias instead.
Evaluation file was written in Python 3.
Annotations of all name spans in the test set can be found in json file ```gap-test-name-spans.json```
To re-compute the weights, please refer to the script ```compute_weights.sh``` which contains comments on all the necessary steps.
To re-compute the weights, Python 3 and Matlab with its Linprog package are required. Matlab version R2019b was used in our work.
## How to Cite
```
@inproceedings{kocijan21aaai,
title = {The Gap on Gap: Tackling the Problem of Differing Data Distributions in Bias-Measuring Datasets},
author = {Vid Kocijan and
Oana-Maria Camburu and
Thomas Lukasiewicz},
booktitle = {{Proceedings of the 35th AAAI}},
month = {February},
year = {2021}
}
|
e887f60720f8a0b46352f5f4197660369cdcb31d
|
{
"blob_id": "e887f60720f8a0b46352f5f4197660369cdcb31d",
"branch_name": "refs/heads/main",
"committer_date": "2021-01-18T10:09:24",
"content_id": "130127f79f2e487eb4252b7a6bdbba145d20b61d",
"detected_licenses": [
"MIT"
],
"directory_id": "6070a3fb029d7c6787a04c628b8f6c854ced713d",
"extension": "md",
"filename": "README.md",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 301458409,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2108,
"license": "MIT",
"license_type": "permissive",
"path": "/README.md",
"provenance": "stack-edu-markdown-0009.json.gz:121666",
"repo_name": "vid-koci/weightingGAP",
"revision_date": "2021-01-18T10:09:24",
"revision_id": "490e4bbf5319236f09ee87224db17d965a9f3e4e",
"snapshot_id": "988a4217287feedb6203c8865d38b81e94ddf2f3",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/vid-koci/weightingGAP/490e4bbf5319236f09ee87224db17d965a9f3e4e/README.md",
"visit_date": "2023-02-17T13:44:20.060068",
"added": "2024-11-18T23:07:16.281749+00:00",
"created": "2021-01-18T10:09:24",
"int_score": 3,
"score": 3.34375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0009.json.gz"
}
|
## `OPFCommunityFeeCollector`
Ocean Protocol Foundation Community Fee Collector contract
allows consumers to pay very small fee as part of the exchange of
data tokens with ocean token in order to support the community of
ocean protocol and provide a sustainble development.
### `constructor(address payable newCollector, address OPFOwnerAddress)` (public)
constructor
Called prior contract deployment. set the controller address and
the contract owner address
### `fallback()` (external)
fallback function
this is a default fallback function in which receives
the collected ether.
### `withdrawETH()` (external)
withdrawETH
transfers all the accumlated ether the collector address
### `withdrawToken(address tokenAddress)` (external)
withdrawToken
transfers all the accumlated tokens the collector address
### `changeCollector(address payable newCollector)` (external)
changeCollector
change the current collector address. Only owner can do that.
|
5d1238235ffbf1f5f3d836328e0b49388b46f77b
|
{
"blob_id": "5d1238235ffbf1f5f3d836328e0b49388b46f77b",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-01T10:21:35",
"content_id": "23cce511ae6760e71871d756e1febd2eed6097b5",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "98d73d2cb90f224c4f32098b26e11f364b9a33ee",
"extension": "md",
"filename": "OPFCommunityFeeCollector.md",
"fork_events_count": 0,
"gha_created_at": "2021-10-06T08:52:21",
"gha_event_created_at": "2021-10-06T08:52:22",
"gha_language": null,
"gha_license_id": "Apache-2.0",
"github_id": 414137378,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1019,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/docs/contracts/communityFee/OPFCommunityFeeCollector.md",
"provenance": "stack-edu-markdown-0012.json.gz:159240",
"repo_name": "magic990619/contracts",
"revision_date": "2021-10-01T10:21:35",
"revision_id": "f1b6630bc04eabc87a89b79f88ef81e60b557406",
"snapshot_id": "971c59d6aa601c6a3d676d5f14aef352a41d2279",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/magic990619/contracts/f1b6630bc04eabc87a89b79f88ef81e60b557406/docs/contracts/communityFee/OPFCommunityFeeCollector.md",
"visit_date": "2023-08-15T16:00:28.403214",
"added": "2024-11-18T22:17:40.016266+00:00",
"created": "2021-10-01T10:21:35",
"int_score": 3,
"score": 2.515625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0012.json.gz"
}
|
import React from 'react'
import { Grid, Container, Image } from 'semantic-ui-react'
import logo from '../images/logo.png'
import './index.css'
const MyNavigation = ({ children }) => (
<Container fluid className="navigation">
<Grid columns={3}>
<Grid.Column>
<div className='wrapper-menu'>
{children}
</div>
</Grid.Column>
<Grid.Column>
<div className='wrapper-logo'>
<Image src={logo} size='small' className="logo" />
</div>
</Grid.Column>
</Grid>
</Container>
)
export default MyNavigation
|
4d5dbb59621794995d52a779984ac09561ecb745
|
{
"blob_id": "4d5dbb59621794995d52a779984ac09561ecb745",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-27T14:07:56",
"content_id": "838a9dea3e4f0c67e0e98fea2232c151a660c2dc",
"detected_licenses": [
"MIT"
],
"directory_id": "e42ef41ea4cf494a4e236074d172138f36774f9d",
"extension": "js",
"filename": "index.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 146300816,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 585,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Navigationbar/index.js",
"provenance": "stack-edu-0044.json.gz:565219",
"repo_name": "michaeltamsil/galonku-frontend",
"revision_date": "2018-08-27T14:07:56",
"revision_id": "2b57aa8e973edbc29694add71733ab1278b1cb0f",
"snapshot_id": "9d4d9998af1bc8dd8865f6354358b9e13d07e576",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/michaeltamsil/galonku-frontend/2b57aa8e973edbc29694add71733ab1278b1cb0f/src/Navigationbar/index.js",
"visit_date": "2020-03-27T08:57:00.410212",
"added": "2024-11-19T01:51:39.351823+00:00",
"created": "2018-08-27T14:07:56",
"int_score": 2,
"score": 2.03125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0062.json.gz"
}
|
novamente = "S"
while novamente == "S":
mes = str(input("Digite o mês do seu aniversário: " )).lower()
tipo = ""
tipo2 = ""
while tipo == "":
if "jan" in mes or mes == "1":
tipo = "Ground"
elif "fev" in mes or mes == "2":
tipo = "Fighting"
elif "mar" in mes or mes == "3":
tipo = "Normal"
elif "abr" in mes or mes == "4":
tipo = "Steel"
elif "mai" in mes or mes == "5":
tipo = "Flying"
elif "jun" in mes or mes == "6":
tipo = "Psychic"
elif "jul" in mes or mes == "7":
tipo = "Normal"
elif "ago" in mes or mes == "8":
tipo = "Ground"
elif "set" in mes or mes == "9":
tipo = "Flying"
elif "out" in mes or mes == "10":
tipo = "Psychic"
elif "nov" in mes or mes == "11":
tipo = "Fighting"
elif "dez" in mes or mes == "12":
tipo = "Steel"
else:
print("Escolha Inválida")
mes = (input("Digite o mês do seu aniversário novamente: " )).lower()
dia = int(input("Digite o dia do seu aniversário: "))
while tipo2 == "":
if dia == 1 or dia == 9 or dia == 17:
tipo2 = tipo + " Eletric"
elif dia == 2 or dia == 10 or dia == 21:
tipo2 = tipo + " Fairy"
elif dia == 3 or dia == 24:
tipo2 = tipo + " Normal"
elif dia == 4 or dia == 12 or dia == 23:
tipo2 = tipo + " Dark"
elif dia == 5 or dia == 22 or dia == 27:
tipo2 = tipo + " Dragon"
elif dia == 6 or dia == 16 or dia == 29:
tipo2 = tipo + " Ice"
elif dia == 7 or dia == 18:
tipo2 = tipo + " Bug"
elif dia == 8 or dia == 19 or dia == 30:
tipo2 = tipo + " Poison"
elif dia == 11 or dia == 22:
tipo2 = tipo + " Ghost"
elif dia == 13 or dia == 26:
tipo2 = tipo + " Fire"
elif dia == 14 or dia == 25:
tipo2 = tipo + " Grass"
elif dia == 15 or dia == 28:
tipo2 = tipo + " Water"
elif dia == 20 or dia == 31:
tipo2 = tipo + " Rock"
else:
print("Escolha inválida")
dia = int(input("Digite o dia do seu aniversário novamente: "))
print(f"Seu tipo é: {tipo2}")
novamente = str(input("Gostaria de ver o seu tipo Pokémon novamente? S/N : ")).upper()
|
64c3c581991d04e4a3f51e81408bc87c83c10152
|
{
"blob_id": "64c3c581991d04e4a3f51e81408bc87c83c10152",
"branch_name": "refs/heads/main",
"committer_date": "2021-09-14T21:03:31",
"content_id": "8fd438ca6e1e26e263bcbca50727f081e94572ca",
"detected_licenses": [
"MIT"
],
"directory_id": "e6b7ff1cce26a2eebd7fec71abf2e855ed77c95d",
"extension": "py",
"filename": "Pokemon.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 365386229,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2545,
"license": "MIT",
"license_type": "permissive",
"path": "/Pokemon.py",
"provenance": "stack-edu-0063.json.gz:54718",
"repo_name": "gabrieloliveira2111/Gerador-de-tipo-pok-mon",
"revision_date": "2021-09-14T21:03:31",
"revision_id": "4cc8e2e0a4be093ae9cf24cf4b10d3c849ec569b",
"snapshot_id": "614c204429b60000b2ebd9bf01379008493a7571",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gabrieloliveira2111/Gerador-de-tipo-pok-mon/4cc8e2e0a4be093ae9cf24cf4b10d3c849ec569b/Pokemon.py",
"visit_date": "2023-08-08T02:54:28.319834",
"added": "2024-11-19T01:44:07.900047+00:00",
"created": "2021-09-14T21:03:31",
"int_score": 4,
"score": 3.609375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0081.json.gz"
}
|
/*
* Copyright (C) 2019-2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "level_zero/tools/source/tracing/tracing_imp.h"
__zedllexport ze_result_t __zecall
zeCommandListCreate_Tracing(ze_device_handle_t hDevice,
const ze_command_list_desc_t *desc,
ze_command_list_handle_t *phCommandList) {
ZE_HANDLE_TRACER_RECURSION(driver_ddiTable.core_ddiTable.CommandList.pfnCreate,
hDevice,
desc,
phCommandList);
ze_command_list_create_params_t tracerParams;
tracerParams.phDevice = &hDevice;
tracerParams.pdesc = &desc;
tracerParams.pphCommandList = &phCommandList;
L0::APITracerCallbackDataImp<ze_pfnCommandListCreateCb_t> apiCallbackData;
ZE_GEN_PER_API_CALLBACK_STATE(apiCallbackData, ze_pfnCommandListCreateCb_t, CommandList, pfnCreateCb);
return L0::APITracerWrapperImp(driver_ddiTable.core_ddiTable.CommandList.pfnCreate,
&tracerParams,
apiCallbackData.apiOrdinal,
apiCallbackData.prologCallbacks,
apiCallbackData.epilogCallbacks,
*tracerParams.phDevice,
*tracerParams.pdesc,
*tracerParams.pphCommandList);
}
__zedllexport ze_result_t __zecall
zeCommandListCreateImmediate_Tracing(
ze_device_handle_t hDevice,
const ze_command_queue_desc_t *altdesc,
ze_command_list_handle_t *phCommandList) {
ZE_HANDLE_TRACER_RECURSION(driver_ddiTable.core_ddiTable.CommandList.pfnCreateImmediate,
hDevice,
altdesc,
phCommandList);
ze_command_list_create_immediate_params_t tracerParams;
tracerParams.phDevice = &hDevice;
tracerParams.paltdesc = &altdesc;
tracerParams.pphCommandList = &phCommandList;
L0::APITracerCallbackDataImp<ze_pfnCommandListCreateImmediateCb_t> apiCallbackData;
ZE_GEN_PER_API_CALLBACK_STATE(apiCallbackData, ze_pfnCommandListCreateImmediateCb_t, CommandList, pfnCreateImmediateCb);
return L0::APITracerWrapperImp(driver_ddiTable.core_ddiTable.CommandList.pfnCreateImmediate,
&tracerParams,
apiCallbackData.apiOrdinal,
apiCallbackData.prologCallbacks,
apiCallbackData.epilogCallbacks,
*tracerParams.phDevice,
*tracerParams.paltdesc,
*tracerParams.pphCommandList);
}
__zedllexport ze_result_t __zecall
zeCommandListDestroy_Tracing(ze_command_list_handle_t hCommandList) {
ZE_HANDLE_TRACER_RECURSION(driver_ddiTable.core_ddiTable.CommandList.pfnDestroy, hCommandList);
ze_command_list_destroy_params_t tracerParams;
tracerParams.phCommandList = &hCommandList;
L0::APITracerCallbackDataImp<ze_pfnCommandListDestroyCb_t> apiCallbackData;
ZE_GEN_PER_API_CALLBACK_STATE(apiCallbackData, ze_pfnCommandListDestroyCb_t, CommandList, pfnDestroyCb);
return L0::APITracerWrapperImp(driver_ddiTable.core_ddiTable.CommandList.pfnDestroy,
&tracerParams,
apiCallbackData.apiOrdinal,
apiCallbackData.prologCallbacks,
apiCallbackData.epilogCallbacks,
*tracerParams.phCommandList);
}
__zedllexport ze_result_t __zecall
zeCommandListClose_Tracing(ze_command_list_handle_t hCommandList) {
ZE_HANDLE_TRACER_RECURSION(driver_ddiTable.core_ddiTable.CommandList.pfnClose, hCommandList);
ze_command_list_close_params_t tracerParams;
tracerParams.phCommandList = &hCommandList;
L0::APITracerCallbackDataImp<ze_pfnCommandListCloseCb_t> apiCallbackData;
ZE_GEN_PER_API_CALLBACK_STATE(apiCallbackData, ze_pfnCommandListCloseCb_t, CommandList, pfnCloseCb);
return L0::APITracerWrapperImp(driver_ddiTable.core_ddiTable.CommandList.pfnClose,
&tracerParams,
apiCallbackData.apiOrdinal,
apiCallbackData.prologCallbacks,
apiCallbackData.epilogCallbacks,
*tracerParams.phCommandList);
}
__zedllexport ze_result_t __zecall
zeCommandListReset_Tracing(ze_command_list_handle_t hCommandList) {
ZE_HANDLE_TRACER_RECURSION(driver_ddiTable.core_ddiTable.CommandList.pfnReset,
hCommandList);
ze_command_list_reset_params_t tracerParams;
tracerParams.phCommandList = &hCommandList;
L0::APITracerCallbackDataImp<ze_pfnCommandListResetCb_t> apiCallbackData;
ZE_GEN_PER_API_CALLBACK_STATE(apiCallbackData, ze_pfnCommandListResetCb_t, CommandList, pfnResetCb);
return L0::APITracerWrapperImp(driver_ddiTable.core_ddiTable.CommandList.pfnReset,
&tracerParams,
apiCallbackData.apiOrdinal,
apiCallbackData.prologCallbacks,
apiCallbackData.epilogCallbacks,
*tracerParams.phCommandList);
}
|
a9c491318c7412a8e54589ee23a95bfb3a349762
|
{
"blob_id": "a9c491318c7412a8e54589ee23a95bfb3a349762",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-16T17:55:54",
"content_id": "3165ab8875d0a259cb3506680149aeb4a4273510",
"detected_licenses": [
"MIT"
],
"directory_id": "ddde32ea983e7e85d74fc1d8ef18c513365b98b3",
"extension": "cpp",
"filename": "tracing_cmdlist_imp.cpp",
"fork_events_count": 0,
"gha_created_at": "2020-04-17T05:42:42",
"gha_event_created_at": "2020-04-17T05:42:42",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 256411858,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5532,
"license": "MIT",
"license_type": "permissive",
"path": "/level_zero/tools/source/tracing/tracing_cmdlist_imp.cpp",
"provenance": "stack-edu-0008.json.gz:73335",
"repo_name": "dkjiang2018/compute-runtime",
"revision_date": "2020-04-16T17:45:41",
"revision_id": "310947e6ddefc4bb9a7a268fc1ee8639155b730c",
"snapshot_id": "194a259fd550c81f852b932c87d9d21c02f2f7cb",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/dkjiang2018/compute-runtime/310947e6ddefc4bb9a7a268fc1ee8639155b730c/level_zero/tools/source/tracing/tracing_cmdlist_imp.cpp",
"visit_date": "2022-04-18T00:57:42.916437",
"added": "2024-11-18T20:40:38.666292+00:00",
"created": "2020-04-16T17:45:41",
"int_score": 2,
"score": 2.078125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0026.json.gz"
}
|
MQTTAgent_Unsubscribe proof
==============
This directory contains a memory safety proof for MQTTAgent_Unsubscribe.
The proof runs within 10 seconds on a t2.2xlarge. It provides complete coverage of:
* MQTTAgent_Unsubscribe()
* MQTTAgent_Init()
* addCommandToQueue()
* createAndAddCommand()
* validateStruct()
* isSpaceInPendingAckList()
For this proof, stubs are used for the implementation of functions in the following interfaces and
function types. Since the implementation for these functions will be provided by the applications,
the proof only will require stubs.
* MQTTAgentMessageInterface_t
* TransportInterface_t
* MQTTGetCurrentTimeFunc_t
* MQTTAgentIncomingPublishCallback_t
To run the proof.
-------------
* Add `cbmc`, `goto-cc`, `goto-instrument`, `goto-analyzer`, and `cbmc-viewer`
to your path.
* Run `make`.
* Open html/index.html in a web browser.
To use [`arpa`](https://github.com/awslabs/aws-proof-build-assistant) to simplify writing Makefiles.
-------------
* Run `make arpa` to generate a Makefile.arpa that contains relevant build information for the proof.
* Use Makefile.arpa as the starting point for your proof Makefile by:
1. Modifying Makefile.arpa (if required).
2. Including Makefile.arpa into the existing proof Makefile (add `sinclude Makefile.arpa` at the bottom of the Makefile, right before `include ../Makefile.common`).
|
53f9ad4083358aa115bfbfc4bd00b9a715cbe7bb
|
{
"blob_id": "53f9ad4083358aa115bfbfc4bd00b9a715cbe7bb",
"branch_name": "refs/heads/main",
"committer_date": "2021-07-23T00:10:09",
"content_id": "25311f61fdfd2d95b4fb5b7554e9b16ec702de5a",
"detected_licenses": [
"MIT"
],
"directory_id": "33ee29f447d5ae56d63bfa3eb5d2a3e8bb97195c",
"extension": "md",
"filename": "README.md",
"fork_events_count": 0,
"gha_created_at": "2021-03-18T20:47:22",
"gha_event_created_at": "2021-04-22T23:37:06",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 349212870,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1385,
"license": "MIT",
"license_type": "permissive",
"path": "/test/cbmc/proofs/MQTTAgent_Unsubscribe/README.md",
"provenance": "stack-edu-markdown-0006.json.gz:330260",
"repo_name": "muneebahmed10/coreMQTT-Agent",
"revision_date": "2021-07-23T00:10:09",
"revision_id": "abffd5c9eade2862a98d8d6df61a5754df65dc1a",
"snapshot_id": "a09923faa774a2000bfda5300f93f4ec3c8660da",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/muneebahmed10/coreMQTT-Agent/abffd5c9eade2862a98d8d6df61a5754df65dc1a/test/cbmc/proofs/MQTTAgent_Unsubscribe/README.md",
"visit_date": "2023-08-29T00:08:56.071381",
"added": "2024-11-19T00:43:41.587509+00:00",
"created": "2021-07-23T00:10:09",
"int_score": 3,
"score": 3.078125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0006.json.gz"
}
|
<?php
use Livro\Database\Record;
class Grupo extends Record
{
const TABLENAME = 'grupo';
}
|
8eb717d73889496cbed98c972b999b5ccc5c27f9
|
{
"blob_id": "8eb717d73889496cbed98c972b999b5ccc5c27f9",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-22T04:05:28",
"content_id": "190d463daf7119cedbc28ca63aaead0f15f44850",
"detected_licenses": [
"MIT"
],
"directory_id": "b35adfd8f482f06708569431c5d8b5ffc9d672ab",
"extension": "php",
"filename": "Grupo.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 222994859,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 96,
"license": "MIT",
"license_type": "permissive",
"path": "/App/Model/Grupo.php",
"provenance": "stack-edu-0046.json.gz:864264",
"repo_name": "andr3m0ur4/Aplicacao_Controle_de_Vendas",
"revision_date": "2021-09-22T04:05:28",
"revision_id": "ad37cacf199cda68ef8172ffeb4d38258b71c0c5",
"snapshot_id": "8b440600c1da9cf272083730f0b88df5983eb2fc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/andr3m0ur4/Aplicacao_Controle_de_Vendas/ad37cacf199cda68ef8172ffeb4d38258b71c0c5/App/Model/Grupo.php",
"visit_date": "2021-12-27T04:57:38.278989",
"added": "2024-11-18T21:33:04.200975+00:00",
"created": "2021-09-22T04:05:28",
"int_score": 2,
"score": 2.09375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0064.json.gz"
}
|
#ifndef ERIZOAPI_SYNTHETICINPUT_H_
#define ERIZOAPI_SYNTHETICINPUT_H_
#include <nan.h>
#include <media/SyntheticInput.h>
#include "MediaDefinitions.h"
#include "WebRtcConnection.h"
/*
* Wrapper class of erizo::SyntheticInput
*
* Represents a SyntheticInput connection.
*/
class SyntheticInput : public Nan::ObjectWrap {
public:
static NAN_MODULE_INIT(Init);
std::shared_ptr<erizo::SyntheticInput> me;
private:
SyntheticInput();
~SyntheticInput();
/*
* Constructor.
* Constructs a SyntheticInput
*/
static NAN_METHOD(New);
/*
* Closes the SyntheticInput.
* The object cannot be used after this call
*/
static NAN_METHOD(close);
/*
* Inits the SyntheticInput
* Returns true ready
*/
static NAN_METHOD(init);
/*
* Sets a MediaSink that is going to receive Audio Data
* Param: the MediaSink to send audio to.
*/
static NAN_METHOD(setAudioReceiver);
/*
* Sets a MediaSink that is going to receive Video Data
* Param: the MediaSink
*/
static NAN_METHOD(setVideoReceiver);
static NAN_METHOD(setFeedbackSource);
static Nan::Persistent<v8::Function> constructor;
};
#endif // ERIZOAPI_SYNTHETICINPUT_H_
|
f4aedae7e6d338409e4cd0b1124bc0e31be6e340
|
{
"blob_id": "f4aedae7e6d338409e4cd0b1124bc0e31be6e340",
"branch_name": "refs/heads/master",
"committer_date": "2017-11-01T04:53:53",
"content_id": "b68edddd1f9cd7d846c36be4e2ea868554a2576a",
"detected_licenses": [
"MIT"
],
"directory_id": "2db67e19655818c7ad4436838bda9e2daea65ace",
"extension": "h",
"filename": "SyntheticInput.h",
"fork_events_count": 3,
"gha_created_at": "2017-10-19T09:49:13",
"gha_event_created_at": "2017-11-01T04:53:55",
"gha_language": "C++",
"gha_license_id": null,
"github_id": 107528367,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1248,
"license": "MIT",
"license_type": "permissive",
"path": "/erizoAPI/SyntheticInput.h",
"provenance": "stack-edu-0007.json.gz:123391",
"repo_name": "nareix/licode",
"revision_date": "2017-11-01T04:53:53",
"revision_id": "936d5bda73bc085cb7bff505f8ef2aa4d4467a2f",
"snapshot_id": "b9b5910a31066fce2afefe5fcd2b34056b9d1758",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/nareix/licode/936d5bda73bc085cb7bff505f8ef2aa4d4467a2f/erizoAPI/SyntheticInput.h",
"visit_date": "2021-07-22T07:30:06.095658",
"added": "2024-11-18T22:51:07.695156+00:00",
"created": "2017-11-01T04:53:53",
"int_score": 2,
"score": 2.0625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0025.json.gz"
}
|
using System.Xml.Serialization;
namespace Comair.Console.MockUserCreator.XmlModels
{
/*
Licensed under the Apache License, Version 2.0
http://www.apache.org/licenses/LICENSE-2.0
*/
[XmlRoot(ElementName = "Header", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Header
{
[XmlAttribute(AttributeName = "s", Namespace = "http://www.w3.org/2000/xmlns/")]
public string S { get; set; }
}
}
|
1e27e5d873fae38dfd4bf42ceae8f5375c5420e9
|
{
"blob_id": "1e27e5d873fae38dfd4bf42ceae8f5375c5420e9",
"branch_name": "refs/heads/main",
"committer_date": "2021-11-12T22:25:08",
"content_id": "1a080ca8fe42578396aa114372b0af9586160b7c",
"detected_licenses": [
"MIT"
],
"directory_id": "2e84c5c786512bbcf595c4b71d0eef00fd5dfee1",
"extension": "cs",
"filename": "Header.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 418224860,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 440,
"license": "MIT",
"license_type": "permissive",
"path": "/Comair.Console.MockUserCreator/Comair.Console.MockUserCreator/XmlModels/Header.cs",
"provenance": "stack-edu-0012.json.gz:406404",
"repo_name": "mabochster/AspNetMicoroServices",
"revision_date": "2021-11-12T22:25:08",
"revision_id": "2cdb0c39e400f5a878ea4497af5fb0ccad1304b9",
"snapshot_id": "3186da8085531f5f4ec54f6ea0411dc3775d4ae0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mabochster/AspNetMicoroServices/2cdb0c39e400f5a878ea4497af5fb0ccad1304b9/Comair.Console.MockUserCreator/Comair.Console.MockUserCreator/XmlModels/Header.cs",
"visit_date": "2023-09-05T03:32:25.814130",
"added": "2024-11-18T22:38:51.357047+00:00",
"created": "2021-11-12T22:25:08",
"int_score": 2,
"score": 2.109375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0030.json.gz"
}
|
/****************************************************************************
* Copyright 2020, Optimizely, Inc. and contributors *
* *
* 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. *
***************************************************************************/
// Package middleware //
package middleware
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strings"
"sync"
"time"
"github.com/optimizely/agent/config"
"github.com/go-chi/render"
"golang.org/x/sync/errgroup"
)
// BatchResponse has the structure for the final response
type BatchResponse struct {
StartedAt time.Time `json:"startedAt"`
EndedAt time.Time `json:"endedAt"`
ErrorCount int `json:"errorCount"`
ResponseItems []ResponseCollector `json:"response"`
lock sync.Mutex
}
// NewBatchResponse constructs a BatchResponse with default values
func NewBatchResponse() *BatchResponse {
return &BatchResponse{
StartedAt: time.Now(),
ResponseItems: make([]ResponseCollector, 0),
}
}
func (br *BatchResponse) append(col ResponseCollector) {
br.lock.Lock()
defer br.lock.Unlock()
if col.Status != http.StatusOK {
br.ErrorCount++
}
br.ResponseItems = append(br.ResponseItems, col)
br.EndedAt = time.Now()
}
// ResponseCollector collects responses for the writer
type ResponseCollector struct {
Status int `json:"status"`
RequestID string `json:"requestID"`
OperationID string `json:"operationID"`
Method string `json:"method"`
URL string `json:"url"`
Body interface{} `json:"body"`
StartedAt time.Time `json:"startedAt"`
EndedAt time.Time `json:"endedAt"`
headerMap http.Header
}
// NewResponseCollector constructs a ResponseCollector with default values
func NewResponseCollector(op BatchOperation) ResponseCollector {
return ResponseCollector{
headerMap: make(http.Header),
Method: op.Method,
URL: op.URL,
OperationID: op.OperationID,
StartedAt: time.Now(),
Status: http.StatusOK,
}
}
// WriteHeader sets the status code
func (rec *ResponseCollector) WriteHeader(code int) {
rec.Status = code
}
// Write is just the collector for BatchResponse
func (rec *ResponseCollector) Write(b []byte) (int, error) {
var data interface{}
if err := json.Unmarshal(b, &data); err != nil {
return 0, err
}
rec.Body = data
if header, ok := rec.headerMap["X-Request-Id"]; ok {
rec.RequestID = header[0]
}
return 0, nil
}
// Header returns header map
func (rec *ResponseCollector) Header() http.Header {
return rec.headerMap
}
// BatchOperation defines a single request within a batch
type BatchOperation struct {
Method string `json:"method"`
URL string `json:"url"`
OperationID string `json:"operationID"`
Body map[string]interface{} `json:"body"`
Params map[string]string `json:"params"`
Headers map[string]string `json:"headers"`
}
// BatchRequest is the original request that is used for batching
type BatchRequest struct {
Operations []BatchOperation `json:"operations"`
}
func makeRequest(next http.Handler, r *http.Request, op BatchOperation) ResponseCollector {
col := NewResponseCollector(op)
bytesBody, err := json.Marshal(op.Body)
if err != nil {
col.Status = http.StatusNotFound
GetLogger(r).Error().Err(err).Msg("cannot convert operation body to bytes for operation id: " + op.OperationID)
return col
}
reader := bytes.NewReader(bytesBody)
opReq, err := http.NewRequest(op.Method, op.URL, reader)
if err != nil {
col.Status = http.StatusBadRequest
GetLogger(r).Error().Err(err).Msg("cannot make a new request for operation id: " + op.OperationID)
return col
}
for headerKey, headerValue := range op.Headers {
opReq.Header.Add(headerKey, headerValue)
col.headerMap[headerKey] = []string{headerValue}
}
for paramKey, paramValue := range op.Params {
values := opReq.URL.Query()
values.Add(paramKey, paramValue)
opReq.URL.RawQuery = values.Encode()
}
next.ServeHTTP(&col, opReq)
col.EndedAt = time.Now()
return col
}
// BatchRouter intercepts requests for the given url to return a StatusOK.
func BatchRouter(batchRequests config.BatchRequestsConfig) func(http.Handler) http.Handler {
f := func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" && strings.HasSuffix(strings.ToLower(r.URL.Path), "/batch") {
decoder := json.NewDecoder(r.Body)
var req BatchRequest
err := decoder.Decode(&req)
if err != nil {
http.Error(w, `{"error": "cannot decode the operation body"}`, http.StatusBadRequest)
return
}
if len(req.Operations) > batchRequests.OperationsLimit {
http.Error(w, fmt.Sprintf(`{"error": "too many operations, exceeding %d operations"}`, batchRequests.OperationsLimit), http.StatusUnprocessableEntity)
return
}
batchRes := NewBatchResponse()
var eg, ctx = errgroup.WithContext(r.Context())
ch := make(chan struct{}, batchRequests.MaxConcurrency)
for _, op := range req.Operations {
op := op
ch <- struct{}{}
eg.Go(func() error {
defer func() { <-ch }()
select {
case <-ctx.Done():
GetLogger(r).Error().Err(ctx.Err()).Msg("terminating request")
return ctx.Err()
default:
col := makeRequest(next, r, op)
// Append response item
batchRes.append(col)
}
return nil
})
}
if err := eg.Wait(); err != nil {
http.Error(w, `{"error": "problem with making operation requests"}`, http.StatusBadRequest)
return
}
render.JSON(w, r, batchRes)
return
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
return f
}
|
e828320207f88f84d514416374b749a137149ff2
|
{
"blob_id": "e828320207f88f84d514416374b749a137149ff2",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-10T15:20:16",
"content_id": "5df658314acba2dcaae51c67eddf0a319b11e9bd",
"detected_licenses": [
"BSD-3-Clause",
"MIT",
"Apache-2.0"
],
"directory_id": "cecd2015c5edf31d775dbc913587752f17d80210",
"extension": "go",
"filename": "batch.go",
"fork_events_count": 29,
"gha_created_at": "2019-07-02T20:37:25",
"gha_event_created_at": "2023-09-12T10:45:04",
"gha_language": "Go",
"gha_license_id": "Apache-2.0",
"github_id": 194931406,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 6693,
"license": "BSD-3-Clause,MIT,Apache-2.0",
"license_type": "permissive",
"path": "/pkg/middleware/batch.go",
"provenance": "stack-edu-0017.json.gz:418335",
"repo_name": "optimizely/agent",
"revision_date": "2023-08-10T15:20:16",
"revision_id": "bf234067ab705b5e14f30b8110e40705880f170f",
"snapshot_id": "f8e243083e94047f4b561c9f7198cf66b29e13d2",
"src_encoding": "UTF-8",
"star_events_count": 27,
"url": "https://raw.githubusercontent.com/optimizely/agent/bf234067ab705b5e14f30b8110e40705880f170f/pkg/middleware/batch.go",
"visit_date": "2023-08-14T02:18:19.344243",
"added": "2024-11-19T00:22:09.925962+00:00",
"created": "2023-08-10T15:20:16",
"int_score": 2,
"score": 2.265625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0035.json.gz"
}
|
#include"Http.hpp"
int Http::g_epollfd = -1;
void Http::init(int sockfd, const sockaddr_in& addr, bool triggerET)
{
if (sockfd <= 0)
{
ERROR(LOG({"Bad sockfd!"}));
exit(-1);
}
m_sockfd = sockfd;
m_addr = addr;
m_triggerET = triggerET;
epollAddfd(g_epollfd, m_sockfd, triggerET);
init();
std::cout << "初始化http\n";
}
void Http::init()
{
m_parseState = PARSE_REQUEST_LINE;
m_method = GET;
m_accountState = ACCOUNT_NOTEXIST;
m_fileMmap = nullptr;
memset(m_readBuf, '\0', READBUF_SIZE);
memset(m_writeBuf, '\0', WRITEBUF_SIZE);
m_readPara.clear();
m_writePara.clear();
m_httpMsg.clear();
}
bool Http::Read()
{
int size = 0;
if (m_readPara.readIndex >= READBUF_SIZE)
{
ERROR(LOG({__FILE__, ": Reading buffer is full!"}));
return false;
}
if (m_triggerET)
{
while (true)
{
size = read(m_sockfd, m_readBuf + m_readPara.readIndex, READBUF_SIZE);
if (size == -1)
{
if (errno == EWOULDBLOCK || errno == EAGAIN)
break;
return false;
}
else if (size == 0)
return true;
m_readPara.readIndex += size;
}
DEBUG(LOG({__FILE__, ": ", std::to_string(m_readPara.readIndex)}));
INFO(LOG({__FILE__, ": \n", m_readBuf}));
return true;
}
size = read(m_sockfd, m_readBuf, READBUF_SIZE);
if (size < 0)
return false;
m_readPara.readIndex += size;
INFO(LOG({__FILE__, ": \n", m_readBuf}));
return true;
}
Http::LINE_STATE Http::parseLine()
{
char temp;
for (; m_readPara.checkIndex < m_readPara.readIndex; ++m_readPara.checkIndex)
{
temp = m_readBuf[m_readPara.checkIndex];
if (temp == '\r')
{
if ((m_readPara.checkIndex + 1) == m_readPara.readIndex)
return LINE_UNKNOWN;
else if (m_readBuf[m_readPara.checkIndex + 1] == '\n')
{
m_readBuf[m_readPara.checkIndex++] = '\0';
m_readBuf[m_readPara.checkIndex++] = '\0';
return LINE_OK;
}
return LINE_BAD;
}
else if (temp == '\n')
{
if (m_readPara.checkIndex > 1 && m_readBuf[m_readPara.checkIndex - 1] == '\r')
{
m_readBuf[m_readPara.checkIndex - 1] = '\0';
m_readBuf[m_readPara.checkIndex++] = '\0';
return LINE_OK;
}
return LINE_BAD;
}
}
return LINE_UNKNOWN;
}
Http::RESPOND_STATE Http::stateTransform()
{
while (m_parseState == PARSE_PREV_CONTENT || m_parseState == PARSE_CONTENT || parseLine() == LINE_OK)
{
auto text = [&]()-> char* {
return m_readBuf + m_readPara.line;}();
m_readPara.line = m_readPara.checkIndex;
switch (m_parseState)
{
case PARSE_REQUEST_LINE:
{
auto ret = parseRequestLine(text);
if (ret == BAD_REQUEST)
return BAD_REQUEST;
break;
}
case PARSE_HEADER:
{
auto ret = parseHeader(text);
if (ret == BAD_REQUEST)
return BAD_REQUEST;
else if (ret == GET_REQUEST)
return handleRequest();
break;
}
case PARSE_PREV_CONTENT:
{
m_parseState = PARSE_CONTENT;
break;
}
case PARSE_CONTENT:
{
auto ret = parseContent(text);
if (ret == GET_REQUEST)
return handleRequest();
break;
}
default:
return INTERNAL_ERROR;
}
}
return NO_REQUEST;
}
Http::RESPOND_STATE Http::parseRequestLine(string text)
{
DEBUG(LOG({__FILE__, ": ", text}));
string str;
if (text[0] == 'G')
{
str = text.substr(0, 3);
if (str == "GET" && text[3] == ' ')
m_method = GET;
else
return BAD_REQUEST;
}
else if (text[0] == 'P')
{
str = text.substr(0, 4);
if (str == "POST" && text[4] == ' ')
m_method = POST;
else
return BAD_REQUEST;
}
else
return BAD_REQUEST;
INFO(LOG({__FILE__, ": PARSE method ", str}));
text.erase(0, str.length() + 1);
str.clear();
auto ret = text.find(' ');
if (ret >= text.size())
return BAD_REQUEST;
str = text.substr(ret + 1, 8);
if (str == "HTTP/1.0" || str == "HTTP/1.1")
{
m_httpMsg.Version = str;
INFO(LOG({__FILE__, ": PARSE version ", str}));
}
else
return BAD_REQUEST;
text.erase(ret, 9);
str.clear();
ret = text.rfind('/');
if (ret >= text.length())
return BAD_REQUEST;
text.erase(0, ret);
if (text.length() > 0)
{
if (m_method == GET)
{
if (text.length() == 1)
m_httpMsg.URL = "index.html";
else
m_httpMsg.URL.assign(text.begin() + 1, text.end());
INFO(LOG({__FILE__, ":PARSE URL ", m_httpMsg.URL}));
}
m_parseState = PARSE_HEADER;
return NO_REQUEST;
}
else
return BAD_REQUEST;
}
Http::RESPOND_STATE Http::parseHeader(string text)
{
INFO(LOG({__FILE__, ": ", text}));
if (text.length() == 0)
{
if (m_method == GET)
return GET_REQUEST;
else
{
m_parseState = PARSE_PREV_CONTENT;
return NO_REQUEST;
}
}
string str = text.substr(0, 4);
if (str == "Host" && text[4] == ':')
{
m_httpMsg.Host.assign(text.begin() + 6, text.end());
INFO(LOG({__FILE__, ":PARSE Host ", m_httpMsg.Host}));
return NO_REQUEST;
}
str = text.substr(0, 14);
if (str == "Content-Length" && text[14] == ':')
{
str.assign(text.begin() + 16, text.end());
char* end;
m_httpMsg.ContentLen = static_cast<int>(std::strtol(str.c_str(), &end, 0));
INFO(LOG({__FILE__, ":PARSE Content-Length ", str}));
return NO_REQUEST;
}
return NO_REQUEST;
}
Http::RESPOND_STATE Http::parseContent(string text)
{
if (text.size() == m_httpMsg.ContentLen)
{
m_httpMsg.Content = text;
INFO(LOG({__FILE__, ":PARSE Content ", text}));
m_readPara.checkIndex = m_readPara.readIndex;
return GET_REQUEST;
}
m_readPara.checkIndex = m_readPara.readIndex;
memset(m_readBuf, '\0', READBUF_SIZE);
return NO_REQUEST;
}
Http::RESPOND_STATE Http::handleRequest()
{
m_requestFile = getcwd(NULL, 0);
m_requestFile += "/html/";
if (m_method == GET && m_httpMsg.ContentLen == 0)
m_requestFile += m_httpMsg.URL;
else if (m_method == POST && m_httpMsg.ContentLen != 0)
{
int ret = m_httpMsg.Content.find("submit=");
if (ret == 0)
{
m_httpMsg.Content.erase(0, 7);
m_requestFile += m_httpMsg.Content + ".html";
}
else
{
ret = m_httpMsg.Content.find("User=");
string temp(m_httpMsg.Content.begin(), m_httpMsg.Content.begin() + ret);
m_httpMsg.Content.erase(0, ret + 5);
ret = m_httpMsg.Content.find("&password=");
string name(m_httpMsg.Content.begin(), m_httpMsg.Content.begin()+ret);
string password(m_httpMsg.Content.begin() + ret + 10, m_httpMsg.Content.end());
pair<string, string> account;
m_accountState = checkAccount(name, password, account);
if (temp == "register")
registerSQL(name, password);
else if (temp == "load")
{
if (password == account.second)
m_requestFile += "homepage.html";
else
m_requestFile += "Reload.html";
}
else
return NO_REQUEST;
}
}
else
return BAD_REQUEST;
INFO(LOG({__FILE__, ":FILE ", m_requestFile}));
if (stat(m_requestFile.c_str(), &m_fileStat) < 0)
return NO_RESOURCE;
if (S_ISDIR(m_fileStat.st_mode))
return BAD_REQUEST;
if (!(m_fileStat.st_mode & S_IROTH))
return FORBIDDEN_REQUEST;
int fd = open(m_requestFile.c_str(), O_RDONLY);
m_fileMmap = static_cast<char*>(mmap(0, m_fileStat.st_size, PROT_READ, MAP_PRIVATE, fd, 0));
close(fd);
return FILE_REQUEST;
}
Http::SQL_RES Http::checkAccount(string& name, string& passwd, pair<string, string>& account)
{
shared_ptr<AbstractFactory> redisFac(new FactoryRedis);
shared_ptr<AbstractFactory> mysqlFac(new FactoryMysql);
if (!redisFac->createSQL()->selectFromSQL(name, account))
{
if (!mysqlFac->createSQL()->selectFromSQL(name, account))
return ACCOUNT_NOTEXIST;
}
return ACCOUNT_EXIST;
}
void Http::registerSQL(string& name, string& password)
{
if (m_accountState == ACCOUNT_EXIST)
m_requestFile += "Reregister.html";
else
{
shared_ptr<AbstractFactory> redisFac(new FactoryRedis);
string query("HSET webuser ");
query = query + name + " " + password;
if (!redisFac->createSQL()->IDUIntoSQL(query))
{
WARN(LOG({__FILE__, ": Cannot insert into Redis"}));
m_requestFile += "Reregister.html";
return;
}
shared_ptr<AbstractFactory> mysqlFac(new FactoryMysql);
query = "insert into webuser(name, passwd) values('" + name +"','" + password + "')";
if (!mysqlFac->createSQL()->IDUIntoSQL(query))
{
WARN(LOG({__FILE__, ": Cannot insert into Redis"}));
m_requestFile += "Reregister.html";
return;
}
m_requestFile += "load.html";
}
}
void Http::run()
{
auto ret = stateTransform();
DEBUG(LOG({__FILE__, ": ParseHttpMsg result ", std::to_string(ret)}));
if (ret == NO_REQUEST)
{
epollModfd(g_epollfd, m_sockfd, EPOLLIN, m_triggerET);
init();
return;
}
bool writeRes = writeResponse(ret);
std::cout << "wirteRES: " << writeRes << std::endl;
if (!writeRes)
{
if (m_sockfd != -1)
{
epollDelfd(g_epollfd, m_sockfd);
m_sockfd = -1;
return;
}
}
epollModfd(g_epollfd, m_sockfd, EPOLLOUT, m_triggerET);
DEBUG(LOG({__FILE__, ": ready to send to client!"}));
}
bool Http::writeResponse(RESPOND_STATE state)
{
switch (state)
{
case INTERNAL_ERROR:
{
writeResponseLine(500, "Internal Server Error");
writeBlank();
break;
}
case BAD_REQUEST:
{
writeResponseLine(400, "Bad Request");
writeBlank();
break;
}
case FORBIDDEN_REQUEST:
{
writeResponseLine(403, "Forbidden");
writeBlank();
break;
}
case NO_RESOURCE:
{
writeResponseLine(404, "Not Found");
writeBlank();
break;
}
case FILE_REQUEST:
{
writeResponseLine(200, "OK");
std::cout << "写头部\n" << m_fileStat.st_size << std::endl;
if (m_fileStat.st_size != 0)
{
writeContentType();
writeContentLen(m_fileStat.st_size);
writeBlank();
m_writePara.iov[0].iov_base = m_writeBuf;
m_writePara.iov[0].iov_len = m_writePara.writeIndex;
m_writePara.iov[1].iov_base = m_fileMmap;
m_writePara.iov[1].iov_len = m_fileStat.st_size;
m_writePara.bufSize = m_writePara.writeIndex + m_fileStat.st_size;
INFO(LOG({__FILE__, ": Response\n", m_writeBuf}));
return true;
}
else
{
writeContentLen(0);
writeBlank();
break;
}
}
default:
return false;
}
m_writePara.iocNum = 1;
m_writePara.iov[0].iov_base = m_writeBuf;
m_writePara.iov[0].iov_len = m_writePara.writeIndex;
m_writePara.bufSize = m_writePara.writeIndex;
return true;
}
void Http::writeHttpResponse(const char* format, ...)
{
if (m_writePara.writeIndex >= WRITEBUF_SIZE)
{
ERROR(LOG({__FILE__, ": Http Response'size is too long"}));
return;
}
va_list arg;
va_start(arg, format);
int len = vsnprintf(m_writeBuf + m_writePara.writeIndex, WRITEBUF_SIZE - m_writePara.writeIndex - 1, format, arg);
if (len >= (WRITEBUF_SIZE - m_writePara.writeIndex - 1))
{
ERROR(LOG({__FILE__, ": Http Response'size is too long"}));
va_end(arg);
return;
}
m_writePara.writeIndex += len;
va_end(arg);
}
void Http::writeResponseLine(int state, const char* description)
{
writeHttpResponse("%s %d %s\r\n", "HTTP/1.1", state, description);
}
void Http::writeContentType()
{
writeHttpResponse("Content-Type: %s\r\n", "text/html; charset=UTF-8; image/x-icon; image/png; audio/*");
}
void Http::writeContentLen(int len)
{
writeHttpResponse("Content-Length: %d\r\n", len);
}
void Http::writeBlank()
{
writeHttpResponse("%s", "\r\n");
}
void Http::writeContent(const char* text)
{
writeHttpResponse("%s", text);
}
void Http::releaseMmap()
{
if (m_fileMmap != nullptr)
{
munmap(m_fileMmap, m_fileStat.st_size);
m_fileMmap = nullptr;
}
}
bool Http::Write()
{
int index = 0;
if (m_writePara.bufSize == 0)
{
epollModfd(g_epollfd, m_sockfd, EPOLLIN, m_triggerET);
init();
return true;
}
while (true)
{
index = writev(m_sockfd, m_writePara.iov, m_writePara.iocNum);
if (index < 0)
{
if (errno == EWOULDBLOCK || errno == EAGAIN)
{
epollModfd(g_epollfd, m_sockfd, EPOLLOUT, m_triggerET);
return true;
}
else
{
releaseMmap();
return false;
}
}
m_writePara.sendMark += index;
m_writePara.bufSize -= index;
if (m_writePara.bufSize <= 0)
{
INFO(LOG({__FILE__, ": Already send to client"}));
releaseMmap();
epollModfd(g_epollfd, m_sockfd, EPOLLIN, m_triggerET);
init();
return true;
}
if (m_writePara.sendMark >= m_writePara.iov[0].iov_len)
{
m_writePara.iov[0].iov_len = 0;
m_writePara.iov[1].iov_base = m_fileMmap + m_writePara.sendMark - m_writePara.writeIndex;
m_writePara.iov[1].iov_len = m_writePara.bufSize;
}
else
{
m_writePara.iov[0].iov_base = m_writeBuf + m_writePara.sendMark;
m_writePara.iov[0].iov_len -= m_writePara.sendMark;
}
}
}
|
0866b44a077e6b0378de971dacecf823ddbde342
|
{
"blob_id": "0866b44a077e6b0378de971dacecf823ddbde342",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-26T04:50:49",
"content_id": "0c1226806569b326d737397555076acaea47b61a",
"detected_licenses": [
"MIT"
],
"directory_id": "02112f9d63df4eabd9e342433fa71bf02c028830",
"extension": "cpp",
"filename": "Http.cpp",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 357199427,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 15336,
"license": "MIT",
"license_type": "permissive",
"path": "/http/Http.cpp",
"provenance": "stack-edu-0006.json.gz:101152",
"repo_name": "useryoung-2019/MyHttpServer",
"revision_date": "2021-06-26T04:50:49",
"revision_id": "ce23c1bf161edba08a82d54de6693167a8917d18",
"snapshot_id": "0ff21540c03c42d901c3157f10abee26f3e55862",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/useryoung-2019/MyHttpServer/ce23c1bf161edba08a82d54de6693167a8917d18/http/Http.cpp",
"visit_date": "2023-06-01T08:32:06.364444",
"added": "2024-11-18T23:27:53.983865+00:00",
"created": "2021-06-26T04:50:49",
"int_score": 2,
"score": 2.171875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0024.json.gz"
}
|
package scw
import (
"errors"
"os"
"path/filepath"
)
const (
// XDG wiki: https://wiki.archlinux.org/index.php/XDG_Base_Directory
xdgConfigDirEnv = "XDG_CONFIG_HOME"
xdgCacheDirEnv = "XDG_CACHE_HOME"
unixHomeDirEnv = "HOME"
windowsHomeDirEnv = "USERPROFILE"
defaultConfigFileName = "config.yaml"
)
var (
// ErrNoHomeDir errors when no user directory is found
ErrNoHomeDir = errors.New("user home directory not found")
)
// GetCacheDirectory returns the default cache directory.
// Cache directory is based on the following priority order:
// - $SCW_CACHE_DIR
// - $XDG_CACHE_HOME/scw
// - $HOME/.cache/scw
// - $USERPROFILE/.cache/scw
func GetCacheDirectory() string {
cacheDir := ""
switch {
case os.Getenv(ScwCacheDirEnv) != "":
cacheDir = os.Getenv(ScwCacheDirEnv)
case os.Getenv(xdgCacheDirEnv) != "":
cacheDir = filepath.Join(os.Getenv(xdgCacheDirEnv), "scw")
case os.Getenv(unixHomeDirEnv) != "":
cacheDir = filepath.Join(os.Getenv(unixHomeDirEnv), ".cache", "scw")
case os.Getenv(windowsHomeDirEnv) != "":
cacheDir = filepath.Join(os.Getenv(windowsHomeDirEnv), ".cache", "scw")
default:
// TODO: fallback on local folder?
}
// Clean the cache directory path when exiting the function
return filepath.Clean(cacheDir)
}
// GetConfigPath returns the default path.
// Default path is based on the following priority order:
// - $SCW_CONFIG_PATH
// - $XDG_CONFIG_HOME/scw/config.yaml
// - $HOME/.config/scw/config.yaml
// - $USERPROFILE/.config/scw/config.yaml
func GetConfigPath() string {
configPath := os.Getenv(ScwConfigPathEnv)
if configPath == "" {
configPath, _ = getConfigV2FilePath()
}
return filepath.Clean(configPath)
}
// getConfigV2FilePath returns the path to the v2 config file
func getConfigV2FilePath() (string, bool) {
configDir, err := GetScwConfigDir()
if err != nil {
return "", false
}
return filepath.Clean(filepath.Join(configDir, defaultConfigFileName)), true
}
// GetScwConfigDir returns the path to scw config folder
func GetScwConfigDir() (string, error) {
if xdgPath := os.Getenv(xdgConfigDirEnv); xdgPath != "" {
return filepath.Join(xdgPath, "scw"), nil
}
homeDir, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(homeDir, ".config", "scw"), nil
}
func fileExist(name string) bool {
_, err := os.Stat(name)
return err == nil
}
|
40b019b21a472d178e0438f7815f95999190c2d1
|
{
"blob_id": "40b019b21a472d178e0438f7815f95999190c2d1",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-31T17:08:49",
"content_id": "7bc0a3c3ce6c0afee424889c8b3e952668b4b394",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "180e06100ef04a8f4a0b8e0b6172bc5cb469c15c",
"extension": "go",
"filename": "path.go",
"fork_events_count": 5583,
"gha_created_at": "2016-06-27T22:01:15",
"gha_event_created_at": "2023-09-14T17:20:15",
"gha_language": "Go",
"gha_license_id": "Apache-2.0",
"github_id": 62091339,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 2360,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/vendor/github.com/scaleway/scaleway-sdk-go/scw/path.go",
"provenance": "stack-edu-0016.json.gz:181551",
"repo_name": "kubernetes/kops",
"revision_date": "2023-08-31T17:08:49",
"revision_id": "1276dcf1efb14729e95700926b3da367cb712b1e",
"snapshot_id": "5093108797233c02d8e5228331e2b5857cd94977",
"src_encoding": "UTF-8",
"star_events_count": 16057,
"url": "https://raw.githubusercontent.com/kubernetes/kops/1276dcf1efb14729e95700926b3da367cb712b1e/vendor/github.com/scaleway/scaleway-sdk-go/scw/path.go",
"visit_date": "2023-09-01T00:22:56.557569",
"added": "2024-11-18T22:46:16.114198+00:00",
"created": "2023-08-31T17:08:49",
"int_score": 3,
"score": 2.625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0034.json.gz"
}
|
use std::marker::PhantomData;
use std::mem;
use super::super::*;
pub struct BtrfsSuperblockSystemChunks<'a> {
address: *const u8,
end_address: *const u8,
phantom: PhantomData<&'a BtrfsSuperblockData>,
}
impl<'a> BtrfsSuperblockSystemChunks<'a> {
pub fn new(superblock_data: &'a BtrfsSuperblockData) -> BtrfsSuperblockSystemChunks<'a> {
let start_address = &superblock_data.system_chunks.data[0] as *const u8;
let end_address =
unsafe { start_address.offset(superblock_data.system_chunks_size as isize) };
BtrfsSuperblockSystemChunks {
address: start_address,
end_address,
phantom: PhantomData,
}
}
}
impl<'a> Iterator for BtrfsSuperblockSystemChunks<'a> {
type Item = BtrfsSuperblockChunkItem<'a>;
fn next(&mut self) -> Option<BtrfsSuperblockChunkItem<'a>> {
if self.address < self.end_address {
// get key
let chunk_item_key = unsafe { &*(self.address as *const BtrfsKey) };
self.address = unsafe { self.address.add(mem::size_of::<BtrfsKey>()) };
// get data
let chunk_item_data = unsafe { &*(self.address as *const BtrfsChunkItemData) };
self.address = unsafe { self.address.add(mem::size_of::<BtrfsChunkItemData>()) };
// skip chunk item stripes
self.address = unsafe {
self.address.offset(
mem::size_of::<BtrfsChunkItemStripeData>() as isize
* chunk_item_data.num_stripes() as isize,
)
};
// return
Some(
BtrfsSuperblockChunkItem::new(chunk_item_key, chunk_item_data)
.expect("Invalid chunk item"),
)
} else {
None
}
}
}
|
97d47660ad68f4de4e5289b253d229b997dfecf6
|
{
"blob_id": "97d47660ad68f4de4e5289b253d229b997dfecf6",
"branch_name": "refs/heads/master",
"committer_date": "2021-07-23T22:21:19",
"content_id": "41fe08f75085ed96374c9d135a319d45789e6d7d",
"detected_licenses": [
"MIT"
],
"directory_id": "dd71d7bc542046771ccb6c8a6dcdbbed0974bda5",
"extension": "rs",
"filename": "superblock_system_chunks.rs",
"fork_events_count": 0,
"gha_created_at": "2021-07-23T20:15:15",
"gha_event_created_at": "2021-07-23T20:15:16",
"gha_language": null,
"gha_license_id": null,
"github_id": 388916157,
"is_generated": false,
"is_vendor": false,
"language": "Rust",
"length_bytes": 1845,
"license": "MIT",
"license_type": "permissive",
"path": "/src/diskformat/core/superblock_system_chunks.rs",
"provenance": "stack-edu-0068.json.gz:239193",
"repo_name": "vorot93/rust-btrfs",
"revision_date": "2021-07-23T22:21:19",
"revision_id": "e480ad8857ad479f3f78763aa121e5ac22ebaa14",
"snapshot_id": "66ae35cfd6e6a845f6d8e09e5de52eee45f3f9c1",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/vorot93/rust-btrfs/e480ad8857ad479f3f78763aa121e5ac22ebaa14/src/diskformat/core/superblock_system_chunks.rs",
"visit_date": "2023-06-21T06:41:43.556655",
"added": "2024-11-18T22:47:33.576107+00:00",
"created": "2021-07-23T22:21:19",
"int_score": 3,
"score": 2.53125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0086.json.gz"
}
|
//------------------------------------------------------------------------------
// <auto-generated>
// このコードはツールによって生成されました。
// ランタイム バージョン:4.0.30319.18052
//
// このファイルへの変更は、以下の状況下で不正な動作の原因になったり、
// コードが再生成されるときに損失したりします。
// </auto-generated>
//------------------------------------------------------------------------------
namespace WWDistortionNoise.Properties {
using System;
/// <summary>
/// ローカライズされた文字列などを検索するための、厳密に型指定されたリソース クラスです。
/// </summary>
// このクラスは StronglyTypedResourceBuilder クラスが ResGen
// または Visual Studio のようなツールを使用して自動生成されました。
// メンバーを追加または削除するには、.ResX ファイルを編集して、/str オプションと共に
// ResGen を実行し直すか、または VS プロジェクトをビルドし直します。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// このクラスで使用されているキャッシュされた ResourceManager インスタンスを返します。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WWDistortionNoise.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 厳密に型指定されたこのリソース クラスを使用して、すべての検索リソースに対し、
/// 現在のスレッドの CurrentUICulture プロパティをオーバーライドします。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Add new filter に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ButtonAddNewFilter {
get {
return ResourceManager.GetString("ButtonAddNewFilter", resourceCulture);
}
}
/// <summary>
/// _Browse... に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ButtonBrowseB {
get {
return ResourceManager.GetString("ButtonBrowseB", resourceCulture);
}
}
/// <summary>
/// B_rowse... に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ButtonBrowseR {
get {
return ResourceManager.GetString("ButtonBrowseR", resourceCulture);
}
}
/// <summary>
/// Delete selected に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ButtonDeleteSelected {
get {
return ResourceManager.GetString("ButtonDeleteSelected", resourceCulture);
}
}
/// <summary>
/// Edit selected に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ButtonEditSelected {
get {
return ResourceManager.GetString("ButtonEditSelected", resourceCulture);
}
}
/// <summary>
/// _Load settings... に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ButtonLoadSettings {
get {
return ResourceManager.GetString("ButtonLoadSettings", resourceCulture);
}
}
/// <summary>
/// Move down selected に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ButtonMoveDownSelected {
get {
return ResourceManager.GetString("ButtonMoveDownSelected", resourceCulture);
}
}
/// <summary>
/// Move up selected に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ButtonMoveUpSelected {
get {
return ResourceManager.GetString("ButtonMoveUpSelected", resourceCulture);
}
}
/// <summary>
/// Save settings as... に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ButtonSaveSettingsAs {
get {
return ResourceManager.GetString("ButtonSaveSettingsAs", resourceCulture);
}
}
/// <summary>
/// _Start conversion に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ButtonStartConversion {
get {
return ResourceManager.GetString("ButtonStartConversion", resourceCulture);
}
}
/// <summary>
/// Use this filter に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ButtonUseThisFilter {
get {
return ResourceManager.GetString("ButtonUseThisFilter", resourceCulture);
}
}
/// <summary>
/// FFT Upsampler に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string CbItemFftUpsampler {
get {
return ResourceManager.GetString("CbItemFftUpsampler", resourceCulture);
}
}
/// <summary>
/// 2nd order に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string CbItemNoiseShaping2nd {
get {
return ResourceManager.GetString("CbItemNoiseShaping2nd", resourceCulture);
}
}
/// <summary>
/// 4th order に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string CbItemNoiseShaping4th {
get {
return ResourceManager.GetString("CbItemNoiseShaping4th", resourceCulture);
}
}
/// <summary>
/// Zero-Order Hold Upsampler に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string CbItemZohUpsampler {
get {
return ResourceManager.GetString("CbItemZohUpsampler", resourceCulture);
}
}
/// <summary>
/// Dropped data is not file に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string DroppedDataIsNotFile {
get {
return ResourceManager.GetString("DroppedDataIsNotFile", resourceCulture);
}
}
/// <summary>
/// Error に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string Error {
get {
return ResourceManager.GetString("Error", resourceCulture);
}
}
/// <summary>
/// Filter file version mismatch. expected version={0}, file version={1} に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ErrorFilterFileVersionMismatch {
get {
return ResourceManager.GetString("ErrorFilterFileVersionMismatch", resourceCulture);
}
}
/// <summary>
/// Please input gain value in number に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ErrorGainValueIsNan {
get {
return ResourceManager.GetString("ErrorGainValueIsNan", resourceCulture);
}
}
/// <summary>
/// Please input gain value larger than 0.0 に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ErrorGainValueIsTooSmall {
get {
return ResourceManager.GetString("ErrorGainValueIsTooSmall", resourceCulture);
}
}
/// <summary>
/// Please input Low pass filter cutoff frequency in number に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ErrorLpfCutoffFreqIsNan {
get {
return ResourceManager.GetString("ErrorLpfCutoffFreqIsNan", resourceCulture);
}
}
/// <summary>
/// Please input Low pass filter cutoff frequency larger than 0.0 に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ErrorLpfCutoffFreqIsNegative {
get {
return ResourceManager.GetString("ErrorLpfCutoffFreqIsNegative", resourceCulture);
}
}
/// <summary>
/// Please input Low pass filter slope in number に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ErrorLpfSlopeIsNan {
get {
return ResourceManager.GetString("ErrorLpfSlopeIsNan", resourceCulture);
}
}
/// <summary>
/// Please input Low pass filter slope larger than 1 に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ErrorLpfSlopeIsTooSmall {
get {
return ResourceManager.GetString("ErrorLpfSlopeIsTooSmall", resourceCulture);
}
}
/// <summary>
/// Prease input Target Quantization Bit Rate in number に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ErrorNoiseShapingBitIsNan {
get {
return ResourceManager.GetString("ErrorNoiseShapingBitIsNan", resourceCulture);
}
}
/// <summary>
/// Prease input Target Quantization Bit Rate in integer in the range of 1 to 23 に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ErrorNoiseShapingBitIsOutOfRange {
get {
return ResourceManager.GetString("ErrorNoiseShapingBitIsOutOfRange", resourceCulture);
}
}
/// <summary>
/// Output data becomes too large! {0} Gbytes に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ErrorOutputDataTooLarge {
get {
return ResourceManager.GetString("ErrorOutputDataTooLarge", resourceCulture);
}
}
/// <summary>
/// RPDF Jitter Amount must be 0 or larger value に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ErrorRpdfJitterAmount {
get {
return ResourceManager.GetString("ErrorRpdfJitterAmount", resourceCulture);
}
}
/// <summary>
/// Too large magnitude sample detected! channel={0}, magnitude={1:0.000}
/// に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ErrorSampleValueClipped {
get {
return ResourceManager.GetString("ErrorSampleValueClipped", resourceCulture);
}
}
/// <summary>
/// Sinusoidal Jitter Amount must be 0 or larger value に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ErrorSinusolidalJitterAmount {
get {
return ResourceManager.GetString("ErrorSinusolidalJitterAmount", resourceCulture);
}
}
/// <summary>
/// Sinusoidal Jitter Freq must be 0 or larger value に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ErrorSinusolidalJitterFreq {
get {
return ResourceManager.GetString("ErrorSinusolidalJitterFreq", resourceCulture);
}
}
/// <summary>
/// TPDF Jitter Amount must be 0 or larger value に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ErrorTpdfJitterAmount {
get {
return ResourceManager.GetString("ErrorTpdfJitterAmount", resourceCulture);
}
}
/// <summary>
/// Please specify different file to write. WWAudioFilter cannot write to input file. に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string ErrorWriteToReadFile {
get {
return ResourceManager.GetString("ErrorWriteToReadFile", resourceCulture);
}
}
/// <summary>
/// FFT upsample: {0}x, FFT length={1} に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FilterFftUpsampleDesc {
get {
return ResourceManager.GetString("FilterFftUpsampleDesc", resourceCulture);
}
}
/// <summary>
/// FLAC files|*.flac に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FilterFlacFiles {
get {
return ResourceManager.GetString("FilterFlacFiles", resourceCulture);
}
}
/// <summary>
/// Gain : {0}x ({1:0.00}dB) に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FilterGainDesc {
get {
return ResourceManager.GetString("FilterGainDesc", resourceCulture);
}
}
/// <summary>
/// Add Jitter : Sinusoidal={0}Hz {1}ns, TPDF={2}ns, RPDF={3}ns, Filter Length={4} に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FilterJitterAddDesc {
get {
return ResourceManager.GetString("FilterJitterAddDesc", resourceCulture);
}
}
/// <summary>
/// LPF : Cutoff={0}Hz, slope={1}db/oct, FIR length={2} に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FilterLpfDesc {
get {
return ResourceManager.GetString("FilterLpfDesc", resourceCulture);
}
}
/// <summary>
/// 2nd order MASH noise shaping: targetBitsPerSample={0} に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FilterMashDesc {
get {
return ResourceManager.GetString("FilterMashDesc", resourceCulture);
}
}
/// <summary>
/// 4th order noise shaping: targetBitsPerSample={0} に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FilterNoiseShaping4thDesc {
get {
return ResourceManager.GetString("FilterNoiseShaping4thDesc", resourceCulture);
}
}
/// <summary>
/// Noise shaping: order={0}, targetBitsPerSample={1} に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FilterNoiseShapingDesc {
get {
return ResourceManager.GetString("FilterNoiseShapingDesc", resourceCulture);
}
}
/// <summary>
/// FLAC files|*.flac|DSF files|*.dsf に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FilterWriteAudioFiles {
get {
return ResourceManager.GetString("FilterWriteAudioFiles", resourceCulture);
}
}
/// <summary>
/// WWAudioFilter files|*.wwaf に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FilterWWAFilterFiles {
get {
return ResourceManager.GetString("FilterWWAFilterFiles", resourceCulture);
}
}
/// <summary>
/// Zero order hold upsample: {0}x に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FilterZOHDesc {
get {
return ResourceManager.GetString("FilterZOHDesc", resourceCulture);
}
}
/// <summary>
/// FLAC header corrupted に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorBadHeader {
get {
return ResourceManager.GetString("FlacErrorBadHeader", resourceCulture);
}
}
/// <summary>
/// FLAC bad parameter error に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorBadParams {
get {
return ResourceManager.GetString("FlacErrorBadParams", resourceCulture);
}
}
/// <summary>
/// FLAC buffer size mismatch に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorBufferSizeMismatch {
get {
return ResourceManager.GetString("FlacErrorBufferSizeMismatch", resourceCulture);
}
}
/// <summary>
/// Data not ready に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorDataNotReady {
get {
return ResourceManager.GetString("FlacErrorDataNotReady", resourceCulture);
}
}
/// <summary>
/// FLAC decoder process failed に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorDecoderProcessFailed {
get {
return ResourceManager.GetString("FlacErrorDecoderProcessFailed", resourceCulture);
}
}
/// <summary>
/// FLAC encoder error に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorEncoder {
get {
return ResourceManager.GetString("FlacErrorEncoder", resourceCulture);
}
}
/// <summary>
/// FLAC encoder process failed に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorEncoderProcessFailed {
get {
return ResourceManager.GetString("FlacErrorEncoderProcessFailed", resourceCulture);
}
}
/// <summary>
/// FLAC file read open error に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorFileReadOpen {
get {
return ResourceManager.GetString("FlacErrorFileReadOpen", resourceCulture);
}
}
/// <summary>
/// FLAC frame CRC mismatch に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorFrameCrcMismatch {
get {
return ResourceManager.GetString("FlacErrorFrameCrcMismatch", resourceCulture);
}
}
/// <summary>
/// Internal error (id not found) に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorIdNotFound {
get {
return ResourceManager.GetString("FlacErrorIdNotFound", resourceCulture);
}
}
/// <summary>
/// FLAC bits per sample error に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorInvalidBitsPerSample {
get {
return ResourceManager.GetString("FlacErrorInvalidBitsPerSample", resourceCulture);
}
}
/// <summary>
/// FLAC metadata error に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorInvalidMetadata {
get {
return ResourceManager.GetString("FlacErrorInvalidMetadata", resourceCulture);
}
}
/// <summary>
/// FLAC number of channels is invalid (must be smaller than or equal to 8) に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorInvalidNumberOfChannels {
get {
return ResourceManager.GetString("FlacErrorInvalidNumberOfChannels", resourceCulture);
}
}
/// <summary>
/// FLAC sample rate is out of range (must be smaller than or equal to 655,350Hz) に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorInvalidSampleRate {
get {
return ResourceManager.GetString("FlacErrorInvalidSampleRate", resourceCulture);
}
}
/// <summary>
/// FLAC lost sync error に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorLostSync {
get {
return ResourceManager.GetString("FlacErrorLostSync", resourceCulture);
}
}
/// <summary>
/// FLAC memory exhausted に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorMemoryExhausted {
get {
return ResourceManager.GetString("FlacErrorMemoryExhausted", resourceCulture);
}
}
/// <summary>
/// FLAC number of frames is not aligned に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorNumFrameIsNotAligned {
get {
return ResourceManager.GetString("FlacErrorNumFrameIsNotAligned", resourceCulture);
}
}
/// <summary>
/// FLAC other error に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorOther {
get {
return ResourceManager.GetString("FlacErrorOther", resourceCulture);
}
}
/// <summary>
/// Output data size exceeds 2GB per channel! Process aborted. に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorOutputFileTooLarge {
get {
return ResourceManager.GetString("FlacErrorOutputFileTooLarge", resourceCulture);
}
}
/// <summary>
/// FLAC receive buffer size is insufficient に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorRecvBufferSizeInsufficient {
get {
return ResourceManager.GetString("FlacErrorRecvBufferSizeInsufficient", resourceCulture);
}
}
/// <summary>
/// FLAC stream decoder init failed に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorStreamDecoderInitFailed {
get {
return ResourceManager.GetString("FlacErrorStreamDecoderInitFailed", resourceCulture);
}
}
/// <summary>
/// FLAC stream decoder new failed に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorStreamDecoderNewFailed {
get {
return ResourceManager.GetString("FlacErrorStreamDecoderNewFailed", resourceCulture);
}
}
/// <summary>
/// FLAC unparseable error に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacErrorUnparseable {
get {
return ResourceManager.GetString("FlacErrorUnparseable", resourceCulture);
}
}
/// <summary>
/// Write open failed に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string FlacerrorWriteOpenFailed {
get {
return ResourceManager.GetString("FlacerrorWriteOpenFailed", resourceCulture);
}
}
/// <summary>
/// Filter settings に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string GroupFilterSettings {
get {
return ResourceManager.GetString("GroupFilterSettings", resourceCulture);
}
}
/// <summary>
/// Gain に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string GroupGain {
get {
return ResourceManager.GetString("GroupGain", resourceCulture);
}
}
/// <summary>
/// Input file に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string GroupInputFile {
get {
return ResourceManager.GetString("GroupInputFile", resourceCulture);
}
}
/// <summary>
/// Log に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string GroupLog {
get {
return ResourceManager.GetString("GroupLog", resourceCulture);
}
}
/// <summary>
/// FIR Linear-Phase Low pass Filter に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string GroupLPF {
get {
return ResourceManager.GetString("GroupLPF", resourceCulture);
}
}
/// <summary>
/// Noise Shaping に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string GroupNoiseShaping {
get {
return ResourceManager.GetString("GroupNoiseShaping", resourceCulture);
}
}
/// <summary>
/// Output File に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string GroupOutputFile {
get {
return ResourceManager.GetString("GroupOutputFile", resourceCulture);
}
}
/// <summary>
/// Upsampler に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string GroupUpsampler {
get {
return ResourceManager.GetString("GroupUpsampler", resourceCulture);
}
}
/// <summary>
/// Cutoff frequency: に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string LabelCutoffFreq {
get {
return ResourceManager.GetString("LabelCutoffFreq", resourceCulture);
}
}
/// <summary>
/// FIR filter length: に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string LabelFilterLength {
get {
return ResourceManager.GetString("LabelFilterLength", resourceCulture);
}
}
/// <summary>
/// Gain in Amplitude: に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string LabelGainInAmplitude {
get {
return ResourceManager.GetString("LabelGainInAmplitude", resourceCulture);
}
}
/// <summary>
/// Gain in dB: に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string LabelGainInDb {
get {
return ResourceManager.GetString("LabelGainInDb", resourceCulture);
}
}
/// <summary>
/// Gain roll off slopes: に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string LabelGainRolloffSlopes {
get {
return ResourceManager.GetString("LabelGainRolloffSlopes", resourceCulture);
}
}
/// <summary>
/// Input file: に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string LabelInputFile {
get {
return ResourceManager.GetString("LabelInputFile", resourceCulture);
}
}
/// <summary>
/// Noise shaping method: に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string LabelNoiseShapingMethod {
get {
return ResourceManager.GetString("LabelNoiseShapingMethod", resourceCulture);
}
}
/// <summary>
/// Target Quantized Bit Rate: に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string LabelNoiseShapingTargetBit {
get {
return ResourceManager.GetString("LabelNoiseShapingTargetBit", resourceCulture);
}
}
/// <summary>
/// Output file: に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string LabelOutputFile {
get {
return ResourceManager.GetString("LabelOutputFile", resourceCulture);
}
}
/// <summary>
/// samples に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string LabelSamples {
get {
return ResourceManager.GetString("LabelSamples", resourceCulture);
}
}
/// <summary>
/// FFT Length: に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string LabelUpsamplerLength {
get {
return ResourceManager.GetString("LabelUpsamplerLength", resourceCulture);
}
}
/// <summary>
/// Upsampler Type: に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string LabelUpsamplerType {
get {
return ResourceManager.GetString("LabelUpsamplerType", resourceCulture);
}
}
/// <summary>
/// Upsampling factor: に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string LabelUpsamplingFactor {
get {
return ResourceManager.GetString("LabelUpsamplingFactor", resourceCulture);
}
}
/// <summary>
/// x に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string LabelX {
get {
return ResourceManager.GetString("LabelX", resourceCulture);
}
}
/// <summary>
/// Completed.
/// に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string LogCompleted {
get {
return ResourceManager.GetString("LogCompleted", resourceCulture);
}
}
/// <summary>
/// Read completed. now processing...
/// に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string LogFileReadCompleted {
get {
return ResourceManager.GetString("LogFileReadCompleted", resourceCulture);
}
}
/// <summary>
/// Reading file {0} ...
/// に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string LogFileReadStarted {
get {
return ResourceManager.GetString("LogFileReadStarted", resourceCulture);
}
}
/// <summary>
/// Process completed. now writing to {0} ...
/// に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string LogfileWriteStarted {
get {
return ResourceManager.GetString("LogfileWriteStarted", resourceCulture);
}
}
/// <summary>
/// Nothing to store. に類似しているローカライズされた文字列を検索します。
/// </summary>
internal static string NothingToStore {
get {
return ResourceManager.GetString("NothingToStore", resourceCulture);
}
}
}
}
|
a396e52da9fee6a2da57c7662222798ca07d43fc
|
{
"blob_id": "a396e52da9fee6a2da57c7662222798ca07d43fc",
"branch_name": "refs/heads/master",
"committer_date": "2020-11-21T16:49:20",
"content_id": "b62ce10c43520d2684c6f40a00e5209358465e5c",
"detected_licenses": [
"MIT"
],
"directory_id": "05688de8dd33283bbf09a67edfb4acd53a1f2376",
"extension": "cs",
"filename": "Resources.Designer.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 317008535,
"is_generated": true,
"is_vendor": false,
"language": "C#",
"length_bytes": 38750,
"license": "MIT",
"license_type": "permissive",
"path": "/PlayPcmWin/WWDistortionNoise/Properties/Resources.Designer.cs",
"provenance": "stack-edu-0013.json.gz:169684",
"repo_name": "jcreator35/PlayPcmWin",
"revision_date": "2020-11-21T16:49:20",
"revision_id": "4296c2093a28808fe67b39943f580ead0a207fb9",
"snapshot_id": "f72da2d586dcca05499aae2bb2974b36739261c9",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/jcreator35/PlayPcmWin/4296c2093a28808fe67b39943f580ead0a207fb9/PlayPcmWin/WWDistortionNoise/Properties/Resources.Designer.cs",
"visit_date": "2021-06-24T00:59:37.305328",
"added": "2024-11-19T01:50:10.251843+00:00",
"created": "2020-11-21T16:49:20",
"int_score": 2,
"score": 2.078125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0031.json.gz"
}
|
# Log Stash
Push json formatted log to local file system
## Usage
_1_. go get github.com/vonlippmann/logstash<br>
_2_. import "github.com/vonlippmann/logstash" in your code<br>
_3_. make a new instance of Logger:<br>
```go
logger := NewLogStash(&Config{
LogPath: "<your specified path>",
LogKeepDays: 0,
FileName: "<your specified file name>",
CleanLog: false,
})
```
_4_. then you can use logger in anywhere you need to sink log to the specified path:
```go
logger.Sink(Massage{
"auth": "pep-pig",
"age": "18",
})
```
### Hooks
* you can use hook to postprocess the massage you sinked, such as add some other fields. You can do this simply by register a hook function:
```go
logger.RegisterHook(func(msg Massage)(err error){
<EMAIL_ADDRESS> return
})
```
### Example
```go
package main
var logger *Logger
func main(){
for{
logger.Sink(Massage{
"auth": "pep-pig",
"age": "18",
})
}
}
func addField(massage Massage) (err error) {
massage["email"] =<EMAIL_ADDRESS> return
}
func init() {
logger = NewLogStash(&Config{
LogPath: "/var/log/logstash",
LogKeepDays: 0,
FileName: "elk",
CleanLog: false,
})
logger.RegisterHook(addField)
}
```
|
d33c48e0ac22e72aa6461efcf9504c4d9595a097
|
{
"blob_id": "d33c48e0ac22e72aa6461efcf9504c4d9595a097",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-10T07:46:49",
"content_id": "255fd8d7b57dc874e79f3dcf0006b0e789afe0fd",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "d616512ddf4f26383fe66172a9edf87e5e031996",
"extension": "md",
"filename": "README.md",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 219412104,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1338,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/README.md",
"provenance": "stack-edu-markdown-0010.json.gz:276567",
"repo_name": "pep-pig/logstash",
"revision_date": "2020-01-10T07:46:49",
"revision_id": "44f559bea97a788aa960f0358e1143dbf7178803",
"snapshot_id": "34019d6b5bfb569262dd32760814be603c3be0ba",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/pep-pig/logstash/44f559bea97a788aa960f0358e1143dbf7178803/README.md",
"visit_date": "2020-09-03T07:01:08.558257",
"added": "2024-11-19T00:03:18.469511+00:00",
"created": "2020-01-10T07:46:49",
"int_score": 3,
"score": 3.484375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0010.json.gz"
}
|
* Ticket Triage: 283 (issues +PR) (+3)
* Attending: Anne, Karl
## Content
* New Requests on Learning Center:
* Selecting Elements: "Multiple Selector" missing
* https://github.com/jquery/learn.jquery.com/issues/702
* Agreed.
* Karl to prepare a PR (page needs an overhaul)
* Anne to check that there aren’t any other issues reported with this page so that everything can be taken care of in one go.
* More detailed explanation in article on deferred
* http://learn.jquery.com/code-organization/deferreds/jquery-deferreds/
* https://github.com/jquery/learn.jquery.com/issues/701
* Dave made a suggestion.
* We think the suggestion is good
* Waiting on user to comment back.
* http://learn.jquery.com/code-organization/deferreds/examples/
* https://github.com/jquery/learn.jquery.com/issues/693
* Article on optimizing selectors
* https://github.com/jquery/learn.jquery.com/issues/697
* https://github.com/jquery/learn.jquery.com/issues/696
* Karl will try to come up with a solution
* Api.jquery.com & api.jquerymobile.com
* Deployment is broken (however api.jqueryui.com is fine and some other sites are fine as well).
* Ongoing issues:
* A few issues raised with SVG and jQuery. We need to make it clear to users that jQuery doesn’t support SVG even if some things will work.
* https://github.com/jquery/api.jquery.com/issues/884
* https://github.com/jquery/api.jquery.com/issues/885
* Aurelio will work on a PR for this.
* GSOC:
* Getting some interest
* Students should be directed to https://github.com/jquery/learn.jquery.com/issues/641 to see past discussion
* CLA:
* Seems to be reporting incorrect failures
|
f530d58a4ac4f5b4e9a61d7f932a8c1f5acea08d
|
{
"blob_id": "f530d58a4ac4f5b4e9a61d7f932a8c1f5acea08d",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-17T01:28:31",
"content_id": "221b5976904a80883b72518eaf858178601fd3d4",
"detected_licenses": [
"MIT"
],
"directory_id": "4da50d69009a10b1441aa31605dca02dba955bee",
"extension": "md",
"filename": "2016-03-09.md",
"fork_events_count": 25,
"gha_created_at": "2013-03-30T14:15:27",
"gha_event_created_at": "2023-04-15T11:51:13",
"gha_language": "JavaScript",
"gha_license_id": "NOASSERTION",
"github_id": 9116821,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1707,
"license": "MIT",
"license_type": "permissive",
"path": "/minutes/content/2016-03-09.md",
"provenance": "stack-edu-markdown-0008.json.gz:65708",
"repo_name": "jquery/meetings.jquery.org",
"revision_date": "2023-08-17T01:26:17",
"revision_id": "641f00d8e166147820b82b3eed7a94178e239f8f",
"snapshot_id": "bf7b5e7ccfa27066e62ce15fa5b70398cbb5352a",
"src_encoding": "UTF-8",
"star_events_count": 29,
"url": "https://raw.githubusercontent.com/jquery/meetings.jquery.org/641f00d8e166147820b82b3eed7a94178e239f8f/minutes/content/2016-03-09.md",
"visit_date": "2023-08-31T10:53:31.088001",
"added": "2024-11-18T21:23:05.529625+00:00",
"created": "2023-08-17T01:26:17",
"int_score": 2,
"score": 2.421875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0008.json.gz"
}
|
use crate::{
error::{Error, Result},
transport::{proto::Endpoint, Client, Request, Response},
};
pub struct Paxos<'a, C> {
client: &'a mut C,
size: usize,
my_addr: Endpoint,
// TODO: come up with a design for onDecide
}
impl<'a, C> Paxos<'a, C> {
pub fn new(client: &'a mut C, size: usize, my_addr: Endpoint) -> Paxos<C> {
Paxos {
client,
size,
my_addr,
}
}
async fn start_round(&mut self) -> Result<Response> {
unimplemented!()
}
pub(crate) async fn handle_phase_1a(&self, request: Request) -> crate::Result<Response> {
unimplemented!()
}
pub(crate) async fn handle_phase_1b(&self, request: Request) -> crate::Result<Response> {
unimplemented!()
}
pub(crate) async fn handle_phase_2a(&self, request: Request) -> crate::Result<Response> {
unimplemented!()
}
pub(crate) async fn handle_phase_2b(&self, request: Request) -> crate::Result<Response> {
unimplemented!()
}
}
|
398cfac00ab639a3ecbdc49a26b5fce90bc48b1b
|
{
"blob_id": "398cfac00ab639a3ecbdc49a26b5fce90bc48b1b",
"branch_name": "refs/heads/master",
"committer_date": "2019-07-09T23:12:37",
"content_id": "6e4e822d49c4bcfe6ea9ccdef23c9550df60f4aa",
"detected_licenses": [
"MIT"
],
"directory_id": "99f4b5e76b01d42cc809157bb2cb81601b2314b2",
"extension": "rs",
"filename": "paxos.rs",
"fork_events_count": 0,
"gha_created_at": "2019-07-10T05:50:54",
"gha_event_created_at": "2019-07-10T05:50:54",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 196139806,
"is_generated": false,
"is_vendor": false,
"language": "Rust",
"length_bytes": 1040,
"license": "MIT",
"license_type": "permissive",
"path": "/src/consensus/paxos.rs",
"provenance": "stack-edu-0068.json.gz:207583",
"repo_name": "gilescope/clique",
"revision_date": "2019-07-09T23:12:37",
"revision_id": "f725715d4490b5d4866ab034cc546b7d5224f199",
"snapshot_id": "0b4f9bdc3bd27f87c56ed1d00bb65437bb1128e3",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gilescope/clique/f725715d4490b5d4866ab034cc546b7d5224f199/src/consensus/paxos.rs",
"visit_date": "2020-06-18T02:39:16.885642",
"added": "2024-11-18T21:43:18.954386+00:00",
"created": "2019-07-09T23:12:37",
"int_score": 2,
"score": 2.046875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0086.json.gz"
}
|
---
layout: post
title: Modelling with Differentiation
author: Paul Druce
summary: Some examples and question of how to use differentiation to model situations.
category: tutoring
tags: [post,questions,notes]
---
When you first start learning about differentiation, integration and calculus in general, we often stick to equations that exclusively use the variables $x, y$ and $t$. The variable $t$ is often used to represent time, and $y$ and $x$ are related to the graphs of specific functions, i.e. $y = f(x)$, where $f$ can be any reasonable^[To find out what reasonable means requires a more in-depth knowledge of calculus.] function. However, there is nothing special about the letters $x,y$ or $t$. So in many cases we will choose different letters to represent important quantities.
For instance, consider a circle of radius^[There is nothing special about the letter r, it's just short for radius.] $r$. We then know how to calculate the circumference of the circle, $2\pi r$, or the area $\pi r^2$.
The inquisitive of you might start to wonder how the circumference and area of circles change as we increase or decrease the radius. How could we quantify such behaviour?
Well this is where differentiation is particularly useful. Because when we compute the derivative ${dy\over dx}$, what we are really asking is how does the function $y$ change as we vary the variable $x$.
So what if we define the circumference as a function of the radius as follows: Let $C$ be the circumference of a circle of radius $r$, so $C(r) = 2 \pi r$.
Then what does ${dC\over dr}$ compute[^a]? Well it computes how the circumference changes as we vary the radius of the circle.
[^a]: Note that the derivative is really the following limit: $${dC \over dr} = \lim\limits_{\epsilon \to 0} {C(r+\epsilon) - C(r) \over \epsilon}$$
:::{.example}
A drop of oil is placed on the surface of a still pool of water. The oil spreads out over time in a circular manner. The rate of increase of the radius of the circle the oil forms is proportional to the time since it was dropped. At time $t=0s$, the radius of the circle is $r=1cm$ and at $t=1s$, the radius is $r=2cm$. Find it's radius after 10 seconds.
<div class="single-image">

</div>
<u>Solution</u>:<br>
Given that ${dr\over dt} \propto t$ we can say that ${dr\over dt} = kt$, so (via integration) we have that $r = {1\over 2}kt^2 + C$. We then use the data that we have: At $t=0$, $r= {1\over 2}k (0\text{ s})^2 +C = C$, but we know that $r=1cm$ at $t=0$, so $C=1cm$. Then we need to have another piece of data to find the coefficient $k$, this is given to us as follows:
At $t=1s$, we have that:
$$\begin{align}r &= {1\over 2}k (1\text{ s})^2 + 1 \text{ cm}\\ &= {1\over 2}\text{ s}^2 \times k + 1 \text{ cm},\end{align}$$
but we know that $r=2 \text{ cm}$ at $t=1s$, so we have that ${1 \over 2}\text{ s}^2 k + 1 cm = 2cm$.
So $k = 2\text{cm}/\text{s}^2$, where the units of $k$ are determined in order for the equation to make sense.
So we have that
$$r = (t^2 + 1)\text{ cm.}$$
So we have that at $t=10 \text{s}$, then we have that $r = 100+1 \text{ cm} = 101 \text{cm}$.
:::
## Converting words to mathematics = Terminology
It is often harder to setup the mathematics than it is to solve to equations. Or at-least, we get very good at using the specific mathematical tools, but converting paragraphs to mathematics is difficult. Mathematicians use very specific words to mean very specific mathematical operations. Here are a few phrases that often turn up in these style of questions.
| Sentence | Mathematics |
|:-----:| :----:|
|$X$ is proportional to $Y$| $X\propto Y$ which is equivalent to $X = k Y$ for some unknown constant $k$|
|$X$ is inversely proportional to $Y$| $X \propto {1\over Y}$ or $X = {k \over Y}$ for some unknown constant $k$ |
|$X$ exponentially grows with respect to $Y$| $A \propto e^{kY}$ or $X=\alpha e^{k Y}$ for two unknown constants $k$ and $\alpha$. |
|$X$ exponentially decays with respect to $Y$| $X \propto e^{-kY}$ or $X = \alpha e^{-kY}$ for two unknown constants $k$ and $\alpha$.|
Mathematicians also heavily rely on *context*. This is the idea that there is something *obvious* or inherent to the question. However, this is usually a barrier to understanding for those learning or anyone who is interested trying to understand.
In regards to modelling with differentiation, this often shows itself when we start to discuss the *rate of change of $X$* where $X$ is some property of interest.
The term **rate of change of** refers to a derivative as was discuss at the beginning of this note. However, what we are taking the derivative with respects to is not always stated. You could argue that it should be. But my argument for why context is a natural and useful tool to rely on, is as follows. When ask someone "is it raining?" you don't usually have to tell them where you are inquiring about. It's hidden in context that you care about if it is raining *here*, where you are. You aren't asking if it is raining in Melbourne, Australia. You've relied on context.
So, when we ask about the rate of change of velocity, we usually assume we are talking about the rate of change of velocity *with respects to time*. When we ask about the rate of change of sound intensity, we can assume we are talking about the rate of change of sound intensity with respects to distance from the source **or** with respects to time. Being able to read into the context usually requires some familiarity with the system or example in questions.
The probability of contracting the virus from this person decreases exponentially as the distance between you is increased. The rate of decrease of the probability at a distance of $0\text{ m}$ is $17 \text{ m}^{-1}$.
a. Write down the probability as a function of distance.
b. Assuming that the probability of contraction is equal to $1$ at a distance of $0 \text{ m}$. Find the rate of change of the probability as a function of distance.
c. What is the probability of contraction at $2\text{ m}$ to three significant figures?
:::
</summary>
<u> Solution </u>
a. The probability, $P$, is modelled by the following function $P = A e^{-k x}$, where $x$ is the distance from the person.
b. As the probability is equal to $1$ at $0 \text{ m}$, we have that $P(x=0) = A e^{-k\cdot 0} = A$, so we have that $A=1$. So we have that $P(x) = e^{-kx}$. The rate of change of the probability with respects to the distance is given by
$${dP\over dx} = -k e^{-k x}.$$ Using the data that the rate of **decrease** of the probability at $x=0 \text{ m}$ is equal to $17 \text{ m}^{-1}$, we have that:
$${dP\over dx}(x=0) = - ke^{-k \cdot 0}=-k = -17.$$ So we have that $k=17\text{ m}^{-1}$.
c. The probability at $x=2 \text{ m}$ is $P(x=2) = e^{-17\cdot 2} =e^{-34}=1.71 \times 10^{-15}$ or $0.000000000000171 \% $
</details>
<details>
<summary>
:::{.question}
A regular hexagon has a side of length $l$.
a. What is the perimeter as a function of $l$?
b. What is the rate-of-change of it's perimeter as a function of $l$?
c. What is the area of the regular hexagon as a function of $l$? (tricky)
d. What is the rate-of-change of the area as a function of $l$?
e. What is the value of $l$ when the rate of change of the area is equal to $\sqrt{675}$?
:::
</summary>
<u> Solution </u>
a. The perimeter, $P$ is $6l$.
b. The rate of change of the perimeter as a function of $l$ is $${dP\over dl} = 6$$.
c. To solve this questions, cut up the hexagon into 6 equilateral triangles with side length $l$. This is done by connecting the center of the hexagon to the vertices. The area of these triangles is then
$$\frac{1}{2}\cdot b \cdot h = \frac{1}{2} \cdot l \cdot {\sqrt{3}\over 2} l = {\sqrt{3}\over 4} l^2,$$ where the height $h$ can be calculate used Pythogoras. We then know that the total area of a hexagon is $6$ times the area of one of these triangles. So the area is $A = {3\sqrt{3}\over 2} l^2$
d. The rate of change of the area is given by
$${dA\over dl} = 3\sqrt{3} l$$
e. Firstly, we note that $l$ can not be negative, as a negative side length is not a reasonable quantity. We can solve this by rewriting $3 = \sqrt{9}$ and $l = \sqrt{l^2}$, so that ${dA\over dl}= \sqrt{9 \cdot 3 \cdot l^2} = \sqrt{27\cdot l^2}$ which equals $\sqrt{675}$. As $675\div 27 = 25$ this yields that $l=5$.
</details>
<details>
<summary>
:::{.question name="Hard"}
A town council planted a tree in the centre of a roundabout 5 years ago. When they planted the tree, it was $1\text{ m}$ tall. Today it is $3.5\text{ m}$ tall. This species of tree has a maximum height of $12$ m. They employ you, a mathematician, to estimate how long it will be before the tree is $10\text{ m}$ tall.
a. Supposing that the tree's height is rate of increase of the tree's height is constant. How many years does it take?
b. Supposing now that the rate of increase of the tree's height exponentially decreases with respects to the number of years since it was planted. How long does it take?
c. Compare the two models. Which is the most reasonable? Justify your answer.
:::
</summary>
<u> Solution </u>
a. As the rate of increase of the tree is constant, we have that $${dh\over dt} = k,$$ so by integrating this expression we can model the height of the tree as: $h = k\cdot t +c$. As the tree was planted at a height of $1$ m at $t=0$, we have that $c=1$.
We are then told after $5$ years, the tree is now $3.5m$ tall. We then have that $3.5 = h = k\cdot 5 + 1$ so we have that $k = (3.5-1)/5 = 2.5/5 = 0.5$. The units of the constant $k$ convert time (seconds) to distance (metres) so $k = 0.5 \text{ m s}^{-1}$.
So we have that
$$h = 0.5 t + 1.$$
So when is $h=10$ m? Well $10 = 0.5 t + 1$ so we have that
$$t = {10-1 \over 0.5} = 18.$$ This is the time since the tree was planted, so from the present time that is $18 -5 = 13$ years.
b. Now we suppose that the rate of increase is given by:
$${dh\over dt} = Ae^{-k t},$$
so by integrating we have that
$h= -{A\over k} e^{-k t} + c$.
Now we use the data from the
question.
- At $t=0$ the height of the tree is $1$ m tall, so
we have that
$$1=h = -{A/k} e^{0} + c = c- {A\over k}.$$
- We also have that at $t=5$ the tree is $3.5$ tall. So we have
that
$$3.5 = -{A\over k} e^{-5k} + c.$$
- Finally, the fact the tree has a maximum height of $12\text{ m}$, means that at
$t=\infty$ the height of the tree should be $12$ m.
Implementing this ins the equation we have that $c = 12$ m,
as $e^{-kt} \to 0$ as $t\to \infty$.
So we have the following equations:
$$
\begin{align}
c &= 12, \\
{A\over k} &= c-1 = 11 \implies A = 11 k, \\
{A\over k} e^{-5k}&= c-3.5 = 8.5.
\end{align}
$$
Using that ${A\over k} = 11$, we have that $e^{-5k} = {8.5\over 11}$, taking the natural logarithm of this equation gives:
$$
-5k = \ln({8.5\over 11})
$$
Which tells us that $k = {1\over 5}\ln({11 \over 8.5})$, which makes $A = 11k = {11\over 5} \ln({11\over 8.5})$. We now have a complete equation for the height of the tree as a function of time:
$$h = 12 -11 e^{-\ln({11\over 8.5}) {t\over 5}}.$$ Complicated! You can see why the council hired a mathematician!
So when does the height of the tree reach $10$ m in this model?
$$
\begin{align}
10 &= 12 -11 e^{-\ln({11\over 8.5}) {t\over 5}} \\
-2 &= -11 e^{-\ln({11\over 8.5}) {t\over 5}}\\
{2\over 11} &= e^{-\ln({11\over 8.5}) {t\over 5}}
\end{align}
$$
taking the natural logarithm of this we get that:
$$ -\ln({11\over 8.5}) {t\over 5} = \ln ({2\over 11})$$
This gives the time:
$$t = 5 {\ln(11/2) \over \ln(11/8.5)} = 33.0597... $$
So the tree will reach $10$ m tall $33.06$ years after it was planted, which is $33.06-5 = 28.06$ years from now.
c. The first model doesn't restrict the growth of the tree to $12\text{ m}$. After $22$ years the tree will exceed this maximum height. The second model however means the tree will always be below this maximum height. However, it is not necessarily a good model, it's just better than the first. The second model also starts with the tree growing rapidly to begin with and the growth slowing down as the tree ages, much like a real tree would. However, these models don't encode how trees grow rapidly in the spring and then don't grow in the winter. But if we treat this as the average growth per year, this makes sense. But that means the parameter $t$ needs to take values in the natural numbers $\mathbb{N} = \{0,1,2,3,4,\dots\}$.
</details>
<details >
<summary>
::: {.question name="The values and data in this question are completely made up. "}
A country is keenly monitoring the spread of a virus. To stop the virus from overloading the country's healthcare system, the government will strategically implement a "national lockdown". The country monitors the situation by measuring the virus' reproduction value, i.e. it's $R$ value. This is the average number of people an infected person will pass the virus on to. If the rate of change of the $R$ value exceeds $0.9$ per week. The country will implement a national lockdown to slow the spread of the virus.
a. Without any "social distancing", the $R$ value is modelled as $R = \exp(1.4 t)$, where $t$ is the time measured in weeks. How long is it before the rate of change of the $R$ value exceeds the threshold for a national lockdown?
b. With the social distancing measures in place the $R$ value is modelled as $R = \exp(0.8 t)$. How long is it before the rate of change of the $R$ value exceeds the threshold?
c. The government apply a series of city-lockdowns, to try and combat the local "hot-spots" of the virus and to prevent a nationwide lock down. These measures cause the $R$ value to be modelled by $R = \exp(0.08 t)$. How long is it before the rate of change of the $R$ value exceeds the threshold?
:::
</summary>
<u> Solution </u>
The rate of change of the $R$ value is given by the derivative of the
$${dR\over dt}.$$
a. If we model the $R$ value as $R = \exp(1.4 t)$, then we find the derivative to be:
$${dR\over dt} = 1.4 \exp(1.4t).$$
The question asks when does this value exceed the threshold of $0.9$. So for zero weeks the rate of change of the $R$ value is larger than the threshold.
b. Now $dR/dt = 0.8\exp(0.8 t)$ so for when is $0.8 \exp(0.8 t) >0.9$ is when $\exp(0.8 t) >0.9/0.8 = 1.125$, so $t> \ln(1.125)/0.8 = 0.147...$, which is still within a week.
c. Now $dR/dt = 0.08\exp(0.8)t$, which exceeds $0.9$ when $\exp(0.8 t)>0.9/0.08=11.25$. By taking the natural logarithm again, we have that $t >\ln(11.25)/0.08 = 30.25$. Which is now a much longer time period before a national lockdown is required.
</details>
|
a221c51b9bfd39e85d5fe717e37a167d72e2d0d8
|
{
"blob_id": "a221c51b9bfd39e85d5fe717e37a167d72e2d0d8",
"branch_name": "refs/heads/master",
"committer_date": "2023-03-08T20:18:46",
"content_id": "1242907d8064522e7540789c27f5bf7500fcecf7",
"detected_licenses": [
"MIT"
],
"directory_id": "64dd7c9af20406d9f645bc20030a43c0ff4a33fb",
"extension": "md",
"filename": "2020-11-01-modelling-with-differentiation.md",
"fork_events_count": 0,
"gha_created_at": "2017-12-06T08:53:28",
"gha_event_created_at": "2021-01-13T16:52:21",
"gha_language": "HTML",
"gha_license_id": "MIT",
"github_id": 113292117,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 14884,
"license": "MIT",
"license_type": "permissive",
"path": "/tutoring/a_level/_posts/2020-11-01-modelling-with-differentiation.md",
"provenance": "stack-edu-markdown-0016.json.gz:172535",
"repo_name": "pauldruce/pauldruce.github.io",
"revision_date": "2023-03-08T20:18:46",
"revision_id": "3b0a925a9c345dceec41aa86709818600a01e06c",
"snapshot_id": "e8577d45c5e32eb04b849a9facc22d54984a3408",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/pauldruce/pauldruce.github.io/3b0a925a9c345dceec41aa86709818600a01e06c/tutoring/a_level/_posts/2020-11-01-modelling-with-differentiation.md",
"visit_date": "2023-03-20T03:03:26.488633",
"added": "2024-11-19T00:06:36.379664+00:00",
"created": "2023-03-08T20:18:46",
"int_score": 4,
"score": 3.9375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0016.json.gz"
}
|
package gateway
import (
"encoding/json"
"io"
"text/template"
)
// PlaygroundConfig contains configuration for rendering a playground UI with a few, critical settings.
type PlaygroundConfig struct {
Endpoint string `json:"endpoint"`
Settings PlaygroundSettings `json:"settings"`
}
// PlaygroundSettings contains settings for setting up a playground UI.
// It contains only a few, critical settings to provide a stronger backward-compatibility guarantee.
//
// If you need more options, consider opening an issue or serving your own custom playground UI.
type PlaygroundSettings struct {
// options correspond to these: https://github.com/graphql/graphql-playground#settings
RequestCredentials string `json:"request.credentials"`
RequestGlobalHeaders map[string]string `json:"request.globalHeaders"`
}
func writePlayground(w io.Writer, config PlaygroundConfig) error {
return playgroundTemplate.Execute(w, config)
}
var playgroundTemplate = template.Must(template.New("").Funcs(map[string]interface{}{
"toJSON": func(v interface{}) (string, error) {
bytes, err := json.Marshal(v)
return string(bytes), err
},
}).Parse(playgroundContent))
// playgroundContent sourced from here: https://github.com/graphql/graphql-playground/blob/main/packages/graphql-playground-html/minimal.html
const playgroundContent = `
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8/>
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, minimal-ui">
<title>GraphQL Playground</title>
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/graphql-playground-react/build/static/css/index.css" />
<link rel="shortcut icon" href="//cdn.jsdelivr.net/npm/graphql-playground-react/build/favicon.png" />
<script src="//cdn.jsdelivr.net/npm/graphql-playground-react/build/static/js/middleware.js"></script>
</head>
<body>
<div id="root">
<style>
body {
background-color: rgb(23, 42, 58);
font-family: Open Sans, sans-serif;
height: 90vh;
}
#root {
height: 100%;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.loading {
font-size: 32px;
font-weight: 200;
color: rgba(255, 255, 255, .6);
margin-left: 20px;
}
img {
width: 78px;
height: 78px;
}
.title {
font-weight: 400;
}
</style>
<img src='//cdn.jsdelivr.net/npm/graphql-playground-react/build/logo.png' alt=''>
<div class="loading"> Loading
<span class="title">GraphQL Playground</span>
</div>
</div>
<script>window.addEventListener('load', function (event) {
GraphQLPlayground.init(document.getElementById('root'), {{ . | toJSON }})
})</script>
</body>
</html>
`
|
6133c04118b9ab0511a24a24ffdb1235df3fa0b1
|
{
"blob_id": "6133c04118b9ab0511a24a24ffdb1235df3fa0b1",
"branch_name": "refs/heads/master",
"committer_date": "2023-06-08T22:21:48",
"content_id": "d731f1ffc25b151f2b40b6bfd8f6dcbb01d81f4b",
"detected_licenses": [
"MIT"
],
"directory_id": "df27213913085d96766d7134a0c251d246eba7d7",
"extension": "go",
"filename": "graphiql.go",
"fork_events_count": 58,
"gha_created_at": "2018-12-30T02:28:14",
"gha_event_created_at": "2023-06-08T22:21:49",
"gha_language": "Go",
"gha_license_id": "MIT",
"github_id": 163555743,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 2850,
"license": "MIT",
"license_type": "permissive",
"path": "/graphiql.go",
"provenance": "stack-edu-0018.json.gz:339420",
"repo_name": "nautilus/gateway",
"revision_date": "2023-06-08T22:21:48",
"revision_id": "4f5f37754f5480162d6c7fcd6bd21955c337c0d9",
"snapshot_id": "bcfb177ef516c4b3aea37424975de82eeaaee637",
"src_encoding": "UTF-8",
"star_events_count": 389,
"url": "https://raw.githubusercontent.com/nautilus/gateway/4f5f37754f5480162d6c7fcd6bd21955c337c0d9/graphiql.go",
"visit_date": "2023-07-01T12:27:20.649261",
"added": "2024-11-19T01:51:39.589154+00:00",
"created": "2023-06-08T22:21:48",
"int_score": 2,
"score": 2.375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0036.json.gz"
}
|
Build the SENĆOŦEN wordlist
===========================
Requirements
------------
* GNU `make`
* Python >= 3.6
* `SaanichWordFreq.txt` from Dr. Montler
How
---
Type `make` in this directory. That's all!
|
dc4b6a7cf0d50aaf4ffa95149c797d9bef2d3b77
|
{
"blob_id": "dc4b6a7cf0d50aaf4ffa95149c797d9bef2d3b77",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-29T16:08:06",
"content_id": "88e96c69ca97b9c86642456b4cfe08d36acc5293",
"detected_licenses": [
"MIT"
],
"directory_id": "73726c3bd3db0bd4f2be54cde663887ccf36ffc9",
"extension": "md",
"filename": "README.md",
"fork_events_count": 36,
"gha_created_at": "2019-01-26T14:10:41",
"gha_event_created_at": "2023-08-14T20:59:18",
"gha_language": "HTML",
"gha_license_id": "MIT",
"github_id": 167696050,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 212,
"license": "MIT",
"license_type": "permissive",
"path": "/release/nrc/nrc.str.sencoten/extras/README.md",
"provenance": "stack-edu-markdown-0008.json.gz:104511",
"repo_name": "keymanapp/lexical-models",
"revision_date": "2023-07-29T16:08:06",
"revision_id": "7baa65560e31dee4e7426c0746db04de8fdb7465",
"snapshot_id": "d04f88346595cd84b275304ee5875b58fc3728e2",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/keymanapp/lexical-models/7baa65560e31dee4e7426c0746db04de8fdb7465/release/nrc/nrc.str.sencoten/extras/README.md",
"visit_date": "2023-08-18T09:32:36.559842",
"added": "2024-11-18T21:33:02.351340+00:00",
"created": "2023-07-29T16:08:06",
"int_score": 2,
"score": 2.078125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0008.json.gz"
}
|
import {
Position, window, Selection
} from 'vscode';
export function 尝试插入词典标签(标签名: "//##{}#" | "//#{}#") {
if (window.activeTextEditor) {
let 当前编辑器 = window.activeTextEditor
let 当前文档 = window.activeTextEditor.document
let 选择 = 当前编辑器.selection
let 当前行对象 = 当前文档.lineAt(选择.isReversed ? 选择.anchor.line : 选择.active.line)
let 行 = 选择.isReversed ? 选择.anchor.line : 选择.active.line
let 前部空格 = 当前行对象.text.substring(0, 当前行对象.firstNonWhitespaceCharacterIndex)
let 词典头 = 前部空格 + 标签名 + "\n"
let 位置 = new Position(行, 0)
if (当前行对象.isEmptyOrWhitespace) {
词典头 = 前部空格 + 标签名
}
if (/^\s*\/\/+\s?(#|##)\{.+$/.test(当前行对象.text)) {
位置 = new Position(行 + 1, 0)
}
当前编辑器.edit(E => {
E.replace(位置, 词典头)
})
let 新位置 = new Position(位置.line, 词典头.lastIndexOf("{") + 1)
let 新选择 = new Selection(新位置, 新位置)
当前编辑器.selection = 新选择
}
}
|
2584eda1555d06a3ca2659625b894ea73998e60e
|
{
"blob_id": "2584eda1555d06a3ca2659625b894ea73998e60e",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-02T06:00:52",
"content_id": "91b576c1b2e88e1ecd3c03135c3cb99fa41133c2",
"detected_licenses": [
"MIT"
],
"directory_id": "0ac03ecf0b8a52d1e1c6965b1fdcea31d5336ae5",
"extension": "ts",
"filename": "插入词典标签.ts",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 119939945,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 1249,
"license": "MIT",
"license_type": "permissive",
"path": "/src/features/中文插件/插入词典标签.ts",
"provenance": "stack-edu-0072.json.gz:363101",
"repo_name": "program-in-chinese/vsc_cts",
"revision_date": "2018-02-02T06:00:52",
"revision_id": "43b794ef0c5b4e0038d26522dcefc792fa73c74d",
"snapshot_id": "16153a1c677b5ff2d6bfcbc852c8a96b8d4445c7",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/program-in-chinese/vsc_cts/43b794ef0c5b4e0038d26522dcefc792fa73c74d/src/features/中文插件/插入词典标签.ts",
"visit_date": "2021-05-16T16:25:35.485797",
"added": "2024-11-19T01:18:02.681070+00:00",
"created": "2018-02-02T06:00:52",
"int_score": 3,
"score": 2.609375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0090.json.gz"
}
|
using System;
using System.Collections.Generic;
namespace Gw2Sharp.WebApi.V2.Models
{
/// <summary>
/// Represents a WvW upgrade.
/// </summary>
public class WvwUpgrade : ApiV2BaseObject, IIdentifiable<int>
{
/// <summary>
/// The upgrade id.
/// </summary>
public int Id { get; set; }
/// <summary>
/// The upgrade tiers.
/// </summary>
public IReadOnlyList<WvwUpgradeTier> Tiers { get; set; } = Array.Empty<WvwUpgradeTier>();
}
}
|
e9ee349847fcc3b910d715c17d841283abdb9849
|
{
"blob_id": "e9ee349847fcc3b910d715c17d841283abdb9849",
"branch_name": "refs/heads/master",
"committer_date": "2023-02-28T21:24:50",
"content_id": "8249e6637ce18c94ce2a6b25267d620d72213842",
"detected_licenses": [
"MIT"
],
"directory_id": "3567f3b051bf270cc64f895b7d8aabbb12bd9318",
"extension": "cs",
"filename": "WvwUpgrade.cs",
"fork_events_count": 0,
"gha_created_at": "2020-01-23T02:24:45",
"gha_event_created_at": "2020-01-23T02:24:46",
"gha_language": null,
"gha_license_id": null,
"github_id": 235709122,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 522,
"license": "MIT",
"license_type": "permissive",
"path": "/Gw2Sharp/WebApi/V2/Models/Wvw/WvwUpgrade.cs",
"provenance": "stack-edu-0011.json.gz:718807",
"repo_name": "dlamkins/Gw2Sharp",
"revision_date": "2023-02-28T21:24:50",
"revision_id": "e9efd5a721ad4082b22fea13ee0604b51aa14000",
"snapshot_id": "ecc0ec4c0ba9d9e80d9bc8a7e3cf75dabfe83eda",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dlamkins/Gw2Sharp/e9efd5a721ad4082b22fea13ee0604b51aa14000/Gw2Sharp/WebApi/V2/Models/Wvw/WvwUpgrade.cs",
"visit_date": "2023-03-03T19:05:07.450947",
"added": "2024-11-19T01:28:01.775644+00:00",
"created": "2023-02-28T21:24:50",
"int_score": 2,
"score": 2.09375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0029.json.gz"
}
|
/// <reference path="./syntax.ts" />
/// <reference path="./lexer.ts" />
class Parser {
public static run (code:string): Program {
let tokens:Array<Token> = RacketLexer.parse(code);
let definitions:Array<Definition> = [];
let expressions:Array<Expression> = [];
let index:number = 0;
while(index < tokens.length) {
let scope = ParseTree.parse(tokens, index, tokens.length);
index += scope.size;
if (scope.body[0] instanceof Token && scope.body[0].text == "define") {
definitions.push(Parser.fetchDefinition(scope));
} else {
expressions.push(Parser.fetch(scope));
}
}
return Syntax.createProgram(definitions, expressions);
}
public static fetchDefinition (node:ParseTree): Definition {
let identifiers:Array<string> = Parser.fetchIdentifier(node.body[1]);
let identifier:string = identifiers[0];
let parameters:Array<string> = identifiers.slice(1);
let expression:Expression = Parser.fetch(node.body[2]);
let lambda = Syntax.createLambdaExpression(parameters, expression);
return Syntax.createDefinition(identifier, lambda);
}
public static fetch (node:ParseTree): Expression {
if (node instanceof Token) {
let token = node as Token;
if (token.type == TokenType.NUMBER) {
return Syntax.createConstantExpression(Syntax.createNumberData(token.text));
} else if (token.type == TokenType.BOOLEAN) {
return Syntax.createConstantExpression(Syntax.createBooleanData(token.text));
} else if (token.type == TokenType.STRING) {
return Syntax.createConstantExpression(Syntax.createQuotedStringData(token.text));
} else {
return Syntax.createIdentifierExpression(node.text);
}
}
let operator = node.body[0];
if (operator instanceof ParseTree) {
return Parser.fetchCallExpression(node);
}
if (operator.type != TokenType.IDENTIFIER) {
console.error("why?");
}
switch(operator.text) {
case "let":
return Parser.fetchLetExpression(node);
case "lambda":
case "λ":
return Parser.fetchLambdaExpression(node);
case "if":
return Parser.fetchIfExpression(node);
default:
return Parser.fetchCallExpression(node);
}
}
public static fetchLambdaExpression (node:ParseTree): LambdaExpression {
// node.body[0] must be lambda or λ
let formals:Array<string> = Parser.fetchIdentifier(node.body[1]);
let expression:Expression = Parser.fetch(node.body[2]);
return Syntax.createLambdaExpression(formals, expression);
}
public static fetchCallExpression (node:ParseTree): CallExpression {
let operator:Expression = null;
let parameters:Array<Expression> = [];
node.body.forEach(element => {
let exp:Expression = Parser.fetch(element);
if (operator == null) {
operator = exp;
} else {
parameters.push(exp);
}
});
return Syntax.createCallExpression(operator, parameters);
}
public static fetchLetExpression (node:ParseTree): BindExpression {
let bindings:Array<[string,Expression]> = Parser.fetchBindings(node.body[1]);
let expression:Expression = Parser.fetch(node.body[2]);
return Syntax.createBindExpression(bindings, expression);
}
public static fetchIfExpression (node:ParseTree): IfExpression {
if (node.body.length != 4) {
throw new Error("if expression should conatins 3 expressions");
}
let testExpression = Parser.fetch(node.body[1]);
let thenExpression = Parser.fetch(node.body[2]);
let elseExpression = Parser.fetch(node.body[3]);
return Syntax.createIfExpression(testExpression, thenExpression, elseExpression)
}
public static fetchBinding (node:ParseTree): [string,Expression] {
let identifier:string = node.body[0].text;
let expression:Expression = Parser.fetch(node.body[1]);
return [identifier,expression];
}
public static fetchBindings (node:ParseTree): Array<[string,Expression]> {
let bindings:Array<[string,Expression]> = [];
node.body.forEach(element => {
bindings.push(Parser.fetchBinding(element));
});
return bindings;
}
/**
* Fetch a list of identifiers in a ParseTree node.
* All elements must be identifier tokens.
*
* @param node a ParseTree node
*/
public static fetchIdentifier (node:ParseTree): Array<string> {
let parameters:Array<string> = [];
node.body.forEach(element => {
let tokenElement = element as Token;
parameters.push(tokenElement.text);
});
return parameters;
}
}
class ParseTree {
body:Array<any>;
size:number;
constructor() {
this.body = [];
this.size = 0;
}
public static parse(tokens:Array<Token>, index:number, length:number):ParseTree {
let startToken = tokens[index].text;
let endToken = "";
if (startToken == "(") {
endToken = ")";
} else if (startToken == "[") {
endToken = "]";
} else if (startToken == "{") {
endToken = "}";
}
index ++;
let obj:ParseTree = new ParseTree();
obj.size += 1;
while(index < length) {
let currentToken = tokens[index].text;
if (currentToken == "(" || currentToken == "[" || currentToken == "{") {
let subObj:ParseTree = ParseTree.parse(tokens, index, length);
obj.body.push(subObj);
index += subObj.size;
obj.size += subObj.size;
} else if (currentToken == endToken) {
obj.size += 1;
break;
} else {
obj.body.push(tokens[index]);
index += 1;
obj.size += 1;
}
}
return obj;
}
}
|
46db7f702d20c2f05e182d4c7c6392df08d40852
|
{
"blob_id": "46db7f702d20c2f05e182d4c7c6392df08d40852",
"branch_name": "refs/heads/master",
"committer_date": "2017-04-17T23:59:00",
"content_id": "8d9934e194cdd201b6e1e18783afaadb76057ad4",
"detected_licenses": [
"MIT"
],
"directory_id": "10d9ccee01135254c43f83fa8cb91dcc7bf7779d",
"extension": "ts",
"filename": "parser.ts",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 87040603,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 6362,
"license": "MIT",
"license_type": "permissive",
"path": "/src/interpreter/parser.ts",
"provenance": "stack-edu-0074.json.gz:418458",
"repo_name": "yangyuan/racket.js",
"revision_date": "2017-04-17T23:59:00",
"revision_id": "b19473e6363556d4fa9ed4033ffb62fc08b54da5",
"snapshot_id": "96e133b5a4fb974ef4b3709f7be838d0ca487f63",
"src_encoding": "UTF-8",
"star_events_count": 13,
"url": "https://raw.githubusercontent.com/yangyuan/racket.js/b19473e6363556d4fa9ed4033ffb62fc08b54da5/src/interpreter/parser.ts",
"visit_date": "2021-01-18T22:15:56.123178",
"added": "2024-11-19T00:14:31.542431+00:00",
"created": "2017-04-17T23:59:00",
"int_score": 3,
"score": 3.25,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0092.json.gz"
}
|
import hmac
import json
import os
import uuid
from base64 import encodebytes
from datetime import datetime
from hashlib import sha1
from urllib.error import HTTPError
from urllib.parse import urlencode, quote_plus
from urllib.request import urlopen
def log(*args, **kwargs):
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"), ":", *args, *kwargs)
def get_ip_address():
url = 'http://members.3322.org/dyndns/getip'
try:
res = urlopen(url)
body = res.read().decode().strip()
return body
except RuntimeError as e:
log("获取公网ip失败:", e.args)
return None
def get_domain_record():
params = {
"Action": "DescribeSubDomainRecords",
"SubDomain": os.getenv("DOMAIN"),
}
signed_params = get_signed_params("GET", params)
url = "http://alidns.aliyuncs.com/?" + urlencode(signed_params)
try:
res = json.loads(urlopen(url).read().decode())
if res["TotalCount"] == 0:
return None
return res["DomainRecords"]["Record"][0]
except RuntimeError as e:
log("获取域名解析失败:", e)
def update_domain_record(record):
params = {
"Action": "UpdateDomainRecord",
"RecordId": record["RecordId"],
"RR": record["RR"],
"Type": record["Type"],
"Value": record["Value"]
}
signed_params = get_signed_params("GET", params)
url = "http://alidns.aliyuncs.com/?" + urlencode(signed_params)
try:
urlopen(url)
log("更新域名解析成功!")
except HTTPError as e:
log("更新域名解析失败:", e)
def add_domain_record(record):
params = {
"Action": "AddDomainRecord",
"DomainName": record["DomainName"],
"RR": record["RR"],
"Type": record["Type"],
"Value": record["Value"]
}
signed_params = get_signed_params("GET", params)
url = "http://alidns.aliyuncs.com/?" + urlencode(signed_params)
try:
urlopen(url)
log("添加域名解析成功!")
except HTTPError as e:
log("添加域名解析失败:", e)
def get_common_params():
"""
获取公共参数
参考文档:https://help.aliyun.com/document_detail/29745.html?spm=5176.doc29776.6.588.sYhLJ0
"""
return {
'Format': 'JSON',
'Version': '2015-01-09',
'AccessKeyId': os.getenv('ACCESS_KEY'),
'SignatureMethod': 'HMAC-SHA1',
'Timestamp': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'),
'SignatureVersion': '1.0',
'SignatureNonce': uuid.uuid4()
}
def get_signed_params(http_method, params):
"""
参考文档:https://help.aliyun.com/document_detail/29747.html?spm=5176.doc29745.2.1.V2tmbU
"""
# 1、合并参数,不包括Signature
params.update(get_common_params())
# 2、按照参数的字典顺序排序
sorted_params = sorted(params.items())
# 3、encode 参数
query_params = urlencode(sorted_params)
# 4、构造需要签名的字符串
str_to_sign = "&".join([http_method, quote_plus("/"), quote_plus(query_params)])
# 5、计算签名
h = hmac.new((os.getenv('ACCESS_SECRET') + '&').encode('ASCII'), str_to_sign.encode('ASCII'), sha1)
signature = encodebytes(h.digest()).strip()
# 6、将签名加入参数中
params['Signature'] = signature
return params
def main():
# 获取当前公网ip地址
address = get_ip_address()
# 获取当前解析配置
record = get_domain_record()
if record is not None:
if record["Value"] != address:
record["Value"] = address
log("更新域名解析IP地址为:", address)
update_domain_record(record)
else:
log("当前IP地址有效:", address)
else:
domains = os.getenv("DOMAIN").split(".")
record = {
"DomainName": ".".join(domains[1:]),
"RR": domains[0],
"Type": "A",
"Value": address
}
log("添加域名解析IP地址:", address)
add_domain_record(record)
if __name__ == '__main__':
main()
|
b3d41d591894da8f0cb9f722f6527dc4ca14ac74
|
{
"blob_id": "b3d41d591894da8f0cb9f722f6527dc4ca14ac74",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-08T08:09:05",
"content_id": "15b6aa28bee21e307d6db96e31a9d6b0553fe589",
"detected_licenses": [
"MIT"
],
"directory_id": "4ed9552cb390edf87034f25df5a572a3776e827b",
"extension": "py",
"filename": "ddns.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4132,
"license": "MIT",
"license_type": "permissive",
"path": "/ddns.py",
"provenance": "stack-edu-0060.json.gz:420520",
"repo_name": "colababy/dockerlize-aliyun-ddns",
"revision_date": "2019-01-08T08:09:05",
"revision_id": "2a54e3dd0b5dcecea8f0741c8f053cf55bb008d0",
"snapshot_id": "86aefb22b2509ee5b8792fae6849ace511850ed7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/colababy/dockerlize-aliyun-ddns/2a54e3dd0b5dcecea8f0741c8f053cf55bb008d0/ddns.py",
"visit_date": "2020-04-14T11:53:30.990482",
"added": "2024-11-18T19:44:28.051296+00:00",
"created": "2019-01-08T08:09:05",
"int_score": 3,
"score": 2.546875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0078.json.gz"
}
|
#calss header
class _LOUT():
def __init__(self,):
self.name = "LOUT"
self.definitions = [u'a young man who behaves in a very rude, offensive, and sometimes violent way: ']
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.specie = 'nouns'
def run(self, obj1 = [], obj2 = []):
return self.jsondata
|
b78c6faf011aeb99db312bd5f41005dd04bdb881
|
{
"blob_id": "b78c6faf011aeb99db312bd5f41005dd04bdb881",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-28T02:00:50",
"content_id": "9c91344b285d7aa443f119818d22b5c3107eea26",
"detected_licenses": [
"MIT"
],
"directory_id": "9743d5fd24822f79c156ad112229e25adb9ed6f6",
"extension": "py",
"filename": "_lout.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 354,
"license": "MIT",
"license_type": "permissive",
"path": "/xai/brain/wordbase/nouns/_lout.py",
"provenance": "stack-edu-0057.json.gz:371658",
"repo_name": "cash2one/xai",
"revision_date": "2017-01-28T02:00:50",
"revision_id": "e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6",
"snapshot_id": "de7adad1758f50dd6786bf0111e71a903f039b64",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cash2one/xai/e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6/xai/brain/wordbase/nouns/_lout.py",
"visit_date": "2021-01-19T12:33:54.964379",
"added": "2024-11-18T22:44:21.172480+00:00",
"created": "2017-01-28T02:00:50",
"int_score": 2,
"score": 2.46875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0075.json.gz"
}
|
# Invite Keys
Invite keys are used by Chat API for public blockchain account resolution.
When we are creating claims describing a chat invite key we must use the following mandatory fields in the jwt:
* iat - timestamp when jwt was issued
* exp - timestamp when jwt must expire
* iss - public identity key in form of did:key according to the [Ed25519](https://w3c-ccg.github.io/did-method-key/#ed25519-x25519)
* sub - public key for chat invite key in form of did:key according to the [X25519](https://w3c-ccg.github.io/did-method-key/#x25519)
* aud - key server URL used for registering
* pkh - corresponding blockchain account (did:pkh)
* act - description of action intent. Must be equal to specific value defined in each claims
Expiry will be calculated 1 hour (3600 seconds) from issued date
## Register Invite
When we are validating invite key registration claims we must use specify act:
* act - description of action intent. Must be equal to "register_invite"
## Unregister Invite
When we are validating invite key registration claims we must use specify act:
* act - description of action intent. Must be equal to "unregister_invite"
|
909fcc3fdb1f88898a007680849dad13668da57c
|
{
"blob_id": "909fcc3fdb1f88898a007680849dad13668da57c",
"branch_name": "refs/heads/main",
"committer_date": "2023-09-02T21:12:16",
"content_id": "271488901067e50b053a19b70a301afc1966eac4",
"detected_licenses": [
"MIT"
],
"directory_id": "c1ab383707518caf148132cb6238b59aa322fe58",
"extension": "md",
"filename": "invite-keys.md",
"fork_events_count": 304,
"gha_created_at": "2018-05-22T18:06:13",
"gha_event_created_at": "2023-09-14T15:25:58",
"gha_language": "CSS",
"gha_license_id": "MIT",
"github_id": 134455847,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1152,
"license": "MIT",
"license_type": "permissive",
"path": "/docs/specs/clients/chat/invite-keys.md",
"provenance": "stack-edu-markdown-0009.json.gz:85418",
"repo_name": "WalletConnect/walletconnect-docs",
"revision_date": "2023-09-02T21:12:16",
"revision_id": "bc06a39f37effd79cbb3b0d59c201c1e3346cbdd",
"snapshot_id": "3ff0da093117c81af41322baf28ad014fbef859b",
"src_encoding": "UTF-8",
"star_events_count": 371,
"url": "https://raw.githubusercontent.com/WalletConnect/walletconnect-docs/bc06a39f37effd79cbb3b0d59c201c1e3346cbdd/docs/specs/clients/chat/invite-keys.md",
"visit_date": "2023-09-04T04:40:41.643956",
"added": "2024-11-18T23:37:19.597345+00:00",
"created": "2023-09-02T21:12:16",
"int_score": 3,
"score": 3.265625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0009.json.gz"
}
|
var firewall = require('../util/firewall'),
reportDao = require('../dao/report');
module.exports = function (app) {
function handleError(res) {
return function (err) {
console.error(err);
res.send(500, 'Internal Server Error');
};
}
app.get('/reports', firewall('admin', function (req, res) {
var locals = {
user: req.user
};
reportDao.getAppointmentsDailyStats().then(function (stats) {
locals.appointments_daily_stats = stats;
return reportDao.getWorkersDailyStats();
}).then(function (stats) {
locals.workers_daily_stats = stats;
}).then(function () {
res.render('reports/index', locals);
}).catch(handleError(res));
}));
};
|
692d5692dece83e2603f571431b039aa93a8268e
|
{
"blob_id": "692d5692dece83e2603f571431b039aa93a8268e",
"branch_name": "refs/heads/master",
"committer_date": "2014-02-23T20:39:02",
"content_id": "79b21f6c205a6029b76f64204a51f0f873e97da5",
"detected_licenses": [
"MIT"
],
"directory_id": "870d7a999a87b04ae22ab5a1335484150e931e59",
"extension": "js",
"filename": "reports.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 801,
"license": "MIT",
"license_type": "permissive",
"path": "/src/controller/reports.js",
"provenance": "stack-edu-0036.json.gz:293923",
"repo_name": "nfrolov/useless-barbershop",
"revision_date": "2014-02-23T20:39:02",
"revision_id": "40d033a9bc923cb02895b12eeda7e6a2c0bb6235",
"snapshot_id": "a9a782b4d27f847899738155ee8e5449bd3288cf",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/nfrolov/useless-barbershop/40d033a9bc923cb02895b12eeda7e6a2c0bb6235/src/controller/reports.js",
"visit_date": "2021-01-23T17:59:13.949136",
"added": "2024-11-18T23:39:14.168830+00:00",
"created": "2014-02-23T20:39:02",
"int_score": 2,
"score": 2.328125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0054.json.gz"
}
|
<?php
namespace SilverStripe\Assets\Flysystem;
use Generator;
use InvalidArgumentException;
use League\Flysystem\Directory;
use League\Flysystem\Exception;
use League\Flysystem\Filesystem;
use League\Flysystem\Util;
use LogicException;
use SilverStripe\Assets\File;
use SilverStripe\Assets\Storage\AssetNameGenerator;
use SilverStripe\Assets\Storage\AssetStore;
use SilverStripe\Assets\Storage\AssetStoreRouter;
use SilverStripe\Control\Controller;
use SilverStripe\Control\Director;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\Control\HTTPStreamResponse;
use SilverStripe\Core\Config\Configurable;
use SilverStripe\Core\Flushable;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\ORM\DB;
use SilverStripe\Versioned\Versioned;
/**
* Asset store based on flysystem Filesystem as a backend
*/
class FlysystemAssetStore implements AssetStore, AssetStoreRouter, Flushable
{
use Configurable;
/**
* Session key to use for user grants
*/
const GRANTS_SESSION = 'AssetStore_Grants';
/**
* @var Filesystem
*/
private $publicFilesystem = null;
/**
* Filesystem to use for protected files
*
* @var Filesystem
*/
private $protectedFilesystem = null;
/**
* Enable to use legacy filename behaviour (omits hash)
*
* Note that if using legacy filenames then duplicate files will not work.
*
* @config
* @var bool
*/
private static $legacy_filenames = false;
/**
* Flag if empty folders are allowed.
* If false, empty folders are cleared up when their contents are deleted.
*
* @config
* @var bool
*/
private static $keep_empty_dirs = false;
/**
* Set HTTP error code for requests to secure denied assets.
* Note that this defaults to 404 to prevent information disclosure
* of secure files
*
* @config
* @var int
*/
private static $denied_response_code = 404;
/**
* Set HTTP error code to use for missing secure assets
*
* @config
* @var int
*/
private static $missing_response_code = 404;
/**
* Define the HTTP Response code for request that should be redirected to a different URL. Defaults to a temporary
* redirection (302). Set to 308 if you would rather your redirections be permanent and indicate to search engine
* that they should index the other file.
* @config
* @var int
*/
private static $redirect_response_code = 302;
/**
* Custom headers to add to all custom file responses
*
* @config
* @var array
*/
private static $file_response_headers = array(
'Cache-Control' => 'private'
);
/**
* Assign new flysystem backend
*
* @param Filesystem $filesystem
* @return $this
*/
public function setPublicFilesystem(Filesystem $filesystem)
{
if (!$filesystem->getAdapter() instanceof PublicAdapter) {
throw new InvalidArgumentException("Configured adapter must implement PublicAdapter");
}
$this->publicFilesystem = $filesystem;
return $this;
}
/**
* Get the currently assigned flysystem backend
*
* @return Filesystem
* @throws LogicException
*/
public function getPublicFilesystem()
{
if (!$this->publicFilesystem) {
throw new LogicException("Filesystem misconfiguration error");
}
return $this->publicFilesystem;
}
/**
* Assign filesystem to use for non-public files
*
* @param Filesystem $filesystem
* @return $this
*/
public function setProtectedFilesystem(Filesystem $filesystem)
{
if (!$filesystem->getAdapter() instanceof ProtectedAdapter) {
throw new InvalidArgumentException("Configured adapter must implement ProtectedAdapter");
}
$this->protectedFilesystem = $filesystem;
return $this;
}
/**
* Get filesystem to use for non-public files
*
* @return Filesystem
* @throws Exception
*/
public function getProtectedFilesystem()
{
if (!$this->protectedFilesystem) {
throw new Exception("Filesystem misconfiguration error");
}
return $this->protectedFilesystem;
}
/**
* Return the store that contains the given fileID
*
* @param string $fileID Internal file identifier
* @return Filesystem
*/
protected function getFilesystemFor($fileID)
{
if ($this->getPublicFilesystem()->has($fileID)) {
return $this->getPublicFilesystem();
}
if ($this->getProtectedFilesystem()->has($fileID)) {
return $this->getProtectedFilesystem();
}
return null;
}
public function getCapabilities()
{
return array(
'visibility' => array(
self::VISIBILITY_PUBLIC,
self::VISIBILITY_PROTECTED
),
'conflict' => array(
self::CONFLICT_EXCEPTION,
self::CONFLICT_OVERWRITE,
self::CONFLICT_RENAME,
self::CONFLICT_USE_EXISTING
)
);
}
public function getVisibility($filename, $hash)
{
$fileID = $this->getFileID($filename, $hash);
if ($this->getPublicFilesystem()->has($fileID)) {
return self::VISIBILITY_PUBLIC;
}
if ($this->getProtectedFilesystem()->has($fileID)) {
return self::VISIBILITY_PROTECTED;
}
return null;
}
public function getAsStream($filename, $hash, $variant = null)
{
$fileID = $this->getFileID($filename, $hash, $variant);
return $this
->getFilesystemFor($fileID)
->readStream($fileID);
}
public function getAsString($filename, $hash, $variant = null)
{
$fileID = $this->getFileID($filename, $hash, $variant);
return $this
->getFilesystemFor($fileID)
->read($fileID);
}
public function getAsURL($filename, $hash, $variant = null, $grant = true)
{
$fileID = $this->getFileID($filename, $hash, $variant);
// Check with filesystem this asset exists in
$public = $this->getPublicFilesystem();
$protected = $this->getProtectedFilesystem();
if ($public->has($fileID) || !$protected->has($fileID)) {
/** @var PublicAdapter $publicAdapter */
$publicAdapter = $public->getAdapter();
return $publicAdapter->getPublicUrl($fileID);
}
if ($grant) {
$this->grant($filename, $hash);
}
/** @var ProtectedAdapter $protectedAdapter */
$protectedAdapter = $protected->getAdapter();
return $protectedAdapter->getProtectedUrl($fileID);
}
public function setFromLocalFile($path, $filename = null, $hash = null, $variant = null, $config = array())
{
// Validate this file exists
if (!file_exists($path)) {
throw new InvalidArgumentException("$path does not exist");
}
// Get filename to save to
if (empty($filename)) {
$filename = basename($path);
}
// Callback for saving content
$callback = function (Filesystem $filesystem, $fileID) use ($path) {
// Read contents as string into flysystem
$handle = fopen($path, 'r');
if ($handle === false) {
throw new InvalidArgumentException("$path could not be opened for reading");
}
$result = $filesystem->putStream($fileID, $handle);
if (is_resource($handle)) {
fclose($handle);
}
return $result;
};
// When saving original filename, generate hash
if (!$variant) {
$hash = sha1_file($path);
}
// Submit to conflict check
return $this->writeWithCallback($callback, $filename, $hash, $variant, $config);
}
public function setFromString($data, $filename, $hash = null, $variant = null, $config = array())
{
// Callback for saving content
$callback = function (Filesystem $filesystem, $fileID) use ($data) {
return $filesystem->put($fileID, $data);
};
// When saving original filename, generate hash
if (!$variant) {
$hash = sha1($data);
}
// Submit to conflict check
return $this->writeWithCallback($callback, $filename, $hash, $variant, $config);
}
public function setFromStream($stream, $filename, $hash = null, $variant = null, $config = array())
{
// If the stream isn't rewindable, write to a temporary filename
if (!$this->isSeekableStream($stream)) {
$path = $this->getStreamAsFile($stream);
$result = $this->setFromLocalFile($path, $filename, $hash, $variant, $config);
unlink($path);
return $result;
}
// Callback for saving content
$callback = function (Filesystem $filesystem, $fileID) use ($stream) {
return $filesystem->putStream($fileID, $stream);
};
// When saving original filename, generate hash
if (!$variant) {
$hash = $this->getStreamSHA1($stream);
}
// Submit to conflict check
return $this->writeWithCallback($callback, $filename, $hash, $variant, $config);
}
public function delete($filename, $hash)
{
$fileID = $this->getFileID($filename, $hash);
$protected = $this->deleteFromFilesystem($fileID, $this->getProtectedFilesystem());
$public = $this->deleteFromFilesystem($fileID, $this->getPublicFilesystem());
return $protected || $public;
}
public function rename($filename, $hash, $newName)
{
if (empty($newName)) {
throw new InvalidArgumentException("Cannot write to empty filename");
}
if ($newName === $filename) {
return $filename;
}
$newName = $this->cleanFilename($newName);
$fileID = $this->getFileID($filename, $hash);
$filesystem = $this->getFilesystemFor($fileID);
foreach ($this->findVariants($fileID, $filesystem) as $nextID) {
// Get variant and build new ID for this variant
$variant = $this->getVariant($nextID);
$newID = $this->getFileID($newName, $hash, $variant);
$filesystem->rename($nextID, $newID);
}
// Truncate empty dirs
$this->truncateDirectory(dirname($fileID), $filesystem);
return $newName;
}
public function copy($filename, $hash, $newName)
{
if (empty($newName)) {
throw new InvalidArgumentException("Cannot write to empty filename");
}
if ($newName === $filename) {
return $filename;
}
$newName = $this->cleanFilename($newName);
$fileID = $this->getFileID($filename, $hash);
$filesystem = $this->getFilesystemFor($fileID);
foreach ($this->findVariants($fileID, $filesystem) as $nextID) {
// Get variant and build new ID for this variant
$variant = $this->getVariant($nextID);
$newID = $this->getFileID($newName, $hash, $variant);
$filesystem->copy($nextID, $newID);
}
return $newName;
}
/**
* Delete the given file (and any variants) in the given {@see Filesystem}
*
* @param string $fileID
* @param Filesystem $filesystem
* @return bool True if a file was deleted
*/
protected function deleteFromFilesystem($fileID, Filesystem $filesystem)
{
$deleted = false;
foreach ($this->findVariants($fileID, $filesystem) as $nextID) {
$filesystem->delete($nextID);
$deleted = true;
}
// Truncate empty dirs
$this->truncateDirectory(dirname($fileID), $filesystem);
return $deleted;
}
/**
* Clear directory if it's empty
*
* @param string $dirname Name of directory
* @param Filesystem $filesystem
*/
protected function truncateDirectory($dirname, Filesystem $filesystem)
{
if ($dirname
&& ltrim(dirname($dirname), '.')
&& !$this->config()->get('keep_empty_dirs')
&& !$filesystem->listContents($dirname)
) {
$filesystem->deleteDir($dirname);
}
}
/**
* Returns an iterable {@see Generator} of all files / variants for the given $fileID in the given $filesystem
* This includes the empty (no) variant.
*
* @param string $fileID ID of original file to compare with.
* @param Filesystem $filesystem
* @return Generator
*/
protected function findVariants($fileID, Filesystem $filesystem)
{
$dirname = ltrim(dirname($fileID), '.');
foreach ($filesystem->listContents($dirname) as $next) {
if ($next['type'] !== 'file') {
continue;
}
$nextID = $next['path'];
// Compare given file to target, omitting variant
if ($fileID === $this->removeVariant($nextID)) {
yield $nextID;
}
}
}
public function publish($filename, $hash)
{
$fileID = $this->getFileID($filename, $hash);
$protected = $this->getProtectedFilesystem();
$public = $this->getPublicFilesystem();
$this->moveBetweenFilesystems($fileID, $protected, $public);
}
public function protect($filename, $hash)
{
$fileID = $this->getFileID($filename, $hash);
$public = $this->getPublicFilesystem();
$protected = $this->getProtectedFilesystem();
$this->moveBetweenFilesystems($fileID, $public, $protected);
}
/**
* Move a file (and its associative variants) between filesystems
*
* @param string $fileID
* @param Filesystem $from
* @param Filesystem $to
*/
protected function moveBetweenFilesystems($fileID, Filesystem $from, Filesystem $to)
{
foreach ($this->findVariants($fileID, $from) as $nextID) {
// Copy via stream
$stream = $from->readStream($nextID);
$to->putStream($nextID, $stream);
if (is_resource($stream)) {
fclose($stream);
}
$from->delete($nextID);
}
// Truncate empty dirs
$this->truncateDirectory(dirname($fileID), $from);
}
public function grant($filename, $hash)
{
$session = Controller::curr()->getRequest()->getSession();
$fileID = $this->getFileID($filename, $hash);
$granted = $session->get(self::GRANTS_SESSION) ?: array();
$granted[$fileID] = true;
$session->set(self::GRANTS_SESSION, $granted);
}
public function revoke($filename, $hash)
{
$fileID = $this->getFileID($filename, $hash);
$session = Controller::curr()->getRequest()->getSession();
$granted = $session->get(self::GRANTS_SESSION) ?: array();
unset($granted[$fileID]);
if ($granted) {
$session->set(self::GRANTS_SESSION, $granted);
} else {
$session->clear(self::GRANTS_SESSION);
}
}
public function canView($filename, $hash)
{
$fileID = $this->getFileID($filename, $hash);
if ($this->getProtectedFilesystem()->has($fileID)) {
return $this->isGranted($fileID);
}
return true;
}
/**
* Determine if a grant exists for the given FileID
*
* @param string $fileID
* @return bool
*/
protected function isGranted($fileID)
{
// Since permissions are applied to the non-variant only,
// map back to the original file before checking
$originalID = $this->removeVariant($fileID);
$session = Controller::curr()->getRequest()->getSession();
$granted = $session->get(self::GRANTS_SESSION) ?: array();
return !empty($granted[$originalID]);
}
/**
* get sha1 hash from stream
*
* @param resource $stream
* @return string str1 hash
*/
protected function getStreamSHA1($stream)
{
Util::rewindStream($stream);
$context = hash_init('sha1');
hash_update_stream($context, $stream);
return hash_final($context);
}
/**
* Get stream as a file
*
* @param resource $stream
* @return string Filename of resulting stream content
* @throws Exception
*/
protected function getStreamAsFile($stream)
{
// Get temporary file and name
$file = tempnam(sys_get_temp_dir(), 'ssflysystem');
$buffer = fopen($file, 'w');
if (!$buffer) {
throw new Exception("Could not create temporary file");
}
// Transfer from given stream
Util::rewindStream($stream);
stream_copy_to_stream($stream, $buffer);
if (!fclose($buffer)) {
throw new Exception("Could not write stream to temporary file");
}
return $file;
}
/**
* Determine if this stream is seekable
*
* @param resource $stream
* @return bool True if this stream is seekable
*/
protected function isSeekableStream($stream)
{
return Util::isSeekableStream($stream);
}
/**
* Invokes the conflict resolution scheme on the given content, and invokes a callback if
* the storage request is approved.
*
* @param callable $callback Will be invoked and passed a fileID if the file should be stored
* @param string $filename Name for the resulting file
* @param string $hash SHA1 of the original file content
* @param string $variant Variant to write
* @param array $config Write options. {@see AssetStore}
* @return array Tuple associative array (Filename, Hash, Variant)
* @throws Exception
*/
protected function writeWithCallback($callback, $filename, $hash, $variant = null, $config = array())
{
// Set default conflict resolution
if (empty($config['conflict'])) {
$conflictResolution = $this->getDefaultConflictResolution($variant);
} else {
$conflictResolution = $config['conflict'];
}
// Validate parameters
if ($variant && $conflictResolution === AssetStore::CONFLICT_RENAME) {
// As variants must follow predictable naming rules, they should not be dynamically renamed
throw new InvalidArgumentException("Rename cannot be used when writing variants");
}
if (!$filename) {
throw new InvalidArgumentException("Filename is missing");
}
if (!$hash) {
throw new InvalidArgumentException("File hash is missing");
}
$filename = $this->cleanFilename($filename);
$fileID = $this->getFileID($filename, $hash, $variant);
// Check conflict resolution scheme
$resolvedID = $this->resolveConflicts($conflictResolution, $fileID);
if ($resolvedID !== false) {
// Check if source file already exists on the filesystem
$mainID = $this->getFileID($filename, $hash);
$filesystem = $this->getFilesystemFor($mainID);
// If writing a new file use the correct visibility
if (!$filesystem) {
// Default to public store unless requesting protected store
if (isset($config['visibility']) && $config['visibility'] === self::VISIBILITY_PROTECTED) {
$filesystem = $this->getProtectedFilesystem();
} else {
$filesystem = $this->getPublicFilesystem();
}
}
// Submit and validate result
$result = $callback($filesystem, $resolvedID);
if (!$result) {
throw new Exception("Could not save {$filename}");
}
// in case conflict resolution renamed the file, return the renamed
$filename = $this->getOriginalFilename($resolvedID);
} elseif (empty($variant)) {
// If deferring to the existing file, return the sha of the existing file,
// unless we are writing a variant (which has the same hash value as its original file)
$stream = $this
->getFilesystemFor($fileID)
->readStream($fileID);
$hash = $this->getStreamSHA1($stream);
}
return array(
'Filename' => $filename,
'Hash' => $hash,
'Variant' => $variant
);
}
/**
* Choose a default conflict resolution
*
* @param string $variant
* @return string
*/
protected function getDefaultConflictResolution($variant)
{
// If using new naming scheme (segment by hash) it's normally safe to overwrite files.
// Variants are also normally safe to overwrite, since lazy-generation is implemented at a higher level.
$legacy = $this->useLegacyFilenames();
if (!$legacy || $variant) {
return AssetStore::CONFLICT_OVERWRITE;
}
// Legacy behaviour is to rename
return AssetStore::CONFLICT_RENAME;
}
/**
* Determine if legacy filenames should be used. These do not have hash path parts.
*
* @return bool
*/
protected function useLegacyFilenames()
{
return $this->config()->get('legacy_filenames');
}
public function getMetadata($filename, $hash, $variant = null)
{
$fileID = $this->getFileID($filename, $hash, $variant);
$filesystem = $this->getFilesystemFor($fileID);
if ($filesystem) {
return $filesystem->getMetadata($fileID);
}
return null;
}
public function getMimeType($filename, $hash, $variant = null)
{
$fileID = $this->getFileID($filename, $hash, $variant);
$filesystem = $this->getFilesystemFor($fileID);
if ($filesystem) {
return $filesystem->getMimetype($fileID);
}
return null;
}
public function exists($filename, $hash, $variant = null)
{
$fileID = $this->getFileID($filename, $hash, $variant);
$filesystem = $this->getFilesystemFor($fileID);
return !empty($filesystem);
}
/**
* Determine the path that should be written to, given the conflict resolution scheme
*
* @param string $conflictResolution
* @param string $fileID
* @return string|false Safe filename to write to. If false, then don't write, and use existing file.
* @throws Exception
*/
protected function resolveConflicts($conflictResolution, $fileID)
{
// If overwrite is requested, simply put
if ($conflictResolution === AssetStore::CONFLICT_OVERWRITE) {
return $fileID;
}
// Otherwise, check if this exists
$exists = $this->getFilesystemFor($fileID);
if (!$exists) {
return $fileID;
}
// Flysystem defaults to use_existing
switch ($conflictResolution) {
// Throw tantrum
case static::CONFLICT_EXCEPTION: {
throw new InvalidArgumentException("File already exists at path {$fileID}");
}
// Rename
case static::CONFLICT_RENAME: {
foreach ($this->fileGeneratorFor($fileID) as $candidate) {
if (!$this->getFilesystemFor($candidate)) {
return $candidate;
}
}
throw new InvalidArgumentException("File could not be renamed with path {$fileID}");
}
// Use existing file
case static::CONFLICT_USE_EXISTING:
default: {
return false;
}
}
}
/**
* Get an asset renamer for the given filename.
*
* @param string $fileID Adapter specific identifier for this file/version
* @return AssetNameGenerator
*/
protected function fileGeneratorFor($fileID)
{
return Injector::inst()->createWithArgs(AssetNameGenerator::class, array($fileID));
}
/**
* Performs filename cleanup before sending it back.
*
* This name should not contain hash or variants.
*
* @param string $filename
* @return string
*/
protected function cleanFilename($filename)
{
// Since we use double underscore to delimit variants, eradicate them from filename
return preg_replace('/_{2,}/', '_', $filename);
}
/**
* Get Filename and Variant from fileid
*
* @param string $fileID
* @return array
*/
protected function parseFileID($fileID)
{
if ($this->useLegacyFilenames()) {
$pattern = '#^(?<folder>([^/]+/)*)(?<basename>((?<!__)[^/.])+)(__(?<variant>[^.]+))?(?<extension>(\..+)*)$#';
} else {
$pattern = '#^(?<folder>([^/]+/)*)(?<hash>[a-zA-Z0-9]{10})/(?<basename>((?<!__)[^/.])+)(__(?<variant>[^.]+))?(?<extension>(\..+)*)$#';
}
// not a valid file (or not a part of the filesystem)
if (!preg_match($pattern, $fileID, $matches)) {
return null;
}
$filename = $matches['folder'] . $matches['basename'] . $matches['extension'];
$variant = isset($matches['variant']) ? $matches['variant'] : null;
$hash = isset($matches['hash']) ? $matches['hash'] : null;
return [
'Filename' => $filename,
'Variant' => $variant,
'Hash' => $hash
];
}
/**
* Try to parse a file ID using the old SilverStripe 3 format legacy or the SS4 legacy filename format.
*
* @param string $fileID
* @return array
*/
private function parseLegacyFileID($fileID)
{
// assets/folder/_resampled/ResizedImageWzEwMCwxMzNd/basename.extension
$ss3Pattern = '#^(?<folder>([^/]+/)*?)(_resampled/(?<variant>([^/.]+))/)?((?<basename>((?<!__)[^/.])+))(?<extension>(\..+)*)$#';
// assets/folder/basename__ResizedImageWzEwMCwxMzNd.extension
$ss4LegacyPattern = '#^(?<folder>([^/]+/)*)(?<basename>((?<!__)[^/.])+)(__(?<variant>[^.]+))?(?<extension>(\..+)*)$#';
// not a valid file (or not a part of the filesystem)
if (!preg_match($ss3Pattern, $fileID, $matches) && !preg_match($ss4LegacyPattern, $fileID, $matches)) {
return null;
}
$filename = $matches['folder'] . $matches['basename'] . $matches['extension'];
$variant = isset($matches['variant']) ? $matches['variant'] : null;
return [
'Filename' => $filename,
'Variant' => $variant
];
}
/**
* Given a FileID, map this back to the original filename, trimming variant and hash
*
* @param string $fileID Adapter specific identifier for this file/version
* @return string Filename for this file, omitting hash and variant
*/
protected function getOriginalFilename($fileID)
{
$parts = $this->parseFileID($fileID);
if (!$parts) {
return null;
}
return $parts['Filename'];
}
/**
* Get variant from this file
*
* @param string $fileID
* @return string
*/
protected function getVariant($fileID)
{
$parts = $this->parseFileID($fileID);
if (!$parts) {
return null;
}
return $parts['Variant'];
}
/**
* Remove variant from a fileID
*
* @param string $fileID
* @return string FileID without variant
*/
protected function removeVariant($fileID)
{
$variant = $this->getVariant($fileID);
if (empty($variant)) {
return $fileID;
}
return str_replace("__{$variant}", '', $fileID);
}
/**
* Map file tuple (hash, name, variant) to a filename to be used by flysystem
*
* The resulting file will look something like my/directory/EA775CB4D4/filename__variant.jpg
*
* @param string $filename Name of file
* @param string $hash Hash of original file
* @param string $variant (if given)
* @return string Adapter specific identifier for this file/version
*/
protected function getFileID($filename, $hash, $variant = null)
{
// Since we use double underscore to delimit variants, eradicate them from filename
$filename = $this->cleanFilename($filename);
$name = basename($filename);
// Split extension
$extension = null;
if (($pos = strpos($name, '.')) !== false) {
$extension = substr($name, $pos);
$name = substr($name, 0, $pos);
}
// Unless in legacy mode, inject hash just prior to the filename
if ($this->useLegacyFilenames()) {
$fileID = $name;
} else {
$fileID = substr($hash, 0, 10) . '/' . $name;
}
// Add directory
$dirname = ltrim(dirname($filename), '.');
if ($dirname) {
$fileID = $dirname . '/' . $fileID;
}
// Add variant
if ($variant) {
$fileID .= '__' . $variant;
}
// Add extension
if ($extension) {
$fileID .= $extension;
}
return $fileID;
}
/**
* Ensure each adapter re-generates its own server configuration files
*/
public static function flush()
{
// Ensure that this instance is constructed on flush, thus forcing
// bootstrapping of necessary .htaccess / web.config files
$instance = singleton(AssetStore::class);
if ($instance instanceof FlysystemAssetStore) {
$public = $instance->getPublicFilesystem();
if ($public instanceof Filesystem) {
$publicAdapter = $public->getAdapter();
if ($publicAdapter instanceof AssetAdapter) {
$publicAdapter->flush();
}
}
$protected = $instance->getProtectedFilesystem();
if ($protected instanceof Filesystem) {
$protectedAdapter = $protected->getAdapter();
if ($protectedAdapter instanceof AssetAdapter) {
$protectedAdapter->flush();
}
}
}
}
public function getResponseFor($asset)
{
$public = $this->getPublicFilesystem();
$protected = $this->getProtectedFilesystem();
// If the file exists on the public store, we just straight return it.
if ($public->has($asset)) {
return $this->createResponseFor($public, $asset);
}
// If the file exists in the protected store and the user has been explicitely granted access to it
if ($protected->has($asset) && $this->isGranted($asset)) {
return $this->createResponseFor($protected, $asset);
// Let's not deny if the file is in the protected store, but is not granted.
// We might be able to redirect to a live version.
}
// If we found a URL to redirect to
if ($redirectUrl = $this->searchForEquivalentFileID($asset)) {
if ($redirectUrl != $asset && $public->has($redirectUrl)) {
return $this->createRedirectResponse($redirectUrl);
} else {
// Something weird is going on e.g. a publish file without a physical file
return $this->createMissingResponse();
}
}
// Deny if file is protected and denied
if ($protected->has($asset)) {
return $this->createDeniedResponse();
}
// We've looked everywhere and couldn't find a file
return $this->createMissingResponse();
}
/**
* Given a FileID, try to find an equivalent file ID for a more recent file using the latest format.
* @param string $asset
* @return string
*/
private function searchForEquivalentFileID($asset)
{
// If File is not versionable, let's bail
if (!class_exists(Versioned::class) || !File::has_extension(Versioned::class)) {
return '';
}
$parsedFileID = $this->parseFileID($asset);
if ($parsedFileID && $parsedFileID['Hash']) {
// Try to find a live version of this file
$stage = Versioned::get_stage();
Versioned::set_stage(Versioned::LIVE);
$file = File::get()->filter(['FileFilename' => $parsedFileID['Filename']])->first();
Versioned::set_stage($stage);
// If we found a matching live file, let's see if our hash was publish at any point
if ($file) {
$oldVersionCount = $file->allVersions(
[
['"FileHash" like ?' => DB::get_conn()->escapeString($parsedFileID['Hash']) . '%'],
['not "FileHash" like ?' => DB::get_conn()->escapeString($file->getHash())],
'WasPublished' => true
],
"",
1
)->count();
// Our hash was published at some other stage
if ($oldVersionCount > 0) {
return $this->getFileID($file->getFilename(), $file->getHash(), $parsedFileID['Variant']);
}
}
}
// Let's see if $asset is a legacy URL that can be map to a current file
$parsedFileID = $this->parseLegacyFileID($asset);
if ($parsedFileID) {
$filename = $parsedFileID['Filename'];
$variant = $parsedFileID['Variant'];
// Let's try to match the plain file name
$stage = Versioned::get_stage();
Versioned::set_stage(Versioned::LIVE);
$file = File::get()->filter(['FileFilename' => $filename])->first();
Versioned::set_stage($stage);
if ($file) {
return $this->getFileID($filename, $file->getHash(), $variant);
}
}
return '';
}
/**
* Generate an {@see HTTPResponse} for the given file from the source filesystem
* @param Filesystem $flysystem
* @param string $fileID
* @return HTTPResponse
*/
protected function createResponseFor(Filesystem $flysystem, $fileID)
{
// Block directory access
if ($flysystem->get($fileID) instanceof Directory) {
return $this->createDeniedResponse();
}
// Create streamable response
$stream = $flysystem->readStream($fileID);
$size = $flysystem->getSize($fileID);
$mime = $flysystem->getMimetype($fileID);
$response = HTTPStreamResponse::create($stream, $size)
->addHeader('Content-Type', $mime);
// Add standard headers
$headers = $this->config()->get('file_response_headers');
foreach ($headers as $header => $value) {
$response->addHeader($header, $value);
}
return $response;
}
/**
* Redirect browser to specified file ID on the public store. Assumes an existence check for the fileID has
* already occured.
* @note This was introduced as a patch and will be rewritten/remove in SS4.4.
* @param $fileID
* @return HTTPResponse
*/
private function createRedirectResponse($fileID)
{
$response = new HTTPResponse(null, $this->config()->get('redirect_response_code'));
/** @var PublicAdapter $adapter */
$adapter = $this->getPublicFilesystem()->getAdapter();
$response->addHeader('Location', $adapter->getPublicUrl($fileID));
return $response;
}
/**
* Generate a response for requests to a denied protected file
*
* @return HTTPResponse
*/
protected function createDeniedResponse()
{
$code = (int)$this->config()->get('denied_response_code');
return $this->createErrorResponse($code);
}
/**
* Generate a response for missing file requests
*
* @return HTTPResponse
*/
protected function createMissingResponse()
{
$code = (int)$this->config()->get('missing_response_code');
return $this->createErrorResponse($code);
}
/**
* Create a response with the given error code
*
* @param int $code
* @return HTTPResponse
*/
protected function createErrorResponse($code)
{
$response = new HTTPResponse('', $code);
// Show message in dev
if (!Director::isLive()) {
$response->setBody($response->getStatusDescription());
}
return $response;
}
}
|
9f4ebb6a8680b828ef154db86249fda799eaa395
|
{
"blob_id": "9f4ebb6a8680b828ef154db86249fda799eaa395",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-28T07:34:46",
"content_id": "f3ae5cc92e1fc1afab4987d0da5be8a5479e3143",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "47e628ed961ccec12d42432b8831fcf26f323473",
"extension": "php",
"filename": "FlysystemAssetStore.php",
"fork_events_count": 0,
"gha_created_at": "2019-05-28T07:31:23",
"gha_event_created_at": "2019-05-28T07:31:24",
"gha_language": null,
"gha_license_id": null,
"github_id": 188977521,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 37043,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/vendor/silverstripe/assets/src/Flysystem/FlysystemAssetStore.php",
"provenance": "stack-edu-0052.json.gz:655047",
"repo_name": "bgoldhawk/silverstripe-memberprofiles",
"revision_date": "2019-05-28T07:34:46",
"revision_id": "89b5039c547a511c86192a1276df4c575d4b6505",
"snapshot_id": "f631dc6ccd38b542c8a7a3007b988c66555f479e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/bgoldhawk/silverstripe-memberprofiles/89b5039c547a511c86192a1276df4c575d4b6505/vendor/silverstripe/assets/src/Flysystem/FlysystemAssetStore.php",
"visit_date": "2020-05-28T11:01:44.070381",
"added": "2024-11-18T21:57:01.377411+00:00",
"created": "2019-05-28T07:34:46",
"int_score": 2,
"score": 2.390625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz"
}
|
## Description
> Pidgey has an extremely sharp sense of direction. It is capable of unerringly returning home to its nest, however far it may be removed from its familiar surroundings.
pidgey is a small map bot I wrote for our local Pokemon Go discord, to
help the users locate pokestops and gyms.
It will take a JSON file with pois (gyms, pokestops, portals) and make
this searchable through discord. It will *not* help you assemble this
file, it assumes you already have a list of pois which you want to
make searchable.
## Install and configuration
Checkout the git.
Run npm install to install the dependencies.
Create a config.json, using config.json-dist as a template.
| Parameter | Description |
| --- | --- |
| token | Discord bot token. See https://github.com/reactiflux/discord-irc/wiki/Creating-a-discord-bot-&-getting-a-token |
| command | Map command |
| google_api_key | Google static map api key https://developers.google.com/maps/documentation/maps-static/intro |
| poifile | JSON file with pois. See data/poi.json-sample for format. |
## Screenshots


(Icon made by Roundicons Freebies from www.flaticon.com)
|
73fd7f625cfd64e19fc83bc1ba64a1f5f5ce3847
|
{
"blob_id": "73fd7f625cfd64e19fc83bc1ba64a1f5f5ce3847",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-31T08:32:06",
"content_id": "0a35af4ce5b3c383667a246ed5baa5c6258e170c",
"detected_licenses": [
"MIT"
],
"directory_id": "4c86f99053c79cf647c854db4d10fbdc5fa9ebc2",
"extension": "md",
"filename": "README.md",
"fork_events_count": 8,
"gha_created_at": "2018-06-18T20:32:37",
"gha_event_created_at": "2019-10-31T09:05:58",
"gha_language": "JavaScript",
"gha_license_id": "MIT",
"github_id": 137803398,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1260,
"license": "MIT",
"license_type": "permissive",
"path": "/README.md",
"provenance": "stack-edu-markdown-0006.json.gz:329034",
"repo_name": "bragef/pidgey",
"revision_date": "2019-10-31T08:32:06",
"revision_id": "c0fd7202d8ca79c07c32de4f771fecaa41fc5259",
"snapshot_id": "614bfac5ff8525b074d2f0e054c64d5d0b9383e7",
"src_encoding": "UTF-8",
"star_events_count": 9,
"url": "https://raw.githubusercontent.com/bragef/pidgey/c0fd7202d8ca79c07c32de4f771fecaa41fc5259/README.md",
"visit_date": "2020-03-20T22:32:45.917397",
"added": "2024-11-18T23:33:10.513343+00:00",
"created": "2019-10-31T08:32:06",
"int_score": 3,
"score": 3.09375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0006.json.gz"
}
|
# Lint as: python3
# Copyright 2019, The TensorFlow Federated 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.
"""Libraries of Keras metrics."""
from typing import Any, Dict, List, Optional, TypeVar, Union
import tensorflow as tf
class NumBatchesCounter(tf.keras.metrics.Sum):
"""A `tf.keras.metrics.Metric` that counts the number of batches seen."""
def __init__(self, name: str = 'num_batches', dtype=tf.int64): # pylint: disable=useless-super-delegation
super().__init__(name, dtype)
def update_state(self,
y_true: tf.Tensor,
y_pred: tf.Tensor,
sample_weight: Optional[tf.Tensor] = None) -> tf.Tensor:
return super().update_state(1)
class NumExamplesCounter(tf.keras.metrics.Sum):
"""A `tf.keras.metrics.Metric` that counts the number of examples seen."""
def __init__(self, name: str = 'num_examples', dtype=tf.int64): # pylint: disable=useless-super-delegation
super().__init__(name, dtype)
def update_state(self,
y_true: tf.Tensor,
y_pred: tf.Tensor,
sample_weight: Optional[tf.Tensor] = None) -> tf.Tensor:
return super().update_state(tf.shape(y_pred)[0])
def _mask_ground_truth(
y_true: tf.Tensor, sample_weight: tf.Tensor,
token_to_mask: Optional[Union[tf.Tensor, str, float, int]]) -> tf.Tensor:
"""Generated sample weight to mask ground truth."""
def _convert_masked_tokens_to_negative(y_true, token_to_mask) -> tf.Tensor:
"""Converts tokens to maks to negative values."""
if token_to_mask is None:
neq = tf.equal(y_true, y_true)
else:
neq = tf.not_equal(y_true, token_to_mask)
mask = tf.cast(neq, y_true.dtype) * 2 - 1
return mask
if sample_weight is not None:
sample_weight = tf.cast(
tf.math.greater(
_convert_masked_tokens_to_negative(y_true, token_to_mask), 0),
tf.float32) * tf.cast(tf.reshape(sample_weight, [-1, 1]), tf.float32)
else:
sample_weight = tf.cast(
tf.math.greater(
_convert_masked_tokens_to_negative(y_true, token_to_mask), 0),
tf.float32)
return sample_weight
class FlattenedNumExamplesCounter(tf.keras.metrics.Sum):
"""A `tf.keras.metrics.Metric` that counts the number of examples seen."""
def __init__(self,
name: str = 'num_flattened_examples',
dtype=tf.int64,
mask_zero=False):
super().__init__(name, dtype)
self._token_to_mask = None
if mask_zero:
self._token_to_mask = 0
def update_state(self,
y_true: tf.Tensor,
y_pred: tf.Tensor,
sample_weight: Optional[tf.Tensor] = None) -> tf.Tensor:
y_true = tf.reshape(y_true, [-1, 1])
if sample_weight is not None:
sample_weight = tf.reshape(sample_weight, [-1, 1])
sample_weight = _mask_ground_truth(y_true, sample_weight,
self._token_to_mask)
return super().update_state(tf.reduce_sum(sample_weight))
maskable = TypeVar('maskable', tf.Tensor, str, float, int)
class FlattenedCategoricalAccuracy(tf.keras.metrics.SparseCategoricalAccuracy):
"""An accuracy metric that flattens out sequences and masks a given token."""
def __init__(self,
vocab_size: int,
name: str = 'accuracy',
dtype=None,
masked_tokens: Union[List[maskable], maskable] = None,
mask_zero: bool = False):
self._vocab_size = vocab_size
self._tokens_to_mask = [masked_tokens] if (
not isinstance(masked_tokens, List)) else masked_tokens # type: List
if mask_zero:
self._tokens_to_mask.append(0)
super().__init__(name, dtype=dtype)
def update_state(self,
y_true: tf.Tensor,
y_pred: tf.Tensor,
sample_weight: Optional[tf.Tensor] = None) -> tf.Tensor:
"""Flattens and masks `y_true`, `y_pred` and `sample_weight`.
Args:
y_true: Tensor representing ground truth of sequence model. Must contain
only nonnegative indices.
y_pred: Tensor representing per-element predictions over the sequence
model's vocabulary; should have total number of elements equal to the
total number of elements in `y_true` multiplied by `self._vocab_size`.
sample_weight: (Optional) Tensor representing the per-element weights for
computing accuracy over the sequence `y_true`. Must be broadcastable to
the flattened shape of `y_true`.
Returns:
Update Op.
"""
y_true = tf.reshape(y_true, [-1, 1])
y_pred = tf.reshape(y_pred, [-1, self._vocab_size, 1])
if sample_weight is not None:
sample_weight = tf.reshape(sample_weight, [-1, 1])
for token in self._tokens_to_mask:
sample_weight = _mask_ground_truth(y_true, sample_weight, token)
return super().update_state(y_true, y_pred, sample_weight)
def get_config(self) -> Dict[str, Any]:
config = super().get_config()
config['masked_tokens'] = tuple(self._tokens_to_mask)
config['vocab_size'] = self._vocab_size
return config
|
3edb47cb4a520b0a55d60476c07662aeb59a3450
|
{
"blob_id": "3edb47cb4a520b0a55d60476c07662aeb59a3450",
"branch_name": "refs/heads/master",
"committer_date": "2020-02-26T18:32:21",
"content_id": "1c83abde8bc16d15d40b115037402d32f3bc69cb",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a5e6123dd06d7e8d707c2b3057177fa946cb0c4a",
"extension": "py",
"filename": "keras_metrics.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5666,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/tensorflow_federated/python/research/optimization/shared/keras_metrics.py",
"provenance": "stack-edu-0065.json.gz:275192",
"repo_name": "paperflight/federated",
"revision_date": "2020-02-26T18:23:24",
"revision_id": "0e1f018bd8c6445a07105e262ce74c4017a0173f",
"snapshot_id": "6ed017b7869852004a87dfee614abc6fffc02c72",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/paperflight/federated/0e1f018bd8c6445a07105e262ce74c4017a0173f/tensorflow_federated/python/research/optimization/shared/keras_metrics.py",
"visit_date": "2021-01-26T06:23:18.044546",
"added": "2024-11-19T01:21:43.104054+00:00",
"created": "2020-02-26T18:23:24",
"int_score": 2,
"score": 2.3125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0083.json.gz"
}
|
package gatekeeper
import (
"encoding/json"
"io"
"net/http"
"strconv"
"time"
"github.com/nemosupremo/vault-gatekeeper/scheduler"
"github.com/nemosupremo/vault-gatekeeper/vault/unsealer"
"github.com/franela/goreq"
"github.com/go-chi/chi"
)
func (g *Gatekeeper) OkResponse(w http.ResponseWriter, message string) {
resp := struct {
Unsealed bool `json:"unsealed"`
Message string `json:"message"`
}{Unsealed: g.IsUnsealed()}
resp.Message = message
json.NewEncoder(w).Encode(resp)
}
func (g *Gatekeeper) ErrorResponse(w http.ResponseWriter, code int, err string) {
resp := struct {
Unsealed bool `json:"unsealed"`
Error string `json:"error"`
}{Unsealed: g.IsUnsealed()}
resp.Error = err
w.WriteHeader(code)
json.NewEncoder(w).Encode(resp)
}
func (g *Gatekeeper) Routes() http.Handler {
r := chi.NewRouter()
r.Use(NewLogger(nil))
r.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
next.ServeHTTP(w, r)
})
})
r.Get("/", g.status)
r.Get("/status", g.status)
r.Post("/seal", g.seal)
r.Post("/unseal", g.unseal)
r.Post("/token", g.requestToken)
r.Post("/policies/reload", g.reloadPolicies)
return r
}
func (g *Gatekeeper) status(w http.ResponseWriter, r *http.Request) {
var status struct {
Id string `json:"id"`
Stats interface{} `json:"stats"`
Uptime string `json:"uptime"`
Unsealed bool `json:"unsealed"`
Started time.Time `json:"started"`
Ok bool `json:"ok"`
Version string `json:"version"`
Peers []peer `json:"peers,omitempty"`
}
status.Id = g.PeerId
status.Started = g.Started
status.Uptime = time.Since(status.Started).String()
stats := g.Stats
status.Stats = stats
status.Ok = true
status.Version = g.config.Version
status.Unsealed = g.IsUnsealed()
var peers []peer
for _, peer := range g.Peers() {
peer.Address = peer.address()
peers = append(peers, peer)
}
status.Peers = peers
if status.Unsealed {
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(http.StatusServiceUnavailable)
}
json.NewEncoder(w).Encode(status)
}
func (g *Gatekeeper) seal(w http.ResponseWriter, r *http.Request) {
g.Seal()
g.OkResponse(w, "Gatekeeper sealed.")
}
func (g *Gatekeeper) unseal(w http.ResponseWriter, r *http.Request) {
var body struct {
Method string `json:"method"`
Token string `json:"token"`
PersonalToken string `json:"personal_token"`
RoleId string `json:"role_id"`
SecretId string `json:"secret_id"`
Role string `json:"aws_role"`
Nonce string `json:"aws_nonce"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err == nil {
var uns unsealer.Unsealer
switch body.Method {
case "token":
uns = unsealer.TokenUnsealer{
AuthToken: body.Token,
}
case "token-wrapped":
uns = unsealer.WrappedTokenUnsealer{
TempToken: body.Token,
}
case "approle":
uns = unsealer.AppRoleUnsealer{
RoleId: body.RoleId,
SecretId: body.SecretId,
}
case "aws-ec2", "aws":
uns = unsealer.AwsUnsealer{
Role: body.Role,
Nonce: body.Nonce,
}
case "github":
uns = unsealer.GitHubUnsealer{
PersonalToken: body.PersonalToken,
}
default:
g.ErrorResponse(w, http.StatusUnprocessableEntity, "Cannot unseal with unknown method: '"+body.Method+"'")
return
}
if err := g.Unseal(uns); err == nil {
g.OkResponse(w, "Unseal successful with the '"+uns.Name()+"' method.")
} else {
g.ErrorResponse(w, http.StatusUnauthorized, "Unseal failed with the '"+uns.Name()+"' method.")
}
} else {
g.ErrorResponse(w, http.StatusBadRequest, "JSON body could not be decoded: "+err.Error())
}
}
func (g *Gatekeeper) requestToken(w http.ResponseWriter, r *http.Request) {
log := GetLog(r)
if r.Header.Get("Gatekeeper-Proxy") != "" {
LogEntrySetField(r, "proxied", true)
}
var body struct {
Scheduler string `json:"scheduler"`
TaskId string `json:"task_id"`
Role string `json:"role"`
}
if g.IsUnsealed() {
if err := json.NewDecoder(r.Body).Decode(&body); err == nil {
if token, ttl, err := g.RequestToken(body.Scheduler, body.TaskId, body.Role, r.RemoteAddr); err == nil {
log.Debugf("Reponse Token: %s\n", token)
resp := struct {
Unsealed bool `json:"unsealed"`
Token string `json:"token"`
Ttl string `json:"ttl"`
VaultAddr string `json:"vault_addr"`
}{
Unsealed: g.IsUnsealed(),
Token: token,
Ttl: ttl.String(),
VaultAddr: g.config.Vault.Address,
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(resp)
} else {
log.Debugf("Reponse Token Error: %v\n", err)
switch err {
case scheduler.ErrTaskNotFound, ErrHostMismatch:
g.ErrorResponse(w, http.StatusUnauthorized, err.Error())
case ErrTaskNotFresh, ErrRoleMismatch, ErrNoSuchRole:
g.ErrorResponse(w, http.StatusForbidden, err.Error())
case ErrMaxTokensGiven:
g.ErrorResponse(w, http.StatusTooManyRequests, err.Error())
default:
g.ErrorResponse(w, http.StatusInternalServerError, err.Error())
}
}
} else {
g.ErrorResponse(w, http.StatusBadRequest, "JSON body could not be decoded: "+err.Error())
}
} else {
if len(g.Peers()) > 0 && r.Header.Get("Gatekeeper-Proxy") == "" {
for _, peer := range g.Peers() {
if peer.Unsealed {
req, err := goreq.Request{
Uri: peer.TokenUri(),
Method: "POST",
Body: body,
}.WithHeader("Gatekeeper-Proxy", g.PeerId).WithHeader("User-Agent", r.UserAgent()).Do()
if err == nil {
w.WriteHeader(req.StatusCode)
io.Copy(w, req.Body)
return
} else {
log.Warnf("Failed to communicate with peer %v: %v", peer, err)
g.ErrorResponse(w, http.StatusServiceUnavailable, "Unable to provide token: Gatekeeper is sealed.")
return
}
}
}
}
g.ErrorResponse(w, http.StatusServiceUnavailable, "Unable to provide token: Gatekeeper is sealed.")
}
}
func (g *Gatekeeper) reloadPolicies(w http.ResponseWriter, r *http.Request) {
log := GetLog(r)
if g.IsUnsealed() {
log.Infof("Reloading policies...")
if policies, err := g.loadPolicies(); err == nil {
g.Lock()
g.Policies = policies
numPolicies := policies.Len()
g.Unlock()
if r.Header.Get("Gatekeeper-Proxy") == "" {
for _, peer := range g.Peers() {
if peer.Unsealed {
req, err := goreq.Request{
Uri: peer.ReloadUri(),
Method: "POST",
}.WithHeader("Gatekeeper-Proxy", g.PeerId).WithHeader("User-Agent", r.UserAgent()).Do()
if err != nil {
log.Warnf("Failed to communicate with peer %s: %v", peer, err)
} else {
req.Body.Close()
}
}
}
}
log.Infof("Policies reloaded. %d total policies.", numPolicies)
g.OkResponse(w, "Policies reloaded. "+strconv.Itoa(numPolicies)+" total policies.")
} else {
log.Warnf("Failed to reload policies: %v", err)
g.ErrorResponse(w, http.StatusInternalServerError, "There was an error attempting to reload the policies. Please check the gatekeeper logs for more info.")
}
} else {
g.ErrorResponse(w, http.StatusServiceUnavailable, "Failed to reload policies: gatekeeper is sealed.")
}
}
|
582ac357d3c828e90b4d7661b9dc83e5315c6e87
|
{
"blob_id": "582ac357d3c828e90b4d7661b9dc83e5315c6e87",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-16T22:01:36",
"content_id": "eb2e226b35fc63e4635383686ef219f38aba70b1",
"detected_licenses": [
"MIT"
],
"directory_id": "dc47fe7e08ba8f27739cd16ab6499092ac007ef1",
"extension": "go",
"filename": "routes.go",
"fork_events_count": 1,
"gha_created_at": "2018-02-09T13:40:37",
"gha_event_created_at": "2019-01-16T22:01:37",
"gha_language": "Go",
"gha_license_id": "MIT",
"github_id": 120910205,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 7281,
"license": "MIT",
"license_type": "permissive",
"path": "/routes.go",
"provenance": "stack-edu-0017.json.gz:278734",
"repo_name": "hmhco/vault-gatekeeper-mesos",
"revision_date": "2019-01-16T22:01:36",
"revision_id": "b6f329efad9d67f3892765d040775992a0d4aeee",
"snapshot_id": "737fc27604e460d1bd3890e8ece3cd7d1940ca19",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hmhco/vault-gatekeeper-mesos/b6f329efad9d67f3892765d040775992a0d4aeee/routes.go",
"visit_date": "2021-05-02T04:50:22.754731",
"added": "2024-11-18T19:07:22.040345+00:00",
"created": "2019-01-16T22:01:36",
"int_score": 2,
"score": 2.4375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0035.json.gz"
}
|
using System;
using System.Threading.Tasks;
using BurnForMoney.Domain;
using BurnForMoney.Functions.CommandHandlers;
using BurnForMoney.Functions.Commands;
using BurnForMoney.Functions.Domain;
using BurnForMoney.Infrastructure.Messages;
using BurnForMoney.Infrastructure.Persistence;
namespace BurnForMoney.Functions.UnitTests.Domain
{
public abstract class AthleteBaseTests
{
protected readonly IRepository<Athlete> _athleteRepo = new Repository<Athlete>(new MemoryEventStore());
protected async Task<Athlete> GetAthleteAsync(Guid id) => await _athleteRepo.GetByIdAsync(id);
protected async Task<Guid> CreateNewAthleteAsync(string firstName = "test_first_name", string lastName = "test_last_name",
string profilePictureUrl = "http://test.com/img.png", Source source = Source.Strava)
{
var newAthleteId = Guid.NewGuid();
await HandleCommand(new CreateAthleteCommand(newAthleteId, Guid.NewGuid().ToString(),
firstName, lastName, profilePictureUrl, source));
return newAthleteId;
}
protected async Task HandleCommand<T>(T command) where T : Command
{
switch(command)
{
case CreateAthleteCommand cmd:
await new CreateAthleteCommandHandler(_athleteRepo).HandleAsync(cmd);
break;
case ActivateAthleteCommand cmd:
await new ActivateAthleteCommandHandler(_athleteRepo).HandleAsync(cmd);
break;
case DeactivateAthleteCommand cmd:
await new DeactivateAthleteCommandHandler(_athleteRepo).HandleAsync(cmd);
break;
case AddActivityCommand cmd:
await new AddActivityCommandHandler(_athleteRepo).HandleAsync(cmd);
break;
case UpdateActivityCommand cmd:
await new UpdateActivityCommandHandler(_athleteRepo).HandleAsync(cmd);
break;
case DeleteActivityCommand cmd:
await new DeleteActivityCommandHandler(_athleteRepo).HandleAsync(cmd);
break;
default:
throw new NotImplementedException();
}
}
}
}
|
fcbb56cad3f8824b170f6403b716c7519575542f
|
{
"blob_id": "fcbb56cad3f8824b170f6403b716c7519575542f",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-01T11:09:50",
"content_id": "a576f17e610e73d736463c47bd43cd9042fe101e",
"detected_licenses": [
"MIT"
],
"directory_id": "3b949ccea9fa3e73364bb8454a9ce5e977a7bfb3",
"extension": "cs",
"filename": "AthleteBaseTests.cs",
"fork_events_count": 0,
"gha_created_at": "2020-08-11T11:27:49",
"gha_event_created_at": "2020-08-11T11:27:50",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 286726300,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 2347,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/BurnForMoney.Functions.UnitTests/Domain/AthleteBaseTests.cs",
"provenance": "stack-edu-0015.json.gz:382781",
"repo_name": "woitheq/BurnForMoney",
"revision_date": "2021-09-01T11:09:50",
"revision_id": "6a794e65b205da50f79c4de5aec149930cd636ac",
"snapshot_id": "4f9169c153241d054c2d275fec37657e8d56cde8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/woitheq/BurnForMoney/6a794e65b205da50f79c4de5aec149930cd636ac/tests/BurnForMoney.Functions.UnitTests/Domain/AthleteBaseTests.cs",
"visit_date": "2023-07-25T16:17:00.039949",
"added": "2024-11-19T00:57:52.492679+00:00",
"created": "2021-09-01T11:09:50",
"int_score": 2,
"score": 2.46875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0033.json.gz"
}
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// IMPORTANT: Before updating this file
// please read react-native-windows repo:
// vnext/Microsoft.ReactNative.Cxx/README.md
#pragma once
#ifndef MICROSOFT_REACTNATIVE_REACTDISPATCHER
#define MICROSOFT_REACTNATIVE_REACTDISPATCHER
#include <winrt/Microsoft.ReactNative.h>
#include "ReactHandleHelper.h"
namespace winrt::Microsoft::ReactNative {
// Represents a dispatcher queue to invoke work item asynchronously.
// It wraps up the IReactDispatcher and adds convenience methods for
// working with C++ types.
struct ReactDispatcher {
ReactDispatcher(std::nullptr_t = nullptr) noexcept {}
explicit ReactDispatcher(IReactDispatcher const &handle) noexcept : m_handle{handle} {}
IReactDispatcher const &Handle() const noexcept {
return m_handle;
}
explicit operator bool() const noexcept {
return m_handle ? true : false;
}
void Post(ReactDispatcherCallback const &callback) const noexcept {
if (m_handle) {
m_handle.Post(callback);
}
}
bool HasThreadAccess() const noexcept {
return m_handle ? m_handle.HasThreadAccess() : false;
}
static ReactDispatcher CreateSerialDispatcher() noexcept {
return ReactDispatcher{ReactDispatcherHelper::CreateSerialDispatcher()};
}
private:
IReactDispatcher m_handle;
};
} // namespace winrt::Microsoft::ReactNative
#endif // MICROSOFT_REACTNATIVE_REACTDISPATCHER
|
81c11adb27f70accf4c2b82de74a833f096a43b4
|
{
"blob_id": "81c11adb27f70accf4c2b82de74a833f096a43b4",
"branch_name": "refs/heads/master",
"committer_date": "2022-08-11T03:18:22",
"content_id": "9b252913e2cad3de6e15cc26abbf50ddfc6a3152",
"detected_licenses": [
"MIT"
],
"directory_id": "8afb5afd38548c631f6f9536846039ef6cb297b9",
"extension": "h",
"filename": "ReactDispatcher.h",
"fork_events_count": 12,
"gha_created_at": "2021-07-03T13:58:52",
"gha_event_created_at": "2022-10-10T14:13:54",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 382628698,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1443,
"license": "MIT",
"license_type": "permissive",
"path": "/_REPO/MICROSOFT/react-native-windows/vnext/Microsoft.ReactNative.Cxx/ReactDispatcher.h",
"provenance": "stack-edu-0004.json.gz:390819",
"repo_name": "bgoonz/UsefulResourceRepo2.0",
"revision_date": "2022-08-11T03:18:22",
"revision_id": "2cb4b45dd14a230aa0e800042e893f8dfb23beda",
"snapshot_id": "d87588ffd668bb498f7787b896cc7b20d83ce0ad",
"src_encoding": "UTF-8",
"star_events_count": 10,
"url": "https://raw.githubusercontent.com/bgoonz/UsefulResourceRepo2.0/2cb4b45dd14a230aa0e800042e893f8dfb23beda/_REPO/MICROSOFT/react-native-windows/vnext/Microsoft.ReactNative.Cxx/ReactDispatcher.h",
"visit_date": "2023-03-17T01:22:05.254751",
"added": "2024-11-19T01:21:28.748505+00:00",
"created": "2022-08-11T03:18:22",
"int_score": 2,
"score": 2.421875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0022.json.gz"
}
|
# -*- coding: utf-8 -*-
"""
BLRevive Gear | Classes that make saving and moving gear sets easier.
Version 1.0
Requires: N/A
@author: Kinetos#6935
"""
import numpy as np
from helpers_pyinstaller import resource_path
class BLReviveGear:
def __init__(self, config_name, friendly_name, image_icon_path=None, small_icon_path=None, gear_types=[]):
self.config_name = config_name
self.friendly_name = friendly_name
self.image_icon_path = image_icon_path
self.small_icon_path = small_icon_path
self.gear_types = gear_types
# --------------------------------------------------------------------------- #
# --------------------------------------------------------------------------- #
def GetName(self):
return self.config_name
def SetName(self, config_name):
self.config_name = config_name
# --------------------------------------------------------------------------- #
def GetFriendlyName(self):
return self.friendly_name
def SetFriendlyName(self, friendly_name):
self.friendly_name = friendly_name
# --------------------------------------------------------------------------- #
def GetImageIconPath(self):
return self.image_icon_path
def SetImageIconPath(self, path):
self.image_icon_path = path
# --------------------------------------------------------------------------- #
def GetSmallIconPath(self):
return self.small_icon_path
def SetSmallIconPath(self, path):
self.small_icon_path = path
# --------------------------------------------------------------------------- #
def GetGearTypes(self):
return self.gear_types
def SetGearTypes(self, types):
self.gear_types = types
# --------------------------------------------------------------------------- #
# --------------------------------------------------------------------------- #
def IsType(self, type):
return type in self.gear_types
# --------------------------------------------------------------------------- #
def EmptyGear():
return BLReviveGear(None, '')
# --------------------------------------------------------------------------- #
def to_dict(self):
return {
'config_name': self.config_name,
'friendly_name': self.friendly_name,
'image_path': self.image_icon_path,
'icon_path': self.small_icon_path,
'gear_types': self.gear_types
}
# --------------------------------------------------------------------------- #
# --------------------------------------------------------------------------- #
class BLReviveReceiver(BLReviveGear):
def __init__(self, config_name, friendly_name, image_icon_path=None, small_icon_path=None, gear_types=[]):
super().__init__(config_name, friendly_name, image_icon_path, small_icon_path, gear_types)
def EmptyGear():
return BLReviveReceiver(None, '')
# --------------------------------------------------------------------------- #
# --------------------------------------------------------------------------- #
class BLReviveStock(BLReviveGear):
def __init__(self, config_name, friendly_name, image_icon_path=None, small_icon_path=None, gear_types=[]):
super().__init__(config_name, friendly_name, image_icon_path, small_icon_path, gear_types)
def EmptyGear():
return BLReviveStock(None, '')
# --------------------------------------------------------------------------- #
# --------------------------------------------------------------------------- #
class BLReviveBarrel(BLReviveGear):
def __init__(self, config_name, friendly_name, image_icon_path=None, small_icon_path=None, gear_types=[]):
super().__init__(config_name, friendly_name, image_icon_path, small_icon_path, gear_types)
def EmptyGear():
return BLReviveBarrel(None, '')
# --------------------------------------------------------------------------- #
# --------------------------------------------------------------------------- #
class BLReviveScope(BLReviveGear):
def __init__(self, config_name, friendly_name, image_icon_path=None, small_icon_path=None, gear_types=[]):
super().__init__(config_name, friendly_name, image_icon_path, small_icon_path, gear_types)
def EmptyGear():
return BLReviveScope(None, '')
# --------------------------------------------------------------------------- #
# --------------------------------------------------------------------------- #
class BLReviveMuzzle(BLReviveGear):
def __init__(self, config_name, friendly_name, image_icon_path=None, small_icon_path=None, gear_types=[]):
super().__init__(config_name, friendly_name, image_icon_path, small_icon_path, gear_types)
def EmptyGear():
return BLReviveMuzzle(0, '')
# --------------------------------------------------------------------------- #
# --------------------------------------------------------------------------- #
class BLReviveMagazine(BLReviveGear):
def __init__(self, config_name, friendly_name, image_icon_path=None, small_icon_path=None, gear_types=[]):
super().__init__(config_name, friendly_name, image_icon_path, small_icon_path, gear_types)
def EmptyGear():
return BLReviveMagazine(-1, '')
# --------------------------------------------------------------------------- #
# --------------------------------------------------------------------------- #
class BLReviveGrip(BLReviveGear):
def __init__(self, config_name, friendly_name, image_icon_path=None, small_icon_path=None, gear_types=[]):
super().__init__(config_name, friendly_name, image_icon_path, small_icon_path, gear_types)
def EmptyGear():
return BLReviveGrip(None, '')
# --------------------------------------------------------------------------- #
# --------------------------------------------------------------------------- #
class BLReviveTag(BLReviveGear):
def __init__(self, config_name, friendly_name, image_icon_path=None, small_icon_path=None, gear_types=[]):
super().__init__(config_name, friendly_name, image_icon_path, small_icon_path, gear_types)
def EmptyGear():
return BLReviveTag(None, '')
# --------------------------------------------------------------------------- #
# --------------------------------------------------------------------------- #
class BLReviveCamo(BLReviveGear):
def __init__(self, config_name, friendly_name, image_icon_path=None, small_icon_path=None, gear_types=[]):
super().__init__(config_name, friendly_name, image_icon_path, small_icon_path, gear_types)
def EmptyGear():
return BLReviveCamo(None, '')
# --------------------------------------------------------------------------- #
# --------------------------------------------------------------------------- #
class BLReviveWeapon:
def __init__(self, name, receiver, stock, barrel, scope, muzzle, magazine, grip, tag, camo):
self.name = name
self.receiver = receiver
self.stock = stock
self.barrel = barrel
self.scope = scope
self.muzzle = muzzle
self.magazine = magazine
self.grip = grip
self.tag = tag
self.camo = camo
# --------------------------------------------------------------------------- #
def EmptyWeapon():
return BLReviveWeapon(None,
BLReviveReceiver.EmptyGear(),
BLReviveStock.EmptyGear(),
BLReviveBarrel.EmptyGear(),
BLReviveScope.EmptyGear(),
BLReviveMuzzle.EmptyGear(),
BLReviveMagazine.EmptyGear(),
BLReviveGrip.EmptyGear(),
BLReviveTag.EmptyGear(),
BLReviveCamo.EmptyGear())
# --------------------------------------------------------------------------- #
def ToMagiCow(self):
columns = np.genfromtxt(resource_path('data/muzzles.csv'), delimiter=',', dtype=str)
muzzles = list(columns.T[1])
columns = np.genfromtxt(resource_path('data/magazines.csv'), delimiter=',', dtype=str)
magazines = list(columns.T[1])
weapon = {}
weapon['Receiver'] = self.receiver.friendly_name
if self.muzzle.friendly_name in muzzles:
weapon['Muzzle'] = muzzles.index(self.muzzle.friendly_name)
else:
weapon['Muzzle'] = 0
weapon['Stock'] = self.stock.friendly_name
weapon['Barrel'] = self.barrel.friendly_name
if self.magazine.friendly_name in magazines:
weapon['Magazine'] = magazines.index(self.magazine.friendly_name)
else:
# TODO: Add default magazine pairs to auto set this
weapon['Magazine'] = -1
weapon['Scope'] = self.scope.friendly_name
weapon['Grip'] = self.grip.friendly_name
return weapon
def LoadWeapon(weapon_dict):
if 'name' not in weapon_dict:
return BLReviveWeapon.EmptyWeapon()
re = BLReviveReceiver(*weapon_dict['receiver'].values())
st = BLReviveStock(*weapon_dict['stock'].values())
ba = BLReviveBarrel(*weapon_dict['barrel'].values())
sc = BLReviveScope(*weapon_dict['scope'].values())
if 'muzzle' in weapon_dict:
mz = BLReviveMuzzle(*weapon_dict['muzzle'].values())
mg = BLReviveMagazine(*weapon_dict['magazine'].values())
gp = BLReviveGrip(*weapon_dict['grip'].values())
tg = BLReviveTag(*weapon_dict['tag'].values())
cm = BLReviveCamo(*weapon_dict['camo'].values())
else:
mz = BLReviveMuzzle.EmptyGear()
mg = BLReviveMagazine.EmptyGear()
gp = BLReviveGrip.EmptyGear()
tg = BLReviveTag.EmptyGear()
cm = BLReviveCamo.EmptyGear()
return BLReviveWeapon(
weapon_dict['name'],
re,
st,
ba,
sc,
mz,
mg,
gp,
tg,
cm
)
def to_dict(self):
return {
'name': self.name,
'receiver': self.receiver.to_dict(),
'stock': self.stock.to_dict(),
'barrel': self.barrel.to_dict(),
'scope': self.scope.to_dict(),
'muzzle': self.muzzle.to_dict(),
'magazine': self.magazine.to_dict(),
'grip': self.grip.to_dict(),
'tag': self.tag.to_dict(),
'camo': self.camo.to_dict()
}
# --------------------------------------------------------------------------- #
# --------------------------------------------------------------------------- #
class BLReviveLoadout:
def __init__(self, name, primary, secondary, tactical, gear1, gear2, gear3, gear4):
self.name = name
self.primary = primary
self.secondary = secondary
self.tactical = tactical
self.gear1 = gear1
self.gear2 = gear2
self.gear3 = gear3
self.gear4 = gear4
# --------------------------------------------------------------------------- #
def ToMagiCow(self):
loadout = {}
if self.primary is not None:
loadout['Primary'] = self.primary.ToMagiCow()
else:
loadout['Primary'] = BLReviveWeapon.EmptyWeapon().ToMagiCow()
if self.secondary is not None:
loadout['Secondary'] = self.secondary.ToMagiCow()
else:
loadout['Secondary'] = BLReviveWeapon.EmptyWeapon().ToMagiCow()
return loadout
# --------------------------------------------------------------------------- #
# --------------------------------------------------------------------------- #
|
12c5819c8ff5b6dfe7f1c28dd37be08917497dec
|
{
"blob_id": "12c5819c8ff5b6dfe7f1c28dd37be08917497dec",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-19T00:15:41",
"content_id": "6d0c74a77a65f59851bd8c4c964b9665ed9ac26d",
"detected_licenses": [
"MIT"
],
"directory_id": "7d8b3bd21b5d9cee2cd5ff8068c2ecb671548052",
"extension": "py",
"filename": "blrevive_gear.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 415771112,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11870,
"license": "MIT",
"license_type": "permissive",
"path": "/blrevive_gear.py",
"provenance": "stack-edu-0065.json.gz:384936",
"repo_name": "daakru/BLReLM",
"revision_date": "2021-10-19T00:15:41",
"revision_id": "ad1001c101821356abff711c1ed4d3178a77baa7",
"snapshot_id": "49e61cd7633d64f6e670f189b9a68616b69a596c",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/daakru/BLReLM/ad1001c101821356abff711c1ed4d3178a77baa7/blrevive_gear.py",
"visit_date": "2023-08-18T07:14:55.312721",
"added": "2024-11-19T01:11:30.439680+00:00",
"created": "2021-10-19T00:15:41",
"int_score": 2,
"score": 2.359375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0083.json.gz"
}
|
/**
* Copyright 2015-present OpenCB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {LitElement, html} from "lit";
import LitUtils from "../utils/lit-utils.js";
import UtilsNew from "../../../core/utils-new.js";
import "../forms/select-field-filter.js";
export default class AcmgFilter extends LitElement {
constructor() {
super();
// Set status and init private properties
this._init();
}
createRenderRoot() {
return this;
}
static get properties() {
return {
acmg: {
type: Array,
},
multiple: {
type: Boolean,
},
};
}
_init() {
this.config = this.getDefaultConfig();
}
filterChange(e) {
const value = (e.detail.value || "").split(",").filter(v => !!v);
LitUtils.dispatchCustomEvent(this, "filterChange", value);
}
render() {
return html`
<select-field-filter
.data="${this.config.data}"
.value=${this.acmg || []}
?multiple="${this.multiple ?? this.config.multiple}"
?liveSearch=${this.config.liveSearch}
@filterChange="${this.filterChange}">
</select-field-filter>
`;
}
getDefaultConfig() {
return {
multiple: true,
liveSearch: false,
data: [
{
id: "PVS - Very strong evidence of pathogenicity",
name: "Very strong evidence of pathogenicity",
fields: [
{
id: "PVS1",
description: "Null variant (nonsense, frameshift, canonical +/−1 or 2 splice sites, initiation codon, " +
"or multi-exon deletion) in a gene where loss of function (LOF) is a known mechanism of disease"
}
]
},
{
id: "PS - Strong evidence of pathogenicity",
name: "Strong evidence of pathogenicity",
fields: [
{
id: "PS1",
description: "Same amino acid change as a previously established pathogenic variant regardless of nucleotide change"
},
{
id: "PS2",
description: "De novo (both maternity and paternity confirmed) in a patient with the disease and no family history"
},
{
id: "PS3",
description: "Well-established in vitro or in vivo functional studies supportive of a damaging effect on the gene or gene product"
},
{
id: "PS4",
description: "The prevalence of the variant in affected individuals is significantly increased compared with the prevalence in controls"
}
]
},
{
id: "PM - Moderate evidence of pathogenecity",
name: "Moderate evidence of pathogenecity",
fields: [
{
id: "PM1",
description: "Located in a mutational hot spot and/or critical and well-established functional domain (e.g., active site of an enzyme) without benign variation"
},
{
id: "PM2",
description: "Absent from controls (or at extremely low frequency if recessive) in Exome Sequencing Project, 1000 Genomes Project, or Exome Aggregation Consortium"
},
{
id: "PM3",
description: "For recessive disorders, detected in trans with a pathogenic variant Note: This requires testing of parents (or offspring) to determine phase."
},
{
id: "PM4",
description: "Protein length changes as a result of in-frame deletions/insertions in a nonrepeat region or stop-loss variants"
},
{
id: "PM5",
description: "Novel missense change at an amino acid residue where a different missense change determined to be pathogenic has been seen before"
},
{
id: "PM6",
description: "Assumed de novo, but without confirmation of paternity and maternity"
}
]
},
{
id: "PP - Supporting evidence of pathogenicity",
name: "Supporting evidence of pathogenicity",
fields: [
{
id: "PP1",
description: "Cosegregation with disease in multiple affected family members in a gene definitively known to cause the disease"
},
{
id: "PP2",
description: "Missense variant in a gene that has a low rate of benign missense variation and in which missense variants are a common mechanism of disease"
},
{
id: "PP3",
description: "Multiple lines of computational evidence support a deleterious effect on the gene or gene product (conservation, evolutionary, splicing impact, etc.)"
},
{
id: "PP4",
description: "Patient’s phenotype or family history is highly specific for a disease with a single genetic etiology"
},
{
id: "PP5",
description: "Reputable source recently reports variant as pathogenic, but the evidence is not available to the laboratory to perform an independent evaluation"
}
]
},
{
id: "BA - Stand-alone evidence for benign variants",
name: "Stand-alone evidence for benign variants",
fields: [
{
id: "BA1",
description: "Allele frequency is >5% in Exome Sequencing Project, 1000 Genomes Project, or Exome Aggregation Consortium"
}
]
},
{
id: "BS - Strong evidence for benign variants",
name: "Strong evidence for benign variants",
fields: [
{
id: "BS1",
description: "Allele frequency is greater than expected for disorder"
},
{
id: "BS2",
description: "Observed in a healthy adult individual for a recessive (homozygous), dominant (heterozygous), or X-linked (hemizygous) disorder, with full penetrance expected at an early age"
},
{
id: "BS3",
description: "Well-established in vitro or in vivo functional studies show no damaging effect on protein function or splicing"
},
{
id: "BS4",
description: "Lack of segregation in affected members of a family"
}
]
},
{
id: "BP - Supporting evidence for benign variants",
name: "Supporting evidence for benign variants",
fields: [
{
id: "BP1",
description: "Missense variant in a gene for which primarily truncating variants are known to cause disease"
},
{
id: "BP2",
description: "Observed in trans with a pathogenic variant for a fully penetrant dominant gene/disorder or observed in cis with a pathogenic variant in any inheritance pattern"
},
{
id: "BP3",
description: "In-frame deletions/insertions in a repetitive region without a known function"
},
{
id: "BP4",
description: "Multiple lines of computational evidence suggest no impact on gene or gene product (conservation, evolutionary, splicing impact, etc.)"
},
{
id: "BP5",
description: "Variant found in a case with an alternate molecular basis for disease"
},
{
id: "BP6",
description: "Reputable source recently reports variant as benign, but the evidence is not available to the laboratory to perform an independent evaluation"
},
{
id: "BP7",
description: "A synonymous (silent) variant for which splicing prediction algorithms predict no impact " +
"to the splice consensus sequence nor the creation of a new splice site AND the nucleotide is not highly conserved"
}
]
}
],
};
}
}
customElements.define("acmg-filter", AcmgFilter);
|
a628b91d2ba756384570ac6aeaf9eaf409070000
|
{
"blob_id": "a628b91d2ba756384570ac6aeaf9eaf409070000",
"branch_name": "refs/heads/develop",
"committer_date": "2023-08-29T12:58:54",
"content_id": "601619002c95b5cabc7e3c0cdc815b0d28612d2b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a666b4e1d6acf487a4527719eca33180442520e5",
"extension": "js",
"filename": "acmg-filter.js",
"fork_events_count": 24,
"gha_created_at": "2013-09-24T10:20:12",
"gha_event_created_at": "2023-09-11T13:59:01",
"gha_language": "JavaScript",
"gha_license_id": "Apache-2.0",
"github_id": 13061134,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 10862,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/webcomponents/commons/filters/acmg-filter.js",
"provenance": "stack-edu-0043.json.gz:693498",
"repo_name": "opencb/jsorolla",
"revision_date": "2023-08-29T12:58:54",
"revision_id": "c8cf99023263c06614569fd241de7717b3dcd96d",
"snapshot_id": "4302cdb39c88b0bf888c7e1319b113ecbaf8c68d",
"src_encoding": "UTF-8",
"star_events_count": 44,
"url": "https://raw.githubusercontent.com/opencb/jsorolla/c8cf99023263c06614569fd241de7717b3dcd96d/src/webcomponents/commons/filters/acmg-filter.js",
"visit_date": "2023-08-31T03:56:33.817021",
"added": "2024-11-19T02:06:00.658576+00:00",
"created": "2023-08-29T12:58:54",
"int_score": 2,
"score": 2.046875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0061.json.gz"
}
|
/**
* @file 4.cpp
* @author Jiwon Park ([email protected])
* @brief Assignment 1
* @date 2021-10-03
*
* @copyright Copyright (c) 2021
*
*/
/**
* How many swap operations are performed by function `transpose` (Program 2.19)?
*/
// Program 2.19
template<class T>
void transpose(T **a, int rows)
{// In-place transpose of matrix a[0:rows-1][0:rows-1]
for (int i=0; i<rows; i++) // operation count: ${rows}
for (int j=i+1; j<rows; j++) // operation count: rows(rows+1)/2
swap(a[i][j], a[j][i]); // operation count: rows(rows-1)/2 (element in down-right diagonal will not swapped)
}
|
088a39ae6b84babea2aa145ed83601c01b25aa56
|
{
"blob_id": "088a39ae6b84babea2aa145ed83601c01b25aa56",
"branch_name": "refs/heads/main",
"committer_date": "2021-10-21T04:26:36",
"content_id": "e10c47592d95ca4278b803c8bf4996a1a78b9416",
"detected_licenses": [
"MIT"
],
"directory_id": "91853193f94942917d7e87046e2bdcfed257d69f",
"extension": "cpp",
"filename": "4.cpp",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 401927815,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 612,
"license": "MIT",
"license_type": "permissive",
"path": "/assignments/01/4.cpp",
"provenance": "stack-edu-0003.json.gz:310223",
"repo_name": "jiwonMe/APA254",
"revision_date": "2021-10-21T04:26:36",
"revision_id": "afb13551d73f67314a80af8fb1864daaa0b41e4d",
"snapshot_id": "faf91bacfe7604f33a065115ea1ea26c90d75101",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jiwonMe/APA254/afb13551d73f67314a80af8fb1864daaa0b41e4d/assignments/01/4.cpp",
"visit_date": "2023-08-16T07:37:34.474715",
"added": "2024-11-18T21:48:16.519792+00:00",
"created": "2021-10-21T04:26:36",
"int_score": 3,
"score": 3.21875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0021.json.gz"
}
|
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
$form = ActiveForm::begin(['id' => 'create-data-form', 'action' => '']);
?>
<?php
if($categories->parent==0) {
?>
<?php echo $form->field($categories, 'parent')->hiddenInput(['value'=> 0])->label(false);
?>
<?php
} elseif ($child!='') {
$categories->uid = $child;
?>
<div class="fomr-group">
<?php echo $form->field($categories, 'uid')->dropDownList($Category,
['prompt'=>'-Choose a Category-']) ?>
</div>
<?php
} else {
?>
<div class="fomr-group">
<?php echo $form->field($categories, 'uid')->dropDownList($Category,
['prompt'=>'-Choose a Category-']) ?>
</div>
<?php }?>
<div class="fomr-group">
<label for="url">Name</label>
<?php echo $form->field($categories, 'name')->textInput(['class' => 'form-control', 'id' => '', 'placeholder' => 'Enter Name'])->label(false); ?>
</div>
<div class="fomr-group">
<label for="url">Price</label>
<?php echo $form->field($categories, 'price')->textInput(['class' => 'form-control', 'id' => '', 'placeholder' => 'Enter Price'])->label(false); ?>
</div>
<?php
ActiveForm::end();
?>
|
62522f4e3f26fc05b57a8aa95a59afeafea55551
|
{
"blob_id": "62522f4e3f26fc05b57a8aa95a59afeafea55551",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-02T05:28:01",
"content_id": "2173f942c3bf597c1d0acdf673a5215a96d6a476",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "7d6d90b98a978443a626b8dde7b2a43574de4456",
"extension": "php",
"filename": "update.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 1131,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/backend/modules/categories/views/default/update.php",
"provenance": "stack-edu-0049.json.gz:391527",
"repo_name": "sadiyafarheen/verkopen",
"revision_date": "2017-01-02T05:28:01",
"revision_id": "7488475127d52cf3c17127136d06acbec3239329",
"snapshot_id": "58d1701fda786c2de258f4351f722e627c1552cc",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/sadiyafarheen/verkopen/7488475127d52cf3c17127136d06acbec3239329/backend/modules/categories/views/default/update.php",
"visit_date": "2021-06-09T18:06:20.842877",
"added": "2024-11-18T22:17:40.036494+00:00",
"created": "2017-01-02T05:28:01",
"int_score": 2,
"score": 2.3125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0067.json.gz"
}
|
from typing import Tuple, List
from phdTester import commons
from phdTester.common_types import KS001Str, PathStr, DataTypeStr, GetSuchInfo
from phdTester.model_interfaces import IComplexCsvFilter
class NumberBound(IComplexCsvFilter):
"""
Accepts csvs up until a certain quota
"""
def __init__(self, max_accepted: int):
self.max_accepted = max_accepted
self.csv_accepted = 0
def reset(self):
self.csv_accepted = 0
def is_valid(self, path: PathStr, csv_ks0001str: KS001Str, csv_ks001: "KS001", data_type: DataTypeStr, index: int, csv_data: List[Tuple[str, "ITestContext", KS001Str, "KS001", str]]) -> bool:
if self.csv_accepted < self.max_accepted:
self.csv_accepted += 1
return True
return False
|
52bacb6f3bb01da90a13257d506de8184feabbbf
|
{
"blob_id": "52bacb6f3bb01da90a13257d506de8184feabbbf",
"branch_name": "refs/heads/master",
"committer_date": "2022-12-08T10:55:04",
"content_id": "02f60f3341072263a2f59d6e1fa20d68130914bb",
"detected_licenses": [
"MIT"
],
"directory_id": "4b378464014d57340b83dbd6231a71546065f43c",
"extension": "py",
"filename": "complex_filters.py",
"fork_events_count": 0,
"gha_created_at": "2019-02-07T15:23:03",
"gha_event_created_at": "2023-02-08T00:38:37",
"gha_language": "C++",
"gha_license_id": "MIT",
"github_id": 169592989,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 790,
"license": "MIT",
"license_type": "permissive",
"path": "/PhdTester/phdTester/resource_filters/complex_filters.py",
"provenance": "stack-edu-0062.json.gz:560279",
"repo_name": "Koldar/phdTester",
"revision_date": "2022-12-08T10:55:04",
"revision_id": "14f0b3244573ca493ad502fd30aa6eeb7abc5bf9",
"snapshot_id": "d16d9838fb29c53e85672ab549c6111086065792",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Koldar/phdTester/14f0b3244573ca493ad502fd30aa6eeb7abc5bf9/PhdTester/phdTester/resource_filters/complex_filters.py",
"visit_date": "2023-02-26T06:04:18.504300",
"added": "2024-11-19T00:44:16.235558+00:00",
"created": "2022-12-08T10:55:04",
"int_score": 2,
"score": 2.34375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0080.json.gz"
}
|
from tensorflow.keras.layers import Dense, Dropout, LSTM
from tensorflow.keras.models import Sequential
# Neural Network
def lstm(train_shape):
model = Sequential()
model.add(LSTM(units=100, return_sequences=True, input_shape=(train_shape[1], 1)))
model.add(Dropout(0.5))
model.add(LSTM(units=50, return_sequences=True))
model.add(Dropout(0.5))
model.add(LSTM(units=25))
model.add(Dropout(0.5))
model.add(Dense(units=1))
return model
|
ba4128e050f09bf35fa4a5cda07b3030c83a43e9
|
{
"blob_id": "ba4128e050f09bf35fa4a5cda07b3030c83a43e9",
"branch_name": "refs/heads/main",
"committer_date": "2021-05-05T21:12:41",
"content_id": "ebea810a1e81f601b760189c9fec37d70af63406",
"detected_licenses": [
"MIT"
],
"directory_id": "b6403292916c523a3580c7ce7785d11cdb50aae4",
"extension": "py",
"filename": "model.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 364701410,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 452,
"license": "MIT",
"license_type": "permissive",
"path": "/model.py",
"provenance": "stack-edu-0063.json.gz:102283",
"repo_name": "aaronwangj/cryptocurrency-lstm",
"revision_date": "2021-05-05T21:12:41",
"revision_id": "2f93619472d2d41216106a1682f9e74b4203012e",
"snapshot_id": "ec156b664757de5d8309f4e1d32926752f5436c8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/aaronwangj/cryptocurrency-lstm/2f93619472d2d41216106a1682f9e74b4203012e/model.py",
"visit_date": "2023-05-03T00:26:25.352560",
"added": "2024-11-19T02:32:42.648676+00:00",
"created": "2021-05-05T21:12:41",
"int_score": 3,
"score": 2.5625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0081.json.gz"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.