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
20caa29c86a6c5b5e0395ca3
train
class
@override_settings( PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'], ROOT_URLCONF='admin_widgets.urls', ) class AdminFileWidgetTests(TestDataMixin, TestCase): @classmethod def setUpTestData(cls): super(AdminFileWidgetTests, cls).setUpTestData() band = models.Band.obj...
@override_settings( PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'], ROOT_URLCONF='admin_widgets.urls', ) class AdminFileWidgetTests(TestDataMixin, TestCase): @classmethod
def setUpTestData(cls): super(AdminFileWidgetTests, cls).setUpTestData() band = models.Band.objects.create(name='Linkin Park') cls.album = band.album_set.create( name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg' ) def test_render(self): w = widgets....
;&lt;script&gt;' 'alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;</a><br />' 'Change: <input class="vURLField" name="test" type="url" ' 'value="http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;' 'alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;" /></p>' ) @override_s...
148
148
495
46
102
himleyb85/django
tests/admin_widgets/tests.py
Python
AdminFileWidgetTests
AdminFileWidgetTests
410
464
410
416
23434898d54e6d6b1c74f2e110af46974202c2c2
bigcode/the-stack
train
34a62b8d1a2d49f000a7aa5c
train
class
class AdminDateWidgetTest(SimpleTestCase): def test_attrs(self): """ Ensure that user-supplied attrs are used. Refs #12073. """ w = widgets.AdminDateWidget() self.assertHTMLEqual( w.render('test', datetime(2007, 12, 1, 9, 30)), '<input value="2...
class AdminDateWidgetTest(SimpleTestCase):
def test_attrs(self): """ Ensure that user-supplied attrs are used. Refs #12073. """ w = widgets.AdminDateWidget() self.assertHTMLEqual( w.render('test', datetime(2007, 12, 1, 9, 30)), '<input value="2007-12-01" type="text" class="vDateField" n...
self.assertHTMLEqual( w.render('test', 'test'), '<select multiple="multiple" name="test" class="selectfilterstacked" ' 'data-field-name="test\\" data-is-stacked="1">\n</select>' ) class AdminDateWidgetTest(SimpleTestCase):
64
64
202
9
55
himleyb85/django
tests/admin_widgets/tests.py
Python
AdminDateWidgetTest
AdminDateWidgetTest
288
304
288
288
efcf7e37abb7906888243e33cccee13528adcc95
bigcode/the-stack
train
1071bdbb9139641d06b125f2
train
class
class FilteredSelectMultipleWidgetTest(SimpleTestCase): def test_render(self): # Backslash in verbose_name to ensure it is JavaScript escaped. w = widgets.FilteredSelectMultiple('test\\', False) self.assertHTMLEqual( w.render('test', 'test'), '<select multiple="multip...
class FilteredSelectMultipleWidgetTest(SimpleTestCase):
def test_render(self): # Backslash in verbose_name to ensure it is JavaScript escaped. w = widgets.FilteredSelectMultiple('test\\', False) self.assertHTMLEqual( w.render('test', 'test'), '<select multiple="multiple" name="test" class="selectfilter" ' 'data...
_callable(): return 'works' lookup1 = widgets.url_params_from_lookup_dict({'myfield': my_callable}) lookup2 = widgets.url_params_from_lookup_dict({'myfield': my_callable()}) self.assertEqual(lookup1, lookup2) class FilteredSelectMultipleWidgetTest(SimpleTestCase):
64
64
193
11
53
himleyb85/django
tests/admin_widgets/tests.py
Python
FilteredSelectMultipleWidgetTest
FilteredSelectMultipleWidgetTest
268
285
268
268
7f5e94d8ea87da59a64e24209f84af7d3f0947c7
bigcode/the-stack
train
e5b3ec716aa55f9b2f3d2495
train
class
@override_settings(TIME_ZONE='US/Eastern') class DateTimePickerAltTimezoneSeleniumFirefoxTests(DateTimePickerShortcutsSeleniumFirefoxTests): pass
@override_settings(TIME_ZONE='US/Eastern') class DateTimePickerAltTimezoneSeleniumFirefoxTests(DateTimePickerShortcutsSeleniumFirefoxTests):
pass
' # The above tests run with Asia/Singapore which are on the positive side of # UTC. Here we test with a timezone on the negative side. @override_settings(TIME_ZONE='US/Eastern') class DateTimePickerAltTimezoneSeleniumFirefoxTests(DateTimePickerShortcutsSeleniumFirefoxTests):
64
64
34
31
33
himleyb85/django
tests/admin_widgets/tests.py
Python
DateTimePickerAltTimezoneSeleniumFirefoxTests
DateTimePickerAltTimezoneSeleniumFirefoxTests
890
892
890
891
05703e15e2886778f0335800fdfb40937e65d083
bigcode/the-stack
train
c56421aa8cf7cf2a351caf34
train
class
class DateTimePickerAltTimezoneSeleniumChromeTests(DateTimePickerAltTimezoneSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class DateTimePickerAltTimezoneSeleniumChromeTests(DateTimePickerAltTimezoneSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
we test with a timezone on the negative side. @override_settings(TIME_ZONE='US/Eastern') class DateTimePickerAltTimezoneSeleniumFirefoxTests(DateTimePickerShortcutsSeleniumFirefoxTests): pass class DateTimePickerAltTimezoneSeleniumChromeTests(DateTimePickerAltTimezoneSeleniumFirefoxTests):
64
64
33
20
43
himleyb85/django
tests/admin_widgets/tests.py
Python
DateTimePickerAltTimezoneSeleniumChromeTests
DateTimePickerAltTimezoneSeleniumChromeTests
895
896
895
895
a0584f6783cb6c113c2b1bf09092d9d18b8b0005
bigcode/the-stack
train
f7431803ac09663b0807a185
train
class
class DateTimePickerAltTimezoneSeleniumIETests(DateTimePickerAltTimezoneSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
class DateTimePickerAltTimezoneSeleniumIETests(DateTimePickerAltTimezoneSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
ShortcutsSeleniumFirefoxTests): pass class DateTimePickerAltTimezoneSeleniumChromeTests(DateTimePickerAltTimezoneSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' class DateTimePickerAltTimezoneSeleniumIETests(DateTimePickerAltTimezoneSeleniumFirefoxTests):
64
64
34
21
43
himleyb85/django
tests/admin_widgets/tests.py
Python
DateTimePickerAltTimezoneSeleniumIETests
DateTimePickerAltTimezoneSeleniumIETests
899
900
899
899
b2df30201f7f9f5c66eabbb9186dffd425e2b90c
bigcode/the-stack
train
7a6405419f3c543f15a88e7e
train
class
class AdminRawIdWidgetSeleniumIETests(AdminRawIdWidgetSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
class AdminRawIdWidgetSeleniumIETests(AdminRawIdWidgetSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
_for_value('#id_supporting_bands', '42,98') class AdminRawIdWidgetSeleniumChromeTests(AdminRawIdWidgetSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' class AdminRawIdWidgetSeleniumIETests(AdminRawIdWidgetSeleniumFirefoxTests):
64
64
32
19
45
himleyb85/django
tests/admin_widgets/tests.py
Python
AdminRawIdWidgetSeleniumIETests
AdminRawIdWidgetSeleniumIETests
1,296
1,297
1,296
1,296
eeb7dfae35ba5764e1d494a0901fd2f5885d71be
bigcode/the-stack
train
ecc4eeaef40da0839b33b3f9
train
class
class AdminSplitDateTimeWidgetTest(SimpleTestCase): def test_render(self): w = widgets.AdminSplitDateTime() self.assertHTMLEqual( w.render('test', datetime(2007, 12, 1, 9, 30)), '<p class="datetime">' 'Date: <input value="2007-12-01" type="text" class="vDateField"...
class AdminSplitDateTimeWidgetTest(SimpleTestCase):
def test_render(self): w = widgets.AdminSplitDateTime() self.assertHTMLEqual( w.render('test', datetime(2007, 12, 1, 9, 30)), '<p class="datetime">' 'Date: <input value="2007-12-01" type="text" class="vDateField" ' 'name="test_0" size="10" /><br />' ...
.AdminTimeWidget(attrs={'size': 20, 'class': 'myTimeField'}) self.assertHTMLEqual( w.render('test', datetime(2007, 12, 1, 9, 30)), '<input value="09:30:00" type="text" class="myTimeField" name="test" size="20" />', ) class AdminSplitDateTimeWidgetTest(SimpleTestCase):
92
92
309
11
81
himleyb85/django
tests/admin_widgets/tests.py
Python
AdminSplitDateTimeWidgetTest
AdminSplitDateTimeWidgetTest
326
350
326
326
29dbb3111be59ba4b6360723c28861002d7a5607
bigcode/the-stack
train
b337fc683015186a7cd4aadc
train
class
class DateTimePickerSeleniumIETests(DateTimePickerSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
class DateTimePickerSeleniumIETests(DateTimePickerSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
year are displayed self.wait_for_text('#calendarin0 caption', expected_caption) class DateTimePickerSeleniumChromeTests(DateTimePickerSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' class DateTimePickerSeleniumIETests(DateTimePickerSeleniumFirefoxTests):
64
64
30
17
47
himleyb85/django
tests/admin_widgets/tests.py
Python
DateTimePickerSeleniumIETests
DateTimePickerSeleniumIETests
815
816
815
815
ec7d6524598ffafb92e054dbca2a550d3ae3b49a
bigcode/the-stack
train
01f59c0dd993542aaa852490
train
class
class AdminFormfieldForDBFieldTests(SimpleTestCase): """ Tests for correct behavior of ModelAdmin.formfield_for_dbfield """ def assertFormfield(self, model, fieldname, widgetclass, **admin_overrides): """ Helper to call formfield_for_dbfield for a given model and field name and ...
class AdminFormfieldForDBFieldTests(SimpleTestCase):
""" Tests for correct behavior of ModelAdmin.formfield_for_dbfield """ def assertFormfield(self, model, fieldname, widgetclass, **admin_overrides): """ Helper to call formfield_for_dbfield for a given model and field name and verify that the returned formfield is appropriate. ...
=False, is_staff=True, last_login=datetime(2007, 5, 30, 13, 20, 10), date_joined=datetime(2007, 5, 30, 13, 20, 10) ) models.Car.objects.create(id=1, owner=cls.u1, make='Volkswagen', model='Passat') models.Car.objects.create(id=2, owner=cls.u2, make='BMW', model='M3') cl...
256
256
1,169
12
244
himleyb85/django
tests/admin_widgets/tests.py
Python
AdminFormfieldForDBFieldTests
AdminFormfieldForDBFieldTests
62
195
62
62
6694cfd52f9a35ef70a070deb76d8b37638efe33
bigcode/the-stack
train
def9a63d4f5ab6331f228404
train
class
class DateTimePickerShortcutsSeleniumChromeTests(DateTimePickerShortcutsSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class DateTimePickerShortcutsSeleniumChromeTests(DateTimePickerShortcutsSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
now" on the server side. member = models.Member.objects.get(name='test') self.assertGreater(member.birthdate, now - error_margin) self.assertLess(member.birthdate, now + error_margin) class DateTimePickerShortcutsSeleniumChromeTests(DateTimePickerShortcutsSeleniumFirefoxTests):
64
64
33
20
44
himleyb85/django
tests/admin_widgets/tests.py
Python
DateTimePickerShortcutsSeleniumChromeTests
DateTimePickerShortcutsSeleniumChromeTests
880
881
880
880
324dd71c4bdc0bd667f19aa7b1e8103457458d08
bigcode/the-stack
train
b571d639b606234e53cb396e
train
class
class BooleanData(OutputData): HANDLED_CLASSES = [bool] PARAMS = { } def __init__(self, name: str): super().__init__(name) self.data: Optional[bool] = None def display(self) -> str: return str(self.data)
class BooleanData(OutputData):
HANDLED_CLASSES = [bool] PARAMS = { } def __init__(self, name: str): super().__init__(name) self.data: Optional[bool] = None def display(self) -> str: return str(self.data)
from typing import Optional, TYPE_CHECKING from .base import OutputData if TYPE_CHECKING: pass class BooleanData(OutputData):
30
64
64
6
23
furbrain/CVExplorer
src/datatypes/boolean.py
Python
BooleanData
BooleanData
9
19
9
9
ab5803e3f99ade1b583075d4d894cbedc61739bc
bigcode/the-stack
train
96eaad2453bd6456a1bef0fe
train
function
def worker(p): x,prn = p metric,code,doppler = search(x,prn,doppler_search,ms) return 'prn %2d doppler % 7.1f metric % 7.1f code_offset %6.1f' % (prn,doppler,metric,code)
def worker(p):
x,prn = p metric,code,doppler = search(x,prn,doppler_search,ms) return 'prn %2d doppler % 7.1f metric % 7.1f code_offset %6.1f' % (prn,doppler,metric,code)
),np.arange(len(x)),np.real(x)) xi = np.interp((1/fsr)*np.arange(ms_pad*3*10230),np.arange(len(x)),np.imag(x)) x = xr+(1j)*xi # iterate (in parallel) over PRNs of interest def worker(p):
64
64
75
4
59
wumouyan/GNSS-SDR-Python
acquire-gps-l5i.py
Python
worker
worker
97
100
97
97
1aa859a7d7ea55b78d55d747533e7b1e7a321d21
bigcode/the-stack
train
fcbdea9733cbe6dd2370e04a
train
function
def search(x,prn,doppler_search,ms): fs = 3*10230000.0 n = 3*10230 # 1 ms coherent integration doppler_min, doppler_max, doppler_incr = doppler_search incr = float(l5i.code_length)/n c = l5i.code(prn,0,0,incr,n) # obtain samples of the L5I code c = ...
def search(x,prn,doppler_search,ms):
fs = 3*10230000.0 n = 3*10230 # 1 ms coherent integration doppler_min, doppler_max, doppler_incr = doppler_search incr = float(l5i.code_length)/n c = l5i.code(prn,0,0,incr,n) # obtain samples of the L5I code c = fft.fft(np.concatenate((c,np.zeros(n)...
#!/usr/bin/env python import optparse import numpy as np import scipy.signal import scipy.fftpack as fft import gnsstools.gps.l5i as l5i import gnsstools.nco as nco import gnsstools.io as io import gnsstools.util as util # # Acquisition search # def search(x,prn,doppler_search,ms):
90
93
312
13
77
wumouyan/GNSS-SDR-Python
acquire-gps-l5i.py
Python
search
search
18
40
18
18
51e8f39a4a70f600a2fe7206ecf4dea7d597a57b
bigcode/the-stack
train
0858878d8a3547d1743193a5
train
function
def lazy_import(): from fattureincloud_python_sdk.model.issued_document_pre_create_info import IssuedDocumentPreCreateInfo globals()['IssuedDocumentPreCreateInfo'] = IssuedDocumentPreCreateInfo
def lazy_import():
from fattureincloud_python_sdk.model.issued_document_pre_create_info import IssuedDocumentPreCreateInfo globals()['IssuedDocumentPreCreateInfo'] = IssuedDocumentPreCreateInfo
, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, validate_get_composed_info, OpenApiModel ) from fattureincloud_python_sdk.exceptions import ApiAttributeError def lazy_import():
64
64
44
4
59
fattureincloud/fattureincloud-python-sdk
fattureincloud_python_sdk/model/get_issued_document_pre_create_info_response.py
Python
lazy_import
lazy_import
33
35
33
33
9c9b28e5bac012e6f608a7bef5b5c0dff81701e9
bigcode/the-stack
train
149e45a7ead2352d7d458296
train
class
class GetIssuedDocumentPreCreateInfoResponse(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name ...
class GetIssuedDocumentPreCreateInfoResponse(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a c...
chosen by more than 400.000 businesses in Italy. The Fatture in Cloud API is based on REST, and makes possible to interact with the user related data prior authorization via OAuth2 protocol. # noqa: E501 The version of the OpenAPI document: 2.0.15 Contact: info@fattureincloud.it Generated by: https://o...
256
256
1,947
11
244
fattureincloud/fattureincloud-python-sdk
fattureincloud_python_sdk/model/get_issued_document_pre_create_info_response.py
Python
GetIssuedDocumentPreCreateInfoResponse
GetIssuedDocumentPreCreateInfoResponse
38
262
38
38
a13b62551b537a4d7a051670a8037f8b14adf89d
bigcode/the-stack
train
d84235905e1c090dae07e440
train
function
def k_day_percent_change(k, df): """ Computes the k-day adjusted close percent change. Example: k=2, is the daily percent change Arguments: k -- number of days into past to use , k>1 df -- yahoo finance dataframe. Must be indexed by data, and have columne adj_close """ return (df.open ...
def k_day_percent_change(k, df):
""" Computes the k-day adjusted close percent change. Example: k=2, is the daily percent change Arguments: k -- number of days into past to use , k>1 df -- yahoo finance dataframe. Must be indexed by data, and have columne adj_close """ return (df.open / df.adj_close.shift(k)) - 1
daily price change over 1 day Arguments: df -- yahoo finance dataframe Returns: new pandas series object of the same shape as df with computed daily percent change """ return (df.open / df.adj_close) - 1 def k_day_percent_change(k, df):
64
64
93
9
54
sammichaelis/influencer_hypothesis
src/data/stock_features.py
Python
k_day_percent_change
k_day_percent_change
23
32
23
23
fa2fe5c7bd934f236d722c49bc8f2fb41fed63d0
bigcode/the-stack
train
59fa6f14665856422046c2bd
train
function
def returns(k, df): """ Computes the log returns over a k-day period Arguments: k -- window size df -- yahoo finance dataframe Returns: Log returns over a day period """ return ((df.open / df.adj_close.shift(k)) - 1) * 100
def returns(k, df):
""" Computes the log returns over a k-day period Arguments: k -- window size df -- yahoo finance dataframe Returns: Log returns over a day period """ return ((df.open / df.adj_close.shift(k)) - 1) * 100
): """ Computes the log returns over a k-day period Arguments: k -- window size df -- yahoo finance dataframe Returns: Log returns over a day period """ return np.log(df.open/ df.adj_close.shift(k)) def returns(k, df):
64
64
70
6
58
sammichaelis/influencer_hypothesis
src/data/stock_features.py
Python
returns
returns
50
61
50
50
3af3cc754c2ad504a6632095a7f2defe8f796f89
bigcode/the-stack
train
639e672c5d0fdfeeb3e92476
train
function
def generate_target(forecast_period, df): """ Comppute growth of a stock of a forecast period Arguments: forecast_period -- length of forecast (in days) df -- yahoo finance dataframe. Returns: feature vector of ground truth percent changes Exampls: """ #return np.log((df.adj_cl...
def generate_target(forecast_period, df):
""" Comppute growth of a stock of a forecast period Arguments: forecast_period -- length of forecast (in days) df -- yahoo finance dataframe. Returns: feature vector of ground truth percent changes Exampls: """ #return np.log((df.adj_close.shift(-1 * forecast_period) / df.adj_c...
df -- yahoo finance dataframe ret_key -- string key to access the returns Returns: Volatility of a stock with a window of k """ return df[ret_key].rolling(window=period).std() * np.sqrt(period) def generate_target(forecast_period, df):
64
64
113
10
54
sammichaelis/influencer_hypothesis
src/data/stock_features.py
Python
generate_target
generate_target
78
91
78
78
07bba689b5fd8995bd3e1f67c66c845302ad4d1c
bigcode/the-stack
train
3f41582e53c966f4bc9a6b39
train
function
def log_returns(k, df): """ Computes the log returns over a k-day period Arguments: k -- window size df -- yahoo finance dataframe Returns: Log returns over a day period """ return np.log(df.open/ df.adj_close.shift(k))
def log_returns(k, df):
""" Computes the log returns over a k-day period Arguments: k -- window size df -- yahoo finance dataframe Returns: Log returns over a day period """ return np.log(df.open/ df.adj_close.shift(k))
: k -- number of days into past to use , k>1 df -- yahoo finance dataframe. Must be indexed by data, and have columne adj_close """ return (df.open / df.adj_close.shift(k)) - 1 def log_returns(k, df):
64
64
64
7
56
sammichaelis/influencer_hypothesis
src/data/stock_features.py
Python
log_returns
log_returns
36
47
36
36
d6c0bc044a5cc560cce4717a581619a48166bd3c
bigcode/the-stack
train
cf1ab804eb1342bc3f9a03aa
train
function
def compute_volatility(period, df, ret_key='monthly_returns'): """ Computes the rolling volatility (standard deviation) of the log returns Arguments: preiod -- window (suggested size of 252) df -- yahoo finance dataframe ret_key -- string key to access the returns Returns: Volatility o...
def compute_volatility(period, df, ret_key='monthly_returns'):
""" Computes the rolling volatility (standard deviation) of the log returns Arguments: preiod -- window (suggested size of 252) df -- yahoo finance dataframe ret_key -- string key to access the returns Returns: Volatility of a stock with a window of k """ return df[ret_key].rol...
Arguments: k -- window size df -- yahoo finance dataframe Returns: Log returns over a day period """ return ((df.open / df.adj_close.shift(k)) - 1) * 100 def compute_volatility(period, df, ret_key='monthly_returns'):
64
64
100
14
49
sammichaelis/influencer_hypothesis
src/data/stock_features.py
Python
compute_volatility
compute_volatility
64
76
64
64
3c1529b3e2e92bbc11409531d507d52adfb8a2b8
bigcode/the-stack
train
6277a0e881af26b50f332eb1
train
function
def daily_change(df): """ Computes daily price change over 1 day Arguments: df -- yahoo finance dataframe Returns: new pandas series object of the same shape as df with computed daily percent change """ return (df.open / df.adj_close) - 1
def daily_change(df):
""" Computes daily price change over 1 day Arguments: df -- yahoo finance dataframe Returns: new pandas series object of the same shape as df with computed daily percent change """ return (df.open / df.adj_close) - 1
# Stock Features """ Collection of stock-based features based on Yahoo Finance Data """ import pandas as pd def daily_change(df):
27
64
64
5
21
sammichaelis/influencer_hypothesis
src/data/stock_features.py
Python
daily_change
daily_change
9
19
9
9
bd28f37ff87482681ee21ca8f51f53d795f14a60
bigcode/the-stack
train
a42b5f82425ccb4419ed6061
train
function
def welcome(): """ This funciton welcomes the user to the program. """ clear() menu_selector = input(""" Welcome to the work log application! Here you may add or delete tasks for your work log. Enter anything to continue or enter 'q' to quit. """).lower() if menu_selector != 'q': return...
def welcome():
""" This funciton welcomes the user to the program. """ clear() menu_selector = input(""" Welcome to the work log application! Here you may add or delete tasks for your work log. Enter anything to continue or enter 'q' to quit. """).lower() if menu_selector != 'q': return True else:...
import os from entry_changer import EntryChanger def clear(): """ This function clears the screen for easier reading and use.""" os.system('cls' if os.name == 'nt' else 'clear') def welcome():
47
64
93
3
44
Zachary-Jackson/Database-Work-Log
database_work_log.py
Python
welcome
welcome
11
23
11
11
4ef1cb90f590e594d801817327eaf7c631fabb53
bigcode/the-stack
train
abcac276d663efa4dd37b3ee
train
function
def main_all_names(): """ Returns to main() if the user wants to use all names or not.""" all_names = input("\n Do you want to search via all names " + "or your name?\n" + " Enter 'my' to search by your name, " + 'otherwise, all will be searche...
def main_all_names():
""" Returns to main() if the user wants to use all names or not.""" all_names = input("\n Do you want to search via all names " + "or your name?\n" + " Enter 'my' to search by your name, " + 'otherwise, all will be searched. ').lower() if ...
bon voyage!") return False def main_initalization(): """ This creates a few values for main.""" menu_item = EntryChanger() first_name, last_name = menu_item.run_entry_changer(command='get names') return menu_item, first_name, last_name def main_all_names():
64
64
96
5
58
Zachary-Jackson/Database-Work-Log
database_work_log.py
Python
main_all_names
main_all_names
33
42
33
33
9451e93325d90b88f41950f39d9c9d24fb3f4d48
bigcode/the-stack
train
dda0f472364a32653b6ed1b2
train
function
def main_initalization(): """ This creates a few values for main.""" menu_item = EntryChanger() first_name, last_name = menu_item.run_entry_changer(command='get names') return menu_item, first_name, last_name
def main_initalization():
""" This creates a few values for main.""" menu_item = EntryChanger() first_name, last_name = menu_item.run_entry_changer(command='get names') return menu_item, first_name, last_name
you may add or delete tasks for your work log. Enter anything to continue or enter 'q' to quit. """).lower() if menu_selector != 'q': return True else: print("\nUntil next time, bon voyage!") return False def main_initalization():
64
64
52
6
57
Zachary-Jackson/Database-Work-Log
database_work_log.py
Python
main_initalization
main_initalization
26
30
26
26
d75a2640c9aa4c08a4b43e0820388295b6361dcf
bigcode/the-stack
train
9be82c913bbc9e90819d8a78
train
function
def main(menu_item, first_name, last_name): """ This is the primary menu for work_log.py and gathers information to call on the correct class. The user is also allowed to quit and end the script.""" main_loop = True while main_loop: # This clears the screen on every new instance of the loop...
def main(menu_item, first_name, last_name):
""" This is the primary menu for work_log.py and gathers information to call on the correct class. The user is also allowed to quit and end the script.""" main_loop = True while main_loop: # This clears the screen on every new instance of the loop clear() # This is the prima...
values for main.""" menu_item = EntryChanger() first_name, last_name = menu_item.run_entry_changer(command='get names') return menu_item, first_name, last_name def main_all_names(): """ Returns to main() if the user wants to use all names or not.""" all_names = input("\n Do you want to search vi...
147
147
490
11
135
Zachary-Jackson/Database-Work-Log
database_work_log.py
Python
main
main
45
95
45
45
493906d6040ad58e5c50396d91433ba5528049fd
bigcode/the-stack
train
e26dce643a93d722fe3f8691
train
function
def clear(): """ This function clears the screen for easier reading and use.""" os.system('cls' if os.name == 'nt' else 'clear')
def clear():
""" This function clears the screen for easier reading and use.""" os.system('cls' if os.name == 'nt' else 'clear')
import os from entry_changer import EntryChanger def clear():
14
64
33
3
10
Zachary-Jackson/Database-Work-Log
database_work_log.py
Python
clear
clear
6
8
6
6
a60c6dd6563219bf9ab7b8e3094c11d9df6ba8e4
bigcode/the-stack
train
965cd3f603ebf2bbec3e8d37
train
function
def generate_problems_pdf(args): """ Takes the parsed arguments, generates appropriate latex, converts it a pdf, and cleans up any temporary files :param args: parsed arguments that define how to generate the document """ contents = generate_problems(number_of_problems=args.numproblems, maximum_inte...
def generate_problems_pdf(args):
""" Takes the parsed arguments, generates appropriate latex, converts it a pdf, and cleans up any temporary files :param args: parsed arguments that define how to generate the document """ contents = generate_problems(number_of_problems=args.numproblems, maximum_integer=args.maximum_integer, problem...
, help='Generate multiple pages for entire class or for extra practice') args = parser.parse_args() assert args.problemtype in operators, '{} not a valid problemtype, only {}'.format(args.problemtype, ', '.join([x for x in operators])) return args def generate_problems_pdf(args):
64
64
107
7
56
sourcery-ai-bot/education_math_homework_generator
education_math_homework_generator/gen_add_subtract.py
Python
generate_problems_pdf
generate_problems_pdf
88
95
88
88
f8098f504712f3ee42b8300a5793a15190b7654a
bigcode/the-stack
train
b7b1bc6adc3d71d0b00d4616
train
function
def generate_problems(number_of_problems=2, maximum_integer=50, problem_type='Addition', number_of_pages=1): """ Generates random example math problems in latex format for practicing Addition, Subtraction, or Multiplication :param number_of_problems: defines how many problems to generate :param maximum_...
def generate_problems(number_of_problems=2, maximum_integer=50, problem_type='Addition', number_of_pages=1):
""" Generates random example math problems in latex format for practicing Addition, Subtraction, or Multiplication :param number_of_problems: defines how many problems to generate :param maximum_integer: defines the maximum integer possible during the generation of problems :param problem_type: type...
import argparse import random from education_math_homework_generator.util import convert_latex_to_pdf from education_math_homework_generator.util import remove_temporary_files # Credits: # latex formatting adopted from stackexchange # https://tex.stackexchange.com/questions/11702/how-to-present-a-vertical-multiplica...
94
167
558
27
66
sourcery-ai-bot/education_math_homework_generator
education_math_homework_generator/gen_add_subtract.py
Python
generate_problems
generate_problems
12
64
12
12
4a7219f38338b44157bf09e6e39da2e2f98c8118
bigcode/the-stack
train
50ccd6a96663c2b936f1d6ef
train
function
def parse_arguments(): """ Parse user arguments to modify how the document is generated for problem generation :return: parsed args passed by the user or defaults defined below """ operators = ('Addition', 'Subtraction', 'Mixed') parser = argparse.ArgumentParse...
def parse_arguments():
""" Parse user arguments to modify how the document is generated for problem generation :return: parsed args passed by the user or defaults defined below """ operators = ('Addition', 'Subtraction', 'Mixed') parser = argparse.ArgumentParser(description='Generate...
'\end{large}') lines.append(r'\end{multicols}') # generate the next set of problems on a new page for student i if index != number_of_pages: lines.append(r'\newpage') lines.append(r'\end{document}') return '\n'.join(lines) def parse_arguments():
69
69
230
4
65
sourcery-ai-bot/education_math_homework_generator
education_math_homework_generator/gen_add_subtract.py
Python
parse_arguments
parse_arguments
67
85
67
67
67b761eec150379dc734a65bcce7fb4afc9a3492
bigcode/the-stack
train
09f421fd9a1170b7015df16c
train
function
def add_searches(title, url, new_article, session): """ This method takes the relevant keywords from the title and URL, and tries to properly clean them. It finally adds the ArticleWord to the session, to be committed as a whole. :param title: The title of the article :param url: The url of the ...
def add_searches(title, url, new_article, session):
""" This method takes the relevant keywords from the title and URL, and tries to properly clean them. It finally adds the ArticleWord to the session, to be committed as a whole. :param title: The title of the article :param url: The url of the article :param new_article: The actual new artic...
}') log(f' Low Quality: {skipped_due_to_low_quality}') log(f' Already in DB: {skipped_already_in_db}') def add_topics(new_article, session): for loc_topic in LocalizedTopic.query.all(): if loc_topic.language == new_article.language and loc_topic.matches_article(new_article): new_arti...
99
99
333
13
86
simonchristensen1/Zeeguu-Core
zeeguu_core/content_retriever/article_downloader.py
Python
add_searches
add_searches
186
218
186
186
f11f8351616237bc6190df76d8dc8841fa39adca
bigcode/the-stack
train
69e06e192c2048970a4e9498
train
function
def _url_after_redirects(url): # solve redirects and save the clean url response = requests.get(url) return response.url
def _url_after_redirects(url): # solve redirects and save the clean url
response = requests.get(url) return response.url
from zeeguu_core.constants import SIMPLE_TIME_FORMAT import requests LOG_CONTEXT = "FEED RETRIEVAL" def log(msg: str): zeeguu_core.log(LOG_CONTEXT + " " + msg) def _url_after_redirects(url): # solve redirects and save the clean url
64
64
30
18
46
simonchristensen1/Zeeguu-Core
zeeguu_core/content_retriever/article_downloader.py
Python
_url_after_redirects
_url_after_redirects
29
32
29
30
5230c1548a813533a58f03774cd8dc162aa2f42b
bigcode/the-stack
train
45468a40d7b53fc1f28bd36b
train
function
def add_topics(new_article, session): for loc_topic in LocalizedTopic.query.all(): if loc_topic.language == new_article.language and loc_topic.matches_article(new_article): new_article.add_topic(loc_topic.topic) session.add(new_article)
def add_topics(new_article, session):
for loc_topic in LocalizedTopic.query.all(): if loc_topic.language == new_article.language and loc_topic.matches_article(new_article): new_article.add_topic(loc_topic.topic) session.add(new_article)
ipped due to time: {skipped} ') log(f' Downloaded: {downloaded}') log(f' Low Quality: {skipped_due_to_low_quality}') log(f' Already in DB: {skipped_already_in_db}') def add_topics(new_article, session):
63
64
51
8
55
simonchristensen1/Zeeguu-Core
zeeguu_core/content_retriever/article_downloader.py
Python
add_topics
add_topics
179
183
179
179
11ef61f1df813c241adb1d8a10b7251371132e36
bigcode/the-stack
train
739ac41bec62f1746115380e
train
function
def download_from_feed(feed: RSSFeed, session, limit=1000): """ Session is needed because this saves stuff to the DB. last_crawled_time is useful because otherwise there would be a lot of time wasted trying to retrieve the same articles, especially the ones which can't be retrieve...
def download_from_feed(feed: RSSFeed, session, limit=1000):
""" Session is needed because this saves stuff to the DB. last_crawled_time is useful because otherwise there would be a lot of time wasted trying to retrieve the same articles, especially the ones which can't be retrieved, so they won't be cached. """ log(feed.title) ...
""" Goes through all the interesting sources that the server knows about and downloads new articles saving them in the DB. """ from datetime import datetime import newspaper import re import zeeguu_core from zeeguu_core import model from zeeguu_core.content_retriever.content_cleaner import cleanup_non_c...
217
256
911
16
201
simonchristensen1/Zeeguu-Core
zeeguu_core/content_retriever/article_downloader.py
Python
download_from_feed
download_from_feed
40
176
40
40
2b78f5cbed01446bcd01b88306010eeee78d84e6
bigcode/the-stack
train
5d270f796a804b0a950e27a5
train
function
def strip_article_title_word(word: str): """ Used when tokenizing the titles of articles in order to index them for search """ return word.strip('":;?!<>\'').lower()
def strip_article_title_word(word: str):
""" Used when tokenizing the titles of articles in order to index them for search """ return word.strip('":;?!<>\'').lower()
the ArticleWord and add it to the session article_word_obj = ArticleWord.find_by_word(word) if article_word_obj is None: article_word_obj = ArticleWord(word) article_word_obj.add_article(new_article) session.add(article_word_obj) def strip_article_title_w...
64
64
46
9
55
simonchristensen1/Zeeguu-Core
zeeguu_core/content_retriever/article_downloader.py
Python
strip_article_title_word
strip_article_title_word
221
228
221
221
417bafc7754846f21833ca4fbe4c3229ebed8ef9
bigcode/the-stack
train
96eddac2ad4ea6e03a7c42c3
train
function
def log(msg: str): zeeguu_core.log(LOG_CONTEXT + " " + msg)
def log(msg: str):
zeeguu_core.log(LOG_CONTEXT + " " + msg)
eguu_core.content_retriever.quality_filter import sufficient_quality from zeeguu_core.model import Url, RSSFeed, LocalizedTopic, ArticleWord from zeeguu_core.constants import SIMPLE_TIME_FORMAT import requests LOG_CONTEXT = "FEED RETRIEVAL" def log(msg: str):
64
64
20
6
58
simonchristensen1/Zeeguu-Core
zeeguu_core/content_retriever/article_downloader.py
Python
log
log
25
26
25
25
1e95d91129cf962959bef3e6303c73aa93224b51
bigcode/the-stack
train
b33967620afecb713be33cba
train
function
def _date_in_the_future(time): from datetime import datetime return time > datetime.now()
def _date_in_the_future(time):
from datetime import datetime return time > datetime.now()
ED RETRIEVAL" def log(msg: str): zeeguu_core.log(LOG_CONTEXT + " " + msg) def _url_after_redirects(url): # solve redirects and save the clean url response = requests.get(url) return response.url def _date_in_the_future(time):
64
64
21
8
55
simonchristensen1/Zeeguu-Core
zeeguu_core/content_retriever/article_downloader.py
Python
_date_in_the_future
_date_in_the_future
35
37
35
35
4097faab9ff48df5650cb5daa59655a9109a018e
bigcode/the-stack
train
7250c6c8b2a9f84589806605
train
function
def _write_section(f, file_type, array, dtype): if file_type["type"] == "ascii": ncols = array.shape[1] fmt = " ".join(["%r"] * ncols) np.savetxt(f, array, fmt=fmt) else: array.astype(dtype).tofile(f)
def _write_section(f, file_type, array, dtype):
if file_type["type"] == "ascii": ncols = array.shape[1] fmt = " ".join(["%r"] * ncols) np.savetxt(f, array, fmt=fmt) else: array.astype(dtype).tofile(f)
append(np.zeros(nitems, dtype=int)) if file_type["type"] == "F": _read_section(f, file_type, count=1, dtype=itype) return Mesh(points, cells, cell_data=cell_data) def _write_section(f, file_type, array, dtype):
64
64
72
13
51
nilsmeyerkit/meshio
src/meshio/ugrid/_ugrid.py
Python
_write_section
_write_section
146
152
146
146
562dd6397225a2de467c827513ab4b03c7ac148d
bigcode/the-stack
train
28ef85ef270af0e0099a95b5
train
function
def read(filename): file_type = determine_file_type(filename) with open_file(filename) as f: mesh = read_buffer(f, file_type) return mesh
def read(filename):
file_type = determine_file_type(filename) with open_file(filename) as f: mesh = read_buffer(f, file_type) return mesh
file_type = file_types["ascii"] filename_parts = str(filename).split(".") if len(filename_parts) > 1: type_suffix = filename_parts[-2] if type_suffix in file_types.keys(): file_type = file_types[type_suffix] return file_type def read(filename):
64
64
36
4
59
nilsmeyerkit/meshio
src/meshio/ugrid/_ugrid.py
Python
read
read
51
55
51
51
5d59db4e24538693759820bb61519431eff0da73
bigcode/the-stack
train
cd4c2b622314e516907c7b52
train
function
def determine_file_type(filename): file_type = file_types["ascii"] filename_parts = str(filename).split(".") if len(filename_parts) > 1: type_suffix = filename_parts[-2] if type_suffix in file_types.keys(): file_type = file_types[type_suffix] return file_type
def determine_file_type(filename):
file_type = file_types["ascii"] filename_parts = str(filename).split(".") if len(filename_parts) > 1: type_suffix = filename_parts[-2] if type_suffix in file_types.keys(): file_type = file_types[type_suffix] return file_type
i4"}, "lr8": {"type": "F", "float_type": "<f8", "int_type": "<i4"}, "lr4": {"type": "F", "float_type": "<f4", "int_type": "<i4"}, } def determine_file_type(filename):
64
64
67
6
58
nilsmeyerkit/meshio
src/meshio/ugrid/_ugrid.py
Python
determine_file_type
determine_file_type
41
48
41
41
ecc3f344a5ccfb02f861bfeafd18dc54b9e8b01c
bigcode/the-stack
train
5975103ddd368a699c9ce6f1
train
function
def _read_section(f, file_type, count, dtype): if file_type["type"] == "ascii": return np.fromfile(f, count=count, dtype=dtype, sep=" ") return np.fromfile(f, count=count, dtype=dtype)
def _read_section(f, file_type, count, dtype):
if file_type["type"] == "ascii": return np.fromfile(f, count=count, dtype=dtype, sep=" ") return np.fromfile(f, count=count, dtype=dtype)
(): file_type = file_types[type_suffix] return file_type def read(filename): file_type = determine_file_type(filename) with open_file(filename) as f: mesh = read_buffer(f, file_type) return mesh def _read_section(f, file_type, count, dtype):
64
64
55
13
50
nilsmeyerkit/meshio
src/meshio/ugrid/_ugrid.py
Python
_read_section
_read_section
58
61
58
58
0037fa1d257d99f0dff868cd9f18c6e4fcb9d517
bigcode/the-stack
train
7543ef1805aa0aafd559cf1e
train
function
def read_buffer(f, file_type): cells = [] cell_data = [] itype = file_type["int_type"] ftype = file_type["float_type"] # Fortran type includes a number of bytes before and after each record, according to # documentation [1] there are two records in the file; see also UG_IO freely # availab...
def read_buffer(f, file_type):
cells = [] cell_data = [] itype = file_type["int_type"] ftype = file_type["float_type"] # Fortran type includes a number of bytes before and after each record, according to # documentation [1] there are two records in the file; see also UG_IO freely # available code at [2]. if file_typ...
4"}, "lr8": {"type": "F", "float_type": "<f8", "int_type": "<i4"}, "lr4": {"type": "F", "float_type": "<f4", "int_type": "<i4"}, } def determine_file_type(filename): file_type = file_types["ascii"] filename_parts = str(filename).split(".") if len(filename_parts) > 1: type_suffix = filename...
223
223
746
8
215
nilsmeyerkit/meshio
src/meshio/ugrid/_ugrid.py
Python
read_buffer
read_buffer
64
143
64
64
8d12d3d90ebbaaca58b624d1734c1f476d7b6d45
bigcode/the-stack
train
fc6a48f31255a53e1939df5f
train
function
def _write_buffer(f, file_type, mesh): itype = file_type["int_type"] ftype = file_type["float_type"] ugrid_counts = { "points": 0, "triangle": 0, "quad": 0, "tetra": 0, "pyramid": 0, "wedge": 0, "hexahedron": 0, } # ugrid type to cell array id...
def _write_buffer(f, file_type, mesh):
itype = file_type["int_type"] ftype = file_type["float_type"] ugrid_counts = { "points": 0, "triangle": 0, "quad": 0, "tetra": 0, "pyramid": 0, "wedge": 0, "hexahedron": 0, } # ugrid type to cell array id ugrid_meshio_id = { "point...
* nvertices, dtype=itype ).reshape(nitems, nvertices) if key == "pyramid": out = out[:, [1, 0, 3, 4, 2]] # UGRID is one-based cells.append(CellBlock(key, out - 1)) # fill volume element attributes with zero cell_data["ugrid:ref"].append(np.zeros(nitems, dt...
256
256
996
11
245
nilsmeyerkit/meshio
src/meshio/ugrid/_ugrid.py
Python
_write_buffer
_write_buffer
162
277
162
162
3b7ab944ffa11c386ad288b112195f150391f622
bigcode/the-stack
train
87c4b285c39a9b1feff3a9ce
train
function
def write(filename, mesh): file_type = determine_file_type(filename) with open_file(filename, "w") as f: _write_buffer(f, file_type, mesh)
def write(filename, mesh):
file_type = determine_file_type(filename) with open_file(filename, "w") as f: _write_buffer(f, file_type, mesh)
if file_type["type"] == "ascii": ncols = array.shape[1] fmt = " ".join(["%r"] * ncols) np.savetxt(f, array, fmt=fmt) else: array.astype(dtype).tofile(f) def write(filename, mesh):
64
64
38
6
58
nilsmeyerkit/meshio
src/meshio/ugrid/_ugrid.py
Python
write
write
155
159
155
155
cddb4a9000865b471c07f81b6acab5eb91d892d1
bigcode/the-stack
train
345038037d13c3730d27c84c
train
class
class BoundaryEvent(IntermediateCatchEvent): """ Task Spec for a bpmn:boundaryEvent node. """ def __init__(self, wf_spec, name, cancel_activity=None, event_definition=None, **kwargs): """ Constructor. :param cancel_activity: True if this is a Cancelling boundar...
class BoundaryEvent(IntermediateCatchEvent):
""" Task Spec for a bpmn:boundaryEvent node. """ def __init__(self, wf_spec, name, cancel_activity=None, event_definition=None, **kwargs): """ Constructor. :param cancel_activity: True if this is a Cancelling boundary event. """ super(BoundaryEv...
my_task.children: if child.task_spec == self.main_child_task_spec: child._set_state(state) def _should_cancel(self, task_spec): return (issubclass(task_spec.__class__, BoundaryEvent) and task_spec._cancel_activity) class BoundaryEvent(IntermediateCatchEvent):
64
64
106
8
56
LipotesOps/octo-fibula
SpiffWorkflow/bpmn/specs/BoundaryEvent.py
Python
BoundaryEvent
BoundaryEvent
65
79
65
65
70d53dd3a4a906e79d552cd71dcbdef729891edc
bigcode/the-stack
train
9bf8c3559013940ab2750656
train
class
class _BoundaryEventParent(BpmnSpecMixin): def __init__(self, wf_spec, name, main_child_task_spec, lane=None, **kwargs): super(_BoundaryEventParent, self).__init__( wf_spec, name, lane=lane, **kwargs) self.main_child_task_spec = main_child_task_spec def _child_comp...
class _BoundaryEventParent(BpmnSpecMixin):
def __init__(self, wf_spec, name, main_child_task_spec, lane=None, **kwargs): super(_BoundaryEventParent, self).__init__( wf_spec, name, lane=lane, **kwargs) self.main_child_task_spec = main_child_task_spec def _child_complete_hook(self, child_task): if (chi...
for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA from ...task import Task from .BpmnSpecMixin import BpmnSpecMixin from .Interme...
100
100
335
10
89
LipotesOps/octo-fibula
SpiffWorkflow/bpmn/specs/BoundaryEvent.py
Python
_BoundaryEventParent
_BoundaryEventParent
25
62
25
26
2264d4edaada024359716c2e28d92fcb45aa50e4
bigcode/the-stack
train
233c0e531e4107ba0e4c11c1
train
function
def hsv2rgb(h, s, v): h = float(h) s = float(s) v = float(v) h60 = h / 60.0 h60f = math.floor(h60) hi = int(h60f) % 6 f = h60 - h60f p = v * (1 - s) q = v * (1 - f * s) t = v * (1 - (1 - f) * s) r, g, b = 0, 0, 0 if hi == 0: r, g, b = v, t, p elif hi == 1: r, g, b = q, v, p elif hi == 2: r, ...
def hsv2rgb(h, s, v):
h = float(h) s = float(s) v = float(v) h60 = h / 60.0 h60f = math.floor(h60) hi = int(h60f) % 6 f = h60 - h60f p = v * (1 - s) q = v * (1 - f * s) t = v * (1 - (1 - f) * s) r, g, b = 0, 0, 0 if hi == 0: r, g, b = v, t, p elif hi == 1: r, g, b = q, v, p elif hi == 2: r, g, b = p, v, t elif ...
RGBLED(expander, [3, 4, 5, 6], False) rgbLED3 = RGBLED(expander, [6, 7, 8, 9], False) rgbLED4 = RGBLED(expander, [9, 10, 11, 12], False) expander.startInternalClock() def hsv2rgb(h, s, v):
81
81
272
10
71
ATX-Sabine/Golden-Raider-2017
code/examples/RGB-LED-Cycle.py
Python
hsv2rgb
hsv2rgb
19
38
19
19
e8931d91e3d206e1b548f72b43ca8b06b4cf480a
bigcode/the-stack
train
4090b0595f403578c337115f
train
function
def VBGL_IOCTL_CODE_SIZE(func, size): return 0xc0005600 + (size<<16) + func
def VBGL_IOCTL_CODE_SIZE(func, size):
return 0xc0005600 + (size<<16) + func
ParmType_32bit = 1 VMMDevHGCMParmType_64bit = 2 VMMDevHGCMParmType_LinAddr = 4 VMMDevHGCMParmType_PageList = 10 def VBGL_IOCTL_CODE_SIZE(func, size):
64
64
27
10
53
1052847690/3dpwn
lib/hgcm.py
Python
VBGL_IOCTL_CODE_SIZE
VBGL_IOCTL_CODE_SIZE
21
22
21
21
dcc247533ebb3a75d7dc7735aa6a9cee39110b0a
bigcode/the-stack
train
c68dda6c1a4ff153abcb1cce
train
function
def hgcm_connect(svc): ''' Connect to the HGCM service by the given name. Returns client ID. ''' ''' # define VBGL_IOCTL_HGCM_CONNECT VBGL_IOCTL_CODE_SIZE(4, VBGL_IOCTL_HGCM_CONNECT_SIZE) # define VBGL_IOCTL_HGCM_CONNECT_SIZE sizeof(VBGLIOCHGCMCONNECT) # def...
def hgcm_connect(svc):
''' Connect to the HGCM service by the given name. Returns client ID. ''' ''' # define VBGL_IOCTL_HGCM_CONNECT VBGL_IOCTL_CODE_SIZE(4, VBGL_IOCTL_HGCM_CONNECT_SIZE) # define VBGL_IOCTL_HGCM_CONNECT_SIZE sizeof(VBGLIOCHGCMCONNECT) # define VBGL_IOCTL_HGCM_CON...
if fd is None: fd = os.open('/dev/vboxuser', os.O_RDWR) data = array('b', vbox_ioctl_header(len(data), outsize) + data.ljust(outsize, '\0')) rc = fcntl.ioctl(fd, VBGL_IOCTL_CODE_SIZE(func, len(data)), data, 1) if rc: raise IOError('VBoxError (IOCTL): %d' % rc) _,_,_,rc,_,_ = unpack(...
151
151
505
7
144
1052847690/3dpwn
lib/hgcm.py
Python
hgcm_connect
hgcm_connect
69
131
69
69
c52d2f53f75c97d407c24c14151276bd7a4c11ee
bigcode/the-stack
train
1c48c1b97eb0cff9cb163002
train
function
def hgcm_disconnect(client_id): ''' Disconnect the given HGCM client. ''' ''' # define VBGL_IOCTL_HGCM_DISCONNECT VBGL_IOCTL_CODE_SIZE(5, VBGL_IOCTL_HGCM_DISCONNECT_SIZE) # define VBGL_IOCTL_HGCM_DISCONNECT_SIZE sizeof(VBGLIOCHGCMDISCONNECT) # define VBGL_IOCTL_HG...
def hgcm_disconnect(client_id):
''' Disconnect the given HGCM client. ''' ''' # define VBGL_IOCTL_HGCM_DISCONNECT VBGL_IOCTL_CODE_SIZE(5, VBGL_IOCTL_HGCM_DISCONNECT_SIZE) # define VBGL_IOCTL_HGCM_DISCONNECT_SIZE sizeof(VBGLIOCHGCMDISCONNECT) # define VBGL_IOCTL_HGCM_DISCONNECT_SIZE_IN si...
Size(HGCMServiceLocation, 128+4); ''' data = pack('<I128s', 2, # type = LocalHost_Existing svc # achName ) client_id, = unpack('<I', vbox_ioctl(IOCTL_HGCM_CONNECT, data, 4)) return client_id def hgcm_disconnect(client_id):
80
80
269
7
72
1052847690/3dpwn
lib/hgcm.py
Python
hgcm_disconnect
hgcm_disconnect
133
159
133
133
db3b4307775d18bbc6484312d05516461ac5f2e9
bigcode/the-stack
train
3daf5d7860579f9a7a37f7b8
train
function
def vbox_ioctl(func, data, outsize): global fd if fd is None: fd = os.open('/dev/vboxuser', os.O_RDWR) data = array('b', vbox_ioctl_header(len(data), outsize) + data.ljust(outsize, '\0')) rc = fcntl.ioctl(fd, VBGL_IOCTL_CODE_SIZE(func, len(data)), data, 1) if rc: raise IOError('VBoxE...
def vbox_ioctl(func, data, outsize):
global fd if fd is None: fd = os.open('/dev/vboxuser', os.O_RDWR) data = array('b', vbox_ioctl_header(len(data), outsize) + data.ljust(outsize, '\0')) rc = fcntl.ioctl(fd, VBGL_IOCTL_CODE_SIZE(func, len(data)), data, 1) if rc: raise IOError('VBoxError (IOCTL): %d' % rc) _,_,_,rc,...
0, # uType = VBGLREQHDR_TYPE_DEFAULT -225, # rc = VERR_INTERNAL_ERROR 24+outsize, # cbOut 0) # uReserved fd = None def vbox_ioctl(func, data, outsize):
64
64
158
11
52
1052847690/3dpwn
lib/hgcm.py
Python
vbox_ioctl
vbox_ioctl
56
67
56
56
341110841c8fee0aef5a444c8ef802afa031c63d
bigcode/the-stack
train
51ee6140b83b0f82138df4d8
train
function
def vbox_ioctl_header(insize, outsize): ''' typedef struct VBGLREQHDR { /** IN: The request input size, and output size if cbOut is zero. * @sa VMMDevRequestHeader::size */ uint32_t cbIn; /** IN: Structure version (VBGLREQHDR_VERSION) * @sa VMMDevRequestHead...
def vbox_ioctl_header(insize, outsize):
''' typedef struct VBGLREQHDR { /** IN: The request input size, and output size if cbOut is zero. * @sa VMMDevRequestHeader::size */ uint32_t cbIn; /** IN: Structure version (VBGLREQHDR_VERSION) * @sa VMMDevRequestHeader::version */ uint32_t u...
VMMDevHGCMParmType_32bit = 1 VMMDevHGCMParmType_64bit = 2 VMMDevHGCMParmType_LinAddr = 4 VMMDevHGCMParmType_PageList = 10 def VBGL_IOCTL_CODE_SIZE(func, size): return 0xc0005600 + (size<<16) + func def vbox_ioctl_header(insize, outsize):
98
98
328
11
86
1052847690/3dpwn
lib/hgcm.py
Python
vbox_ioctl_header
vbox_ioctl_header
24
53
24
24
6d4413a9ca76745c3bdac0bddf12c4d1e591cea5
bigcode/the-stack
train
9dfa67bfbe4b79ecd4ffe095
train
function
def hgcm_call(client_id, func, params): ''' Call an HGCM function. Supported parameter types: * int; VMMDevHGCMParmType_32bit * string/bytes: VMMDevHGCMParmType_LinAddr It will return all parameters after the call, in case they were modified by the function. ''' ''' typedef st...
def hgcm_call(client_id, func, params):
''' Call an HGCM function. Supported parameter types: * int; VMMDevHGCMParmType_32bit * string/bytes: VMMDevHGCMParmType_LinAddr It will return all parameters after the call, in case they were modified by the function. ''' ''' typedef struct VBGLIOCHGCMCALL { /** C...
VBGL_IOCTL_HGCM_DISCONNECT VBGL_IOCTL_CODE_SIZE(5, VBGL_IOCTL_HGCM_DISCONNECT_SIZE) # define VBGL_IOCTL_HGCM_DISCONNECT_SIZE sizeof(VBGLIOCHGCMDISCONNECT) # define VBGL_IOCTL_HGCM_DISCONNECT_SIZE_IN sizeof(VBGLIOCHGCMDISCONNECT) # define VBGL_IOCTL_HGCM_DISCONNECT_SIZE_OU...
256
256
1,188
11
245
1052847690/3dpwn
lib/hgcm.py
Python
hgcm_call
hgcm_call
162
282
162
162
fa31d6c811e34758c478ea9abeb2b6b2a49f54c2
bigcode/the-stack
train
abf02904b3356c59027d29bc
train
class
class BasicTensorFlowAlgorithmSingleAssetClassifier(QCAlgorithm): def Initialize(self): # init the tensorflow model object self.model = Model() # setup backtest self.SetStartDate(2016,1,1) #Set Start Date self.SetEndDate(2018,9,30) #Set End Date self.SetCash(10...
class BasicTensorFlowAlgorithmSingleAssetClassifier(QCAlgorithm):
def Initialize(self): # init the tensorflow model object self.model = Model() # setup backtest self.SetStartDate(2016,1,1) #Set Start Date self.SetEndDate(2018,9,30) #Set End Date self.SetCash(100000) #Set Strategy Cash ## Find more symb...
import tensorflow as tf import random import numpy as np import pandas as pd seed = 15 random.seed(seed) np.random.seed(seed) tf.set_random_seed(seed) class BasicTensorFlowAlgorithmSingleAssetClassifier(QCAlgorithm):
51
178
594
12
39
manganganath/QuantConnect-Trading-Strategies
A0168820B_CryptoModel.py
Python
BasicTensorFlowAlgorithmSingleAssetClassifier
BasicTensorFlowAlgorithmSingleAssetClassifier
13
78
13
14
5be4ff68ff8f022cb9ccd245b7bd2ac67011ac9f
bigcode/the-stack
train
3850e3da42b79f9fea80da5b
train
class
class Model(): def __init__(self): # Number of inputs for training (will loose 1) self.eval_lookback = 252*4 + 1# input batch size will be eval_lookback+n_features-1 #252*4+1 # We will feed in the past n open-to-open price changes self.n_features = 15 #15 ...
class Model():
def __init__(self): # Number of inputs for training (will loose 1) self.eval_lookback = 252*4 + 1# input batch size will be eval_lookback+n_features-1 #252*4+1 # We will feed in the past n open-to-open price changes self.n_features = 15 #15 # How much...
current price for model to use at end of historical data self.model.current_price = float(self.Securities[self.symbol].Price) # Accrew history over time vs making huge, slow history calls each step. if not self.do_once: new_hist = self.History([self.symbol,], 1, Resolu...
256
256
1,220
3
253
manganganath/QuantConnect-Trading-Strategies
A0168820B_CryptoModel.py
Python
Model
Model
81
190
81
82
4a61becdf5480ea9cd6c3c4b9006d67e61b15450
bigcode/the-stack
train
8f741c0ece0bd579440146e7
train
class
class InfLibraryClassObject(): def __init__(self): self.LibraryClasses = Sdict() # # Macro defined in this section should be only used in this section. # self.Macros = {} ##SetLibraryClasses # # # @param HelpString: It can be a common comment or contain ...
class InfLibraryClassObject():
def __init__(self): self.LibraryClasses = Sdict() # # Macro defined in this section should be only used in this section. # self.Macros = {} ##SetLibraryClasses # # # @param HelpString: It can be a common comment or contain a recommend # ...
LibName(self, LibName): self.LibName = LibName def GetLibName(self): return self.LibName def SetHelpString(self, HelpString): self.HelpString = HelpString def GetHelpString(self): return self.HelpString def SetFeatureFlagExp(self, FeatureFlagExp): self.FeatureFl...
256
256
1,310
6
250
James992927108/uEFI_Edk2_Practice
BaseTools/Source/Python/UPT/Object/Parser/InfLibraryClassesObject.py
Python
InfLibraryClassObject
InfLibraryClassObject
111
253
111
111
0a88f0f985e70b7ae37cdc6cf03bd5a02e9a51d7
bigcode/the-stack
train
05536e20a9e3505821acf661
train
class
class InfLibraryClassItem(): def __init__(self, LibName='', FeatureFlagExp='', HelpString=None): self.LibName = LibName self.FeatureFlagExp = FeatureFlagExp self.HelpString = HelpString self.CurrentLine = CurrentLine() self.SupArchList = [] self.SupModuleList = [] ...
class InfLibraryClassItem():
def __init__(self, LibName='', FeatureFlagExp='', HelpString=None): self.LibName = LibName self.FeatureFlagExp = FeatureFlagExp self.HelpString = HelpString self.CurrentLine = CurrentLine() self.SupArchList = [] self.SupModuleList = [] self.FileGuid = '' ...
ArchItem = 'COMMON' if (ModuleItem == '' or ModuleItem == None): ModuleItem = 'COMMON' if ArchItem not in __SupArchList: __SupArchList.append(ArchItem) List = ModuleItem.split('|') for Entry in List: if Entry not in __SupModuleList: ...
98
98
329
6
92
James992927108/uEFI_Edk2_Practice
BaseTools/Source/Python/UPT/Object/Parser/InfLibraryClassesObject.py
Python
InfLibraryClassItem
InfLibraryClassItem
58
105
58
58
97c39fce460ec2c69106edf1fc896ba64ca84085
bigcode/the-stack
train
09225fb5bed89f074a45cd66
train
function
def GetArchModuleType(KeyList): __SupArchList = [] __SupModuleList = [] for (ArchItem, ModuleItem) in KeyList: # # Validate Arch # if (ArchItem == '' or ArchItem == None): ArchItem = 'COMMON' if (ModuleItem == '' or ModuleItem == None): ...
def GetArchModuleType(KeyList):
__SupArchList = [] __SupModuleList = [] for (ArchItem, ModuleItem) in KeyList: # # Validate Arch # if (ArchItem == '' or ArchItem == None): ArchItem = 'COMMON' if (ModuleItem == '' or ModuleItem == None): ModuleItem = 'COMMON' ...
Library.Misc import Sdict from Object.Parser.InfCommonObject import CurrentLine from Library.ExpressionValidate import IsValidFeatureFlagExp from Library.ParserValidate import IsValidLibName ## GetArchModuleType # # Get Arch List and ModuleType List # def GetArchModuleType(KeyList):
64
64
151
8
56
James992927108/uEFI_Edk2_Practice
BaseTools/Source/Python/UPT/Object/Parser/InfLibraryClassesObject.py
Python
GetArchModuleType
GetArchModuleType
33
55
33
33
8ca3a8399cc803f47720c1c1874f936403bfa81c
bigcode/the-stack
train
366279c7a4ddf32fbf5602f1
train
class
class MicroC: """Class for microC parser/compiler""" def __init__(self): # Definitions of terminal symbols for microC programming language self.tId = Word(alphas + "_", alphanums + "_") self.tInteger = Word(nums).setParseAction( lambda x: [x[0], SharedData.TYPES.INT] ...
class MicroC:
"""Class for microC parser/compiler""" def __init__(self): # Definitions of terminal symbols for microC programming language self.tId = Word(alphas + "_", alphanums + "_") self.tInteger = Word(nums).setParseAction( lambda x: [x[0], SharedData.TYPES.INT] ) ...
", const, "%15") self.newline_label(self.shared.function_name + "_body", True, True) def function_end(self): """Inserts an exit label and function return instructions""" self.newline_label(self.shared.function_name + "_exit", True, True) self.move("%14", "%15") self.p...
255
256
5,711
4
251
klahnakoski/mo-parsing
examples/pymicko.py
Python
MicroC
MicroC
975
1,622
975
975
83bf8b2a97643233b338da128de4319d3a893340
bigcode/the-stack
train
a436944508608051d2f07f23
train
class
class ExceptionSharedData: """Class for exception handling data""" def __init__(self): # position in currently parsed text self.location = 0 # currently parsed text self.text = "" def setpos(self, location, text): """Helper function for setting curently pa...
class ExceptionSharedData:
"""Class for exception handling data""" def __init__(self): # position in currently parsed text self.location = 0 # currently parsed text self.text = "" def setpos(self, location, text): """Helper function for setting curently parsed text and position""" ...
function self.functon_name = 0 # number of parameters of the currently parsed function self.function_params = 0 # number of local variables of the currently parsed function self.function_vars = 0 #########################################################################...
63
64
82
5
58
klahnakoski/mo-parsing
examples/pymicko.py
Python
ExceptionSharedData
ExceptionSharedData
263
275
263
263
f41ad43fa2f3ab9a3b94d14bdae992909fd8524b
bigcode/the-stack
train
090ea2ac9d1c724d3aede4bc
train
class
class SymbolTableEntry: """Class which represents one symbol table entry.""" def __init__(self, sname="", skind=0, stype=0, sattr=None, sattr_name="None"): """Initialization of symbol table entry. sname - symbol name skind - symbol kind stype - symbol type ...
class SymbolTableEntry:
"""Class which represents one symbol table entry.""" def __init__(self, sname="", skind=0, stype=0, sattr=None, sattr_name="None"): """Initialization of symbol table entry. sname - symbol name skind - symbol kind stype - symbol type sattr - symbol attr...
%d, col %d" % (self.line, self.col) msg += ": %s" % self.message if self.print_location and (self.line != None): msg += "\n%s" % self.text return msg ########################################################################################## ################################...
65
66
223
5
60
klahnakoski/mo-parsing
examples/pymicko.py
Python
SymbolTableEntry
SymbolTableEntry
322
351
322
322
37ae04c8148bf924c9fb3f87be0d4ffa96801668
bigcode/the-stack
train
7924a4cec9f10043909a5e64
train
class
class SemanticException(Exception): """Exception for semantic errors found during parsing, similar to ParseException. Introduced because ParseException is used internally in mo_parsing and custom messages got lost and replaced by mo_parsing's generic errors. """ def __init__(self, messa...
class SemanticException(Exception):
"""Exception for semantic errors found during parsing, similar to ParseException. Introduced because ParseException is used internally in mo_parsing and custom messages got lost and replaced by mo_parsing's generic errors. """ def __init__(self, message, print_location=True): su...
Class for exception handling data""" def __init__(self): # position in currently parsed text self.location = 0 # currently parsed text self.text = "" def setpos(self, location, text): """Helper function for setting curently parsed text and position""" ...
87
87
292
5
82
klahnakoski/mo-parsing
examples/pymicko.py
Python
SemanticException
SemanticException
281
315
281
281
019355188d352eb509d727a98e4ac59393fde1cf
bigcode/the-stack
train
ff9450a264532e8811a9a607
train
class
class CodeGenerator: """Class for code generation methods.""" # dictionary of relational operators RELATIONAL_DICT = {op: i for i, op in enumerate(SharedData.RELATIONAL_OPERATORS)} # conditional jumps for relational operators CONDITIONAL_JUMPS = [ "JLTS", "JGTS", "J...
class CodeGenerator:
"""Class for code generation methods.""" # dictionary of relational operators RELATIONAL_DICT = {op: i for i, op in enumerate(SharedData.RELATIONAL_OPERATORS)} # conditional jumps for relational operators CONDITIONAL_JUMPS = [ "JLTS", "JGTS", "JLES", "JGES",...
index - index in symbol table function_index - function's index in symbol table argument_number - # of function's argument """ try: same = ( self.table[function_index].param_types[argument_number] == self.table[index].type ...
255
256
2,838
4
251
klahnakoski/mo-parsing
examples/pymicko.py
Python
CodeGenerator
CodeGenerator
622
968
622
622
c6d99c7672494fc10f4df97d8e4cd3308f6c94a2
bigcode/the-stack
train
a9ce8a99be2a4da4016857b1
train
class
class SharedData: """Data used in all three main classes""" # Possible kinds of symbol table entries KINDS = Enumerate( "NO_KIND WORKING_REGISTER GLOBAL_VAR FUNCTION PARAMETER LOCAL_VAR CONSTANT" ) # Supported types of functions and variables TYPES = Enumerate("NO_TYPE INT UNSIG...
class SharedData:
"""Data used in all three main classes""" # Possible kinds of symbol table entries KINDS = Enumerate( "NO_KIND WORKING_REGISTER GLOBAL_VAR FUNCTION PARAMETER LOCAL_VAR CONSTANT" ) # Supported types of functions and variables TYPES = Enumerate("NO_TYPE INT UNSIGNED") # bit ...
return_statement # -> "return" num_exp ";" # compound_statement # -> "{" statement_list "}" # Comment: /* a comment */ ########################################################################################## ########################################################################################## ...
104
104
348
4
99
klahnakoski/mo-parsing
examples/pymicko.py
Python
SharedData
SharedData
223
256
223
223
85e53cd085bbd79c81845062e5a82b96a939553f
bigcode/the-stack
train
1d67fa4a011f8b717a580967
train
class
class Enumerate(dict): """C enum emulation (original by Scott David Daniels)""" def __init__(self, names): for name in names.split(): number = name.lower() setattr(self, name, number) self[number] = name
class Enumerate(dict):
"""C enum emulation (original by Scott David Daniels)""" def __init__(self, names): for name in names.split(): number = name.lower() setattr(self, name, number) self[number] = name
# -> "while" "(" log_exp ")" statement # return_statement # -> "return" num_exp ";" # compound_statement # -> "{" statement_list "}" # Comment: /* a comment */ ########################################################################################## ##############################################...
63
64
56
5
58
klahnakoski/mo-parsing
examples/pymicko.py
Python
Enumerate
Enumerate
213
220
213
213
866a928b8dc9cca7b675d314ffcc828163b3be19
bigcode/the-stack
train
70aa540231c7c511734cb63a
train
class
class SymbolTable: """Class for symbol table of microC program""" def __init__(self, shared): """Initialization of the symbol table""" self.table = [] self.lable_len = 0 # put working registers in the symbol table for reg in range(SharedData.FUNCTION_REGISTER + 1...
class SymbolTable:
"""Class for symbol table of microC program""" def __init__(self, shared): """Initialization of the symbol table""" self.table = [] self.lable_len = 0 # put working registers in the symbol table for reg in range(SharedData.FUNCTION_REGISTER + 1): self...
self.line != None): msg += "\n%s" % self.text return msg ########################################################################################## ########################################################################################## class SymbolTableEntry: """Class which repr...
255
256
2,023
4
251
klahnakoski/mo-parsing
examples/pymicko.py
Python
SymbolTable
SymbolTable
354
615
354
354
422c8e234773763bddebcec2bbdcbddce6aac9d5
bigcode/the-stack
train
b9945a2f04ca3dea77f0f00c
train
class
class VOTLTDataset(Dataset): """ Args: name: dataset name, 'VOT2018-LT' dataset_root: dataset root load_img: wether to load all imgs """ def __init__(self, name, dataset_root, load_img=False): super(VOTLTDataset, self).__init__(name, dataset_root) with open(os.pat...
class VOTLTDataset(Dataset):
""" Args: name: dataset name, 'VOT2018-LT' dataset_root: dataset root load_img: wether to load all imgs """ def __init__(self, name, dataset_root, load_img=False): super(VOTLTDataset, self).__init__(name, dataset_root) with open(os.path.join(dataset_root, name+'.j...
idence_file, 'r') as f: score = [float(x.strip()) for x in f.readlines()[1:]] score.insert(0, float('nan')) if store: self.confidence[name] = score return traj, score class VOTLTDataset(Dataset):
64
64
209
9
54
Existever/PyCFTrackers
lib/pysot/datasets/vot.py
Python
VOTLTDataset
VOTLTDataset
179
201
179
179
dc82886ee1085edeb57b5c02cc5860f748f7f811
bigcode/the-stack
train
3ae372bf776ccbcffbc52fb4
train
class
class VOTVideo(Video): """ Args: name: video name root: dataset root video_dir: video directory init_rect: init rectangle img_names: image names gt_rect: groundtruth rectangle camera_motion: camera motion tag illum_change: illum change tag ...
class VOTVideo(Video):
""" Args: name: video name root: dataset root video_dir: video directory init_rect: init rectangle img_names: image names gt_rect: groundtruth rectangle camera_motion: camera motion tag illum_change: illum change tag motion_change: motion c...
import os import cv2 import json import numpy as np from glob import glob from tqdm import tqdm from PIL import Image from .dataset import Dataset from .video import Video class VOTVideo(Video):
48
236
788
6
41
Existever/PyCFTrackers
lib/pysot/datasets/vot.py
Python
VOTVideo
VOTVideo
13
92
13
13
63c5a51774924bb2f6f3cee624d9a5e591ea4c69
bigcode/the-stack
train
297964108b73cd01001067c7
train
class
class VOTLTVideo(Video): """ Args: name: video name root: dataset root video_dir: video directory init_rect: init rectangle img_names: image names gt_rect: groundtruth rectangle """ def __init__(self, name, root, video_dir, init_rect, img_names, ...
class VOTLTVideo(Video):
""" Args: name: video name root: dataset root video_dir: video directory init_rect: init rectangle img_names: image names gt_rect: groundtruth rectangle """ def __init__(self, name, root, video_dir, init_rect, img_names, gt_rect, load_img=False...
= VOTVideo(video, dataset_root, meta_data[video]['video_dir'], meta_data[video]['init_rect'], meta_data[video]['img_names'], ...
136
136
456
7
129
Existever/PyCFTrackers
lib/pysot/datasets/vot.py
Python
VOTLTVideo
VOTLTVideo
128
177
128
128
df5a60b6d97bfdc9520e64d640427ea3004861ae
bigcode/the-stack
train
1ed042a33e47f6abbe845120
train
class
class VOTDataset(Dataset): """ Args: name: dataset name, should be 'VOT2018', 'VOT2016' dataset_root: dataset root load_img: wether to load all imgs """ def __init__(self, name, dataset_root, load_img=False): super(VOTDataset, self).__init__(name, dataset_root) wi...
class VOTDataset(Dataset):
""" Args: name: dataset name, should be 'VOT2018', 'VOT2016' dataset_root: dataset root load_img: wether to load all imgs """ def __init__(self, name, dataset_root, load_img=False): super(VOTDataset, self).__init__(name, dataset_root) with open(os.path.join(datase...
pred_traj = [] for traj_file in traj_files: with open(traj_file, 'r') as f: traj = [list(map(float, x.strip().split(','))) for x in f.readlines()] pred_traj.append(traj) if store: self.pred_trajs...
87
87
293
7
79
Existever/PyCFTrackers
lib/pysot/datasets/vot.py
Python
VOTDataset
VOTDataset
94
125
94
94
eeb3cd18bd79cbc90bfc84c8c2ada717071b22dc
bigcode/the-stack
train
215533d51231da80c3847a93
train
function
def pozeni_umesnik(): #Naredimo novo igro trenutna_igra = model.nova_igra() while True: print(izpis_igra(trenutna_igra)) crka = zahtevaj_vnos() rezultat = trenutna_igra.ugibaj(crka) if trenutna_igra.zmaga(): print(izpis_zmage(trenutna_igra)) break ...
def pozeni_umesnik(): #Naredimo novo igro
trenutna_igra = model.nova_igra() while True: print(izpis_igra(trenutna_igra)) crka = zahtevaj_vnos() rezultat = trenutna_igra.ugibaj(crka) if trenutna_igra.zmaga(): print(izpis_zmage(trenutna_igra)) break if trenutna_igra.poraz(): p...
ILO_DOVOLJENIH_NAPAK - igra.stevilo_napak()} možnosti za napako' ) return text def zahtevaj_vnos(): return input('Vpiši naslednjo črko') def pozeni_umesnik(): #Naredimo novo igro
64
64
131
16
48
bernardkucina/vislice
tekstovni_umeski.py
Python
pozeni_umesnik
pozeni_umesnik
21
36
21
22
b691bd428b952373d6c3fe6e3fe39f5066c572ca
bigcode/the-stack
train
7f586ccaef80b05d04d94228
train
function
def izpis_zmage(igra): return f'ZMAGAL SI, GESLO JE BILO: {igra.geslo},' + f'POTREBOVAL SI {len(igra.napacne_crke())} UGIBOV'
def izpis_zmage(igra):
return f'ZMAGAL SI, GESLO JE BILO: {igra.geslo},' + f'POTREBOVAL SI {len(igra.napacne_crke())} UGIBOV'
import model def izpis_poraza(igra): return f'IZGUBIL SI , GESLO JE BILO: {igra.geslo}' def izpis_zmage(igra):
46
64
59
9
37
bernardkucina/vislice
tekstovni_umeski.py
Python
izpis_zmage
izpis_zmage
6
7
6
6
b1d9d10b983c6dac6452374e05d1b8f4e2591507
bigcode/the-stack
train
d55eca7ba5113233084dc929
train
function
def izpis_poraza(igra): return f'IZGUBIL SI , GESLO JE BILO: {igra.geslo}'
def izpis_poraza(igra):
return f'IZGUBIL SI , GESLO JE BILO: {igra.geslo}'
import model def izpis_poraza(igra):
12
64
34
9
2
bernardkucina/vislice
tekstovni_umeski.py
Python
izpis_poraza
izpis_poraza
3
4
3
3
6e9f54918359d9d6a32decc3bc0082f5e08d7487
bigcode/the-stack
train
043670d4733b9b721363db84
train
function
def zahtevaj_vnos(): return input('Vpiši naslednjo črko')
def zahtevaj_vnos():
return input('Vpiši naslednjo črko')
tanje gesla: {igra.praviln_del_gesla()} \n ' f'Imaš še {model.STEVILO_DOVOLJENIH_NAPAK - igra.stevilo_napak()} možnosti za napako' ) return text def zahtevaj_vnos():
64
64
19
6
57
bernardkucina/vislice
tekstovni_umeski.py
Python
zahtevaj_vnos
zahtevaj_vnos
18
19
18
18
a6396e85e2ed9dc82f10919a21e807d8b1367ead
bigcode/the-stack
train
8e0fdc08acbf5b830655798d
train
function
def izpis_igra(igra): text = ( f'Stanje gesla: {igra.praviln_del_gesla()} \n ' f'Imaš še {model.STEVILO_DOVOLJENIH_NAPAK - igra.stevilo_napak()} možnosti za napako' ) return text
def izpis_igra(igra):
text = ( f'Stanje gesla: {igra.praviln_del_gesla()} \n ' f'Imaš še {model.STEVILO_DOVOLJENIH_NAPAK - igra.stevilo_napak()} možnosti za napako' ) return text
(igra): return f'ZMAGAL SI, GESLO JE BILO: {igra.geslo},' + f'POTREBOVAL SI {len(igra.napacne_crke())} UGIBOV' def izpis_igra(igra):
64
64
75
10
54
bernardkucina/vislice
tekstovni_umeski.py
Python
izpis_igra
izpis_igra
9
16
9
9
3f7a59cce066b6b41f666362d170283103311b00
bigcode/the-stack
train
d36e132a7d5b89778bac82a7
train
function
def init(): """Initialize the AWS plugin.""" return Aws()
def init():
"""Initialize the AWS plugin.""" return Aws()
""" await send_communications_policy_change_request_v2(extended_request) return @staticmethod def handle_detected_role(role): pass async def should_auto_approve_policy_v2(self, extended_request, user, user_groups): return {"approved": False} def init():
64
64
14
3
61
cyc115/consoleme
consoleme/default_plugins/plugins/aws/aws.py
Python
init
init
725
727
725
725
9ff51804cb38c409b96d59ea4e32c19243b3baca
bigcode/the-stack
train
33024de2cd678dc9146bc85b
train
class
class Aws: """The AWS class handles interactions with AWS.""" def __init__(self) -> None: self.red = RedisHandler().redis_sync() self.redis_key = config.get("aws.iamroles_redis_key", "IAM_ROLE_CACHE") self.dynamo = IAMRoleDynamoHandler() @retry( stop_max_attempt_number=3, ...
class Aws:
"""The AWS class handles interactions with AWS.""" def __init__(self) -> None: self.red = RedisHandler().redis_sync() self.redis_key = config.get("aws.iamroles_redis_key", "IAM_ROLE_CACHE") self.dynamo = IAMRoleDynamoHandler() @retry( stop_max_attempt_number=3, wait...
sys from datetime import datetime, timedelta from typing import Any, Dict, Optional import bleach import boto3 import requests as requests_sync import tenacity import ujson as json from asgiref.sync import sync_to_async from botocore.exceptions import ClientError from cloudaux.aws.iam import ( get_role_inline_pol...
256
256
5,108
3
253
cyc115/consoleme
consoleme/default_plugins/plugins/aws/aws.py
Python
Aws
Aws
40
722
40
40
326d526bebe6e2d12039892e2010e836f5c5fba6
bigcode/the-stack
train
21132dbd732b0f49d6959594
train
class
class core: def __init__(self, environ = None, location = None): self.response = None if environ == None and location == None: #If the environ and the location are None, no make anything. self.response = """<h1>Petition doesn't have <u>Environ</u> or <u>Locatio...
class core:
def __init__(self, environ = None, location = None): self.response = None if environ == None and location == None: #If the environ and the location are None, no make anything. self.response = """<h1>Petition doesn't have <u>Environ</u> or <u>Location</u></h1>""" ...
from datetime import datetime import os class core:
13
201
670
4
8
hidura/sugelico
tools/loadKar.py
Python
core
core
6
90
6
8
da6050c740a28734b1463d2d27c949d4f90d7378
bigcode/the-stack
train
c3fa1c4205fda389e7201e00
train
class
class WeatherServiceFailedToRetrieveException(Exception): pass
class WeatherServiceFailedToRetrieveException(Exception):
pass
class WeatherServiceFailedToLocateException(Exception): pass class WeatherServiceFailedToRetrieveException(Exception):
21
64
12
9
11
Gabriel737/CadorsMap
api/weather/WeatherExceptions.py
Python
WeatherServiceFailedToRetrieveException
WeatherServiceFailedToRetrieveException
4
5
4
4
c8d674d96ee48cd75c968a454ca23b5b3af6a798
bigcode/the-stack
train
2a80ff54033702f8b0fffb08
train
class
class WeatherServiceFailedToLocateException(Exception): pass
class WeatherServiceFailedToLocateException(Exception):
pass
class WeatherServiceFailedToLocateException(Exception):
9
64
12
9
0
Gabriel737/CadorsMap
api/weather/WeatherExceptions.py
Python
WeatherServiceFailedToLocateException
WeatherServiceFailedToLocateException
1
2
1
1
e5cd940491bfb4f050be98e8fc67a354099cccab
bigcode/the-stack
train
9e262f0d2ba31a2234451e75
train
class
class CTS(Converter): """ Chemical Translation Service performs batch conversions of the most common compound identifiers. Available online at: http://cts.fiehnlab.ucdavis.edu More info about the available conversions: http://cts.fiehnlab.ucdavis.edu/services """ def __init__(self, session): ...
class CTS(Converter):
""" Chemical Translation Service performs batch conversions of the most common compound identifiers. Available online at: http://cts.fiehnlab.ucdavis.edu More info about the available conversions: http://cts.fiehnlab.ucdavis.edu/services """ def __init__(self, session): super().__init_...
import json from MSMetaEnhancer.libs.services.Converter import Converter class CTS(Converter):
20
227
758
5
14
xtrojak/pyMSPannotator
MSMetaEnhancer/libs/services/CTS.py
Python
CTS
CTS
6
104
6
6
e66ce3234b7c3eae7ab252504d9002dcb64badd9
bigcode/the-stack
train
b07055f66f64e4cfa64195d9
train
class
class CrossEntropyLoss(BaseLoss): """Calculate the cross entropy loss between the predictions and labels. """ def calculate_loss(self, predictions, labels, **unused_params): with tf.name_scope("loss_xent"): epsilon = 10e-6 float_labels = tf.cast(labels, tf.float32) ...
class CrossEntropyLoss(BaseLoss):
"""Calculate the cross entropy loss between the predictions and labels. """ def calculate_loss(self, predictions, labels, **unused_params): with tf.name_scope("loss_xent"): epsilon = 10e-6 float_labels = tf.cast(labels, tf.float32) cross_entropy_loss = float_label...
-d tensor storing the labels, which has the same shape as the unused_predictions. The labels must be in the range of 0 and 1. unused_params: loss specific parameters. Returns: A scalar loss tensor. """ raise NotImplementedError() class CrossEntropyLoss(BaseLoss):...
64
64
130
7
57
pomonam/youtube-8m
losses.py
Python
CrossEntropyLoss
CrossEntropyLoss
41
51
41
41
79cccc7f1cd5df3b0e0625ffc4a08e004f82f098
bigcode/the-stack
train
d483cf8c5af1c472dd32d57d
train
class
class HingeLoss(BaseLoss): """Calculate the hinge loss between the predictions and labels. Note the subgradient is used in the backpropagation, and thus the optimization may converge slower. The predictions trained by the hinge loss are between -1 and +1. """ def calculate_loss(self, prediction...
class HingeLoss(BaseLoss):
"""Calculate the hinge loss between the predictions and labels. Note the subgradient is used in the backpropagation, and thus the optimization may converge slower. The predictions trained by the hinge loss are between -1 and +1. """ def calculate_loss(self, predictions, labels, b=1.0, **unused_...
_labels * tf.log(predictions + epsilon) + \ (1 - float_labels) * tf.log(1 - predictions + epsilon) cross_entropy_loss = tf.negative(cross_entropy_loss) return tf.reduce_mean(tf.reduce_sum(cross_entropy_loss, 1)) class HingeLoss(BaseLoss):
64
64
199
7
57
pomonam/youtube-8m
losses.py
Python
HingeLoss
HingeLoss
54
69
54
54
f3548657f0a69eab24c8c8ce8083ffb6995cd571
bigcode/the-stack
train
c4b947a6ff7464b40e67835a
train
class
class BaseLoss(object): """Inherit from this class when implementing new losses.""" def calculate_loss(self, unused_predictions, unused_labels, **unused_params): """Calculates the average loss of the examples in a mini-batch. Args: unused_predictions: a 2-d tensor storing the predic...
class BaseLoss(object):
"""Inherit from this class when implementing new losses.""" def calculate_loss(self, unused_predictions, unused_labels, **unused_params): """Calculates the average loss of the examples in a mini-batch. Args: unused_predictions: a 2-d tensor storing the prediction scores, in which ...
OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Provides definitions for non-regularized training or test losses.""" # noinspection PyUnresolvedReferences import pathmagic import tensorflow as tf class Base...
64
64
153
5
58
pomonam/youtube-8m
losses.py
Python
BaseLoss
BaseLoss
21
38
21
21
9dd04f21a8669e110395647f9bdb6e9f90c495d6
bigcode/the-stack
train
c1fd86d9935177de75f17098
train
class
class SoftmaxLoss(BaseLoss): """Calculate the softmax loss between the predictions and labels. The function calculates the loss in the following way: first we feed the predictions to the softmax activation function and then we calculate the minus linear dot product between the logged softmax activation...
class SoftmaxLoss(BaseLoss):
"""Calculate the softmax loss between the predictions and labels. The function calculates the loss in the following way: first we feed the predictions to the softmax activation function and then we calculate the minus linear dot product between the logged softmax activations and the normalized grou...
=tf.float32) sign_labels = tf.subtract(tf.scalar_mul(2, float_labels), all_ones) hinge_loss = tf.maximum( all_zeros, tf.scalar_mul(b, all_ones) - sign_labels * predictions) return tf.reduce_mean(tf.reduce_sum(hinge_loss, 1)) class SoftmaxLoss(BaseLoss):
73
73
246
7
66
pomonam/youtube-8m
losses.py
Python
SoftmaxLoss
SoftmaxLoss
72
96
72
72
48a95a356c9f06efb636df0627e2fa34456b2338
bigcode/the-stack
train
bb61343a1a3570f4d1afdbea
train
function
def add_panet_config(cfg): """ Add config for PANet. """ # Filter annotations by area cfg.DATALOADER.FILTER_ANNOTATIONS_AREA = CN() cfg.DATALOADER.FILTER_ANNOTATIONS_AREA.MIN_AREA = 0 cfg.DATALOADER.FILTER_ANNOTATIONS_AREA.MAX_AREA = 1e6 # Fully Connected Fusion cfg.MODEL.ROI_MASK_H...
def add_panet_config(cfg):
""" Add config for PANet. """ # Filter annotations by area cfg.DATALOADER.FILTER_ANNOTATIONS_AREA = CN() cfg.DATALOADER.FILTER_ANNOTATIONS_AREA.MIN_AREA = 0 cfg.DATALOADER.FILTER_ANNOTATIONS_AREA.MAX_AREA = 1e6 # Fully Connected Fusion cfg.MODEL.ROI_MASK_HEAD.FCF = CN() cfg.MODE...
# -*- coding: utf-8 -*- from detectron2.config import CfgNode as CN def add_panet_config(cfg):
27
64
131
7
19
ashnair1/detectron2
projects/PANet/panet/config.py
Python
add_panet_config
add_panet_config
5
17
5
5
b9d9902411ad5d63038ea2ab7cc130354b9cd59d
bigcode/the-stack
train
7bfc56b22b35f529b81da531
train
function
def set_extended_from_env(extended: Optional[bool] = None, force: bool = False) -> None: # env settings have precedence, unless force=True - if nothing is passed, the default value will be used """ >>> # Setup >>> default_fmt = log_settings.fmt >>> # No env Setting, extended=None >>> set_extend...
def set_extended_from_env(extended: Optional[bool] = None, force: bool = False) -> None: # env settings have precedence, unless force=True - if nothing is passed, the default value will be used
""" >>> # Setup >>> default_fmt = log_settings.fmt >>> # No env Setting, extended=None >>> set_extended_from_env() >>> assert log_settings.fmt == default_fmt >>> # No env Setting, extended = True >>> set_extended_from_env(True) >>> assert log_settings.fmt == log_settings.fmt_extend...
10 >>> # Teardown >>> log_settings.width = default_banner_width >>> del os.environ['LOG_UTIL_WIDTH'] """ if 'LOG_UTIL_WIDTH' in os.environ: if width is not None and force: log_settings.width = width else: s_error = 'invalid environment setting for "LOG_UTI...
194
194
647
47
146
bitranox/lib_log_utils
lib_log_utils/lib_log_utils_cli.py
Python
set_extended_from_env
set_extended_from_env
174
245
174
175
cfdef7003740585bd9595b90a8770a4f374576fb
bigcode/the-stack
train
9857f322023e86ea968382d1
train
function
def set_width_from_env(width: Optional[int] = None, force: bool = False) -> None: # env settings have precedence, unless force=True - if nothing is passed, the default value will be used """ >>> # Setup >>> default_banner_width = log_settings.width >>> # No env Setting, width=None >>> set_width...
def set_width_from_env(width: Optional[int] = None, force: bool = False) -> None: # env settings have precedence, unless force=True - if nothing is passed, the default value will be used
""" >>> # Setup >>> default_banner_width = log_settings.width >>> # No env Setting, width=None >>> set_width_from_env() >>> assert log_settings.width == default_banner_width >>> # No env Setting, width = default + 1 >>> set_width_from_env(default_banner_width + 1) >>> assert log_se...
(most recent call last): ... ValueError: the environment setting "LOG_UTIL_LEVEL" has to be from ... >>> # Teardown >>> del os.environ['LOG_UTIL_LEVEL'] >>> log_settings.new_logger_level = log_level_default """ if 'LOG_UTIL_LEVEL' in os.environ: try: log_settings....
169
169
564
45
124
bitranox/lib_log_utils
lib_log_utils/lib_log_utils_cli.py
Python
set_width_from_env
set_width_from_env
109
171
109
110
e8c16a5748e21853cb23858ab0937389ed5d74e3
bigcode/the-stack
train
c1dcf40b88b33655dae635b5
train
function
def set_wrap_from_env(wrap_text: Optional[bool] = None, force: bool = False) -> None: # env settings have precedence, unless force=True - if nothing is passed, the default value will be used """ >>> # Setup >>> default_wrap_text = log_settings.wrap >>> # No env Setting, wrap=None >>> set_wrap_f...
def set_wrap_from_env(wrap_text: Optional[bool] = None, force: bool = False) -> None: # env settings have precedence, unless force=True - if nothing is passed, the default value will be used
""" >>> # Setup >>> default_wrap_text = log_settings.wrap >>> # No env Setting, wrap=None >>> set_wrap_from_env() >>> assert log_settings.wrap == default_wrap_text >>> # No env Setting, wrap = not default_wrap_text >>> set_wrap_from_env(not default_wrap_text) >>> assert log_setting...
log_settings.fmt_plain if 'LOG_UTIL_FMT' in os.environ: if extended is not None and force: set_fmt(extended) else: if os.environ['LOG_UTIL_FMT'].lower().startswith('plain'): log_settings.fmt = log_settings.fmt_plain elif os.environ['LOG_UTIL_FMT'...
163
163
544
48
115
bitranox/lib_log_utils
lib_log_utils/lib_log_utils_cli.py
Python
set_wrap_from_env
set_wrap_from_env
248
305
248
249
848f323e0c34b4135668ccf28adc95be62cb7ee0
bigcode/the-stack
train
7eb270859bcb920f0e81a712
train
function
def do_log(message: str, level_str: str = 'info', extended: Optional[bool] = None, banner: bool = False, width: Optional[int] = None, wrap: Optional[bool] = None, silent: Optional[str] = None, quiet: Optional[bool] = None, force: bool = False, colortest: bool = False) -> None: """ >>> do_...
def do_log(message: str, level_str: str = 'info', extended: Optional[bool] = None, banner: bool = False, width: Optional[int] = None, wrap: Optional[bool] = None, silent: Optional[str] = None, quiet: Optional[bool] = None, force: bool = False, colortest: bool = False) -> None:
""" >>> do_log('test', banner=False) >>> do_log('test', banner=True) >>> do_log('test', silent='True') >>> do_log('test', silent='False') """ if silent is not None: # this is intentionally, we accept every value, only "true" is handled ! if silent.lower().startswith('true'):...
print_info() def do_log(message: str, level_str: str = 'info', extended: Optional[bool] = None, banner: bool = False, width: Optional[int] = None, wrap: Optional[bool] = None, silent: Optional[str] = None, quiet: Optional[bool] = None, force: bool = False, colortest: bool = False) -> None:
86
86
289
83
3
bitranox/lib_log_utils
lib_log_utils/lib_log_utils_cli.py
Python
do_log
do_log
41
72
41
44
5f517f8a98c4f0d2e696d9965c7de30f4df2276d
bigcode/the-stack
train
493a53ff9d33393bdf612c9d
train
function
def cli_info() -> None: """ >>> cli_info() Info for ... """ __init__conf__.print_info()
def cli_info() -> None:
""" >>> cli_info() Info for ... """ __init__conf__.print_info()
_levels # type: ignore # pragma: no cover from log_config import log_settings # type: ignore # pragma: no cover # CONSTANTS CLICK_CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) logger = logging.getLogger() def cli_info() -> None:
64
64
29
7
57
bitranox/lib_log_utils
lib_log_utils/lib_log_utils_cli.py
Python
cli_info
cli_info
32
38
32
32
fd3897c31a56b4e9eba542f59313d2a5ccb9688e
bigcode/the-stack
train
0cb96baceff760b06fc686d3
train
function
def set_quiet_from_env(quiet: Optional[bool] = None, force: bool = False) -> None: # env settings have precedence, unless force=True - if nothing is passed, the default value will be used # parameter -q is anything else then "True" (not case sensitive), or not set, it is considered as False. """ >>> # S...
def set_quiet_from_env(quiet: Optional[bool] = None, force: bool = False) -> None: # env settings have precedence, unless force=True - if nothing is passed, the default value will be used # parameter -q is anything else then "True" (not case sensitive), or not set, it is considered as False.
""" >>> # Setup >>> default_quiet = log_settings.quiet >>> # No env Setting, log_console=None >>> set_quiet_from_env() >>> assert log_settings.quiet == default_quiet >>> # No env Setting, log_console = default_quiet >>> set_quiet_from_env(not default_quiet) >>> assert log_settings....
_text is not None and force: log_settings.wrap = wrap_text else: if os.environ['LOG_UTIL_WRAP'].lower().startswith('false'): log_settings.wrap = False elif os.environ['LOG_UTIL_WRAP'].lower().startswith('true'): log_settings.wrap = True ...
183
183
613
75
107
bitranox/lib_log_utils
lib_log_utils/lib_log_utils_cli.py
Python
set_quiet_from_env
set_quiet_from_env
308
367
308
310
73fded88cc5094b5c785b13e5aaf9d17947b0b93
bigcode/the-stack
train
33993cfb217b15dc75c132e6
train
function
def set_logger_level_from_env() -> None: """ >>> # Setup >>> log_level_default = log_settings.new_logger_level >>> # no env Set >>> set_logger_level_from_env() >>> assert log_settings.new_logger_level == log_level_default >>> # env Set spam >>> os.environ['LOG_UTIL_LEVEL']='spam' >...
def set_logger_level_from_env() -> None:
""" >>> # Setup >>> log_level_default = log_settings.new_logger_level >>> # no env Set >>> set_logger_level_from_env() >>> assert log_settings.new_logger_level == log_level_default >>> # env Set spam >>> os.environ['LOG_UTIL_LEVEL']='spam' >>> set_logger_level_from_env() >>> as...
set_quiet_from_env(quiet, force) logger.level = log_settings.new_logger_level lib_log_utils.setup_handler(logger) if colortest: lib_log_utils.colortest() else: lib_log_utils.log_level(message=message, level=level, banner=banner) def set_logger_level_from_env() -> None:
74
74
248
10
64
bitranox/lib_log_utils
lib_log_utils/lib_log_utils_cli.py
Python
set_logger_level_from_env
set_logger_level_from_env
75
106
75
75
bb28754bbf17d56ea04c560879ef009703602cb3
bigcode/the-stack
train
2f860068bda6439af3a87a1f
train
function
@click.command(help=__init__conf__.title, context_settings=CLICK_CONTEXT_SETTINGS) @click.version_option(version=__init__conf__.version, prog_name=__init__conf__.shell_command, message='{} version %(version)s'.format(__init__conf__.shell_command)) @click.option('-e', '--exten...
@click.command(help=__init__conf__.title, context_settings=CLICK_CONTEXT_SETTINGS) @click.version_option(version=__init__conf__.version, prog_name=__init__conf__.shell_command, message='{} version %(version)s'.format(__init__conf__.shell_command)) @click.option('-e', '--exten...
""" log a message """ if traceback is not None: cli_exit_tools.config.traceback = traceback if program_info: cli_info() else: if plain: extended = False do_log(message=message, level_str=level, extended=extended, banner=banner, width=width, wrap...
@click.command(help=__init__conf__.title, context_settings=CLICK_CONTEXT_SETTINGS) @click.version_option(version=__init__conf__.version, prog_name=__init__conf__.shell_command, message='{} version %(version)s'.format(__init__conf__.shell_command)) @click.option('-e', '--exten...
487
174
580
487
0
bitranox/lib_log_utils
lib_log_utils/lib_log_utils_cli.py
Python
cli_main
cli_main
370
400
370
390
c8d336f6dc3d5bbc7b230da12a4b37219c015b28
bigcode/the-stack
train
f430a767bfc4314aec07c0a1
train
class
class Migration(migrations.Migration): dependencies = [ ('zerver', '0120_botuserconfigdata'), ] operations = [ migrations.AddField( model_name='realm', name='signup_notifications_stream', field=models.ForeignKey(blank=True, null=True, on_delete=django.db...
class Migration(migrations.Migration):
dependencies = [ ('zerver', '0120_botuserconfigdata'), ] operations = [ migrations.AddField( model_name='realm', name='signup_notifications_stream', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='...
None: realm_model = apps.get_model("zerver", "Realm") realms = realm_model.objects.exclude(notifications_stream__isnull=True) for realm in realms: realm.signup_notifications_stream = realm.notifications_stream realm.save(update_fields=["signup_notifications_stream"]) class Migration(migrati...
64
64
105
7
57
pranayshahxyz/zulip
zerver/migrations/0121_realm_signup_notifications_stream.py
Python
Migration
Migration
17
31
17
18
4ef5941a6662933d8c1784ebf79fc2fabdcb128e
bigcode/the-stack
train
b2ad93c465358b2fe77812f5
train
function
def set_initial_value_for_signup_notifications_stream( apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None: realm_model = apps.get_model("zerver", "Realm") realms = realm_model.objects.exclude(notifications_stream__isnull=True) for realm in realms: realm.signup_notifications_stream...
def set_initial_value_for_signup_notifications_stream( apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
realm_model = apps.get_model("zerver", "Realm") realms = realm_model.objects.exclude(notifications_stream__isnull=True) for realm in realms: realm.signup_notifications_stream = realm.notifications_stream realm.save(update_fields=["signup_notifications_stream"])
.models.deletion from django.db import migrations, models from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor from django.db.migrations.state import StateApps def set_initial_value_for_signup_notifications_stream( apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
64
64
80
25
38
pranayshahxyz/zulip
zerver/migrations/0121_realm_signup_notifications_stream.py
Python
set_initial_value_for_signup_notifications_stream
set_initial_value_for_signup_notifications_stream
9
15
9
10
771646c2826f8517e25b0b253fa07db0f892791b
bigcode/the-stack
train
f18a3cd6ef3c215dfc992bc5
train
class
class ZhonePortSchema(PortSchema): class Meta: model = Port fields = PortSchema.Meta.fields
class ZhonePortSchema(PortSchema):
class Meta: model = Port fields = PortSchema.Meta.fields
<https://github.com/Dinker1996> # - Philipp-Noah Groß <https://github.com/pngross> # # License: https://github.com/inexio/NESi/LICENSE.rst from nesi.devices.softbox.api.schemas.port_schemas import * class ZhonePortSchema(PortSchema):
64
64
26
9
55
inexio/NESi
nesi/devices/zhone/api/schemas/zhone_port_schemas.py
Python
ZhonePortSchema
ZhonePortSchema
11
14
11
11
6e9990296c3f05c3447c84529be6d0376e619218
bigcode/the-stack
train
e8acf5e16ff809cc47967e4c
train
function
def main(): """main body""" rads = np.zeros((1000, 10), dtype=float) # loop 1000 times to mean over later for rep in range(1000): my_girl = Drunk() for time in range(10): for _ in range(100): my_girl.topple() rads[rep, time] = my_girl.get_rad_sq()...
def main():
"""main body""" rads = np.zeros((1000, 10), dtype=float) # loop 1000 times to mean over later for rep in range(1000): my_girl = Drunk() for time in range(10): for _ in range(100): my_girl.topple() rads[rep, time] = my_girl.get_rad_sq() my_gir...
.75: # go up self.y_pos += 1 else: # go down self.y_pos -= 1 def get_rad_sq(self): """return radius squared""" return self.x_pos ** 2 + self.y_pos ** 2 def main():
64
64
191
3
60
alpha-leo/ComputationalPhysics-Fall2020
PSet4/p5/2d_rw.py
Python
main
main
39
59
39
39
3a8e821556d210b8a37348a8f2b3f253bb5d4bbe
bigcode/the-stack
train
37b165207b3e76fd8f14d12b
train
class
class Drunk: def __init__(self): self.x_pos = 0 self.y_pos = 0 def topple(self): """topple in the major directions""" rand = np.random.uniform() if rand < 0.25: # go left self.x_pos -= 1 elif rand < 0.5: # go right ...
class Drunk:
def __init__(self): self.x_pos = 0 self.y_pos = 0 def topple(self): """topple in the major directions""" rand = np.random.uniform() if rand < 0.25: # go left self.x_pos -= 1 elif rand < 0.5: # go right self.x_pos +...
#!/usr/bin/env python """ simulate a 2d random walker with equal probability to move in any of the 4 major directions. then prove the equation in question 5 """ import numpy as np from matplotlib import pyplot as plt class Drunk:
55
64
160
4
50
alpha-leo/ComputationalPhysics-Fall2020
PSet4/p5/2d_rw.py
Python
Drunk
Drunk
12
36
12
12
a8f0ff106b30fe74f6cbbb67e40816437fe35955
bigcode/the-stack
train
cf6b14af67b25d92610b0b10
train
class
class ReduceLROnPlateau(TorchScheduler): def __init__(self, mode='min', factor=0.1, patience=10, verbose=False, threshold=1e-4, threshold_mode='rel', cooldown=0, min_lr=0, eps=1e-8): super(ReduceLROnPlateau, self).__init__(scheduler_fn=partial(lrs.ReduceLROnPlateau, ...
class ReduceLROnPlateau(TorchScheduler):
def __init__(self, mode='min', factor=0.1, patience=10, verbose=False, threshold=1e-4, threshold_mode='rel', cooldown=0, min_lr=0, eps=1e-8): super(ReduceLROnPlateau, self).__init__(scheduler_fn=partial(lrs.ReduceLROnPlateau, ...
_min=0, last_epoch=-1): super(CosineAnnealingLR, self).__init__(scheduler_fn=partial(lrs.CosineAnnealingLR, T_max=T_max, eta_min=eta_min, last_epoch=last_epoch)) class Reduce...
64
64
140
11
53
vladstreltsin/blox
btorch/scheduler.py
Python
ReduceLROnPlateau
ReduceLROnPlateau
58
67
58
58
90a2032ed77b2c2bcbe7b1c1c69661d6a47675c0
bigcode/the-stack
train