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
4b45112ff7c07b836c648916
train
function
@app.route('/predict',methods=['POST']) def predict(): global CURR_MODEL, CURR_MODEL_KEYWORD, TOPK if request.method == 'POST': print("#################") print(request.form) print(request.form.keys()) message = request.form['hidden-message'] message = message.strip("\n").strip("\r") if message==...
@app.route('/predict',methods=['POST']) def predict():
global CURR_MODEL, CURR_MODEL_KEYWORD, TOPK if request.method == 'POST': print("#################") print(request.form) print(request.form.keys()) message = request.form['hidden-message'] message = message.strip("\n").strip("\r") if message=="": return render_template('loaded.html') if TOPK...
.route('/loaded',methods=['POST']) def loaded(): global CURR_MODEL_KEYWORD, CURR_MODEL print(request.form) print(request.form["checkers"]) CURR_MODEL_KEYWORD = request.form["checkers"] CURR_MODEL = load_model(CURR_MODEL_KEYWORD) return render_template('loaded.html') @app.route('/reset',methods=['POST'])...
99
99
330
12
87
suryabulusu/neuspell
neuspell/flask-server/app.py
Python
predict
predict
56
81
56
57
3bc370201e94a24452465beb29895bec09b6524d
bigcode/the-stack
train
7bbc2e88d27a2d273d88abe1
train
function
@app.route('/loaded',methods=['POST']) def loaded(): global CURR_MODEL_KEYWORD, CURR_MODEL print(request.form) print(request.form["checkers"]) CURR_MODEL_KEYWORD = request.form["checkers"] CURR_MODEL = load_model(CURR_MODEL_KEYWORD) return render_template('loaded.html')
@app.route('/loaded',methods=['POST']) def loaded():
global CURR_MODEL_KEYWORD, CURR_MODEL print(request.form) print(request.form["checkers"]) CURR_MODEL_KEYWORD = request.form["checkers"] CURR_MODEL = load_model(CURR_MODEL_KEYWORD) return render_template('loaded.html')
# Define the app app = Flask(__name__) CORS(app) # needed for cross-domain requests, allow everything by default @app.route('/') @app.route('/home', methods=['POST']) def home(): return render_template('home.html') @app.route('/loaded',methods=['POST']) def loaded():
64
64
69
12
52
suryabulusu/neuspell
neuspell/flask-server/app.py
Python
loaded
loaded
43
50
43
44
d7da2b2a6745373602e43d6cebead8861005fbf0
bigcode/the-stack
train
96b29163d4b251ee995d289a
train
function
@app.route('/reset',methods=['POST']) def reset(): return render_template('loaded.html')
@app.route('/reset',methods=['POST']) def reset():
return render_template('loaded.html')
WORD, CURR_MODEL print(request.form) print(request.form["checkers"]) CURR_MODEL_KEYWORD = request.form["checkers"] CURR_MODEL = load_model(CURR_MODEL_KEYWORD) return render_template('loaded.html') @app.route('/reset',methods=['POST']) def reset():
64
64
19
12
52
suryabulusu/neuspell
neuspell/flask-server/app.py
Python
reset
reset
52
54
52
53
4dd10803a56550d06e8a3b6f98cfa369fd12ef0a
bigcode/the-stack
train
cb1ef7125bc1dcc2f68dc7ba
train
function
def preload_models(): print("pre-loading models") global PRELOADED_MODELS PRELOADED_MODELS = { # "aspell": CorrectorAspell(), # "jamspell": CorrectorJamspell(), # "cnn-rnn": CorrectorCnnLstm(pretrained=True), "sc-rnn": CorrectorSCLstm(tokenize=TOKENIZE, pretrained=True), # "nested-rnn": CorrectorL...
def preload_models():
print("pre-loading models") global PRELOADED_MODELS PRELOADED_MODELS = { # "aspell": CorrectorAspell(), # "jamspell": CorrectorJamspell(), # "cnn-rnn": CorrectorCnnLstm(pretrained=True), "sc-rnn": CorrectorSCLstm(tokenize=TOKENIZE, pretrained=True), # "nested-rnn": CorrectorLstmLstm(pretrained=True...
tsc-rnn": return CorrectorBertSCLstm(tokenize=TOKENIZE, pretrained=True) elif model_keyword=="scrnn-bert": return CorrectorSCLstmBert(tokenize=TOKENIZE, pretrained=True) else: raise NotImplementedError(f"unknown model_keyword: {model_keyword}") return def preload_models():
73
73
245
4
68
suryabulusu/neuspell
neuspell/flask-server/app.py
Python
preload_models
preload_models
112
131
112
112
f041954b96ad4a0fcfdaee4d341631b10f8c96dd
bigcode/the-stack
train
b057a39cccbc845ff901d8eb
train
class
class IndexableTable(Table): default_index_fields = [] def __init__( self, storage: Storage, name: str, cache_size: int = Table.default_query_cache_capacity, # index_fields: List[str] = default_index_fields, ): # print(self.default_index_fields) # ...
class IndexableTable(Table):
default_index_fields = [] def __init__( self, storage: Storage, name: str, cache_size: int = Table.default_query_cache_capacity, # index_fields: List[str] = default_index_fields, ): # print(self.default_index_fields) # print(index_fields) super(...
from tinydb.table import Table, Document from tinydb.storages import Storage from tinydb.queries import Query # from sortedcollection import SortedCollection from sortedcontainers import SortedKeyList from typing import ( Callable, Dict, Iterable, Iterator, List, Mapping, Optional, Unio...
81
256
1,946
7
74
dcflachs/tinydb-smartindex
index_table.py
Python
IndexableTable
IndexableTable
19
291
19
20
2654b74fb6a5770f89019bf58eded040ab5496ea
bigcode/the-stack
train
6cec53c366491be579a8b27d
train
class
@method_decorator(login_required, name="dispatch") class EventCreate(CreateView): """ View used by organizers and facilitators """ model = Event form_class = EventForm success_url = reverse_lazy('studygroups_facilitator') def get_context_data(self, **kwargs): context = super().get_context_d...
@method_decorator(login_required, name="dispatch") class EventCreate(CreateView):
""" View used by organizers and facilitators """ model = Event form_class = EventForm success_url = reverse_lazy('studygroups_facilitator') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context def form_valid(self, form): self...
_ from django import http from .models import Event from .forms import EventForm from .forms import EventModerateForm from .decorators import user_owns_event from .tasks import send_new_event_notification @method_decorator(login_required, name="dispatch") class EventCreate(CreateView):
64
64
164
17
46
p2pu/learning-circles
community_calendar/views.py
Python
EventCreate
EventCreate
21
40
21
22
edaabfacaa1fa8328e488125b45a220c89bca3ef
bigcode/the-stack
train
85275cae83d33d1f627de875
train
class
@method_decorator(event_edit_decorators, name="dispatch") class EventDelete(DeleteView): model = Event success_url = reverse_lazy('studygroups_facilitator') def delete(self, request, *args, **kwargs): messages.success(self.request, _('Your event has been deleted.')) return super().delete(re...
@method_decorator(event_edit_decorators, name="dispatch") class EventDelete(DeleteView):
model = Event success_url = reverse_lazy('studygroups_facilitator') def delete(self, request, *args, **kwargs): messages.success(self.request, _('Your event has been deleted.')) return super().delete(request, *args, **kwargs)
success_url = reverse_lazy('studygroups_facilitator') def form_valid(self, form): messages.success(self.request, _('Your event has been updated.')) return super().form_valid(form) @method_decorator(event_edit_decorators, name="dispatch") class EventDelete(DeleteView):
64
64
79
20
44
p2pu/learning-circles
community_calendar/views.py
Python
EventDelete
EventDelete
55
62
55
56
4e914ca939fb71a4865e07b1eef7564ef6162898
bigcode/the-stack
train
0b2c51f80403d44e4eb371d6
train
class
@method_decorator(event_edit_decorators, name="dispatch") class EventUpdate(UpdateView): model = Event form_class = EventForm success_url = reverse_lazy('studygroups_facilitator') def form_valid(self, form): messages.success(self.request, _('Your event has been updated.')) return super(...
@method_decorator(event_edit_decorators, name="dispatch") class EventUpdate(UpdateView):
model = Event form_class = EventForm success_url = reverse_lazy('studygroups_facilitator') def form_valid(self, form): messages.success(self.request, _('Your event has been updated.')) return super().form_valid(form)
.delay(self.object) messages.success(self.request, _('Your event has been added.')) return http.HttpResponseRedirect(self.get_success_url()) event_edit_decorators = [login_required, user_owns_event] @method_decorator(event_edit_decorators, name="dispatch") class EventUpdate(UpdateView):
64
64
76
20
44
p2pu/learning-circles
community_calendar/views.py
Python
EventUpdate
EventUpdate
44
52
44
45
8438d4b68254bd43f74fbb7bca4a72f3bdab1c54
bigcode/the-stack
train
2ff5f5bd5a84bd7e578a7b79
train
class
@method_decorator(login_required, name="dispatch") class EventModerate(UpdateView): model = Event form_class = EventModerateForm success_url = reverse_lazy('studygroups_facilitator') template_name = 'community_calendar/event_moderate.html' def dispatch(self, request, *args, **kwargs): if no...
@method_decorator(login_required, name="dispatch") class EventModerate(UpdateView):
model = Event form_class = EventModerateForm success_url = reverse_lazy('studygroups_facilitator') template_name = 'community_calendar/event_moderate.html' def dispatch(self, request, *args, **kwargs): if not request.user.is_staff : raise PermissionDenied return super()....
ygroups_facilitator') def delete(self, request, *args, **kwargs): messages.success(self.request, _('Your event has been deleted.')) return super().delete(request, *args, **kwargs) @method_decorator(login_required, name="dispatch") class EventModerate(UpdateView):
64
64
154
18
46
p2pu/learning-circles
community_calendar/views.py
Python
EventModerate
EventModerate
65
82
65
66
7edbb9dcb7156ffd7aa701dda22fae7c66a64871
bigcode/the-stack
train
a52652dd94b34ec40ea9ee6a
train
function
async def has_role(message, role_name): return message.author in get_role(message.guild, role_name).members
async def has_role(message, role_name):
return message.author in get_role(message.guild, role_name).members
}") if user in role.members: await user.remove_roles(role) await ctx.send(notices[1]) # role removed notice else: await user.add_roles(role) await ctx.send(notices[0]) # role added notice async def has_role(message, role_name):
64
64
24
9
54
lewdrops/neetbot
src/utils.py
Python
has_role
has_role
40
41
40
40
7d604e176ee0194af9223afa25f72c81ca47f786
bigcode/the-stack
train
8245f65fd7b610c2b8cc3b97
train
function
def msg_to_member(message): name = message.content[message.content.index(' ') + 1:] target = message.guild.get_member_named(name) return target
def msg_to_member(message):
name = message.content[message.content.index(' ') + 1:] target = message.guild.get_member_named(name) return target
import asyncio import discord def msg_to_member(message):
12
64
35
6
5
lewdrops/neetbot
src/utils.py
Python
msg_to_member
msg_to_member
6
9
6
6
6a86305b40c92140d079495a45fb80e3e9095bd2
bigcode/the-stack
train
3b82ef93f938f473c5d135d5
train
function
async def create_roles_if_needed(guild, *role_names): for name in role_names: if not get_role(guild, name): await guild.create_role(name=name) print(f"created role '{name}' in {guild}")
async def create_roles_if_needed(guild, *role_names):
for name in role_names: if not get_role(guild, name): await guild.create_role(name=name) print(f"created role '{name}' in {guild}")
(name) return target def get_role(guild, role_name): # print("---", isinstance(ctx, discord.message.Message)) """returns None if server doesn't have role""" return discord.utils.get(guild.roles, name=role_name) async def create_roles_if_needed(guild, *role_names):
64
64
51
13
51
lewdrops/neetbot
src/utils.py
Python
create_roles_if_needed
create_roles_if_needed
18
22
18
18
fd49f019c7745e14c031fcf0c3cb1686a9db547f
bigcode/the-stack
train
59ae99a15d3caac43d36cbb4
train
function
async def toggle_role_for(ctx, role_name, notices=(None, None)): user = ctx.message.author role = get_role(ctx.guild, role_name) if notices == (None, None): notices = (f"{role_name} added to {user}", f"{role_name} removed from {user}") if user in role.members: await user.remove_roles(r...
async def toggle_role_for(ctx, role_name, notices=(None, None)):
user = ctx.message.author role = get_role(ctx.guild, role_name) if notices == (None, None): notices = (f"{role_name} added to {user}", f"{role_name} removed from {user}") if user in role.members: await user.remove_roles(role) await ctx.send(notices[1]) # role removed notice ...
_if_needed(guild, *role_names): for name in role_names: if not get_role(guild, name): await guild.create_role(name=name) print(f"created role '{name}' in {guild}") async def toggle_role_for(ctx, role_name, notices=(None, None)):
63
64
121
16
47
lewdrops/neetbot
src/utils.py
Python
toggle_role_for
toggle_role_for
25
37
25
25
14ce5dbb793f06d4bdff429e74c97fa7fc79f910
bigcode/the-stack
train
f7db65c5ef80ef169d7c14b8
train
function
def get_role(guild, role_name): # print("---", isinstance(ctx, discord.message.Message)) """returns None if server doesn't have role""" return discord.utils.get(guild.roles, name=role_name)
def get_role(guild, role_name): # print("---", isinstance(ctx, discord.message.Message))
"""returns None if server doesn't have role""" return discord.utils.get(guild.roles, name=role_name)
import asyncio import discord def msg_to_member(message): name = message.content[message.content.index(' ') + 1:] target = message.guild.get_member_named(name) return target def get_role(guild, role_name): # print("---", isinstance(ctx, discord.message.Message))
62
64
45
21
40
lewdrops/neetbot
src/utils.py
Python
get_role
get_role
12
15
12
13
37f8f4ce593f144cadcfb61efef303e6b168c8ee
bigcode/the-stack
train
43761ea61ac75797dd61c414
train
function
def after_space(S): return S[S.index(' ')+1:]
def after_space(S):
return S[S.index(' ')+1:]
ices[1]) # role removed notice else: await user.add_roles(role) await ctx.send(notices[0]) # role added notice async def has_role(message, role_name): return message.author in get_role(message.guild, role_name).members def after_space(S):
64
64
15
5
58
lewdrops/neetbot
src/utils.py
Python
after_space
after_space
44
45
44
44
ec8e431200268766b64aebfb5e79116aa72bf74c
bigcode/the-stack
train
834da7d53cbbc34ec80403a3
train
class
class IgmpMldRange(Base): """ The IgmpMldRange class encapsulates a list of igmpMldRange resources that are managed by the user. A list of resources can be retrieved from the server using the IgmpMldRange.find() method. The list can be managed by using the IgmpMldRange.add() and IgmpMldRange.remove() me...
class IgmpMldRange(Base):
""" The IgmpMldRange class encapsulates a list of igmpMldRange resources that are managed by the user. A list of resources can be retrieved from the server using the IgmpMldRange.find() method. The list can be managed by using the IgmpMldRange.add() and IgmpMldRange.remove() methods. """ __slot...
ight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or se...
256
256
12,364
8
247
OpenIxia/ixnetwork_restpy
ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocolstack/igmpmldrange_3a80161aa7685feb09f160c6fce9f43e.py
Python
IgmpMldRange
IgmpMldRange
27
559
27
27
758a9f7549f7fac2c2ee6ab1bedbb1b2c401b6a7
bigcode/the-stack
train
950feafdc9c9348bcbb183c4
train
function
def _make_200(content): response = _make_http_response(200) response._content = content return response
def _make_200(content):
response = _make_http_response(200) response._content = content return response
r.test_lib import test_lib def _make_http_response(code=200): """A helper for creating HTTP responses.""" response = requests.Response() response.status_code = code return response def _make_404(): return _make_http_response(404) def _make_200(content):
64
64
28
7
57
4ndygu/grr
grr/client/grr_response_client/comms_test.py
Python
_make_200
_make_200
35
38
35
35
7888fe111987385d1ac3e2295783685de598bdb9
bigcode/the-stack
train
100cea2fbadeef1698001032
train
class
class URLFilter(RequestsInstrumentor): """Emulate only a single server url that works.""" def request(self, url=None, **kwargs): # If request is from server2 - return a valid response. Assume, server2 is # reachable from all proxies. response = super(URLFilter, self).request(url=url, **kwargs) if "...
class URLFilter(RequestsInstrumentor):
"""Emulate only a single server url that works.""" def request(self, url=None, **kwargs): # If request is from server2 - return a valid response. Assume, server2 is # reachable from all proxies. response = super(URLFilter, self).request(url=url, **kwargs) if "server2" in url: return _make_200...
instrument(self): """Install the mocks required. Returns: A context manager that when exits restores the mocks. """ self.actions = [] return utils.MultiStubber((requests, "request", self.request), (time, "sleep", self.sleep)) class URLFilter(RequestsInstrumento...
64
64
96
8
56
4ndygu/grr
grr/client/grr_response_client/comms_test.py
Python
URLFilter
URLFilter
77
86
77
77
e6a82c850f0ef61facf1a44f77ed54c789882fcd
bigcode/the-stack
train
9cfec1e7986f129504ef12cd
train
class
class SizeLimitedQueueTest(test_lib.GRRBaseTest): def testSizeLimitedQueue(self): limited_queue = comms.SizeLimitedQueue( maxsize=10000000, heart_beat_cb=lambda: None) msg_a = rdf_flows.GrrMessage(name="A") msg_b = rdf_flows.GrrMessage(name="B") msg_c = rdf_flows.GrrMessage(name="C") f...
class SizeLimitedQueueTest(test_lib.GRRBaseTest):
def testSizeLimitedQueue(self): limited_queue = comms.SizeLimitedQueue( maxsize=10000000, heart_beat_cb=lambda: None) msg_a = rdf_flows.GrrMessage(name="A") msg_b = rdf_flows.GrrMessage(name="B") msg_c = rdf_flows.GrrMessage(name="C") for _ in range(10): limited_queue.Put(msg_a) ...
to commence enrollment workflow. """ instrumentor = RequestsInstrumentor() instrumentor.responses = [_make_http_response(code=406)] manager = MockHTTPManager() with instrumentor.instrument(): # First request - should raise a 406 error. result = manager.OpenServerEndpoint("control")...
243
243
812
12
231
4ndygu/grr
grr/client/grr_response_client/comms_test.py
Python
SizeLimitedQueueTest
SizeLimitedQueueTest
249
349
249
250
4187eab52d5e9a16b9535778aada85782b20eda8
bigcode/the-stack
train
a0aef23414f976da82f02c1a
train
class
class GRRClientWorkerTest(test_lib.GRRBaseTest): """Tests the GRRClientWorker class.""" def setUp(self): super(GRRClientWorkerTest, self).setUp() # GRRClientWorker starts a stats collector thread that will send replies # shortly after starting up. Those replies interfere with the test below so # we...
class GRRClientWorkerTest(test_lib.GRRBaseTest):
"""Tests the GRRClientWorker class.""" def setUp(self): super(GRRClientWorkerTest, self).setUp() # GRRClientWorker starts a stats collector thread that will send replies # shortly after starting up. Those replies interfere with the test below so # we disable the ClientStatsCollector thread here. ...
String()), heart_beat_cb=heartbeat) limited_queue.Put(msg_a) limited_queue.Put(msg_b) limited_queue.Put(msg_c) with self.assertRaises(queue.Full): limited_queue.Put(msg_d, timeout=1) self.assertTrue(heartbeat.called) class GRRClientWorkerTest(test_lib.GRRBaseTest):
70
70
236
13
57
4ndygu/grr
grr/client/grr_response_client/comms_test.py
Python
GRRClientWorkerTest
GRRClientWorkerTest
352
373
352
352
3ef729d759df17167c4ce78ff30dfc08cf331089
bigcode/the-stack
train
01f6aae713be419b16a3fb58
train
class
class RequestsInstrumentor(object): """Instrument the `requests` library.""" def __init__(self): self.time = 0 self.current_opener = None # Record the actions in order. self.actions = [] # These are the responses we will do. self.responses = [] def request(self, **request_options): ...
class RequestsInstrumentor(object):
"""Instrument the `requests` library.""" def __init__(self): self.time = 0 self.current_opener = None # Record the actions in order. self.actions = [] # These are the responses we will do. self.responses = [] def request(self, **request_options): self.actions.append([self.time, requ...
= requests.Response() response.status_code = code return response def _make_404(): return _make_http_response(404) def _make_200(content): response = _make_http_response(200) response._content = content return response class RequestsInstrumentor(object):
64
64
195
6
57
4ndygu/grr
grr/client/grr_response_client/comms_test.py
Python
RequestsInstrumentor
RequestsInstrumentor
41
74
41
41
799c9624a3b96a818ff17d45db70ff147bb12685
bigcode/the-stack
train
52f50c620ae2ca46e3e865e3
train
class
class MockHTTPManager(comms.HTTPManager): def _GetBaseURLs(self): return ["http://server1/", "http://server2/", "http://server3/"] def _GetProxies(self): """Do not test the proxy gathering logic itself.""" return ["proxy1", "proxy2", "proxy3"]
class MockHTTPManager(comms.HTTPManager):
def _GetBaseURLs(self): return ["http://server1/", "http://server2/", "http://server3/"] def _GetProxies(self): """Do not test the proxy gathering logic itself.""" return ["proxy1", "proxy2", "proxy3"]
a valid response. Assume, server2 is # reachable from all proxies. response = super(URLFilter, self).request(url=url, **kwargs) if "server2" in url: return _make_200("Good") return response class MockHTTPManager(comms.HTTPManager):
64
64
71
9
54
4ndygu/grr
grr/client/grr_response_client/comms_test.py
Python
MockHTTPManager
MockHTTPManager
89
96
89
90
f3c6eaeebda2b621df1b140287b97afe08539210
bigcode/the-stack
train
305cdc5eb7ca516ce888a1ea
train
class
class HTTPManagerTest(test_lib.GRRBaseTest): """Tests the HTTP Manager.""" def MakeRequest(self, instrumentor, manager, path, verify_cb=lambda x: True): with utils.MultiStubber((requests, "request", instrumentor.request), (time, "sleep", instrumentor.sleep)): return manager.Op...
class HTTPManagerTest(test_lib.GRRBaseTest):
"""Tests the HTTP Manager.""" def MakeRequest(self, instrumentor, manager, path, verify_cb=lambda x: True): with utils.MultiStubber((requests, "request", instrumentor.request), (time, "sleep", instrumentor.sleep)): return manager.OpenServerEndpoint(path, verify_cb=verify_cb) ...
return _make_404() def sleep(self, timeout): self.time += timeout def instrument(self): """Install the mocks required. Returns: A context manager that when exits restores the mocks. """ self.actions = [] return utils.MultiStubber((requests, "request", self.request), ...
255
256
1,172
11
244
4ndygu/grr
grr/client/grr_response_client/comms_test.py
Python
HTTPManagerTest
HTTPManagerTest
99
246
99
99
3afa6051ce81f33818f7b2827264bae0ae5afef6
bigcode/the-stack
train
cd92a6653204cf71b978c942
train
function
def _make_404(): return _make_http_response(404)
def _make_404():
return _make_http_response(404)
rdf_flows from grr_response_core.lib.util import compatibility from grr.test_lib import test_lib def _make_http_response(code=200): """A helper for creating HTTP responses.""" response = requests.Response() response.status_code = code return response def _make_404():
64
64
15
6
57
4ndygu/grr
grr/client/grr_response_client/comms_test.py
Python
_make_404
_make_404
31
32
31
31
2497a0eb51a6add611e84def50d5375c9d70acdc
bigcode/the-stack
train
80750b2749496a40aeb9c744
train
function
def main(argv): test_lib.main(argv)
def main(argv):
test_lib.main(argv)
) self.assertEqual(messages[0].args_rdf_name, compatibility.GetName(rdfvalue.RDFDatetime)) self.assertIsInstance(messages[0].payload, rdfvalue.RDFDatetime) self.assertEqual(messages[0].payload, rdfvalue.RDFDatetime(0)) def main(argv):
64
64
10
4
60
4ndygu/grr
grr/client/grr_response_client/comms_test.py
Python
main
main
376
377
376
376
ecd94fc80a33de9e929d8f215b77bba11a49aa84
bigcode/the-stack
train
3f80c77f09d44bf283099d11
train
function
def _make_http_response(code=200): """A helper for creating HTTP responses.""" response = requests.Response() response.status_code = code return response
def _make_http_response(code=200):
"""A helper for creating HTTP responses.""" response = requests.Response() response.status_code = code return response
flags from grr_response_core.lib import rdfvalue from grr_response_core.lib import utils from grr_response_core.lib.rdfvalues import flows as rdf_flows from grr_response_core.lib.util import compatibility from grr.test_lib import test_lib def _make_http_response(code=200):
64
64
35
9
54
4ndygu/grr
grr/client/grr_response_client/comms_test.py
Python
_make_http_response
_make_http_response
24
28
24
24
2b7daf1570b80b60010c32d23538afddde891552
bigcode/the-stack
train
f3874846e8936a7697a45141
train
function
@pytest.fixture @pytest.mark.usefixtures('isfile') def history_lines(mocker): def aux(lines): mock = mocker.patch('io.open') mock.return_value.__enter__ \ .return_value.readlines.return_value = lines return aux
@pytest.fixture @pytest.mark.usefixtures('isfile') def history_lines(mocker):
def aux(lines): mock = mocker.patch('io.open') mock.return_value.__enter__ \ .return_value.readlines.return_value = lines return aux
@pytest.fixture def builtins_open(mocker): return mocker.patch('six.moves.builtins.open') @pytest.fixture def isfile(mocker): return mocker.patch('os.path.isfile', return_value=True) @pytest.fixture @pytest.mark.usefixtures('isfile') def history_lines(mocker):
64
64
54
17
47
juzim/thefuck
tests/shells/conftest.py
Python
history_lines
history_lines
14
22
14
16
5cfe01d82f7f5a3a4e0366e8032505d3c5f36c49
bigcode/the-stack
train
60d21fe0f8086c3d1b8a2d48
train
function
@pytest.fixture def builtins_open(mocker): return mocker.patch('six.moves.builtins.open')
@pytest.fixture def builtins_open(mocker):
return mocker.patch('six.moves.builtins.open')
import pytest @pytest.fixture def builtins_open(mocker):
13
64
23
10
2
juzim/thefuck
tests/shells/conftest.py
Python
builtins_open
builtins_open
4
6
4
5
4fe62da48c7fa628a1528f0705a31649a5072d76
bigcode/the-stack
train
02eb17771de59769096eb223
train
function
@pytest.fixture def isfile(mocker): return mocker.patch('os.path.isfile', return_value=True)
@pytest.fixture def isfile(mocker):
return mocker.patch('os.path.isfile', return_value=True)
import pytest @pytest.fixture def builtins_open(mocker): return mocker.patch('six.moves.builtins.open') @pytest.fixture def isfile(mocker):
35
64
23
9
26
juzim/thefuck
tests/shells/conftest.py
Python
isfile
isfile
9
11
9
10
6164db0405b9087a6755d6f8aa1b636c4fe323cf
bigcode/the-stack
train
9d356162dd40fdd86c05f8be
train
class
class SymmetricSignatureVerifier(SignatureVerifier): """Verifier for HMAC signatures, which rely on shared secrets. Args: shared_secret (str): The shared secret used to decode the token. algorithm (str, optional): The expected signing algorithm. Defaults to "HS256". """ def __init__(se...
class SymmetricSignatureVerifier(SignatureVerifier):
"""Verifier for HMAC signatures, which rely on shared secrets. Args: shared_secret (str): The shared secret used to decode the token. algorithm (str, optional): The expected signing algorithm. Defaults to "HS256". """ def __init__(self, shared_secret, algorithm="HS256"): super(...
try: decoded = jwt.decode(jwt=token, key=secret_or_certificate, algorithms=[self._algorithm], options=self.DISABLE_JWT_CHECKS) except jwt.exceptions.InvalidSignatureError: raise TokenValidationError("Invalid token signature.") return decoded clas...
64
64
116
9
54
authok/authok-python
authok/v3/authentication/token_verifier.py
Python
SymmetricSignatureVerifier
SymmetricSignatureVerifier
80
93
80
80
932ee1a79d08d7836cb60d5811babf29f5c88e0e
bigcode/the-stack
train
40bdc0147ad40326ec64d79f
train
class
class AsymmetricSignatureVerifier(SignatureVerifier): """Verifier for RSA signatures, which rely on public key certificates. Args: jwks_url (str): The url where the JWK set is located. algorithm (str, optional): The expected signing algorithm. Defaults to "RS256". """ def __init__(self...
class AsymmetricSignatureVerifier(SignatureVerifier):
"""Verifier for RSA signatures, which rely on public key certificates. Args: jwks_url (str): The url where the JWK set is located. algorithm (str, optional): The expected signing algorithm. Defaults to "RS256". """ def __init__(self, jwks_url, algorithm="RS256"): super(Asymmetr...
def __init__(self, shared_secret, algorithm="HS256"): super(SymmetricSignatureVerifier, self).__init__(algorithm) self._shared_secret = shared_secret def _fetch_key(self, key_id=None): return self._shared_secret class AsymmetricSignatureVerifier(SignatureVerifier):
64
64
130
9
54
authok/authok-python
authok/v3/authentication/token_verifier.py
Python
AsymmetricSignatureVerifier
AsymmetricSignatureVerifier
96
109
96
96
5dad38737a2c3c5d2c1a7be468eac3e9352d1de3
bigcode/the-stack
train
ee225d4c2dd97b45031cab20
train
class
class JwksFetcher(object): """Class that fetches and holds a JSON web key set. This class makes use of an in-memory cache. For it to work properly, define this instance once and re-use it. Args: jwks_url (str): The url where the JWK set is located. cache_ttl (str, optional): The lifetime of...
class JwksFetcher(object):
"""Class that fetches and holds a JSON web key set. This class makes use of an in-memory cache. For it to work properly, define this instance once and re-use it. Args: jwks_url (str): The url where the JWK set is located. cache_ttl (str, optional): The lifetime of the JWK set cache in secon...
): The expected signing algorithm. Defaults to "HS256". """ def __init__(self, shared_secret, algorithm="HS256"): super(SymmetricSignatureVerifier, self).__init__(algorithm) self._shared_secret = shared_secret def _fetch_key(self, key_id=None): return self._shared_secret class As...
206
206
687
7
199
authok/authok-python
authok/v3/authentication/token_verifier.py
Python
JwksFetcher
JwksFetcher
112
197
112
112
fa672330566e7fe3d98488884256964e754c92ab
bigcode/the-stack
train
f12cf28cdc81e5e667600ff7
train
class
class TokenVerifier(): """Class that verifies ID tokens following the steps defined in the OpenID Connect spec. An OpenID Connect ID token is not meant to be consumed until it's verified. Args: signature_verifier (SignatureVerifier): The instance that knows how to verify the signature. issu...
class TokenVerifier():
"""Class that verifies ID tokens following the steps defined in the OpenID Connect spec. An OpenID Connect ID token is not meant to be consumed until it's verified. Args: signature_verifier (SignatureVerifier): The instance that knows how to verify the signature. issuer (str): The expected ...
def _parse_jwks(jwks): """ Converts a JWK string representation into a binary certificate in PEM format. """ keys = {} for key in jwks['keys']: # noinspection PyUnresolvedReferences # requirement already includes cryptography -> pyjwt[crypto] ...
256
256
1,530
4
252
authok/authok-python
authok/v3/authentication/token_verifier.py
Python
TokenVerifier
TokenVerifier
200
349
200
200
c353ce1eb0918b46ce50a1986c615a8ad51878d6
bigcode/the-stack
train
1ca1a33edf923ca37c456fcd
train
class
class SignatureVerifier(object): """Abstract class that will verify a given JSON web token's signature using the key fetched internally given its key id. Args: algorithm (str): The expected signing algorithm (e.g. RS256). """ DISABLE_JWT_CHECKS = { "verify_signature": True, ...
class SignatureVerifier(object):
"""Abstract class that will verify a given JSON web token's signature using the key fetched internally given its key id. Args: algorithm (str): The expected signing algorithm (e.g. RS256). """ DISABLE_JWT_CHECKS = { "verify_signature": True, "verify_exp": False, "ve...
"""Token Verifier module""" import json import time import jwt import requests from authok.v3.exceptions import TokenValidationError class SignatureVerifier(object):
34
144
482
5
28
authok/authok-python
authok/v3/authentication/token_verifier.py
Python
SignatureVerifier
SignatureVerifier
11
77
11
11
a4614abcccb67d769540896102010e4d5f4c0b21
bigcode/the-stack
train
243eeb2b84fa778738bfa767
train
function
def test_failure(database): """ Test failure AwardingOfficeCode must be submitted for new awards (ActionType = A or blank) whose ActionDate is on or after October 1, 2018, and whose CorrectionDeleteIndicator is either Blank or C. """ det_award_1 = DetachedAwardFinancialAssistanceFactory(awarding_of...
def test_failure(database):
""" Test failure AwardingOfficeCode must be submitted for new awards (ActionType = A or blank) whose ActionDate is on or after October 1, 2018, and whose CorrectionDeleteIndicator is either Blank or C. """ det_award_1 = DetachedAwardFinancialAssistanceFactory(awarding_office_code='', action_type='A...
', correction_delete_indicatr='D') errors = number_of_errors(_FILE, database, models=[det_award_1, det_award_2, det_award_3, det_award_4, det_award_5]) assert errors == 0 def test_failure(database):
64
64
175
5
58
brianherman/data-act-broker-backend
tests/unit/dataactvalidator/test_fabs38_detached_award_financial_assistance_3.py
Python
test_failure
test_failure
40
50
40
40
e7ebd9ba0277850654f19690738800ba032143c0
bigcode/the-stack
train
1337dd1c5fa1c75864683449
train
function
def test_success(database): """ Test AwardingOfficeCode must be submitted for new awards (ActionType = A or blank) whose ActionDate is on or after October 1, 2018, and whose CorrectionDeleteIndicator is either Blank or C. """ # All factors as stated det_award_1 = DetachedAwardFinancialAssistanc...
def test_success(database):
""" Test AwardingOfficeCode must be submitted for new awards (ActionType = A or blank) whose ActionDate is on or after October 1, 2018, and whose CorrectionDeleteIndicator is either Blank or C. """ # All factors as stated det_award_1 = DetachedAwardFinancialAssistanceFactory(awarding_office_cod...
import DetachedAwardFinancialAssistanceFactory from tests.unit.dataactvalidator.utils import number_of_errors, query_columns _FILE = 'fabs38_detached_award_financial_assistance_3' def test_column_headers(database): expected_subset = {'row_number', 'awarding_office_code', 'action_type', 'correction_delete_indica...
109
109
364
5
103
brianherman/data-act-broker-backend
tests/unit/dataactvalidator/test_fabs38_detached_award_financial_assistance_3.py
Python
test_success
test_success
14
37
14
14
f90310be2a5b0d42f666989104929fa4c8cc102a
bigcode/the-stack
train
b0c72d110b5fe817fc04789b
train
function
def test_column_headers(database): expected_subset = {'row_number', 'awarding_office_code', 'action_type', 'correction_delete_indicatr', 'action_date', 'uniqueid_AssistanceTransactionUniqueKey'} actual = set(query_columns(_FILE, database)) assert expected_subset == actual
def test_column_headers(database):
expected_subset = {'row_number', 'awarding_office_code', 'action_type', 'correction_delete_indicatr', 'action_date', 'uniqueid_AssistanceTransactionUniqueKey'} actual = set(query_columns(_FILE, database)) assert expected_subset == actual
from tests.unit.dataactcore.factories.staging import DetachedAwardFinancialAssistanceFactory from tests.unit.dataactvalidator.utils import number_of_errors, query_columns _FILE = 'fabs38_detached_award_financial_assistance_3' def test_column_headers(database):
55
64
65
6
49
brianherman/data-act-broker-backend
tests/unit/dataactvalidator/test_fabs38_detached_award_financial_assistance_3.py
Python
test_column_headers
test_column_headers
7
11
7
7
a4c4ca60630c03fab248996d8f63b6096640c3f5
bigcode/the-stack
train
79d1cfa6e2bad698cd114bec
train
class
@task() class CTLTrafoClassifier(CTLClassifierDataMixin, TransformerClassifierMixin, SimpleTask): pass
@task() class CTLTrafoClassifier(CTLClassifierDataMixin, TransformerClassifierMixin, SimpleTask):
pass
ixin import CTLClassifierDataMixin from .transformer_classifier_mixin import TransformerClassifierMixin from .simple_task import SimpleTask from typing import Dict, Any, List from .. import task @task() class CTLTrafoClassifier(CTLClassifierDataMixin, TransformerClassifierMixin, SimpleTask):
64
64
24
22
41
RobertCsordas/tcf
tasks/simple/ctl_trafo_classifier.py
Python
CTLTrafoClassifier
CTLTrafoClassifier
8
10
8
9
63277c99f341d4d3a46c838600d2e2c67923fa88
bigcode/the-stack
train
12f658e0b3e250d1d3d4e034
train
function
def project_radial_to3d(point_2d): alpha = point_2d.norm() if alpha == 0: beta = 1 else: beta = sin(alpha) / alpha point_3d = point_2d * beta point_3d.z = cos(alpha) return point_3d
def project_radial_to3d(point_2d):
alpha = point_2d.norm() if alpha == 0: beta = 1 else: beta = sin(alpha) / alpha point_3d = point_2d * beta point_3d.z = cos(alpha) return point_3d
= 0 else: alpha = arcsin(beta) / beta if point_3d.z < 0: alpha = pi / beta - alpha point_2d *= alpha return point_2d def project_radial_to3d(point_2d):
64
64
76
12
51
cle1109/scot
scot/eegtopo/projections.py
Python
project_radial_to3d
project_radial_to3d
26
34
26
26
4a31c7c33c1deef278c2ccfa44c2621025f610e3
bigcode/the-stack
train
964dc377e8ab600812da2182
train
function
def project_radial_to2d(point_3d): point_2d = point_3d.copy() point_2d.z = 0 beta = point_2d.norm() if beta == 0: alpha = 0 else: alpha = arcsin(beta) / beta if point_3d.z < 0: alpha = pi / beta - alpha point_2d *= alpha return point_2d
def project_radial_to2d(point_3d):
point_2d = point_3d.copy() point_2d.z = 0 beta = point_2d.norm() if beta == 0: alpha = 0 else: alpha = arcsin(beta) / beta if point_3d.z < 0: alpha = pi / beta - alpha point_2d *= alpha return point_2d
http://opensource.org/licenses/MIT # Copyright (c) 2013 Martin Billinger from numpy import arcsin, sin, cos, pi, sqrt, sum from numpy import atleast_2d, asarray, zeros, newaxis def project_radial_to2d(point_3d):
64
64
104
12
51
cle1109/scot
scot/eegtopo/projections.py
Python
project_radial_to2d
project_radial_to2d
9
23
9
9
13a2074f247ae15bb7c90f20fa4aeb937bc06339
bigcode/the-stack
train
6e7150de18a7ecaf2d9353c3
train
function
def array_project_radial_to2d(points_3d): points_3d = atleast_2d(points_3d) points_2d = points_3d[:, 0:2] betas = sqrt(sum(points_2d**2, -1)) alphas = zeros(betas.shape) mask = betas != 0 alphas[mask] = arcsin(betas[mask]) / betas[mask] mask = points_3d[:, 2] < 0 alphas[mask] = pi / ...
def array_project_radial_to2d(points_3d):
points_3d = atleast_2d(points_3d) points_2d = points_3d[:, 0:2] betas = sqrt(sum(points_2d**2, -1)) alphas = zeros(betas.shape) mask = betas != 0 alphas[mask] = arcsin(betas[mask]) / betas[mask] mask = points_3d[:, 2] < 0 alphas[mask] = pi / betas[mask] - alphas[mask] return poi...
0: beta = 1 else: beta = sin(alpha) / alpha point_3d = point_2d * beta point_3d.z = cos(alpha) return point_3d def array_project_radial_to2d(points_3d):
64
64
146
13
50
cle1109/scot
scot/eegtopo/projections.py
Python
array_project_radial_to2d
array_project_radial_to2d
37
51
37
37
33672789092bda6ad8ca2ea90e4d9e5c0db4d57d
bigcode/the-stack
train
9a72a20b8b58d6b75ee3c2c4
train
function
def array_project_radial_to3d(points_2d): points_2d = atleast_2d(points_2d) alphas = sqrt(sum(points_2d**2, -1)) betas = sin(alphas) / alphas betas[alphas == 0] = 1 x = points_2d[..., 0] * betas y = points_2d[..., 1] * betas z = cos(alphas) points_3d = asarray([x, y, z]).T retur...
def array_project_radial_to3d(points_2d):
points_2d = atleast_2d(points_2d) alphas = sqrt(sum(points_2d**2, -1)) betas = sin(alphas) / alphas betas[alphas == 0] = 1 x = points_2d[..., 0] * betas y = points_2d[..., 1] * betas z = cos(alphas) points_3d = asarray([x, y, z]).T return points_3d
[mask] mask = points_3d[:, 2] < 0 alphas[mask] = pi / betas[mask] - alphas[mask] return points_2d * alphas[:, newaxis] def array_project_radial_to3d(points_2d):
64
64
131
13
51
cle1109/scot
scot/eegtopo/projections.py
Python
array_project_radial_to3d
array_project_radial_to3d
54
68
54
54
ab3e48eed5cf8df3709cebd0154984c9d0bffe07
bigcode/the-stack
train
fab50387b0ee4638e458095a
train
class
class LeafClimateSwitch(LeafEntity, ToggleEntity): """Nissan Leaf Climate Control switch.""" @property def name(self) -> str: """Switch name.""" return f"{self.car.leaf.nickname} Climate Control" def log_registration(self) -> None: """Log registration.""" _LOGGER.debug(...
class LeafClimateSwitch(LeafEntity, ToggleEntity):
"""Nissan Leaf Climate Control switch.""" @property def name(self) -> str: """Switch name.""" return f"{self.car.leaf.nickname} Climate Control" def log_registration(self) -> None: """Log registration.""" _LOGGER.debug( "Registered LeafClimateSwitch integrat...
"""Nissan Leaf switch platform setup.""" if discovery_info is None: return devices = [] for vin, datastore in hass.data[DATA_LEAF].items(): _LOGGER.debug("Adding switch for vin=%s", vin) devices.append(LeafClimateSwitch(datastore)) add_devices(devices, True) class LeafClima...
81
81
271
11
70
hypnosiss/core
homeassistant/components/nissan_leaf/switch.py
Python
LeafClimateSwitch
LeafClimateSwitch
35
70
35
35
9c00cbe2d3997e55cf97fc02638fd564d8798e99
bigcode/the-stack
train
f5ef8ba31c23a8fffb0c3966
train
function
def setup_platform( hass: HomeAssistant, config: ConfigType, add_devices: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Nissan Leaf switch platform setup.""" if discovery_info is None: return devices = [] for vin, datastore in hass.data[DATA...
def setup_platform( hass: HomeAssistant, config: ConfigType, add_devices: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None:
"""Nissan Leaf switch platform setup.""" if discovery_info is None: return devices = [] for vin, datastore in hass.data[DATA_LEAF].items(): _LOGGER.debug("Adding switch for vin=%s", vin) devices.append(LeafClimateSwitch(datastore)) add_devices(devices, True)
from . import DATA_CLIMATE, DATA_LEAF, LeafEntity _LOGGER = logging.getLogger(__name__) def setup_platform( hass: HomeAssistant, config: ConfigType, add_devices: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None:
64
64
110
40
24
hypnosiss/core
homeassistant/components/nissan_leaf/switch.py
Python
setup_platform
setup_platform
17
32
17
22
8f1db7db6025894f72841acd51280b8fb3f4ae05
bigcode/the-stack
train
fa9a8d04675a4cb5c56ae3bb
train
function
def test_virtualipe(): # # Set up the GMPE, IPE, and GMICE # gmpe_cy14 = ChiouYoungs2014() gmpe = MultiGMPE.from_list([gmpe_cy14], [1.0]) gmice = WGRW12() ipe = VirtualIPE.fromFuncs(gmpe, gmice) # # Use the Calexico event info # homedir = os.path.dirname(os.path.abspath(__f...
def test_virtualipe(): # # Set up the GMPE, IPE, and GMICE #
gmpe_cy14 = ChiouYoungs2014() gmpe = MultiGMPE.from_list([gmpe_cy14], [1.0]) gmice = WGRW12() ipe = VirtualIPE.fromFuncs(gmpe, gmice) # # Use the Calexico event info # homedir = os.path.dirname(os.path.abspath(__file__)) datadir = os.path.abspath(os.path.join( homedir, '...
# third party modules import numpy as np from openquake.hazardlib.gsim.chiou_youngs_2014 import ChiouYoungs2014 from openquake.hazardlib.gsim.boore_2014 import BooreEtAl2014 import openquake.hazardlib.const as oqconst from openquake.hazardlib.imt import MMI, PGA, PGV, SA import pytest # local imports from shakelib.v...
256
256
2,015
24
232
ynthdhj/shakemap
tests/shakelib/virtualipe_test.py
Python
test_virtualipe
test_virtualipe
30
212
30
34
10d5251e36c38f923e2e2bfacdd478b6ed421f72
bigcode/the-stack
train
797fa2dfaca6d5461754e4e0
train
class
class PSFLets: """ Helper class to deal with the PSFLets on the detector. Does most of the heavy lifting during the wavelength calibration step. """ def __init__(self, load=False, infile=None, infiledir='.'): ''' Initialize the class Parameters ---------- lo...
class PSFLets:
""" Helper class to deal with the PSFLets on the detector. Does most of the heavy lifting during the wavelength calibration step. """ def __init__(self, load=False, infile=None, infiledir='.'): ''' Initialize the class Parameters ---------- load: Boolean ...
#!/usr/bin/env python import copy import glob import logging import os import re import numpy as np from astropy.io import fits from scipy import interpolate, ndimage, optimize, signal try: from charis.image import Image except: from image import Image log = logging.getLogger('main') class PSFLets:
76
256
3,015
5
71
thaynecurrie/charis-dep
charis/primitives/locate_psflets.py
Python
PSFLets
PSFLets
21
371
21
21
465f90fb4080f34cbdb00c45cce7baa9c68d643e
bigcode/the-stack
train
b3f74478042e2fae57f5888c
train
function
def locatePSFlets(inImage, polyorder=2, sig=0.7, coef=None, trimfrac=0.1, phi=np.arctan2(1.926, -1), scale=15.02, fitorder=None): """ function locatePSFlets takes an Image class, assumed to be a monochromatic grid of spots with read noise and shot noise, and returns the esimated positi...
def locatePSFlets(inImage, polyorder=2, sig=0.7, coef=None, trimfrac=0.1, phi=np.arctan2(1.926, -1), scale=15.02, fitorder=None):
""" function locatePSFlets takes an Image class, assumed to be a monochromatic grid of spots with read noise and shot noise, and returns the esimated positions of the spot centroids. This is designed to constrain the domain of the PSF-let fitting later in the pipeline. Parameters -----...
trim Default 0.1 (5% trimmed on the high end, 5% on the low end) highordercoef: boolean Returns ------- score: float Negative sum of PSFlet fluxes, to be minimized """ ################################################################# # Use np.nan for lenslet coordinate...
256
256
1,900
54
201
thaynecurrie/charis-dep
charis/primitives/locate_psflets.py
Python
locatePSFlets
locatePSFlets
603
771
603
604
19f7da7685d72b483bc52ba5c7b3eb0a89856eed
bigcode/the-stack
train
ebb61965f03440e6e085417e
train
function
def _transform(x, y, order, coef, highordercoef=None): """ Private function _transform in locate_psflets Apply the coefficients given to transform the coordinates using a polynomial. Parameters ---------- x: ndarray Rectilinear grid y: ndarray of floats Rectilin...
def _transform(x, y, order, coef, highordercoef=None):
""" Private function _transform in locate_psflets Apply the coefficients given to transform the coordinates using a polynomial. Parameters ---------- x: ndarray Rectilinear grid y: ndarray of floats Rectilinear grid order: int Order of the polynomial...
= int(np.sqrt(len(coef) + 0.25) - 1.5 + 1e-12) shortorder = int(np.sqrt(len(coefshort) + 0.25) - 1.5 + 1e-12) i = 0 j = 0 for ix in range(coeforder + 1): for iy in range(coeforder - ix + 1): if ix + iy <= shortorder: coef[i] = coefshort[j] j += 1 ...
200
200
668
16
183
thaynecurrie/charis-dep
charis/primitives/locate_psflets.py
Python
_transform
_transform
470
552
470
470
3c3bbcc60525fdf7c222e20f663edd5ee2e55ed2
bigcode/the-stack
train
b7c8d50b8050b553ff9be1ba
train
function
def _pullorder(coef, order=1): coeforder = int(np.sqrt(len(coef) + 0.25) - 1.5 + 1e-12) coef_short = [] i = 0 for ix in range(coeforder + 1): for iy in range(coeforder - ix + 1): if ix + iy <= order: coef_short += [coef[i]] i += 1 for ix in range(coe...
def _pullorder(coef, order=1):
coeforder = int(np.sqrt(len(coef) + 0.25) - 1.5 + 1e-12) coef_short = [] i = 0 for ix in range(coeforder + 1): for iy in range(coeforder - ix + 1): if ix + iy <= order: coef_short += [coef[i]] i += 1 for ix in range(coeforder + 1): for iy in r...
coef[n / 2] = y0 coef[n / 2 + 1] = scale * np.sin(phi) coef[n / 2 + order + 1] = scale * np.cos(phi) return list(coef) def _pullorder(coef, order=1):
64
64
152
11
53
thaynecurrie/charis-dep
charis/primitives/locate_psflets.py
Python
_pullorder
_pullorder
428
445
428
429
26882492a30e946a26c02049cdb85bbc1b2e2750
bigcode/the-stack
train
7633f901d81f4d677d9a73f4
train
function
def _initcoef(order, scale=15.02, phi=np.arctan2(1.926, -1), x0=0, y0=0): """ Private function _initcoef in locate_psflets Create a set of coefficients including a rotation matrix plus zeros. Parameters ---------- order: int The polynomial order of the grid distortion scale: float ...
def _initcoef(order, scale=15.02, phi=np.arctan2(1.926, -1), x0=0, y0=0):
""" Private function _initcoef in locate_psflets Create a set of coefficients including a rotation matrix plus zeros. Parameters ---------- order: int The polynomial order of the grid distortion scale: float The linear separation in pixels of the PSFlets. Default 15.02. ...
[ix, iy]], tck_x) for nlam_max in range(x.shape[-1]): if np.all(y[:, :, nlam_max] == 0): break self.xindx = x[:, :, :nlam_max] self.yindx = y[:, :, :nlam_max] self.nlam = nlam self.lam_indx = lam_out[:, :, :nlam_max] self.nlam_max = np.amax(n...
136
136
456
36
100
thaynecurrie/charis-dep
charis/primitives/locate_psflets.py
Python
_initcoef
_initcoef
374
425
374
374
a0c1401cebe79bdf9cabf5c18942f05f7a1e3d1e
bigcode/the-stack
train
6f302161992f767ead584e35
train
function
def _insertorder(coefshort, coef): coeforder = int(np.sqrt(len(coef) + 0.25) - 1.5 + 1e-12) shortorder = int(np.sqrt(len(coefshort) + 0.25) - 1.5 + 1e-12) i = 0 j = 0 for ix in range(coeforder + 1): for iy in range(coeforder - ix + 1): if ix + iy <= shortorder: c...
def _insertorder(coefshort, coef):
coeforder = int(np.sqrt(len(coef) + 0.25) - 1.5 + 1e-12) shortorder = int(np.sqrt(len(coefshort) + 0.25) - 1.5 + 1e-12) i = 0 j = 0 for ix in range(coeforder + 1): for iy in range(coeforder - ix + 1): if ix + iy <= shortorder: coef[i] = coefshort[j] ...
for ix in range(coeforder + 1): for iy in range(coeforder - ix + 1): if ix + iy <= order: coef_short += [coef[i]] i += 1 return coef_short def _insertorder(coefshort, coef):
64
64
197
10
53
thaynecurrie/charis-dep
charis/primitives/locate_psflets.py
Python
_insertorder
_insertorder
448
467
448
448
c506f5f2819f89f7ab65c77d0883b7216fb966d1
bigcode/the-stack
train
25dd5b0e470fba17eb044722
train
function
def _corrval(coef, x, y, filtered, order, trimfrac=0.1, highordercoef=None): """ Private function _corrval in locate_psflets Return the negative of the sum of the middle XX% of the PSFlet spot fluxes (disregarding those with the most and the least flux to limit the impact of outliers). Analogous t...
def _corrval(coef, x, y, filtered, order, trimfrac=0.1, highordercoef=None):
""" Private function _corrval in locate_psflets Return the negative of the sum of the middle XX% of the PSFlet spot fluxes (disregarding those with the most and the least flux to limit the impact of outliers). Analogous to the trimmed mean. Parameters ---------- coef: list of floa...
_x += coef[i] * x**ix * y**iy i += 1 for ix in range(order2 + 1): for iy in range(order1 - ix + 1): if ix + iy <= order1: continue _y += coef[i] * x**ix * y**iy i += 1 return [_x, _y] def _corrval(coef, x, y, f...
114
114
381
27
87
thaynecurrie/charis-dep
charis/primitives/locate_psflets.py
Python
_corrval
_corrval
555
600
555
555
0ec28860341eb5d3d3ea2dc2f5d2e0374eb3e425
bigcode/the-stack
train
75d43d1e5cea9f20f9ba46a0
train
class
class QualAnalysis(object): def __init__(self): self.kb_facts = self.read_kb_facts(kb_file) if use_kb else None self.text_kb_facts = self.read_text_kb_facts(text_kb_file) if use_text else None self.questions = self.read_questions(input_test_file) # print('Reading mid to word map') ...
class QualAnalysis(object):
def __init__(self): self.kb_facts = self.read_kb_facts(kb_file) if use_kb else None self.text_kb_facts = self.read_text_kb_facts(text_kb_file) if use_text else None self.questions = self.read_questions(input_test_file) # print('Reading mid to word map') # self.mid_to_word_ma...
import numpy as np import argparse from tqdm import tqdm import json class QualAnalysis(object):
21
256
1,936
5
15
Program-Bear/WalkingNetwork
code/qual_eval.py
Python
QualAnalysis
QualAnalysis
7
172
7
7
c629ee56205bb4ac6a6b7317b58af667f73615b3
bigcode/the-stack
train
bdc6c848f5962357911ba695
train
class
class PerformanceMetricsUnitTest(unittest.TestCase): def mock_trade(self, id, amount, price, position="OPEN", type="BUY", fee=None): trade = MagicMock() trade.order_id = id trade.position = position trade.trade_type = type trade.amount = amount trade.price = price ...
class PerformanceMetricsUnitTest(unittest.TestCase):
def mock_trade(self, id, amount, price, position="OPEN", type="BUY", fee=None): trade = MagicMock() trade.order_id = id trade.position = position trade.trade_type = type trade.amount = amount trade.price = price if fee: trade.trade_fee = fee.to_jso...
import asyncio import time import unittest from decimal import Decimal from unittest.mock import MagicMock, patch from hummingbot.client.performance import PerformanceMetrics from hummingbot.core.data_type.trade_fee import AddedToCostTradeFee, TokenAmount from hummingbot.core.event.events import PositionAction from hu...
118
256
2,163
9
109
BGTCapital/hummingbot
test/hummingbot/client/test_performance.py
Python
PerformanceMetricsUnitTest
PerformanceMetricsUnitTest
17
232
17
17
bcffb979fd75e1687d4f995f2d8a6cea61f3b8e3
bigcode/the-stack
train
7fcba5f063f5232f63e791f5
train
function
def find_puzzle(img, draw_contours=False): '''Finds the biggest object in the image and returns its 4 corners (to crop it)''' # Preprocessing: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) edges = cv2.GaussianBlur(gray, (5, 5), 0) kernel = np.ones((3, 3), np.uint8) edges = cv2.morphologyEx(edges...
def find_puzzle(img, draw_contours=False):
'''Finds the biggest object in the image and returns its 4 corners (to crop it)''' # Preprocessing: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) edges = cv2.GaussianBlur(gray, (5, 5), 0) kernel = np.ones((3, 3), np.uint8) edges = cv2.morphologyEx(edges, cv2.MORPH_OPEN, kernel) edges = cv2.a...
import cv2, sys import numpy as np from imutils.perspective import four_point_transform from classifier import ocr # (9*9) grid grid = np.zeros((9, 9), dtype=int) ## searching and getting the puzzle def find_puzzle(img, draw_contours=False):
67
238
794
11
55
lakhaniaayush/Sudoku-Solver
extract.py
Python
find_puzzle
find_puzzle
10
80
10
10
ea90a3195af2d491ba60b9039066b41cc4d892d4
bigcode/the-stack
train
7ed5265c61ab9e0fb6f82af5
train
function
def extract_digits(puzzle, debug=False): # divide the cropped image into 81 small squares y = round(puzzle.shape[0] / 9) x = round(puzzle.shape[1] / 9) coords = [] for i in range(9): row = [] for j in range(9): startX = j*x startY = i*y endX = (j+1...
def extract_digits(puzzle, debug=False): # divide the cropped image into 81 small squares
y = round(puzzle.shape[0] / 9) x = round(puzzle.shape[1] / 9) coords = [] for i in range(9): row = [] for j in range(9): startX = j*x startY = i*y endX = (j+1)*x endY = (i+1)*y row.append((startX, startY, endX, endY)) ...
_transform(img, cnt) return edges, cropped else: return edges, None return edges, None ## extracting (OCR) digits from the image # returns a matrix of digits def extract_digits(puzzle, debug=False): # divide the cropped image into 81 small squares
64
64
212
21
42
lakhaniaayush/Sudoku-Solver
extract.py
Python
extract_digits
extract_digits
85
109
85
86
bf242c8c224dde336cac4582e3b3083da5c89e78
bigcode/the-stack
train
51938e174c110de941c4ba95
train
function
def extract_puzzle(imgPath, debug=False): im = cv2.imread(imgPath, cv2.IMREAD_COLOR) if im is not None: _, cropped = find_puzzle(im) # if puzzle found if cropped is not None: grid, coords = extract_digits(cropped, debug) return cropped, [coords, grid] else...
def extract_puzzle(imgPath, debug=False):
im = cv2.imread(imgPath, cv2.IMREAD_COLOR) if im is not None: _, cropped = find_puzzle(im) # if puzzle found if cropped is not None: grid, coords = extract_digits(cropped, debug) return cropped, [coords, grid] else: print("Puzzle not found!!!")...
, debug) grid[i][j] = digit # recording coordinates for each cell coords.append(row) # return puzzle grid print("\n################ Sudoku puzzle ###################\n") # print(grid) return grid, coords def extract_puzzle(imgPath, debug=False):
64
64
105
10
53
lakhaniaayush/Sudoku-Solver
extract.py
Python
extract_puzzle
extract_puzzle
112
125
112
112
c9f07eab2fa4d8a2532cfd2fb8bfbb751f3b0358
bigcode/the-stack
train
b1d5c425ccc3db4d394da956
train
function
@thread_wrapped_func def test_mp(args, model, test_samplers, rank=0, mode='Test', queue=None): test(args, model, test_samplers, rank, mode, queue)
@thread_wrapped_func def test_mp(args, model, test_samplers, rank=0, mode='Test', queue=None):
test(args, model, test_samplers, rank, mode, queue)
: th.set_num_threads(args.num_thread) train(args, model, train_sampler, valid_samplers, rank, rel_parts, cross_rels, barrier) @thread_wrapped_func def test_mp(args, model, test_samplers, rank=0, mode='Test', queue=None):
64
64
46
29
35
jspisak/dgl
apps/kg/train_pytorch.py
Python
test_mp
test_mp
214
216
214
215
a7fc3fc5ebe6a68906844c680d3ef671118047d9
bigcode/the-stack
train
87da463d292dadfb0609ff32
train
class
class KGEClient(KVClient): """User-defined kvclient for DGL-KGE """ def _push_handler(self, name, ID, data, target): """Row-Sparse Adagrad updater """ original_name = name[0:-6] state_sum = target[original_name+'_state-data-'] grad_sum = (data * data).mean(1) ...
class KGEClient(KVClient):
"""User-defined kvclient for DGL-KGE """ def _push_handler(self, name, ID, data, target): """Row-Sparse Adagrad updater """ original_name = name[0:-6] state_sum = target[original_name+'_state-data-'] grad_sum = (data * data).mean(1) state_sum.index_add_(0, ID,...
ytorch.tensor_models import thread_wrapped_func import os import logging import time from functools import wraps import dgl from dgl.contrib import KVClient import dgl.backend as F from dataloader import EvalDataset from dataloader import get_dataset class KGEClient(KVClient):
66
66
223
8
57
jspisak/dgl
apps/kg/train_pytorch.py
Python
KGEClient
KGEClient
26
53
26
26
0f68921e00aa200e5d10790283900115280dea71
bigcode/the-stack
train
dc278306365d80c1378a2ada
train
function
def load_model_from_checkpoint(logger, args, n_entities, n_relations, ckpt_path): model = load_model(logger, args, n_entities, n_relations) model.load_emb(ckpt_path, args.dataset) return model
def load_model_from_checkpoint(logger, args, n_entities, n_relations, ckpt_path):
model = load_model(logger, args, n_entities, n_relations) model.load_emb(ckpt_path, args.dataset) return model
double_entity_emb=args.double_ent, double_relation_emb=args.double_rel) if ckpt is not None: assert False, "We do not support loading model emb for genernal Embedding" return model def load_model_from_checkpoint(logger, args, n_entities, n_relations, ckpt_path):
64
64
52
20
43
jspisak/dgl
apps/kg/train_pytorch.py
Python
load_model_from_checkpoint
load_model_from_checkpoint
88
91
88
88
10c41fa8072204f031bcd360de82eb308ceb057e
bigcode/the-stack
train
d7c7d17d1029a55f356a42d4
train
function
def load_model(logger, args, n_entities, n_relations, ckpt=None): model = KEModel(args, args.model_name, n_entities, n_relations, args.hidden_dim, args.gamma, double_entity_emb=args.double_ent, double_relation_emb=args.double_rel) if ckpt is not None: assert False...
def load_model(logger, args, n_entities, n_relations, ckpt=None):
model = KEModel(args, args.model_name, n_entities, n_relations, args.hidden_dim, args.gamma, double_entity_emb=args.double_ent, double_relation_emb=args.double_rel) if ckpt is not None: assert False, "We do not support loading model emb for genernal Embedding" ...
_book=relation_pb) else: my_client.set_partition_book(name='entity_emb') my_client.set_partition_book(name='relation_emb') my_client.set_local2global(l2g) return my_client def load_model(logger, args, n_entities, n_relations, ckpt=None):
64
64
89
18
45
jspisak/dgl
apps/kg/train_pytorch.py
Python
load_model
load_model
79
85
79
79
c7b9833b4353f949ec4e0fcf3260820885efceec
bigcode/the-stack
train
6d7f1f62f8884ce3feb3cf2b
train
function
def connect_to_kvstore(args, entity_pb, relation_pb, l2g): """Create kvclient and connect to kvstore service """ server_namebook = dgl.contrib.read_ip_config(filename=args.ip_config) my_client = KGEClient(server_namebook=server_namebook) my_client.set_clr(args.lr) my_client.connect() if ...
def connect_to_kvstore(args, entity_pb, relation_pb, l2g):
"""Create kvclient and connect to kvstore service """ server_namebook = dgl.contrib.read_ip_config(filename=args.ip_config) my_client = KGEClient(server_namebook=server_namebook) my_client.set_clr(args.lr) my_client.connect() if my_client.get_id() % args.num_client == 0: my_clien...
self.clr = learning_rate def set_local2global(self, l2g): self._l2g = l2g def get_local2global(self): return self._l2g def connect_to_kvstore(args, entity_pb, relation_pb, l2g):
64
64
167
18
45
jspisak/dgl
apps/kg/train_pytorch.py
Python
connect_to_kvstore
connect_to_kvstore
56
76
56
56
294163ce5dd604349918c96febfec2b8c4fadb08
bigcode/the-stack
train
4d59d4cd4e130f090630202e
train
function
@thread_wrapped_func def train_mp(args, model, train_sampler, valid_samplers=None, rank=0, rel_parts=None, cross_rels=None, barrier=None): if args.num_proc > 1: th.set_num_threads(args.num_thread) train(args, model, train_sampler, valid_samplers, rank, rel_parts, cross_rels, barrier)
@thread_wrapped_func def train_mp(args, model, train_sampler, valid_samplers=None, rank=0, rel_parts=None, cross_rels=None, barrier=None):
if args.num_proc > 1: th.set_num_threads(args.num_thread) train(args, model, train_sampler, valid_samplers, rank, rel_parts, cross_rels, barrier)
_samplers[0].reset() test_samplers[1] = test_samplers[1].reset() @thread_wrapped_func def train_mp(args, model, train_sampler, valid_samplers=None, rank=0, rel_parts=None, cross_rels=None, barrier=None):
64
64
81
38
26
jspisak/dgl
apps/kg/train_pytorch.py
Python
train_mp
train_mp
208
212
208
209
87171cf4dc800743829d94c517ed32185ae6b6cd
bigcode/the-stack
train
bca3f33904f4f47432e3df5b
train
function
def test(args, model, test_samplers, rank=0, mode='Test', queue=None): if len(args.gpu) > 0: gpu_id = args.gpu[rank % len(args.gpu)] if args.mix_cpu_gpu and args.num_proc > 1 else args.gpu[0] else: gpu_id = -1 if args.strict_rel_part or args.soft_rel_part: model.load_relation(th.dev...
def test(args, model, test_samplers, rank=0, mode='Test', queue=None):
if len(args.gpu) > 0: gpu_id = args.gpu[rank % len(args.gpu)] if args.mix_cpu_gpu and args.num_proc > 1 else args.gpu[0] else: gpu_id = -1 if args.strict_rel_part or args.soft_rel_part: model.load_relation(th.device('cuda:' + str(gpu_id))) with th.no_grad(): logs = [] ...
barrier is not None: barrier.wait() print('train {} takes {:.3f} seconds'.format(rank, time.time() - train_start)) if args.async_update: model.finish_async_update() if args.strict_rel_part or args.soft_rel_part: model.writeback_relation(rank, rel_parts) def test(args, model...
87
87
291
22
65
jspisak/dgl
apps/kg/train_pytorch.py
Python
test
test
180
206
180
180
ae24cb2a0100bee2e9f1667db0d41b9e7ad989bb
bigcode/the-stack
train
533f166ad8db77d42f17e139
train
function
@thread_wrapped_func def dist_train_test(args, model, train_sampler, entity_pb, relation_pb, l2g, rank=0, rel_parts=None, cross_rels=None, barrier=None): if args.num_proc > 1: th.set_num_threads(args.num_thread) client = connect_to_kvstore(args, entity_pb, relation_pb, l2g) client.barrier() tra...
@thread_wrapped_func def dist_train_test(args, model, train_sampler, entity_pb, relation_pb, l2g, rank=0, rel_parts=None, cross_rels=None, barrier=None):
if args.num_proc > 1: th.set_num_threads(args.num_thread) client = connect_to_kvstore(args, entity_pb, relation_pb, l2g) client.barrier() train_time_start = time.time() train(args, model, train_sampler, None, rank, rel_parts, cross_rels, barrier, client) client.barrier() print('Tota...
None: queue.put(logs) else: for k, v in metrics.items(): print('[{}]{} average {} at [{}/{}]: {}'.format(rank, mode, k, args.step, args.max_step, v)) test_samplers[0] = test_samplers[0].reset() test_samplers[1] = test_samplers[1].reset() @thread_wrapped_func def...
256
256
1,044
43
213
jspisak/dgl
apps/kg/train_pytorch.py
Python
dist_train_test
dist_train_test
218
342
218
219
a8b8fa8c5d441f630dfda37085e80b386411f31b
bigcode/the-stack
train
4cf238566b1be0395c859003
train
function
def train(args, model, train_sampler, valid_samplers=None, rank=0, rel_parts=None, cross_rels=None, barrier=None, client=None): logs = [] for arg in vars(args): logging.info('{:20}:{}'.format(arg, getattr(args, arg))) if len(args.gpu) > 0: gpu_id = args.gpu[rank % len(args.gpu)] if args.mix...
def train(args, model, train_sampler, valid_samplers=None, rank=0, rel_parts=None, cross_rels=None, barrier=None, client=None):
logs = [] for arg in vars(args): logging.info('{:20}:{}'.format(arg, getattr(args, arg))) if len(args.gpu) > 0: gpu_id = args.gpu[rank % len(args.gpu)] if args.mix_cpu_gpu and args.num_proc > 1 else args.gpu[0] else: gpu_id = -1 if args.async_update: model.create_as...
', partition_book=entity_pb) my_client.set_partition_book(name='relation_emb', partition_book=relation_pb) else: my_client.set_partition_book(name='entity_emb') my_client.set_partition_book(name='relation_emb') my_client.set_local2global(l2g) return my_client def load_model(logge...
240
240
802
34
205
jspisak/dgl
apps/kg/train_pytorch.py
Python
train
train
93
178
93
93
f9b72f84279e4903f1a870d862f93897795209cd
bigcode/the-stack
train
e7a8bff8d44a15e8757d564b
train
class
class Migration(migrations.Migration): dependencies = [ ('raster_aggregation', '0017_auto_20171124_0851'), ] operations = [ migrations.AddField( model_name='aggregationlayer', name='extent', field=django.contrib.gis.db.models.fields.PolygonField(null=Tru...
class Migration(migrations.Migration):
dependencies = [ ('raster_aggregation', '0017_auto_20171124_0851'), ] operations = [ migrations.AddField( model_name='aggregationlayer', name='extent', field=django.contrib.gis.db.models.fields.PolygonField(null=True, srid=3857), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-02-13 05:02 from __future__ import unicode_literals import django.contrib.gis.db.models.fields from django.db import migrations class Migration(migrations.Migration):
61
64
79
7
53
photonbit/django-raster-aggregation
raster_aggregation/migrations/0018_aggregationlayer_extent.py
Python
Migration
Migration
9
21
9
10
47314a2f82c5f4fda41a2aecb0b0a87197fae2e2
bigcode/the-stack
train
a41d35a8b9a78271186cac49
train
function
def _import_object_from_name(module_name, fullname): obj = sys.modules.get(module_name) if obj is None: return None for comp in fullname.split('.'): obj = getattr(obj, comp) return obj
def _import_object_from_name(module_name, fullname):
obj = sys.modules.get(module_name) if obj is None: return None for comp in fullname.split('.'): obj = getattr(obj, comp) return obj
, what, name, obj, options, lines): _docstring_check.check(app, what, name, obj, options, lines) def _build_finished(app, exception): if exception is None: _autosummary_check.check(app, exception) def _import_object_from_name(module_name, fullname):
64
64
50
11
53
yuhonghong66/chainer
docs/source/conf.py
Python
_import_object_from_name
_import_object_from_name
380
386
380
380
203665240eec58b65f307606b96b4266163f497e
bigcode/the-stack
train
0403d5a59a5e9c735d8d82e9
train
function
def _is_git_root(path): return os.path.isdir(os.path.join(path, '.git'))
def _is_git_root(path):
return os.path.isdir(os.path.join(path, '.git'))
return None for comp in fullname.split('.'): obj = getattr(obj, comp) return obj def _is_egg_directory(path): return (path.endswith('.egg') and os.path.isdir(os.path.join(path, 'EGG-INFO'))) def _is_git_root(path):
63
64
20
7
56
yuhonghong66/chainer
docs/source/conf.py
Python
_is_git_root
_is_git_root
394
395
394
394
d65f95b7bf1067446e93b1f6915f8c51f79fd03d
bigcode/the-stack
train
4f4757158717917173461fce
train
function
def setup(app): app.connect('autodoc-process-docstring', _autodoc_process_docstring) app.connect('build-finished', _build_finished)
def setup(app):
app.connect('autodoc-process-docstring', _autodoc_process_docstring) app.connect('build-finished', _build_finished)
, Chain, ChainList import chainer.functions as F import chainer.links as L from chainer.training import extensions import chainerx np.random.seed(0) ''' spelling_lang = 'en_US' spelling_word_list_filename = 'spelling_wordlist.txt' def setup(app):
64
64
35
4
60
yuhonghong66/chainer
docs/source/conf.py
Python
setup
setup
366
368
366
366
3d16ec1967227e6b176c592fd89e6af4b13aa9e5
bigcode/the-stack
train
7efca1e49ddcdde97861fcbe
train
function
def _get_sourcefile_and_linenumber(obj): # Retrieve the original function wrapped by contextlib.contextmanager if callable(obj): closure = getattr(obj, '__closure__', None) if closure is not None: obj = closure[0].cell_contents # Get the source file name and line number at which...
def _get_sourcefile_and_linenumber(obj): # Retrieve the original function wrapped by contextlib.contextmanager
if callable(obj): closure = getattr(obj, '__closure__', None) if closure is not None: obj = closure[0].cell_contents # Get the source file name and line number at which obj is defined. try: filename = inspect.getsourcefile(obj) except TypeError: # obj is not ...
)) dir = dir_ return _source_root def _get_source_relative_path(source_abs_path): return os.path.relpath(source_abs_path, _find_source_root(source_abs_path)) def _get_sourcefile_and_linenumber(obj): # Retrieve the original function wrapped by contextlib.contextmanager
64
64
163
24
40
yuhonghong66/chainer
docs/source/conf.py
Python
_get_sourcefile_and_linenumber
_get_sourcefile_and_linenumber
425
446
425
426
04291b36e43266dd79a7efd336bebb29ea5b5900
bigcode/the-stack
train
0863b51498b07fe327197afc
train
function
def _autodoc_process_docstring(app, what, name, obj, options, lines): _docstring_check.check(app, what, name, obj, options, lines)
def _autodoc_process_docstring(app, what, name, obj, options, lines):
_docstring_check.check(app, what, name, obj, options, lines)
_filename = 'spelling_wordlist.txt' def setup(app): app.connect('autodoc-process-docstring', _autodoc_process_docstring) app.connect('build-finished', _build_finished) def _autodoc_process_docstring(app, what, name, obj, options, lines):
64
64
38
20
44
yuhonghong66/chainer
docs/source/conf.py
Python
_autodoc_process_docstring
_autodoc_process_docstring
371
372
371
371
f421a9873fb298417ef3c76c2e5498a71f5daaed
bigcode/the-stack
train
e24cd5b705c9b7f5cdf9bf72
train
function
def linkcode_resolve(domain, info): if domain != 'py' or not info['module']: return None if 1 == int(os.environ.get('CHAINER_DOCS_SKIP_LINKCODE', 0)): return None # Import the object from module path obj = _import_object_from_name(info['module'], info['fullname']) # If it's not def...
def linkcode_resolve(domain, info):
if domain != 'py' or not info['module']: return None if 1 == int(os.environ.get('CHAINER_DOCS_SKIP_LINKCODE', 0)): return None # Import the object from module path obj = _import_object_from_name(info['module'], info['fullname']) # If it's not defined in the internal module, return ...
. return None, None # inspect can return None for cython objects if filename is None: return None, None # Get the source line number _, linenum = inspect.getsourcelines(obj) return filename, linenum def linkcode_resolve(domain, info):
67
67
226
9
57
yuhonghong66/chainer
docs/source/conf.py
Python
linkcode_resolve
linkcode_resolve
449
474
449
449
e105fb48884395e4779b89515a1fecedfd521403
bigcode/the-stack
train
b1656ce07127ef3cd2658af6
train
function
def _is_egg_directory(path): return (path.endswith('.egg') and os.path.isdir(os.path.join(path, 'EGG-INFO')))
def _is_egg_directory(path):
return (path.endswith('.egg') and os.path.isdir(os.path.join(path, 'EGG-INFO')))
_check.check(app, exception) def _import_object_from_name(module_name, fullname): obj = sys.modules.get(module_name) if obj is None: return None for comp in fullname.split('.'): obj = getattr(obj, comp) return obj def _is_egg_directory(path):
64
64
33
8
55
yuhonghong66/chainer
docs/source/conf.py
Python
_is_egg_directory
_is_egg_directory
389
391
389
389
46fb9b9146a1512ab172159ffcd2c1f02560ad25
bigcode/the-stack
train
94e509317d40d3097381baa8
train
function
def _build_finished(app, exception): if exception is None: _autosummary_check.check(app, exception)
def _build_finished(app, exception):
if exception is None: _autosummary_check.check(app, exception)
odoc_process_docstring) app.connect('build-finished', _build_finished) def _autodoc_process_docstring(app, what, name, obj, options, lines): _docstring_check.check(app, what, name, obj, options, lines) def _build_finished(app, exception):
64
64
24
8
56
yuhonghong66/chainer
docs/source/conf.py
Python
_build_finished
_build_finished
375
377
375
375
3e54cdfd72c66c0cce1da7b8e7db270195daac20
bigcode/the-stack
train
fa692ece2e58df47a158ca56
train
function
def _find_source_root(source_abs_path): # Note that READTHEDOCS* environment variable cannot be used, because they # are not set under docker environment. global _source_root if _source_root is None: dir = os.path.dirname(source_abs_path) while True: if _is_egg_directory(dir)...
def _find_source_root(source_abs_path): # Note that READTHEDOCS* environment variable cannot be used, because they # are not set under docker environment.
global _source_root if _source_root is None: dir = os.path.dirname(source_abs_path) while True: if _is_egg_directory(dir) or _is_git_root(dir): # Reached the root directory _source_root = dir break dir_ = os.path.dirname(di...
) def _is_git_root(path): return os.path.isdir(os.path.join(path, '.git')) _source_root = None def _find_source_root(source_abs_path): # Note that READTHEDOCS* environment variable cannot be used, because they # are not set under docker environment.
64
64
153
37
26
yuhonghong66/chainer
docs/source/conf.py
Python
_find_source_root
_find_source_root
401
418
401
403
fc2b0b7938876f09f1fb18eec76e6dd1391d38be
bigcode/the-stack
train
ad827d4ff979f50675b806fe
train
function
def _get_source_relative_path(source_abs_path): return os.path.relpath(source_abs_path, _find_source_root(source_abs_path))
def _get_source_relative_path(source_abs_path):
return os.path.relpath(source_abs_path, _find_source_root(source_abs_path))
dir_ = os.path.dirname(dir) if len(dir_) == len(dir): raise RuntimeError('Couldn\'t parse root directory from ' 'source file: {}'.format(source_abs_path)) dir = dir_ return _source_root def _get_source_relative_path(source_abs_pa...
64
64
28
10
53
yuhonghong66/chainer
docs/source/conf.py
Python
_get_source_relative_path
_get_source_relative_path
421
422
421
421
9a093d1251623a65532822ae7d24c1ccabd3cbc8
bigcode/the-stack
train
82b526bb158ab1df095c3a67
train
function
def create_tester_selector(trello: TrelloClient, github_teams: List[str], user_config, app_dir: str): github = Github(user_config, 5, 'datadog-agent', 'DataDog') now = datetime.utcnow() user_cache_expiration = now + timedelta(days=-7) trello_users = TrelloUsers(trello, app_dir, user_cache_expiration) ...
def create_tester_selector(trello: TrelloClient, github_teams: List[str], user_config, app_dir: str):
github = Github(user_config, 5, 'datadog-agent', 'DataDog') now = datetime.utcnow() user_cache_expiration = now + timedelta(days=-7) trello_users = TrelloUsers(trello, app_dir, user_cache_expiration) github_users = GithubUsers(github, app_dir, user_cache_expiration) userMatcher = GithubTrelloUse...
Matcher from .github_users import GithubUser, GithubUsers from .tester_selector_team import TesterSelectorTeam from .trello_users import TrelloUser, TrelloUsers def create_tester_selector(trello: TrelloClient, github_teams: List[str], user_config, app_dir: str):
64
64
157
27
36
TheBooper/integrations-core
datadog_checks_dev/datadog_checks/dev/tooling/commands/release/trello/tester_selector/tester_selector.py
Python
create_tester_selector
create_tester_selector
17
26
17
17
6fb430881180de27aed7f1957384800fc80b1a29
bigcode/the-stack
train
a308db28a50907ae7cac6ff9
train
class
class TesterSelector: """ Select a teammmate for QAing a trello card from github author. The algorithm is described in TesterSelectorTeam. Only users who created a pull request after `inactivity_date` are considered. """ def __init__( self, team_names: List[str], git...
class TesterSelector:
""" Select a teammmate for QAing a trello card from github author. The algorithm is described in TesterSelectorTeam. Only users who created a pull request after `inactivity_date` are considered. """ def __init__( self, team_names: List[str], github_users: GithubUsers...
trello_users import TrelloUser, TrelloUsers def create_tester_selector(trello: TrelloClient, github_teams: List[str], user_config, app_dir: str): github = Github(user_config, 5, 'datadog-agent', 'DataDog') now = datetime.utcnow() user_cache_expiration = now + timedelta(days=-7) trello_users = TrelloUs...
173
173
577
4
169
TheBooper/integrations-core
datadog_checks_dev/datadog_checks/dev/tooling/commands/release/trello/tester_selector/tester_selector.py
Python
TesterSelector
TesterSelector
29
94
29
29
ded54f76309fe70501e769990d09c10e4426222b
bigcode/the-stack
train
c2b108df91042a77336c7c19
train
function
def main(config_file): with open(config_file) as in_handle: config = yaml.load(in_handle) setup_logging(config) start_cluster(config) from bipy.cluster import view input_files = config["input"] for stage in config["run"]: if config["stage"][stage]["program"] == "tagdust": ...
def main(config_file):
with open(config_file) as in_handle: config = yaml.load(in_handle) setup_logging(config) start_cluster(config) from bipy.cluster import view input_files = config["input"] for stage in config["run"]: if config["stage"][stage]["program"] == "tagdust": tagdust_config = ...
from bipy.log import logger, setup_logging from bipy.cluster import start_cluster, stop_cluster import yaml import sys from bipy.toolbox import tagdust def main(config_file):
40
64
117
5
34
roryk/bipy
test/tagdust/test_tagdust.py
Python
main
main
8
22
8
8
93c4c3e6e63940b574aaeaf7d3250cd9e74a1696
bigcode/the-stack
train
eee7d7766dc27be172e9aa13
train
function
def body_end_architecture(astParser,args,keywords=None): return v_noop()
def body_end_architecture(astParser,args,keywords=None):
return v_noop()
Sig(dummy_DefaultVarSig) astParser.pop_scope() return architecure_body(Node.name, ret) Add_Export_Function("architecture",body_unfold_architecture_body) add_class("architecture",body_unfold_architecture_body) def body_end_architecture(astParser,args,keywords=None):
64
64
19
13
51
HardwareDesignWithPython/HDPython
HDPython/ast/ast_classes/ast_function_architeture.py
Python
body_end_architecture
body_end_architecture
49
50
49
49
bb19194f81fa87da9306eef80f12fd42d39733a2
bigcode/the-stack
train
43cda9d9381603d30bbe97fb
train
function
def body_unfold_architecture_body(astParser,Node): localContext = astParser.Context astParser.push_scope("architecture") dummy_DefaultVarSig = getDefaultVarSig() setDefaultVarSig(varSig.signal_t) #decorator_l = astParser.Unfold_body(Node.decorator_list) ret = list() astParser.Context ...
def body_unfold_architecture_body(astParser,Node):
localContext = astParser.Context astParser.push_scope("architecture") dummy_DefaultVarSig = getDefaultVarSig() setDefaultVarSig(varSig.signal_t) #decorator_l = astParser.Unfold_body(Node.decorator_list) ret = list() astParser.Context = ret for x in Node.body: if type(x).__name_...
for x in self.Body: v = str(x) if v.strip(): ret += " " + v + ";\n" ret += " -- end " + self.Name +"\n" return ret def body_unfold_architecture_body(astParser,Node):
64
64
167
13
50
HardwareDesignWithPython/HDPython
HDPython/ast/ast_classes/ast_function_architeture.py
Python
body_unfold_architecture_body
body_unfold_architecture_body
22
44
22
23
d021bb0ee992d7cc2ca80ee86a20259386f96887
bigcode/the-stack
train
8b62bfb5fb35d3bc797f065d
train
class
class architecure_body(v_ast_base): def __init__(self, Name, BodyList): self.Name =Name self.Body = BodyList def __str__(self): ret = " -- begin " + self.Name +"\n" for x in self.Body: v = str(x) if v.strip(): ret += " " + v + "...
class architecure_body(v_ast_base):
def __init__(self, Name, BodyList): self.Name =Name self.Body = BodyList def __str__(self): ret = " -- begin " + self.Name +"\n" for x in self.Body: v = str(x) if v.strip(): ret += " " + v + ";\n" ret += " -- end " + se...
add_class, add_ast_function_call from HDPython.lib_enums import getDefaultVarSig, setDefaultVarSig,varSig from HDPython.ast.ast_classes.ast_noop import v_noop from HDPython.hdl_exporter import Add_Export_Function class architecure_body(v_ast_base):
64
64
108
10
53
HardwareDesignWithPython/HDPython
HDPython/ast/ast_classes/ast_function_architeture.py
Python
architecure_body
architecure_body
7
20
7
7
9a5a837b6bd0a926b092f6691caafdecc8121951
bigcode/the-stack
train
4be3e2104ac82660ff732e4b
train
class
class DummySpinner: def __init__(self, *args, **kwargs): self.text = '' def write(self, *args, **kwargs): print(*args, **kwargs) def __getattr__(self, name): return self def __call__(self): pass def __enter__(self): return self def __exit__(self, *arg...
class DummySpinner:
def __init__(self, *args, **kwargs): self.text = '' def write(self, *args, **kwargs): print(*args, **kwargs) def __getattr__(self, name): return self def __call__(self): pass def __enter__(self): return self def __exit__(self, *args, **kwargs): ...
classmethod def verify_spinners_present(cls, name): y = yaspin.yaspin() for spinner in cls.random_spinners: if not hasattr(y, spinner): raise RuntimeError( 'Random spinner "{}" missing from yaspin'.format(spinner)) class DummySpinner:
64
64
108
4
60
hemna/haminfo
haminfo/spinner.py
Python
DummySpinner
DummySpinner
37
58
37
37
0159c2c52a607b20ea748ea87428da44da265917
bigcode/the-stack
train
75c752815eca02b0bf5c3ea3
train
class
class Spinner: enabled = True random = True random_spinners = [ 'dots', 'line', 'growVertical', 'circleHalves', 'toggle', 'arrow3', 'bouncingBar', 'bouncingBall', 'pong', 'shark', 'weather', 'dots12', 'moon', ] @classmethod def get(cls, *args, **kwargs): if cls....
class Spinner:
enabled = True random = True random_spinners = [ 'dots', 'line', 'growVertical', 'circleHalves', 'toggle', 'arrow3', 'bouncingBar', 'bouncingBall', 'pong', 'shark', 'weather', 'dots12', 'moon', ] @classmethod def get(cls, *args, **kwargs): if cls.enabled: ...
import contextlib import random import yaspin class Spinner:
15
68
228
3
11
hemna/haminfo
haminfo/spinner.py
Python
Spinner
Spinner
6
34
6
6
2ae24e5712411eef6a689fa973c0199ded36ae99
bigcode/the-stack
train
d45b72d98e32a7d20491626d
train
class
class SpinnerProxy: """Spinner-like class for parallel running threads This class either directly sets/calls its parent's `.text` or `write()` if `is_current` is set or keeps the lines written around to output them once `is_current` is set or and outside entity uses `flush()`. When `prefix` is set...
class SpinnerProxy:
"""Spinner-like class for parallel running threads This class either directly sets/calls its parent's `.text` or `write()` if `is_current` is set or keeps the lines written around to output them once `is_current` is set or and outside entity uses `flush()`. When `prefix` is set, setting `text` on ...
**kwargs): print(*args, **kwargs) def __getattr__(self, name): return self def __call__(self): pass def __enter__(self): return self def __exit__(self, *args, **kwargs): return False @contextlib.contextmanager def hidden(self): yield class Sp...
82
82
275
4
77
hemna/haminfo
haminfo/spinner.py
Python
SpinnerProxy
SpinnerProxy
61
102
61
61
c6541c56be12f79336798b19e6cd54aa8678c1b5
bigcode/the-stack
train
dbb15abb7e10d10596b5ab3d
train
function
async def main(): adc = ADC(1) while True: #ret = await adc.is_on_hp(audio['hp_l']) #ret = await adc.is_on_hp(audio['hp_r']) ret = await adc.is_off_hp(audio['hp_l']) ret = await adc.is_off_hp(audio['hp_r'])
async def main():
adc = ADC(1) while True: #ret = await adc.is_on_hp(audio['hp_l']) #ret = await adc.is_on_hp(audio['hp_r']) ret = await adc.is_off_hp(audio['hp_l']) ret = await adc.is_off_hp(audio['hp_r'])
pins = GPIO(model) pwrs = pins.pwrs keypads = pins.keypads pin10 = pins.pin10 led_sys = pins.led_sys led_pwr = pins.led_pwr led_chg = pins.led_chg audio = pins.audio async def main():
64
64
69
4
59
charles-park/sbc-jig
agent/test_audio.py
Python
main
main
52
58
52
52
a5f58fbba9b31e50c6da1d3a693e9a9f13d9bcd3
bigcode/the-stack
train
9841b61eb87f0b8185827626
train
function
async def _main(stdscr, adc): # Clear screen stdscr.clear() curses.use_default_colors() curses.init_pair(1, curses.COLOR_YELLOW, -1) curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLUE) curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE) slaves = [0x8, 0x9, 0xa, 0xb, 0x18, 0x19]...
async def _main(stdscr, adc): # Clear screen
stdscr.clear() curses.use_default_colors() curses.init_pair(1, curses.COLOR_YELLOW, -1) curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLUE) curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE) slaves = [0x8, 0x9, 0xa, 0xb, 0x18, 0x19] ch = [0xf, 0xb, 0xe, 0xa, 0xd, 0x9, 0xc, 0x8...
import asyncio from adc import ADC from gpio import GPIO async def _main(stdscr, adc): # Clear screen
28
142
474
15
12
charles-park/sbc-jig
agent/test_audio.py
Python
_main
_main
8
41
8
9
de20f873e0626860f92846d0f8608286167cf740
bigcode/the-stack
train
005de13da00106e143a9a021
train
function
def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('default_account_types', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(), nullable=False), sa.Column('description', sa.Text(), nullable=False), sa.PrimaryKeyConstraint('id') ...
def upgrade(): # ### commands auto generated by Alembic - please adjust! ###
op.create_table('default_account_types', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(), nullable=False), sa.Column('description', sa.Text(), nullable=False), sa.PrimaryKeyConstraint('id') ) op.create_table('account_types', sa.Column('id', sa.Integer(), null...
as sa # revision identifiers, used by Alembic. revision = '2cec471fc310' down_revision = '9f2d4e946acb' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ###
64
64
154
18
45
csdt/Pawi
migrations/versions/2cec471fc310_.py
Python
upgrade
upgrade
19
34
19
20
788fffa31fc045768916ec6aebe0325518aeedd2
bigcode/the-stack
train
ad3afe9c1c548f211c3e9ce9
train
function
def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('account_types') op.drop_table('default_account_types')
def downgrade(): # ### commands auto generated by Alembic - please adjust! ###
op.drop_table('account_types') op.drop_table('default_account_types')
sa.Column('owner_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ###
63
64
35
18
45
csdt/Pawi
migrations/versions/2cec471fc310_.py
Python
downgrade
downgrade
38
41
38
39
95398bd5005493d810b6951a3cb77d7ae6e030aa
bigcode/the-stack
train
d27cefd87b374501216aa9c4
train
function
def extract_val_set_binary(input_data, targets, val_percentage): change_every = 1 / val_percentage # add to val indicies every 1/percentage pos = 0 neg = 0 classes = [pos, neg] train_long_tensor = [] val_long_tensor = [] for t, target in enumerate(targets): int_targ = int(ta...
def extract_val_set_binary(input_data, targets, val_percentage):
change_every = 1 / val_percentage # add to val indicies every 1/percentage pos = 0 neg = 0 classes = [pos, neg] train_long_tensor = [] val_long_tensor = [] for t, target in enumerate(targets): int_targ = int(target[0]) classes[int_targ] += 1 if classes[int_t...
() z.update(y) return z class ResetStatesCallback(callbacks.Callback): def __init__(self): self.current_epoch = 0 def on_batch_begin(self, batch, logs={}): self.model.reset_states() def extract_val_set_binary(input_data, targets, val_percentage):
64
64
192
13
51
burunkus/Linux-Malware-Prediction-Using-RNN
experiments/useful.py
Python
extract_val_set_binary
extract_val_set_binary
257
277
257
257
3b8209a7e2bc87d20c1c078b92e66d8716f0d938
bigcode/the-stack
train
d48f10e19d4e54138aa3be89
train
function
def into_sliding_chunk_arrays(data_x, chunk_size): """return array of data cut into chunks of size chunk_size sliding along array and array of tuples denoting starting index and end index for chunk""" big_X = [] data_temp = array_to_list(data_x) idx_len_tuples = list(range(len(data_temp[0]) - c...
def into_sliding_chunk_arrays(data_x, chunk_size):
"""return array of data cut into chunks of size chunk_size sliding along array and array of tuples denoting starting index and end index for chunk""" big_X = [] data_temp = array_to_list(data_x) idx_len_tuples = list(range(len(data_temp[0]) - chunk_size + 1)) if ids == [] else ids for i i...
sample,timesteps,features) new_y = y.reshape(y.shape[0], 1) return new_x, new_y def array_to_list(arr): try: return arr.tolist() except AttributeError: return arr def into_sliding_chunk_arrays(data_x, chunk_size):
64
64
148
12
51
burunkus/Linux-Malware-Prediction-Using-RNN
experiments/useful.py
Python
into_sliding_chunk_arrays
into_sliding_chunk_arrays
195
208
195
195
0eaa581c4b850fd32e834114249fb5a02ddb4a79
bigcode/the-stack
train
fb640ae810ccab8608079eee
train
function
def scale_array(dataset, means, stdvs): """normalise by means and standard deviations along 0th axis of tensor""" return (dataset - means) / (stdvs + K.epsilon())
def scale_array(dataset, means, stdvs):
"""normalise by means and standard deviations along 0th axis of tensor""" return (dataset - means) / (stdvs + K.epsilon())
return x, y def get_mean_and_stdv(dataset): """return means and standard deviations along 0th axis of tensor""" means = dataset.mean(0) stdvs = dataset.std(0) return means, stdvs def scale_array(dataset, means, stdvs):
64
64
45
10
53
burunkus/Linux-Malware-Prediction-Using-RNN
experiments/useful.py
Python
scale_array
scale_array
67
70
67
67
3f725e1801dbc9e0fb950526601d3955d29d6ee7
bigcode/the-stack
train
a357885f00fa263a85e15a47
train
function
def unison_shuffled_copies(arrays): """shuffle multiple arrays keeping corresponding items in same relative positions between arrays""" # print(len(arrays)) # print(len(arrays[0])) length = len(arrays[1]) # print(length) for x in arrays: # print(x) # print(l...
def unison_shuffled_copies(arrays):
"""shuffle multiple arrays keeping corresponding items in same relative positions between arrays""" # print(len(arrays)) # print(len(arrays[0])) length = len(arrays[1]) # print(length) for x in arrays: # print(x) # print(len(x)) assert len(x) == leng...
import os.path import numpy as np import keras.backend as K from keras import callbacks np.random.seed(5) def unison_shuffled_copies(arrays):
36
64
105
10
26
burunkus/Linux-Malware-Prediction-Using-RNN
experiments/useful.py
Python
unison_shuffled_copies
unison_shuffled_copies
9
24
9
9
50f889876bbcec67f1bcc3500e8b7f7145ef637a
bigcode/the-stack
train
358e2938925a74016faca124
train
function
def get_mean_and_stdv(dataset): """return means and standard deviations along 0th axis of tensor""" means = dataset.mean(0) stdvs = dataset.std(0) return means, stdvs
def get_mean_and_stdv(dataset):
"""return means and standard deviations along 0th axis of tensor""" means = dataset.mean(0) stdvs = dataset.std(0) return means, stdvs
necesary to convert it to one # print(x) # print(x.shape) # print(x.ndim) # print("\n") # print(y) # print(y.shape) # print(y.ndim) return x, y def get_mean_and_stdv(dataset):
64
64
49
8
55
burunkus/Linux-Malware-Prediction-Using-RNN
experiments/useful.py
Python
get_mean_and_stdv
get_mean_and_stdv
59
64
59
59
9739fdbab99e0710a3263d414c5522a415525ac8
bigcode/the-stack
train
1c9d4020e24127ba62408abc
train
function
def remove_short_idx(dataX, dataY, idxs, length): """ Remove any seqences in dataX shorter than length, crop any longer than length, return new X and Y tensors and indicies of the returned samples with refernce to their position in the original array""" new_X = [] new_Y = [] new_idx...
def remove_short_idx(dataX, dataY, idxs, length):
""" Remove any seqences in dataX shorter than length, crop any longer than length, return new X and Y tensors and indicies of the returned samples with refernce to their position in the original array""" new_X = [] new_Y = [] new_idxs = [] for x in list(range(len(dataX))): ...
#if len(dataX[x]) >= length: new_X.append(dataX[x][:length]) new_Y.append(dataY[x][:length]) x, y = to_numpy_tensors(new_X, new_Y) #x, y = to_numpy_tensors(dataX, dataY) return x, y def remove_short_idx(dataX, dataY, idxs, length):
82
82
275
15
66
burunkus/Linux-Malware-Prediction-Using-RNN
experiments/useful.py
Python
remove_short_idx
remove_short_idx
129
162
129
129
e360f55d750449a6d208ee664df85cd6eeaaa09f
bigcode/the-stack
train
1a3c1bd223de52c227b9605c
train
function
def array_to_list(arr): try: return arr.tolist() except AttributeError: return arr
def array_to_list(arr):
try: return arr.tolist() except AttributeError: return arr
from 2D to 3D tensor. which is what the rnn is expecting in the form [sample,timesteps,features](sample,timesteps,features) new_y = y.reshape(y.shape[0], 1) return new_x, new_y def array_to_list(arr):
64
64
23
6
57
burunkus/Linux-Malware-Prediction-Using-RNN
experiments/useful.py
Python
array_to_list
array_to_list
188
192
188
188
641fbecc605961d287f3083f22425a9ac647ecac
bigcode/the-stack
train
d2572bf24f5396f9ed8a05e1
train
function
def merge_two_dicts(x, y): """Given two dicts, merge them into a new dict as a shallow copy. Credit: http://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-expression""" z = x.copy() z.update(y) return z
def merge_two_dicts(x, y):
"""Given two dicts, merge them into a new dict as a shallow copy. Credit: http://stackoverflow.com/questions/38987/how-to-merge-two-python-dictionaries-in-a-single-expression""" z = x.copy() z.update(y) return z
chunks.append(l[i:i + n]) # Extras distributed evenly: for i in range(n * num_chunks, len(l)): chunks[last_one].append(l[i]) last_one = (last_one + 1) % num_chunks return chunks def merge_two_dicts(x, y):
64
64
65
9
54
burunkus/Linux-Malware-Prediction-Using-RNN
experiments/useful.py
Python
merge_two_dicts
merge_two_dicts
242
246
242
242
fcc3bfcd69db2de2209dbe53176f0c3dee46e605
bigcode/the-stack
train
61bc562fbef51e0a99a81209
train
function
def to_numpy_tensors(x, y): """ return x and y as numpy tensors, x as a 3-D tensor, y as a 2-D tensor""" x_shape = (len(x), len(x[0]), len(x[0][0])) y_shape = (len(y), 1) # print(x) # print(x.shape) # print(x.ndim) if type(x) is list: x = np.array(x) if type(y...
def to_numpy_tensors(x, y):
""" return x and y as numpy tensors, x as a 3-D tensor, y as a 2-D tensor""" x_shape = (len(x), len(x[0]), len(x[0][0])) y_shape = (len(y), 1) # print(x) # print(x.shape) # print(x.ndim) if type(x) is list: x = np.array(x) if type(y) is list: y = np.ar...
])) length = len(arrays[1]) # print(length) for x in arrays: # print(x) # print(len(x)) assert len(x) == length p = np.random.permutation(length) return tuple([x[p] for x in arrays]) def to_numpy_tensors(x, y):
70
71
238
9
61
burunkus/Linux-Malware-Prediction-Using-RNN
experiments/useful.py
Python
to_numpy_tensors
to_numpy_tensors
27
56
27
27
0469635b8c4423e8cf08b0c337d149493745473b
bigcode/the-stack
train
1a8b14b10fe58b6aa527d955
train
function
def check_filename(originalName): """ add number to filename to make unique if not already - returns new name""" count = 1 exists = True fileName = originalName while(exists): exists = os.path.exists(fileName) if exists: if "." in originalName: ...
def check_filename(originalName):
""" add number to filename to make unique if not already - returns new name""" count = 1 exists = True fileName = originalName while(exists): exists = os.path.exists(fileName) if exists: if "." in originalName: fileName = originalName.split("....
dataset.std(0) return means, stdvs def scale_array(dataset, means, stdvs): """normalise by means and standard deviations along 0th axis of tensor""" return (dataset - means) / (stdvs + K.epsilon()) def check_filename(originalName):
63
64
125
6
57
burunkus/Linux-Malware-Prediction-Using-RNN
experiments/useful.py
Python
check_filename
check_filename
73
89
73
73
3f9e3101c90cd9f39ad477c9563a14ccfadddaf2
bigcode/the-stack
train