uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
806526a6bd17f881b22dca58
train
function
def get_colors_for_classes(num_classes): """Return list of random colors for number of classes given.""" # Use previously generated colors if num_classes is the same. if (hasattr(get_colors_for_classes, "colors") and len(get_colors_for_classes.colors) == num_classes): return get_colors_f...
def get_colors_for_classes(num_classes):
"""Return list of random colors for number of classes given.""" # Use previously generated colors if num_classes is the same. if (hasattr(get_colors_for_classes, "colors") and len(get_colors_for_classes.colors) == num_classes): return get_colors_for_classes.colors hsv_tuples = [(x /...
0 width = image_shape[1] * 1.0 image_dims = K.stack([height, width, height, width]) image_dims = K.reshape(image_dims, [1, 4]) boxes = boxes * image_dims return boxes def get_colors_for_classes(num_classes):
66
66
220
8
57
just-youssef/YOLO-Car-Detection-Model
yad2k/utils/utils.py
Python
get_colors_for_classes
get_colors_for_classes
65
81
65
65
75db476f3273f7c46e196ae04c4950b491121cf7
bigcode/the-stack
train
f9cdde1917b49951ef8eb97e
train
function
def preprocess_image(img_path, model_image_size): image_type = imghdr.what(img_path) image = Image.open(img_path) resized_image = image.resize(tuple(reversed(model_image_size)), Image.BICUBIC) image_data = np.array(resized_image, dtype='float32') image_data /= 255. image_data = np.expand_dims(im...
def preprocess_image(img_path, model_image_size):
image_type = imghdr.what(img_path) image = Image.open(img_path) resized_image = image.resize(tuple(reversed(model_image_size)), Image.BICUBIC) image_data = np.array(resized_image, dtype='float32') image_data /= 255. image_data = np.expand_dims(image_data, 0) # Add batch dimension. return im...
"""Draw predicted or ground truth boxes on input image.""" import imghdr import colorsys import random import numpy as np from PIL import Image, ImageDraw, ImageFont from tensorflow.keras import backend as K from functools import reduce def preprocess_image(img_path, model_image_size):
62
64
96
10
51
just-youssef/YOLO-Car-Detection-Model
yad2k/utils/utils.py
Python
preprocess_image
preprocess_image
11
18
11
11
020d05883bb48176a7ce0a4c8eb42020cc7d16ac
bigcode/the-stack
train
9b7009a9f77a489db5647cbe
train
function
def scale_boxes(boxes, image_shape): """ Scales the predicted boxes in order to be drawable on the image""" height = image_shape[0] * 1.0 width = image_shape[1] * 1.0 image_dims = K.stack([height, width, height, width]) image_dims = K.reshape(image_dims, [1, 4]) boxes = boxes * image_dims re...
def scale_boxes(boxes, image_shape):
""" Scales the predicted boxes in order to be drawable on the image""" height = image_shape[0] * 1.0 width = image_shape[1] * 1.0 image_dims = K.stack([height, width, height, width]) image_dims = K.reshape(image_dims, [1, 4]) boxes = boxes * image_dims return boxes
:2], # y_min box_mins[..., 0:1], # x_min box_maxes[..., 1:2], # y_max box_maxes[..., 0:1] # x_max ]) def scale_boxes(boxes, image_shape):
64
64
95
9
55
just-youssef/YOLO-Car-Detection-Model
yad2k/utils/utils.py
Python
scale_boxes
scale_boxes
56
63
56
56
2eb3e314257b9d02178429d92dc4b400980b97fb
bigcode/the-stack
train
a6aed74bc97e484860b0ad81
train
function
def draw_boxes(image, boxes, box_classes, class_names, scores=None): """Draw bounding boxes on image. Draw bounding boxes with class name and optional box score on image. Args: image: An `array` of shape (width, height, 3) with values in [0, 1]. boxes: An `array` of shape (num_boxes, 4) co...
def draw_boxes(image, boxes, box_classes, class_names, scores=None):
"""Draw bounding boxes on image. Draw bounding boxes with class name and optional box score on image. Args: image: An `array` of shape (width, height, 3) with values in [0, 1]. boxes: An `array` of shape (num_boxes, 4) containing box corners as (y_min, x_min, y_max, x_max). ...
(get_colors_for_classes.colors) == num_classes): return get_colors_for_classes.colors hsv_tuples = [(x / num_classes, 1., 1.) for x in range(num_classes)] colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples)) colors = list( map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[...
185
185
619
16
168
just-youssef/YOLO-Car-Detection-Model
yad2k/utils/utils.py
Python
draw_boxes
draw_boxes
84
144
84
84
5068747cb043bb75856769b5599649e9edf9e6bc
bigcode/the-stack
train
64b163d5694a0d3b2e300f1c
train
function
def compose(*funcs): """Compose arbitrarily many functions, evaluated left to right. Reference: https://mathieularose.com/function-composition-in-python/ """ # return lambda x: reduce(lambda v, f: f(v), funcs, x) if funcs: return reduce(lambda f, g: lambda *a, **kw: g(f(*a, **kw)), funcs) ...
def compose(*funcs):
"""Compose arbitrarily many functions, evaluated left to right. Reference: https://mathieularose.com/function-composition-in-python/ """ # return lambda x: reduce(lambda v, f: f(v), funcs, x) if funcs: return reduce(lambda f, g: lambda *a, **kw: g(f(*a, **kw)), funcs) else: rais...
(model_image_size)), Image.BICUBIC) image_data = np.array(resized_image, dtype='float32') image_data /= 255. image_data = np.expand_dims(image_data, 0) # Add batch dimension. return image, image_data def compose(*funcs):
64
64
100
6
57
just-youssef/YOLO-Car-Detection-Model
yad2k/utils/utils.py
Python
compose
compose
20
29
20
20
9685cbe48a5f8ea6e19111b2897dc8b912129d36
bigcode/the-stack
train
9958f46ccddaa39d1668b9d3
train
function
def read_classes(classes_path): with open(classes_path) as f: class_names = f.readlines() class_names = [c.strip() for c in class_names] return class_names
def read_classes(classes_path):
with open(classes_path) as f: class_names = f.readlines() class_names = [c.strip() for c in class_names] return class_names
: reduce(lambda v, f: f(v), funcs, x) if funcs: return reduce(lambda f, g: lambda *a, **kw: g(f(*a, **kw)), funcs) else: raise ValueError('Composition of empty sequence not supported.') def read_classes(classes_path):
64
64
41
6
58
just-youssef/YOLO-Car-Detection-Model
yad2k/utils/utils.py
Python
read_classes
read_classes
31
35
31
31
b8efccc016f39170ab6460a62c469a975a4cf1c3
bigcode/the-stack
train
aa51e4d7059ae4a235ba9769
train
function
def yolo_boxes_to_corners(box_xy, box_wh): """Convert YOLO box predictions to bounding box corners.""" box_mins = box_xy - (box_wh / 2.) box_maxes = box_xy + (box_wh / 2.) return K.concatenate([ box_mins[..., 1:2], # y_min box_mins[..., 0:1], # x_min box_maxes[..., 1:2], # y_...
def yolo_boxes_to_corners(box_xy, box_wh):
"""Convert YOLO box predictions to bounding box corners.""" box_mins = box_xy - (box_wh / 2.) box_maxes = box_xy + (box_wh / 2.) return K.concatenate([ box_mins[..., 1:2], # y_min box_mins[..., 0:1], # x_min box_maxes[..., 1:2], # y_max box_maxes[..., 0:1] # x_max ...
_path): with open(anchors_path) as f: anchors = f.readline() anchors = [float(x) for x in anchors.split(',')] anchors = np.array(anchors).reshape(-1, 2) return anchors def yolo_boxes_to_corners(box_xy, box_wh):
64
64
122
13
50
just-youssef/YOLO-Car-Detection-Model
yad2k/utils/utils.py
Python
yolo_boxes_to_corners
yolo_boxes_to_corners
44
54
44
44
0bad4e5b6e1b9dc64afd8b43082121f8d4a2b639
bigcode/the-stack
train
01bc42df2d9864f1887b7157
train
class
class Migration(migrations.Migration): dependencies = [ ('car', '0006_cartype_carsign'), ] operations = [ migrations.CreateModel( name='CarDetailModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_na...
class Migration(migrations.Migration):
dependencies = [ ('car', '0006_cartype_carsign'), ] operations = [ migrations.CreateModel( name='CarDetailModel', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('carmodel', ...
# Generated by Django 3.1.7 on 2021-07-10 04:54 from django.db import migrations, models class Migration(migrations.Migration):
38
70
234
7
30
Dante-max/Design_System
design_System/design_System/apps/car/migrations/0007_cardetailmodel.py
Python
Migration
Migration
6
30
6
7
d430756d0342ad8227f4e5a7e0510d78a74ccb10
bigcode/the-stack
train
af4b8f8bd812af959926277b
train
function
def payment_process(request): order_id = request.session.get("order_id") order = get_object_or_404(Order, id=order_id) paystack_key = paystack_public_key if request.method == "POST": transaction = Transaction.initialize( reference=f"ANGALABIRI_REF_ORDER_{order_id}", emai...
def payment_process(request):
order_id = request.session.get("order_id") order = get_object_or_404(Order, id=order_id) paystack_key = paystack_public_key if request.method == "POST": transaction = Transaction.initialize( reference=f"ANGALABIRI_REF_ORDER_{order_id}", email=order.email, amo...
.PAYSTACK_SECRET_KEY paystack_public_key = settings.PAYSTACK_PUBLIC_KEY paystack = Paystack(secret_key=paystack_secret_key) from angalabiri.shop.models.ordermodels import Order from django.shortcuts import get_object_or_404, redirect, render def payment_process(request):
64
64
168
5
58
dark-codr/ebiangala
angalabiri/shop/views/billingviews.py
Python
payment_process
payment_process
69
87
69
69
ec17d8191693a1488872a9443827ba8adfc21f43
bigcode/the-stack
train
607cd150f4c2552843bb7aef
train
function
def payment_done(request): return render(request, 'shop/billing/payment-done.html')
def payment_done(request):
return render(request, 'shop/billing/payment-done.html')
.transaction_id = transaction.id order.save() return redirect('shop:payment-done') else: return redirect('shop:payment-failed') return render(request, 'shop/billing/payment.html', {'order': order, 'paystack_key': paystack_key}) def payment_done(request):
64
64
19
5
59
dark-codr/ebiangala
angalabiri/shop/views/billingviews.py
Python
payment_done
payment_done
90
91
90
90
6d89795a12249fc2b8c09ff0c2658d627b26bf88
bigcode/the-stack
train
5e4a920cc826f89cf0484298
train
function
def payment_failed(request): return render(request, 'shop/billing/payment-failed.html')
def payment_failed(request):
return render(request, 'shop/billing/payment-failed.html')
') else: return redirect('shop:payment-failed') return render(request, 'shop/billing/payment.html', {'order': order, 'paystack_key': paystack_key}) def payment_done(request): return render(request, 'shop/billing/payment-done.html') def payment_failed(request):
64
64
19
5
59
dark-codr/ebiangala
angalabiri/shop/views/billingviews.py
Python
payment_failed
payment_failed
94
95
94
94
3ace7e0abc2644c3309258ead5737dc63200b227
bigcode/the-stack
train
11f67964c099e528fb823c17
train
class
class EventTemplate(models.Model): title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) address = models.TextField(null=True, blank=True) map_search_query = models.CharField(max_length=300, blank=True, null=True) in_person = models.BooleanField(default=True...
class EventTemplate(models.Model):
title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) address = models.TextField(null=True, blank=True) map_search_query = models.CharField(max_length=300, blank=True, null=True) in_person = models.BooleanField(default=True) live_stream = models.BooleanF...
): local_timezone = pytz.timezone(settings.TIME_ZONE) local_date = self.start.astimezone(local_timezone) return f'{local_date.strftime("%G-%m-%d %I:%M%p")} - {self.church.name} - {self.title}' class EventTemplate(models.Model):
63
64
139
6
57
mennonitengemeinde/church_site
schedules/models.py
Python
EventTemplate
EventTemplate
57
73
57
57
1741cacd5ffdef5c42a3e4117fe18f6f2c5feac3
bigcode/the-stack
train
789bd32f2660dbe4fe104f1b
train
class
class Attendant(models.Model): event = models.ForeignKey(Event, on_delete=models.PROTECT, related_name='attendants') full_name = models.CharField(max_length=150) amount = models.IntegerField(default=1, validators=[MinValueValidator(1)]) class Meta: ordering = ('event', 'full_name') def __s...
class Attendant(models.Model):
event = models.ForeignKey(Event, on_delete=models.PROTECT, related_name='attendants') full_name = models.CharField(max_length=150) amount = models.IntegerField(default=1, validators=[MinValueValidator(1)]) class Meta: ordering = ('event', 'full_name') def __str__(self): return f'{s...
attendance_limit = models.IntegerField(default=0) attendance_signup = models.BooleanField(default=False) visibility = models.CharField(max_length=50, choices=visibility_choices) class Meta: ordering = ['title'] def __str__(self): return self.title class Attendant(models.Model):
64
64
90
6
57
mennonitengemeinde/church_site
schedules/models.py
Python
Attendant
Attendant
76
85
76
76
8dfd306bbbfaa23f17b469c206de1d6c538e13b6
bigcode/the-stack
train
5b260d31dd6c3b57bbbc473e
train
class
class Event(models.Model): church = models.ForeignKey(Church, on_delete=models.PROTECT, related_name='events') start = models.DateTimeField() end = models.DateTimeField() title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) address = models.TextField(nul...
class Event(models.Model):
church = models.ForeignKey(Church, on_delete=models.PROTECT, related_name='events') start = models.DateTimeField() end = models.DateTimeField() title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) address = models.TextField(null=True, blank=True) map...
import pytz from django.conf import settings from django.core.validators import MinValueValidator from django.db import models from churches.models import Church from speakers.models import Speaker visibility_choices = ( ('public', 'Public'), ('private', 'Private'), ('members', 'Members Only'), ) class Ev...
69
100
335
5
64
mennonitengemeinde/church_site
schedules/models.py
Python
Event
Event
16
54
16
16
75a59894864a6f9d1d259b270dc0130470828551
bigcode/the-stack
train
7d9a7a502dd40dedf43cb9a0
train
function
def logPowerSpectrum(sig, samplingFreq, fftLength=512): '''The signal log power spectrum''' powerSpec, freqs = powerSpectrum(sig, samplingFreq, fftLength) powerSpec[powerSpec == 0] = 1e-20 logPowerSpec = 10 * np.log10(powerSpec) return logPowerSpec, freqs
def logPowerSpectrum(sig, samplingFreq, fftLength=512):
'''The signal log power spectrum''' powerSpec, freqs = powerSpectrum(sig, samplingFreq, fftLength) powerSpec[powerSpec == 0] = 1e-20 logPowerSpec = 10 * np.log10(powerSpec) return logPowerSpec, freqs
plotEnabled: plt.figure() plt.plot(freqs, powerSpec, color='black') plt.xlabel('Freq (kHz)') plt.ylabel('Power (linear)') plt.draw() return powerSpec, freqs def logPowerSpectrum(sig, samplingFreq, fftLength=512):
64
64
79
14
49
liborutgers12/audiospeech
preprocessing.py
Python
logPowerSpectrum
logPowerSpectrum
89
94
89
89
5f487807370f47b83a640a40321ebfe6c84938c3
bigcode/the-stack
train
5358ad48fc311aa150c44bc6
train
function
def powerSpectrum(sig, samplingFreq, fftLength=512, sides='onesided', plotEnabled=False): '''The signal power spectrum (in V^2)''' assert(sig.ndim==1) lenSig = sig.shape[0] # Apply Fourier transform sigDft = myfft(sig, fftLength, sides) lenDft = len(sigDft) # for power spectral density in V^2/Hz, different...
def powerSpectrum(sig, samplingFreq, fftLength=512, sides='onesided', plotEnabled=False):
'''The signal power spectrum (in V^2)''' assert(sig.ndim==1) lenSig = sig.shape[0] # Apply Fourier transform sigDft = myfft(sig, fftLength, sides) lenDft = len(sigDft) # for power spectral density in V^2/Hz, different scale is needed scale = 1.0 # 1.0/samplingFreq powerSpec = scale * np.conjugate(sig...
osided'): if sides == 'twosided': return fftpack.fft(sig,fftLength) elif sides == 'onesided': return np.fft.rfft(sig.real,fftLength) else: raise ValueError('Sides options: twosided or onesided') def powerSpectrum(sig, samplingFreq, fftLength=512, sides='onesided', plotEnabled=False):
84
84
281
22
62
liborutgers12/audiospeech
preprocessing.py
Python
powerSpectrum
powerSpectrum
59
87
59
59
33de4a40b6df8c7d2f1f1f71d67d75d6958ecec4
bigcode/the-stack
train
f24088afeafbdf92521733c1
train
function
def overlapSegs(sig, lenSeg, overlapRatio=0, mode='TRUNC', winType='RECT'): '''Break the 1D signal into overlapping segments in 2D numpy array lenSeg*numSegs''' assert(sig.ndim == 1) lenSkip = int(lenSeg * (1 - overlapRatio)) numSegs = (sig.shape[0] - (lenSeg-lenSkip)) // lenSkip sigSegs = np.zeros(lenS...
def overlapSegs(sig, lenSeg, overlapRatio=0, mode='TRUNC', winType='RECT'):
'''Break the 1D signal into overlapping segments in 2D numpy array lenSeg*numSegs''' assert(sig.ndim == 1) lenSkip = int(lenSeg * (1 - overlapRatio)) numSegs = (sig.shape[0] - (lenSeg-lenSkip)) // lenSkip sigSegs = np.zeros(lenSeg*numSegs).reshape(lenSeg,numSegs) for n in np.arange(numSegs): idx...
elif winType == 'HANN': winCoeff = 0.5*(1 - np.cos(2*np.pi/(lenW-1)*np.arange(lenW))) else: raise ValueError('Window type options: RECT or TRIANG or HANN or HAMMING') return winCoeff def overlapSegs(sig, lenSeg, overlapRatio=0, mode='TRUNC', winType='RECT'):
91
91
304
25
65
liborutgers12/audiospeech
preprocessing.py
Python
overlapSegs
overlapSegs
24
49
24
24
1305deab02123b07519ca0d0dfad45881d042d8b
bigcode/the-stack
train
e6054e1acbd6f934014a01bf
train
function
def myfft(sig, fftLength=512, sides='twosided'): if sides == 'twosided': return fftpack.fft(sig,fftLength) elif sides == 'onesided': return np.fft.rfft(sig.real,fftLength) else: raise ValueError('Sides options: twosided or onesided')
def myfft(sig, fftLength=512, sides='twosided'):
if sides == 'twosided': return fftpack.fft(sig,fftLength) elif sides == 'onesided': return np.fft.rfft(sig.real,fftLength) else: raise ValueError('Sides options: twosided or onesided')
TRUNC or PADDING0') #Apply window function winCoeff = getWinCoeff(winType, lenSeg) sigSegs = sigSegs * winCoeff[:,np.newaxis] return sigSegs def myfft(sig, fftLength=512, sides='twosided'):
64
64
75
16
47
liborutgers12/audiospeech
preprocessing.py
Python
myfft
myfft
51
57
51
51
6ee08544ba6d25e98264ebab015d9d5d8b3ade60
bigcode/the-stack
train
c7f5ac9089db82adc04d2ca8
train
function
def getWinCoeff(winType, lenW): if winType == 'RECT': winCoeff = np.ones(lenW) elif winType == 'TRIANG': winCoeff = 1 - np.abs((np.arange(lenW) - (lenW-1)/2)/((lenW-1)/2)) elif winType == 'HAMMING': winCoeff = 0.54 - 0.46*np.cos(2*np.pi/(lenW-1)*np.arange(lenW)) elif winType == 'HANN': winCoeff ...
def getWinCoeff(winType, lenW):
if winType == 'RECT': winCoeff = np.ones(lenW) elif winType == 'TRIANG': winCoeff = 1 - np.abs((np.arange(lenW) - (lenW-1)/2)/((lenW-1)/2)) elif winType == 'HAMMING': winCoeff = 0.54 - 0.46*np.cos(2*np.pi/(lenW-1)*np.arange(lenW)) elif winType == 'HANN': winCoeff = 0.5*(1 - np.cos(2*np.pi/(lenW-...
from __future__ import division from __future__ import print_function import numpy as np from scipy import fftpack import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import matplotlib.cm as cm def getWinCoeff(winType, lenW):
62
64
175
10
51
liborutgers12/audiospeech
preprocessing.py
Python
getWinCoeff
getWinCoeff
10
22
10
10
435f77bd28c432cd4a5a10890810d25bb6f9f41e
bigcode/the-stack
train
8672a6fbebf852ae4324cd8b
train
function
def spectrogram(sig, samplingFreq, fftLength=512, overlapRatio=0.5, winType='HAMMING', plotEnabled=False): '''The signal spectrogram of the audio signal''' assert(sig.ndim==1) sigSegs = overlapSegs(sig, fftLength, overlapRatio, winType=winType) numSegs = sigSegs.shape[1] sigSpectrogram = np.zeros((fftLength//...
def spectrogram(sig, samplingFreq, fftLength=512, overlapRatio=0.5, winType='HAMMING', plotEnabled=False):
'''The signal spectrogram of the audio signal''' assert(sig.ndim==1) sigSegs = overlapSegs(sig, fftLength, overlapRatio, winType=winType) numSegs = sigSegs.shape[1] sigSpectrogram = np.zeros((fftLength//2 + 1, numSegs)) for idx in np.arange(numSegs): sigSeg = sigSegs[:,idx] sigSpectrogram[:,idx], _ ...
''' powerSpec, freqs = powerSpectrum(sig, samplingFreq, fftLength) powerSpec[powerSpec == 0] = 1e-20 logPowerSpec = 10 * np.log10(powerSpec) return logPowerSpec, freqs def spectrogram(sig, samplingFreq, fftLength=512, overlapRatio=0.5, winType='HAMMING', plotEnabled=False):
89
89
299
31
57
liborutgers12/audiospeech
preprocessing.py
Python
spectrogram
spectrogram
97
120
97
97
c8c973ec3ad050903411e9c97ef0f40501968a00
bigcode/the-stack
train
76cb7d543cc7d1d0e1740e17
train
function
def GetTraceString(exctype, value, traceb): traceString = '\u200b'.join(traceback.format_exception(exctype, value, traceb)) traceString = re.sub(r'"[^"]+/(?:API/AddIns|Api/Python)', '"', traceString) return traceString.replace(getpass.getuser(),'<user>').replace('\\','\\\u200b').replace('/','/\u200b')
def GetTraceString(exctype, value, traceb):
traceString = '\u200b'.join(traceback.format_exception(exctype, value, traceb)) traceString = re.sub(r'"[^"]+/(?:API/AddIns|Api/Python)', '"', traceString) return traceString.replace(getpass.getuser(),'<user>').replace('\\','\\\u200b').replace('/','/\u200b')
\ErrorUtilities.py # Shorten file paths, to compact the message >>> traceString = ''.join(traceback.format_exception(exctype, value, traceb)) # Attempt to scrub the user's username from the traceback, if any remains """ def GetTraceString(exctype, value, traceb):
64
64
87
12
52
Zxynine/AddinLib
error.py
Python
GetTraceString
GetTraceString
25
28
25
25
3aacb7ff0dc37422dc545b45c95b86a4ab90e014
bigcode/the-stack
train
4ea4e597d1fbe5877ca1ee36
train
class
class ErrorCatcher(): ''' Showing a messagebox is disabled in debugging, by default, to avoid the case where Fusion is stopped and the debugger fails to reattach on Restart. --- ## __init__ msgbox_in_debug: Show an error message box also when debugging. msg_prefix: Prefix error message with this text. E....
class ErrorCatcher():
''' Showing a messagebox is disabled in debugging, by default, to avoid the case where Fusion is stopped and the debugger fails to reattach on Restart. --- ## __init__ msgbox_in_debug: Show an error message box also when debugging. msg_prefix: Prefix error message with this text. E.g. with add-in na...
cripts part of the path caller = re.sub(r'.*API[/\\]','',callerPath) return (f'{PreMessage} error: {ErrorValue}\n\n' + 'Copy this message by taking a screenshot. ' + 'Describe what you did to get this error or record a video.\n\n' + f'{"-"*50}\n\n'+ f'Fusion 360 v. {FusionVersion}\n' + f'{caller} faile...
120
120
401
5
115
Zxynine/AddinLib
error.py
Python
ErrorCatcher
ErrorCatcher
43
89
43
43
5c24061811d0cdd6c0d8abed720cbed99ea0e166
bigcode/the-stack
train
d706b2a87019d1176f777dc5
train
function
def GetMessage(PreMessage,ErrorValue, callerPath, FusionVersion, TraceString): # Only keep the AddIns/Scripts part of the path caller = re.sub(r'.*API[/\\]','',callerPath) return (f'{PreMessage} error: {ErrorValue}\n\n' + 'Copy this message by taking a screenshot. ' + 'Describe what you did to get this error o...
def GetMessage(PreMessage,ErrorValue, callerPath, FusionVersion, TraceString): # Only keep the AddIns/Scripts part of the path
caller = re.sub(r'.*API[/\\]','',callerPath) return (f'{PreMessage} error: {ErrorValue}\n\n' + 'Copy this message by taking a screenshot. ' + 'Describe what you did to get this error or record a video.\n\n' + f'{"-"*50}\n\n'+ f'Fusion 360 v. {FusionVersion}\n' + f'{caller} failed: \n\n' + TraceString)
) return traceString.replace(getpass.getuser(),'<user>').replace('\\','\\\u200b').replace('/','/\u200b') def GetMessage(PreMessage,ErrorValue, callerPath, FusionVersion, TraceString): # Only keep the AddIns/Scripts part of the path
63
64
142
33
30
Zxynine/AddinLib
error.py
Python
GetMessage
GetMessage
30
38
30
31
b45218a18fb5c76dd0cf409ae855749146b2b513
bigcode/the-stack
train
d616377c7d77262813baeae2
train
class
class Ignore: def __init__(self, *types): self.types=types def __enter__(self):return self def __exit__(self,ExType,ExVal,ExTrace): return self.types or ExType in self.types
class Ignore:
def __init__(self, *types): self.types=types def __enter__(self):return self def __exit__(self,ExType,ExVal,ExTrace): return self.types or ExType in self.types
) else: print("Not shown in message box.") return True # Exception handled # def _error_catcher_wrapper(class_self_Ref, func): # def catcher(func_self, args): # with class_self_Ref.error_catcher: func(args) # return catcher class Ignore:
64
64
53
3
60
Zxynine/AddinLib
error.py
Python
Ignore
Ignore
99
103
99
99
245bdaf8dcf5372f1ee502188d8c6da9a58222c6
bigcode/the-stack
train
f8fe0bbde3e7431d11f86c6b
train
class
class APIs: """The wrapper for all annotation APIs""" def __init__(self, parameters): self.namespace = parameters['namespace'] self.logger = Logger('\'' + self.namespace + '\'', parameters['logger']) self.socket = parameters['socket'] self.package = parameters['package'] ...
class APIs:
"""The wrapper for all annotation APIs""" def __init__(self, parameters): self.namespace = parameters['namespace'] self.logger = Logger('\'' + self.namespace + '\'', parameters['logger']) self.socket = parameters['socket'] self.package = parameters['package'] self.api_par...
"""The default APIs class""" import importlib from flask import request from .logger import Logger from .file import FileOperations as FileOp from .api import get_client_msg class APIs:
42
204
680
3
38
CFLai1990/ObjDetection
apis/libs/apis.py
Python
APIs
APIs
8
98
8
8
2ccd6fbf33e0d3b97395b1c565ca6ae31064d553
bigcode/the-stack
train
eda66e6f28821bbf2a412013
train
class
class Solution: def sortedSquares(self, nums: list[int]) -> list[int]: positive_start = sys.maxsize for index, num in enumerate(nums): if num >= 0: positive_start = index break negatives, positives = nums[:positive_start], nums[positive_start:] ...
class Solution:
def sortedSquares(self, nums: list[int]) -> list[int]: positive_start = sys.maxsize for index, num in enumerate(nums): if num >= 0: positive_start = index break negatives, positives = nums[:positive_start], nums[positive_start:] positive_...
2[index2] if num1 < num2: output.append(num1) index1 += 1 else: output.append(num2) index2 += 1 output += list1[index1:] output += list2[index2:] return output class Solution:
64
64
111
3
60
tusharsadhwani/leetcode
squares_of_a_sorted_array.py
Python
Solution
Solution
21
34
21
21
e6ae5a0e4520a181fc2709cc4940620296f89646
bigcode/the-stack
train
b4f98aaf9a7d49c18e70d831
train
function
def merge(list1: list[int], list2: list[int]) -> list[int]: output: list[int] = [] index1, index2 = 0, 0 while index1 < len(list1) and index2 < len(list2): num1, num2 = list1[index1], list2[index2] if num1 < num2: output.append(num1) index1 += 1 else: ...
def merge(list1: list[int], list2: list[int]) -> list[int]:
output: list[int] = [] index1, index2 = 0, 0 while index1 < len(list1) and index2 < len(list2): num1, num2 = list1[index1], list2[index2] if num1 < num2: output.append(num1) index1 += 1 else: output.append(num2) index2 += 1 output ...
import sys def merge(list1: list[int], list2: list[int]) -> list[int]:
21
64
130
18
2
tusharsadhwani/leetcode
squares_of_a_sorted_array.py
Python
merge
merge
4
18
4
4
0475d16682d15710084f6d59c335676fc07b2258
bigcode/the-stack
train
ae7e452b0fd315a177d3edc2
train
function
def guess_loops_hierarchically(vdc_vec, projected_loops_2d): """ Provides loop parameter guesses for a given set of loops Parameters ---------- vdc_vec : 1D numpy float numpy array DC voltage offsets for the loops projected_loops_2d : 2D numpy float array Projected loops arrange...
def guess_loops_hierarchically(vdc_vec, projected_loops_2d):
""" Provides loop parameter guesses for a given set of loops Parameters ---------- vdc_vec : 1D numpy float numpy array DC voltage offsets for the loops projected_loops_2d : 2D numpy float array Projected loops arranged as [instance or position x dc voltage steps] Returns ...
.dtype, self._h5_fit.shape, self._h5_fit.dtype)) self._h5_fit[curr_pixels, :] = fits_2d self._h5_fit.file.flush() def _be_loop_err(coef_vec, data_vec, dc_vec, *args): """ Parameters ---------- coef_vec : numpy.ndarray data_vec : numpy.ndarray dc_vec : num...
256
256
1,017
19
236
pycroscopy/BGlib
BGlib/be/analysis/be_loop_fitter.py
Python
guess_loops_hierarchically
guess_loops_hierarchically
1,223
1,333
1,223
1,223
24e79f97f2fc1dadaa2e4246f38279da9d570e07
bigcode/the-stack
train
c87c048214ff4d6da6ad02ec
train
function
def _be_loop_err(coef_vec, data_vec, dc_vec, *args): """ Parameters ---------- coef_vec : numpy.ndarray data_vec : numpy.ndarray dc_vec : numpy.ndarray The DC offset vector args : list Returns ------- fitness : float The 1-r^2 value for the current set of loop c...
def _be_loop_err(coef_vec, data_vec, dc_vec, *args):
""" Parameters ---------- coef_vec : numpy.ndarray data_vec : numpy.ndarray dc_vec : numpy.ndarray The DC offset vector args : list Returns ------- fitness : float The 1-r^2 value for the current set of loop coefficients """ if coef_vec.size < 9: ...
fits_2d.dtype, self._h5_fit.shape, self._h5_fit.dtype)) self._h5_fit[curr_pixels, :] = fits_2d self._h5_fit.file.flush() def _be_loop_err(coef_vec, data_vec, dc_vec, *args):
64
64
195
18
46
pycroscopy/BGlib
BGlib/be/analysis/be_loop_fitter.py
Python
_be_loop_err
_be_loop_err
1,190
1,220
1,190
1,190
2dfa94aab1e5735bc21339a6fe70b3a4f575b550
bigcode/the-stack
train
ebb40469d513239cbb5877d8
train
class
class BELoopFitter(Fitter): """ A class that fits Simple Harmonic Oscillator model data to a 9-parameter model to describe hysteretic switching in ferroelectric materials Notes ----- Quantitative mapping of switching behavior in piezoresponse force microscopy, Stephen Jesse, Ho Nyung Lee, ...
class BELoopFitter(Fitter):
""" A class that fits Simple Harmonic Oscillator model data to a 9-parameter model to describe hysteretic switching in ferroelectric materials Notes ----- Quantitative mapping of switching behavior in piezoresponse force microscopy, Stephen Jesse, Ho Nyung Lee, and Sergei V. Kalinin, Re...
\ loop_fit_function, calc_switching_coef_vec, switching32 from .utils.tree import ClusterTree from .be_sho_fitter import sho32 from .fitter import Fitter ''' Custom dtypes for the datasets created during fitting. ''' loop_metrics32 = np.dtype({'names': ['Area', 'Centroid x', 'Centroid y', ...
256
256
10,499
8
248
pycroscopy/BGlib
BGlib/be/analysis/be_loop_fitter.py
Python
BELoopFitter
BELoopFitter
55
1,187
55
55
60fef410d2886ee47d4d40edfb4b275387e06df2
bigcode/the-stack
train
4467d99baf0334aa967c03e9
train
function
def shift_vdc(vdc_vec): """ Rolls the Vdc vector by a quarter cycle Parameters ---------- vdc_vec : 1D numpy array DC offset vector Returns ------- shift_ind : int Number of indices by which the vector was rolled vdc_shifted : 1D numpy array Vdc vector rolle...
def shift_vdc(vdc_vec):
""" Rolls the Vdc vector by a quarter cycle Parameters ---------- vdc_vec : 1D numpy array DC offset vector Returns ------- shift_ind : int Number of indices by which the vector was rolled vdc_shifted : 1D numpy array Vdc vector rolled by a quarter cycle ...
_fit_results[clust_id][0].fun ** 2)) guess_parms[pix_inds] = stack_real_to_compound( np.hstack([temp, np.atleast_2d(r2)]), loop_fit32) return guess_parms def shift_vdc(vdc_vec):
64
64
141
8
55
pycroscopy/BGlib
BGlib/be/analysis/be_loop_fitter.py
Python
shift_vdc
shift_vdc
1,336
1,356
1,336
1,336
1ce1e6b228dac627c17855138dbe1011400456b4
bigcode/the-stack
train
b0edf01a49399e189b1496fc
train
function
def gpu_worker_proc_6_1(kn, rank, gpu_i, q): nk = pynccl.NcclWrp(kn, rank, gpu_i) if rank == 0: nuid = nk.get_nuid() w = torch.Tensor(np.random.random((kn * 10, 5))) # w w = w.cuda(gpu_i) # =====> gpu print('w', w.shape, w) for j in range(kn - 1): q.put...
def gpu_worker_proc_6_1(kn, rank, gpu_i, q):
nk = pynccl.NcclWrp(kn, rank, gpu_i) if rank == 0: nuid = nk.get_nuid() w = torch.Tensor(np.random.random((kn * 10, 5))) # w w = w.cuda(gpu_i) # =====> gpu print('w', w.shape, w) for j in range(kn - 1): q.put((nuid, w)) else: nuid, w = q.get...
3] # ------------------------------------- procs = [] q = mp.Queue() # ------------------------------------- for i in range(nrank): worker = mp.Process( target=gpu_worker_proc_6_1, args=(nrank, i, gpu_is[i], q)) worker.daemon = True worker.start(...
106
106
356
17
89
lancelee82/pynccl
tests/test_23_pt_p2p.py
Python
gpu_worker_proc_6_1
gpu_worker_proc_6_1
54
109
54
55
444510bddef891928289f0b650654969c17f4e22
bigcode/the-stack
train
f03291f9cc38669dc448a28b
train
function
def test_6_001(): nrank = 2#4#8 gpu_is = [1, 3] # ------------------------------------- procs = [] q = mp.Queue() # ------------------------------------- for i in range(nrank): worker = mp.Process( target=gpu_worker_proc_6_1, args=(nrank, i, gpu_is[i], q...
def test_6_001():
nrank = 2#4#8 gpu_is = [1, 3] # ------------------------------------- procs = [] q = mp.Queue() # ------------------------------------- for i in range(nrank): worker = mp.Process( target=gpu_worker_proc_6_1, args=(nrank, i, gpu_is[i], q)) worker.d...
#from numba import cuda #from numba.cuda import driver as cuda_driver CURR_DIR = os.path.dirname(os.path.abspath(__file__)) ROOT_DIR = os.path.dirname(CURR_DIR) sys.path.insert(0, ROOT_DIR) import pynccl import torch def test_6_001():
64
64
114
7
56
lancelee82/pynccl
tests/test_23_pt_p2p.py
Python
test_6_001
test_6_001
28
51
28
29
fe05654dc7802fefd07626bf1f43c937269322dd
bigcode/the-stack
train
5a5dceb6d5ffa659e6a16694
train
function
@pytest.fixture def pdf(scope="module"): df = pd.DataFrame() df["Integer"] = np.array([2345, 11987, 9027, 9027]) df["Float"] = np.array([9.001, 8.343, 6, 2.781]) df["Integer2"] = np.array([2345, 106, 2088, 789277], dtype="uint64") df["String"] = np.array(["Alpha", "Beta", "Gamma", "Delta"]) df["...
@pytest.fixture def pdf(scope="module"):
df = pd.DataFrame() df["Integer"] = np.array([2345, 11987, 9027, 9027]) df["Float"] = np.array([9.001, 8.343, 6, 2.781]) df["Integer2"] = np.array([2345, 106, 2088, 789277], dtype="uint64") df["String"] = np.array(["Alpha", "Beta", "Gamma", "Delta"]) df["Boolean"] = np.array([True, False, True, ...
= pa.hdfs.connect(host=host, port=port) try: if not fs.exists(basedir): fs.mkdir(basedir) except pa.lib.ArrowIOError: pytest.skip("hdfs config probably incorrect") return fs @pytest.fixture def pdf(scope="module"):
64
64
136
9
54
res-life/cudf
python/cudf/cudf/tests/test_hdfs.py
Python
pdf
pdf
38
46
38
39
b7e96e24095b07176a3c497f8dc5e9c02dfb1850
bigcode/the-stack
train
5e584ab69fc822a39d081ee4
train
function
def test_storage_options_error(tmpdir, pdf, hdfs): fname = tmpdir.mkdir("csv").join("file.csv") # Write to local file system pdf.to_csv(fname) # Read from local file system as buffer with open(fname, mode="rb") as f: buffer = BytesIO(f.read()) # Write to hdfs hdfs.upload(basedir + "/...
def test_storage_options_error(tmpdir, pdf, hdfs):
fname = tmpdir.mkdir("csv").join("file.csv") # Write to local file system pdf.to_csv(fname) # Read from local file system as buffer with open(fname, mode="rb") as f: buffer = BytesIO(f.read()) # Write to hdfs hdfs.upload(basedir + "/file.csv", buffer) hd_fpath = f"hdfs://{host}:...
_csv(hd_fpath, storage_options=storage_options) # Read pandas from byte buffer with hdfs.open(basedir + "/file.csv") as f: expect = pd.read_csv(f) assert_eq(expect, got) def test_storage_options_error(tmpdir, pdf, hdfs):
64
64
150
13
51
res-life/cudf
python/cudf/cudf/tests/test_hdfs.py
Python
test_storage_options_error
test_storage_options_error
286
301
286
286
29b0d5183e15c24cbf51d0c8f0ebaab3f1b5976e
bigcode/the-stack
train
8ff252574596486e7f1f58db
train
function
@pytest.mark.parametrize("test_url", [False, True]) def test_read_json(tmpdir, pdf, hdfs, test_url): fname = tmpdir.mkdir("json").join("test_json_reader.json") # Write to local file system # Sorting by col_name now as pandas sorts by col name while reading json pdf.sort_index(axis=1).to_json(fname, ori...
@pytest.mark.parametrize("test_url", [False, True]) def test_read_json(tmpdir, pdf, hdfs, test_url):
fname = tmpdir.mkdir("json").join("test_json_reader.json") # Write to local file system # Sorting by col_name now as pandas sorts by col name while reading json pdf.sort_index(axis=1).to_json(fname, orient="records", lines=True) # Read from local file system as buffer with open(fname, mode="rb"...
test_parquet_partitioned.parquet") got = pd.read_parquet(hd_fpath) expect = pd.read_parquet( tmpdir.join("pandas_parquet_writer_partitioned.parquet") ) assert_eq(expect, got) @pytest.mark.parametrize("test_url", [False, True]) def test_read_json(tmpdir, pdf, hdfs, test_url):
79
79
265
27
52
res-life/cudf
python/cudf/cudf/tests/test_hdfs.py
Python
test_read_json
test_read_json
171
197
171
172
16b929f3724c6a310038432d9e3e24d7ac0b71d3
bigcode/the-stack
train
766421f54a825a96d3e04258
train
function
def test_storage_options(tmpdir, pdf, hdfs): fname = tmpdir.mkdir("csv").join("file.csv") # Write to local file system pdf.to_csv(fname) # Read from local file system as buffer with open(fname, mode="rb") as f: buffer = BytesIO(f.read()) # Write to hdfs hdfs.upload(basedir + "/file.c...
def test_storage_options(tmpdir, pdf, hdfs):
fname = tmpdir.mkdir("csv").join("file.csv") # Write to local file system pdf.to_csv(fname) # Read from local file system as buffer with open(fname, mode="rb") as f: buffer = BytesIO(f.read()) # Write to hdfs hdfs.upload(basedir + "/file.csv", buffer) hd_fpath = f"hdfs://{basedi...
open(fname, mode="rb") as f: expect = pd.DataFrame.from_records(fa.reader(f)) for col in expect.columns: expect[col] = expect[col].astype(got[col].dtype) assert_eq(expect, got) def test_storage_options(tmpdir, pdf, hdfs):
64
64
178
12
52
res-life/cudf
python/cudf/cudf/tests/test_hdfs.py
Python
test_storage_options
test_storage_options
263
283
263
263
3922983142a6663381ce448c07ab74fc06a3ac9e
bigcode/the-stack
train
f2a78ec25575ba2a6b37b81a
train
function
@pytest.mark.parametrize("test_url", [False, True]) def test_read_avro(datadir, hdfs, test_url): fname = datadir / "avro" / "example.avro" # Read from local file system as buffer with open(fname, mode="rb") as f: buffer = BytesIO(f.read()) # Write to hdfs hdfs.upload(basedir + "/file.avro", ...
@pytest.mark.parametrize("test_url", [False, True]) def test_read_avro(datadir, hdfs, test_url):
fname = datadir / "avro" / "example.avro" # Read from local file system as buffer with open(fname, mode="rb") as f: buffer = BytesIO(f.read()) # Write to hdfs hdfs.upload(basedir + "/file.avro", buffer) if test_url: hd_fpath = f"hdfs://{host}:{port}{basedir}/file.avro" else:...
}/test_orc_writer.orc", mode="rb") as f: got = orc.ORCFile(f).read().to_pandas() assert_eq(pdf, got) @pytest.mark.parametrize("test_url", [False, True]) def test_read_avro(datadir, hdfs, test_url):
64
64
207
26
38
res-life/cudf
python/cudf/cudf/tests/test_hdfs.py
Python
test_read_avro
test_read_avro
240
260
240
241
6f381f5b48cb1c6140a721709ffd4e06c65f2b2e
bigcode/the-stack
train
adb1a1a4a78e8661685d5f45
train
function
@pytest.mark.parametrize("test_url", [False, True]) def test_read_orc(datadir, hdfs, test_url): fname = datadir / "orc" / "TestOrcFile.testSnappy.orc" # Read from local file system as buffer with open(fname, mode="rb") as f: buffer = BytesIO(f.read()) # Write to hdfs hdfs.upload(basedir + "/...
@pytest.mark.parametrize("test_url", [False, True]) def test_read_orc(datadir, hdfs, test_url):
fname = datadir / "orc" / "TestOrcFile.testSnappy.orc" # Read from local file system as buffer with open(fname, mode="rb") as f: buffer = BytesIO(f.read()) # Write to hdfs hdfs.upload(basedir + "/file.orc", buffer) if test_url: hd_fpath = f"hdfs://{host}:{port}{basedir}/file.orc...
buffer with hdfs.open(basedir + "/test_json_reader.json") as f: expect = pd.read_json(f, lines=True) assert_eq(expect, got) @pytest.mark.parametrize("test_url", [False, True]) def test_read_orc(datadir, hdfs, test_url):
64
64
181
26
38
res-life/cudf
python/cudf/cudf/tests/test_hdfs.py
Python
test_read_orc
test_read_orc
200
216
200
201
e5aa30ad5f46af2dafdb1f5cb809694a043ef9f0
bigcode/the-stack
train
c89324f4d2624aa6eda91c26
train
function
@pytest.fixture def hdfs(scope="module"): # Default Rpc port can be 8020/9000 depending on the hdfs config fs = pa.hdfs.connect(host=host, port=port) try: if not fs.exists(basedir): fs.mkdir(basedir) except pa.lib.ArrowIOError: pytest.skip("hdfs config probably incorrect") ...
@pytest.fixture def hdfs(scope="module"): # Default Rpc port can be 8020/9000 depending on the hdfs config
fs = pa.hdfs.connect(host=host, port=port) try: if not fs.exists(basedir): fs.mkdir(basedir) except pa.lib.ArrowIOError: pytest.skip("hdfs config probably incorrect") return fs
tests") basedir = "/tmp/test-hdfs" host = "localhost" # hadoop hostname port = 9000 # hadoop rpc port @pytest.fixture def hdfs(scope="module"): # Default Rpc port can be 8020/9000 depending on the hdfs config
64
64
87
30
33
res-life/cudf
python/cudf/cudf/tests/test_hdfs.py
Python
hdfs
hdfs
25
35
25
27
b91012c4bd8620e52ee502b21822cb6f6356bd0a
bigcode/the-stack
train
83d2d3e505cfca5fcba76eef
train
function
@pytest.mark.parametrize("test_url", [False, True]) def test_read_parquet(tmpdir, pdf, hdfs, test_url): fname = tmpdir.mkdir("parquet").join("test_parquet_reader.parquet") # Write to local file system pdf.to_parquet(fname) # Read from local file system as buffer with open(fname, mode="rb") as f: ...
@pytest.mark.parametrize("test_url", [False, True]) def test_read_parquet(tmpdir, pdf, hdfs, test_url):
fname = tmpdir.mkdir("parquet").join("test_parquet_reader.parquet") # Write to local file system pdf.to_parquet(fname) # Read from local file system as buffer with open(fname, mode="rb") as f: buffer = BytesIO(f.read()) # Write to hdfs hdfs.upload(basedir + "/test_parquet_reader.parq...
with hdfs.open(f"{basedir}/test_csv_writer.csv", mode="rb") as f: got = pd.read_csv(f, dtype=dict(pdf.dtypes)) assert_eq(pdf, got) @pytest.mark.parametrize("test_url", [False, True]) def test_read_parquet(tmpdir, pdf, hdfs, test_url):
70
70
234
28
42
res-life/cudf
python/cudf/cudf/tests/test_hdfs.py
Python
test_read_parquet
test_read_parquet
94
118
94
95
2e58d70344f87c9ae6b5276f75cf1f00ad5dc100
bigcode/the-stack
train
c72d5eb6e0d468ea8ae24a52
train
function
@pytest.mark.parametrize("test_url", [False, True]) def test_write_parquet(pdf, hdfs, test_url): gdf = cudf.from_pandas(pdf) if test_url: hd_fpath = "hdfs://{}:{}{}/test_parquet_writer.parquet".format( host, port, basedir ) else: hd_fpath = f"hdfs://{basedir}/test_parquet...
@pytest.mark.parametrize("test_url", [False, True]) def test_write_parquet(pdf, hdfs, test_url):
gdf = cudf.from_pandas(pdf) if test_url: hd_fpath = "hdfs://{}:{}{}/test_parquet_writer.parquet".format( host, port, basedir ) else: hd_fpath = f"hdfs://{basedir}/test_parquet_writer.parquet" gdf.to_parquet(hd_fpath) assert hdfs.exists(f"{basedir}/test_parquet_w...
byte buffer with hdfs.open(basedir + "/test_parquet_reader.parquet") as f: expect = pd.read_parquet(f) assert_eq(expect, got) @pytest.mark.parametrize("test_url", [False, True]) def test_write_parquet(pdf, hdfs, test_url):
64
64
164
25
39
res-life/cudf
python/cudf/cudf/tests/test_hdfs.py
Python
test_write_parquet
test_write_parquet
121
137
121
122
f55f45080ded63d2d1bacebfee2254f195eb3c30
bigcode/the-stack
train
582b6b90dae11a7ee27ab903
train
function
@pytest.mark.parametrize("test_url", [False, True]) def test_write_csv(pdf, hdfs, test_url): gdf = cudf.from_pandas(pdf) if test_url: hd_fpath = "hdfs://{}:{}{}/test_csv_writer.csv".format( host, port, basedir ) else: hd_fpath = f"hdfs://{basedir}/test_csv_writer.csv" ...
@pytest.mark.parametrize("test_url", [False, True]) def test_write_csv(pdf, hdfs, test_url):
gdf = cudf.from_pandas(pdf) if test_url: hd_fpath = "hdfs://{}:{}{}/test_csv_writer.csv".format( host, port, basedir ) else: hd_fpath = f"hdfs://{basedir}/test_csv_writer.csv" gdf.to_csv(hd_fpath, index=False) assert hdfs.exists(f"{basedir}/test_csv_writer.csv")...
# Read pandas from byte buffer with hdfs.open(basedir + "/test_csv_reader.csv") as f: expect = pd.read_csv(f) assert_eq(expect, got) @pytest.mark.parametrize("test_url", [False, True]) def test_write_csv(pdf, hdfs, test_url):
64
64
162
24
40
res-life/cudf
python/cudf/cudf/tests/test_hdfs.py
Python
test_write_csv
test_write_csv
76
91
76
77
eeafb281fef2abcf065b07149fad718ab8a078ca
bigcode/the-stack
train
c47a469bb773d382c8b40d35
train
function
@pytest.mark.parametrize("test_url", [False, True]) def test_write_orc(pdf, hdfs, test_url): # Orc writer doesn't support writing unsigned ints pdf["Integer2"] = pdf["Integer2"].astype("int64") gdf = cudf.from_pandas(pdf) if test_url: hd_fpath = "hdfs://{}:{}{}/test_orc_writer.orc".format( ...
@pytest.mark.parametrize("test_url", [False, True]) def test_write_orc(pdf, hdfs, test_url): # Orc writer doesn't support writing unsigned ints
pdf["Integer2"] = pdf["Integer2"].astype("int64") gdf = cudf.from_pandas(pdf) if test_url: hd_fpath = "hdfs://{}:{}{}/test_orc_writer.orc".format( host, port, basedir ) else: hd_fpath = f"hdfs://{basedir}/test_orc_writer.orc" gdf.to_orc(hd_fpath) assert hdfs...
c(hd_fpath) expect = orc.ORCFile(buffer).read().to_pandas() assert_eq(expect, got) @pytest.mark.parametrize("test_url", [False, True]) def test_write_orc(pdf, hdfs, test_url): # Orc writer doesn't support writing unsigned ints
64
64
198
35
29
res-life/cudf
python/cudf/cudf/tests/test_hdfs.py
Python
test_write_orc
test_write_orc
219
237
219
221
e80945894b95c7dc965dfa3c80c729bb3f67d020
bigcode/the-stack
train
a5264b989a29f9d1d4507f9a
train
function
@pytest.mark.parametrize("test_url", [False, True]) def test_read_csv(tmpdir, pdf, hdfs, test_url): fname = tmpdir.mkdir("csv").join("file.csv") # Write to local file system pdf.to_csv(fname) # Read from local file system as buffer with open(fname, mode="rb") as f: buffer = BytesIO(f.read())...
@pytest.mark.parametrize("test_url", [False, True]) def test_read_csv(tmpdir, pdf, hdfs, test_url):
fname = tmpdir.mkdir("csv").join("file.csv") # Write to local file system pdf.to_csv(fname) # Read from local file system as buffer with open(fname, mode="rb") as f: buffer = BytesIO(f.read()) # Write to hdfs hdfs.upload(basedir + "/test_csv_reader.csv", buffer) if test_url: ...
String"] = np.array(["Alpha", "Beta", "Gamma", "Delta"]) df["Boolean"] = np.array([True, False, True, False]) return df @pytest.mark.parametrize("test_url", [False, True]) def test_read_csv(tmpdir, pdf, hdfs, test_url):
65
65
217
27
37
res-life/cudf
python/cudf/cudf/tests/test_hdfs.py
Python
test_read_csv
test_read_csv
49
73
49
50
2a3d247c3797d91ce53b7f1a215b81a15c9e6df2
bigcode/the-stack
train
22574cc75faab05cbb8488c5
train
function
@pytest.mark.xfail( reason="Writing string columns with parition_cols is incorrect" ) @pytest.mark.parametrize("test_url", [False, True]) def test_write_parquet_partitioned(tmpdir, pdf, hdfs, test_url): pdf.to_parquet( path=tmpdir.join("pandas_parquet_writer_partitioned.parquet"), index=False, ...
@pytest.mark.xfail( reason="Writing string columns with parition_cols is incorrect" ) @pytest.mark.parametrize("test_url", [False, True]) def test_write_parquet_partitioned(tmpdir, pdf, hdfs, test_url):
pdf.to_parquet( path=tmpdir.join("pandas_parquet_writer_partitioned.parquet"), index=False, partition_cols=["Integer", "Boolean"], ) gdf = cudf.from_pandas(pdf) if test_url: hd_fpath = "hdfs://{}:{}{}/test_parquet_partitioned.parquet".format( host, port, based...
basedir}/test_parquet_writer.parquet", mode="rb") as f: got = pd.read_parquet(f) assert_eq(pdf, got) @pytest.mark.xfail( reason="Writing string columns with parition_cols is incorrect" ) @pytest.mark.parametrize("test_url", [False, True]) def test_write_parquet_partitioned(tmpdir, pdf, hdfs, test_url):...
82
82
276
49
33
res-life/cudf
python/cudf/cudf/tests/test_hdfs.py
Python
test_write_parquet_partitioned
test_write_parquet_partitioned
140
168
140
144
d320846be46855b5ec2c16997de3ae42e2e27313
bigcode/the-stack
train
a5ce277e9007947429fac5b3
train
class
class TextWriter(object): u'text in, text out' def __init__(self, response: Any): self.response = response def write_records(self, records: list[Any]): self.response.write(records)
class TextWriter(object):
u'text in, text out' def __init__(self, response: Any): self.response = response def write_records(self, records: list[Any]): self.response.write(records)
format( name=encode_rfc2231(name))) if bom: response.stream.write(BOM_UTF8) csv.writer( response.stream, dialect='excel-tab').writerow( f['id'] for f in fields) yield TextWriter(response.stream) class TextWriter(object):
64
64
48
5
59
robin-NEC/ckan
ckanext/datastore/writer.py
Python
TextWriter
TextWriter
72
78
72
72
280f38ef50700897cd5da388315401a1785f310f
bigcode/the-stack
train
c10627e0fe518b99c749921d
train
function
@contextmanager def json_writer(response: Any, fields: list[dict[str, Any]], name: Optional[str] = None, bom: bool = False): u'''Context manager for writing UTF-8 JSON data to response :param response: file-like or response-like object for writing data and headers (response-like objects...
@contextmanager def json_writer(response: Any, fields: list[dict[str, Any]], name: Optional[str] = None, bom: bool = False):
u'''Context manager for writing UTF-8 JSON data to response :param response: file-like or response-like object for writing data and headers (response-like objects only) :param fields: list of datastore fields :param name: file name (for headers, response-like objects only) :param bom: True ...
): u'text in, text out' def __init__(self, response: Any): self.response = response def write_records(self, records: list[Any]): self.response.write(records) @contextmanager def json_writer(response: Any, fields: list[dict[str, Any]], name: Optional[str] = None, bom: bool = ...
79
79
264
35
44
robin-NEC/ckan
ckanext/datastore/writer.py
Python
json_writer
json_writer
81
106
81
83
6d8f58b37956305aa241122111c4ca638c08e57d
bigcode/the-stack
train
e36ac6bebc983ab5e6438889
train
class
class JSONWriter(object): def __init__(self, response: Any): self.response = response self.first = True def write_records(self, records: list[Any]): for r in records: if self.first: self.first = False self.response.write(b'\n ') ...
class JSONWriter(object):
def __init__(self, response: Any): self.response = response self.first = True def write_records(self, records: list[Any]): for r in records: if self.first: self.first = False self.response.write(b'\n ') else: sel...
( six.ensure_binary(u'{\n "fields": %s,\n "records": [' % dumps( fields, ensure_ascii=False, separators=(u',', u':')))) yield JSONWriter(response.stream) response.stream.write(b'\n]}\n') class JSONWriter(object):
64
64
101
5
59
robin-NEC/ckan
ckanext/datastore/writer.py
Python
JSONWriter
JSONWriter
109
123
109
109
f4a3567c30ee331d3394e12e0e7cd2e24d3d2448
bigcode/the-stack
train
59d353e68543dd193e7e40c5
train
function
@contextmanager def xml_writer(response: Any, fields: list[dict[str, Any]], name: Optional[str] = None, bom: bool = False): u'''Context manager for writing UTF-8 XML data to response :param response: file-like or response-like object for writing data and headers (response-like objects on...
@contextmanager def xml_writer(response: Any, fields: list[dict[str, Any]], name: Optional[str] = None, bom: bool = False):
u'''Context manager for writing UTF-8 XML data to response :param response: file-like or response-like object for writing data and headers (response-like objects only) :param fields: list of datastore fields :param name: file name (for headers, response-like objects only) :param bom: True t...
else: self.response.write(b',\n ') self.response.write(dumps( r, ensure_ascii=False, separators=(u',', u':'))) @contextmanager def xml_writer(response: Any, fields: list[dict[str, Any]], name: Optional[str] = None, bom: bool = False):
70
71
239
35
35
robin-NEC/ckan
ckanext/datastore/writer.py
Python
xml_writer
xml_writer
126
149
126
128
975e67e5cf13ca831a5c4d43ca983c03e5503e79
bigcode/the-stack
train
e181b49bf1f993e969541056
train
class
class XMLWriter(object): _key_attr = u'key' _value_tag = u'value' def __init__(self, response: Any, columns: list[str]): self.response = response self.id_col = columns[0] == u'_id' if self.id_col: columns = columns[1:] self.columns = columns def _insert_node...
class XMLWriter(object):
_key_attr = u'key' _value_tag = u'value' def __init__(self, response: Any, columns: list[str]): self.response = response self.id_col = columns[0] == u'_id' if self.id_col: columns = columns[1:] self.columns = columns def _insert_node(self, root: Any, k: str,...
if name: response.headers['Content-disposition'] = ( u'attachment; filename="{name}.xml"'.format( name=encode_rfc2231(name))) if bom: response.stream.write(BOM_UTF8) response.stream.write(b'<data>\n') yield XMLWriter(response.stream, [f[u'id'] ...
93
93
311
5
88
robin-NEC/ckan
ckanext/datastore/writer.py
Python
XMLWriter
XMLWriter
152
189
152
152
55597bf64fc9cb2264ff77f39dc28514dc533988
bigcode/the-stack
train
09dc16e98beb488002dad2e4
train
function
@contextmanager def tsv_writer(response: Any, fields: list[dict[str, Any]], name: Optional[str] = None, bom: bool = False): u'''Context manager for writing UTF-8 TSV data to response :param response: file-like or response-like object for writing data and headers (response-like objects on...
@contextmanager def tsv_writer(response: Any, fields: list[dict[str, Any]], name: Optional[str] = None, bom: bool = False):
u'''Context manager for writing UTF-8 TSV data to response :param response: file-like or response-like object for writing data and headers (response-like objects only) :param fields: list of datastore fields :param name: file name (for headers, response-like objects only) :param bom: True t...
: response.stream.write(BOM_UTF8) csv.writer(response.stream).writerow( f['id'] for f in fields) yield TextWriter(response.stream) @contextmanager def tsv_writer(response: Any, fields: list[dict[str, Any]], name: Optional[str] = None, bom: bool = False):
72
72
240
36
36
robin-NEC/ckan
ckanext/datastore/writer.py
Python
tsv_writer
tsv_writer
43
69
43
45
ddb7e7873c867667b51fc365b4c71fcd661a3f65
bigcode/the-stack
train
995b1aa830e7981b9463c6fb
train
function
@contextmanager def csv_writer(response: Any, fields: list[dict[str, Any]], name: Optional[str] = None, bom: bool = False): u'''Context manager for writing UTF-8 CSV data to response :param response: file-like or response-like object for writing data and headers (response-like objects on...
@contextmanager def csv_writer(response: Any, fields: list[dict[str, Any]], name: Optional[str] = None, bom: bool = False):
u'''Context manager for writing UTF-8 CSV data to response :param response: file-like or response-like object for writing data and headers (response-like objects only) :param fields: list of datastore fields :param name: file name (for headers, response-like objects only) :param bom: True t...
json import dumps import six from xml.etree.cElementTree import Element, SubElement, ElementTree import csv from codecs import BOM_UTF8 @contextmanager def csv_writer(response: Any, fields: list[dict[str, Any]], name: Optional[str] = None, bom: bool = False):
68
68
227
35
32
robin-NEC/ckan
ckanext/datastore/writer.py
Python
csv_writer
csv_writer
17
40
17
19
2d7773bff2e3d25b21225c61dade24b0fd754733
bigcode/the-stack
train
f0f2de6d7da72a1d619ec9f8
train
class
class AllPlatformTests(BasePlatformTests): ''' Tests that should run on all platforms ''' def test_default_options_prefix(self): ''' Tests that setting a prefix in default_options in project() works. Can't be an ordinary test because we pass --prefix to meson there. https...
class AllPlatformTests(BasePlatformTests):
''' Tests that should run on all platforms ''' def test_default_options_prefix(self): ''' Tests that setting a prefix in default_options in project() works. Can't be an ordinary test because we pass --prefix to meson there. https://github.com/mesonbuild/meson/issues/1349 ...
Target(self, target): ret = self.build() if self.backend is Backend.ninja: self.assertIn('Linking target {}'.format(target), ret) elif self.backend is Backend.vs: # Ensure that this target was rebuilt clre = re.compile('ClCompile:\n [^\n]*cl[^\n]*' + target, f...
256
256
15,099
8
248
royb3/meson
run_unittests.py
Python
AllPlatformTests
AllPlatformTests
754
2,121
754
754
fb434467314558e0e1e1e394d33cb829f20d19b6
bigcode/the-stack
train
e4c89ea06fc696dada8e8ebf
train
class
class FailureTests(BasePlatformTests): ''' Tests that test failure conditions. Build files here should be dynamically generated and static tests should go into `test cases/failing*`. This is useful because there can be many ways in which a particular function can fail, and creating failing tests for...
class FailureTests(BasePlatformTests):
''' Tests that test failure conditions. Build files here should be dynamically generated and static tests should go into `test cases/failing*`. This is useful because there can be many ways in which a particular function can fail, and creating failing tests for all of them is tedious and slows d...
warning_level'].value, '3') self.wipe() # Mixing --option and -Doption is forbidden with self.assertRaises(subprocess.CalledProcessError) as e: self.init(testdir, extra_args=['--warnlevel=1', '-Dwarning_level=3']) self.assertNotEqual(0, e.returncode) self.ass...
256
256
2,252
7
249
royb3/meson
run_unittests.py
Python
FailureTests
FailureTests
2,124
2,328
2,124
2,124
2943d679a226c257ea1dd1e5dd72517fda8d83f4
bigcode/the-stack
train
283667387e7713de3c4de6d1
train
class
class InternalTests(unittest.TestCase): def test_version_number(self): searchfunc = mesonbuild.environment.search_version self.assertEqual(searchfunc('foobar 1.2.3'), '1.2.3') self.assertEqual(searchfunc('1.2.3'), '1.2.3') self.assertEqual(searchfunc('foobar 2016.10.28 1.2.3'), '1.2...
class InternalTests(unittest.TestCase):
def test_version_number(self): searchfunc = mesonbuild.environment.search_version self.assertEqual(searchfunc('foobar 1.2.3'), '1.2.3') self.assertEqual(searchfunc('1.2.3'), '1.2.3') self.assertEqual(searchfunc('foobar 2016.10.28 1.2.3'), '1.2.3') self.assertEqual(searchfunc(...
_tests import exe_suffix, get_fake_options from run_tests import get_builddir_target_args, get_backend_commands, Backend from run_tests import ensure_backend_detects_changes, run_configure, meson_exe from run_tests import should_run_linux_cross_tests def get_dynamic_section_entry(fname, entry): if is_cygwin() or ...
255
256
5,246
7
249
royb3/meson
run_unittests.py
Python
InternalTests
InternalTests
78
477
78
79
e5eb1609ad8918665231238a24150209ef335aed
bigcode/the-stack
train
61812b9f36429c1987fb699b
train
function
def unset_envs(): # For unit tests we must fully control all commend lines # so that there are no unexpected changes coming from the # environment, for example when doing a package build. varnames = ['CPPFLAGS', 'LDFLAGS'] + list(mesonbuild.environment.cflags_mapping.values()) for v in varnames: ...
def unset_envs(): # For unit tests we must fully control all commend lines # so that there are no unexpected changes coming from the # environment, for example when doing a package build.
varnames = ['CPPFLAGS', 'LDFLAGS'] + list(mesonbuild.environment.cflags_mapping.values()) for v in varnames: if v in os.environ: del os.environ[v]
.build')) self.assertEqual(s2, self.read_contents('sub2/meson.build')) def unset_envs(): # For unit tests we must fully control all commend lines # so that there are no unexpected changes coming from the # environment, for example when doing a package build.
63
64
88
43
20
royb3/meson
run_unittests.py
Python
unset_envs
unset_envs
3,253
3,260
3,253
3,256
048d65fb31835f402d68874587c0052327a104e7
bigcode/the-stack
train
072a37289e289d0d1a48e2af
train
class
class WindowsTests(BasePlatformTests): ''' Tests that should run on Cygwin, MinGW, and MSVC ''' def setUp(self): super().setUp() self.platform_test_dir = os.path.join(self.src_root, 'test cases/windows') def test_find_program(self): ''' Test that Windows-specific edg...
class WindowsTests(BasePlatformTests):
''' Tests that should run on Cygwin, MinGW, and MSVC ''' def setUp(self): super().setUp() self.platform_test_dir = os.path.join(self.src_root, 'test cases/windows') def test_find_program(self): ''' Test that Windows-specific edge-cases in find_program are functioning...
.assertRegex(out, r'Dependency.*somenotfounddep.*from subproject.*' 'subprojects.*somesubproj.*found:.*NO') self.assertRegex(out, r'Dependency.*zlibproxy.*from subproject.*' 'subprojects.*somesubproj.*found:.*YES.*(cached)') self.assertRegex(out, r'Also ...
210
210
701
7
203
royb3/meson
run_unittests.py
Python
WindowsTests
WindowsTests
2,331
2,389
2,331
2,331
c4e61e0f71982851d5ce4bd526add99112ac7a31
bigcode/the-stack
train
522009be901b203eb46daa69
train
class
class PythonTests(BasePlatformTests): ''' Tests that verify compilation of python extension modules ''' def test_versions(self): if self.backend is not Backend.ninja: raise unittest.SkipTest('Skipping python tests with {} backend'.format(self.backend.name)) testdir = os.path...
class PythonTests(BasePlatformTests):
''' Tests that verify compilation of python extension modules ''' def test_versions(self): if self.backend is not Backend.ninja: raise unittest.SkipTest('Skipping python tests with {} backend'.format(self.backend.name)) testdir = os.path.join(self.src_root, 'test cases', 'py...
3049 https://github.com/mesonbuild/meson/issues/3089 ''' testdir = os.path.join(self.unit_test_dir, '29 cross file overrides always args') self.meson_cross_file = os.path.join(testdir, 'ubuntu-armhf-overrides.txt') self.init(testdir) compdb = self.get_compdb() sel...
114
114
383
7
107
royb3/meson
run_unittests.py
Python
PythonTests
PythonTests
3,143
3,187
3,143
3,143
e736e7f2575c5c6a1414556b12d8bbbed1e865c9
bigcode/the-stack
train
0aab798483fd2f5f5e902a15
train
class
class RewriterTests(unittest.TestCase): def setUp(self): super().setUp() src_root = os.path.dirname(__file__) self.testroot = os.path.realpath(tempfile.mkdtemp()) self.rewrite_command = python_command + [os.path.join(src_root, 'mesonrewriter.py')] self.tmpdir = os.path.realp...
class RewriterTests(unittest.TestCase):
def setUp(self): super().setUp() src_root = os.path.dirname(__file__) self.testroot = os.path.realpath(tempfile.mkdtemp()) self.rewrite_command = python_command + [os.path.join(src_root, 'mesonrewriter.py')] self.tmpdir = os.path.realpath(tempfile.mkdtemp()) self.work...
will raise MESON_SKIP_TEST, we could check beforehand what version # of python is available, but it's a bit of a chicken and egg situation, # as that is the job of the module, so we just ask for forgiveness rather # than permission. pass self.wipe() # T...
173
173
577
8
165
royb3/meson
run_unittests.py
Python
RewriterTests
RewriterTests
3,190
3,250
3,190
3,191
7ef8b8d27982ccf8e12069dda33484ec1c7431f4
bigcode/the-stack
train
0b5ca6053dfe7211ab2564ba
train
function
def get_dynamic_section_entry(fname, entry): if is_cygwin() or is_osx(): raise unittest.SkipTest('Test only applicable to ELF platforms') try: raw_out = subprocess.check_output(['readelf', '-d', fname], universal_newlines=True) except FileNotFou...
def get_dynamic_section_entry(fname, entry):
if is_cygwin() or is_osx(): raise unittest.SkipTest('Test only applicable to ELF platforms') try: raw_out = subprocess.check_output(['readelf', '-d', fname], universal_newlines=True) except FileNotFoundError: # FIXME: Try using depfixer....
run_tests import exe_suffix, get_fake_options from run_tests import get_builddir_target_args, get_backend_commands, Backend from run_tests import ensure_backend_detects_changes, run_configure, meson_exe from run_tests import should_run_linux_cross_tests def get_dynamic_section_entry(fname, entry):
64
64
152
9
54
royb3/meson
run_unittests.py
Python
get_dynamic_section_entry
get_dynamic_section_entry
53
68
53
53
b9b421cf4393bdf366371bbffa7b4abe1b6770ee
bigcode/the-stack
train
439e97e5776be27f1eebc537
train
function
def get_rpath(fname): return get_dynamic_section_entry(fname, r'(?:rpath|runpath)')
def get_rpath(fname):
return get_dynamic_section_entry(fname, r'(?:rpath|runpath)')
_out.split('\n'): m = pattern.search(line) if m is not None: return m.group(1) return None # The file did not contain the specified entry. def get_soname(fname): return get_dynamic_section_entry(fname, 'soname') def get_rpath(fname):
64
64
23
6
58
royb3/meson
run_unittests.py
Python
get_rpath
get_rpath
74
75
74
74
1f8d62d59073eff5affa285ec2c2007fb011c16a
bigcode/the-stack
train
701aabc839a525d627ffc533
train
class
class BasePlatformTests(unittest.TestCase): def setUp(self): super().setUp() src_root = os.path.dirname(__file__) src_root = os.path.join(os.getcwd(), src_root) self.src_root = src_root self.prefix = '/usr' self.libdir = os.path.join(self.prefix, 'lib') # Get ...
class BasePlatformTests(unittest.TestCase):
def setUp(self): super().setUp() src_root = os.path.dirname(__file__) src_root = os.path.join(os.getcwd(), src_root) self.src_root = src_root self.prefix = '/usr' self.libdir = os.path.join(self.prefix, 'lib') # Get the backend # FIXME: Extract this fr...
'.md': with f.open() as snippet: for line in snippet: m = re.match(hashcounter, line) if m: self.assertEqual(len(m.group(0)), 2, 'All headings in snippets must have two hash symbols: ' + f.name) ...
256
256
2,687
8
248
royb3/meson
run_unittests.py
Python
BasePlatformTests
BasePlatformTests
480
751
480
480
88eb0064b01beb155cba53efe4851a855ab3ef30
bigcode/the-stack
train
b165f69705f44a87f265607f
train
class
class LinuxlikeTests(BasePlatformTests): ''' Tests that should run on Linux and *BSD ''' def test_basic_soname(self): ''' Test that the soname is set correctly for shared libraries. This can't be an ordinary test case because we need to run `readelf` and actually check th...
class LinuxlikeTests(BasePlatformTests):
''' Tests that should run on Linux and *BSD ''' def test_basic_soname(self): ''' Test that the soname is set correctly for shared libraries. This can't be an ordinary test case because we need to run `readelf` and actually check the soname. https://github.com/meso...
adds the interpreter prog = ExternalProgram('test-script-ext.py') self.assertTrue(prog.found(), msg='test-script-ext.py not found in PATH') self.assertPathEqual(prog.get_command()[0], python_command[0]) self.assertPathBasenameEqual(prog.get_path(), 'test-script-ext.py') def test_ig...
255
256
7,800
8
247
royb3/meson
run_unittests.py
Python
LinuxlikeTests
LinuxlikeTests
2,392
3,103
2,392
2,392
d45cb9b608661e2b612236f9bae2f78c992ebbab
bigcode/the-stack
train
e70100416e5533fdb677dd03
train
class
class LinuxArmCrossCompileTests(BasePlatformTests): ''' Tests that verify cross-compilation to Linux/ARM ''' def setUp(self): super().setUp() src_root = os.path.dirname(__file__) self.meson_cross_file = os.path.join(src_root, 'cross', 'ubuntu-armhf.txt') def test_cflags_cros...
class LinuxArmCrossCompileTests(BasePlatformTests):
''' Tests that verify cross-compilation to Linux/ARM ''' def setUp(self): super().setUp() src_root = os.path.dirname(__file__) self.meson_cross_file = os.path.join(src_root, 'cross', 'ubuntu-armhf.txt') def test_cflags_cross_environment_pollution(self): ''' T...
, extra_args=['--prefix=' + tempdirname, '--libdir=lib', '--default-library=static'], default_args=False) self.build() self.install(use_destdir=False) # build user of library pkg_...
109
109
365
10
99
royb3/meson
run_unittests.py
Python
LinuxArmCrossCompileTests
LinuxArmCrossCompileTests
3,106
3,140
3,106
3,106
00e18efdfaffb03f1b27d2d56425486aee91ec9a
bigcode/the-stack
train
d16c26cf6bdcc556f92360e5
train
function
def get_soname(fname): return get_dynamic_section_entry(fname, 'soname')
def get_soname(fname):
return get_dynamic_section_entry(fname, 'soname')
pattern = re.compile(entry + r': \[(.*?)\]') for line in raw_out.split('\n'): m = pattern.search(line) if m is not None: return m.group(1) return None # The file did not contain the specified entry. def get_soname(fname):
64
64
19
7
57
royb3/meson
run_unittests.py
Python
get_soname
get_soname
70
71
70
70
cb89275bdd33aae52396445e7d0f0fa9bd0ad750
bigcode/the-stack
train
bc44cee3b30775a1b858d4f1
train
class
class XController2(XController_b00e0b8f): """ extends the XController interface **since** OOo 3.0 See Also: `API XController2 <https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1frame_1_1XController2.html>`_ """ __ooo_ns__: str = 'com.sun.star.fram...
class XController2(XController_b00e0b8f):
""" extends the XController interface **since** OOo 3.0 See Also: `API XController2 <https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1frame_1_1XController2.html>`_ """ __ooo_ns__: str = 'com.sun.star.frame' __ooo_full_ns__: str = 'com.sun.sta...
7.3 # Namespace: com.sun.star.frame import typing from abc import abstractmethod, abstractproperty from .x_controller import XController as XController_b00e0b8f if typing.TYPE_CHECKING: from ..awt.x_window import XWindow as XWindow_713b0924 from ..beans.property_value import PropertyValue as PropertyValue_c961...
122
122
409
14
107
Amourspirit/ooo_uno_tmpl
ooobuild/lo/frame/x_controller2.py
Python
XController2
XController2
29
76
29
29
87db67c7032cd3e98656a97bf30d1ba6ed64029b
bigcode/the-stack
train
ecd397ad78b3b7ab72cebd89
train
function
def parse_string(s): assert s[0] == '"' assert s[-1] == '"' return s[1:-1]
def parse_string(s):
assert s[0] == '"' assert s[-1] == '"' return s[1:-1]
the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test RPC help output.""" from test_framework.test_framework import BitcoinTestFramework from test_framework.util import assert_equal, assert_raises_rpc_error from collections import defaultdict import os import re def parse_str...
64
64
31
5
58
crptec/sinovate
test/functional/rpc_help.py
Python
parse_string
parse_string
15
18
15
15
8520934045ad8c5ccd406475cb66b20b7919cd1a
bigcode/the-stack
train
3458aaafadc1c134183dd356
train
function
def process_mapping(fname): """Find and parse conversion table in implementation file `fname`.""" cmds = [] in_rpcs = False with open(fname, "r", encoding="utf8") as f: for line in f: line = line.rstrip() if not in_rpcs: if line == 'static const CRPCConver...
def process_mapping(fname):
"""Find and parse conversion table in implementation file `fname`.""" cmds = [] in_rpcs = False with open(fname, "r", encoding="utf8") as f: for line in f: line = line.rstrip() if not in_rpcs: if line == 'static const CRPCConvertParam vRPCConvertParams[] =...
import BitcoinTestFramework from test_framework.util import assert_equal, assert_raises_rpc_error from collections import defaultdict import os import re def parse_string(s): assert s[0] == '"' assert s[-1] == '"' return s[1:-1] def process_mapping(fname):
66
66
221
5
61
crptec/sinovate
test/functional/rpc_help.py
Python
process_mapping
process_mapping
21
42
21
21
4e3c8f6a98087588f61afcd07b9cf3b0f84c7034
bigcode/the-stack
train
76cd08819866a8b09ccce61b
train
class
class HelpRpcTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 1 self.supports_cli = False def run_test(self): self.test_client_conversion_table() self.test_categories() self.dump_help() if self.is_wallet_compiled(): self.wallet_...
class HelpRpcTest(BitcoinTestFramework):
def set_test_params(self): self.num_nodes = 1 self.supports_cli = False def run_test(self): self.test_client_conversion_table() self.test_categories() self.dump_help() if self.is_wallet_compiled(): self.wallet_help() def test_client_conversion_ta...
[0] == '"' assert s[-1] == '"' return s[1:-1] def process_mapping(fname): """Find and parse conversion table in implementation file `fname`.""" cmds = [] in_rpcs = False with open(fname, "r", encoding="utf8") as f: for line in f: line = line.rstrip() if not in_r...
253
253
846
9
243
crptec/sinovate
test/functional/rpc_help.py
Python
HelpRpcTest
HelpRpcTest
45
128
45
45
75d384dd001fe64b33b5f111e8fb134a3c418e7a
bigcode/the-stack
train
8491baeea54527b3f8e310af
train
class
class NoticeTester(unittest.TestCase): def setUp(self): self._ResetCounters() def _ResetCounters(self): self._changeCount = 0 self._contentsCount = 0 self._objectsCount = 0 self._editTargetsCount = 0 def OnStageContentsChanged(self, *args): self._changeCount...
class NoticeTester(unittest.TestCase):
def setUp(self): self._ResetCounters() def _ResetCounters(self): self._changeCount = 0 self._contentsCount = 0 self._objectsCount = 0 self._editTargetsCount = 0 def OnStageContentsChanged(self, *args): self._changeCount += 1 self._contentsCount += 1 ...
0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # # 6. Trademarks. This License does not grant permission to use the trade # names, tradema...
256
256
1,940
7
249
dalgos-adsk/USD
pxr/usd/lib/usd/testenv/testUsdNotices.py
Python
NoticeTester
NoticeTester
30
230
30
30
3e569fb4eb814bc833f8e7136ff6dd193ac4a5b6
bigcode/the-stack
train
1f9f414ede73c8a1b3e3fd1b
train
function
def parse_direct_mention(message_text): """ Finds a direct mention (a mention that is at the beginning) in message text and returns the user ID which was mentioned. If there is no direct mention returns None """ matches = re.search(MENTION_REGEX, message_text) # the first group contains the ...
def parse_direct_mention(message_text):
""" Finds a direct mention (a mention that is at the beginning) in message text and returns the user ID which was mentioned. If there is no direct mention returns None """ matches = re.search(MENTION_REGEX, message_text) # the first group contains the username, # the second group contai...
event["channel"], text="test % s" % global_var["hello"] ) user_id, message = parse_direct_mention(event["text"]) if user_id == starterbot_id: return message, event["channel"] return None, None def parse_direct_mention(message_text):
64
64
106
8
55
rhsu/slackjack
starterbot.py
Python
parse_direct_mention
parse_direct_mention
94
103
94
94
cf775dcf2a3a87735e483055487bd31e76544216
bigcode/the-stack
train
e254f5c6de73922949c9d8d1
train
function
def parse_bot_commands(slack_events): """ Parses a list of events coming from the Slack RTM API to find bot commands. If a bot command is found, this function returns a tuple of command and channel. If its not found, then this function returns None, None. """ for event in slack_events: ...
def parse_bot_commands(slack_events):
""" Parses a list of events coming from the Slack RTM API to find bot commands. If a bot command is found, this function returns a tuple of command and channel. If its not found, then this function returns None, None. """ for event in slack_events: if event["type"] == "message" and "...
import logging from dotenv import load_dotenv # load .env variables load_dotenv() # sets default logging logging.basicConfig() # instantiate Slack client slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN')) # starterbot's user ID in Slack: value is assigned after the bot starts up starterbot_id = None # co...
141
141
470
8
133
rhsu/slackjack
starterbot.py
Python
parse_bot_commands
parse_bot_commands
29
91
29
29
f0aa9a0019f5239e9176789516287c9079500069
bigcode/the-stack
train
0eaf27274cd43ebb015f8194
train
function
def handle_command(command, channel): """ Executes bot command if the command is known """ # Default response is help text for the user default_response = "Not sure what you mean. Try *{}*.".format(EXAMPLE_COMMAND) # Finds and executes the given command, filling in response response = None ...
def handle_command(command, channel):
""" Executes bot command if the command is known """ # Default response is help text for the user default_response = "Not sure what you mean. Try *{}*.".format(EXAMPLE_COMMAND) # Finds and executes the given command, filling in response response = None # This is where you start to imple...
""" matches = re.search(MENTION_REGEX, message_text) # the first group contains the username, # the second group contains the remaining message return (matches.group(1), matches.group(2).strip()) if matches else (None, None) def handle_command(command, channel):
64
64
143
7
57
rhsu/slackjack
starterbot.py
Python
handle_command
handle_command
106
124
106
106
a8a3bc2c8164f2b428974f04cf2f0c26b33b56e9
bigcode/the-stack
train
81c5500c275039d128515dee
train
function
def test_add_semicolon_spaces(): for input, expected in [ ("foo;bar;baz", "foo; bar; baz"), ("123;456;789;", "123; 456; 789;"), ("foo; bar;baz", "foo; bar; baz"), ("foo1;bar2;3baz", "foo1; bar2; 3baz")]: assert add_semicolon_spaces(input) == expected
def test_add_semicolon_spaces():
for input, expected in [ ("foo;bar;baz", "foo; bar; baz"), ("123;456;789;", "123; 456; 789;"), ("foo; bar;baz", "foo; bar; baz"), ("foo1;bar2;3baz", "foo1; bar2; 3baz")]: assert add_semicolon_spaces(input) == expected
from ford_grants_notes import add_semicolon_spaces, handle_fap_title, to_sentence_case def test_add_semicolon_spaces():
27
64
96
7
19
RockefellerArchiveCenter/scripts
archivessnake/ford_grants_test.py
Python
test_add_semicolon_spaces
test_add_semicolon_spaces
3
9
3
3
d13c35f89f63cf76a1613c8c361def05bd56750e
bigcode/the-stack
train
bbe054401329981dc8fb44a8
train
function
def test_handle_fap_title(): for input, expected in [ ("Foundation-Administered Project (FAP) (06390191): TRAINING PROGRAM FOR ASSOCIATES IN OVERSEAS DEVELOPMENT IN LATIN AMERICA AND THE CARIBBEAN", "Foundation-Administered Project (FAP) (06390191): Training Program For Associates In Overse...
def test_handle_fap_title():
for input, expected in [ ("Foundation-Administered Project (FAP) (06390191): TRAINING PROGRAM FOR ASSOCIATES IN OVERSEAS DEVELOPMENT IN LATIN AMERICA AND THE CARIBBEAN", "Foundation-Administered Project (FAP) (06390191): Training Program For Associates In Overseas Development In Latin Ameri...
DID NOT KNOW THE ANSWER; IT WAS ALL TOO CLEAR.", "I did not know the answer; it was all too clear."), ("IT WAS DARK. And stormy.", "It was dark. And stormy.")]: assert to_sentence_case(input) == expected def test_handle_fap_title():
64
64
172
7
56
RockefellerArchiveCenter/scripts
archivessnake/ford_grants_test.py
Python
test_handle_fap_title
test_handle_fap_title
20
27
20
20
9f556cc2a7847c98937e6edce36385477b23a2e5
bigcode/the-stack
train
45eee604965d75289fe08f9b
train
function
def test_to_sentence_case(): for input, expected in [ ("THIS IS A STRING.", "This is a string."), ("TRY THIS. AND THIS.", "Try this. And this."), ("I DID NOT KNOW THE ANSWER; IT WAS ALL TOO CLEAR.", "I did not know the answer; it was all too clear."), ("IT WAS DARK. A...
def test_to_sentence_case():
for input, expected in [ ("THIS IS A STRING.", "This is a string."), ("TRY THIS. AND THIS.", "Try this. And this."), ("I DID NOT KNOW THE ANSWER; IT WAS ALL TOO CLEAR.", "I did not know the answer; it was all too clear."), ("IT WAS DARK. And stormy.", "It was dark. An...
123; 456; 789;"), ("foo; bar;baz", "foo; bar; baz"), ("foo1;bar2;3baz", "foo1; bar2; 3baz")]: assert add_semicolon_spaces(input) == expected def test_to_sentence_case():
64
64
101
6
57
RockefellerArchiveCenter/scripts
archivessnake/ford_grants_test.py
Python
test_to_sentence_case
test_to_sentence_case
11
17
11
11
7a7c23c499f632aeea849499b419bfdf8e305723
bigcode/the-stack
train
dc666fdc14ff0c165db3d5fa
train
class
class SpyLog(list): def getLast(self, method: SpyableMethod, required: bool = False) -> \ Optional[Entry]: entry = None # type: Optional[Entry] if callable(method): method = method.__name__ try: entry = next(x for x in reversed(self) if x.method == method...
class SpyLog(list):
def getLast(self, method: SpyableMethod, required: bool = False) -> \ Optional[Entry]: entry = None # type: Optional[Entry] if callable(method): method = method.__name__ try: entry = next(x for x in reversed(self) if x.method == method) except Sto...
ImportError: pass from plenum.common.util import objSearchReplace from stp_core.common.log import getlogger logger = getlogger() Entry = NamedTuple('Entry', [('starttime', float), ('endtime', float), ('method', str), ('params...
93
93
310
5
88
andkononykhin/plenum
plenum/test/testable.py
Python
SpyLog
SpyLog
29
62
29
29
6ff996ebd5d1fd967b7321b7fb9edb28e2cfd4c8
bigcode/the-stack
train
db6565cc15631e48ae2094ef
train
function
def spy(func, is_init, should_spy, spy_log=None): sig = inspect.signature(func) # sets up spylog, but doesn't spy on init def init_only(self, *args, **kwargs): self.spylog = SpyLog() return func(self, *args, **kwargs) init_only.__name__ = func.__name__ # sets up spylog, and also s...
def spy(func, is_init, should_spy, spy_log=None):
sig = inspect.signature(func) # sets up spylog, but doesn't spy on init def init_only(self, *args, **kwargs): self.spylog = SpyLog() return func(self, *args, **kwargs) init_only.__name__ = func.__name__ # sets up spylog, and also spys on init def init_wrap(self, *args, **kwarg...
def getLastResult(self, method: str, required: bool = True) -> Tuple: last = self.getLast(method, required) return last.result if last is not None else None def count(self, method: SpyableMethod) -> int: if callable(method): method = method.__name__ return sum(1 for ...
98
98
327
15
83
andkononykhin/plenum
plenum/test/testable.py
Python
spy
spy
65
107
65
65
d660dea69322ba35d98fde8a3ce10fc47ed399e8
bigcode/the-stack
train
e16c6d2e6a5fc5c4ee1455d1
train
function
def spyable(name: str = None, methods: SpyableMethods = None, deep_level: int = None): def decorator(clas): if 'NO_SPIES' in globals() and globals()['NO_SPIES']: # Since spylog consumes resources, benchmarking tests need to be # able to not have spyables, so they set a m...
def spyable(name: str = None, methods: SpyableMethods = None, deep_level: int = None):
def decorator(clas): if 'NO_SPIES' in globals() and globals()['NO_SPIES']: # Since spylog consumes resources, benchmarking tests need to be # able to not have spyables, so they set a module global `NO_SPIES`, # it's their responsibility to unset it logger.in...
.warning("{}".format(traceback.format_exc())) raise finally: bound = sig.bind(self, *args, **kwargs) params = dict(bound.arguments) params.pop('self', None) used_log = self.spylog if hasattr(self, 'spylog') else spy_log used_log.append(Entr...
134
134
448
25
108
andkononykhin/plenum
plenum/test/testable.py
Python
spyable
spyable
110
158
110
111
265e3b9c8129c3e6219049aa799279b7a125a51d
bigcode/the-stack
train
2e94138e409b74463b1500e8
train
class
class SAC(Base_Agent): """Soft Actor-Critic model based on the 2018 paper https://arxiv.org/abs/1812.05905 and on this github implementation https://github.com/pranz24/pytorch-soft-actor-critic. It is an actor-critic algorithm where the agent is also trained to maximise the entropy of their actions as w...
class SAC(Base_Agent):
"""Soft Actor-Critic model based on the 2018 paper https://arxiv.org/abs/1812.05905 and on this github implementation https://github.com/pranz24/pytorch-soft-actor-critic. It is an actor-critic algorithm where the agent is also trained to maximise the entropy of their actions as well as their cumulative...
from CybORG.Agents.ComplexAgents.Base_Agent import Base_Agent from CybORG.Agents.ComplexAgents.utilities.OU_Noise import OU_Noise from CybORG.Agents.ComplexAgents.utilities.data_structures.Replay_Buffer import Replay_Buffer from torch.optim import Adam import torch import torch.nn.functional as F from torch.distributio...
131
256
2,794
6
124
rafvasq/cage-challenge-1
CybORG/CybORG/Agents/ComplexAgents/actor_critic_agents/SAC.py
Python
SAC
SAC
15
211
15
15
47f854ac946d3f461bf82e7795f773384e669832
bigcode/the-stack
train
4749b5f512b5fd979a8cb6a2
train
function
def load_img(path): filename_code = ntpath.basename(path).split('.')[0] im = cv2.imread(path, cv2.IMREAD_GRAYSCALE) im = cv2.bitwise_not(im) return im, to_categorical([int(c) for c in filename_code], 10)
def load_img(path):
filename_code = ntpath.basename(path).split('.')[0] im = cv2.imread(path, cv2.IMREAD_GRAYSCALE) im = cv2.bitwise_not(im) return im, to_categorical([int(c) for c in filename_code], 10)
import glob import ntpath from random import sample import cv2 import numpy as np from keras.utils.np_utils import to_categorical def load_img(path):
37
64
64
5
31
malavv/aixperience
load.py
Python
load_img
load_img
10
14
10
10
5500936caf974e88551467c859b51c564f126794
bigcode/the-stack
train
bae0485330c7e7d5afe3b135
train
function
def downsize(img, w, h): return cv2.resize(img, (w, h), interpolation=cv2.INTER_AREA)
def downsize(img, w, h):
return cv2.resize(img, (w, h), interpolation=cv2.INTER_AREA)
) x, y, w, h = cv2.boundingRect(coords) # Find minimum spanning bounding box rect = img[y:y+h, x:x+w] # Crop the image - note we do this on the original image return rect def downsize(img, w, h):
64
64
27
9
54
malavv/aixperience
load.py
Python
downsize
downsize
59
60
59
59
4f1d5f2766c3decf1ec99bd00d76e6344814d361
bigcode/the-stack
train
63e25e23d1de76efc4451d28
train
function
def generator(folder, batch_size=32): all_files = glob.glob(folder + '*.png') while True: # Loop forever so the generator never terminates images = [] labels = [] for batch_sample in range(batch_size): filename = sample(all_files, 1)[0] img, label = load_img(fil...
def generator(folder, batch_size=32):
all_files = glob.glob(folder + '*.png') while True: # Loop forever so the generator never terminates images = [] labels = [] for batch_sample in range(batch_size): filename = sample(all_files, 1)[0] img, label = load_img(filename) images.append(img)...
.np_utils import to_categorical def load_img(path): filename_code = ntpath.basename(path).split('.')[0] im = cv2.imread(path, cv2.IMREAD_GRAYSCALE) im = cv2.bitwise_not(im) return im, to_categorical([int(c) for c in filename_code], 10) def generator(folder, batch_size=32):
81
81
270
9
72
malavv/aixperience
load.py
Python
generator
generator
17
46
17
17
0b7124aa3a515186efb6fe8efd83339b798738ee
bigcode/the-stack
train
bf3f14375ab0a4c394c9c692
train
function
def crop(img): # https://stackoverflow.com/questions/49907382/how-to-remove-whitespace-from-an-image-in-opencv gray = 255 * (img < 128).astype(np.uint8) # To invert the text to white coords = cv2.findNonZero(gray) # Find all non-zero points (text) x, y, w, h = cv2.boundingRect(coords) # Find minimum ...
def crop(img): # https://stackoverflow.com/questions/49907382/how-to-remove-whitespace-from-an-image-in-opencv
gray = 255 * (img < 128).astype(np.uint8) # To invert the text to white coords = cv2.findNonZero(gray) # Find all non-zero points (text) x, y, w, h = cv2.boundingRect(coords) # Find minimum spanning bounding box rect = img[y:y+h, x:x+w] # Crop the image - note we do this on the original image re...
yield x_train, [y1, y2, y3, y4, y5, y6, y7, y8] # Assume black text with white background def crop(img): # https://stackoverflow.com/questions/49907382/how-to-remove-whitespace-from-an-image-in-opencv
64
64
127
27
36
malavv/aixperience
load.py
Python
crop
crop
50
56
50
51
96a2394efba1a06bd6271b05ff6f968b18fef91c
bigcode/the-stack
train
adfc3be9c08e228f4efe4b50
train
function
@experimental("1.3.0") def get_param_importances( study: Study, evaluator: BaseImportanceEvaluator = None, params: Optional[List[str]] = None ) -> Dict[str, float]: """Evaluate parameter importances based on completed trials in the given study. The parameter importances are returned as a dictionary where t...
@experimental("1.3.0") def get_param_importances( study: Study, evaluator: BaseImportanceEvaluator = None, params: Optional[List[str]] = None ) -> Dict[str, float]:
"""Evaluate parameter importances based on completed trials in the given study. The parameter importances are returned as a dictionary where the keys consist of parameter names and their values importances. The importances are represented by floating point numbers that sum to 1.0 over the entire di...
from typing import Dict from typing import List from typing import Optional from optuna._experimental import experimental from optuna.importance._base import BaseImportanceEvaluator from optuna.importance._fanova import FanovaImportanceEvaluator from optuna.study import Study @experimental("1.3.0") def get_param_impor...
100
135
453
44
55
gorogoroumaru/optuna
optuna/importance/__init__.py
Python
get_param_importances
get_param_importances
11
61
11
14
6b1f18f1ed5c43a71e064c9edb5e0b1f275656af
bigcode/the-stack
train
bb253ec37b20b1f4d56db267
train
class
class AdminSiteTests(TestCase): def setUp(self): self.client = Client() self.admin_user = get_user_model().objects.create_superuser( email="admin@admin.com", password="password123" ) self.client.force_login(self.admin_user) self.user = get_user_model().objects.cre...
class AdminSiteTests(TestCase):
def setUp(self): self.client = Client() self.admin_user = get_user_model().objects.create_superuser( email="admin@admin.com", password="password123" ) self.client.force_login(self.admin_user) self.user = get_user_model().objects.create_user( email="tes...
from django.test import TestCase, Client from django.contrib.auth import get_user_model from django.urls import reverse class AdminSiteTests(TestCase):
31
75
250
7
23
PeterBrick/recipe-app-api
app/core/tests/test_admin.py
Python
AdminSiteTests
AdminSiteTests
6
37
6
6
20c1b80eef5babdb84a3a4f416d16d2e9c4cb89f
bigcode/the-stack
train
b233d244dce3f53f612fa07b
train
class
class CandidateInlineAdmin(admin.TabularInline): model = Candidate
class CandidateInlineAdmin(admin.TabularInline):
model = Candidate
only_fields(request, obj) if obj: fields.append('type') return fields def get_fieldsets(self, request, obj=None): if obj: return self.inperson_change_fieldsets else: return self.add_fieldsets class CandidateInlineAdmin(admin.TabularInline):
64
64
14
9
54
SmartElect/SmartElect
voting/admin.py
Python
CandidateInlineAdmin
CandidateInlineAdmin
50
51
50
50
190cc76fd225a1624e8198d3a5d8087daf18bb19
bigcode/the-stack
train
b5b53433cb1c7a074ff4d5e0
train
class
class BallotAdmin(LibyaAdminModel): inlines = [CandidateInlineAdmin] list_display = ['election', 'internal_ballot_number', 'get_subconstituencies', 'name', 'ballot_number'] list_display_links = ['internal_ballot_number'] list_filter = ['electio...
class BallotAdmin(LibyaAdminModel):
inlines = [CandidateInlineAdmin] list_display = ['election', 'internal_ballot_number', 'get_subconstituencies', 'name', 'ballot_number'] list_display_links = ['internal_ballot_number'] list_filter = ['election'] def get_subconstituencies(s...
') return fields def get_fieldsets(self, request, obj=None): if obj: return self.inperson_change_fieldsets else: return self.add_fieldsets class CandidateInlineAdmin(admin.TabularInline): model = Candidate class BallotAdmin(LibyaAdminModel):
64
64
107
10
53
SmartElect/SmartElect
voting/admin.py
Python
BallotAdmin
BallotAdmin
54
65
54
54
5192e5f38d9fbcc0133c98946d0b160e027fc3d4
bigcode/the-stack
train
ea28b8c6eb9d3bb998b3b1f4
train
class
class BallotInlineAdmin(admin.TabularInline): model = Ballot
class BallotInlineAdmin(admin.TabularInline):
model = Ballot
from django.contrib import admin from django.utils.timezone import now from libya_elections.admin_models import LibyaAdminModel from libya_elections.admin_site import admin_site from voting.models import Election, Ballot, Candidate, RegistrationPeriod class BallotInlineAdmin(admin.TabularInline):
61
64
16
10
50
SmartElect/SmartElect
voting/admin.py
Python
BallotInlineAdmin
BallotInlineAdmin
9
10
9
9
8682e5a124be01070c96ea126fb5032cd2f0c535
bigcode/the-stack
train
11036b9a44b0645eb3e1d37b
train
class
class RegistrationPeriodAdmin(LibyaAdminModel): list_display = ['start_time', 'end_time'] def get_readonly_fields(self, request, obj=None): """Don't allow editing start or end times that have passed""" fields = set(super(RegistrationPeriodAdmin, self).get_readonly_fields(request, obj)) ...
class RegistrationPeriodAdmin(LibyaAdminModel):
list_display = ['start_time', 'end_time'] def get_readonly_fields(self, request, obj=None): """Don't allow editing start or end times that have passed""" fields = set(super(RegistrationPeriodAdmin, self).get_readonly_fields(request, obj)) if obj: right_now = now() ...
list_display = ['election', 'ballot', 'candidate_number', 'name_arabic', 'name_english'] list_display_links = ['candidate_number', 'name_arabic', 'name_english'] list_filter = ['ballot'] class RegistrationPeriodAdmin(LibyaAdminModel):
64
64
115
10
54
SmartElect/SmartElect
voting/admin.py
Python
RegistrationPeriodAdmin
RegistrationPeriodAdmin
74
86
74
74
bbb31c0b498a4bde3ae5a610d8be7a6872f823ea
bigcode/the-stack
train
cd89d4547a7172928a4a2c3f
train
class
class ElectionAdmin(LibyaAdminModel): fieldsets = ( (None, { 'fields': ['name_arabic', 'name_english', 'start_time', 'end_time', 'polling_start_time', 'polling_end_time', ], }), ) inperson_change_fieldsets = ( ...
class ElectionAdmin(LibyaAdminModel):
fieldsets = ( (None, { 'fields': ['name_arabic', 'name_english', 'start_time', 'end_time', 'polling_start_time', 'polling_end_time', ], }), ) inperson_change_fieldsets = ( (None, { 'fields': ...
from django.contrib import admin from django.utils.timezone import now from libya_elections.admin_models import LibyaAdminModel from libya_elections.admin_site import admin_site from voting.models import Election, Ballot, Candidate, RegistrationPeriod class BallotInlineAdmin(admin.TabularInline): model = Ballot ...
76
82
274
9
66
SmartElect/SmartElect
voting/admin.py
Python
ElectionAdmin
ElectionAdmin
13
47
13
13
e39b80bffb52baacd583d24b02a45d52a28cacb2
bigcode/the-stack
train
303e377558d23d90cc71638f
train
class
class CandidateAdmin(LibyaAdminModel): list_display = ['election', 'ballot', 'candidate_number', 'name_arabic', 'name_english'] list_display_links = ['candidate_number', 'name_arabic', 'name_english'] list_filter = ['ballot']
class CandidateAdmin(LibyaAdminModel):
list_display = ['election', 'ballot', 'candidate_number', 'name_arabic', 'name_english'] list_display_links = ['candidate_number', 'name_arabic', 'name_english'] list_filter = ['ballot']
list_display_links = ['internal_ballot_number'] list_filter = ['election'] def get_subconstituencies(self, obj): return obj.subconstituency_ids_formatted get_subconstituencies.short_description = "Subconstituencies" class CandidateAdmin(LibyaAdminModel):
64
64
64
9
55
SmartElect/SmartElect
voting/admin.py
Python
CandidateAdmin
CandidateAdmin
68
71
68
68
a30dd7427707e0b56c177783457505e45738fe74
bigcode/the-stack
train
bac212f11439b673cb668fc7
train
class
class TestExpandRoles(base.TestCase): def test_simple(self): roles = [ {'name': 'Compute'}, {'name': 'Controller'}, ] action = baremetal_deploy.ExpandRolesAction(roles) result = action.run(mock.Mock()) self.assertEqual( [ {...
class TestExpandRoles(base.TestCase):
def test_simple(self): roles = [ {'name': 'Compute'}, {'name': 'Controller'}, ] action = baremetal_deploy.ExpandRolesAction(roles) result = action.run(mock.Mock()) self.assertEqual( [ {'hostname': 'overcloud-novacompute-0', ...
action.run(mock.Mock()) self.assertIn("RuntimeError: boom", result.error) pr.wait_for_provisioning.assert_called_once_with(['uuid1'], timeout=3600) self.assertFalse(pr.unprovision_node.called) @mock.patch.object(baremetal_deploy, '_pro...
256
256
4,610
8
248
AllenJSebastian/tripleo-common
tripleo_common/tests/actions/test_baremetal_deploy.py
Python
TestExpandRoles
TestExpandRoles
648
1,246
648
649
19e316374d44132510d488926c157626471d6218
bigcode/the-stack
train
d534e1c267159314780c03f2
train
class
@mock.patch.object(baremetal_deploy, '_provisioner', autospec=True) class TestUndeployInstance(base.TestCase): def test_success(self, mock_pr): pr = mock_pr.return_value action = baremetal_deploy.UndeployInstanceAction('inst1') result = action.run(mock.Mock()) self.assertIsNone(resu...
@mock.patch.object(baremetal_deploy, '_provisioner', autospec=True) class TestUndeployInstance(base.TestCase):
def test_success(self, mock_pr): pr = mock_pr.return_value action = baremetal_deploy.UndeployInstanceAction('inst1') result = action.run(mock.Mock()) self.assertIsNone(result) pr.show_instance.assert_called_once_with('inst1') pr.unprovision_node.assert_called_once_wi...
result.error) pr.wait_for_provisioning.assert_called_once_with(['uuid1'], timeout=3600) self.assertFalse(pr.unprovision_node.called) @mock.patch.object(baremetal_deploy, '_provisioner', autospec=True) class TestUndeployInstance(base.TestCase):
64
64
198
29
35
AllenJSebastian/tripleo-common
tripleo_common/tests/actions/test_baremetal_deploy.py
Python
TestUndeployInstance
TestUndeployInstance
624
645
624
626
98108566b5ae666811f7c575dbd2e090d828b05f
bigcode/the-stack
train
2497c8419b0ba7d8effbb0f5
train
class
class TestPopulateEnvironment(base.TestCase): def test_success(self): port_map = { 'compute-0': { 'ctlplane': { 'network': { 'tags': ['foo'], 'mtu': 1350, 'id': 'aaaa' # will be filtered...
class TestPopulateEnvironment(base.TestCase):
def test_success(self): port_map = { 'compute-0': { 'ctlplane': { 'network': { 'tags': ['foo'], 'mtu': 1350, 'id': 'aaaa' # will be filtered out }, ...
', 'image': {'href': 'overcloud-full'}, 'traits': ['CUSTOM_FOO'], 'nics': [{'subnet': 'leaf-2'}]}, ], result['instances']) def test_more_instances_than_count(self): roles = [{ 'name': 'Compute', 'count': 3, 'defau...
205
205
684
8
197
AllenJSebastian/tripleo-common
tripleo_common/tests/actions/test_baremetal_deploy.py
Python
TestPopulateEnvironment
TestPopulateEnvironment
1,249
1,326
1,249
1,250
3b349c6593e617ba1699907d6144bcaee1f26e31
bigcode/the-stack
train
d8d2ba2c1c49d31ced5c759d
train
class
@mock.patch.object(baremetal_deploy, '_provisioner', autospec=True) class TestDeployNode(base.TestCase): def test_success_defaults(self, mock_pr): action = baremetal_deploy.DeployNodeAction( instance={'hostname': 'host1', 'image': {'href': 'overcloud-full'}}, n...
@mock.patch.object(baremetal_deploy, '_provisioner', autospec=True) class TestDeployNode(base.TestCase):
def test_success_defaults(self, mock_pr): action = baremetal_deploy.DeployNodeAction( instance={'hostname': 'host1', 'image': {'href': 'overcloud-full'}}, node='1234' ) result = action.run(mock.Mock()) pr = mock_pr.return_value s...
(instances) result = action.run(mock.Mock()) self.assertIn('Node node-1 is requested more than once', result.error) self.assertFalse(mock_pr.return_value.reserve_node.called) def test_hostname_format(self, mock_pr): self.assertEqual( '%stackname%-controller-%index%', ...
256
256
2,141
27
229
AllenJSebastian/tripleo-common
tripleo_common/tests/actions/test_baremetal_deploy.py
Python
TestDeployNode
TestDeployNode
197
451
197
199
6ff9f8caad635f635ccbefe91487454872f06654
bigcode/the-stack
train
083e4d00c17aea854a594d9f
train
class
@mock.patch.object(baremetal_deploy, '_provisioner', autospec=True) class TestCheckExistingInstances(base.TestCase): def test_success(self, mock_pr): pr = mock_pr.return_value instances = [ {'hostname': 'host1', 'image': {'href': 'overcloud-full'}}, {'hostname':...
@mock.patch.object(baremetal_deploy, '_provisioner', autospec=True) class TestCheckExistingInstances(base.TestCase):
def test_success(self, mock_pr): pr = mock_pr.return_value instances = [ {'hostname': 'host1', 'image': {'href': 'overcloud-full'}}, {'hostname': 'host3', 'image': {'href': 'overcloud-full'}}, {'hostname': 'host2', 'resource_class': 'comp...
= mock_pr.return_value instance = {'hostname': 'host1', 'image': {'href': 'overcloud-full'}} action = baremetal_deploy.DeployNodeAction( instance=instance, node='1234' ) pr.provision_node.side_effect = RuntimeError('boom') pr.unprovisi...
253
254
848
28
225
AllenJSebastian/tripleo-common
tripleo_common/tests/actions/test_baremetal_deploy.py
Python
TestCheckExistingInstances
TestCheckExistingInstances
454
557
454
456
b470aaf2ba639e29411f5eedc9fefbb6e8216c64
bigcode/the-stack
train
de608b60c69a0de877780a71
train
class
@mock.patch.object(baremetal_deploy, '_provisioner', autospec=True) class TestReserveNodes(base.TestCase): def test_success(self, mock_pr): instances = [ {'hostname': 'host1', 'profile': 'compute', 'image': {'href': 'overcloud-full'}}, {'hostname': 'host2', 'resource_cl...
@mock.patch.object(baremetal_deploy, '_provisioner', autospec=True) class TestReserveNodes(base.TestCase):
def test_success(self, mock_pr): instances = [ {'hostname': 'host1', 'profile': 'compute', 'image': {'href': 'overcloud-full'}}, {'hostname': 'host2', 'resource_class': 'compute', 'capabilities': {'answer': '42'}, 'image': {'href': 'overcloud-fu...
# Copyright 2018 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
202
256
1,499
27
174
AllenJSebastian/tripleo-common
tripleo_common/tests/actions/test_baremetal_deploy.py
Python
TestReserveNodes
TestReserveNodes
24
194
24
26
431a85efc25d72e580876fc99a2c7c61574a20ff
bigcode/the-stack
train
73cfd1193a07eb24826ddffe
train
class
@mock.patch.object(baremetal_deploy, '_provisioner', autospec=True) class TestWaitForDeployment(base.TestCase): def test_success(self, mock_pr): pr = mock_pr.return_value inst = pr.wait_for_provisioning.return_value[0] inst.to_dict.return_value = {'hostname': 'compute.cloud'} actio...
@mock.patch.object(baremetal_deploy, '_provisioner', autospec=True) class TestWaitForDeployment(base.TestCase):
def test_success(self, mock_pr): pr = mock_pr.return_value inst = pr.wait_for_provisioning.return_value[0] inst.to_dict.return_value = {'hostname': 'compute.cloud'} action = baremetal_deploy.WaitForDeploymentAction( {'hostname': 'compute.cloud', 'uuid': 'uuid1', ...
found", result.error) mock_pr.return_value.show_instance.assert_called_once_with('host1') def test_unexpected_error(self, mock_pr): instances = [ {'image': {'href': 'overcloud-full'}, 'hostname': 'host%d' % i} for i in range(3) ] mock_pr.return_value.show_i...
172
172
574
28
144
AllenJSebastian/tripleo-common
tripleo_common/tests/actions/test_baremetal_deploy.py
Python
TestWaitForDeployment
TestWaitForDeployment
560
621
560
562
b200d823bc803dbce7f2cf6faa52619ed6d91be4
bigcode/the-stack
train