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
c18b2a0076889aa017c53477
train
function
def test_merge_rule_lists_updated(): existing = { 'rule_lists': [{ 'id': '1', 'name': 'existing list', 'type': 'ip', 'description': 'existing list', 'entries': ['1.1.1.1'] }] } expected = { 'rule_lists': { '1': {...
def test_merge_rule_lists_updated():
existing = { 'rule_lists': [{ 'id': '1', 'name': 'existing list', 'type': 'ip', 'description': 'existing list', 'entries': ['1.1.1.1'] }] } expected = { 'rule_lists': { '1': { 'entries': { ...
(existing, expected) test_data = [{ 'name': 'new list', 'type': 'ip', 'description': 'new list', 'entries': ['2.2.2.2'] }] merge.merge_rule_lists(api, test_data) def test_merge_rule_lists_updated():
64
64
175
7
57
foospidy/sigsci_site_manager
tests/test_merge.py
Python
test_merge_rule_lists_updated
test_merge_rule_lists_updated
88
116
88
88
53de2126cacf522a1764600e2153c5129e614f19
bigcode/the-stack
train
4c92bc586316fe55dafa53c5
train
class
class Handler(BaseHTTPRequestHandler): def do_GET(s): s.send_response(200) s.end_headers() # Ensure we can write to given directory: try: with open(argv[1] + "/test", "w") as f: f.write(b"testing 123") except Exception as e: s.wfile.wri...
class Handler(BaseHTTPRequestHandler):
def do_GET(s): s.send_response(200) s.end_headers() # Ensure we can write to given directory: try: with open(argv[1] + "/test", "w") as f: f.write(b"testing 123") except Exception as e: s.wfile.write(str(e.__class__) + ": " + str(e)) ...
""" HTTP server that ensures it can write to given directory as a non-root user, then returns "hi". """ from sys import argv from os import setuid from pwd import getpwnam from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class Handler(BaseHTTPRequestHandler):
61
64
103
6
54
stackriot/flocker
flocker/acceptance/scripts/nonrootwritehttp.py
Python
Handler
Handler
12
24
12
12
9dbcf085db188e29d851849992638dad6f94a4f8
bigcode/the-stack
train
b8fb6b2f71bfb381937786c4
train
function
def main(): blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN() # attempt KNN training if blnKNNTrainingSuccessful == False: # if KNN training was not successful print ("\nerror: KNN traning was not successful\n") # show error message ...
def main():
blnKNNTrainingSuccessful = DetectChars.loadKNNDataAndTrainKNN() # attempt KNN training if blnKNNTrainingSuccessful == False: # if KNN training was not successful print ("\nerror: KNN traning was not successful\n") # show error message return ...
# Main.py import cv2 import numpy as np import os import DetectChars import DetectPlates import PossiblePlate # module level variables ########################################################################## SCALAR_BLACK = (0.0, 0.0, 0.0) SCALAR_WHITE = (255.0, 255.0, 255.0) SCALAR_YELLOW = (0.0, 255.0, 255.0) SCA...
143
195
651
3
140
DreamN/Smart-Tollbooth
RaspberryPi/Main(NoArg).py
Python
main
main
21
77
21
22
5201193f686b145d33b50a255b9108c58d6fb821
bigcode/the-stack
train
ce43943f145297fdaeb2b68f
train
function
def drawRedRectangleAroundPlate(imgOriginalScene, licPlate): p2fRectPoints = cv2.boxPoints(licPlate.rrLocationOfPlateInScene) # get 4 vertices of rotated rect cv2.line(imgOriginalScene, tuple(p2fRectPoints[0]), tuple(p2fRectPoints[1]), SCALAR_YELLOW, 2) # draw 4 red lines cv2.line(imgOr...
def drawRedRectangleAroundPlate(imgOriginalScene, licPlate):
p2fRectPoints = cv2.boxPoints(licPlate.rrLocationOfPlateInScene) # get 4 vertices of rotated rect cv2.line(imgOriginalScene, tuple(p2fRectPoints[0]), tuple(p2fRectPoints[1]), SCALAR_YELLOW, 2) # draw 4 red lines cv2.line(imgOriginalScene, tuple(p2fRectPoints[1]), tuple(p2fRectPoints[2]),...
licPlate.imgPlate) # write license plate image out to file # end if else cv2.waitKey(0) # hold windows open until user presses a key return # end main ################################################################################################### def drawRedRectangleAroundPlate(imgOri...
64
64
189
13
51
DreamN/Smart-Tollbooth
RaspberryPi/Main(NoArg).py
Python
drawRedRectangleAroundPlate
drawRedRectangleAroundPlate
81
88
81
82
19016f95c71fe959262170b87116ccc99fc071fa
bigcode/the-stack
train
7a8d329be78201129d0c842b
train
function
def writeLicensePlateCharsOnImage(imgOriginalScene, licPlate): ptCenterOfTextAreaX = 0 # this will be the center of the area the text will be written to ptCenterOfTextAreaY = 0 ptLowerLeftTextOriginX = 0 # this will be the bottom left of the area that th...
def writeLicensePlateCharsOnImage(imgOriginalScene, licPlate):
ptCenterOfTextAreaX = 0 # this will be the center of the area the text will be written to ptCenterOfTextAreaY = 0 ptLowerLeftTextOriginX = 0 # this will be the bottom left of the area that the text will be written to ptLowerLeftTextOriginY = 0 s...
Points = cv2.boxPoints(licPlate.rrLocationOfPlateInScene) # get 4 vertices of rotated rect cv2.line(imgOriginalScene, tuple(p2fRectPoints[0]), tuple(p2fRectPoints[1]), SCALAR_YELLOW, 2) # draw 4 red lines cv2.line(imgOriginalScene, tuple(p2fRectPoints[1]), tuple(p2fRectPoints[2]), SCALAR_YEL...
192
192
643
14
178
DreamN/Smart-Tollbooth
RaspberryPi/Main(NoArg).py
Python
writeLicensePlateCharsOnImage
writeLicensePlateCharsOnImage
92
128
92
92
63ed3fb5712a95f8a67974d6a3c7d0594b017d53
bigcode/the-stack
train
fab2bb8c20ac0b88a236a85a
train
function
def compress_kml(kml): "Returns compressed KMZ from the given KML string." kmz = cStringIO.StringIO() zf = zipfile.ZipFile(kmz, 'a', zipfile.ZIP_DEFLATED) zf.writestr('doc.kml', kml.encode(settings.DEFAULT_CHARSET)) zf.close() kmz.seek(0) return kmz.read()
def compress_kml(kml):
"Returns compressed KMZ from the given KML string." kmz = cStringIO.StringIO() zf = zipfile.ZipFile(kmz, 'a', zipfile.ZIP_DEFLATED) zf.writestr('doc.kml', kml.encode(settings.DEFAULT_CHARSET)) zf.close() kmz.seek(0) return kmz.read()
import cStringIO, zipfile from django.conf import settings from django.http import HttpResponse from django.template import loader def compress_kml(kml):
34
64
89
7
26
egenerat/gae-django
django/contrib/gis/shortcuts.py
Python
compress_kml
compress_kml
6
13
6
6
1034bb12db9e9bf668b4c5b15161bb4b18f217af
bigcode/the-stack
train
e9f08ae6767b98f078da2157
train
function
def render_to_kmz(*args, **kwargs): """ Compresses the KML content and returns as KMZ (using the correct MIME type). """ return HttpResponse(compress_kml(loader.render_to_string(*args, **kwargs)), mimetype='application/vnd.google-earth.kmz')
def render_to_kmz(*args, **kwargs):
""" Compresses the KML content and returns as KMZ (using the correct MIME type). """ return HttpResponse(compress_kml(loader.render_to_string(*args, **kwargs)), mimetype='application/vnd.google-earth.kmz')
render_to_kml(*args, **kwargs): "Renders the response as KML (using the correct MIME type)." return HttpResponse(loader.render_to_string(*args, **kwargs), mimetype='application/vnd.google-earth.kml+xml') def render_to_kmz(*args, **kwargs):
64
64
65
11
53
egenerat/gae-django
django/contrib/gis/shortcuts.py
Python
render_to_kmz
render_to_kmz
20
26
20
20
098d6ac77ca3bc513a837218dd42d1407f558e74
bigcode/the-stack
train
8f78479a866a4997dc4c9827
train
function
def render_to_text(*args, **kwargs): "Renders the response using the MIME type for plain text." return HttpResponse(loader.render_to_string(*args, **kwargs), mimetype='text/plain')
def render_to_text(*args, **kwargs):
"Renders the response using the MIME type for plain text." return HttpResponse(loader.render_to_string(*args, **kwargs), mimetype='text/plain')
""" Compresses the KML content and returns as KMZ (using the correct MIME type). """ return HttpResponse(compress_kml(loader.render_to_string(*args, **kwargs)), mimetype='application/vnd.google-earth.kmz') def render_to_text(*args, **kwargs):
63
64
45
10
53
egenerat/gae-django
django/contrib/gis/shortcuts.py
Python
render_to_text
render_to_text
29
32
29
29
c260561217425ceabac7b55477499958a7e4f167
bigcode/the-stack
train
7e966d88e43d7b69f04aa029
train
function
def render_to_kml(*args, **kwargs): "Renders the response as KML (using the correct MIME type)." return HttpResponse(loader.render_to_string(*args, **kwargs), mimetype='application/vnd.google-earth.kml+xml')
def render_to_kml(*args, **kwargs):
"Renders the response as KML (using the correct MIME type)." return HttpResponse(loader.render_to_string(*args, **kwargs), mimetype='application/vnd.google-earth.kml+xml')
.ZipFile(kmz, 'a', zipfile.ZIP_DEFLATED) zf.writestr('doc.kml', kml.encode(settings.DEFAULT_CHARSET)) zf.close() kmz.seek(0) return kmz.read() def render_to_kml(*args, **kwargs):
64
64
54
11
53
egenerat/gae-django
django/contrib/gis/shortcuts.py
Python
render_to_kml
render_to_kml
15
18
15
15
2f133e386d14c091ab1997d7f17ac212b6687b11
bigcode/the-stack
train
e2b9394aa1b152a0bd08dafd
train
class
class HotStarSeriesIE(HotStarBaseIE): IE_NAME = 'hotstar:series' _VALID_URL = r'(?P<url>https?://(?:www\.)?hotstar\.com(?:/in)?/tv/[^/]+/(?P<id>\d+))' _TESTS = [{ 'url': 'https://www.hotstar.com/in/tv/radhakrishn/1260000646', 'info_dict': { 'id': '1260000646', }, ...
class HotStarSeriesIE(HotStarBaseIE):
IE_NAME = 'hotstar:series' _VALID_URL = r'(?P<url>https?://(?:www\.)?hotstar\.com(?:/in)?/tv/[^/]+/(?P<id>\d+))' _TESTS = [{ 'url': 'https://www.hotstar.com/in/tv/radhakrishn/1260000646', 'info_dict': { 'id': '1260000646', }, 'playlist_mincount': 690, }, { ...
2480', 'only_matching': True, }] def _real_extract(self, url): playlist_id = self._match_id(url) collection = self._call_api('o/v1/tray/find', playlist_id, 'uqId')['body']['results'] entries = [ self.url_result( 'https://www.hotstar.com/%s' % video['...
142
142
474
11
131
git-anony-mouse/yt-dlp
yt_dlp/extractor/hotstar.py
Python
HotStarSeriesIE
HotStarSeriesIE
297
338
297
297
517e18df76fe3165b2d95ee5651ec8a26c9a60e0
bigcode/the-stack
train
e44cfcc71c284eb6236147df
train
class
class HotStarPlaylistIE(HotStarBaseIE): IE_NAME = 'hotstar:playlist' _VALID_URL = r'https?://(?:www\.)?hotstar\.com/tv/[^/]+/s-\w+/list/[^/]+/t-(?P<id>\w+)' _TESTS = [{ 'url': 'https://www.hotstar.com/tv/savdhaan-india/s-26/list/popular-clips/t-3_2_26', 'info_dict': { 'id': '3_2_...
class HotStarPlaylistIE(HotStarBaseIE):
IE_NAME = 'hotstar:playlist' _VALID_URL = r'https?://(?:www\.)?hotstar\.com/tv/[^/]+/s-\w+/list/[^/]+/t-(?P<id>\w+)' _TESTS = [{ 'url': 'https://www.hotstar.com/tv/savdhaan-india/s-26/list/popular-clips/t-3_2_26', 'info_dict': { 'id': '3_2_26', }, 'playlist_mincou...
_data.get('seasonName'), 'season_number': int_or_none(video_data.get('seasonNo')), 'season_id': video_data.get('seasonId'), 'episode': title, 'episode_number': int_or_none(video_data.get('episodeNo')), 'http_headers': { 'Referer': 'https://www....
89
89
297
11
78
git-anony-mouse/yt-dlp
yt_dlp/extractor/hotstar.py
Python
HotStarPlaylistIE
HotStarPlaylistIE
269
294
269
269
226a7113bb1b8c7aede68335c4e10f0b88e7aad1
bigcode/the-stack
train
2affb8e6687eded1e207186d
train
class
class HotStarBaseIE(InfoExtractor): _AKAMAI_ENCRYPTION_KEY = b'\x05\xfc\x1a\x01\xca\xc9\x4b\xc4\x12\xfc\x53\x12\x07\x75\xf9\xee' def _call_api_impl(self, path, video_id, query, st=None, cookies=None): st = int_or_none(st) or int(time.time()) exp = st + 6000 auth = 'st=%d~exp=%d~acl=/*' ...
class HotStarBaseIE(InfoExtractor):
_AKAMAI_ENCRYPTION_KEY = b'\x05\xfc\x1a\x01\xca\xc9\x4b\xc4\x12\xfc\x53\x12\x07\x75\xf9\xee' def _call_api_impl(self, path, video_id, query, st=None, cookies=None): st = int_or_none(st) or int(time.time()) exp = st + 6000 auth = 'st=%d~exp=%d~acl=/*' % (st, exp) auth += '~hmac='...
# coding: utf-8 from __future__ import unicode_literals import hashlib import hmac import re import time import uuid import json from .common import InfoExtractor from ..compat import ( compat_HTTPError, compat_str ) from ..utils import ( determine_ext, ExtractorError, int_or_none, str_or_none...
99
187
626
9
90
git-anony-mouse/yt-dlp
yt_dlp/extractor/hotstar.py
Python
HotStarBaseIE
HotStarBaseIE
26
77
26
26
8008de2b1b231fede5184529ec3b980ac5fb8318
bigcode/the-stack
train
fb5f87c9a765d08369de3b8b
train
class
class HotStarIE(HotStarBaseIE): IE_NAME = 'hotstar' _VALID_URL = r'''(?x) (?: hotstar\:| https?://(?:www\.)?hotstar\.com(?:/in)?/(?!in/) ) (?: (?P<type>movi...
class HotStarIE(HotStarBaseIE):
IE_NAME = 'hotstar' _VALID_URL = r'''(?x) (?: hotstar\:| https?://(?:www\.)?hotstar\.com(?:/in)?/(?!in/) ) (?: (?P<type>movies|sports|episode|(?P<tv>tv)) ...
['message'], expected=True) return response['data'] def _call_api(self, path, video_id, query_name='contentId'): return self._download_json('https://api.hotstar.com/' + path, video_id=video_id, query={ query_name: video_id, 'tas': 10000, }, headers={ 'x-c...
256
256
1,862
10
246
git-anony-mouse/yt-dlp
yt_dlp/extractor/hotstar.py
Python
HotStarIE
HotStarIE
80
266
80
80
ec235967f3db7d99a7fa297a318c7b4c122a0967
bigcode/the-stack
train
c4f81af8086e5c264fe2fb89
train
function
@pytest.mark.parametrize("x_dtype", [cp.float32, cp.float64]) @pytest.mark.parametrize("y_dtype", [cp.int32, cp.int64]) def test_basic_fit_predict_dense_numpy(x_dtype, y_dtype, nlp_20news): """ Cupy Test """ X, y = nlp_20news X = sparse_scipy_to_cp(X, x_dtype).astype(x_dtype) y = y.astype(y_dty...
@pytest.mark.parametrize("x_dtype", [cp.float32, cp.float64]) @pytest.mark.parametrize("y_dtype", [cp.int32, cp.int64]) def test_basic_fit_predict_dense_numpy(x_dtype, y_dtype, nlp_20news):
""" Cupy Test """ X, y = nlp_20news X = sparse_scipy_to_cp(X, x_dtype).astype(x_dtype) y = y.astype(y_dtype) X = X.tocsr()[0:500].todense() y = y[:500] model = MultinomialNB() model.fit(np.ascontiguousarray(cp.asnumpy(X)), y) y_hat = model.predict(X) y_hat = cp.asnum...
accuracy_score(y, y_hat) >= 0.924 @pytest.mark.parametrize("x_dtype", [cp.float32, cp.float64]) @pytest.mark.parametrize("y_dtype", [cp.int32, cp.int64]) def test_basic_fit_predict_dense_numpy(x_dtype, y_dtype, nlp_20news):
64
64
182
51
12
garanews/cuml
python/cuml/test/test_naive_bayes.py
Python
test_basic_fit_predict_dense_numpy
test_basic_fit_predict_dense_numpy
63
85
63
65
a5a6c1fa70a5c22ac6889f1be530954c4148321c
bigcode/the-stack
train
c2f3caeecbebe755ed33ee92
train
function
@pytest.mark.parametrize("x_dtype", [cp.float32, cp.float64]) @pytest.mark.parametrize("y_dtype", [cp.int32, cp.int64]) def test_predict_proba(x_dtype, y_dtype, nlp_20news): X, y = nlp_20news cu_X = sparse_scipy_to_cp(X, x_dtype).astype(x_dtype) cu_y = y.astype(y_dtype) cu_X = cu_X.tocsr() y = y...
@pytest.mark.parametrize("x_dtype", [cp.float32, cp.float64]) @pytest.mark.parametrize("y_dtype", [cp.int32, cp.int64]) def test_predict_proba(x_dtype, y_dtype, nlp_20news):
X, y = nlp_20news cu_X = sparse_scipy_to_cp(X, x_dtype).astype(x_dtype) cu_y = y.astype(y_dtype) cu_X = cu_X.tocsr() y = y.get() cuml_model = MultinomialNB() sk_model = skNB() cuml_model.fit(cu_X, cu_y) sk_model.fit(X, y) cuml_proba = cuml_model.predict_proba(cu_X).get() ...
assert accuracy_score(y, y_hat) >= 0.924 @pytest.mark.parametrize("x_dtype", [cp.float32, cp.float64]) @pytest.mark.parametrize("y_dtype", [cp.int32, cp.int64]) def test_predict_proba(x_dtype, y_dtype, nlp_20news):
64
64
199
49
14
garanews/cuml
python/cuml/test/test_naive_bayes.py
Python
test_predict_proba
test_predict_proba
134
157
134
137
c2375a09ed2decaa1e28daabe7f9e1468a708ed5
bigcode/the-stack
train
88c94088808e35429cc261e7
train
function
@pytest.mark.parametrize("x_dtype", [cp.float32, cp.float64]) @pytest.mark.parametrize("y_dtype", [cp.int32, cp.int64]) def test_predict_log_proba(x_dtype, y_dtype, nlp_20news): X, y = nlp_20news cu_X = sparse_scipy_to_cp(X, x_dtype).astype(x_dtype) cu_y = y.astype(y_dtype) cu_X = cu_X.tocsr() y...
@pytest.mark.parametrize("x_dtype", [cp.float32, cp.float64]) @pytest.mark.parametrize("y_dtype", [cp.int32, cp.int64]) def test_predict_log_proba(x_dtype, y_dtype, nlp_20news):
X, y = nlp_20news cu_X = sparse_scipy_to_cp(X, x_dtype).astype(x_dtype) cu_y = y.astype(y_dtype) cu_X = cu_X.tocsr() y = y.get() cuml_model = MultinomialNB() sk_model = skNB() cuml_model.fit(cu_X, cu_y) sk_model.fit(X, y) cuml_proba = cuml_model.predict_log_proba(cu_X).get...
=1e-6, rtol=1e-2) @pytest.mark.parametrize("x_dtype", [cp.float32, cp.float64]) @pytest.mark.parametrize("y_dtype", [cp.int32, cp.int64]) def test_predict_log_proba(x_dtype, y_dtype, nlp_20news):
64
64
202
50
14
garanews/cuml
python/cuml/test/test_naive_bayes.py
Python
test_predict_log_proba
test_predict_log_proba
160
183
160
163
0f6ecee267f8e13b03f09b5cb5efbcdae425a9cc
bigcode/the-stack
train
caf5d7cc6fc74ff6e8df0610
train
function
@pytest.mark.parametrize("x_dtype", [cp.float32, cp.float64]) @pytest.mark.parametrize("y_dtype", [cp.int32, cp.int64]) def test_score(x_dtype, y_dtype, nlp_20news): X, y = nlp_20news cu_X = sparse_scipy_to_cp(X, x_dtype).astype(x_dtype) cu_y = y.astype(y_dtype) cu_X = cu_X.tocsr() y = y.get() ...
@pytest.mark.parametrize("x_dtype", [cp.float32, cp.float64]) @pytest.mark.parametrize("y_dtype", [cp.int32, cp.int64]) def test_score(x_dtype, y_dtype, nlp_20news):
X, y = nlp_20news cu_X = sparse_scipy_to_cp(X, x_dtype).astype(x_dtype) cu_y = y.astype(y_dtype) cu_X = cu_X.tocsr() y = y.get() cuml_model = MultinomialNB() sk_model = skNB() cuml_model.fit(cu_X, cu_y) sk_model.fit(X, y) cuml_score = cuml_model.score(cu_X, cu_y) sk_sc...
ba, atol=1e-2, rtol=1e-2) @pytest.mark.parametrize("x_dtype", [cp.float32, cp.float64]) @pytest.mark.parametrize("y_dtype", [cp.int32, cp.int64]) def test_score(x_dtype, y_dtype, nlp_20news):
64
64
194
47
17
garanews/cuml
python/cuml/test/test_naive_bayes.py
Python
test_score
test_score
186
211
186
189
f4d82988a868e4ad2b59a88b6332164519691b02
bigcode/the-stack
train
8a9e9934e86e2b37b8f6b76b
train
function
@pytest.mark.parametrize("x_dtype", [cp.float32, cp.float64]) @pytest.mark.parametrize("y_dtype", [cp.int32, cp.int64]) def test_partial_fit(x_dtype, y_dtype, nlp_20news): chunk_size = 500 X, y = nlp_20news X = sparse_scipy_to_cp(X, x_dtype).astype(x_dtype) y = y.astype(y_dtype) X = X.tocsr() ...
@pytest.mark.parametrize("x_dtype", [cp.float32, cp.float64]) @pytest.mark.parametrize("y_dtype", [cp.int32, cp.int64]) def test_partial_fit(x_dtype, y_dtype, nlp_20news):
chunk_size = 500 X, y = nlp_20news X = sparse_scipy_to_cp(X, x_dtype).astype(x_dtype) y = y.astype(y_dtype) X = X.tocsr() model = MultinomialNB() classes = np.unique(y) total_fit = 0 for i in range(math.ceil(X.shape[0] / chunk_size)): upper = i*chunk_size+chunk_size ...
y_hat = model.predict(X) y_hat = cp.asnumpy(y_hat) y = cp.asnumpy(y) accuracy_score(y, y_hat) >= 0.911 @pytest.mark.parametrize("x_dtype", [cp.float32, cp.float64]) @pytest.mark.parametrize("y_dtype", [cp.int32, cp.int64]) def test_partial_fit(x_dtype, y_dtype, nlp_20news):
88
88
294
48
39
garanews/cuml
python/cuml/test/test_naive_bayes.py
Python
test_partial_fit
test_partial_fit
88
131
88
90
88ded161455168da5b8da58113d7c511218e7c58
bigcode/the-stack
train
efc9d8b16459c72cb05ff235
train
function
@pytest.mark.parametrize("x_dtype", [cp.float32, cp.float64]) @pytest.mark.parametrize("y_dtype", [cp.int32, cp.int64]) def test_basic_fit_predict_sparse(x_dtype, y_dtype, nlp_20news): """ Cupy Test """ X, y = nlp_20news X = sparse_scipy_to_cp(X, x_dtype).astype(x_dtype) y = y.astype(y_dtype) ...
@pytest.mark.parametrize("x_dtype", [cp.float32, cp.float64]) @pytest.mark.parametrize("y_dtype", [cp.int32, cp.int64]) def test_basic_fit_predict_sparse(x_dtype, y_dtype, nlp_20news):
""" Cupy Test """ X, y = nlp_20news X = sparse_scipy_to_cp(X, x_dtype).astype(x_dtype) y = y.astype(y_dtype) # Priming it seems to lower the end-to-end runtime model = MultinomialNB() model.fit(X, y) cp.cuda.Stream.null.synchronize() with cp.prof.time_range(message="star...
omialNB as skNB import math import numpy as np @pytest.mark.parametrize("x_dtype", [cp.float32, cp.float64]) @pytest.mark.parametrize("y_dtype", [cp.int32, cp.int64]) def test_basic_fit_predict_sparse(x_dtype, y_dtype, nlp_20news):
64
64
204
50
13
garanews/cuml
python/cuml/test/test_naive_bayes.py
Python
test_basic_fit_predict_sparse
test_basic_fit_predict_sparse
33
60
33
35
84c34471ea168952d5226069bcd36343539aaa01
bigcode/the-stack
train
8611122220b4f1be5986863b
train
class
class Solution: def numIslands(self, grid: List[List[str]]) -> int: LAND = '1' WATER = '0' DIRECTIONS = [(1, 0), (-1, 0), (0, 1), (0, -1)] numberOfIslands = 0 numberOfRows = len(grid) if numberOfRows == 0: return numberOfIslands numberOfColumns = l...
class Solution:
def numIslands(self, grid: List[List[str]]) -> int: LAND = '1' WATER = '0' DIRECTIONS = [(1, 0), (-1, 0), (0, 1), (0, -1)] numberOfIslands = 0 numberOfRows = len(grid) if numberOfRows == 0: return numberOfIslands numberOfColumns = len(grid[0]) ...
class Solution:
3
78
263
3
0
UtkarshPathrabe/Competitive-Coding
LeetCode/Stacks and Queues/Number of Islands.py
Python
Solution
Solution
1
27
1
1
7af07b07c32c3fbb62f07b54f0c7cd7ce51adda3
bigcode/the-stack
train
1d847cafea5cd395fd2901e9
train
function
def __renumber(dictionary) : """Renumber the values of the dictionary from 0 to n """ count = 0 ret = dictionary.copy() new_values = dict([]) for key in dictionary.keys() : value = dictionary[key] new_value = new_values.get(value, -1) if new_value == -1 : ...
def __renumber(dictionary) :
"""Renumber the values of the dictionary from 0 to n """ count = 0 ret = dictionary.copy() new_values = dict([]) for key in dictionary.keys() : value = dictionary[key] new_value = new_values.get(value, -1) if new_value == -1 : new_values[value] = count ...
] com2 = partition[node2] w_prec = ret.get_edge_data(com1, com2, {"weight":0}).get("weight", 1) ret.add_edge(com1, com2, weight = w_prec + weight) return ret def __renumber(dictionary) :
64
64
111
7
56
romainrossi/weblabdeusto
server/src/weblab/admin/web/community.py
Python
__renumber
__renumber
312
328
312
312
422107755941a0dcb6c914952c765d114a6e436a
bigcode/the-stack
train
0f6bc2e8e5d4d7cb0d977f47
train
function
def best_partition(graph, partition = None) : """Compute the partition of the graph nodes which maximises the modularity (or try..) using the Louvain heuristices This is the partition of highest modularity, i.e. the highest partition of the dendogram generated by the Louvain algorithm. Paramet...
def best_partition(graph, partition = None) :
"""Compute the partition of the graph nodes which maximises the modularity (or try..) using the Louvain heuristices This is the partition of highest modularity, i.e. the highest partition of the dendogram generated by the Louvain algorithm. Parameters ---------- graph : networkx.Graph ...
.get(com, 0.) + graph.degree(node, weight = 'weight') for neighbor, datas in graph[node].iteritems() : weight = datas.get("weight", 1) if partition[neighbor] == com : if neighbor == node : inc[com] = inc.get(com, 0.) + float(weight) els...
158
158
529
10
147
romainrossi/weblabdeusto
server/src/weblab/admin/web/community.py
Python
best_partition
best_partition
125
187
125
125
966e015ed7eb1ce4589b831478b21c38c8ce6404
bigcode/the-stack
train
504d70a4e269c1da53504fe4
train
function
def __neighcom(node, graph, status) : """ Compute the communities in the neighborood of node in the graph given with the decomposition node2com """ weights = {} for neighbor, datas in graph[node].iteritems() : if neighbor != node : weight = datas.get("weight", 1) ...
def __neighcom(node, graph, status) :
""" Compute the communities in the neighborood of node in the graph given with the decomposition node2com """ weights = {} for neighbor, datas in graph[node].iteritems() : if neighbor != node : weight = datas.get("weight", 1) neighborcom = status.node2com[neighbor...
part[neighbor] == com : if neighbor == node : inc += float(weight) else : inc += float(weight) / 2. self.internals[com] = self.internals.get(com, 0) + inc def __neighcom(node, graph, status) :
64
64
107
12
51
romainrossi/weblabdeusto
server/src/weblab/admin/web/community.py
Python
__neighcom
__neighcom
471
483
471
471
0894fed0a0fb8507979009ce00f05eb4e0384987
bigcode/the-stack
train
7c6fc1d79948e179cff3fe6b
train
function
def __main() : """Main function to mimic C++ version behavior""" try : filename = sys.argv[1] graphfile = __load_binary(filename) partition = best_partition(graphfile) print(str(modularity(partition, graphfile)), file = sys.stderr) for elem, part in partition.iteritems() ...
def __main() :
"""Main function to mimic C++ version behavior""" try : filename = sys.argv[1] graphfile = __load_binary(filename) partition = best_partition(graphfile) print(str(modularity(partition, graphfile)), file = sys.stderr) for elem, part in partition.iteritems() : p...
in_degree = status.internals.get(community, 0.) degree = status.degrees.get(community, 0.) if links > 0 : result = result + in_degree / links - ((degree / (2.*links))**2) return result def __main() :
64
64
143
5
58
romainrossi/weblabdeusto
server/src/weblab/admin/web/community.py
Python
__main
__main
518
532
518
518
ec9d0fcc775ecf106ad81c480872f798f41ef013
bigcode/the-stack
train
9a1bdba9c735c2078fd99c6f
train
function
def induced_graph(partition, graph) : """Produce the graph where nodes are the communities there is a link of weight w between communities if the sum of the weights of the links between their elements is w Parameters ---------- partition : dict a dictionary where keys are graph nodes and v...
def induced_graph(partition, graph) :
"""Produce the graph where nodes are the communities there is a link of weight w between communities if the sum of the weights of the links between their elements is w Parameters ---------- partition : dict a dictionary where keys are graph nodes and values the part the node belongs to ...
current_graph) status.init(current_graph) while True : __one_level(current_graph, status) new_mod = __modularity(status) if new_mod - mod < __MIN : break partition = __renumber(status.node2com) status_list.append(partition) mod = new_mod ...
102
102
340
9
92
romainrossi/weblabdeusto
server/src/weblab/admin/web/community.py
Python
induced_graph
induced_graph
269
309
269
269
6aaac3ea5557135c83599caac852de600b8e2a6d
bigcode/the-stack
train
9d16f5b867a1fc43f9f69df0
train
function
def __insert(node, com, weight, status) : """ Insert node into community and modify status""" status.node2com[node] = com status.degrees[com] = ( status.degrees.get(com, 0.) + status.gdegrees.get(node, 0.) ) status.internals[com] = float( status.internals.get(com, 0.) + ...
def __insert(node, com, weight, status) :
""" Insert node into community and modify status""" status.node2com[node] = com status.degrees[com] = ( status.degrees.get(com, 0.) + status.gdegrees.get(node, 0.) ) status.internals[com] = float( status.internals.get(com, 0.) + weight + status.loo...
degrees.get(node, 0.) ) status.internals[com] = float( status.internals.get(com, 0.) - weight - status.loops.get(node, 0.) ) status.node2com[node] = -1 def __insert(node, com, weight, status) :
64
64
95
12
51
romainrossi/weblabdeusto
server/src/weblab/admin/web/community.py
Python
__insert
__insert
495
501
495
495
a0e7c442bf8856029d5d078e81d203c3c6b4d017
bigcode/the-stack
train
fc2967f3ddb0a801af03a3c8
train
function
def __modularity(status) : """ Compute the modularity of the partition of the graph faslty using status precomputed """ links = float(status.total_weight) result = 0. for community in set(status.node2com.values()) : in_degree = status.internals.get(community, 0.) degree = status....
def __modularity(status) :
""" Compute the modularity of the partition of the graph faslty using status precomputed """ links = float(status.total_weight) result = 0. for community in set(status.node2com.values()) : in_degree = status.internals.get(community, 0.) degree = status.degrees.get(community, 0.) ...
] = ( status.degrees.get(com, 0.) + status.gdegrees.get(node, 0.) ) status.internals[com] = float( status.internals.get(com, 0.) + weight + status.loops.get(node, 0.) ) def __modularity(status) :
64
64
115
7
57
romainrossi/weblabdeusto
server/src/weblab/admin/web/community.py
Python
__modularity
__modularity
504
515
504
504
3c9e54533160227b441687c6644d7222d622c995
bigcode/the-stack
train
ebe19a43f1363bd5796d66d0
train
class
class Status : """ To handle several data in one struct. Could be replaced by named tuple, but don't want to depend on python 2.6 """ node2com = {} total_weight = 0 internals = {} degrees = {} gdegrees = {} def __init__(self) : self.node2com = dict([]) self....
class Status :
""" To handle several data in one struct. Could be replaced by named tuple, but don't want to depend on python 2.6 """ node2com = {} total_weight = 0 internals = {} degrees = {} gdegrees = {} def __init__(self) : self.node2com = dict([]) self.total_weight = ...
.gdegrees.get(node, 0.) / (status.total_weight*2.) neigh_communities = __neighcom(node, graph, status) __remove(node, com_node, neigh_communities.get(com_node, 0.), status) best_com = com_node best_increase = 0 for com, dnc in neigh_communi...
189
189
633
3
185
romainrossi/weblabdeusto
server/src/weblab/admin/web/community.py
Python
Status
Status
395
467
395
395
cd4524306f9bc05c3c082b433341a8de75da8ecf
bigcode/the-stack
train
505605f22a1e00d67d89882f
train
function
def modularity(partition, graph) : """Compute the modularity of a partition of a graph Parameters ---------- partition : dict the partition of the nodes, i.e a dictionary where keys are their nodes and values the communities graph : networkx.Graph the networkx graph which is decompose...
def modularity(partition, graph) :
"""Compute the modularity of a partition of a graph Parameters ---------- partition : dict the partition of the nodes, i.e a dictionary where keys are their nodes and values the communities graph : networkx.Graph the networkx graph which is decomposed Returns ------- modu...
ity Examples -------- >>> G=nx.erdos_renyi_graph(100, 0.01) >>> dendo = generate_dendogram(G) >>> for level in range(len(dendo) - 1) : >>> print "partition at level", level, "is", partition_at_level(dendo, level) """ partition = dendogram[0].copy() for index in range(1, level + ...
136
136
455
9
126
romainrossi/weblabdeusto
server/src/weblab/admin/web/community.py
Python
modularity
modularity
65
122
65
65
c9cb3c06a3ff621f6a26b37ad3f7f8a86b1982ba
bigcode/the-stack
train
26c82ee95b952edcee4b3404
train
function
def partition_at_level(dendogram, level) : """Return the partition of the nodes at the given level A dendogram is a tree and each level is a partition of the graph nodes. Level 0 is the first partition, which contains the smallest communities, and the best is len(dendogram) - 1. The higher the level is...
def partition_at_level(dendogram, level) :
"""Return the partition of the nodes at the given level A dendogram is a tree and each level is a partition of the graph nodes. Level 0 is the first partition, which contains the smallest communities, and the best is len(dendogram) - 1. The higher the level is, the bigger are the communities Param...
_graph"] __author__ = """Thomas Aynaud (thomas.aynaud@lip6.fr)""" # Copyright (C) 2009 by # Thomas Aynaud <thomas.aynaud@lip6.fr> # All rights reserved. # BSD license. __PASS_MAX = -1 __MIN = 0.0000001 import networkx as nx import sys import types import array def partition_at_level(dendogram, level) :
105
105
352
11
93
romainrossi/weblabdeusto
server/src/weblab/admin/web/community.py
Python
partition_at_level
partition_at_level
23
62
23
23
87fa9eda34f6a2c718e495cad2025898322d267e
bigcode/the-stack
train
5f109458d83b8b9d86020de6
train
function
def __one_level(graph, status) : """Compute one level of communities """ modif = True nb_pass_done = 0 cur_mod = __modularity(status) new_mod = cur_mod while modif and nb_pass_done != __PASS_MAX : cur_mod = new_mod modif = False nb_pass_done += 1 ...
def __one_level(graph, status) :
"""Compute one level of communities """ modif = True nb_pass_done = 0 cur_mod = __modularity(status) new_mod = cur_mod while modif and nb_pass_done != __PASS_MAX : cur_mod = new_mod modif = False nb_pass_done += 1 for node in graph.nodes() : ...
.tolist() graph = nx.Graph() graph.add_nodes_from(range(num_nodes)) prec_deg = 0 for index in range(num_nodes) : last_deg = cum_deg[index] neighbors = links[prec_deg:last_deg] graph.add_edges_from([(index, int(neigh)) for neigh in neighbors]) prec_deg = last_deg ...
88
88
295
9
78
romainrossi/weblabdeusto
server/src/weblab/admin/web/community.py
Python
__one_level
__one_level
360
392
360
360
3219c3b322e834d8e784dbf949485cdb94959762
bigcode/the-stack
train
0777a1dbc333d44489d0edd1
train
function
def generate_dendogram(graph, part_init = None) : """Find communities in the graph and return the associated dendogram A dendogram is a tree and each level is a partition of the graph nodes. Level 0 is the first partition, which contains the smallest communities, and the best is len(dendogram) - 1. The higher...
def generate_dendogram(graph, part_init = None) :
"""Find communities in the graph and return the associated dendogram A dendogram is a tree and each level is a partition of the graph nodes. Level 0 is the first partition, which contains the smallest communities, and the best is len(dendogram) - 1. The higher the level is, the bigger are the communities ...
partition >>> partition = community.best_partition(G) >>> #drawing >>> size = float(len(set(partition.values()))) >>> pos = nx.spring_layout(G) >>> count = 0. >>> for com in set(partition.values()) : >>> count = count + 1. >>> list_nodes = [nodes for nodes in partition.keys() ...
184
184
616
13
171
romainrossi/weblabdeusto
server/src/weblab/admin/web/community.py
Python
generate_dendogram
generate_dendogram
190
266
190
190
8283647de297f20672958e6572e1f2c6b1dba626
bigcode/the-stack
train
5f9879837e53c041523f750d
train
function
def __load_binary(data) : """Load binary graph as used by the cpp implementation of this algorithm """ if type(data) == types.StringType : data = open(data, "rb") reader = array.array("I") reader.fromfile(data, 1) num_nodes = reader.pop() reader = array.array("I") reader...
def __load_binary(data) :
"""Load binary graph as used by the cpp implementation of this algorithm """ if type(data) == types.StringType : data = open(data, "rb") reader = array.array("I") reader.fromfile(data, 1) num_nodes = reader.pop() reader = array.array("I") reader.fromfile(data, num_nodes)...
dictionary[key] new_value = new_values.get(value, -1) if new_value == -1 : new_values[value] = count new_value = count count = count + 1 ret[key] = new_value return ret def __load_binary(data) :
64
64
199
7
56
romainrossi/weblabdeusto
server/src/weblab/admin/web/community.py
Python
__load_binary
__load_binary
331
357
331
331
c9f6299d0c771bb804e28b69ac518d0f2de54380
bigcode/the-stack
train
9fefaa082502a5325d139361
train
function
def __remove(node, com, weight, status) : """ Remove node from community com and modify status""" status.degrees[com] = ( status.degrees.get(com, 0.) - status.gdegrees.get(node, 0.) ) status.internals[com] = float( status.internals.get(com, 0.) - weight - ...
def __remove(node, com, weight, status) :
""" Remove node from community com and modify status""" status.degrees[com] = ( status.degrees.get(com, 0.) - status.gdegrees.get(node, 0.) ) status.internals[com] = float( status.internals.get(com, 0.) - weight - status.loops.get(node, 0.) ) status.no...
: if neighbor != node : weight = datas.get("weight", 1) neighborcom = status.node2com[neighbor] weights[neighborcom] = weights.get(neighborcom, 0) + weight return weights def __remove(node, com, weight, status) :
64
64
97
12
51
romainrossi/weblabdeusto
server/src/weblab/admin/web/community.py
Python
__remove
__remove
486
492
486
486
52dd9916c4705db1a0edf1bd7c87a2de27d650c6
bigcode/the-stack
train
1dc4a4b5a7d06d9adfedb934
train
function
def argManager(): parser = argparse.ArgumentParser() parser.add_argument("-artist", "--artist", action="store_true", help="Download for an Artist") parser.add_argument("-song", "--song", action="store_true", help="Download Songs") parser.add_argument("-album", "--album", action="store_true", help="Downl...
def argManager():
parser = argparse.ArgumentParser() parser.add_argument("-artist", "--artist", action="store_true", help="Download for an Artist") parser.add_argument("-song", "--song", action="store_true", help="Download Songs") parser.add_argument("-album", "--album", action="store_true", help="Download Albums") p...
_ip = '' if ('http_proxy' in os.environ): proxy_ip = os.environ['http_proxy'] proxies = { 'http': proxy_ip, 'https': proxy_ip, } headers = { 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:49.0) Gecko/20100101 Firefox/49.0', 'cache-control': 'private, ma...
115
115
386
4
110
sudheer09441/Saavn-Downloader
scripts/helper.py
Python
argManager
argManager
31
53
31
31
ba4bc7451addd1821f2f5e71f54bf6e1c0f360dc
bigcode/the-stack
train
43fbc67c041745b77b21787d
train
function
def setProxy(): proxy_ip = '' if ('http_proxy' in os.environ): proxy_ip = os.environ['http_proxy'] proxies = { 'http': proxy_ip, 'https': proxy_ip, } headers = { 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:49.0) Gecko/20100101 Firefox/49.0', 'cac...
def setProxy():
proxy_ip = '' if ('http_proxy' in os.environ): proxy_ip = os.environ['http_proxy'] proxies = { 'http': proxy_ip, 'https': proxy_ip, } headers = { 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:49.0) Gecko/20100101 Firefox/49.0', 'cache-control': 'pr...
album' in url_parts: return 'album' elif 'artist' in url_parts: return 'artist' elif 'playlist' in url_parts or 'featured' in url_parts: return 'playlist' elif 'song' in url_parts: return 'song' def setProxy():
64
64
117
4
60
sudheer09441/Saavn-Downloader
scripts/helper.py
Python
setProxy
setProxy
17
29
17
17
208ff73a50a9fcb1d0d335137b08b2ea252826ca
bigcode/the-stack
train
c4fa74bc833460272a6a0b8b
train
function
def scan_url(url): url_parts = url.split('/') if 'album' in url_parts: return 'album' elif 'artist' in url_parts: return 'artist' elif 'playlist' in url_parts or 'featured' in url_parts: return 'playlist' elif 'song' in url_parts: return 'song'
def scan_url(url):
url_parts = url.split('/') if 'album' in url_parts: return 'album' elif 'artist' in url_parts: return 'artist' elif 'playlist' in url_parts or 'featured' in url_parts: return 'playlist' elif 'song' in url_parts: return 'song'
import os import argparse import json import re def scan_url(url):
17
64
75
5
11
sudheer09441/Saavn-Downloader
scripts/helper.py
Python
scan_url
scan_url
6
15
6
6
29c90544001ac17dacf5cbab6595913f9c793e1c
bigcode/the-stack
train
1e228c3590c61930ea5aa799
train
function
def update_a_path_manipulation(main, file): """ Replace PATH manipulating with a PATH setting which actually respects our Python version wish """ if main.replace_in_file(file, "set PATH=%PATH%;%PYTHON_HOME%/Scripts/", "set PATH=%PYTHON_HOME%;%PYTHON_HOME%/Scripts/;%PATH%"): main.output_resul...
def update_a_path_manipulation(main, file):
""" Replace PATH manipulating with a PATH setting which actually respects our Python version wish """ if main.replace_in_file(file, "set PATH=%PATH%;%PYTHON_HOME%/Scripts/", "set PATH=%PYTHON_HOME%;%PYTHON_HOME%/Scripts/;%PATH%"): main.output_result_update(title="AppVeyor: Update PATH manipu...
def update_a_path_manipulation(main, file):
11
64
104
11
0
madebr/bincrafters-repo-bincrafters-conventions
bincrafters_conventions/actions/update_a_path_manipulation.py
Python
update_a_path_manipulation
update_a_path_manipulation
1
8
1
1
e7514e5efaacc6b820377477bc3aabe64a99cd44
bigcode/the-stack
train
e5b8b1a504bb88af9074d83b
train
function
def task_function(path,task,image_path): X = np.load(path+'X_'+task+'.npy') y = np.load(path+'y_'+task+'.npy') df = create_dataframe(X,y) col_nm = df.columns data_stats(df) histogram_plot(df,col_nm,image_path,'Histogram_'+task+'.jpg') count_plot(df,image_path,'Class_Balance_'+task+'.jpg') ...
def task_function(path,task,image_path):
X = np.load(path+'X_'+task+'.npy') y = np.load(path+'y_'+task+'.npy') df = create_dataframe(X,y) col_nm = df.columns data_stats(df) histogram_plot(df,col_nm,image_path,'Histogram_'+task+'.jpg') count_plot(df,image_path,'Class_Balance_'+task+'.jpg') box_plot(df,col_nm,image_path,'Boxplot_...
_length', 'sepal_width','petal_length','petal_width']) df_target = pd.DataFrame(y, columns=['species']) # Final DataFrame df = pd.concat([df_data,df_target],axis=1) return df def task_function(path,task,image_path):
64
64
117
9
54
NikhilNandoskar/Iris-on-GCP
Iris on GCP/EDA_After_Train_Test.py
Python
task_function
task_function
35
44
35
35
8a858716a664e84d3d378a7590ec3c884658d916
bigcode/the-stack
train
15b7272ae530cc7546a44d32
train
function
def save_numpy(path,X_train, X_test, y_train, y_test): np.save(path+'X_Train.npy',X_train) np.save(path+'X_Test.npy',X_test) np.save(path+'y_Train.npy',y_train) np.save(path+'y_Test.npy',y_test)
def save_numpy(path,X_train, X_test, y_train, y_test):
np.save(path+'X_Train.npy',X_train) np.save(path+'X_Test.npy',X_test) np.save(path+'y_Train.npy',y_train) np.save(path+'y_Test.npy',y_test)
,-1] # Dependent Feature # convert from dataframes to numpy matrices X = np.array(X.values) y = np.array(y.values) y = y.flatten() return X, y def save_numpy(path,X_train, X_test, y_train, y_test):
64
64
66
16
47
NikhilNandoskar/Iris-on-GCP
Iris on GCP/EDA_After_Train_Test.py
Python
save_numpy
save_numpy
21
25
21
21
fcfa86a489e84c7ab15795f2731a2a4d976df288
bigcode/the-stack
train
d2a2ec88e36d91a362b6501b
train
function
def transform_data(df): X = df.iloc[:,:-1] # Idependent Features y = df.iloc[:,-1] # Dependent Feature # convert from dataframes to numpy matrices X = np.array(X.values) y = np.array(y.values) y = y.flatten() return X, y
def transform_data(df):
X = df.iloc[:,:-1] # Idependent Features y = df.iloc[:,-1] # Dependent Feature # convert from dataframes to numpy matrices X = np.array(X.values) y = np.array(y.values) y = y.flatten() return X, y
#Imports import numpy as np import pandas as pd import time from sklearn.model_selection import train_test_split from EDA import * np.random.seed(0) def transform_data(df):
41
64
75
5
36
NikhilNandoskar/Iris-on-GCP
Iris on GCP/EDA_After_Train_Test.py
Python
transform_data
transform_data
12
19
12
12
3291cd15784191f2eb06a83360487277ae160386
bigcode/the-stack
train
e3166c61fdd587091fec60f4
train
function
def create_dataframe(X,y): df_data = pd.DataFrame(X, columns=['sepal_length', 'sepal_width','petal_length','petal_width']) df_target = pd.DataFrame(y, columns=['species']) # Final DataFrame df = pd.concat([df_data,df_target],axis=1) return df
def create_dataframe(X,y):
df_data = pd.DataFrame(X, columns=['sepal_length', 'sepal_width','petal_length','petal_width']) df_target = pd.DataFrame(y, columns=['species']) # Final DataFrame df = pd.concat([df_data,df_target],axis=1) return df
, y_train, y_test): np.save(path+'X_Train.npy',X_train) np.save(path+'X_Test.npy',X_test) np.save(path+'y_Train.npy',y_train) np.save(path+'y_Test.npy',y_test) def create_dataframe(X,y):
63
64
74
6
57
NikhilNandoskar/Iris-on-GCP
Iris on GCP/EDA_After_Train_Test.py
Python
create_dataframe
create_dataframe
27
33
27
27
c22962f17852d414ca7826ba99da98733f7bf0cd
bigcode/the-stack
train
b0a29c5c1dbee0c0f3eabeaa
train
class
class ProjectFileWriter: def __init__(self, filename, target_name, *, vc_platforms=None, root_namespace=None): self.filename = filename self.target_name = target_name self.root_namespace = root_namespace or target_name self._file = None self._vc_platforms = vc_platforms ...
class ProjectFileWriter:
def __init__(self, filename, target_name, *, vc_platforms=None, root_namespace=None): self.filename = filename self.target_name = target_name self.root_namespace = root_namespace or target_name self._file = None self._vc_platforms = vc_platforms self.indent = 2 ...
import contextlib import uuid from pathlib import Path _GENERATED_NAMESPACE = uuid.UUID('db509c23-800c-41d5-9d00-359fc120e87a') PROLOGUE = r"""<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">""" TARGETS = Path...
184
256
1,052
5
178
zooba/pymsbuild
pymsbuild/_writer.py
Python
ProjectFileWriter
ProjectFileWriter
31
144
31
31
fb069256a45876e5d18c1906b2baf588cc8318ef
bigcode/the-stack
train
48db2a14e0ba6a1bed97cfb1
train
function
def _guid(target_name): return uuid.uuid3(_GENERATED_NAMESPACE, target_name)
def _guid(target_name):
return uuid.uuid3(_GENERATED_NAMESPACE, target_name)
UE = r"""<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">""" TARGETS = Path(__file__).parent / "targets" def _guid(target_name):
64
64
19
6
58
zooba/pymsbuild
pymsbuild/_writer.py
Python
_guid
_guid
15
16
15
15
474f857fb3163ecad8f264bf4247827b64da1a9b
bigcode/the-stack
train
289033f90e6f4d8bcb91321b
train
class
class CV: has_condition = True def __init__(self, value, condition=None, if_empty=False): self.value = str(value) self.condition = condition self.if_empty = if_empty def __str__(self): return self.value
class CV:
has_condition = True def __init__(self, value, condition=None, if_empty=False): self.value = str(value) self.condition = condition self.if_empty = if_empty def __str__(self): return self.value
8"?> <Project DefaultTargets="Build" ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">""" TARGETS = Path(__file__).parent / "targets" def _guid(target_name): return uuid.uuid3(_GENERATED_NAMESPACE, target_name) class CV:
64
64
58
3
61
zooba/pymsbuild
pymsbuild/_writer.py
Python
CV
CV
19
28
19
19
9b2190735f9403820c3723ce81e24dba2cec5e9f
bigcode/the-stack
train
c914fec5e81ac3975e1be709
train
class
class AmendedListFilter(SimpleListFilter): title = _("amended") parameter_name = 'amended' def lookups(self, request, model_admin): return ( ('3', _("Closed amends")), ('2', _("Open amends")), ('1', _("Any amends")), ('0', _("No amends")), ...
class AmendedListFilter(SimpleListFilter):
title = _("amended") parameter_name = 'amended' def lookups(self, request, model_admin): return ( ('3', _("Closed amends")), ('2', _("Open amends")), ('1', _("Any amends")), ('0', _("No amends")), ) def queryset(self, request, que...
elif self.value() == 'BAD_DEBT': closed = queryset.filter(is_open=False).exclude(approx_total=0) return closed.filter( Q(transactions__state=Transaction.REJECTED) | Q(transactions__isnull=True) ) class AmendedListFilter(SimpleListFilter):
64
64
192
9
55
udm88/django-orchestra
orchestra/contrib/bills/filters.py
Python
AmendedListFilter
AmendedListFilter
137
160
137
137
26ada8ff8414621e9cc79bde6165a8220d937025
bigcode/the-stack
train
32b40795fe1a7399dab0c86e
train
class
class BillTypeListFilter(SimpleListFilter): """ Filter tickets by created_by according to request.user """ title = 'Type' parameter_name = '' def __init__(self, request, *args, **kwargs): super(BillTypeListFilter, self).__init__(request, *args, **kwargs) self.request = request ...
class BillTypeListFilter(SimpleListFilter):
""" Filter tickets by created_by according to request.user """ title = 'Type' parameter_name = '' def __init__(self, request, *args, **kwargs): super(BillTypeListFilter, self).__init__(request, *args, **kwargs) self.request = request def lookups(self, request, model_admin):...
from django.contrib.admin import SimpleListFilter from django.core.urlresolvers import reverse from django.db.models import Q from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ from . models import Bill class BillTypeListFilter(SimpleListFilter):
62
75
251
9
52
udm88/django-orchestra
orchestra/contrib/bills/filters.py
Python
BillTypeListFilter
BillTypeListFilter
10
42
10
10
b4781df910f2131849fc96a065fcdcf08babeb65
bigcode/the-stack
train
8d60629a4417d57650028cf2
train
class
class HasBillContactListFilter(SimpleListFilter): """ Filter Nodes by group according to request.user """ title = _("has bill contact") parameter_name = 'bill' def lookups(self, request, model_admin): return ( ('True', _("Yes")), ('False', _("No")), ) ...
class HasBillContactListFilter(SimpleListFilter):
""" Filter Nodes by group according to request.user """ title = _("has bill contact") parameter_name = 'bill' def lookups(self, request, model_admin): return ( ('True', _("Yes")), ('False', _("No")), ) def queryset(self, request, queryset): i...
return queryset.filter(approx_total=0) elif self.value() == 'lt': return queryset.filter(approx_total__lt=0) elif self.value() == 'ne': return queryset.exclude(approx_total=0) return queryset class HasBillContactListFilter(SimpleListFilter):
64
64
119
10
53
udm88/django-orchestra
orchestra/contrib/bills/filters.py
Python
HasBillContactListFilter
HasBillContactListFilter
69
84
69
69
f39181682e40c6d625bf718c5258f691c231a9de
bigcode/the-stack
train
cd4dc3561e8cbc0039f58699
train
class
class TotalListFilter(SimpleListFilter): title = _("total") parameter_name = 'total' def lookups(self, request, model_admin): return ( ('gt', mark_safe("total &gt; 0")), ('lt', mark_safe("total &lt; 0")), ('eq', "total = 0"), ('ne', mark_safe("tot...
class TotalListFilter(SimpleListFilter):
title = _("total") parameter_name = 'total' def lookups(self, request, model_admin): return ( ('gt', mark_safe("total &gt; 0")), ('lt', mark_safe("total &lt; 0")), ('eq', "total = 0"), ('ne', mark_safe("total &ne; 0")), ) def quer...
lookup, title in self.lookup_choices: yield { 'selected': self.value() == lookup, 'query_string': reverse('admin:bills_%s_changelist' % lookup) + '?%s' % query, 'display': title, } class TotalListFilter(SimpleListFilter):
64
64
184
8
56
udm88/django-orchestra
orchestra/contrib/bills/filters.py
Python
TotalListFilter
TotalListFilter
45
66
45
45
a1c05843b0daa23fb8ddb9aa6558cae3072faf16
bigcode/the-stack
train
f8b6c03bfbdae6b8d8c402d2
train
class
class PaymentStateListFilter(SimpleListFilter): title = _("payment state") parameter_name = 'payment_state' def lookups(self, request, model_admin): return ( ('OPEN', _("Open")), ('PAID', _("Paid")), ('PENDING', _("Pending")), ('BAD_DEBT', _("Bad ...
class PaymentStateListFilter(SimpleListFilter):
title = _("payment state") parameter_name = 'payment_state' def lookups(self, request, model_admin): return ( ('OPEN', _("Open")), ('PAID', _("Paid")), ('PENDING', _("Pending")), ('BAD_DEBT', _("Bad debt")), ) def queryset(self, r...
queryset.exclude(approx_total=0) return queryset class HasBillContactListFilter(SimpleListFilter): """ Filter Nodes by group according to request.user """ title = _("has bill contact") parameter_name = 'bill' def lookups(self, request, model_admin): return ( ('True', ...
140
140
469
9
131
udm88/django-orchestra
orchestra/contrib/bills/filters.py
Python
PaymentStateListFilter
PaymentStateListFilter
87
134
87
87
03c858227d665f312b8d3f8a568706b0b5873872
bigcode/the-stack
train
ef7c1077a0123aba66acddfb
train
class
class SawyerHandlePressSideEnv(SawyerXYZEnv): def __init__(self): hand_low = (-0.5, 0.40, 0.05) hand_high = (0.5, 1, 0.5) obj_low = (-0.35, 0.65, 0.05) obj_high = (-0.25, 0.75, 0.05) super().__init__( self.model_name, hand_low=hand_low, h...
class SawyerHandlePressSideEnv(SawyerXYZEnv):
def __init__(self): hand_low = (-0.5, 0.40, 0.05) hand_high = (0.5, 1, 0.5) obj_low = (-0.35, 0.65, 0.05) obj_high = (-0.25, 0.75, 0.05) super().__init__( self.model_name, hand_low=hand_low, hand_high=hand_high, ) self.in...
import numpy as np from gym.spaces import Box from metaworld.envs.env_util import get_asset_full_path from metaworld.envs.mujoco.sawyer_xyz.base import SawyerXYZEnv, _assert_task_is_set class SawyerHandlePressSideEnv(SawyerXYZEnv):
63
256
1,190
12
50
joncrawf/mime
metaworld/envs/mujoco/sawyer_xyz/sawyer_handle_press_side.py
Python
SawyerHandlePressSideEnv
SawyerHandlePressSideEnv
8
133
8
8
b95e4184696e20a6152744e29d880ee55dd987d5
bigcode/the-stack
train
d14cc7d5e2de340428434067
train
class
class SARSAAgent: def __init__(self,env, layers=8, features=1893, gamma=1.0, learning_rate=0.03, epsilon=0.001): self.action_n = env.action_space.n # 动作数 self.obs_low = env.observation_space.low self.obs_scale = env.observation_space.high - env.observation_space.low # 观测空间范围 self.enc...
class SARSAAgent:
def __init__(self,env, layers=8, features=1893, gamma=1.0, learning_rate=0.03, epsilon=0.001): self.action_n = env.action_space.n # 动作数 self.obs_low = env.observation_space.low self.obs_scale = env.observation_space.high - env.observation_space.low # 观测空间范围 self.encoder = TileCoder(l...
range(self.layers): codeword = (layer,) + tuple(int((f+(1+dim * i)*layer)/self.layers) for i,f in enumerate(scaled_floats))+ints feature = self.get_feature(codeword) features.append(feature) return features class SARSAAgent:
64
64
101
5
58
lusing/algo
dqn.py
Python
SARSAAgent
SARSAAgent
31
36
31
31
8418055f47e66486f1148ed5bb9c549fab5ff372
bigcode/the-stack
train
c3000fb55182ddacc4eeae64
train
class
class TileCoder: def __init__(self, layers, features): self.layers = layers self.features = features self.codebook = {} def get_feature(self, codeword): if codeword in self.codebook: return self.codebook[codeword] count = len(self.codebook) if count>...
class TileCoder:
def __init__(self, layers, features): self.layers = layers self.features = features self.codebook = {} def get_feature(self, codeword): if codeword in self.codebook: return self.codebook[codeword] count = len(self.codebook) if count>=self.features: ...
import gym env = gym.make('MountainCar-v0') class TileCoder:
17
64
208
4
13
lusing/algo
dqn.py
Python
TileCoder
TileCoder
4
28
4
4
4540910a34ef69be6147723c0027a1d5fefd3cac
bigcode/the-stack
train
c7f1648918138ca89180867e
train
function
def cleanLogs(logDir:str='./logs'): if os.path.isdir(logDir): rmtree(logDir) else: print('Path does not denote a valid directory...')
def cleanLogs(logDir:str='./logs'):
if os.path.isdir(logDir): rmtree(logDir) else: print('Path does not denote a valid directory...')
0.1" __maintainer__ = "Konstantin Rolf" __email__ = "konstantin.rolf@gmail.com" __status__ = "Prototype" import sys # sys.exit import argparse import os from shutil import rmtree def cleanLogs(logDir:str='./logs'):
64
64
37
9
54
KonstantinRr/logutils
logutils/cleanlog.py
Python
cleanLogs
cleanLogs
26
30
26
26
77d0461e71e9ef3532f04e62167255858f6932cd
bigcode/the-stack
train
419126dde22984e851fb2b47
train
class
class MapperTestCase(unittest.TestCase): def test_mapper_no_exceptions(self): m = mapper.Mapper(3, 3, seed=42) res = [] def injection(key, value, shingles): res.append([key, value, shingles]) m.print_res = injection m.map(some_data_line1) self.assertEq...
class MapperTestCase(unittest.TestCase):
def test_mapper_no_exceptions(self): m = mapper.Mapper(3, 3, seed=42) res = [] def injection(key, value, shingles): res.append([key, value, shingles]) m.print_res = injection m.map(some_data_line1) self.assertEqual(len(res), 3) def test_simple_map...
398 8364 7807 6443 3122 3292 8004 5448 15 9540 1155 5049 8677 6764 6944" some_data_line2 = "VIDEO_000000000 123 747 2776" some_data_line3 = "VIDEO_000000007 123 747 2776" class MapperTestCase(unittest.TestCase):
90
90
301
8
82
lukaselmer/ethz-data-mining
1-lsh/test/test_mapper.py
Python
MapperTestCase
MapperTestCase
10
55
10
10
6e840b16189ea3a37042446cde607aafe4c33ea0
bigcode/the-stack
train
b2b8d4a04092fb84b33fe421
train
class
class AbstractInstanceVolume(ABC): def __init__(self, volume_config: dict): self._name = volume_config['name'] self._params = self._validate_volume_parameters(volume_config['parameters']) @abstractmethod def _validate_volume_parameters(self, params: dict) -> dict: raise NotImplemen...
class AbstractInstanceVolume(ABC):
def __init__(self, volume_config: dict): self._name = volume_config['name'] self._params = self._validate_volume_parameters(volume_config['parameters']) @abstractmethod def _validate_volume_parameters(self, params: dict) -> dict: raise NotImplementedError @property def name...
from abc import ABC, abstractmethod class AbstractInstanceVolume(ABC):
15
71
237
7
7
greglira/spotty
spotty/config/abstract_instance_volume.py
Python
AbstractInstanceVolume
AbstractInstanceVolume
4
38
4
5
8ccc908e5ea81e383918814ad1193e189d1c447f
bigcode/the-stack
train
8d2146f29bb8e15dc5ac629d
train
function
def sort_batch(seq_len): """Sorts torch tensor of integer indices by decreasing order.""" with torch.no_grad(): slens, sidxs = torch.sort(seq_len, descending=True) oidxs = torch.sort(sidxs)[1] return oidxs, sidxs, slens.tolist()
def sort_batch(seq_len):
"""Sorts torch tensor of integer indices by decreasing order.""" with torch.no_grad(): slens, sidxs = torch.sort(seq_len, descending=True) oidxs = torch.sort(sidxs)[1] return oidxs, sidxs, slens.tolist()
import torch import torch.nn as nn from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence import src.utils.init as my_init from src.utils import nest def sort_batch(seq_len):
46
64
68
6
39
howardchenhd/Paraphrase_Copy
src/modules/rnn.py
Python
sort_batch
sort_batch
7
13
7
7
3e27ea325b291c254eb80a19fc1271dfc3afc493
bigcode/the-stack
train
fc95a5db4dc8eef55ddbe6fb
train
class
class RNN(nn.Module): def __init__(self, type, batch_first=False, **kwargs): super().__init__() self.type = type self.batch_first = batch_first # We always use batch first mode. if self.type == "gru": self.rnn = nn.GRU(batch_first=True, **kwargs) elif ...
class RNN(nn.Module):
def __init__(self, type, batch_first=False, **kwargs): super().__init__() self.type = type self.batch_first = batch_first # We always use batch first mode. if self.type == "gru": self.rnn = nn.GRU(batch_first=True, **kwargs) elif self.type == "lstm": ...
import torch import torch.nn as nn from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence import src.utils.init as my_init from src.utils import nest def sort_batch(seq_len): """Sorts torch tensor of integer indices by decreasing order.""" with torch.no_grad(): slens, sidxs = torch.so...
114
206
688
6
108
howardchenhd/Paraphrase_Copy
src/modules/rnn.py
Python
RNN
RNN
15
103
15
16
7f82268d4e33ea208a93172284eef4068998224c
bigcode/the-stack
train
685a5a11935149bdbf766453
train
function
@cmd("start", group="Timer", desc="Start your timer.", aliases=["restart"]) @in_guild() @timer_ready() async def cmd_start(ctx): """ Usage``: start start <setup string> Description: Start the timer you are subscribed to. Can be used with a setup string to set u...
@cmd("start", group="Timer", desc="Start your timer.", aliases=["restart"]) @in_guild() @timer_ready() async def cmd_start(ctx):
""" Usage``: start start <setup string> Description: Start the timer you are subscribed to. Can be used with a setup string to set up and start the timer in one go. """ timer = ctx.client.interface.get_timer_for(ctx.guild.id, ctx.author.id) if timer is None: ...
Didn't recognise the timer preset `{}`.\n" "Use the `presets` command to view available presets.").format(ctx.arg_str) ) timer.setup(stages) await ctx.reply("Timer pattern set up! Start when ready.") @cmd("start", group="Timer", desc="Start your timer.", alia...
89
90
301
37
52
bekobeko57/--recurse-submodules
bot/commands/timer.py
Python
cmd_start
cmd_start
212
255
212
218
8eda54f5c46dc410d30048fa6f3d5207ff60c53b
bigcode/the-stack
train
8cdac728e2108676b78f86dd
train
function
@cmd("join", group="Timer", desc="Join a group bound to the current channel.", aliases=['sub']) @in_guild() @timer_ready() async def cmd_join(ctx): """ Usage``: join join <group> Description: Join a group in the current channel or guild. If there are multiple m...
@cmd("join", group="Timer", desc="Join a group bound to the current channel.", aliases=['sub']) @in_guild() @timer_ready() async def cmd_join(ctx):
""" Usage``: join join <group> Description: Join a group in the current channel or guild. If there are multiple matching groups, or no group is provided, will show the group selector. Related: leave, status, groups, globalgroups Examples``: joi...
# import datetime import discord from cmdClient import cmd from cmdClient.checks import in_guild from Timer import TimerState, NotifyLevel from utils import timer_utils, interactive, ctx_addons # noqa from wards import timer_ready from presets import get_presets @cmd("join", group="Timer", desc="Join a g...
102
195
652
42
59
bekobeko57/--recurse-submodules
bot/commands/timer.py
Python
cmd_join
cmd_join
15
93
15
21
ab7cd220fb8d3b94fdc98b2a81f3dd99340f0dc7
bigcode/the-stack
train
a251fa04233241e1e41516e6
train
function
@cmd("status", group="Timer", desc="View detailed information about a group.", aliases=["group", "timer"]) @in_guild() @timer_ready() async def cmd_group(ctx): """ Usage``: status [group] Description: Display detailed information about the current group or the specified group....
@cmd("status", group="Timer", desc="View detailed information about a group.", aliases=["group", "timer"]) @in_guild() @timer_ready() async def cmd_group(ctx):
""" Usage``: status [group] Description: Display detailed information about the current group or the specified group. """ if ctx.arg_str: timer = await ctx.get_timers_matching(ctx.arg_str, channel_only=False) if timer is None: return await ctx.error_reply(...
description="\n\n\n".join(sections), colour=discord.Colour(0x9b59b6), title="Group timers in this guild" ) return {'embed': embed} await ctx.live_reply(_groups) @cmd("status", group="Timer", desc="View detailed information about a group.", aliases=...
95
95
317
43
52
bekobeko57/--recurse-submodules
bot/commands/timer.py
Python
cmd_group
cmd_group
328
367
328
334
8a5f69c969a6e0cb3c8f01b1883fdf42c6ff86bf
bigcode/the-stack
train
c1a6039fc2c1fc5c84fed4c3
train
function
@cmd("syncwith", group="Timer", desc="Sync the start of your group timer with another group") @in_guild() @timer_ready() async def cmd_syncwith(ctx): """ Usage``: syncwith <group> Description: Align the start of your group timer with the other group. This will possibly chan...
@cmd("syncwith", group="Timer", desc="Sync the start of your group timer with another group") @in_guild() @timer_ready() async def cmd_syncwith(ctx):
""" Usage``: syncwith <group> Description: Align the start of your group timer with the other group. This will possibly change your stage without notification. Arguments:: group: The name of the group to sync with. Related: join, status, groups, set """ ...
_timer_for(ctx.guild.id, ctx.author.id) if timer is None: return await ctx.error_reply( "You need to join a group first!" ) if not (0 < len(ctx.arg_str) < 20): return await ctx.error_reply( "Please supply a new group name under `20` characters long!\n" ...
157
157
525
41
116
bekobeko57/--recurse-submodules
bot/commands/timer.py
Python
cmd_syncwith
cmd_syncwith
474
530
474
479
2e1963cb2ce9031f8333c0c2956e9da07300b372
bigcode/the-stack
train
9bfde38250c84c8279d881b6
train
function
@cmd("groups", group="Timer", desc="View the guild's groups.", aliases=["timers"]) @in_guild() @timer_ready() async def cmd_groups(ctx): # Handle there being no timers if not ctx.client.interface.get_guild_timers(ctx.guild.id): return await ctx.error_reply("There are no groups set up in t...
@cmd("groups", group="Timer", desc="View the guild's groups.", aliases=["timers"]) @in_guild() @timer_ready() async def cmd_groups(ctx): # Handle there being no timers
if not ctx.client.interface.get_guild_timers(ctx.guild.id): return await ctx.error_reply("There are no groups set up in this guild!") if "live_grouptokens" not in ctx.client.objects: ctx.client.objects["live_grouptokens"] = {} ctx.client.objects["live_grouptokens"][ctx.ch.id] = ctx.msg.id ...
in your study group! " "Are you sure you want to stop the study group timer?"): return timer.stop() await ctx.reply("Your timer has been stopped.") @cmd("groups", group="Timer", desc="View the guild's groups.", aliases=["timers"]) @in_guild() @timer_read...
87
88
295
48
39
bekobeko57/--recurse-submodules
bot/commands/timer.py
Python
cmd_groups
cmd_groups
290
325
290
297
6d787373226ac60a1d967a22fe729cc8a4e25c1a
bigcode/the-stack
train
44866906ce9d86a8c75adcc1
train
function
@cmd("notify", group="Timer", desc="Configure your personal notification level.", aliases=["dm"]) async def cmd_notify(ctx): """ Usage``: notify notify <level> Description: View or set your notification level. The possible levels are described below. Notifi...
@cmd("notify", group="Timer", desc="Configure your personal notification level.", aliases=["dm"]) async def cmd_notify(ctx):
""" Usage``: notify notify <level> Description: View or set your notification level. The possible levels are described below. Notification levels:: all: Receive all stage changes and status updates via DM. warnings: Only receive a DM for inactivity warning...
timer = await ctx.get_timers_matching("", channel_only=False) if timer is None: return await ctx.error_reply("No groups are set up in this guild.") if "live_statustokens" not in ctx.client.objects: ctx.client.objects["live_statustokens"] = {} ctx.client.objects["...
202
202
676
30
172
bekobeko57/--recurse-submodules
bot/commands/timer.py
Python
cmd_notify
cmd_notify
370
441
370
374
3a8b6602b77415479401e0a153f7f33e03c89534
bigcode/the-stack
train
c795c5d6a0486154a1712390
train
function
@cmd("leave", group="Timer", desc="Leave your current group.", aliases=['unsub']) @in_guild() @timer_ready() async def cmd_unsub(ctx): """ Usage``: leave Description: Leave your current group, and unsubscribe from the group timer. Related: join, status, groups ...
@cmd("leave", group="Timer", desc="Leave your current group.", aliases=['unsub']) @in_guild() @timer_ready() async def cmd_unsub(ctx):
""" Usage``: leave Description: Leave your current group, and unsubscribe from the group timer. Related: join, status, groups """ timer = ctx.client.interface.get_timer_for(ctx.guild.id, ctx.author.id) if timer is None: return await ctx.error_reply( ...
_channel: await timer.channel.send("*{} has joined **{}***. Good luck!".format( ctx.author.mention, timer.name, )) @cmd("leave", group="Timer", desc="Leave your current group.", aliases=['unsub']) @in_guild() @timer_ready() async def cmd_unsub(ctx):
72
73
245
40
32
bekobeko57/--recurse-submodules
bot/commands/timer.py
Python
cmd_unsub
cmd_unsub
96
130
96
102
0cdd6619aaf353ae2113090fad63f53630843e04
bigcode/the-stack
train
b9fe6df3df3da0cef8eb726e
train
function
@cmd("stop", group="Timer", desc="Stop your timer.") @in_guild() @timer_ready() async def cmd_stop(ctx): """ Usage``: stop Description: Stop the timer you are subscribed to. """ timer = ctx.client.interface.get_timer_for(ctx.guild.id, ctx.author.id) if timer is None: ...
@cmd("stop", group="Timer", desc="Stop your timer.") @in_guild() @timer_ready() async def cmd_stop(ctx):
""" Usage``: stop Description: Stop the timer you are subscribed to. """ timer = ctx.client.interface.get_timer_for(ctx.guild.id, ctx.author.id) if timer is None: tchan = ctx.client.interface.channels.get(ctx.ch.id, None) if tchan is None or not tchan.timers: ...
up the timer first!") await timer.start() if timer.channel != ctx.ch: await ctx.reply("Timer has been started in {}".format(timer.channel.mention)) @cmd("stop", group="Timer", desc="Stop your timer.") @in_guild() @timer_ready() async def cmd_stop(ctx):
67
67
224
32
35
bekobeko57/--recurse-submodules
bot/commands/timer.py
Python
cmd_stop
cmd_stop
258
287
258
263
fdfe66a9aa06d3bc50b60b2c690cb4a1380c85fa
bigcode/the-stack
train
ca7e7024ea07077d3be84a92
train
function
@cmd("rename", group="Timer", desc="Rename your group.") @in_guild() @timer_ready() async def cmd_rename(ctx): """ Usage``: rename <groupname> Description: Set the name of your current group to `groupname`. Arguments:: groupname: The new name for your group, less than `...
@cmd("rename", group="Timer", desc="Rename your group.") @in_guild() @timer_ready() async def cmd_rename(ctx):
""" Usage``: rename <groupname> Description: Set the name of your current group to `groupname`. Arguments:: groupname: The new name for your group, less than `20` charachters long. Related: join, status, groups """ timer = ctx.client.interface.get_timer_for(ct...
.client.interface.get_subs_for(ctx.author.id): subber.notify = NotifyLevel(newlevel) # Send the update message await ctx.reply(message) @cmd("rename", group="Timer", desc="Rename your group.") @in_guild() @timer_ready() async def cmd_rename(ctx):
66
66
220
33
33
bekobeko57/--recurse-submodules
bot/commands/timer.py
Python
cmd_rename
cmd_rename
444
471
444
449
681be70682010fc4685a79a938c85e8445440c79
bigcode/the-stack
train
32c069211ca00c950084cd3a
train
function
@cmd("set", group="Timer", desc="Setup the stages of a group timer.", aliases=['setup', 'reset']) @in_guild() @timer_ready() async def cmd_set(ctx): """ Usage``: set set <setup string> set <presetname> Description: Setup the stages of the timer you are subscrib...
@cmd("set", group="Timer", desc="Setup the stages of a group timer.", aliases=['setup', 'reset']) @in_guild() @timer_ready() async def cmd_set(ctx):
""" Usage``: set set <setup string> set <presetname> Description: Setup the stages of the timer you are subscribed to. When used with no parameters, uses the following default setup string: ``` Study, 25, Good luck!; Break, 5, Have a rest.; Stu...
(ctx.guild.id, ctx.author.id) if timer is None: return await ctx.error_reply( "You need to join a group before you can leave one!" ) session = await ctx.client.interface.unsub(ctx.guild.id, ctx.author.id) clocked = session[-1] dur = int(clocked) hours = dur // 3600 ...
203
204
681
44
159
bekobeko57/--recurse-submodules
bot/commands/timer.py
Python
cmd_set
cmd_set
133
209
133
139
11d1590fc3cec9f5faff5ecfed75cf7ab22e936c
bigcode/the-stack
train
149344f3ce871391b7e57db8
train
class
class FFTshift(gr.basic_block): #constructor def __init__(self,size,drop_when_overloaded): gr.basic_block.__init__(self, name="FFT_Shift", in_sig=[(numpy.float32,size)], out_sig=[(numpy.float32,size)]) self.drop_true = drop_when_overloaded #run def general_work(self, input_items, output_items): in0 = i...
class FFTshift(gr.basic_block): #constructor
def __init__(self,size,drop_when_overloaded): gr.basic_block.__init__(self, name="FFT_Shift", in_sig=[(numpy.float32,size)], out_sig=[(numpy.float32,size)]) self.drop_true = drop_when_overloaded #run def general_work(self, input_items, output_items): in0 = input_items[0] out = output_items[0] if le...
#!/usr/bin/env python from gnuradio import gr from gnuradio import blocks from gnuradio import digital import numpy #applies fftshift to a vecter. # class FFTshift(gr.basic_block): #constructor
52
64
207
11
41
cityscapesc/specobs
main/tools/USRP_N200_UBX40_Filter_Testing/GRC/FFTshift.py
Python
FFTshift
FFTshift
9
37
9
10
29cb1e0c8fbbf95d93f131aea446baab8ed95f2f
bigcode/the-stack
train
6a3f5fe726651d080245abe7
train
function
def data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes): '''data generator for fit_generator''' n = len(annotation_lines) i = 0 while True: image_data = [] box_data = [] for b in range(batch_size): if i==0: np.rando...
def data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes):
'''data generator for fit_generator''' n = len(annotation_lines) i = 0 while True: image_data = [] box_data = [] for b in range(batch_size): if i==0: np.random.shuffle(annotation_lines) image, box = get_random_data(annotation_lines...
.readline() anchors = [float(x) for x in anchors.split(',')] return np.array(anchors).reshape(-1, 2) #---------------------------------------------------# # 训练数据生成器 #---------------------------------------------------# def data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes):...
64
64
165
17
47
LiaoSteve/yolo3-keras
train.py
Python
data_generator
data_generator
34
51
34
34
f5d3abc2cc4b6a0d76fc3929fd8ea1c76aae5f23
bigcode/the-stack
train
de0b52805e82ee714c0744e5
train
function
def preprocess_true_boxes(true_boxes, input_shape, anchors, num_classes): assert (true_boxes[..., 4]<num_classes).all(), 'class id must be less than num_classes' # 一共有三个特征层数 num_layers = len(anchors)//3 # 先验框 # 678为116,90, 156,198, 373,326 # 345为30,61, 62,45, 59,119 # 012为10,13,...
def preprocess_true_boxes(true_boxes, input_shape, anchors, num_classes):
assert (true_boxes[..., 4]<num_classes).all(), 'class id must be less than num_classes' # 一共有三个特征层数 num_layers = len(anchors)//3 # 先验框 # 678为116,90, 156,198, 373,326 # 345为30,61, 62,45, 59,119 # 012为10,13, 16,30, 33,23, anchor_mask = [[6,7,8], [3,4,5], [0,1,2]] if num_laye...
_path) as f: anchors = f.readline() anchors = [float(x) for x in anchors.split(',')] return np.array(anchors).reshape(-1, 2) #---------------------------------------------------# # 训练数据生成器 #---------------------------------------------------# def data_generator(annotation_lines, batch_size, i...
256
256
975
15
241
LiaoSteve/yolo3-keras
train.py
Python
preprocess_true_boxes
preprocess_true_boxes
57
125
57
58
f6c634b685bcc05f61552e3b34ed964e97c1965e
bigcode/the-stack
train
92b58361d574e8615dd8b382
train
function
def get_anchors(anchors_path): '''loads the anchors from a file''' with open(anchors_path) as f: anchors = f.readline() anchors = [float(x) for x in anchors.split(',')] return np.array(anchors).reshape(-1, 2)
def get_anchors(anchors_path):
'''loads the anchors from a file''' with open(anchors_path) as f: anchors = f.readline() anchors = [float(x) for x in anchors.split(',')] return np.array(anchors).reshape(-1, 2)
和先验框 #---------------------------------------------------# def get_classes(classes_path): '''loads the classes''' with open(classes_path) as f: class_names = f.readlines() class_names = [c.strip() for c in class_names] return class_names def get_anchors(anchors_path):
64
64
62
8
55
LiaoSteve/yolo3-keras
train.py
Python
get_anchors
get_anchors
24
29
24
24
c12b324a5d24b29c0d980b1094a9c727d2fc834c
bigcode/the-stack
train
4e2d10f379eb9828cc23fa9b
train
function
def get_classes(classes_path): '''loads the classes''' with open(classes_path) as f: class_names = f.readlines() class_names = [c.strip() for c in class_names] return class_names
def get_classes(classes_path):
'''loads the classes''' with open(classes_path) as f: class_names = f.readlines() class_names = [c.strip() for c in class_names] return class_names
EarlyStopping from nets.yolo3 import yolo_body from nets.loss import yolo_loss from keras.backend.tensorflow_backend import set_session from utils.utils import get_random_data #---------------------------------------------------# # 获得类和先验框 #---------------------------------------------------# def get_clas...
64
64
47
6
58
LiaoSteve/yolo3-keras
train.py
Python
get_classes
get_classes
17
22
17
17
1e43ce38b06ef7e45064d8f0bec1a895831a17d9
bigcode/the-stack
train
03895cd775c29a775dc5c987
train
class
class RadioButton(BaseButton): def __init__(self, name, selected_value=''): super(RadioButton, self).__init__('RADIO_BUTTON', name) self.set_selected_value(selected_value) def set_selected_value(self, selected_value): self.data['selectedValue'] = selected_value
class RadioButton(BaseButton):
def __init__(self, name, selected_value=''): super(RadioButton, self).__init__('RADIO_BUTTON', name) self.set_selected_value(selected_value) def set_selected_value(self, selected_value): self.data['selectedValue'] = selected_value
#!/usr/bin/env python3 # -*- encoding=utf-8 -*- # description: # author:jack # create_time: 2018/5/28 from dueros.directive.AudioPlayer.Control.BaseButton import BaseButton class RadioButton(BaseButton):
53
64
64
6
46
Mryan2005/bot-sdk-python
dueros/directive/AudioPlayer/Control/RadioButton.py
Python
RadioButton
RadioButton
11
19
11
12
e108ed47500cc6a3e3e4b637f237ed17906f9d8d
bigcode/the-stack
train
971d973730accdee65c44ba1
train
function
def register_plugin(): if platform_.name == "windows": return CMD
def register_plugin():
if platform_.name == "windows": return CMD
("call %s" % value) def command(self, value): self._addline(value) def get_key_token(self, key): return "%%%s%%" % key def join(self, command): return shlex_join(command).replace("'", '"') def register_plugin():
64
64
17
4
60
ColinKennedy/tk-config-default2-respawn
vendors/rez-2.23.1-py2.7/rezplugins/shell/cmd.py
Python
register_plugin
register_plugin
314
316
314
314
66fd9860d97c50d582a09bb7ba353a2ccbb361b4
bigcode/the-stack
train
89a4a6c528020b954e306dd9
train
class
class CMD(Shell): # For reference, the ss64 web page provides useful documentation on builtin # commands for the Windows Command Prompt (cmd). It can be found here : # http://ss64.com/nt/cmd.html syspaths = None _executable = None _doskey = None # Regex to aid with escaping of Windows-spec...
class CMD(Shell): # For reference, the ss64 web page provides useful documentation on builtin # commands for the Windows Command Prompt (cmd). It can be found here : # http://ss64.com/nt/cmd.html
syspaths = None _executable = None _doskey = None # Regex to aid with escaping of Windows-specific special chars: # http://ss64.com/nt/syntax-esc.html _escape_re = re.compile(r'(?<!\^)[&<>]|(?<!\^)\^(?![&<>\^])') _escaper = partial(_escape_re.sub, lambda m: '^' + m.group(0)) @property ...
""" Windows Command Prompt (DOS) shell. """ from rez.config import config from rez.rex import RexExecutor, literal, OutputStyle, EscapedString from rez.shells import Shell from rez.system import system from rez.utils.system import popen from rez.utils.platform_ import platform_ from rez.util import shlex_join from func...
136
256
2,188
52
83
ColinKennedy/tk-config-default2-respawn
vendors/rez-2.23.1-py2.7/rezplugins/shell/cmd.py
Python
CMD
CMD
17
311
17
20
af3c347841956d9574f112e7b4147bac6f3c6f60
bigcode/the-stack
train
d2a35059dff4649edd6eef42
train
class
class TestAffinity: async def test_unit__create_affinity__ok__nominal_case( self, worldmapc_xena_model: CharacterModel, worldmapc_web_app: TestClient, descr_serializer: serpyco.Serializer, worldmapc_kernel: Kernel, ) -> None: web = worldmapc_web_app xena =...
class TestAffinity:
async def test_unit__create_affinity__ok__nominal_case( self, worldmapc_xena_model: CharacterModel, worldmapc_web_app: TestClient, descr_serializer: serpyco.Serializer, worldmapc_kernel: Kernel, ) -> None: web = worldmapc_web_app xena = worldmapc_xena_mode...
# coding: utf-8 from aiohttp.test_utils import TestClient import pytest import serpyco import urllib from rolling.kernel import Kernel from rolling.model.character import CharacterModel from rolling.server.document.affinity import AffinityDirectionType from rolling.server.document.affinity import AffinityDocument from...
161
256
7,362
4
156
buxx/rolling
tests/unit/test_affinity.py
Python
TestAffinity
TestAffinity
22
807
22
22
a5e56a3c0a3a73f271ea4a2b56efe4f793760a63
bigcode/the-stack
train
3fc928f8d78217ecb239dde5
train
class
@pytest.mark.skipif(sys.version_info.major >= 3, reason="Evernote API not compatible with py3.") class TestEvernote: def test_connect(self): # Tricky mocking. Need to mock the EvernoteClient import in # pypdfocr_filer_evernote.py file with patch("pypdfocr.pypdfocr_filer...
@pytest.mark.skipif(sys.version_info.major >= 3, reason="Evernote API not compatible with py3.") class TestEvernote:
def test_connect(self): # Tricky mocking. Need to mock the EvernoteClient import in # pypdfocr_filer_evernote.py file with patch("pypdfocr.pypdfocr_filer_evernote.EvernoteClient") \ as mock_evernote_client: P.PyFilerEvernote("TOKEN") inst = mock_evern...
import hashlib import os import sys import pytest from mock import patch import pypdfocr.pypdfocr_filer_evernote as P if sys.version_info.major == 2: import evernote.edam.type.ttypes as Types def test_import(): """Evernote filing enabled for py2 only""" expect_enabled = sys.version_info.major == 2 ...
120
256
1,197
29
90
benjsec/pypdfocr
test/test_evernote.py
Python
TestEvernote
TestEvernote
20
138
20
23
2a3c94b416887d0eb421c454574d1b7fc3eae134
bigcode/the-stack
train
28281d8750e366dd331c3b20
train
function
def test_import(): """Evernote filing enabled for py2 only""" expect_enabled = sys.version_info.major == 2 assert P.ENABLED == expect_enabled
def test_import():
"""Evernote filing enabled for py2 only""" expect_enabled = sys.version_info.major == 2 assert P.ENABLED == expect_enabled
import hashlib import os import sys import pytest from mock import patch import pypdfocr.pypdfocr_filer_evernote as P if sys.version_info.major == 2: import evernote.edam.type.ttypes as Types def test_import():
59
64
36
4
54
benjsec/pypdfocr
test/test_evernote.py
Python
test_import
test_import
14
17
14
14
e82301977dbdc7205d41f2e3f944d27ba70e080d
bigcode/the-stack
train
e2b43f666ede5e45ed0b60f8
train
class
class CreditCard(graphene.ObjectType): brand = graphene.String(description="Card brand.", required=True) first_digits = graphene.String( description="First 4 digits of the card number.", required=False ) last_digits = graphene.String( description="Last 4 digits of the card number.", requ...
class CreditCard(graphene.ObjectType):
brand = graphene.String(description="Card brand.", required=True) first_digits = graphene.String( description="First 4 digits of the card number.", required=False ) last_digits = graphene.String( description="Last 4 digits of the card number.", required=True ) exp_month = graphen...
id", "created", "payment", "token", "kind", "is_success", "error", "gateway_response", ] @staticmethod def resolve_amount(root: models.Transaction, _info): return root.get_amount() class CreditCard(graphene.Obje...
64
64
121
8
56
nguyentrung194/e-com
saleor/saleor/graphql/payment/types.py
Python
CreditCard
CreditCard
37
52
37
37
ba68236e80b384e53394651f2e5fed78309a75b1
bigcode/the-stack
train
df63789b8b2923290a45888f
train
class
class Transaction(CountableDjangoObjectType): amount = graphene.Field(Money, description="Total amount of the transaction.") class Meta: description = "An object representing a single payment." interfaces = [relay.Node] model = models.Transaction filter_fields = ["id"] o...
class Transaction(CountableDjangoObjectType):
amount = graphene.Field(Money, description="Total amount of the transaction.") class Meta: description = "An object representing a single payment." interfaces = [relay.Node] model = models.Transaction filter_fields = ["id"] only_fields = [ "id", "...
core.tracing import traced_resolver from ...payment import models from ..core.connection import CountableDjangoObjectType from ..core.types import Money from ..decorators import permission_required from .enums import OrderAction, PaymentChargeStatusEnum class Transaction(CountableDjangoObjectType):
64
64
124
10
53
nguyentrung194/e-com
saleor/saleor/graphql/payment/types.py
Python
Transaction
Transaction
13
34
13
13
fcdd1f1913e2c5225de8521cd78921292f5255b7
bigcode/the-stack
train
8ffc6c704571db22cf1c6fe2
train
class
class PaymentSource(graphene.ObjectType): class Meta: description = ( "Represents a payment source stored " "for user in payment gateway, such as credit card." ) gateway = graphene.String(description="Payment gateway name.", required=True) payment_method_id = graphen...
class PaymentSource(graphene.ObjectType):
class Meta: description = ( "Represents a payment source stored " "for user in payment gateway, such as credit card." ) gateway = graphene.String(description="Payment gateway name.", required=True) payment_method_id = graphene.String(description="ID of stored payment...
=True ) exp_month = graphene.Int( description=("Two-digit number representing the card’s expiration month."), required=False, ) exp_year = graphene.Int( description=("Four-digit number representing the card’s expiration year."), required=False, ) class PaymentSource(g...
64
64
92
8
56
nguyentrung194/e-com
saleor/saleor/graphql/payment/types.py
Python
PaymentSource
PaymentSource
55
66
55
55
7b17f6c32de6e71451ebdd158f4d5c60ffad211b
bigcode/the-stack
train
9e7740d4eac278b001efd978
train
class
class PaymentInitialized(graphene.ObjectType): class Meta: description = ( "Server-side data generated by a payment gateway. Optional step when the " "payment provider requires an additional action to initialize payment " "session." ) gateway = graphene.Strin...
class PaymentInitialized(graphene.ObjectType):
class Meta: description = ( "Server-side data generated by a payment gateway. Optional step when the " "payment provider requires an additional action to initialize payment " "session." ) gateway = graphene.String(description="ID of a payment gateway.", requi...
": root.cc_exp_month, "exp_year": root.cc_exp_year, "first_digits": root.cc_first_digits, "last_digits": root.cc_last_digits, } if not any(data.values()): return None return CreditCard(**data) class PaymentInitialized(graphene.ObjectType):
64
64
100
8
56
nguyentrung194/e-com
saleor/saleor/graphql/payment/types.py
Python
PaymentInitialized
PaymentInitialized
174
186
174
174
5927c8749a0d90af2942c747480384083be6ca24
bigcode/the-stack
train
53493fabecbcd422bb8d0123
train
class
class Payment(CountableDjangoObjectType): charge_status = PaymentChargeStatusEnum( description="Internal payment status.", required=True ) actions = graphene.List( OrderAction, description=( "List of actions that can be performed in the current state of a payment." ...
class Payment(CountableDjangoObjectType):
charge_status = PaymentChargeStatusEnum( description="Internal payment status.", required=True ) actions = graphene.List( OrderAction, description=( "List of actions that can be performed in the current state of a payment." ), required=True, ) tota...
="Card brand.", required=True) first_digits = graphene.String( description="First 4 digits of the card number.", required=False ) last_digits = graphene.String( description="Last 4 digits of the card number.", required=True ) exp_month = graphene.Int( description=("Two-digit ...
209
209
697
10
199
nguyentrung194/e-com
saleor/saleor/graphql/payment/types.py
Python
Payment
Payment
69
171
69
69
071257b9cba029bc26f368aae27a0747f7d192dc
bigcode/the-stack
train
11265cc3e48c2a0b9c8fa54f
train
class
class HTTPRequest(object): """Mimics httpserver.HTTPRequest for WSGI applications.""" def __init__(self, environ): """Parses the given WSGI environ to construct the request.""" self.method = environ["REQUEST_METHOD"] self.path = urllib.quote(environ.get("SCRIPT_NAME", "")) self.p...
class HTTPRequest(object):
"""Mimics httpserver.HTTPRequest for WSGI applications.""" def __init__(self, environ): """Parses the given WSGI environ to construct the request.""" self.method = environ["REQUEST_METHOD"] self.path = urllib.quote(environ.get("SCRIPT_NAME", "")) self.path += urllib.quote(environ...
WSGIContainer for details and documentation. """ import cgi import cStringIO import escape import httplib import httputil import logging import sys import time import urllib import web class WSGIApplication(web.Application): """A WSGI-equivalent of web.Application. We support the same interface, but handler...
256
256
947
5
250
dpnova/tornado
tornado/wsgi.py
Python
HTTPRequest
HTTPRequest
87
189
87
87
d2b9aeb882a2a42a7e2ede66c099860c40f622cd
bigcode/the-stack
train
93cb4dd3c2d82c7d2d99cada
train
class
class WSGIApplication(web.Application): """A WSGI-equivalent of web.Application. We support the same interface, but handlers running in a WSGIApplication do not support flush() or asynchronous methods. """ def __init__(self, handlers=None, default_host="", **settings): web.Application.__ini...
class WSGIApplication(web.Application):
"""A WSGI-equivalent of web.Application. We support the same interface, but handlers running in a WSGIApplication do not support flush() or asynchronous methods. """ def __init__(self, handlers=None, default_host="", **settings): web.Application.__init__(self, handlers, default_host, transf...
ado HTTP server and I/O loop. See WSGIContainer for details and documentation. """ import cgi import cStringIO import escape import httplib import httputil import logging import sys import time import urllib import web class WSGIApplication(web.Application):
64
64
204
8
55
dpnova/tornado
tornado/wsgi.py
Python
WSGIApplication
WSGIApplication
64
84
64
64
3bb0d40617d317d1ed45964dd765a35c4d89ae79
bigcode/the-stack
train
a5f3220591c6b46ba67ec729
train
class
class WSGIContainer(object): """Makes a WSGI-compatible function runnable on Tornado's HTTP server. Wrap a WSGI function in a WSGIContainer and pass it to HTTPServer to run it. For example: def simple_app(environ, start_response): status = "200 OK" response_headers = [("Con...
class WSGIContainer(object):
"""Makes a WSGI-compatible function runnable on Tornado's HTTP server. Wrap a WSGI function in a WSGIContainer and pass it to HTTPServer to run it. For example: def simple_app(environ, start_response): status = "200 OK" response_headers = [("Content-type", "text/plain")] ...
continue eoh = part.find("\r\n\r\n") if eoh == -1: logging.warning("multipart/form-data missing headers") continue headers = httputil.HTTPHeaders.parse(part[:eoh]) name_header = headers.get("Content-Disposition", "") if not nam...
256
256
929
7
249
dpnova/tornado
tornado/wsgi.py
Python
WSGIContainer
WSGIContainer
192
295
192
192
e49fe27bd202378108ed0b1cda5b2f9d09859497
bigcode/the-stack
train
10b0952c373fc710c9809942
train
function
def update_odd_even_labels(labels): # odd = 0 # even = 1 for idx, label in enumerate(labels): labels[idx] = np.where(label%2 == 0, 1, 0) return labels
def update_odd_even_labels(labels): # odd = 0 # even = 1
for idx, label in enumerate(labels): labels[idx] = np.where(label%2 == 0, 1, 0) return labels
", 'running_logs.log'), level=logging.INFO, format="[%(asctime)s: %(levelname)s: %(module)s]: %(message)s", filemode="a" ) def update_odd_even_labels(labels): # odd = 0 # even = 1
64
64
55
22
42
abidghias/TransferLearning
src/transfer_learning.py
Python
update_odd_even_labels
update_odd_even_labels
17
22
17
19
bdb1a2545ef86a4b35f7095ea685a7d7dcfe0139
bigcode/the-stack
train
6b6afa662cd2f60c5a18ba8b
train
function
def main(config_path): ## read config files config = read_yaml(config_path) ## load base model - base_model_path = os.path.join("artifacts", "models", "base_model.h5") base_model = tf.keras.models.load_model(base_model_path) base_model.summary() # freeze weights for layer in base_m...
def main(config_path): ## read config files
config = read_yaml(config_path) ## load base model - base_model_path = os.path.join("artifacts", "models", "base_model.h5") base_model = tf.keras.models.load_model(base_model_path) base_model.summary() # freeze weights for layer in base_model.layers[: -1]: print(f"before freezi...
## <<< change stage name logging.basicConfig( filename=os.path.join("logs", 'running_logs.log'), level=logging.INFO, format="[%(asctime)s: %(levelname)s: %(module)s]: %(message)s", filemode="a" ) def update_odd_even_labels(labels): # odd = 0 # even = 1 for idx, label in enumerate(l...
125
125
418
11
113
abidghias/TransferLearning
src/transfer_learning.py
Python
main
main
24
68
24
25
7e0ba212a0a152f7577721158411d72ca476eda9
bigcode/the-stack
train
0e9ead5ef441a661bfb6de7e
train
function
def _tx_resource_for_name(name): """ Return the Transifex resource name """ if name == 'core': return "django.core" else: return "django.contrib-%s" % name
def _tx_resource_for_name(name):
""" Return the Transifex resource name """ if name == 'core': return "django.core" else: return "django.contrib-%s" % name
ld[0] in resources] if len(resources) > len(dirs): print("You have specified some unknown resources. " "Available resource names are: %s" % (', '.join(res_names),)) exit(1) return dirs def _tx_resource_for_name(name):
64
64
45
8
55
pierrevaliorgue/ubiquitous-octo-parakeet
scripts/manage_translations.py
Python
_tx_resource_for_name
_tx_resource_for_name
62
67
62
62
912a5085c5fe1e3af9207e3fcc42f2f863f372b4
bigcode/the-stack
train
60873044470f4dfb3458e0b6
train
function
def lang_stats(resources=None, languages=None): """ Output language statistics of committed translation files for each Django catalog. If resources is provided, it should be a list of translation resource to limit the output (e.g. ['core', 'gis']). """ locale_dirs = _get_locale_dirs(resource...
def lang_stats(resources=None, languages=None):
""" Output language statistics of committed translation files for each Django catalog. If resources is provided, it should be a list of translation resource to limit the output (e.g. ['core', 'gis']). """ locale_dirs = _get_locale_dirs(resources) for name, dir_ in locale_dirs: p...
emessages', locale=['en']) print("Updating en JS catalogs for Django and contrib apps...") call_command('makemessages', locale=['en'], domain='djangojs') # Output changed stats _check_diff('core', os.path.join(os.getcwd(), 'conf', 'locale')) for name, dir_ in contrib_dirs: _check_diff(name,...
89
90
302
9
80
pierrevaliorgue/ubiquitous-octo-parakeet
scripts/manage_translations.py
Python
lang_stats
lang_stats
106
136
106
106
a27dd36d35dabd7ce97196b1aca71c669cbf5cff
bigcode/the-stack
train
450bb77cf9c0c12c5da7da5a
train
function
def _check_diff(cat_name, base_path): """ Output the approximate number of changed/added strings in the en catalog. """ po_path = '%(path)s/en/LC_MESSAGES/django%(ext)s.po' % { 'path': base_path, 'ext': 'js' if cat_name.endswith('-js') else ''} p = Popen("git diff -U0 %s | egrep '^[-+]msgid'...
def _check_diff(cat_name, base_path):
""" Output the approximate number of changed/added strings in the en catalog. """ po_path = '%(path)s/en/LC_MESSAGES/django%(ext)s.po' % { 'path': base_path, 'ext': 'js' if cat_name.endswith('-js') else ''} p = Popen("git diff -U0 %s | egrep '^[-+]msgid' | wc -l" % po_path, std...
exit(1) return dirs def _tx_resource_for_name(name): """ Return the Transifex resource name """ if name == 'core': return "django.core" else: return "django.contrib-%s" % name def _check_diff(cat_name, base_path):
64
64
154
10
53
pierrevaliorgue/ubiquitous-octo-parakeet
scripts/manage_translations.py
Python
_check_diff
_check_diff
70
80
70
70
bf9a896decd1d1347256b4c1bbdcef308c270e3e
bigcode/the-stack
train
89f4bbc61a680a4d34888df2
train
function
def fetch(resources=None, languages=None): """ Fetch translations from Transifex, wrap long lines, generate mo files. """ locale_dirs = _get_locale_dirs(resources) errors = [] for name, dir_ in locale_dirs: # Transifex pull if languages is None: call('tx pull -r %(re...
def fetch(resources=None, languages=None):
""" Fetch translations from Transifex, wrap long lines, generate mo files. """ locale_dirs = _get_locale_dirs(resources) errors = [] for name, dir_ in locale_dirs: # Transifex pull if languages is None: call('tx pull -r %(res)s -a -f --minimum-perc=5' % {'res': _tx_...
= Popen( ['msgfmt', '-vc', '-o', '/dev/null', po_path], stdout=PIPE, stderr=PIPE, env={'LANG': 'C'} ) output, errors = p.communicate() if p.returncode == 0: # msgfmt output stats on stderr print("%s: %s"...
123
124
414
8
115
pierrevaliorgue/ubiquitous-octo-parakeet
scripts/manage_translations.py
Python
fetch
fetch
139
173
139
139
c7b5f3ec0e576936178b39b7d50aff5988a9a413
bigcode/the-stack
train
38249516bb52ce7f327f7564
train
function
def _get_locale_dirs(resources, include_core=True): """ Return a tuple (contrib name, absolute path) for all locale directories, optionally including the django core catalog. If resources list is not None, filter directories matching resources content. """ contrib_dir = os.path.join(os.getcwd(),...
def _get_locale_dirs(resources, include_core=True):
""" Return a tuple (contrib name, absolute path) for all locale directories, optionally including the django core catalog. If resources list is not None, filter directories matching resources content. """ contrib_dir = os.path.join(os.getcwd(), 'django', 'contrib') dirs = [] # Collect a...
Spanish in contrib.admin, run: # # $ python scripts/manage_translations.py lang_stats --language=es --resources=admin import os from argparse import ArgumentParser from subprocess import PIPE, Popen, call import django from django.conf import settings from django.core.management import call_command HAVE_JS = ['adm...
82
82
274
11
71
pierrevaliorgue/ubiquitous-octo-parakeet
scripts/manage_translations.py
Python
_get_locale_dirs
_get_locale_dirs
32
59
32
32
48f15ae8250a7733937ac0669f6a696ad74d4568
bigcode/the-stack
train
bec1cc576349008a95e0bfcb
train
function
def update_catalogs(resources=None, languages=None): """ Update the en/LC_MESSAGES/django.po (main and contrib) files with new/updated translatable strings. """ settings.configure() django.setup() if resources is not None: print("`update_catalogs` will always process all resources.")...
def update_catalogs(resources=None, languages=None):
""" Update the en/LC_MESSAGES/django.po (main and contrib) files with new/updated translatable strings. """ settings.configure() django.setup() if resources is not None: print("`update_catalogs` will always process all resources.") contrib_dirs = _get_locale_dirs(None, include_co...
po_path, stdout=PIPE, stderr=PIPE, shell=True) output, errors = p.communicate() num_changes = int(output.strip()) print("%d changed/added messages in '%s' catalog." % (num_changes, cat_name)) def update_catalogs(resources=None, languages=None):
64
64
192
10
54
pierrevaliorgue/ubiquitous-octo-parakeet
scripts/manage_translations.py
Python
update_catalogs
update_catalogs
83
103
83
83
c7db770f91fe73f559e3f5c86908cafa2aba2586
bigcode/the-stack
train
2a6158cd1b1b87127933ddd7
train
class
@pytest.mark.usefixtures('db') class TestUser: """User tests.""" def test_get_by_id(self): """Get user by ID.""" user = User('foo', 'foo@bar.com') user.save() retrieved = User.get_by_id(user.id) assert retrieved == user def test_created_at_defaults_to_datetime(self...
@pytest.mark.usefixtures('db') class TestUser:
"""User tests.""" def test_get_by_id(self): """Get user by ID.""" user = User('foo', 'foo@bar.com') user.save() retrieved = User.get_by_id(user.id) assert retrieved == user def test_created_at_defaults_to_datetime(self): """Test creation date.""" us...
# -*- coding: utf-8 -*- """Model unit tests.""" import datetime as dt import pytest from jwt_geo.user.models import Role, User from .factories import UserFactory @pytest.mark.usefixtures('db') class TestUser:
50
115
384
11
38
samakshjain/vokal
tests/test_models.py
Python
TestUser
TestUser
12
67
12
13
4d60d1547f4d1dbe60c1a8b3c645678ee2935c4e
bigcode/the-stack
train
6b9115eccd59082dd2f00acb
train
function
def to_environ_key(key): return key.upper()
def to_environ_key(key):
return key.upper()
from __future__ import absolute_import, division import configparser from os import environ from os.path import abspath, dirname, join def to_environ_key(key):
37
64
12
7
29
BHAR-HumanActivity/B-HAR
b_har/utility/configurator.py
Python
to_environ_key
to_environ_key
7
8
7
7
fe898a5b50e906a62c64f077cfc2af2560b10df7
bigcode/the-stack
train
3c40fc5a2ef7b756ef3cea3a
train
function
def get_config_path(): """ Get absolute path to the config file """ current_path = abspath(dirname(__file__)) conf_path = join(current_path, 'etc/Public/config.cfg') if conf_path: return conf_path print("Config file not found")
def get_config_path():
""" Get absolute path to the config file """ current_path = abspath(dirname(__file__)) conf_path = join(current_path, 'etc/Public/config.cfg') if conf_path: return conf_path print("Config file not found")
_config_path(): """ Get absolute path to the private config file """ current_path = abspath(dirname(__file__)) conf_path = join(current_path, 'private_config.cfg') if conf_path: return conf_path print("Private config file not found") def get_config_path():
64
64
60
5
59
BHAR-HumanActivity/B-HAR
b_har/utility/configurator.py
Python
get_config_path
get_config_path
82
92
82
82
405868928a76350f08d889a45c56ab9eeaf61cbc
bigcode/the-stack
train
ae7c16b864521b66f9a87294
train
class
class EnvironmentConfigParser(configparser.ConfigParser): """ ConfigParser with additional option to read from environment variables """ def has_option(self, section, option): if to_environ_key('_'.join((section, option))) in environ: return True return super(EnvironmentConfi...
class EnvironmentConfigParser(configparser.ConfigParser):
""" ConfigParser with additional option to read from environment variables """ def has_option(self, section, option): if to_environ_key('_'.join((section, option))) in environ: return True return super(EnvironmentConfigParser, self).has_option(section, option) def get(se...
if Configurator.__instance is None: Configurator.__instance = object.__new__(EnvironmentConfigParser) Configurator.__instance.__init__(interpolation=configparser.ExtendedInterpolation()) Configurator.__instance.read(cfg_path) return Configurator.__instance class Envir...
64
64
133
9
54
BHAR-HumanActivity/B-HAR
b_har/utility/configurator.py
Python
EnvironmentConfigParser
EnvironmentConfigParser
40
53
40
40
10790ac0c15544e5801d1a204f53a68e2d1d4b24
bigcode/the-stack
train
5702c78ff48f39a9de10703d
train
function
def readConfigFile(cfgfile): """ Read config files and return ConfigParser object @param cfgfile: filename or array of filenames @return: ConfigParser object """ parser = EnvironmentConfigParser( interpolation=configparser.ExtendedInterpolation()) parser.read(cfgfile) return par...
def readConfigFile(cfgfile):
""" Read config files and return ConfigParser object @param cfgfile: filename or array of filenames @return: ConfigParser object """ parser = EnvironmentConfigParser( interpolation=configparser.ExtendedInterpolation()) parser.read(cfgfile) return parser
section, option, raw=False, **kwargs): key = to_environ_key('_'.join((section, option))) if key in environ: return environ[key] return super(EnvironmentConfigParser, self).get(section, option, raw=raw, **kwargs) def readConfigFile(cfgfile):
64
64
66
7
57
BHAR-HumanActivity/B-HAR
b_har/utility/configurator.py
Python
readConfigFile
readConfigFile
56
66
56
56
5845e85abf88841a1f6d4aa8462f85c3a71013e6
bigcode/the-stack
train