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
0eeb1b11a2fda5166077699d
train
function
def inverse_fourier_transform(filtered_image): image_inv_f_shift = np.fft.ifftshift(filtered_image) # flip the corners back image_inv_f_trans = np.fft.ifft2(image_inv_f_shift) return image_inv_f_trans
def inverse_fourier_transform(filtered_image):
image_inv_f_shift = np.fft.ifftshift(filtered_image) # flip the corners back image_inv_f_trans = np.fft.ifft2(image_inv_f_shift) return image_inv_f_trans
, n): b_filter = butter_worth_filter(f_shifted_image.shape[0], f_shifted_image.shape[1], r, n) filtered_image = np.multiply(f_shifted_image, b_filter) return filtered_image # inverse transform the image def inverse_fourier_transform(filtered_image):
64
64
54
8
55
BengisuA14/METU-ImageProcessing
THE2/the2_part2.py
Python
inverse_fourier_transform
inverse_fourier_transform
39
43
39
39
d8fa9e8cd3d1d906f77716b238b1f6cc41f2d9f4
bigcode/the-stack
train
e3ef037ac80ce1e3200da5ec
train
class
class TestTerraformEvaluation(TestCase): def test_directive(self): input_str = '"Hello, %{ if "d" != "" }named%{ else }unnamed%{ endif }!"' expected = 'Hello, named!' self.assertEqual(expected, evaluate_terraform(input_str)) def test_condition(self): input_str = '"2 > 0 ? bigger...
class TestTerraformEvaluation(TestCase):
def test_directive(self): input_str = '"Hello, %{ if "d" != "" }named%{ else }unnamed%{ endif }!"' expected = 'Hello, named!' self.assertEqual(expected, evaluate_terraform(input_str)) def test_condition(self): input_str = '"2 > 0 ? bigger : smaller"' expected = 'bigger' ...
import os from unittest import TestCase from checkov.terraform.variable_rendering.evaluate_terraform import evaluate_terraform, replace_string_value, \ remove_interpolation from checkov.terraform.variable_rendering.safe_eval_functions import PythonCodeError class TestTerraformEvaluation(TestCase):
58
256
3,837
7
50
new23d/checkov
tests/graph/terraform/variable_rendering/test_string_evaluation.py
Python
TestTerraformEvaluation
TestTerraformEvaluation
9
359
9
9
aa22aa2afe960320757ca1268970454a19a56b08
bigcode/the-stack
train
5c17ff78bef540dd7a5e4c7a
train
function
def round_sum(a, b, c): return round10(a) + round10(b) + round10(c)
def round_sum(a, b, c):
return round10(a) + round10(b) + round10(c)
the helper entirely below and at the same indent level as round_sum(). ''' def round10(num): if num % 10 >= 5: return 10 - num % 10 + num else: return num - num % 10 def round_sum(a, b, c):
64
64
25
9
54
SleepNoMore/CodingBat
Logic-2/round_sum.py
Python
round_sum
round_sum
20
21
20
20
8f264e99fd4a6dae26681f41c9bfa0d2d39a8c94
bigcode/the-stack
train
c0e11f2e12557f0e8b6832ad
train
function
def round10(num): if num % 10 >= 5: return 10 - num % 10 + num else: return num - num % 10
def round10(num):
if num % 10 >= 5: return 10 - num % 10 + num else: return num - num % 10
10. Given 3 ints, a b c, return the sum of their rounded values. To avoid code repetition, write a separate helper "def round10(num):" and call it 3 times. Write the helper entirely below and at the same indent level as round_sum(). ''' def round10(num):
63
64
39
5
58
SleepNoMore/CodingBat
Logic-2/round_sum.py
Python
round10
round10
13
17
13
13
f8a7b82e5c95e2428e06f18cdc450bc9adfa8ffb
bigcode/the-stack
train
2a63d67616104c07dc09d40d
train
class
class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Permission', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ...
class Migration(migrations.Migration):
initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Permission', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('url', models.CharField(max_length=64...
# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-06-02 08:41 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):
54
64
179
7
46
gengna92/PythonProjects
host_manager_19/rbac/migrations/0001_initial.py
Python
Migration
Migration
8
32
8
9
7c47c1b0ff5ac84c6efd7d0e6e22e9fd7388f945
bigcode/the-stack
train
47c2fcb1e3c98c05482d4de3
train
class
class TestClassOelintTaskHeredocs(TestBaseClass): @pytest.mark.parametrize('id', ['oelint.task.heredocs']) @pytest.mark.parametrize('occurance', [1]) @pytest.mark.parametrize('input', [ { 'oelint_adv_test.bb': ''' do_foo() { cat > ...
class TestClassOelintTaskHeredocs(TestBaseClass): @pytest.mark.parametrize('id', ['oelint.task.heredocs']) @pytest.mark.parametrize('occurance', [1]) @pytest.mark.parametrize('input', [ { 'oelint_adv_test.bb': ''' do_foo() { cat > ...
def test_bad(self, input, id, occurance): self.check_for_id(self._create_args(input), id, occurance) @pytest.mark.parametrize('id', ['oelint.task.heredocs']) @pytest.mark.parametrize('occurance', [0]) @pytest.mark.parametrize('input', [ { 'oelint_adv_test.bb': ...
class TestClassOelintTaskHeredocs(TestBaseClass): @pytest.mark.parametrize('id', ['oelint.task.heredocs']) @pytest.mark.parametrize('occurance', [1]) @pytest.mark.parametrize('input', [ { 'oelint_adv_test.bb': ''' do_foo() { cat > ...
161
87
290
161
0
Rahix/oelint-adv
tests/test_class_oelint_task_heredocs.py
Python
TestClassOelintTaskHeredocs
TestClassOelintTaskHeredocs
10
56
10
37
f39c9ddc34d7473d527ed714d3d6d1790d9407cd
bigcode/the-stack
train
e8db6cbe91ce976f27597fd5
train
function
def get_day(): '''Asks the user for as an integer day and returns the specified day. Args: none. Returns: (int): Returns the day of the weeek that the user chooses. ''' day = input('\nWhich day? Please type your response as an integer. For example Mon=0, Tues=1, etc.\n') if int...
def get_day():
'''Asks the user for as an integer day and returns the specified day. Args: none. Returns: (int): Returns the day of the weeek that the user chooses. ''' day = input('\nWhich day? Please type your response as an integer. For example Mon=0, Tues=1, etc.\n') if int(day) not in [0...
, April, May, or June?\n') month= month.lower() if month not in ['january', 'february', 'march', 'april','may', 'june']: print('This input is not valid.') return get_month() return month def get_day():
64
64
125
4
59
cmaravil/Bikeshare-data-
bikeshare.py
Python
get_day
get_day
90
104
90
90
77d824ef25f66ffdab523c0fd158486e05b1c637
bigcode/the-stack
train
3ef46365dae8a76394805c5e
train
function
def popular_trip(city_file, time_period): '''Question: What is the most popular trip? Args: city_file, time_period Returns: (str,str) Returns most popular trip. ''' df = load_df(city_file) return df.groupby(['Start Station','End Station'])['Start Station'].count().sort_values(asc...
def popular_trip(city_file, time_period):
'''Question: What is the most popular trip? Args: city_file, time_period Returns: (str,str) Returns most popular trip. ''' df = load_df(city_file) return df.groupby(['Start Station','End Station'])['Start Station'].count().sort_values(ascending=False).index[0]
) st= df.groupby('Start Station')['Start Station'].count().sort_values(ascending=False).index[0] ed= df.groupby('End Station')['End Station'].count().sort_values(ascending=False).index[0] return st,ed def popular_trip(city_file, time_period):
64
64
80
9
54
cmaravil/Bikeshare-data-
bikeshare.py
Python
popular_trip
popular_trip
206
214
206
206
f578b27de352bc74730f00f2268737458ada1e0c
bigcode/the-stack
train
56b93c44966de3420f7692a7
train
function
def users(city_file, time_period): '''Question: What are the counts of each user type? Args: city_file, time_period Returns: (str,int) Returns counts for each user type. ''' df = load_df(city_file) user_results = pd.value_counts(df['User Type']) return user_results
def users(city_file, time_period):
'''Question: What are the counts of each user type? Args: city_file, time_period Returns: (str,int) Returns counts for each user type. ''' df = load_df(city_file) user_results = pd.value_counts(df['User Type']) return user_results
_file, time_period Returns: (str,str) Returns most popular trip. ''' df = load_df(city_file) return df.groupby(['Start Station','End Station'])['Start Station'].count().sort_values(ascending=False).index[0] def users(city_file, time_period):
63
64
73
8
55
cmaravil/Bikeshare-data-
bikeshare.py
Python
users
users
218
227
218
218
43bed913b0cdf84be4f1494f323a0942435a445d
bigcode/the-stack
train
7edcff75c4d6c1f25e78249d
train
function
def popular_hour(city_file, time_period): ''' Question: What is the most popular hour of day for start time? Args: city_file, time_period Returns: (int) Most popular hour of the day for starting time. ''' #setting a new column for the results using df[] popular_hour= ('\nThe ...
def popular_hour(city_file, time_period):
''' Question: What is the most popular hour of day for start time? Args: city_file, time_period Returns: (int) Most popular hour of the day for starting time. ''' #setting a new column for the results using df[] popular_hour= ('\nThe most popular hour of the day for start tim...
'Wednesday','Thursday','Friday','Saturday'] df['weekday'] = df['Start Time'].dt.weekday_name.mode().index[0] return int(df['weekday'].mode()[0]) #print('Most Popular Day:', popular_day) in statistics def popular_hour(city_file, time_period):
64
64
120
9
54
cmaravil/Bikeshare-data-
bikeshare.py
Python
popular_hour
popular_hour
155
167
155
155
111c8127dbd89ddebf8eb8eb53700e3e653b5d5f
bigcode/the-stack
train
b90d7968d0982d9737660d14
train
function
def popular_day(city_file, time_period): ''' Question: What is the most popular day of week (Monday, Tuesday, etc.) for start time? Args: city_file, time_period Returns: (int) Most popular startime for a city's bikeshare data. ''' popular_day=('\n The most popular day of the we...
def popular_day(city_file, time_period):
''' Question: What is the most popular day of week (Monday, Tuesday, etc.) for start time? Args: city_file, time_period Returns: (int) Most popular startime for a city's bikeshare data. ''' popular_day=('\n The most popular day of the week for start time is :\n') df = load_...
) Mode of popular month for a city's bikeshare data. ''' df = load_df(city_file) df['month'] = df['Start Time'].dt.month popular_month_num = int(df['month'].mode()) return popular_month_num def popular_day(city_file, time_period):
64
64
158
9
54
cmaravil/Bikeshare-data-
bikeshare.py
Python
popular_day
popular_day
135
150
135
135
5908769eb0f91ff4bbab5a55277d9ac0f67464af
bigcode/the-stack
train
617eee7eb5ca9be12542180f
train
function
def trip_duration(city_file, time_period): ''' Question: What is the total trip duration and average trip duration? Args: city_file, time_period Returns: (int,int) Returns the total sum of the drip durations and the average. ''' trip_duration=('\nThe total and average durations o...
def trip_duration(city_file, time_period):
''' Question: What is the total trip duration and average trip duration? Args: city_file, time_period Returns: (int,int) Returns the total sum of the drip durations and the average. ''' trip_duration=('\nThe total and average durations of trips are:\n') df=load_df(city_file) ...
[] popular_hour= ('\nThe most popular hour of the day for start time is :\n') df = load_df(city_file) df['hour'] = df['Start Time'].dt.hour return int(df['hour'].mode()) def trip_duration(city_file, time_period):
63
64
110
9
54
cmaravil/Bikeshare-data-
bikeshare.py
Python
trip_duration
trip_duration
173
186
173
173
428a551d984cbf199aa2e73094df9892d4442cdf
bigcode/the-stack
train
120f3d164708e81439b2fb12
train
function
def popular_month(city_file, time_period): ''' Question: What is the most popular month? Args: city_file and time_period Returns: (int) Mode of popular month for a city's bikeshare data. ''' df = load_df(city_file) df['month'] = df['Start Time'].dt.month popular_month_num = i...
def popular_month(city_file, time_period):
''' Question: What is the most popular month? Args: city_file and time_period Returns: (int) Mode of popular month for a city's bikeshare data. ''' df = load_df(city_file) df['month'] = df['Start Time'].dt.month popular_month_num = int(df['month'].mode()) return popular_m...
Returns: Loads city CSV using pandas. ''' df = pd.read_csv(city) df['Start Time'] = pd.to_datetime(df['Start Time']) # df['End Time'] = pd.to_datetime(df['End Time']) return df def popular_month(city_file, time_period):
64
64
91
9
54
cmaravil/Bikeshare-data-
bikeshare.py
Python
popular_month
popular_month
122
132
122
122
31cc8da8eff277877aeee5badc4fb56e6866f143
bigcode/the-stack
train
905311e85b1031f5e30cf610
train
function
def load_df(city): '''Loads data frame. Args: City Returns: Loads city CSV using pandas. ''' df = pd.read_csv(city) df['Start Time'] = pd.to_datetime(df['Start Time']) # df['End Time'] = pd.to_datetime(df['End Time']) return df
def load_df(city):
'''Loads data frame. Args: City Returns: Loads city CSV using pandas. ''' df = pd.read_csv(city) df['Start Time'] = pd.to_datetime(df['Start Time']) # df['End Time'] = pd.to_datetime(df['End Time']) return df
example Mon=0, Tues=1, etc.\n') if int(day) not in [0,1,2,3,4,5,6]: print('This input is not valid.') return get_day() day = int(day) return day def load_df(city):
64
64
72
5
58
cmaravil/Bikeshare-data-
bikeshare.py
Python
load_df
load_df
107
118
107
107
e4145e3b30513f1bfa9bc9d55c46853905ba3319
bigcode/the-stack
train
b9e322474d8962780a198334
train
function
def get_time_period(): '''Asks the user for a time period and returns the specified filter. Args: none. Returns: (str) Time period for a city's bikeshare data. ''' time_period = input('\nWould you like to filter the data by month, day, or not at' ' all? Type ...
def get_time_period():
'''Asks the user for a time period and returns the specified filter. Args: none. Returns: (str) Time period for a city's bikeshare data. ''' time_period = input('\nWould you like to filter the data by month, day, or not at' ' all? Type "none" for no time filt...
new_york_city elif city== 'washington': print('Ok, Let\'s explore the data for Washington') return washington else: print ('Sorry that is not a valid input, please make sure you are using lowercase letters.') return get_city() def get_time_period():
64
64
189
5
59
cmaravil/Bikeshare-data-
bikeshare.py
Python
get_time_period
get_time_period
44
69
44
44
aa419785db2c0c8b0242e761e30c38bb1e9d2132
bigcode/the-stack
train
f6add0913c58488a6a05ac4e
train
function
def gender(city_file, time_period): '''Question: What are the counts of gender? Args: city_file, time_period Returns: (str,int) Returns counts for gender types. ''' df = load_df(city_file) if 'Gender' in df: gender_results = pd.value_counts(df['Gender']) return ge...
def gender(city_file, time_period):
'''Question: What are the counts of gender? Args: city_file, time_period Returns: (str,int) Returns counts for gender types. ''' df = load_df(city_file) if 'Gender' in df: gender_results = pd.value_counts(df['Gender']) return gender_results else: retur...
each user type? Args: city_file, time_period Returns: (str,int) Returns counts for each user type. ''' df = load_df(city_file) user_results = pd.value_counts(df['User Type']) return user_results def gender(city_file, time_period):
64
64
93
8
55
cmaravil/Bikeshare-data-
bikeshare.py
Python
gender
gender
229
241
229
229
9683a39547af5653208e60bb57e97946f96cd2c2
bigcode/the-stack
train
f7828c07e3c3eea484dba56a
train
function
def get_month(): '''Asks the user for a month and returns the specified month. Args: none. Returns: (str): Returns the month the user chooses. ''' month = input('\nWhich month? January, February, March, April, May, or June?\n') month= month.lower() if month not in ['january...
def get_month():
'''Asks the user for a month and returns the specified month. Args: none. Returns: (str): Returns the month the user chooses. ''' month = input('\nWhich month? January, February, March, April, May, or June?\n') month= month.lower() if month not in ['january', 'february', 'm...
data by day.') return get_day() elif time_period == 'none': print('Great, we will not filter the time period.') return time_period else: print('Sorry, that is not a valid input, please try again.') return get_time_period() def get_month():
64
64
115
4
60
cmaravil/Bikeshare-data-
bikeshare.py
Python
get_month
get_month
72
86
72
72
4dab52fc176728d1ebafe6e4ea589cd68a8abba3
bigcode/the-stack
train
700ba763ab2631a10c9be25a
train
function
def statistics(): '''Calculates and prints out the descriptive statistics about a city and time period specified by the user via raw input. Args: none. Returns: none. ''' # Filter by city (Chicago, New York, Washington) city = get_city() # Filter by time period (month, ...
def statistics():
'''Calculates and prints out the descriptive statistics about a city and time period specified by the user via raw input. Args: none. Returns: none. ''' # Filter by city (Chicago, New York, Washington) city = get_city() # Filter by time period (month, day, none) tim...
''' df = load_df(city_file) if 'Birth Year' in df: return (int(df['Birth Year'].max()),int(df['Birth Year'].min()),int(df['Birth Year'].mode()[0])) else: return "Sorry, this data is not available for Washington." def display_data(city_files, current_idx=0): '''Displays five ...
235
236
787
3
233
cmaravil/Bikeshare-data-
bikeshare.py
Python
statistics
statistics
279
371
279
279
0ad088a19a7072b77b572cdb16b4bb8d63107eb7
bigcode/the-stack
train
8e7222eebb3a07ba0a40549a
train
function
def display_data(city_files, current_idx=0): '''Displays five lines of data if the user specifies that they would like to. After displaying five lines, ask the user if they would like to see five more, continuing asking until they say stop. Args: city_file, index Returns: 5 rows at ...
def display_data(city_files, current_idx=0):
'''Displays five lines of data if the user specifies that they would like to. After displaying five lines, ask the user if they would like to see five more, continuing asking until they say stop. Args: city_file, index Returns: 5 rows at a time from csv converted to data frame. ...
'Birth Year' in df: return (int(df['Birth Year'].max()),int(df['Birth Year'].min()),int(df['Birth Year'].mode()[0])) else: return "Sorry, this data is not available for Washington." def display_data(city_files, current_idx=0):
63
64
167
11
52
cmaravil/Bikeshare-data-
bikeshare.py
Python
display_data
display_data
258
276
258
258
b07d74849b651446945ac4d9c4ef25daf0dc2828
bigcode/the-stack
train
9a22fc01066497e9ae5690ac
train
function
def birth_years(city_file, time_period): '''Question: What are the earliest (i.e. oldest user), most recent (i.e. youngest user), and most popular birth years? Args: city_file, time_period Returns: (int) Returns youngest, oldest and most popular birth years. ''' df = load_df(city...
def birth_years(city_file, time_period):
'''Question: What are the earliest (i.e. oldest user), most recent (i.e. youngest user), and most popular birth years? Args: city_file, time_period Returns: (int) Returns youngest, oldest and most popular birth years. ''' df = load_df(city_file) if 'Birth Year' in df: ...
for gender types. ''' df = load_df(city_file) if 'Gender' in df: gender_results = pd.value_counts(df['Gender']) return gender_results else: return "Sorry, this data is not available for Washington." def birth_years(city_file, time_period):
64
64
132
10
54
cmaravil/Bikeshare-data-
bikeshare.py
Python
birth_years
birth_years
244
256
244
244
2a702b2772a0474cee68edd7cbd07dba4fd550c0
bigcode/the-stack
train
c24078c03b9ddf0800304015
train
function
def popular_stations(city_file, time_period): ''' Question: What is the most popular start station and most popular end station? Args: city_file, time_period Returns: (str,str) Returns most common start and end station. ''' #popular_stations(city,time_period) #query to data f...
def popular_stations(city_file, time_period):
''' Question: What is the most popular start station and most popular end station? Args: city_file, time_period Returns: (str,str) Returns most common start and end station. ''' #popular_stations(city,time_period) #query to data frame df = load_df(city_file) st= df.gr...
''' trip_duration=('\nThe total and average durations of trips are:\n') df=load_df(city_file) tot_duration=df['Trip Duration'].sum() avg_duration=df['Trip Duration'].mean() return tot_duration,avg_duration def popular_stations(city_file, time_period):
64
64
134
10
53
cmaravil/Bikeshare-data-
bikeshare.py
Python
popular_stations
popular_stations
190
203
190
190
a324e12c1af9888c922974ec8bd74141cc6ad2ad
bigcode/the-stack
train
dc4c5c4b351f46d322d11271
train
function
def get_city(): '''Asks the user for a city and returns the filename for that city's bike share data. Args: none. Returns: (str) Filename for a city's bikeshare data. ''' city = input('\nHello! Let\'s explore some US bikeshare data!\n' 'Would you like to see data fo...
def get_city():
'''Asks the user for a city and returns the filename for that city's bike share data. Args: none. Returns: (str) Filename for a city's bikeshare data. ''' city = input('\nHello! Let\'s explore some US bikeshare data!\n' 'Would you like to see data for Chicago, New Y...
import csv import pprint import datetime import time import pandas as pd ## Filenames chicago = 'chicago.csv' new_york_city = 'new_york_city.csv' washington = 'washington.csv' def get_city():
54
64
204
4
50
cmaravil/Bikeshare-data-
bikeshare.py
Python
get_city
get_city
16
41
16
16
1a39dc64c6ef9d7835ef569a00d308cea381bf63
bigcode/the-stack
train
8a053761fa5fd41cc756ae96
train
class
class CertonlyTest(unittest.TestCase): """Tests for certbot._internal.main.certonly.""" def setUp(self): self.get_utility_patch = test_util.patch_display_util() self.mock_get_utility = self.get_utility_patch.start() def tearDown(self): self.get_utility_patch.stop() def _call(s...
class CertonlyTest(unittest.TestCase):
"""Tests for certbot._internal.main.certonly.""" def setUp(self): self.get_utility_patch = test_util.patch_display_util() self.mock_get_utility = self.get_utility_patch.start() def tearDown(self): self.get_utility_patch.stop() def _call(self, args): plugins = disco.Plu...
() self.mock_success_renewal.assert_called_once_with([self.domain]) @mock.patch('certbot._internal.main.plug_sel.choose_configurator_plugins') def test_run_enhancement_not_supported(self, mock_choose): mock_choose.return_value = (null.Installer(self.config, "null"), None) plugins = disc...
256
256
1,272
8
248
luisriverag/certbot
certbot/tests/main_test.py
Python
CertonlyTest
CertonlyTest
180
285
180
180
6cd640b809da66de9c37429d8ecf7a818f2d2963
bigcode/the-stack
train
7a70405e7e77b3cb4b06b4cf
train
class
class EnhanceTest(test_util.ConfigTestCase): """Tests for certbot._internal.main.enhance.""" def setUp(self): super().setUp() self.get_utility_patch = test_util.patch_display_util() self.mock_get_utility = self.get_utility_patch.start() self.mockinstaller = mock.MagicMock(spec=e...
class EnhanceTest(test_util.ConfigTestCase):
"""Tests for certbot._internal.main.enhance.""" def setUp(self): super().setUp() self.get_utility_patch = test_util.patch_display_util() self.mock_get_utility = self.get_utility_patch.start() self.mockinstaller = mock.MagicMock(spec=enhancements.AutoHSTSEnhancement) def tea...
Client.return_value = cb_client config = mock.MagicMock() unused_plugins = mock.MagicMock() res = main.unregister(config, unused_plugins) m = "Could not find existing account to deactivate." self.assertEqual(res, m) self.assertIs(cb_client.acme.deactivate_registration.c...
256
256
1,734
9
247
luisriverag/certbot
certbot/tests/main_test.py
Python
EnhanceTest
EnhanceTest
1,626
1,767
1,626
1,626
3e0badc212b285fa9edb89050cda5a33d4f0a442
bigcode/the-stack
train
ef64718bbf6a1785dd8b82c5
train
class
class RevokeTest(test_util.TempDirTestCase): """Tests for certbot._internal.main.revoke.""" def setUp(self): super().setUp() shutil.copy(CERT_PATH, self.tempdir) self.tmp_cert_path = os.path.abspath(os.path.join(self.tempdir, 'cert_512.pem')) patches = [ mock.patch...
class RevokeTest(test_util.TempDirTestCase):
"""Tests for certbot._internal.main.revoke.""" def setUp(self): super().setUp() shutil.copy(CERT_PATH, self.tempdir) self.tmp_cert_path = os.path.abspath(os.path.join(self.tempdir, 'cert_512.pem')) patches = [ mock.patch('acme.client.BackwardsCompatibleClientV2'), ...
.choose_names') def test_display_ops(self, mock_choose_names): mock_config = mock.Mock(domains=None, certname=None) mock_choose_names.return_value = "domainname" # pylint: disable=protected-access self.assertEqual(main._find_domains_or_certname(mock_config, None), ("domainname", None...
256
256
1,383
11
245
luisriverag/certbot
certbot/tests/main_test.py
Python
RevokeTest
RevokeTest
316
439
316
316
2b04006a29fa620bb12b6c2996c094d588c8cf0a
bigcode/the-stack
train
a033946966c376051bf8917f
train
class
class InstallTest(test_util.ConfigTestCase): """Tests for certbot._internal.main.install.""" def setUp(self): super().setUp() self.mockinstaller = mock.MagicMock(spec=enhancements.AutoHSTSEnhancement) @mock.patch('certbot._internal.main.plug_sel.record_chosen_plugins') @mock.patch('cer...
class InstallTest(test_util.ConfigTestCase):
"""Tests for certbot._internal.main.install.""" def setUp(self): super().setUp() self.mockinstaller = mock.MagicMock(spec=enhancements.AutoHSTSEnhancement) @mock.patch('certbot._internal.main.plug_sel.record_chosen_plugins') @mock.patch('certbot._internal.main.plug_sel.pick_installer')...
_lineage.return_value = mock.MagicMock(chain_path="/tmp/nonexistent") self.assertRaises( errors.NotSupportedError, self._call, ['enhance', '--auto-hsts']) def test_enhancement_enable_conflict(self): self.assertRaises( errors.Error, self._call, ['enhan...
88
89
298
9
79
luisriverag/certbot
certbot/tests/main_test.py
Python
InstallTest
InstallTest
1,770
1,799
1,770
1,770
af95eb58906f9ff662f58aa1deddd5631727ff52
bigcode/the-stack
train
ce1093cfa1579aa51c4526b3
train
class
class RunTest(test_util.ConfigTestCase): """Tests for certbot._internal.main.run.""" def setUp(self): super().setUp() self.domain = 'example.org' patches = [ mock.patch('certbot._internal.main._get_and_save_cert'), mock.patch('certbot._internal.main.display_ops.s...
class RunTest(test_util.ConfigTestCase):
"""Tests for certbot._internal.main.run.""" def setUp(self): super().setUp() self.domain = 'example.org' patches = [ mock.patch('certbot._internal.main._get_and_save_cert'), mock.patch('certbot._internal.main.display_ops.success_installation'), mock.p...
= mock.Mock() config.key_type = "rsa" cert = mock.Mock() cert.private_key_type = "ecdsa" mock_set.return_value = True main._handle_unexpected_key_type_migration(config, cert) mock_set.return_value = False with self.assertRaises(errors.Error) as raised: ...
235
235
785
9
226
luisriverag/certbot
certbot/tests/main_test.py
Python
RunTest
RunTest
99
178
99
99
1dcd18adc96beb8a6a17e7c5b31352263f5713be
bigcode/the-stack
train
b334abe392219b27ba79140b
train
class
class ReportNewCertTest(unittest.TestCase): """Tests for certbot._internal.main._report_new_cert and certbot._internal.main._csr_report_new_cert. """ def setUp(self): from datetime import datetime self.notify_patch = mock.patch('certbot._internal.main.display_util.notify') se...
class ReportNewCertTest(unittest.TestCase):
"""Tests for certbot._internal.main._report_new_cert and certbot._internal.main._csr_report_new_cert. """ def setUp(self): from datetime import datetime self.notify_patch = mock.patch('certbot._internal.main.display_util.notify') self.mock_notify = self.notify_patch.start() ...
) @mock.patch('certbot._internal.main.plug_sel.record_chosen_plugins') @mock.patch('certbot._internal.main.plug_sel.pick_installer') def test_install_enhancement_not_supported(self, mock_inst, _rec): mock_inst.return_value = null.Installer(self.config, "null") plugins = disco.PluginsRegistr...
256
256
1,057
9
247
luisriverag/certbot
certbot/tests/main_test.py
Python
ReportNewCertTest
ReportNewCertTest
1,802
1,911
1,802
1,802
84a33e67ffa6f98c6ddafcb28116bef81058f1ac
bigcode/the-stack
train
da660ed8a5b2d0514092e878
train
class
class ReportNextStepsTest(unittest.TestCase): """Tests for certbot._internal.main._report_next_steps""" def setUp(self): self.config = mock.MagicMock( cert_name="example.com", preconfigured_renewal=True, csr=None, authenticator="nginx", manual_auth_hook=None) notify_patc...
class ReportNextStepsTest(unittest.TestCase):
"""Tests for certbot._internal.main._report_next_steps""" def setUp(self): self.config = mock.MagicMock( cert_name="example.com", preconfigured_renewal=True, csr=None, authenticator="nginx", manual_auth_hook=None) notify_patch = mock.patch('certbot._internal.main.display...
.Mock(dry_run=False, authenticator='manual', manual_auth_hook=None), '/path/to/cert.pem', '/path/to/fullchain.pem', '/path/to/privkey.pem') self.mock_notify.assert_called_with( '\nSuccessfully received certificate.\n' 'Certificate is saved at: /path/t...
129
129
433
9
120
luisriverag/certbot
certbot/tests/main_test.py
Python
ReportNextStepsTest
ReportNextStepsTest
1,914
1,962
1,914
1,914
3586624489d732cde5f7dbd2a045da24cfc51efa
bigcode/the-stack
train
a75e7056ff6fd88da53c5ad2
train
class
class UnregisterTest(unittest.TestCase): def setUp(self): self.patchers = { '_determine_account': mock.patch('certbot._internal.main._determine_account'), 'account': mock.patch('certbot._internal.main.account'), 'client': mock.patch('certbot._internal.main.client'), ...
class UnregisterTest(unittest.TestCase):
def setUp(self): self.patchers = { '_determine_account': mock.patch('certbot._internal.main._determine_account'), 'account': mock.patch('certbot._internal.main.account'), 'client': mock.patch('certbot._internal.main.client'), 'get_utility': test_util.patch_dis...
') def test_renew_doesnt_restart_on_dryrun(self, mock_get_cert, mock_init, mock_choose, mock_run_renewal_deployer): """A dry-run renewal shouldn't try to restart the installer""" self.config.dry_run = True installer = mock.MagicMock() mock_...
143
143
478
8
135
luisriverag/certbot
certbot/tests/main_test.py
Python
UnregisterTest
UnregisterTest
1,544
1,602
1,544
1,544
86f4d32a4203cc493360fed030dfdd3a48434b7d
bigcode/the-stack
train
f1bc30a16523d76b27b5e0e0
train
class
class DeleteIfAppropriateTest(test_util.ConfigTestCase): """Tests for certbot._internal.main._delete_if_appropriate """ def _call(self, mock_config): from certbot._internal.main import _delete_if_appropriate _delete_if_appropriate(mock_config) def _test_delete_opt_out_common(self): ...
class DeleteIfAppropriateTest(test_util.ConfigTestCase):
"""Tests for certbot._internal.main._delete_if_appropriate """ def _call(self, mock_config): from certbot._internal.main import _delete_if_appropriate _delete_if_appropriate(mock_config) def _test_delete_opt_out_common(self): with mock.patch('certbot._internal.cert_manager.delete')...
NY, constants.CLI_DEFAULTS['server']) self.mock_success_revoke.assert_called_once_with(self.tmp_cert_path) @mock.patch('certbot._internal.main._delete_if_appropriate') def test_revocation_success(self, mock_delete_if_appropriate): self._call() mock_delete_if_appropriate.return_value = F...
256
256
1,111
12
244
luisriverag/certbot
certbot/tests/main_test.py
Python
DeleteIfAppropriateTest
DeleteIfAppropriateTest
441
542
441
441
3b0788b4c07ef593285164fd40c2e6f98a935e40
bigcode/the-stack
train
5324de773e9ffdd718382217
train
class
class MainTest(test_util.ConfigTestCase): """Tests for different commands.""" def setUp(self): super().setUp() filesystem.mkdir(self.config.logs_dir) self.standard_args = ['--config-dir', self.config.config_dir, '--work-dir', self.config.work_dir, ...
class MainTest(test_util.ConfigTestCase):
"""Tests for different commands.""" def setUp(self): super().setUp() filesystem.mkdir(self.config.logs_dir) self.standard_args = ['--config-dir', self.config.config_dir, '--work-dir', self.config.work_dir, '--logs-dir', self.c...
mock.patch('certbot._internal.main.display_util.notify') def test_no_accounts_no_email(self, mock_notify, mock_get_email): mock_get_email.return_value = 'foo@bar.baz' with mock.patch('certbot._internal.main.client') as client: client.register.return_value = ( self.accs[0...
256
256
10,239
9
247
luisriverag/certbot
certbot/tests/main_test.py
Python
MainTest
MainTest
617
1,541
617
617
4b978df30cb38e538adb99d4790d193a4f147517
bigcode/the-stack
train
b7e24467f72364918762237e
train
class
class MakeOrVerifyNeededDirs(test_util.ConfigTestCase): """Tests for certbot._internal.main.make_or_verify_needed_dirs.""" @mock.patch("certbot._internal.main.util") def test_it(self, mock_util): main.make_or_verify_needed_dirs(self.config) for core_dir in (self.config.config_dir, self.conf...
class MakeOrVerifyNeededDirs(test_util.ConfigTestCase):
"""Tests for certbot._internal.main.make_or_verify_needed_dirs.""" @mock.patch("certbot._internal.main.util") def test_it(self, mock_util): main.make_or_verify_needed_dirs(self.config) for core_dir in (self.config.config_dir, self.config.work_dir,): mock_util.set_up_core_dir.ass...
_plugins = mock.MagicMock() res = main.unregister(config, unused_plugins) m = "Could not find existing account to deactivate." self.assertEqual(res, m) self.assertIs(cb_client.acme.deactivate_registration.called, False) class MakeOrVerifyNeededDirs(test_util.ConfigTestCase):
64
64
178
12
52
luisriverag/certbot
certbot/tests/main_test.py
Python
MakeOrVerifyNeededDirs
MakeOrVerifyNeededDirs
1,605
1,623
1,605
1,605
30407833a05ab9db3702eae60562c3827d38d9a3
bigcode/the-stack
train
2da0d97d9d5ad38ddbe58f2e
train
class
class DetermineAccountTest(test_util.ConfigTestCase): """Tests for certbot._internal.main._determine_account.""" def setUp(self): super().setUp() self.config.account = None self.config.email = None self.config.register_unsafely_without_email = False self.accs = [mock.Mag...
class DetermineAccountTest(test_util.ConfigTestCase):
"""Tests for certbot._internal.main._determine_account.""" def setUp(self): super().setUp() self.config.account = None self.config.email = None self.config.register_unsafely_without_email = False self.accs = [mock.MagicMock(id='x'), mock.MagicMock(id='y')] self.a...
laps') @mock.patch('certbot._internal.storage.full_archive_path') @mock.patch('certbot._internal.cert_manager.cert_path_to_lineage') @mock.patch('certbot._internal.cert_manager.delete') @test_util.patch_display_util() def test_opt_in_deletion(self, mock_get_utility, mock_delete, mock_cer...
220
220
734
10
210
luisriverag/certbot
certbot/tests/main_test.py
Python
DetermineAccountTest
DetermineAccountTest
545
614
545
545
0c8e118d5f711292a5529efe10edc0234828baff
bigcode/the-stack
train
ef87ad3b8d32946952c88aae
train
class
class UpdateAccountTest(test_util.ConfigTestCase): """Tests for certbot._internal.main.update_account""" def setUp(self): patches = { 'account': mock.patch('certbot._internal.main.account'), 'atexit': mock.patch('certbot.util.atexit'), 'client': mock.patch('certbot._...
class UpdateAccountTest(test_util.ConfigTestCase):
"""Tests for certbot._internal.main.update_account""" def setUp(self): patches = { 'account': mock.patch('certbot._internal.main.account'), 'atexit': mock.patch('certbot.util.atexit'), 'client': mock.patch('certbot._internal.main.client'), 'determine_acco...
() return self.mock_notify.call_args_list[0][0][0] def test_report(self): """No steps for a normal renewal""" self.config.authenticator = "manual" self.config.manual_auth_hook = "/bin/true" self._call(self.config, None, None) self.mock_notify.assert_not_called() ...
256
256
1,101
10
246
luisriverag/certbot
certbot/tests/main_test.py
Python
UpdateAccountTest
UpdateAccountTest
1,965
2,068
1,965
1,965
e351bee701f9ea1d0b7e87c004b265df1b864f9f
bigcode/the-stack
train
98c3bbb96328d5d17b67d957
train
class
class FindDomainsOrCertnameTest(unittest.TestCase): """Tests for certbot._internal.main._find_domains_or_certname.""" @mock.patch('certbot.display.ops.choose_names') def test_display_ops(self, mock_choose_names): mock_config = mock.Mock(domains=None, certname=None) mock_choose_names.return_...
class FindDomainsOrCertnameTest(unittest.TestCase):
"""Tests for certbot._internal.main._find_domains_or_certname.""" @mock.patch('certbot.display.ops.choose_names') def test_display_ops(self, mock_choose_names): mock_config = mock.Mock(domains=None, certname=None) mock_choose_names.return_value = "domainname" # pylint: disable=prote...
csr {CSR}", "-d example.com"): self._call(f"certonly {flag} --webroot --cert-name example.com --dry-run".split()) mock_report_next_steps.assert_called_once_with( mock.ANY, mock.ANY, mock.ANY, new_or_renewed_cert=False) mock_report_next_steps.reset_mock() class FindDom...
84
84
281
11
73
luisriverag/certbot
certbot/tests/main_test.py
Python
FindDomainsOrCertnameTest
FindDomainsOrCertnameTest
288
313
288
288
fccfee04be2a3ed3fd1ed5a69a7362507231976d
bigcode/the-stack
train
0a193db6dd1e5cc50fc36a4b
train
class
class TestHandleCerts(unittest.TestCase): """Test for certbot._internal.main._handle_* methods""" @mock.patch("certbot._internal.main._handle_unexpected_key_type_migration") def test_handle_identical_cert_request_pending(self, mock_handle_migration): mock_lineage = mock.Mock() mock_lineage.e...
class TestHandleCerts(unittest.TestCase):
"""Test for certbot._internal.main._handle_* methods""" @mock.patch("certbot._internal.main._handle_unexpected_key_type_migration") def test_handle_identical_cert_request_pending(self, mock_handle_migration): mock_lineage = mock.Mock() mock_lineage.ensure_deployed.return_value = False ...
import os from certbot.plugins import enhancements import certbot.tests.util as test_util try: import mock except ImportError: # pragma: no cover from unittest import mock CERT_PATH = test_util.vector_path('cert_512.pem') CERT = test_util.vector_path('cert_512.pem') CSR = test_util.vector_path('csr_512.der...
150
150
500
9
141
luisriverag/certbot
certbot/tests/main_test.py
Python
TestHandleCerts
TestHandleCerts
52
96
52
52
37d87f12a2ce3cd4154c5aa81222c48ad93bb0a8
bigcode/the-stack
train
6438fc3a47066d1c3f9b5c10
train
class
class log_sum_exp(Atom): """:math:`\log\sum_i e^{x_i}` """ def __init__(self, x): super(log_sum_exp, self).__init__(x) # Evaluates e^x elementwise, sums, and takes the log. @Atom.numpy_numeric def numeric(self, values): exp_mat = np.exp(values[0]) exp_sum = exp_mat.sum(...
class log_sum_exp(Atom):
""":math:`\log\sum_i e^{x_i}` """ def __init__(self, x): super(log_sum_exp, self).__init__(x) # Evaluates e^x elementwise, sums, and takes the log. @Atom.numpy_numeric def numeric(self, values): exp_mat = np.exp(values[0]) exp_sum = exp_mat.sum(axis = 1).sum(axis = 0) ...
PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CVXPY. If not, see <http://www.gnu.org/licenses/>. """ import cvxpy.utilities as u import cvxpy.lin_ops.lin_utils as lu from cvxpy.atoms.atom import Atom from cvxpy.atoms.eleme...
125
125
419
7
117
riadnassiffe/Simulator
src/tools/ecos/cvxpy/cvxpy/atoms/log_sum_exp.py
Python
log_sum_exp
log_sum_exp
28
85
28
28
3efe94780a01880f2ece674f6b7714cdc3a1cdd6
bigcode/the-stack
train
c57d7abb3798a5bc7355f636
train
function
def generalized_singles(wires, delta_sz): r"""Return generalized single excitation terms .. math:: \hat{T_1} = \sum_{pq} t_{p}^{q} \hat{c}^{\dagger}_{q} \hat{c}_{p} """ sz = np.array( [0.5 if (i % 2 == 0) else -0.5 for i in range(len(wires))] ) # alpha-beta electrons gen_singl...
def generalized_singles(wires, delta_sz):
r"""Return generalized single excitation terms .. math:: \hat{T_1} = \sum_{pq} t_{p}^{q} \hat{c}^{\dagger}_{q} \hat{c}_{p} """ sz = np.array( [0.5 if (i % 2 == 0) else -0.5 for i in range(len(wires))] ) # alpha-beta electrons gen_singles_wires = [] for r in range(len(wires...
Contains the k-UpCCGSD template. """ # pylint: disable-msg=too-many-branches,too-many-arguments,protected-access import numpy as np import pennylane as qml from pennylane.operation import Operation, AnyWires def generalized_singles(wires, delta_sz):
64
64
200
10
53
therooler/pennylane
pennylane/templates/subroutines/kupccgsd.py
Python
generalized_singles
generalized_singles
23
41
23
23
0a2e8d0e1428d8d9c9d6e068051ab65b4ef709d9
bigcode/the-stack
train
d0d7616245dd9161c7e87270
train
function
def generalized_pair_doubles(wires): r"""Return pair coupled-cluster double excitations .. math:: \hat{T_2} = \sum_{pq} t_{p_\alpha p_\beta}^{q_\alpha, q_\beta} \hat{c}^{\dagger}_{q_\alpha} \hat{c}^{\dagger}_{q_\beta} \hat{c}_{p_\beta} \hat{c}_{p_\alpha} """ pair_gen_doubles_wir...
def generalized_pair_doubles(wires):
r"""Return pair coupled-cluster double excitations .. math:: \hat{T_2} = \sum_{pq} t_{p_\alpha p_\beta}^{q_\alpha, q_\beta} \hat{c}^{\dagger}_{q_\alpha} \hat{c}^{\dagger}_{q_\beta} \hat{c}_{p_\beta} \hat{c}_{p_\alpha} """ pair_gen_doubles_wires = [ [ wires[r ...
and p != r: if r < p: gen_singles_wires.append(wires[r : p + 1]) else: gen_singles_wires.append(wires[p : r + 1][::-1]) return gen_singles_wires def generalized_pair_doubles(wires):
65
65
217
8
56
therooler/pennylane
pennylane/templates/subroutines/kupccgsd.py
Python
generalized_pair_doubles
generalized_pair_doubles
44
61
44
44
15f4eaa085f598ffe5852847e413a5b774696bba
bigcode/the-stack
train
9590cdc5e1c4081edb2b79b1
train
class
class kUpCCGSD(Operation): r"""Implements the k-Unitary Pair Coupled-Cluster Generalized Singles and Doubles (k-UpCCGSD) ansatz. The k-UpCCGSD ansatz calls the :func:`~.FermionicSingleExcitation` and :func:`~.FermionicDoubleExcitation` templates to exponentiate the product of :math:`k` generalized singles ...
class kUpCCGSD(Operation):
r"""Implements the k-Unitary Pair Coupled-Cluster Generalized Singles and Doubles (k-UpCCGSD) ansatz. The k-UpCCGSD ansatz calls the :func:`~.FermionicSingleExcitation` and :func:`~.FermionicDoubleExcitation` templates to exponentiate the product of :math:`k` generalized singles and pair coupled-cluster do...
]) else: gen_singles_wires.append(wires[p : r + 1][::-1]) return gen_singles_wires def generalized_pair_doubles(wires): r"""Return pair coupled-cluster double excitations .. math:: \hat{T_2} = \sum_{pq} t_{p_\alpha p_\beta}^{q_\alpha, q_\beta} \h...
256
256
2,621
8
247
therooler/pennylane
pennylane/templates/subroutines/kupccgsd.py
Python
kUpCCGSD
kUpCCGSD
64
314
64
64
8ff1e558ee8244ceef752cd12e288ec357bd8cf5
bigcode/the-stack
train
b17ce8975f4bd8cea431db50
train
class
class TranspositionTable: def __init__(self): self._init_zobrist_hash() self._table = {} def contains(self, key): key in self._table def insert(self, key, value): self._table[key] = value def value(self, key): self._table[key] def hash_key(self, board): ...
class TranspositionTable:
def __init__(self): self._init_zobrist_hash() self._table = {} def contains(self, key): key in self._table def insert(self, key, value): self._table[key] = value def value(self, key): self._table[key] def hash_key(self, board): """ Find...
import numpy as np from constants import BOARD_SIZE class TranspositionTable:
16
78
263
5
10
lucaspbordignon/goku
src/transposition.py
Python
TranspositionTable
TranspositionTable
5
37
5
5
0eb35ce791b5f310cdf2734cdfc222a133c3cd1a
bigcode/the-stack
train
d86266fdef864a994ce56f85
train
function
def _double_inverted_gaussian(x, amp1, loc1, std1, amp2, loc2, std2): '''This is a double inverted gaussian. Parameters ---------- x : np.array The items at which the Gaussian is evaluated. amp1,amp2 : float The amplitude...
def _double_inverted_gaussian(x, amp1, loc1, std1, amp2, loc2, std2):
'''This is a double inverted gaussian. Parameters ---------- x : np.array The items at which the Gaussian is evaluated. amp1,amp2 : float The amplitude of Gaussian 1 and Gaussian 2. loc1,loc2 : float The central value of Gaussian 1 and Gaussian 2. std1,std2 : flo...
parameters of `amp`, `loc`, and `std`. ''' return amp * np.exp(-((x - loc)*(x - loc))/(2.0*std*std)) def _double_inverted_gaussian(x, amp1, loc1, std1, amp2, loc2, std2):
67
67
226
29
38
pierfra-ro/astrobase
astrobase/lcmodels/eclipses.py
Python
_double_inverted_gaussian
_double_inverted_gaussian
48
80
48
50
b1a4dde1a86a5cb1a2010af4f7bffdfe1355e29d
bigcode/the-stack
train
328ff78c64b6a4cb26b751bb
train
function
def invgauss_eclipses_curvefit_func( times, period, epoch, pdepth, pduration, psdepthratio, secondaryphase, zerolevel=0.0, fixed_params=None, ): '''This is the inv-gauss eclipses function used with scipy.optimize.curve_fit. Parameters ...
def invgauss_eclipses_curvefit_func( times, period, epoch, pdepth, pduration, psdepthratio, secondaryphase, zerolevel=0.0, fixed_params=None, ):
'''This is the inv-gauss eclipses function used with scipy.optimize.curve_fit. Parameters ---------- times : np.array The array of times at which the model will be evaluated. period : float The period of the eclipsing binary. epoch : float The mid eclipse time of the ...
secondary_eclipse_phase = ( (phase >= (secondaryphase - halfduration)) & (phase <= (secondaryphase + halfduration)) ) # put in the eclipses modelmags[primary_eclipse_ingress] = ( zerolevel + _gaussian(phase[primary_eclipse_ingress], primaryecl_amp, ...
256
256
976
52
203
pierfra-ro/astrobase
astrobase/lcmodels/eclipses.py
Python
invgauss_eclipses_curvefit_func
invgauss_eclipses_curvefit_func
195
334
195
205
c413c334b3cb8dd37e6ba869edcafcbf2d8acc12
bigcode/the-stack
train
00ebc0a0673ca45971cc61f4
train
function
def invgauss_eclipses_residual(ebparams, times, mags, errs): '''This returns the residual between the modelmags and the actual mags. Parameters ---------- ebparams : list of float This contains the parameters for the eclipsing binary:: ebparams = [period (time), ...
def invgauss_eclipses_residual(ebparams, times, mags, errs):
'''This returns the residual between the modelmags and the actual mags. Parameters ---------- ebparams : list of float This contains the parameters for the eclipsing binary:: ebparams = [period (time), epoch (time), pdepth: primary e...
ecl_amp, 1.0, primaryecl_std) ) eclipsemodel[primary_eclipse_egress] = ( zerolevel + _gaussian(phase[primary_eclipse_egress], primaryecl_amp, 0.0, primary...
138
138
461
19
118
pierfra-ro/astrobase
astrobase/lcmodels/eclipses.py
Python
invgauss_eclipses_residual
invgauss_eclipses_residual
337
393
337
337
91e90c0b172d740f28ef474201d6832d90581b9d
bigcode/the-stack
train
edb53d7c7dee1fe29a0e5984
train
function
def _gaussian(x, amp, loc, std): '''This is a simple gaussian. Parameters ---------- x : np.array The items at which the Gaussian is evaluated. amp : float The amplitude of the Gaussian. loc : float The central value of the Gaussian. std : float The stand...
def _gaussian(x, amp, loc, std):
'''This is a simple gaussian. Parameters ---------- x : np.array The items at which the Gaussian is evaluated. amp : float The amplitude of the Gaussian. loc : float The central value of the Gaussian. std : float The standard deviation of the Gaussian. ...
(wbhatti@astro.princeton.edu) - Oct 2017 ''' This contains a double gaussian model for first order modeling of eclipsing binaries. ''' import numpy as np ################################## ## MODEL AND RESIDUAL FUNCTIONS ## ################################## def _gaussian(x, amp, loc, std):
64
64
145
12
52
pierfra-ro/astrobase
astrobase/lcmodels/eclipses.py
Python
_gaussian
_gaussian
18
45
18
18
18227d9b4da7019b6fe3df43450ba701f5b1180e
bigcode/the-stack
train
a3abbb8eb5574523307276dd
train
function
def invgauss_eclipses_func(ebparams, times, mags, errs): '''This returns a double eclipse shaped function. Suitable for first order modeling of eclipsing binaries. Parameters ---------- ebparams : list of float This contains the parameters for the eclipsing binary:: ebparams ...
def invgauss_eclipses_func(ebparams, times, mags, errs):
'''This returns a double eclipse shaped function. Suitable for first order modeling of eclipsing binaries. Parameters ---------- ebparams : list of float This contains the parameters for the eclipsing binary:: ebparams = [period (time), epoch (time), ...
x - loc))/(2.0*std*std)) def _double_inverted_gaussian(x, amp1, loc1, std1, amp2, loc2, std2): '''This is a double inverted gaussian. Parameters ---------- x : np.array The items at which the Gaussian is evaluated. amp1,amp2 : ...
256
256
899
18
237
pierfra-ro/astrobase
astrobase/lcmodels/eclipses.py
Python
invgauss_eclipses_func
invgauss_eclipses_func
83
192
83
83
6acb16813b618f52eb9421d5dccb1025b5cc387c
bigcode/the-stack
train
a445269e34fb458e3522fa2a
train
function
def vggBlock(X, weights1, bias1, weights2, bias2): conv1 = nn.conv2d(X, weights1, strides=[1, 1, 1, 1], padding="VALID", data_format="NHWC") conv1_bias = nn.bias_add(conv1, bias1, data_format="NHWC") relu1 = nn.relu(conv1_bias) conv2 = nn.conv2d(relu1, weights2, strides=[1, 1, 1, 1], padding="SAME"...
def vggBlock(X, weights1, bias1, weights2, bias2):
conv1 = nn.conv2d(X, weights1, strides=[1, 1, 1, 1], padding="VALID", data_format="NHWC") conv1_bias = nn.bias_add(conv1, bias1, data_format="NHWC") relu1 = nn.relu(conv1_bias) conv2 = nn.conv2d(relu1, weights2, strides=[1, 1, 1, 1], padding="SAME", data_format="NHWC") conv2_bias = nn.bias_add(...
tensorflow import nn BATCH_SIZE = 32 N = 112 FIN = 3 FOUT = 32 K_Y = 3 K_X = 3 NB_TESTS = 101 def vggBlock(X, weights1, bias1, weights2, bias2):
64
64
212
18
45
akmaru/tiramisu
benchmarks/DNN/blocks/vggBlock/cpu/dense/vgg_block_tensorflow.py
Python
vggBlock
vggBlock
21
32
21
21
c68059c0365fbdba3dc029df1e9a305ed4df0e65
bigcode/the-stack
train
094e6bda6f27bad4e5a2574f
train
class
class Kamael(BaseAgent): def initialize_agent(self): self.controller_state = None #SimpleControllerState() self.me = physicsObject() self.ball = physicsObject() self.me.team = self.team self.allies = [] self.enemies = [] self.start = 5 self.flipStart ...
class Kamael(BaseAgent):
def initialize_agent(self): self.controller_state = None #SimpleControllerState() self.me = physicsObject() self.ball = physicsObject() self.me.team = self.team self.allies = [] self.enemies = [] self.start = 5 self.flipStart = 0 self.flipping ...
import math from rlbot.agents.base_agent import BaseAgent, SimpleControllerState from rlbot.utils.structures.game_data_struct import GameTickPacket from rlbot.utils.game_state_util import GameState, BallState, CarState, Physics, Vector3 as vector3, Rotator from Utilities import * from States import * import cProfile, p...
196
256
3,011
6
189
RLMarvin/RLBotPack
RLBotPack/Kamael/Kamael.py
Python
Kamael
Kamael
32
363
32
33
26f48f09a2355733e9dc904b771ed7db51779168
bigcode/the-stack
train
d57cb1f8d791ae78671fafb2
train
function
def profile(fnc): """A decorator that uses cProfile to profile a function""" def inner(*args, **kwargs): pr = cProfile.Profile() pr.enable() retval = fnc(*args, **kwargs) pr.disable() s = io.StringIO() sortby = 'cumulative' ps = pstats.Stats(pr, stream=s)...
def profile(fnc):
"""A decorator that uses cProfile to profile a function""" def inner(*args, **kwargs): pr = cProfile.Profile() pr.enable() retval = fnc(*args, **kwargs) pr.disable() s = io.StringIO() sortby = 'cumulative' ps = pstats.Stats(pr, stream=s).sort_stats(sortby...
import GameTickPacket from rlbot.utils.game_state_util import GameState, BallState, CarState, Physics, Vector3 as vector3, Rotator from Utilities import * from States import * import cProfile, pstats, io import time from numba import jit def profile(fnc):
64
64
104
5
58
RLMarvin/RLBotPack
RLBotPack/Kamael/Kamael.py
Python
profile
profile
13
28
13
13
71d169409e6b96ff00454532bb4c88c065d89e5e
bigcode/the-stack
train
a6a3d150732a8dd8e2f48860
train
function
def settings(subparsers) -> None: """Create YAML settings to use with `torchlambda template --yaml`.""" description = "Create YAML settings to use with `torchlambda template --yaml`\n" "This is the easiest way to deploy model, just modify default settings provided by this comand.\n" "Not all provided f...
def settings(subparsers) -> None:
"""Create YAML settings to use with `torchlambda template --yaml`.""" description = "Create YAML settings to use with `torchlambda template --yaml`\n" "This is the easiest way to deploy model, just modify default settings provided by this comand.\n" "Not all provided fields are required, please see: ht...
import argparse def settings(subparsers) -> None:
12
64
178
9
2
medric49/torchlambda
torchlambda/arguments/subparsers.py
Python
settings
settings
4
23
4
4
f22d78d9e8042e68007a8aff6a021c36a0630219
bigcode/the-stack
train
db73fc303ffdc10f2ede587d
train
function
def template(subparsers) -> None: """Create C++ source code template used for model inference.""" description = ( "Create C++ deployment code scheme with AWS Lambda C++ SDK and PyTorch.\n" "In general users are advised to stick to YAML settings (--yaml) flag.\n" "Not all YAML fields are...
def template(subparsers) -> None:
"""Create C++ source code template used for model inference.""" description = ( "Create C++ deployment code scheme with AWS Lambda C++ SDK and PyTorch.\n" "In general users are advised to stick to YAML settings (--yaml) flag.\n" "Not all YAML fields are required, please see: https://git...
description=description, help=description, formatter_class=argparse.RawTextHelpFormatter, ) parser.add_argument( "--destination", required=False, default="./torchlambda.yaml", help="""Path to file where YAML settings will be stored. Default: "./torchlambd...
76
76
256
9
67
medric49/torchlambda
torchlambda/arguments/subparsers.py
Python
template
template
26
56
26
26
c7422e608e09d7c3d7b78ba79378cdd4145a2d12
bigcode/the-stack
train
6d6da50ef9d2c3267230f14b
train
function
def layer(subparsers) -> None: """Pack model as .zip file ready to deploy on AWS Lambda as layer.""" description = "Pack model as .zip file ready to deploy on AWS Lambda as layer." parser = subparsers.add_parser( "layer", description=description, help=description, formatter_c...
def layer(subparsers) -> None:
"""Pack model as .zip file ready to deploy on AWS Lambda as layer.""" description = "Pack model as .zip file ready to deploy on AWS Lambda as layer." parser = subparsers.add_parser( "layer", description=description, help=description, formatter_class=argparse.RawTextHelpFormat...
"--docker-run", required=False, help="Flags passed to docker run command (code deployment building).\n" "Flags should be passed as space separated string, e.g.\n" """--name deployment --mount source=myvol2,target=/home/app".\n""" 'If you want to pass a single flag you should add...
161
161
538
9
152
medric49/torchlambda
torchlambda/arguments/subparsers.py
Python
layer
layer
225
282
225
225
0d5eaecde5b41627160f1591f5a03e7643aa6507
bigcode/the-stack
train
59c517438b80333ef0149963
train
function
def build(subparsers) -> None: """Perform deployment of PyTorch C++ code to AWS Lambda.""" description = "Obtain AWS Lambda ready .zip package from C++ deployment source code and Torchscript compiled model.\n" "See following resources for more information:\n" "- Torchscript documentation: https://pytorc...
def build(subparsers) -> None:
"""Perform deployment of PyTorch C++ code to AWS Lambda.""" description = "Obtain AWS Lambda ready .zip package from C++ deployment source code and Torchscript compiled model.\n" "See following resources for more information:\n" "- Torchscript documentation: https://pytorch.org/docs/stable/jit.html\n" ...
"""Create C++ source code template used for model inference.""" description = ( "Create C++ deployment code scheme with AWS Lambda C++ SDK and PyTorch.\n" "In general users are advised to stick to YAML settings (--yaml) flag.\n" "Not all YAML fields are required, please see: https://git...
256
256
1,677
9
247
medric49/torchlambda
torchlambda/arguments/subparsers.py
Python
build
build
59
222
59
59
9ab67da8d2fd1598bbe39cafa3d8184ed00e381b
bigcode/the-stack
train
a0de70d1fcc427850482b7a9
train
class
class RMatrixmodels(RPackage): """Modelling with sparse and dense 'Matrix' matrices, using modular prediction and response module classes.""" homepage = "http://matrix.r-forge.r-project.org/" url = "https://cran.r-project.org/src/contrib/MatrixModels_0.4-1.tar.gz" list_url = "https://cran.r-pr...
class RMatrixmodels(RPackage):
"""Modelling with sparse and dense 'Matrix' matrices, using modular prediction and response module classes.""" homepage = "http://matrix.r-forge.r-project.org/" url = "https://cran.r-project.org/src/contrib/MatrixModels_0.4-1.tar.gz" list_url = "https://cran.r-project.org/src/contrib/Archive/M...
a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class RMatrixmodels(RPackage):
64
64
137
7
57
HPCToolkit/hpctest
internal/notes/builtin-SAVE/packages/r-matrixmodels/package.py
Python
RMatrixmodels
RMatrixmodels
28
38
28
28
78c86b4ecdacd5b45c098617f8610d365b94a117
bigcode/the-stack
train
6d4e0fd1cdf5d3e4a128dffe
train
class
class Migration(migrations.Migration): dependencies = [ ('app', '0042_doctor_telephone'), ] operations = [ migrations.AlterModelOptions( name='medicationstatus', options={'ordering': ('time',)}, ), migrations.RemoveField( model_name='medi...
class Migration(migrations.Migration):
dependencies = [ ('app', '0042_doctor_telephone'), ] operations = [ migrations.AlterModelOptions( name='medicationstatus', options={'ordering': ('time',)}, ), migrations.RemoveField( model_name='medicationstatus', name='hour', ...
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-04-11 00:04 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):
54
64
108
7
46
cqw1/palliassist_webportal
app/migrations/0043_auto_20170410_1904.py
Python
Migration
Migration
8
28
8
9
4a5b5e5534be79fbcc62026d6db127bfb0588567
bigcode/the-stack
train
b439baf4610ff1b7af59ab5c
train
function
def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'IEMP_Satellite.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's in...
def main():
"""Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'IEMP_Satellite.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and ...
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main():
26
64
101
3
22
qc5111/IEMP
IEMP_Satellite/manage.py
Python
main
main
7
18
7
7
c4662ceb7ee9640b2b584271bda71bb795a3e0b0
bigcode/the-stack
train
9a87e109bb822c5f295e1a85
train
class
@pytest.mark.skipif(not IS_PYTHON3, reason="requires python3.4 or above") class TestAsyncioClient(object): def test_protocol_connection_state_propagation_to_factory(self): protocol = ModbusClientProtocol() assert protocol.factory is None assert protocol.transport is None assert not p...
@pytest.mark.skipif(not IS_PYTHON3, reason="requires python3.4 or above") class TestAsyncioClient(object):
def test_protocol_connection_state_propagation_to_factory(self): protocol = ModbusClientProtocol() assert protocol.factory is None assert protocol.transport is None assert not protocol._connected protocol.factory = mock.MagicMock() protocol.connection_made(mock.sent...
from pymodbus.compat import IS_PYTHON3, PYTHON_VERSION import pytest if IS_PYTHON3 and PYTHON_VERSION >= (3, 4): from unittest import mock from pymodbus.client.asynchronous.asyncio import ( ReconnectingAsyncioModbusTcpClient, ModbusClientProtocol, ModbusUdpClientProtocol) from test.asyncio_t...
202
256
2,216
28
174
sumpfralle/pymodbus
test/test_client_async_asyncio.py
Python
TestAsyncioClient
TestAsyncioClient
19
276
19
20
28866d35d17d2982b6dabd9416f326f920f99cf1
bigcode/the-stack
train
1fe07e2d63e2c6a0cb49cf9b
train
function
def plotLines(X, q0, q1, color): for i in range(X.shape[0]-1): ql = q0[i] - q1[i] qr = q0[i] + q1[i] pylab.plot([X[i], X[i+1]], [ql, qr], color)
def plotLines(X, q0, q1, color):
for i in range(X.shape[0]-1): ql = q0[i] - q1[i] qr = q0[i] + q1[i] pylab.plot([X[i], X[i+1]], [ql, qr], color)
rcParams['image.interpolation'] = 'none' rcParams['image.origin'] = 'lower' rcParams['contour.negative_linestyle'] = 'solid' #rcParams['savefig.bbox'] = 'tight' def plotLines(X, q0, q1, color):
64
64
70
13
51
ammarhakim/ammar-simjournal
sims/s332/plot-diffuse.py
Python
plotLines
plotLines
23
27
23
23
3a337f4b2faf5c995718353aa06a6d97012b5c1d
bigcode/the-stack
train
426cee78769883ac277fb6ee
train
function
def calcDeriv(T, val): dVal = numpy.zeros((T.shape[0]-1,), numpy.float) tVal = numpy.zeros((T.shape[0]-1,), numpy.float) for i in range(T.shape[0]-1): tVal[i] = 0.5*(T[i]+T[i+1]) vAv = 0.5*(val[i+1]+val[i]) dVal[i] = (val[i+1]-val[i])/(T[i+1]-T[i]) return tVal, dVal
def calcDeriv(T, val):
dVal = numpy.zeros((T.shape[0]-1,), numpy.float) tVal = numpy.zeros((T.shape[0]-1,), numpy.float) for i in range(T.shape[0]-1): tVal[i] = 0.5*(T[i]+T[i+1]) vAv = 0.5*(val[i+1]+val[i]) dVal[i] = (val[i+1]-val[i])/(T[i+1]-T[i]) return tVal, dVal
for i in range(X.shape[0]-1): ql = q0[i] - q1[i] qr = q0[i] + q1[i] pylab.plot([X[i], X[i+1]], [ql, qr], color) def calcDeriv(T, val):
64
64
123
8
56
ammarhakim/ammar-simjournal
sims/s332/plot-diffuse.py
Python
calcDeriv
calcDeriv
29
36
29
29
cc8fe026f8f51c8104dd0b0cc2cbe2de7aa443c9
bigcode/the-stack
train
9a083336d8ba44a4df99112c
train
function
def exactSol(X, tend): return pylab.exp(-alpha*tend)*numpy.sin(X)
def exactSol(X, tend):
return pylab.exp(-alpha*tend)*numpy.sin(X)
0[:,1], '-r') plotLines(X, q[:,0], q[:,1], '-k') fh = tables.openFile(baseName+"_src.h5") src = fh.root.StructGridField plotLines(X, src[:,0], src[:,1], '--og') def exactSol(X, tend):
64
64
21
7
57
ammarhakim/ammar-simjournal
sims/s332/plot-diffuse.py
Python
exactSol
exactSol
65
66
65
65
9807e87cb7a2d7ef8d6325ecd37d169f6be46c22
bigcode/the-stack
train
177ba2ce14f738567bf32efa
train
function
def exactSolSS(X): return numpy.sin(X)
def exactSolSS(X):
return numpy.sin(X)
k') fh = tables.openFile(baseName+"_src.h5") src = fh.root.StructGridField plotLines(X, src[:,0], src[:,1], '--og') def exactSol(X, tend): return pylab.exp(-alpha*tend)*numpy.sin(X) def exactSolSS(X):
64
64
12
6
58
ammarhakim/ammar-simjournal
sims/s332/plot-diffuse.py
Python
exactSolSS
exactSolSS
68
69
68
68
4ad5a398b371a985833145c5c35fd99a3cc04b88
bigcode/the-stack
train
174dae370296385f2d9d9320
train
class
class YGMTest(unittest.TestCase): def setUp(self) -> None: return super().setUp() def tearDown(self) -> None: return super().tearDown() def test_read_config_positive(self) -> None: ACCOUNT = "chris@example.com" PASSWORD = "p@ssw0rd!" PORT = 1919 SERVER = "s...
class YGMTest(unittest.TestCase):
def setUp(self) -> None: return super().setUp() def tearDown(self) -> None: return super().tearDown() def test_read_config_positive(self) -> None: ACCOUNT = "chris@example.com" PASSWORD = "p@ssw0rd!" PORT = 1919 SERVER = "smpt.example.com" TO = "['ma...
#!/usr/bin/env python3 import sys import unittest from io import BytesIO, StringIO from json import JSONDecodeError from unittest.mock import MagicMock sys.modules["picamera"] = MagicMock() sys.modules["RPi"] = MagicMock() sys.modules["RPi.GPIO"] = MagicMock() from ygm import YouveGotMail class YGMTest(unittest.Test...
84
163
544
8
75
cplyon/youvegotmail
test_ygm.py
Python
YGMTest
YGMTest
16
73
16
17
c32f76e1143373d44f1582d0ccaecd2abe1a8034
bigcode/the-stack
train
a0dcf3a98c61cd3d19b9e3ef
train
function
def write_data(): last_update: datetime = datetime.now() last_update_str: str = f'const last_update = "{datetime_to_str(last_update)}"; \n' with open("../Web/data/latest_data.js", "w+", encoding="utf-8") as js: js.write(last_update_str) js.write(f"const data = ") json.dump(all_resul...
def write_data():
last_update: datetime = datetime.now() last_update_str: str = f'const last_update = "{datetime_to_str(last_update)}"; \n' with open("../Web/data/latest_data.js", "w+", encoding="utf-8") as js: js.write(last_update_str) js.write(f"const data = ") json.dump(all_result, js, indent=' '...
_datetime import datetime, timedelta import json all_result: dict = {} def handler_selector(shop_name: str, url: str, contents: str): if "www.facebook.com/pg/" in url: all_result.update(analysis_fb_page(shop_name, contents, url)) def write_data():
64
64
110
4
60
BigtoC/Hong-Kong-Facemask-On-Sale
Crawler/data_handler.py
Python
write_data
write_data
17
27
17
17
41ed3d010e34ae5b1dbca04bcb313c03636eb6a3
bigcode/the-stack
train
48a3a508a30d4d9701942411
train
function
def handler_selector(shop_name: str, url: str, contents: str): if "www.facebook.com/pg/" in url: all_result.update(analysis_fb_page(shop_name, contents, url))
def handler_selector(shop_name: str, url: str, contents: str):
if "www.facebook.com/pg/" in url: all_result.update(analysis_fb_page(shop_name, contents, url))
# coding=utf-8 from Crawler.handle_fb_page import analysis_fb_page from Crawler.util import * from _datetime import datetime, timedelta import json all_result: dict = {} def handler_selector(shop_name: str, url: str, contents: str):
56
64
43
16
40
BigtoC/Hong-Kong-Facemask-On-Sale
Crawler/data_handler.py
Python
handler_selector
handler_selector
12
14
12
12
8c13a1028f590611c564c8fa78f9d4ba761d3730
bigcode/the-stack
train
c485c9ba5f53e49c5242eecc
train
function
def test_info_metrics_present(kubectl, apply_gunicorn, port_forward): port_forward('test-pod', '8080') time.sleep(0.5) r = requests.get('http://localhost:8080/metrics') assert r.status_code == 200 found = False print(r.text) for family in text_string_to_metric_families(r.text): if fa...
def test_info_metrics_present(kubectl, apply_gunicorn, port_forward):
port_forward('test-pod', '8080') time.sleep(0.5) r = requests.get('http://localhost:8080/metrics') assert r.status_code == 200 found = False print(r.text) for family in text_string_to_metric_families(r.text): if family.name == 'userspace_exporter_enabled_programs': found ...
# If the apply_gunicorn fixture succeeds, the pod will have gone into # ready. This test is really just here to make it easy to surface failures # in apply_gunicorn pass def test_info_metrics_present(kubectl, apply_gunicorn, port_forward):
64
64
160
17
46
josecv/ebpf-usdt-exporter
integration/usdt_counter_test.py
Python
test_info_metrics_present
test_info_metrics_present
24
39
24
24
cc4213863ef6b5e4acf73be2652d4908cffc0e28
bigcode/the-stack
train
6142bb5fdd168363593ae497
train
function
def test_counter_is_reported(kubectl, apply_gunicorn, port_forward): port_forward('test-pod', '5000') port_forward('test-pod', '8080') time.sleep(0.5) with ThreadPoolExecutor(max_workers=4) as executor: list( executor.map(lambda _: requests.get('http://localhost:5000/'), ...
def test_counter_is_reported(kubectl, apply_gunicorn, port_forward):
port_forward('test-pod', '5000') port_forward('test-pod', '8080') time.sleep(0.5) with ThreadPoolExecutor(max_workers=4) as executor: list( executor.map(lambda _: requests.get('http://localhost:5000/'), range(1000))) r = requests.get('http://localhost:808...
found = True assert len(family.samples) == 5 for sample in family.samples: assert 'pid' in sample.labels assert sample.labels['name'] == 'gc_total' assert sample.value == 1.0 assert found, r.text def test_counter_is_reported(kubectl, apply_gun...
78
78
261
18
59
josecv/ebpf-usdt-exporter
integration/usdt_counter_test.py
Python
test_counter_is_reported
test_counter_is_reported
42
67
42
42
0f47e4274b834b955583aca7fce261c2e5cda56c
bigcode/the-stack
train
e25c5fe421c376b382ab6f5d
train
function
@pytest.fixture() def apply_gunicorn(kubectl, apply_manifest, get_manifest_path, wait_for_pod_ready): manifest = get_manifest_path('gunicorn.yaml') apply_manifest(manifest) wait_for_pod_ready('test-pod', timeout='60s')
@pytest.fixture() def apply_gunicorn(kubectl, apply_manifest, get_manifest_path, wait_for_pod_ready):
manifest = get_manifest_path('gunicorn.yaml') apply_manifest(manifest) wait_for_pod_ready('test-pod', timeout='60s')
import time from concurrent.futures import ThreadPoolExecutor import pytest import requests from prometheus_client.parser import text_string_to_metric_families @pytest.fixture() def apply_gunicorn(kubectl, apply_manifest, get_manifest_path, wait_for_pod_ready):
58
64
59
26
31
josecv/ebpf-usdt-exporter
integration/usdt_counter_test.py
Python
apply_gunicorn
apply_gunicorn
9
14
9
11
4d5e4b2e02a063cd663ebb5dd56ee52d4c7307d1
bigcode/the-stack
train
afcd1592a63dc304e99deb7a
train
function
def test_pod_goes_ready(apply_gunicorn): # If the apply_gunicorn fixture succeeds, the pod will have gone into # ready. This test is really just here to make it easy to surface failures # in apply_gunicorn pass
def test_pod_goes_ready(apply_gunicorn): # If the apply_gunicorn fixture succeeds, the pod will have gone into # ready. This test is really just here to make it easy to surface failures # in apply_gunicorn
pass
od', timeout='60s') def test_pod_goes_ready(apply_gunicorn): # If the apply_gunicorn fixture succeeds, the pod will have gone into # ready. This test is really just here to make it easy to surface failures # in apply_gunicorn
64
64
60
57
7
josecv/ebpf-usdt-exporter
integration/usdt_counter_test.py
Python
test_pod_goes_ready
test_pod_goes_ready
17
21
17
20
e05d098cb9cc4edfd3bd2c4f91d9f30ddeef0829
bigcode/the-stack
train
8adbda0fcf68332da75065f4
train
function
def flush(trypath): prints = [] for name, vals in _since_last_flush.items(): prints.append("{}\t{}".format(name, np.mean(vals.values()))) _since_beginning[name].update(vals) x_vals = np.sort(_since_beginning[name].keys()) y_vals = [_since_beginning[name][x] for x in x_vals] plt.clf() plt.plot(x_vals, y...
def flush(trypath):
prints = [] for name, vals in _since_last_flush.items(): prints.append("{}\t{}".format(name, np.mean(vals.values()))) _since_beginning[name].update(vals) x_vals = np.sort(_since_beginning[name].keys()) y_vals = [_since_beginning[name][x] for x in x_vals] plt.clf() plt.plot(x_vals, y_vals) plt.xlabel(...
') _since_beginning = collections.defaultdict(lambda: {}) _since_last_flush = collections.defaultdict(lambda: {}) _iter = [0] def tick(): _iter[0] += 1 def plot(name, value): _since_last_flush[name][_iter[0]] = value def flush(trypath):
64
64
181
6
57
hebowei2000/OODP
xplot.py
Python
flush
flush
23
43
23
23
9ede529282367953773963dcf5a2b72336579ea7
bigcode/the-stack
train
75171440c70f2460bbf9e487
train
function
def tick(): _iter[0] += 1
def tick():
_iter[0] += 1
import matplotlib.pyplot as plt import collections import time import pickle import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s') _since_beginning = collections.defaultdict(lambda: {}) _since_last_flush = collections.defaultdict(lambda: {}) _iter = [0] def tick():
64
64
12
3
61
hebowei2000/OODP
xplot.py
Python
tick
tick
17
18
17
17
34f2bcb6d366194e9915d7cbc5076837204e5483
bigcode/the-stack
train
ea1e3cc3d3d93430c88eee11
train
function
def plot(name, value): _since_last_flush[name][_iter[0]] = value
def plot(name, value):
_since_last_flush[name][_iter[0]] = value
import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s') _since_beginning = collections.defaultdict(lambda: {}) _since_last_flush = collections.defaultdict(lambda: {}) _iter = [0] def tick(): _iter[0] += 1 def plot(name, value):
64
64
19
6
57
hebowei2000/OODP
xplot.py
Python
plot
plot
20
21
20
20
161ec7fad3437f94c966efff79801449067e1cbb
bigcode/the-stack
train
870b4b2e9093eb21f6ca6ceb
train
function
def write(): now = datetime.now(); separator = '-' timestring = str(now.hour) + separator + str(now.minute) + separator + str(now.second) + separator + str(now.day) + separator +str(now.month) + separator + str(now.year) filename = str("pikabu " + timestring + '.txt') outputFile = open(filename, "a...
def write():
now = datetime.now(); separator = '-' timestring = str(now.hour) + separator + str(now.minute) + separator + str(now.second) + separator + str(now.day) + separator +str(now.month) + separator + str(now.year) filename = str("pikabu " + timestring + '.txt') outputFile = open(filename, "a") count...
content = request.read() encoding = chardet.detect(content)['encoding'] print('Encoding Website: ' + str(encoding)) print('Encoding Console: ' + str(sys.stdout.encoding)) html = content.decode(encoding) parser = MyHTMLParser() parser.feed(html) def write():
64
64
154
3
61
maxter2323/Python-Small-Examples
pikabu.py
Python
write
write
49
65
49
49
eff8428c99c46f2aad0c620ddac635a3adfd9f68
bigcode/the-stack
train
f83215f479658d8ef9cf404d
train
function
def proceed(): request = urllib.request.urlopen(pikabuUrl) content = request.read() encoding = chardet.detect(content)['encoding'] print('Encoding Website: ' + str(encoding)) print('Encoding Console: ' + str(sys.stdout.encoding)) html = content.decode(encoding) parser = MyHTMLParser() ...
def proceed():
request = urllib.request.urlopen(pikabuUrl) content = request.read() encoding = chardet.detect(content)['encoding'] print('Encoding Website: ' + str(encoding)) print('Encoding Console: ' + str(sys.stdout.encoding)) html = content.decode(encoding) parser = MyHTMLParser() parser.feed(htm...
tag == newsTag and self.weAreIn == True: links.append( attr[1]) self.readData = True def handle_data(self, data): if self.readData: headers.append(data) self.weAreIn = False self.readData = False def proceed():
64
64
76
3
60
maxter2323/Python-Small-Examples
pikabu.py
Python
proceed
proceed
37
47
37
37
5ad4dbf6b81a5df4151d01180d4c3221f17ec380
bigcode/the-stack
train
b6d94e69dfc7dd7a9fe89f39
train
class
class MyHTMLParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.readData = False self.weAreIn = False def handle_starttag(self, tag, attrs): for attr in attrs: if attr[0] == classTag: if attr[1] == startTag: sel...
class MyHTMLParser(HTMLParser):
def __init__(self): HTMLParser.__init__(self) self.readData = False self.weAreIn = False def handle_starttag(self, tag, attrs): for attr in attrs: if attr[0] == classTag: if attr[1] == startTag: self.weAreIn = True if tag =...
from datetime import datetime pikabuUrl = 'http://pikabu.ru/top50_comm.php' startTag = 'profile_commented' endTag = 'b-sidebar-sticky' newsTag = 'a' classTag = 'class' headers = [] links = [] class MyHTMLParser(HTMLParser):
64
64
146
8
56
maxter2323/Python-Small-Examples
pikabu.py
Python
MyHTMLParser
MyHTMLParser
15
35
15
16
785b537a68970b6e6d3b7505815492a83223925e
bigcode/the-stack
train
155fa60656cb38d197fd6539
train
function
def keras_name_to_tf_name_stem_top(keras_name, use_ema=True, model_name_tf='efficientnet-b0'): """Mapping name in h5 to ckpt that is in stem or top (head). we map name keras_name that points to a weight in h5 file to a name of weight in ckpt f...
def keras_name_to_tf_name_stem_top(keras_name, use_ema=True, model_name_tf='efficientnet-b0'):
"""Mapping name in h5 to ckpt that is in stem or top (head). we map name keras_name that points to a weight in h5 file to a name of weight in ckpt file. Args: keras_name: str, the name of weight in the h5 file of keras implementation use_ema: Bool, use the ExponentialMovingAverage resuolt in ckpt or n...
.split('/')[1] for x in tf_weight_names if 'block' in x} # sort by number tf_blocks = sorted(tf_blocks, key=lambda x: int(x.split('_')[1])) return tf_blocks def get_keras_blocks(keras_weight_names): """Extract the block names from list of full weight names.""" # example: 'block1a_dwconv/depthwise_kernel:0' ...
154
154
514
29
125
ashutom/tensorflow-upstream
tensorflow/python/keras/applications/efficientnet_weight_update_util.py
Python
keras_name_to_tf_name_stem_top
keras_name_to_tf_name_stem_top
156
205
156
158
1b9dd4d59afdf16f3bd2cf2a07a9fd702129ccaa
bigcode/the-stack
train
428dc36712245df397c1c1a1
train
function
def get_tf_blocks(tf_weight_names): """Extract the block names from list of full weight names.""" # Example: 'efficientnet-b0/blocks_0/conv2d/kernel' -> 'blocks_0' tf_blocks = {x.split('/')[1] for x in tf_weight_names if 'block' in x} # sort by number tf_blocks = sorted(tf_blocks, key=lambda x: int(x.split('_...
def get_tf_blocks(tf_weight_names):
"""Extract the block names from list of full weight names.""" # Example: 'efficientnet-b0/blocks_0/conv2d/kernel' -> 'blocks_0' tf_blocks = {x.split('/')[1] for x in tf_weight_names if 'block' in x} # sort by number tf_blocks = sorted(tf_blocks, key=lambda x: int(x.split('_')[1])) return tf_blocks
x for x in v_name_all if 'ExponentialMovingAverage' not in x] # remove util variables used for RMSprop v_name_all = [x for x in v_name_all if 'RMS' not in x] return v_name_all def get_tf_blocks(tf_weight_names):
64
64
100
8
55
ashutom/tensorflow-upstream
tensorflow/python/keras/applications/efficientnet_weight_update_util.py
Python
get_tf_blocks
get_tf_blocks
140
146
140
140
5674370bdbbe48dd8b43918afa46c1d851382f35
bigcode/the-stack
train
6dfe7bca34efed4560ae1153
train
function
def get_keras_blocks(keras_weight_names): """Extract the block names from list of full weight names.""" # example: 'block1a_dwconv/depthwise_kernel:0' -> 'block1a' keras_blocks = {x.split('_')[0] for x in keras_weight_names if 'block' in x} return sorted(keras_blocks)
def get_keras_blocks(keras_weight_names):
"""Extract the block names from list of full weight names.""" # example: 'block1a_dwconv/depthwise_kernel:0' -> 'block1a' keras_blocks = {x.split('_')[0] for x in keras_weight_names if 'block' in x} return sorted(keras_blocks)
tf_blocks = {x.split('/')[1] for x in tf_weight_names if 'block' in x} # sort by number tf_blocks = sorted(tf_blocks, key=lambda x: int(x.split('_')[1])) return tf_blocks def get_keras_blocks(keras_weight_names):
64
64
77
10
53
ashutom/tensorflow-upstream
tensorflow/python/keras/applications/efficientnet_weight_update_util.py
Python
get_keras_blocks
get_keras_blocks
149
153
149
149
e85b18d4ea62df2e7c7602ba92225601f48aab66
bigcode/the-stack
train
bb9afaaa2a89677247a15525
train
function
def check_match(keras_block, tf_block, keras_weight_names, tf_weight_names, model_name_tf): """Check if the weights in h5 and ckpt match. we match each name from keras_weight_names that is in keras_block and check if there is 1-1 correspondence to names from tf_weight_names that is in tf_block ...
def check_match(keras_block, tf_block, keras_weight_names, tf_weight_names, model_name_tf):
"""Check if the weights in h5 and ckpt match. we match each name from keras_weight_names that is in keras_block and check if there is 1-1 correspondence to names from tf_weight_names that is in tf_block Args: keras_block: str, the block name for keras implementation (e.g. 'block1a') tf_block: str, t...
tf_name.append('tpu_batch_normalization') else: tf_name.append('tpu_batch_normalization_1') for x in ['moving_mean', 'moving_variance', 'beta', 'gamma']: if x in keras_name: tf_name.append(x) if use_ema: tf_name.append('ExponentialMovingAverage') return '/'.join(tf_name)...
106
106
356
23
83
ashutom/tensorflow-upstream
tensorflow/python/keras/applications/efficientnet_weight_update_util.py
Python
check_match
check_match
295
333
295
296
668ab9dc572e9300b0a1b33ceabcdbdb8ad73e72
bigcode/the-stack
train
08fa0cc17862bf0f3a882a4e
train
function
def get_variable_names_from_ckpt(path_ckpt, use_ema=True): """Get list of tensor names from checkpoint. Args: path_ckpt: str, path to the ckpt files use_ema: Bool, whether to use ExponentialMovingAverage result or not. Returns: List of variable names from checkpoint. """ v_all = tf.train.list_var...
def get_variable_names_from_ckpt(path_ckpt, use_ema=True):
"""Get list of tensor names from checkpoint. Args: path_ckpt: str, path to the ckpt files use_ema: Bool, whether to use ExponentialMovingAverage result or not. Returns: List of variable names from checkpoint. """ v_all = tf.train.list_variables(path_ckpt) # keep name only v_name_all = [x[0] ...
Fail to load {} from {}'.format(w.name, tf_name)) total_weights = len(keras_model.weights) print('{}/{} weights updated'.format(changed_weights, total_weights)) keras_model.save_weights(path_h5) def get_variable_names_from_ckpt(path_ckpt, use_ema=True):
64
64
202
16
48
ashutom/tensorflow-upstream
tensorflow/python/keras/applications/efficientnet_weight_update_util.py
Python
get_variable_names_from_ckpt
get_variable_names_from_ckpt
116
137
116
116
344dd3bab32a63a57d3c2ec0f29ff3f3bb33dd32
bigcode/the-stack
train
6d32409c276fcd3763ead76e
train
function
def write_ckpt_to_h5(path_h5, path_ckpt, keras_model, use_ema=True): """Map the weights in checkpoint file (tf) to h5 file (keras). Args: path_h5: str, path to output hdf5 file to write weights loaded from ckpt files. path_ckpt: str, path to the ckpt files (e.g. 'efficientnet-b0/model.ckpt') th...
def write_ckpt_to_h5(path_h5, path_ckpt, keras_model, use_ema=True):
"""Map the weights in checkpoint file (tf) to h5 file (keras). Args: path_h5: str, path to output hdf5 file to write weights loaded from ckpt files. path_ckpt: str, path to the ckpt files (e.g. 'efficientnet-b0/model.ckpt') that records efficientnet weights from original repo https://gith...
0.tar.gz) # to update weight without top layers, saving to efficientnetb0_notop.h5 python efficientnet_weight_update_util.py --model b0 --notop \ --ckpt efficientnet-b0/model.ckpt --o efficientnetb0_notop.h5 # use checkpoint noisy_student_efficientnet-b3/model.ckpt (providing # improved result for b3, can be downl...
221
221
737
23
197
ashutom/tensorflow-upstream
tensorflow/python/keras/applications/efficientnet_weight_update_util.py
Python
write_ckpt_to_h5
write_ckpt_to_h5
46
113
46
46
04c198cf0ab85bf55ffcfa8c967b6c10d323f457
bigcode/the-stack
train
531707678b9494dbe0e59954
train
function
def keras_name_to_tf_name_block(keras_name, keras_block='block1a', tf_block='blocks_0', use_ema=True, model_name_tf='efficientnet-b0'): """Mapping name in h5 to ckpt that belongs to a block....
def keras_name_to_tf_name_block(keras_name, keras_block='block1a', tf_block='blocks_0', use_ema=True, model_name_tf='efficientnet-b0'):
"""Mapping name in h5 to ckpt that belongs to a block. we map name keras_name that points to a weight in h5 file to a name of weight in ckpt file. Args: keras_name: str, the name of weight in the h5 file of keras implementation keras_block: str, the block name for keras implementation (e.g. 'block1a')...
', 'moving_variance']: tf_name = '{}/stem/tpu_batch_normalization/{}{}'.format( model_name_tf, bn_weights, ema) stem_top_dict['stem_bn/{}:0'.format(bn_weights)] = tf_name # top / head batch normalization for bn_weights in ['beta', 'gamma', 'moving_mean', 'moving_variance']: tf_name = '{}/head/t...
209
209
699
43
166
ashutom/tensorflow-upstream
tensorflow/python/keras/applications/efficientnet_weight_update_util.py
Python
keras_name_to_tf_name_block
keras_name_to_tf_name_block
208
292
208
212
e5aea167ac0ee9b8e15a293fe9c5e3223e57ff1b
bigcode/the-stack
train
8f5b8861af9472b54306239b
train
function
def test_parse_row(csv_entry): with io.open('./tests/test.zip', 'rb') as fp: unzipped = unzip_request_content(fp.read()) parsed_row = next(parse_row(unzipped)).replace('\r\n', '') assert parsed_row == csv_entry
def test_parse_row(csv_entry):
with io.open('./tests/test.zip', 'rb') as fp: unzipped = unzip_request_content(fp.read()) parsed_row = next(parse_row(unzipped)).replace('\r\n', '') assert parsed_row == csv_entry
() # Tests unit def test_unzip_request_content(): assert not unzip_request_content(b'') with io.open('./tests/test.zip', 'rb') as fp: unzipped = unzip_request_content(fp.read()) assert isinstance(unzipped, ZipFile) def test_parse_row(csv_entry):
64
64
59
7
57
Leovilhena/pbjs-evaluator
tests/unit_test.py
Python
test_parse_row
test_parse_row
48
55
48
49
99c49fc55dc0f0e5aca643c8ac3ed706bde7f1ad
bigcode/the-stack
train
07b1461ae2347b332209d5d2
train
function
def test_parse_url(result_url_str): with io.open('./tests/test.zip', 'rb') as fp: unzipped = unzip_request_content(fp.read()) parsed_row = next(parse_row(unzipped)).replace('\r\n', '') parsed_result = parse_url(parsed_row) assert parsed_result == result_url_str
def test_parse_url(result_url_str):
with io.open('./tests/test.zip', 'rb') as fp: unzipped = unzip_request_content(fp.read()) parsed_row = next(parse_row(unzipped)).replace('\r\n', '') parsed_result = parse_url(parsed_row) assert parsed_result == result_url_str
_row(csv_entry): with io.open('./tests/test.zip', 'rb') as fp: unzipped = unzip_request_content(fp.read()) parsed_row = next(parse_row(unzipped)).replace('\r\n', '') assert parsed_row == csv_entry def test_parse_url(result_url_str):
64
64
69
8
55
Leovilhena/pbjs-evaluator
tests/unit_test.py
Python
test_parse_url
test_parse_url
57
64
57
57
e86fb5931d8f6dee2851e5a66b0f94a4e696d58e
bigcode/the-stack
train
918f7d0352da71f25a3c9432
train
function
def setup_module(): create_testfiles('1,testing', ['123.123.123.123:80:user:password', '456.456.456.456:80:user:password'])
def setup_module():
create_testfiles('1,testing', ['123.123.123.123:80:user:password', '456.456.456.456:80:user:password'])
'\n') def clean_testfiles(): try: os.remove('./tests/test.zip') os.remove('./tests/test.csv') os.remove('./proxies_test.txt') os.remove('./results.csv') except OSError: print("[*] Test files weren't removed during tests!") def setup_module():
64
64
41
4
60
Leovilhena/pbjs-evaluator
tests/unit_test.py
Python
setup_module
setup_module
33
34
33
33
27fa07cb9e6c4f0c2bdf8bbc24d305036b72c6e2
bigcode/the-stack
train
94a94dff11ed2ef510f59f56
train
function
def teardown_module(): clean_testfiles()
def teardown_module():
clean_testfiles()
.csv') except OSError: print("[*] Test files weren't removed during tests!") def setup_module(): create_testfiles('1,testing', ['123.123.123.123:80:user:password', '456.456.456.456:80:user:password']) def teardown_module():
64
64
9
4
60
Leovilhena/pbjs-evaluator
tests/unit_test.py
Python
teardown_module
teardown_module
36
37
36
36
ea1293a1a64ae32acc898d8def278d2d339c7d36
bigcode/the-stack
train
0d8515bcf6a43da56620881b
train
function
def clean_testfiles(): try: os.remove('./tests/test.zip') os.remove('./tests/test.csv') os.remove('./proxies_test.txt') os.remove('./results.csv') except OSError: print("[*] Test files weren't removed during tests!")
def clean_testfiles():
try: os.remove('./tests/test.zip') os.remove('./tests/test.csv') os.remove('./proxies_test.txt') os.remove('./results.csv') except OSError: print("[*] Test files weren't removed during tests!")
_entry.split(',')) with ZipFile('./tests/test.zip', 'w') as my_zip: my_zip.write('./tests/test.csv') with open("./proxies_test.txt",'w+') as result_file: for proxy in proxies: result_file.write(proxy + '\n') def clean_testfiles():
64
64
57
5
59
Leovilhena/pbjs-evaluator
tests/unit_test.py
Python
clean_testfiles
clean_testfiles
24
31
24
24
7884c3f76a037f3f290f9f93209faf20a34f4e8d
bigcode/the-stack
train
a39daa5eca07c1f7d4f0550c
train
function
def test_crawl_obj(crawl_obj): assert crawl_obj assert isinstance(crawl_obj.session, HTMLSession) assert not crawl_obj.proxies_priority assert isinstance(crawl_obj.user_agent, UserAgent) assert isinstance(crawl_obj.get_headers(), dict) assert not crawl_obj.load_proxies('') assert crawl_obj....
def test_crawl_obj(crawl_obj):
assert crawl_obj assert isinstance(crawl_obj.session, HTMLSession) assert not crawl_obj.proxies_priority assert isinstance(crawl_obj.user_agent, UserAgent) assert isinstance(crawl_obj.get_headers(), dict) assert not crawl_obj.load_proxies('') assert crawl_obj.load_proxies('./proxies_test.tx...
/test.zip', 'rb') as fp: unzipped = unzip_request_content(fp.read()) parsed_row = next(parse_row(unzipped)).replace('\r\n', '') parsed_result = parse_url(parsed_row) assert parsed_result == result_url_str def test_crawl_obj(crawl_obj):
64
64
162
9
54
Leovilhena/pbjs-evaluator
tests/unit_test.py
Python
test_crawl_obj
test_crawl_obj
66
86
66
66
a1013fe1acf58d7be3babfd7e3e788ff595033c6
bigcode/the-stack
train
78e6e273a4784306833bdaf3
train
function
def create_testfiles(csv_entry, proxies): with open("./tests/test.csv",'w+') as result_file: wr = csv.writer(result_file, dialect=csv.Dialect.delimiter) wr.writerow(csv_entry.split(',')) with ZipFile('./tests/test.zip', 'w') as my_zip: my_zip.write('./tests/test.csv') with open("./...
def create_testfiles(csv_entry, proxies):
with open("./tests/test.csv",'w+') as result_file: wr = csv.writer(result_file, dialect=csv.Dialect.delimiter) wr.writerow(csv_entry.split(',')) with ZipFile('./tests/test.zip', 'w') as my_zip: my_zip.write('./tests/test.csv') with open("./proxies_test.txt",'w+') as result_file: ...
import os import io import csv from zipfile import ZipFile from requests_html import HTMLSession from fake_useragent import UserAgent from helpers import unzip_request_content, parse_row, parse_url # Tests functions and configuration def create_testfiles(csv_entry, proxies):
59
64
102
9
49
Leovilhena/pbjs-evaluator
tests/unit_test.py
Python
create_testfiles
create_testfiles
12
22
12
12
4ecba2e67166c55a57a8c4a59ab26eea364acde7
bigcode/the-stack
train
d452d03abb024872ef8a6f29
train
function
def test_unzip_request_content(): assert not unzip_request_content(b'') with io.open('./tests/test.zip', 'rb') as fp: unzipped = unzip_request_content(fp.read()) assert isinstance(unzipped, ZipFile)
def test_unzip_request_content():
assert not unzip_request_content(b'') with io.open('./tests/test.zip', 'rb') as fp: unzipped = unzip_request_content(fp.read()) assert isinstance(unzipped, ZipFile)
during tests!") def setup_module(): create_testfiles('1,testing', ['123.123.123.123:80:user:password', '456.456.456.456:80:user:password']) def teardown_module(): clean_testfiles() # Tests unit def test_unzip_request_content():
64
64
52
7
56
Leovilhena/pbjs-evaluator
tests/unit_test.py
Python
test_unzip_request_content
test_unzip_request_content
41
46
41
41
5d0b2e497b503e1a3c8499b55e303980d3c2400b
bigcode/the-stack
train
a43adbafe7350fc19e4ea84c
train
class
class TestTBATSMatrixBuilder(object): @pytest.mark.parametrize( "components, params, expected_w, expected_g", [ [ dict(), dict(alpha=0.5), [1], # expected_w [0.5], # expected g ], [ # no seasonal ...
class TestTBATSMatrixBuilder(object): @pytest.mark.parametrize( "components, params, expected_w, expected_g", [ [ dict(), dict(alpha=0.5), [1], # expected_w [0.5], # expected g ], [ # no seasonal ...
def test_make_vector(self, components, params, expected_w, expected_g): m = MatrixBuilder( ModelParams( Components(**components), **params ) ) assert np.array_equal( expected_w, m.make_w_vector() ) ...
class TestTBATSMatrixBuilder(object): @pytest.mark.parametrize( "components, params, expected_w, expected_g", [ [ dict(), dict(alpha=0.5), [1], # expected_w [0.5], # expected g ], [ # no seasonal ...
726
256
2,682
726
0
series-temporais/tbats
test/tbats/TBATSMatrixBuilder_test.py
Python
TestTBATSMatrixBuilder
TestTBATSMatrixBuilder
7
214
7
47
075ea8c3790b6b1735e5af8c6fc196ec5ae94c9c
bigcode/the-stack
train
f735e3b3c9a50177e9409fa0
train
function
def text_of(relpath): """ Return string containing the contents of the file at *relpath* relative to this file. """ thisdir = os.path.dirname(__file__) file_path = os.path.join(thisdir, os.path.normpath(relpath)) with open(file_path) as f: text = f.read() return text
def text_of(relpath):
""" Return string containing the contents of the file at *relpath* relative to this file. """ thisdir = os.path.dirname(__file__) file_path = os.path.join(thisdir, os.path.normpath(relpath)) with open(file_path) as f: text = f.read() return text
#!/usr/bin/env python import os import re from setuptools import find_packages, setup def text_of(relpath):
26
64
77
6
19
oled-pentagrid/python-docx
setup.py
Python
text_of
text_of
9
18
9
9
012833f3464f148c911c28024b72367af59f9697
bigcode/the-stack
train
d89b25789d49156245be57c1
train
class
class NeuralNetModel : variable = {} dict = {} graph = {} sess = {} tf = {} init = {} saver = {} def check_duplicate(key, data, target, extra=None): """ check duplicate nn_id for none necessary memory use :param key: insert key :param data: inert data ...
class NeuralNetModel :
variable = {} dict = {} graph = {} sess = {} tf = {} init = {} saver = {} def check_duplicate(key, data, target, extra=None): """ check duplicate nn_id for none necessary memory use :param key: insert key :param data: inert data :param target: t...
import os import datetime class NeuralNetModel :
11
108
363
5
5
TensorMSA/hoyai_docker
skp_edu_docker/code/common/graph/nn_graph_manager.py
Python
NeuralNetModel
NeuralNetModel
4
55
4
4
b6c5ac2c8c8a8a5ed276e26cf6bc10948fce6929
bigcode/the-stack
train
d07f85e58a819361b8e3d62c
train
class
@skipIf(NO_MOCK, NO_MOCK_REASON) class VarnishTestCase(TestCase, LoaderModuleMockMixin): ''' Test cases for salt.modules.varnish ''' def setup_loader_modules(self): return {varnish: {}} def test_version(self): ''' Test to return server version from varnishd -V ''' ...
@skipIf(NO_MOCK, NO_MOCK_REASON) class VarnishTestCase(TestCase, LoaderModuleMockMixin):
''' Test cases for salt.modules.varnish ''' def setup_loader_modules(self): return {varnish: {}} def test_version(self): ''' Test to return server version from varnishd -V ''' with patch.dict(varnish.__salt__, {'cmd.run': MagicMock(ret...
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Jayesh Kariya <jayeshk@saltstack.com>` ''' # Import Python libs from __future__ import absolute_import # Import Salt Testing Libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.unit import skipIf, TestCase from tests.support.mock import ( ...
139
159
530
26
112
jubrad/salt
tests/unit/modules/test_varnish.py
Python
VarnishTestCase
VarnishTestCase
21
85
21
22
90b22fe7446c22d7644622517dfc07dcbcf18fb6
bigcode/the-stack
train
2624f806b9e5d72d365789b9
train
class
class TestServiceUserAcceptor: """Tests for ServiceUser as acceptor.""" def setup(self): self.assoc = Association(AE(), mode='requestor') primitive = A_ASSOCIATE() primitive.application_context_name = '1.2.840.10008.3.1.1.1' primitive.calling_ae_title = 'LOCAL_AE_TITLE ' ...
class TestServiceUserAcceptor:
"""Tests for ServiceUser as acceptor.""" def setup(self): self.assoc = Association(AE(), mode='requestor') primitive = A_ASSOCIATE() primitive.application_context_name = '1.2.840.10008.3.1.1.1' primitive.calling_ae_title = 'LOCAL_AE_TITLE ' primitive.called_ae_title = '...
"""Tests for association.AcceptorRequestor.""" import logging import time import threading import pytest from pynetdicom import ( AE, VerificationPresentationContexts, PYNETDICOM_IMPLEMENTATION_UID, PYNETDICOM_IMPLEMENTATION_VERSION, build_context, debug_logger ) from pynetdicom.association import ServiceUse...
162
256
11,686
7
155
Jesse-Back/pynetdicom
pynetdicom/tests/test_assoc_user.py
Python
TestServiceUserAcceptor
TestServiceUserAcceptor
26
1,389
26
26
3a355bdd659050ace5b7618d435a5988842554f1
bigcode/the-stack
train
9abe4b5b6a6ded169944d47d
train
class
class TestServiceUserRequestor: """Tests for ServiceUser as requestor.""" def setup(self): self.assoc = Association(AE(), mode='requestor') primitive = A_ASSOCIATE() primitive.application_context_name = '1.2.840.10008.3.1.1.1' primitive.calling_ae_title = 'LOCAL_AE_TITLE ' ...
class TestServiceUserRequestor:
"""Tests for ServiceUser as requestor.""" def setup(self): self.assoc = Association(AE(), mode='requestor') primitive = A_ASSOCIATE() primitive.application_context_name = '1.2.840.10008.3.1.1.1' primitive.calling_ae_title = 'LOCAL_AE_TITLE ' primitive.called_ae_title = ...
True user.primitive = self.primitive_ac assert user.writeable is False def test_ae_title(self): """Test setting the ae_title""" user = ServiceUser(self.assoc, mode='acceptor') user.ae_title = ' TEST A ' assert user.ae_title == ' TEST A ' msg = "Invali...
256
256
11,319
7
249
Jesse-Back/pynetdicom
pynetdicom/tests/test_assoc_user.py
Python
TestServiceUserRequestor
TestServiceUserRequestor
1,392
2,707
1,392
1,392
86051764676420cfa2d25e5ad11ca42008bcebd1
bigcode/the-stack
train
d40093da9738e72566e6ca3c
train
class
class nnSolve: def __init__(self, game): self.game = game self.n = game.n self.K = game.K self.K2 = game.K2 self.K3 = game.K3 self.xhat = torch.tensor(game.xhat, dtype=torch.float) self.x = torch.tensor(game.xhat, requires_grad=True, dtype=torch.float) ...
class nnSolve:
def __init__(self, game): self.game = game self.n = game.n self.K = game.K self.K2 = game.K2 self.K3 = game.K3 self.xhat = torch.tensor(game.xhat, dtype=torch.float) self.x = torch.tensor(game.xhat, requires_grad=True, dtype=torch.float) self.us = torc...
# -*- coding: utf-8 -*- import torch import numpy as np from nn import MyLossReg from nn import MyLoss class nnSolve:
33
141
473
4
28
AIandSocialGoodLab/FeatureDeceptionGame
1b2b/nnSolve.py
Python
nnSolve
nnSolve
7
56
7
7
626f22869ad7804744ddf5221991cf7d5833c8e2
bigcode/the-stack
train
468fa90fa8d6571dac285ecc
train
class
class TestParseVagrantMachineReadableBoxList(TestCase): def test_machine_readable_box_list(self): with patch('burlap.vagrant.vagrant.local') as mock_local: mock_local.return_value = textwrap.dedent(r""" 1391708688,,box-name,precise64 1391708688,,box-provider,virt...
class TestParseVagrantMachineReadableBoxList(TestCase):
def test_machine_readable_box_list(self): with patch('burlap.vagrant.vagrant.local') as mock_local: mock_local.return_value = textwrap.dedent(r""" 1391708688,,box-name,precise64 1391708688,,box-provider,virtualbox """) from burlap.vagra...
import textwrap from mock import patch from burlap.tests.base import TestCase class TestParseVagrantMachineReadableBoxList(TestCase):
30
64
146
12
17
tutordelphia/burlap
burlap/tests/test_vagrant_base_boxes.py
Python
TestParseVagrantMachineReadableBoxList
TestParseVagrantMachineReadableBoxList
7
21
7
8
d0703873ff8fc4edb4d456a8e38ede5c481cc644
bigcode/the-stack
train
637b3d9034b7f1e8a40d1e39
train
class
class TestParseVagrantBoxListWithoutProvider(TestCase): def test_parse_box_list(self): with patch('burlap.vagrant.vagrant.local') as mock_local: mock_local.return_value = textwrap.dedent("""\ precise64 """) from burlap.vagrant import vagrant ...
class TestParseVagrantBoxListWithoutProvider(TestCase):
def test_parse_box_list(self): with patch('burlap.vagrant.vagrant.local') as mock_local: mock_local.return_value = textwrap.dedent("""\ precise64 """) from burlap.vagrant import vagrant res = vagrant._box_list_human_readable() s...
._box_list_human_readable() self.assertEqual(res, [ # ('lucid32', 'virtualbox'), ('precise64', 'virtualbox'), # ('precise64', 'vmware_fusion'), ]) class TestParseVagrantBoxListWithoutProvider(TestCase):
63
64
109
12
51
tutordelphia/burlap
burlap/tests/test_vagrant_base_boxes.py
Python
TestParseVagrantBoxListWithoutProvider
TestParseVagrantBoxListWithoutProvider
40
52
40
41
11b4466571179a4dac676bf92ba39cb9be1841d0
bigcode/the-stack
train
a2beac563f65388d017af426
train
class
class TestParseVagrantBoxListWithProvider(TestCase): def test_parse_box_list(self): with patch('burlap.vagrant.vagrant.local') as mock_local: mock_local.return_value = textwrap.dedent("""\ precise64 (virtualbox) """) from burlap.vagran...
class TestParseVagrantBoxListWithProvider(TestCase):
def test_parse_box_list(self): with patch('burlap.vagrant.vagrant.local') as mock_local: mock_local.return_value = textwrap.dedent("""\ precise64 (virtualbox) """) from burlap.vagrant import vagrant res = vagrant._box_list_h...
agrant._box_list_machine_readable() self.assertEqual(res, [ # ('lucid32', 'virtualbox'), ('precise64', 'virtualbox'), # ('precise64', 'vmware_fusion'), ]) class TestParseVagrantBoxListWithProvider(TestCase):
63
64
126
12
51
tutordelphia/burlap
burlap/tests/test_vagrant_base_boxes.py
Python
TestParseVagrantBoxListWithProvider
TestParseVagrantBoxListWithProvider
24
37
24
25
7113a016a330beac7fafbc832b014b943e4c9f83
bigcode/the-stack
train