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
6daba915040227a2a31404c3
train
function
async def send_help(message): print("Sending help message") embed = discord.Embed(title="Cardi-P", description="Ahoy mateys, puzzle bot here!") commands = ["!puzzles", "!puzzles solved", "!puzzles stuck"] embed.add_field(name="Commands", value=", ".join(f"`{c}`" for c in commands)) await message.cha...
async def send_help(message):
print("Sending help message") embed = discord.Embed(title="Cardi-P", description="Ahoy mateys, puzzle bot here!") commands = ["!puzzles", "!puzzles solved", "!puzzles stuck"] embed.add_field(name="Commands", value=", ".join(f"`{c}`" for c in commands)) await message.channel.send(embed=embed)
25: await message.channel.send(embed=embed) embed = discord.Embed(title=title) field_count = 0 embed.add_field(name=line_title, value=line, inline=True) field_count += 1 await message.channel.send(embed=embed) async def send_help(message):
64
64
86
6
58
brentisreallyme/smallboard
chat/management/commands/rundiscordbot.py
Python
send_help
send_help
110
115
110
110
05888521868f4322c147a3f6b63eeb0180b75902
bigcode/the-stack
train
890f26035f740dc016ef6dfb
train
function
def parse_subcommand(message_content): tokens = message_content.split() return tokens[1] if len(tokens) > 1 else None
def parse_subcommand(message_content):
tokens = message_content.split() return tokens[1] if len(tokens) > 1 else None
== client.user: return print(f'{message.channel}/{message.author}: "{message.content}"') if message.content.startswith("!puzzles"): subcommand = parse_subcommand(message.content) or "unsolved" await handle_subcommand(message, subcommand) def parse_subcommand(message_content):
64
64
30
7
57
brentisreallyme/smallboard
chat/management/commands/rundiscordbot.py
Python
parse_subcommand
parse_subcommand
27
29
27
27
1435c6b2773812bcac4c90d37857172d925b131e
bigcode/the-stack
train
bb77c823f540c4912d3de6df
train
function
async def send_puzzles_solved(message): puzzles = await sync_to_async(list)( Puzzle.objects.filter( hunt=settings.BOT_ACTIVE_HUNT, status=Puzzle.SOLVED ).select_related("chat_room") ) await send_puzzles(message, puzzles, "Solved puzzles")
async def send_puzzles_solved(message):
puzzles = await sync_to_async(list)( Puzzle.objects.filter( hunt=settings.BOT_ACTIVE_HUNT, status=Puzzle.SOLVED ).select_related("chat_room") ) await send_puzzles(message, puzzles, "Solved puzzles")
( Q(hunt=settings.BOT_ACTIVE_HUNT), Q(status=Puzzle.SOLVING) | Q(status=Puzzle.PENDING), ).select_related("chat_room") ) await send_puzzles(message, puzzles, "Unsolved puzzles") async def send_puzzles_solved(message):
64
64
62
9
55
brentisreallyme/smallboard
chat/management/commands/rundiscordbot.py
Python
send_puzzles_solved
send_puzzles_solved
52
58
52
52
e1f3df7cac88d691aca44cda6eae8d4e236ed21a
bigcode/the-stack
train
079ad83e3c36fe82c26a5ddd
train
class
class Command(BaseCommand): help = "Starts a Discord chat bot for interacting with Smallboard." def handle(self, *args, **options): self.stdout.write("Starting Discord bot") client.run(settings.DISCORD_API_TOKEN)
class Command(BaseCommand):
help = "Starts a Discord chat bot for interacting with Smallboard." def handle(self, *args, **options): self.stdout.write("Starting Discord bot") client.run(settings.DISCORD_API_TOKEN)
Ahoy mateys, puzzle bot here!") commands = ["!puzzles", "!puzzles solved", "!puzzles stuck"] embed.add_field(name="Commands", value=", ".join(f"`{c}`" for c in commands)) await message.channel.send(embed=embed) class Command(BaseCommand):
64
64
49
5
59
brentisreallyme/smallboard
chat/management/commands/rundiscordbot.py
Python
Command
Command
118
123
118
118
6114a1bea93dcc33bce3e0b92c2aeb5d97f2887d
bigcode/the-stack
train
f533978d228136a0bec71746
train
function
@client.event async def on_message(message): if message.author == client.user: return print(f'{message.channel}/{message.author}: "{message.content}"') if message.content.startswith("!puzzles"): subcommand = parse_subcommand(message.content) or "unsolved" await handle_subcommand(mess...
@client.event async def on_message(message):
if message.author == client.user: return print(f'{message.channel}/{message.author}: "{message.content}"') if message.content.startswith("!puzzles"): subcommand = parse_subcommand(message.content) or "unsolved" await handle_subcommand(message, subcommand)
from django.core.management.base import BaseCommand, CommandError from django.db.models import Q import discord from puzzles.models import Puzzle client = discord.Client() @client.event async def on_ready(): print(f'Logged in as "{client.user}"') @client.event async def on_message(message):
64
64
71
10
54
brentisreallyme/smallboard
chat/management/commands/rundiscordbot.py
Python
on_message
on_message
17
24
17
18
937cb85f108536f8e2e69c8a51c4db208a5c1f3f
bigcode/the-stack
train
317c0070e262806e55aa8c25
train
function
async def send_puzzles(message, puzzles, title): print(f"Sending puzzles {puzzles}") lines_with_titles = [] for p in puzzles: line_title = "" if p.is_solved(): line_title += f"[{p.answer}] " line_title += p.name line = "" if p.url: line += f"[...
async def send_puzzles(message, puzzles, title):
print(f"Sending puzzles {puzzles}") lines_with_titles = [] for p in puzzles: line_title = "" if p.is_solved(): line_title += f"[{p.answer}] " line_title += p.name line = "" if p.url: line += f"[Puzzle]({p.url}) " if p.sheet: ...
("chat_room") ) await send_puzzles(message, puzzles, "Solved puzzles") async def send_puzzles_stuck(message): puzzles = await sync_to_async(list)( Puzzle.objects.filter( Q(hunt=settings.BOT_ACTIVE_HUNT), Q(status=Puzzle.STUCK) | Q(status=Puzzle.EXTRACTION), ).select...
104
104
349
11
93
brentisreallyme/smallboard
chat/management/commands/rundiscordbot.py
Python
send_puzzles
send_puzzles
71
107
71
71
c40097895556cc017eecdf46de3a1f98a851eadd
bigcode/the-stack
train
4157ebc929d31e1dd92603ae
train
function
async def handle_subcommand(message, subcommand): # Dispatch corresponding message response or default to help text. handle = { "unsolved": send_puzzles_unsolved, "solved": send_puzzles_solved, "stuck": send_puzzles_stuck, }.get(subcommand, send_help) await handle(message)
async def handle_subcommand(message, subcommand): # Dispatch corresponding message response or default to help text.
handle = { "unsolved": send_puzzles_unsolved, "solved": send_puzzles_solved, "stuck": send_puzzles_stuck, }.get(subcommand, send_help) await handle(message)
olved" await handle_subcommand(message, subcommand) def parse_subcommand(message_content): tokens = message_content.split() return tokens[1] if len(tokens) > 1 else None async def handle_subcommand(message, subcommand): # Dispatch corresponding message response or default to help text.
64
64
73
22
41
brentisreallyme/smallboard
chat/management/commands/rundiscordbot.py
Python
handle_subcommand
handle_subcommand
32
39
32
33
366e6d018c704841b71f214feab1bde2c7ee066a
bigcode/the-stack
train
deef9f75ec73df5acf0ca211
train
function
def main_handler(event, context): environ = create_environ(event, context,path_reserved) response = get_response(app, environ) return wrap_response(response)
def main_handler(event, context):
environ = create_environ(event, context,path_reserved) response = get_response(app, environ) return wrap_response(response)
的前缀 #例如https://service-*******.ap-shanghai.apigateway.myqcloud.com/release/sample_path app = Flask(__name__) app.config['SECRET_KEY'] = '123456' @app.route('/') def index(): return "Hello World" def main_handler(event, context):
64
64
34
7
57
LiuChangFreeman/flask-serverless-tencent
main.py
Python
main_handler
main_handler
15
18
15
15
a74de550e2999fcd5233b109671e1415e23917e8
bigcode/the-stack
train
b5d968fbd8ad3383ab0d6edb
train
function
@app.route('/') def index(): return "Hello World"
@app.route('/') def index():
return "Hello World"
" #api网关触发器中访问路径自带的前缀 #例如https://service-*******.ap-shanghai.apigateway.myqcloud.com/release/sample_path app = Flask(__name__) app.config['SECRET_KEY'] = '123456' @app.route('/') def index():
64
64
12
6
58
LiuChangFreeman/flask-serverless-tencent
main.py
Python
index
index
11
13
11
12
8f240e9670a481db884b20693088292d2edf8d2d
bigcode/the-stack
train
8a1fcc87e57f7a85eb9bd6ac
train
class
class AppendStepWithVariable(AppendStep, StepWithVariablesMixin): ...
class AppendStepWithVariable(AppendStep, StepWithVariablesMixin):
...
.render_variables import StepWithVariablesMixin from .utils.combination import PipelineOrDomainNameOrReference class AppendStep(BaseStep): name: Literal['append'] = 'append' pipelines: List[PipelineOrDomainNameOrReference] class AppendStepWithVariable(AppendStep, StepWithVariablesMixin):
64
64
16
14
50
ToucanToco/vue-query-builder
server/src/weaverbird/pipeline/steps/append.py
Python
AppendStepWithVariable
AppendStepWithVariable
14
15
14
14
281c90100e4783cc8dcf89353c438eb2df0f3309
bigcode/the-stack
train
584007cfd4580f27755872fd
train
class
class AppendStep(BaseStep): name: Literal['append'] = 'append' pipelines: List[PipelineOrDomainNameOrReference]
class AppendStep(BaseStep):
name: Literal['append'] = 'append' pipelines: List[PipelineOrDomainNameOrReference]
from typing import List, Literal from weaverbird.pipeline.steps.utils.base import BaseStep from weaverbird.pipeline.steps.utils.render_variables import StepWithVariablesMixin from .utils.combination import PipelineOrDomainNameOrReference class AppendStep(BaseStep):
53
64
29
6
46
ToucanToco/vue-query-builder
server/src/weaverbird/pipeline/steps/append.py
Python
AppendStep
AppendStep
9
11
9
9
f8f7c2cf416715d2253a1502bacd852f423108d7
bigcode/the-stack
train
63fe8f93fd29801b499b993f
train
class
class TestMisc: @pytest.mark.asyncio async def test_format_bytes(self): assert format_bytes(None) == "Invalid" assert format_bytes(dict()) == "Invalid" assert format_bytes("some bytes") == "Invalid" assert format_bytes(-1024) == "Invalid" assert format_bytes(0) == "0.000 ...
class TestMisc: @pytest.mark.asyncio
async def test_format_bytes(self): assert format_bytes(None) == "Invalid" assert format_bytes(dict()) == "Invalid" assert format_bytes("some bytes") == "Invalid" assert format_bytes(-1024) == "Invalid" assert format_bytes(0) == "0.000 MiB" assert format_bytes(1024) ==...
import pytest from cunt.util.misc import format_bytes from cunt.util.misc import format_minutes class TestMisc: @pytest.mark.asyncio
30
193
645
11
18
CallMeBrado/cunt-blockchain
tests/util/misc.py
Python
TestMisc
TestMisc
6
52
6
7
e55f6839fa5d0403654ce0043aa7403678654364
bigcode/the-stack
train
f485b43f336b51f2c77634cf
train
class
class TestReporter: def test_build_report(self): reporter = Reporter() dt = datetime.fromisoformat("2012-12-12T12:12:00+00:00") metric = Metric(measurement="test", datetime=dt, value=123.456789) report = reporter._build_report([metric]) assert list(report.keys()).sort() == ...
class TestReporter:
def test_build_report(self): reporter = Reporter() dt = datetime.fromisoformat("2012-12-12T12:12:00+00:00") metric = Metric(measurement="test", datetime=dt, value=123.456789) report = reporter._build_report([metric]) assert list(report.keys()).sort() == ["config", "dyno", "...
from judoscale.core.reporter import Reporter from judoscale.core.metric import Metric from datetime import datetime class TestReporter:
28
64
132
4
23
judoscale/judoscale-python
test/judoscale/reporter_test.py
Python
TestReporter
TestReporter
6
16
6
6
a20c3f76d0aba26106a1552bbdd79242bb220244
bigcode/the-stack
train
9cd8f95e4c69c770daf3d42c
train
function
def rnn_zero_state(batch_size, hidden_dim, num_layers, use_cuda, bidirectional=True): total_layers = num_layers * 2 if bidirectional else num_layers state_shape = (total_layers, batch_size, hidden_dim) h0 = c0 = Variable(torch.zeros(*state_shape), requires_grad=False) if use_cuda: return h0.cuda...
def rnn_zero_state(batch_size, hidden_dim, num_layers, use_cuda, bidirectional=True):
total_layers = num_layers * 2 if bidirectional else num_layers state_shape = (total_layers, batch_size, hidden_dim) h0 = c0 = Variable(torch.zeros(*state_shape), requires_grad=False) if use_cuda: return h0.cuda(), c0.cuda() else: return h0.cpu(), c0.cpu()
return h.sum(1) / (mask.size(1) - mask.float().sum(1)) else: h = h.masked_fill(mask, 0) return h.sum(1) def rnn_zero_state(batch_size, hidden_dim, num_layers, use_cuda, bidirectional=True):
64
64
97
21
43
ChrisjanWust/AGGCN
model/aggcn.py
Python
rnn_zero_state
rnn_zero_state
300
307
300
300
13a7c3da6e075c0d37a94adf05c9aa58d4d1f9aa
bigcode/the-stack
train
ec6235529c9fac94aee48cb0
train
class
class GraphConvLayer(nn.Module): """ A GCN module operated on dependency graphs. """ def __init__(self, opt, mem_dim, layers): super(GraphConvLayer, self).__init__() self.opt = opt self.mem_dim = mem_dim self.layers = layers self.head_dim = self.mem_dim // self.layers ...
class GraphConvLayer(nn.Module):
""" A GCN module operated on dependency graphs. """ def __init__(self, opt, mem_dim, layers): super(GraphConvLayer, self).__init__() self.opt = opt self.mem_dim = mem_dim self.layers = layers self.head_dim = self.mem_dim // self.layers self.gcn_drop = nn.Dropout(...
: attn_tensor = self.attn(outputs, outputs, src_mask) attn_adj_list = [attn_adj.squeeze(1) for attn_adj in torch.split(attn_tensor, 1, dim=1)] outputs = self.layers[i](attn_adj_list, outputs) layer_list.append(outputs) aggregate_out = torch.cat(la...
110
110
368
7
102
ChrisjanWust/AGGCN
model/aggcn.py
Python
GraphConvLayer
GraphConvLayer
186
231
186
186
f5898dc2b65241078a3ddb1155e648ee162dcda6
bigcode/the-stack
train
9e5f8ae4c2a9012e72d7d357
train
class
class GCNClassifier(nn.Module): """ A wrapper classifier for GCNRelationModel. """ def __init__(self, opt, emb_matrix=None): super().__init__() self.gcn_model = GCNRelationModel(opt, emb_matrix=emb_matrix) in_dim = opt['hidden_dim'] self.classifier = nn.Linear(in_dim, opt['num_c...
class GCNClassifier(nn.Module):
""" A wrapper classifier for GCNRelationModel. """ def __init__(self, opt, emb_matrix=None): super().__init__() self.gcn_model = GCNRelationModel(opt, emb_matrix=emb_matrix) in_dim = opt['hidden_dim'] self.classifier = nn.Linear(in_dim, opt['num_class']) self.opt = opt ...
extraction. """ import copy import math import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np from model.tree import head_to_tree, tree_to_adj from utils import constant, torch_utils class GCNClassifier(nn.Module):
64
64
119
7
56
ChrisjanWust/AGGCN
model/aggcn.py
Python
GCNClassifier
GCNClassifier
17
30
17
17
c06557c39f921fecde5b67e6d53210096abb205e
bigcode/the-stack
train
6bebdaf3102052d5b2d2ac9b
train
function
def attention(query, key, mask=None, dropout=None): d_k = query.size(-1) scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k) if mask is not None: scores = scores.masked_fill(mask == 0, -1e9) p_attn = F.softmax(scores, dim=-1) if dropout is not None: p_attn = dropout...
def attention(query, key, mask=None, dropout=None):
d_k = query.size(-1) scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k) if mask is not None: scores = scores.masked_fill(mask == 0, -1e9) p_attn = F.softmax(scores, dim=-1) if dropout is not None: p_attn = dropout(p_attn) return p_attn
batch_size, hidden_dim) h0 = c0 = Variable(torch.zeros(*state_shape), requires_grad=False) if use_cuda: return h0.cuda(), c0.cuda() else: return h0.cpu(), c0.cpu() def attention(query, key, mask=None, dropout=None):
64
64
102
12
52
ChrisjanWust/AGGCN
model/aggcn.py
Python
attention
attention
311
321
311
311
00fc3fb6e3b13b68effe00391e48fb4b6ebf9278
bigcode/the-stack
train
b0928c07ea3c90f4c8973dc4
train
class
class GCNRelationModel(nn.Module): def __init__(self, opt, emb_matrix=None): super().__init__() self.opt = opt self.emb_matrix = emb_matrix # create embedding layers self.emb = nn.Embedding(opt['vocab_size'], opt['emb_dim'], padding_idx=constant.PAD_ID) self.pos_emb ...
class GCNRelationModel(nn.Module):
def __init__(self, opt, emb_matrix=None): super().__init__() self.opt = opt self.emb_matrix = emb_matrix # create embedding layers self.emb = nn.Embedding(opt['vocab_size'], opt['emb_dim'], padding_idx=constant.PAD_ID) self.pos_emb = nn.Embedding(len(constant.POS_TO_...
""" GCN model for relation extraction. """ import copy import math import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np from model.tree import head_to_tree, tree_to_adj from utils import constant, torch_utils class GCNClassifier(nn.Module): ""...
190
224
747
8
181
ChrisjanWust/AGGCN
model/aggcn.py
Python
GCNRelationModel
GCNRelationModel
33
96
33
33
12bc532e65f852e02d18cb6d0becf2e095ca2b16
bigcode/the-stack
train
e276dd170f48085edcf5dbc8
train
class
class MultiHeadAttention(nn.Module): def __init__(self, h, d_model, dropout=0.1): super(MultiHeadAttention, self).__init__() assert d_model % h == 0 self.d_k = d_model // h self.h = h self.linears = clones(nn.Linear(d_model, d_model), 2) self.dropout = nn.Dropout(p=...
class MultiHeadAttention(nn.Module):
def __init__(self, h, d_model, dropout=0.1): super(MultiHeadAttention, self).__init__() assert d_model % h == 0 self.d_k = d_model // h self.h = h self.linears = clones(nn.Linear(d_model, d_model), 2) self.dropout = nn.Dropout(p=dropout) def forward(self, query,...
_attn = F.softmax(scores, dim=-1) if dropout is not None: p_attn = dropout(p_attn) return p_attn def clones(module, N): return nn.ModuleList([copy.deepcopy(module) for _ in range(N)]) class MultiHeadAttention(nn.Module):
63
64
195
7
56
ChrisjanWust/AGGCN
model/aggcn.py
Python
MultiHeadAttention
MultiHeadAttention
328
349
328
329
a8ca378bfe247993af24a4239545a64b3c5de421
bigcode/the-stack
train
b599a6745ebaea9edcdf5b95
train
class
class MultiGraphConvLayer(nn.Module): """ A GCN module operated on dependency graphs. """ def __init__(self, opt, mem_dim, layers, heads): super(MultiGraphConvLayer, self).__init__() self.opt = opt self.mem_dim = mem_dim self.layers = layers self.head_dim = self.mem_dim ...
class MultiGraphConvLayer(nn.Module):
""" A GCN module operated on dependency graphs. """ def __init__(self, opt, mem_dim, layers, heads): super(MultiGraphConvLayer, self).__init__() self.opt = opt self.mem_dim = mem_dim self.layers = layers self.head_dim = self.mem_dim // self.layers self.heads = he...
) AxW = self.weight_list[l](Ax) AxW = AxW + self.weight_list[l](outputs) # self loop AxW = AxW / denom gAxW = F.relu(AxW) cache_list.append(gAxW) outputs = torch.cat(cache_list, dim=2) output_list.append(self.gcn_drop(gAxW)) g...
132
132
441
8
123
ChrisjanWust/AGGCN
model/aggcn.py
Python
MultiGraphConvLayer
MultiGraphConvLayer
234
285
234
234
a94d02e8ee2f75e26d06a4681dfefe34daeaa620
bigcode/the-stack
train
8894625f0da0beba83977aa1
train
function
def pool(h, mask, type='max'): if type == 'max': h = h.masked_fill(mask, -constant.INFINITY_NUMBER) return torch.max(h, 1)[0] elif type == 'avg': h = h.masked_fill(mask, 0) return h.sum(1) / (mask.size(1) - mask.float().sum(1)) else: h = h.masked_fill(mask, 0) ...
def pool(h, mask, type='max'):
if type == 'max': h = h.masked_fill(mask, -constant.INFINITY_NUMBER) return torch.max(h, 1)[0] elif type == 'avg': h = h.masked_fill(mask, 0) return h.sum(1) / (mask.size(1) - mask.float().sum(1)) else: h = h.masked_fill(mask, 0) return h.sum(1)
gcn_ouputs = gcn_ouputs + gcn_inputs multi_head_list.append(gcn_ouputs) final_output = torch.cat(multi_head_list, dim=2) out = self.Linear(final_output) return out def pool(h, mask, type='max'):
64
64
106
10
53
ChrisjanWust/AGGCN
model/aggcn.py
Python
pool
pool
288
297
288
288
0b311cfd8cec81e89f990c42732671d091230fd6
bigcode/the-stack
train
fcf6b2160fc487e40d61022d
train
class
class AGGCN(nn.Module): def __init__(self, opt, embeddings): super().__init__() self.opt = opt self.in_dim = opt['emb_dim'] + opt['pos_dim'] + opt['ner_dim'] self.emb, self.pos_emb, self.ner_emb = embeddings self.use_cuda = opt['cuda'] self.mem_dim = opt['hidden_dim']...
class AGGCN(nn.Module):
def __init__(self, opt, embeddings): super().__init__() self.opt = opt self.in_dim = opt['emb_dim'] + opt['pos_dim'] + opt['ner_dim'] self.emb, self.pos_emb, self.ner_emb = embeddings self.use_cuda = opt['cuda'] self.mem_dim = opt['hidden_dim'] # rnn layer ...
max(l) def inputs_to_tree_reps(head, l): trees = [head_to_tree(head[i], l[i]) for i in range(len(l))] adj = [tree_to_adj(maxlen, tree, directed=False).reshape(1, maxlen, maxlen) for tree in trees] adj = np.concatenate(adj, axis=0) adj = torch.from_numpy(adj) ...
256
256
980
7
248
ChrisjanWust/AGGCN
model/aggcn.py
Python
AGGCN
AGGCN
99
183
99
99
a1f952b3d791786c9db54a6c5982680d1ac6fb6a
bigcode/the-stack
train
387f3d9592d993b5fa4a0697
train
function
def clones(module, N): return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])
def clones(module, N):
return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])
mask is not None: scores = scores.masked_fill(mask == 0, -1e9) p_attn = F.softmax(scores, dim=-1) if dropout is not None: p_attn = dropout(p_attn) return p_attn def clones(module, N):
64
64
22
6
57
ChrisjanWust/AGGCN
model/aggcn.py
Python
clones
clones
324
325
324
324
0d5d062d04b0927db1a3ce6af8c2789e681e1dee
bigcode/the-stack
train
808d9939abac57d76210dfc2
train
function
def getTimes(rgbImg): start = time.time() bb = align.getLargestFaceBoundingBox(rgbImg) if bb is None: raise Exception("Unable to find a face.") detectionTime = time.time() - start start = time.time() alignedFace = align.align(args.imgDim, rgbImg, bb, ...
def getTimes(rgbImg):
start = time.time() bb = align.getLargestFaceBoundingBox(rgbImg) if bb is None: raise Exception("Unable to find a face.") detectionTime = time.time() - start start = time.time() alignedFace = align.align(args.imgDim, rgbImg, bb, landmarkIndices=op...
openface.AlignDlib(args.dlibFacePredictor) net = openface.TorchNeuralNet(args.networkModel, args.imgDim) print("Loading the dlib and OpenFace models took {:0.4f} seconds.".format( time.time() - start)) def getTimes(rgbImg):
63
64
134
6
57
sharmasaravanan/openface-Verification
util/profile-pipeline.py
Python
getTimes
getTimes
62
78
62
62
b4ef09f256d268151a01d61d5eaa227f60289d17
bigcode/the-stack
train
d8383eb28042c58f855d3745
train
class
class TestCommon(TestCase): def create_app(self): return create_app('testing') def test_status_ok(self): response = self.client.get('/v1/status') assert response.json == dict(status='ok'), \ 'status value should be "ok"'
class TestCommon(TestCase):
def create_app(self): return create_app('testing') def test_status_ok(self): response = self.client.get('/v1/status') assert response.json == dict(status='ok'), \ 'status value should be "ok"'
from flask import Flask from flask_testing import TestCase from app import create_app class TestCommon(TestCase):
24
64
58
6
17
davidmogar/cucco-api
tests/api/test_common.py
Python
TestCommon
TestCommon
6
15
6
7
c2e2a284475fe63f59494f28b0a774a500c02778
bigcode/the-stack
train
e082886dc39d7da6bd85c651
train
class
class InstanceDeployFailure(IronicException): message = _("Failed to deploy instance: %(reason)s")
class InstanceDeployFailure(IronicException):
message = _("Failed to deploy instance: %(reason)s")
ctxt.reraise = False super(IronicException, self).__init__(message) def format_message(self): if self.__class__.__name__.endswith('_Remote'): return self.args[0] else: return six.text_type(self) class InstanceDeployFailure(IronicException):
64
64
21
8
56
NaohiroTamura/ironic-lib
ironic_lib/exception.py
Python
InstanceDeployFailure
InstanceDeployFailure
96
97
96
96
e1d1357c6382d313dc66992b06c9d3292b6534e7
bigcode/the-stack
train
2a5380f54e9cd657e4349737
train
class
class IronicException(Exception): """Base Ironic Exception To correctly use this class, inherit from it and define a 'message' property. That message will get printf'd with the keyword arguments provided to the constructor. """ message = _("An unknown exception occurred.") code = 500 h...
class IronicException(Exception):
"""Base Ironic Exception To correctly use this class, inherit from it and define a 'message' property. That message will get printf'd with the keyword arguments provided to the constructor. """ message = _("An unknown exception occurred.") code = 500 headers = {} safe = False ...
import excutils from ironic_lib.common.i18n import _ from ironic_lib.common.i18n import _LE LOG = logging.getLogger(__name__) exc_log_opts = [ cfg.BoolOpt('fatal_exception_format_errors', default=False, help='Make exception message format errors fatal.', deprecat...
93
93
313
6
87
NaohiroTamura/ironic-lib
ironic_lib/exception.py
Python
IronicException
IronicException
48
93
48
48
531d614a8724a272334de57c48980e066db41679
bigcode/the-stack
train
d272388ec18558a16fdded3d
train
class
class InvalidMetricConfig(IronicException): message = _("Invalid value for metrics config option: %(reason)s")
class InvalidMetricConfig(IronicException):
message = _("Invalid value for metrics config option: %(reason)s")
(self) class InstanceDeployFailure(IronicException): message = _("Failed to deploy instance: %(reason)s") class FileSystemNotSupported(IronicException): message = _("Failed to create a file system. " "File system %(fs)s is not supported.") class InvalidMetricConfig(IronicException):
63
64
23
8
55
NaohiroTamura/ironic-lib
ironic_lib/exception.py
Python
InvalidMetricConfig
InvalidMetricConfig
105
106
105
105
c6254ffdfe910802d74a86e4bacfd6b52b1c401a
bigcode/the-stack
train
fbdfee711e7699f120a30a47
train
class
class FileSystemNotSupported(IronicException): message = _("Failed to create a file system. " "File system %(fs)s is not supported.")
class FileSystemNotSupported(IronicException):
message = _("Failed to create a file system. " "File system %(fs)s is not supported.")
format_message(self): if self.__class__.__name__.endswith('_Remote'): return self.args[0] else: return six.text_type(self) class InstanceDeployFailure(IronicException): message = _("Failed to deploy instance: %(reason)s") class FileSystemNotSupported(IronicException):
64
64
32
9
55
NaohiroTamura/ironic-lib
ironic_lib/exception.py
Python
FileSystemNotSupported
FileSystemNotSupported
100
102
100
100
d27e18fb023c41ffc56f9c8c9a2a52816eab4830
bigcode/the-stack
train
3172161718e52db819108acc
train
class
class EABackedBlock(Block): """ Mixin for Block subclasses backed by ExtensionArray. """ values: ExtensionArray def setitem(self, indexer, value): """ Attempt self.values[indexer] = value, possibly creating a new array. This differs from Block.setitem by not allowing setit...
class EABackedBlock(Block):
""" Mixin for Block subclasses backed by ExtensionArray. """ values: ExtensionArray def setitem(self, indexer, value): """ Attempt self.values[indexer] = value, possibly creating a new array. This differs from Block.setitem by not allowing setitem to change the dty...
placement=bp)] return blocks, mask @final def quantile( self, qs: Float64Index, interpolation="linear", axis: int = 0 ) -> Block: """ compute the quantiles of the Parameters ---------- qs : Float64Index List of the quantiles to be comput...
256
256
1,260
7
249
bram2000/pandas
pandas/core/internals/blocks.py
Python
EABackedBlock
EABackedBlock
1,347
1,518
1,347
1,347
a77e018cf5521ad67c087b4ab9130e2dcc640c2f
bigcode/the-stack
train
b76123ce12db53d99f464604
train
function
def get_block_type(dtype: DtypeObj): """ Find the appropriate Block subclass to use for the given values and dtype. Parameters ---------- dtype : numpy or pandas dtype Returns ------- cls : class, subclass of Block """ # We use vtype and kind checks because they are much more p...
def get_block_type(dtype: DtypeObj):
""" Find the appropriate Block subclass to use for the given values and dtype. Parameters ---------- dtype : numpy or pandas dtype Returns ------- cls : class, subclass of Block """ # We use vtype and kind checks because they are much more performant # than is_foo_dtype ...
(values.dtype.type, str): values = np.array(values, dtype=object) if isinstance(values, (DatetimeArray, TimedeltaArray)) and values.freq is not None: # freq is only stored in DatetimeIndex/TimedeltaIndex, not in Series/DataFrame values = values._with_freq(None) return values def ge...
82
82
274
10
71
bram2000/pandas
pandas/core/internals/blocks.py
Python
get_block_type
get_block_type
2,009
2,047
2,009
2,009
15b98b0464c4b722c2f72f544d10abb998f11065
bigcode/the-stack
train
34e91acfdb2b4c29069feaa3
train
function
def new_block(values, placement, *, ndim: int) -> Block: # caller is responsible for ensuring values is NOT a PandasArray if not isinstance(placement, BlockPlacement): placement = BlockPlacement(placement) check_ndim(values, placement, ndim) klass = get_block_type(values.dtype) values = ...
def new_block(values, placement, *, ndim: int) -> Block: # caller is responsible for ensuring values is NOT a PandasArray
if not isinstance(placement, BlockPlacement): placement = BlockPlacement(placement) check_ndim(values, placement, ndim) klass = get_block_type(values.dtype) values = maybe_coerce_values(values) return klass(values, ndim=ndim, placement=placement)
already checked klass = get_block_type(values.dtype) values = maybe_coerce_values(values) return klass(values, ndim=2, placement=placement) def new_block(values, placement, *, ndim: int) -> Block: # caller is responsible for ensuring values is NOT a PandasArray
64
64
90
30
34
bram2000/pandas
pandas/core/internals/blocks.py
Python
new_block
new_block
2,061
2,072
2,061
2,063
46e64719bd265f49c409e6c327531e16be41577e
bigcode/the-stack
train
fe5893dc5d72df6cc82bd5af
train
class
class DatetimeLikeBlock(NDArrayBackedExtensionBlock): """Block for datetime64[ns], timedelta64[ns].""" __slots__ = () is_numeric = False values: DatetimeArray | TimedeltaArray def values_for_json(self) -> np.ndarray: # special casing datetimetz to avoid conversion through # object...
class DatetimeLikeBlock(NDArrayBackedExtensionBlock):
"""Block for datetime64[ns], timedelta64[ns].""" __slots__ = () is_numeric = False values: DatetimeArray | TimedeltaArray def values_for_json(self) -> np.ndarray: # special casing datetimetz to avoid conversion through # object dtype return self.values._ndarray
ValueError): # TODO(2.0): once DTA._validate_setitem_value deprecation # is enforced, stop catching ValueError here altogether if "Timezones don't match" not in str(err): raise class DatetimeLikeBlock(NDArrayBackedExtensionBlock):
64
64
90
13
50
bram2000/pandas
pandas/core/internals/blocks.py
Python
DatetimeLikeBlock
DatetimeLikeBlock
1,889
1,899
1,889
1,889
82bbed4e1710ac7aa8108452673fbe38cbad8d97
bigcode/the-stack
train
08a056f36f3570e995fc5382
train
function
def extend_blocks(result, blocks=None) -> list[Block]: """return a new extended blocks, given the result""" if blocks is None: blocks = [] if isinstance(result, list): for r in result: if isinstance(r, list): blocks.extend(r) else: bloc...
def extend_blocks(result, blocks=None) -> list[Block]:
"""return a new extended blocks, given the result""" if blocks is None: blocks = [] if isinstance(result, list): for r in result: if isinstance(r, list): blocks.extend(r) else: blocks.append(r) else: assert isinstance(result...
D): special case not needed with 2D EAs values = np.atleast_2d(values) if isinstance(dtype, PandasDtype): dtype = dtype.numpy_dtype return values, dtype # ----------------------------------------------------------------- def extend_blocks(result, blocks=None) -> list[Block]:
63
64
90
13
50
bram2000/pandas
pandas/core/internals/blocks.py
Python
extend_blocks
extend_blocks
2,139
2,152
2,139
2,139
b2ca40a91fbc30823b8a1f4ab6e867c1590c32e9
bigcode/the-stack
train
bc116b17d3aeadf438faf87f
train
function
def _catch_deprecated_value_error(err: Exception) -> None: """ We catch ValueError for now, but only a specific one raised by DatetimeArray which will no longer be raised in version.2.0. """ if isinstance(err, ValueError): # TODO(2.0): once DTA._validate_setitem_value deprecation # ...
def _catch_deprecated_value_error(err: Exception) -> None:
""" We catch ValueError for now, but only a specific one raised by DatetimeArray which will no longer be raised in version.2.0. """ if isinstance(err, ValueError): # TODO(2.0): once DTA._validate_setitem_value deprecation # is enforced, stop catching ValueError here altogether ...
.coerce_to_target_dtype(value).fillna( value, limit, inplace, downcast ) new_values = self.values.fillna(value=value, limit=limit) return [self.make_block_same_class(values=new_values)] def _catch_deprecated_value_error(err: Exception) -> None:
63
64
107
14
49
bram2000/pandas
pandas/core/internals/blocks.py
Python
_catch_deprecated_value_error
_catch_deprecated_value_error
1,877
1,886
1,877
1,877
7f01b9c94a0541c67ea999858a6f013fda4e6872
bigcode/the-stack
train
c0fa84326bb56047a3002831
train
class
class ObjectBlock(NumpyBlock): __slots__ = () is_object = True @maybe_split def reduce(self, func, ignore_failures: bool = False) -> list[Block]: """ For object-dtype, we operate column-wise. """ assert self.ndim == 2 try: res = func(self.values) ...
class ObjectBlock(NumpyBlock):
__slots__ = () is_object = True @maybe_split def reduce(self, func, ignore_failures: bool = False) -> list[Block]: """ For object-dtype, we operate column-wise. """ assert self.ndim == 2 try: res = func(self.values) except TypeError: ...
_json(self) -> np.ndarray: # special casing datetimetz to avoid conversion through # object dtype return self.values._ndarray class DatetimeTZBlock(DatetimeLikeBlock): """implement a datetime64 block with a tz attribute""" values: DatetimeArray __slots__ = () is_extension = ...
99
99
330
7
91
bram2000/pandas
pandas/core/internals/blocks.py
Python
ObjectBlock
ObjectBlock
1,913
1,962
1,913
1,913
abf2d2d594aa9e91ad3b9ed1f8a9d730ce98f4e0
bigcode/the-stack
train
8840c35fd0c7a2aa05a1d94f
train
class
class CategoricalBlock(ExtensionBlock): # this Block type is kept for backwards-compatibility __slots__ = () # GH#43232, GH#43334 self.values.dtype can be changed inplace until 2.0, # so this cannot be cached @property def dtype(self) -> DtypeObj: return self.values.dtype
class CategoricalBlock(ExtensionBlock): # this Block type is kept for backwards-compatibility
__slots__ = () # GH#43232, GH#43334 self.values.dtype can be changed inplace until 2.0, # so this cannot be cached @property def dtype(self) -> DtypeObj: return self.values.dtype
numeric=numeric, timedelta=timedelta, copy=copy, ) res_values = ensure_block_shape(res_values, self.ndim) return [self.make_block(res_values)] class CategoricalBlock(ExtensionBlock): # this Block type is kept for backwards-compatibility
63
64
80
21
42
bram2000/pandas
pandas/core/internals/blocks.py
Python
CategoricalBlock
CategoricalBlock
1,965
1,973
1,965
1,966
02b044870e84437f2aedcafff806392602c2a654
bigcode/the-stack
train
29861abbfea37138315c6112
train
function
def new_block_2d(values: ArrayLike, placement: BlockPlacement): # new_block specialized to case with # ndim=2 # isinstance(placement, BlockPlacement) # check_ndim/ensure_block_shape already checked klass = get_block_type(values.dtype) values = maybe_coerce_values(values) return klass(val...
def new_block_2d(values: ArrayLike, placement: BlockPlacement): # new_block specialized to case with # ndim=2 # isinstance(placement, BlockPlacement) # check_ndim/ensure_block_shape already checked
klass = get_block_type(values.dtype) values = maybe_coerce_values(values) return klass(values, ndim=2, placement=placement)
cls = ObjectBlock return cls def new_block_2d(values: ArrayLike, placement: BlockPlacement): # new_block specialized to case with # ndim=2 # isinstance(placement, BlockPlacement) # check_ndim/ensure_block_shape already checked
64
64
86
55
8
bram2000/pandas
pandas/core/internals/blocks.py
Python
new_block_2d
new_block_2d
2,050
2,058
2,050
2,054
4593f907f1dbaaf37542fb23e462792ca1995b60
bigcode/the-stack
train
c878f2c5499909cc8616c0a1
train
class
class ExtensionBlock(libinternals.Block, EABackedBlock): """ Block for holding extension types. Notes ----- This holds all 3rd-party extension array types. It's also the immediate parent class for our internal extension types' blocks, CategoricalBlock. ExtensionArrays are limited to 1-D. ...
class ExtensionBlock(libinternals.Block, EABackedBlock):
""" Block for holding extension types. Notes ----- This holds all 3rd-party extension array types. It's also the immediate parent class for our internal extension types' blocks, CategoricalBlock. ExtensionArrays are limited to 1-D. """ _can_consolidate = False _validate_ndim =...
_values(self) -> ExtensionArray: return self.values def get_values(self, dtype: DtypeObj | None = None) -> np.ndarray: """ return object dtype as boxed values, such as Timestamps/Timedelta """ values: ArrayLike = self.values if dtype == _dtype_obj: values...
256
256
2,585
13
243
bram2000/pandas
pandas/core/internals/blocks.py
Python
ExtensionBlock
ExtensionBlock
1,521
1,800
1,521
1,521
11e628a3fd6765dbdeb8cd98a5e53f7900151a27
bigcode/the-stack
train
1b587cdb857d1d88ec20ced9
train
function
def to_native_types( values: ArrayLike, *, na_rep="nan", quoting=None, float_format=None, decimal=".", **kwargs, ) -> np.ndarray: """convert to our native types format""" if isinstance(values, Categorical): # GH#40754 Convert categorical datetimes to datetime array va...
def to_native_types( values: ArrayLike, *, na_rep="nan", quoting=None, float_format=None, decimal=".", **kwargs, ) -> np.ndarray:
"""convert to our native types format""" if isinstance(values, Categorical): # GH#40754 Convert categorical datetimes to datetime array values = take_nd( values.categories._values, ensure_platform_int(values._codes), fill_value=na_rep, ) values = ...
(values: ArrayLike, ndim: int = 1) -> ArrayLike: """ Reshape if possible to have values.ndim == ndim. """ if values.ndim < ndim: if not is_1d_only_ea_dtype(values.dtype): # TODO(EA2D): https://github.com/pandas-dev/pandas/issues/23023 # block.shape is incorrect for "2D" ...
178
178
594
41
136
bram2000/pandas
pandas/core/internals/blocks.py
Python
to_native_types
to_native_types
2,171
2,256
2,171
2,179
6349e9929dc3f7b40c9ec65bf83d96895341c3fb
bigcode/the-stack
train
91e1daa524651e815bd3cb1c
train
function
def maybe_coerce_values(values: ArrayLike) -> ArrayLike: """ Input validation for values passed to __init__. Ensure that any datetime64/timedelta64 dtypes are in nanoseconds. Ensure that we do not have string dtypes. Parameters ---------- values : np.ndarray or ExtensionArray Returns ...
def maybe_coerce_values(values: ArrayLike) -> ArrayLike:
""" Input validation for values passed to __init__. Ensure that any datetime64/timedelta64 dtypes are in nanoseconds. Ensure that we do not have string dtypes. Parameters ---------- values : np.ndarray or ExtensionArray Returns ------- values : np.ndarray or ExtensionArray ...
34 self.values.dtype can be changed inplace until 2.0, # so this cannot be cached @property def dtype(self) -> DtypeObj: return self.values.dtype # ----------------------------------------------------------------- # Constructor Helpers def maybe_coerce_values(values: ArrayLike) -> ArrayLike:
64
64
198
14
49
bram2000/pandas
pandas/core/internals/blocks.py
Python
maybe_coerce_values
maybe_coerce_values
1,980
2,006
1,980
1,980
7f570dab62fcb1e1910c2f49eab1b5ceb5531345
bigcode/the-stack
train
4c9e872b40ff47b3e324dd69
train
class
class Block(PandasObject): """ Canonical n-dimensional unit of homogeneous dtype contained in a pandas data structure Index-ignorant; let the container take care of that """ values: np.ndarray | ExtensionArray ndim: int __init__: Callable __slots__ = () is_numeric = False ...
class Block(PandasObject):
""" Canonical n-dimensional unit of homogeneous dtype contained in a pandas data structure Index-ignorant; let the container take care of that """ values: np.ndarray | ExtensionArray ndim: int __init__: Callable __slots__ = () is_numeric = False is_object = False is_ex...
Dtype from pandas.core.base import PandasObject import pandas.core.common as com import pandas.core.computation.expressions as expressions from pandas.core.construction import ( ensure_wrapped_if_datetimelike, extract_array, ) from pandas.core.indexers import ( check_setitem_lengths, is_empty_indexer, ...
256
256
8,974
6
250
bram2000/pandas
pandas/core/internals/blocks.py
Python
Block
Block
145
1,344
145
145
94de9e6bb526820f18013ea1c535d3b493168347
bigcode/the-stack
train
f40574f3d959cb20060c95c1
train
function
def ensure_block_shape(values: ArrayLike, ndim: int = 1) -> ArrayLike: """ Reshape if possible to have values.ndim == ndim. """ if values.ndim < ndim: if not is_1d_only_ea_dtype(values.dtype): # TODO(EA2D): https://github.com/pandas-dev/pandas/issues/23023 # block.shape ...
def ensure_block_shape(values: ArrayLike, ndim: int = 1) -> ArrayLike:
""" Reshape if possible to have values.ndim == ndim. """ if values.ndim < ndim: if not is_1d_only_ea_dtype(values.dtype): # TODO(EA2D): https://github.com/pandas-dev/pandas/issues/23023 # block.shape is incorrect for "2D" ExtensionArrays # We can't, and don't...
result: if isinstance(r, list): blocks.extend(r) else: blocks.append(r) else: assert isinstance(result, Block), type(result) blocks.append(result) return blocks def ensure_block_shape(values: ArrayLike, ndim: int = 1) -> ArrayLike:
64
64
141
20
43
bram2000/pandas
pandas/core/internals/blocks.py
Python
ensure_block_shape
ensure_block_shape
2,155
2,168
2,155
2,155
3ad8d2422ce4272d2a761206f3b914e9ab92ac4c
bigcode/the-stack
train
7bc7b4d68909946901d95d44
train
function
def extract_pandas_array( values: np.ndarray | ExtensionArray, dtype: DtypeObj | None, ndim: int ) -> tuple[np.ndarray | ExtensionArray, DtypeObj | None]: """ Ensure that we don't allow PandasArray / PandasDtype in internals. """ # For now, blocks should be backed by ndarrays when possible. if i...
def extract_pandas_array( values: np.ndarray | ExtensionArray, dtype: DtypeObj | None, ndim: int ) -> tuple[np.ndarray | ExtensionArray, DtypeObj | None]:
""" Ensure that we don't allow PandasArray / PandasDtype in internals. """ # For now, blocks should be backed by ndarrays when possible. if isinstance(values, ABCPandasArray): values = values.to_numpy() if ndim and ndim > 1: # TODO(EA2D): special case not needed with 2D E...
2D): special case unnecessary with 2D EAs raise ValueError("need to split") def extract_pandas_array( values: np.ndarray | ExtensionArray, dtype: DtypeObj | None, ndim: int ) -> tuple[np.ndarray | ExtensionArray, DtypeObj | None]:
64
64
158
42
22
bram2000/pandas
pandas/core/internals/blocks.py
Python
extract_pandas_array
extract_pandas_array
2,117
2,133
2,117
2,119
a9f06ebcea0d9e53b8d1c7310b0361a783c6fd11
bigcode/the-stack
train
2f75d467e2e39fec6721d3ca
train
function
def maybe_split(meth: F) -> F: """ If we have a multi-column block, split and operate block-wise. Otherwise use the original method. """ @wraps(meth) def newfunc(self, *args, **kwargs) -> list[Block]: if self.ndim == 1 or self.shape[0] == 1: return meth(self, *args, **kwar...
def maybe_split(meth: F) -> F:
""" If we have a multi-column block, split and operate block-wise. Otherwise use the original method. """ @wraps(meth) def newfunc(self, *args, **kwargs) -> list[Block]: if self.ndim == 1 or self.shape[0] == 1: return meth(self, *args, **kwargs) else: #...
, is_scalar_indexer, ) import pandas.core.missing as missing if TYPE_CHECKING: from pandas import ( Float64Index, Index, ) # comparison is faster than is_object_dtype _dtype_obj = np.dtype("object") def maybe_split(meth: F) -> F:
64
64
128
11
53
bram2000/pandas
pandas/core/internals/blocks.py
Python
maybe_split
maybe_split
127
142
127
127
921c13d70064a0a04ab8fe384f931ae416e67ee7
bigcode/the-stack
train
e59ae4600787b8b2311ab141
train
function
def check_ndim(values, placement: BlockPlacement, ndim: int): """ ndim inference and validation. Validates that values.ndim and ndim are consistent. Validates that len(values) and len(placement) are consistent. Parameters ---------- values : array-like placement : BlockPlacement nd...
def check_ndim(values, placement: BlockPlacement, ndim: int):
""" ndim inference and validation. Validates that values.ndim and ndim are consistent. Validates that len(values) and len(placement) are consistent. Parameters ---------- values : array-like placement : BlockPlacement ndim : int Raises ------ ValueError : the number of...
# caller is responsible for ensuring values is NOT a PandasArray if not isinstance(placement, BlockPlacement): placement = BlockPlacement(placement) check_ndim(values, placement, ndim) klass = get_block_type(values.dtype) values = maybe_coerce_values(values) return klass(values, ndim...
90
90
303
15
75
bram2000/pandas
pandas/core/internals/blocks.py
Python
check_ndim
check_ndim
2,075
2,114
2,075
2,075
a5f91c4b78d3cbb895c995cb2d88c56cbbca7129
bigcode/the-stack
train
a2ca357652df5bf95f075381
train
class
class NumericBlock(NumpyBlock): __slots__ = () is_numeric = True
class NumericBlock(NumpyBlock):
__slots__ = () is_numeric = True
BlockPlacement(place), ndim=2, ) for i, (indices, place) in enumerate(zip(new_values, new_placement)) ] return blocks, mask class NumpyBlock(libinternals.NumpyBlock, Block): values: np.ndarray class NumericBlock(NumpyBlock):
64
64
19
7
56
bram2000/pandas
pandas/core/internals/blocks.py
Python
NumericBlock
NumericBlock
1,807
1,809
1,807
1,807
7e4bd9f70a2c798933e347ba2a1f24e4bc17a3db
bigcode/the-stack
train
9082d45bf0b6ae6e36dd001c
train
class
class DatetimeTZBlock(DatetimeLikeBlock): """implement a datetime64 block with a tz attribute""" values: DatetimeArray __slots__ = () is_extension = True _validate_ndim = True _can_consolidate = False
class DatetimeTZBlock(DatetimeLikeBlock):
"""implement a datetime64 block with a tz attribute""" values: DatetimeArray __slots__ = () is_extension = True _validate_ndim = True _can_consolidate = False
_numeric = False values: DatetimeArray | TimedeltaArray def values_for_json(self) -> np.ndarray: # special casing datetimetz to avoid conversion through # object dtype return self.values._ndarray class DatetimeTZBlock(DatetimeLikeBlock):
64
64
58
10
53
bram2000/pandas
pandas/core/internals/blocks.py
Python
DatetimeTZBlock
DatetimeTZBlock
1,902
1,910
1,902
1,902
bfb5e2ac2332494dd1776818af56acec0ced9416
bigcode/the-stack
train
77820f3c9a4758146f41bb49
train
class
class NDArrayBackedExtensionBlock(libinternals.NDArrayBackedBlock, EABackedBlock): """ Block backed by an NDArrayBackedExtensionArray """ values: NDArrayBackedExtensionArray # error: Signature of "is_extension" incompatible with supertype "Block" @cache_readonly def is_extension(self) -> b...
class NDArrayBackedExtensionBlock(libinternals.NDArrayBackedBlock, EABackedBlock):
""" Block backed by an NDArrayBackedExtensionArray """ values: NDArrayBackedExtensionArray # error: Signature of "is_extension" incompatible with supertype "Block" @cache_readonly def is_extension(self) -> bool: # type: ignore[override] # i.e. datetime64tz, PeriodDtype ret...
validate_scalar. blocks = [ # TODO: could cast to object depending on fill_value? type(self)( self.values.take( indices, allow_fill=needs_masking[i], fill_value=fill_value ), BlockPlacement(place), ndim=2...
147
147
493
22
124
bram2000/pandas
pandas/core/internals/blocks.py
Python
NDArrayBackedExtensionBlock
NDArrayBackedExtensionBlock
1,812
1,874
1,812
1,812
353632ecf5b1e993df2c077fee0ab77464cefe33
bigcode/the-stack
train
8720cc3a052ed62ba8a05168
train
function
def external_values(values: ArrayLike) -> ArrayLike: """ The array that Series.values returns (public attribute). This has some historical constraints, and is overridden in block subclasses to return the correct array (e.g. period returns object ndarray and datetimetz a datetime64[ns] ndarray inste...
def external_values(values: ArrayLike) -> ArrayLike:
""" The array that Series.values returns (public attribute). This has some historical constraints, and is overridden in block subclasses to return the correct array (e.g. period returns object ndarray and datetimetz a datetime64[ns] ndarray instead of proper extension array). """ if isi...
na_rep values = values.astype(f"<U{itemsize}") else: values = np.array(values, dtype="object") values[mask] = na_rep values = values.astype(object, copy=False) return values def external_values(values: ArrayLike) -> ArrayLike:
64
64
172
12
51
bram2000/pandas
pandas/core/internals/blocks.py
Python
external_values
external_values
2,259
2,276
2,259
2,259
1b13dcb3fa60be562531f05d05fb8fe9fdfb27e0
bigcode/the-stack
train
ab0330e50b1d19d4167c760d
train
class
class NumpyBlock(libinternals.NumpyBlock, Block): values: np.ndarray
class NumpyBlock(libinternals.NumpyBlock, Block):
values: np.ndarray
_masking[i], fill_value=fill_value ), BlockPlacement(place), ndim=2, ) for i, (indices, place) in enumerate(zip(new_values, new_placement)) ] return blocks, mask class NumpyBlock(libinternals.NumpyBlock, Block):
64
64
19
13
50
bram2000/pandas
pandas/core/internals/blocks.py
Python
NumpyBlock
NumpyBlock
1,803
1,804
1,803
1,803
235b00d9391993d58f07feabff6fea626b76be7e
bigcode/the-stack
train
12fce3a767b1709e687949de
train
function
@register.simple_tag(takes_context=True) def render_partner_program(context, conference=None): if conference is None: conference = settings.CONFERENCE_CONFERENCE from conference import dataaccess from conference.templatetags.conference import fare_blob fares = [ x for x in dataaccess.fares(conf...
@register.simple_tag(takes_context=True) def render_partner_program(context, conference=None):
if conference is None: conference = settings.CONFERENCE_CONFERENCE from conference import dataaccess from conference.templatetags.conference import fare_blob fares = [ x for x in dataaccess.fares(conference) if x['ticket_type'] == 'partner' and x['valid'] ] fares.sort(key=lambda x: (slugify...
): images = [] for f in os.listdir(STUFF_DIR): images.append('%s%s' % (STUFF_URL, f)) context.update({ 'images': images, }) return context @register.simple_tag(takes_context=True) def render_partner_program(context, conference=None):
64
64
167
18
45
zevaverbach/epcon
p3/templatetags/p3.py
Python
render_partner_program
render_partner_program
343
356
343
344
fce60848b03d312e7221462153e1778b89af77c9
bigcode/the-stack
train
397b69e466a1b2ad94a5d054
train
function
@register.inclusion_tag('p3/box_sponsor.html', takes_context=True) def box_sponsor(context): return context
@register.inclusion_tag('p3/box_sponsor.html', takes_context=True) def box_sponsor(context):
return context
') def box_pycon_italia(): return {} @register.inclusion_tag('p3/box_toc.html', takes_context=True) def box_toc(context): return context @register.inclusion_tag('p3/box_sponsor.html', takes_context=True) def box_sponsor(context):
64
64
28
24
39
zevaverbach/epcon
p3/templatetags/p3.py
Python
box_sponsor
box_sponsor
43
45
43
44
1a570a56002b1cb821d746f8b1aa32a3a03ef524
bigcode/the-stack
train
44b4135c9b4808cbf8134caa
train
function
@register.inclusion_tag('p3/render_map.html', takes_context=True) def render_map(context): return {}
@register.inclusion_tag('p3/render_map.html', takes_context=True) def render_map(context):
return {}
(page): """ controlla se la pagina passata richiede o meno una mappa """ if page: return '{% render_map' in page.expose_content() return False @register.inclusion_tag('p3/render_map.html', takes_context=True) def render_map(context):
64
64
24
21
42
zevaverbach/epcon
p3/templatetags/p3.py
Python
render_map
render_map
146
148
146
147
1e916e294bc1bb1e8bae8b4ac0b3214ee50fb49c
bigcode/the-stack
train
4cfbef9f2cf83ee63d2db482
train
function
@register.filter def tickets_url(user): """ ritorna la url più diretta per mandare l'utente sulla sua pagina ticket """ if user.assopy_user.token: u = reverse('p3-user', kwargs={'token': user.assopy_user.token}) else: u = reverse('p3-tickets') return settings.DEFAULT_URL_PREFIX ...
@register.filter def tickets_url(user):
""" ritorna la url più diretta per mandare l'utente sulla sua pagina ticket """ if user.assopy_user.token: u = reverse('p3-user', kwargs={'token': user.assopy_user.token}) else: u = reverse('p3-tickets') return settings.DEFAULT_URL_PREFIX + u
itted(s): tracks = ConferenceModels.Track.objects.by_schedule(s) s = [] for t in tracks: if t.track.startswith('partner') or t.track.startswith('sprint'): s.append(t) return len(tracks) != len(s) @register.filter def tickets_url(user):
64
64
81
9
55
zevaverbach/epcon
p3/templatetags/p3.py
Python
tickets_url
tickets_url
380
390
380
381
f182259b4601b565b8b3d16945744cf79576386c
bigcode/the-stack
train
168faffb5a3808f240f29fe1
train
function
@register.inclusion_tag('p3/box_newsletter.html', takes_context=True) def box_newsletter(context): return context
@register.inclusion_tag('p3/box_newsletter.html', takes_context=True) def box_newsletter(context):
return context
=True) def box_toc(context): return context @register.inclusion_tag('p3/box_sponsor.html', takes_context=True) def box_sponsor(context): return context @register.inclusion_tag('p3/box_newsletter.html', takes_context=True) def box_newsletter(context):
64
64
28
24
39
zevaverbach/epcon
p3/templatetags/p3.py
Python
box_newsletter
box_newsletter
47
49
47
48
c8c6a7c6f86b9287ed556c939dd0d077d45f4e57
bigcode/the-stack
train
9909bbe2c82bc0aad8ef5a06
train
function
@register.simple_tag(takes_context=True) def get_form(context, name, bound="auto", bound_field=None): if '.' in name: from conference.utils import dotted_import fc = dotted_import(name) else: fc = getattr(p3forms, name) request = context['request'] if bound: if bound == '...
@register.simple_tag(takes_context=True) def get_form(context, name, bound="auto", bound_field=None):
if '.' in name: from conference.utils import dotted_import fc = dotted_import(name) else: fc = getattr(p3forms, name) request = context['request'] if bound: if bound == 'auto': bound = request.method if bound == 'GET': data = request.GET ...
3_profiles_data(uids): return dataaccess.profiles_data(uids) @register.simple_tag() def p3_talk_data(tid): return dataaccess.talk_data(tid) @register.simple_tag(takes_context=True) def get_form(context, name, bound="auto", bound_field=None):
64
64
200
24
40
zevaverbach/epcon
p3/templatetags/p3.py
Python
get_form
get_form
483
513
483
484
596f9347640fa0d26a997cbec517dea394bd3d25
bigcode/the-stack
train
acab7909094af2a508f4f9c2
train
function
@register.simple_tag() def p3_talk_data(tid): return dataaccess.talk_data(tid)
@register.simple_tag() def p3_talk_data(tid):
return dataaccess.talk_data(tid)
, }) return ctx @register.simple_tag() def p3_profile_data(uid): return dataaccess.profile_data(uid) @register.simple_tag() def p3_profiles_data(uids): return dataaccess.profiles_data(uids) @register.simple_tag() def p3_talk_data(tid):
64
64
24
14
50
zevaverbach/epcon
p3/templatetags/p3.py
Python
p3_talk_data
p3_talk_data
479
481
479
480
739768acf602bb531bd33e2ea162a439e09ea7c4
bigcode/the-stack
train
53212a92bdd321984fe5f0d0
train
function
@register.inclusion_tag('p3/box_didyouknow.html', takes_context = True) def box_didyouknow(context): try: d = ConferenceModels.DidYouKnow.objects.filter(visible = True).order_by('?')[0] except IndexError: d = None return { 'd': d, 'LANGUAGE_CODE': context.get('LANGUAGE_CODE')...
@register.inclusion_tag('p3/box_didyouknow.html', takes_context = True) def box_didyouknow(context):
try: d = ConferenceModels.DidYouKnow.objects.filter(visible = True).order_by('?')[0] except IndexError: d = None return { 'd': d, 'LANGUAGE_CODE': context.get('LANGUAGE_CODE'), }
url': context['STUFF_URL'] + fname, 'label': label, 'fsize': fsize, 'ftype': ftype, } @register.inclusion_tag('p3/box_didyouknow.html', takes_context = True) def box_didyouknow(context):
64
64
88
29
35
zevaverbach/epcon
p3/templatetags/p3.py
Python
box_didyouknow
box_didyouknow
88
97
88
89
70c031b21b2d8e0bc44a53e963f26bae42a75f43
bigcode/the-stack
train
639c248037e871f318fd53ab
train
function
@register.simple_tag(takes_context=True) def render_cart_rows(context, fare_type, form): assert fare_type in ('conference', 'goodies', 'partner', 'hotel-room', 'hotel-room-sharing', 'other') ctx = context.flatten() request = ctx['request'] try: company = request.user.assopy_user.account_type == ...
@register.simple_tag(takes_context=True) def render_cart_rows(context, fare_type, form):
assert fare_type in ('conference', 'goodies', 'partner', 'hotel-room', 'hotel-room-sharing', 'other') ctx = context.flatten() request = ctx['request'] try: company = request.user.assopy_user.account_type == 'c' except AttributeError: # anonymous user or without an assopy profile (imp...
', 'other') fares_list = [f for f in cdataaccess.fares(settings.CONFERENCE_CONFERENCE) if f['valid']] if fare_type == 'conference': fares = [ f for f in fares_list if f['code'][0] == 'T' and f['ticket_type'] == 'conference' ] elif fare_type == 'hotel-room-sharing': fares = [ f for f in fare...
256
256
995
20
235
zevaverbach/epcon
p3/templatetags/p3.py
Python
render_cart_rows
render_cart_rows
232
330
232
233
ce28262a20485cba98652bfdf2c7c505ea26c5c4
bigcode/the-stack
train
7a5dc00192180880dca44384
train
function
@register.filter def render_time(tweet, args=None): time = tweet["timestamp"] time = datetime.datetime.fromtimestamp(time) return time.strftime("%d-%m-%y @ %H:%M")
@register.filter def render_time(tweet, args=None):
time = tweet["timestamp"] time = datetime.datetime.fromtimestamp(time) return time.strftime("%d-%m-%y @ %H:%M")
clusion_tag('p3/box_latest_tweets.html', takes_context=True) def box_latest_tweets(context): ctx = context.flatten() ctx.update({ 'screen_name': settings.P3_TWITTER_USER, }) return ctx @register.filter def render_time(tweet, args=None):
64
64
44
12
51
zevaverbach/epcon
p3/templatetags/p3.py
Python
render_time
render_time
131
135
131
132
a98328fc52cf6fb5f9b0dbc94739e4ba3bd71042
bigcode/the-stack
train
cc04b6139a803b5703450c47
train
function
@register.simple_tag() def p3_profiles_data(uids): return dataaccess.profiles_data(uids)
@register.simple_tag() def p3_profiles_data(uids):
return dataaccess.profiles_data(uids)
=lambda x: x[0].order) ctx = context.flatten() ctx.update({ 'events': events, }) return ctx @register.simple_tag() def p3_profile_data(uid): return dataaccess.profile_data(uid) @register.simple_tag() def p3_profiles_data(uids):
64
64
23
13
51
zevaverbach/epcon
p3/templatetags/p3.py
Python
p3_profiles_data
p3_profiles_data
475
477
475
476
b2c44679ceccfc6b3b96d58d655fbe692a389b25
bigcode/the-stack
train
a2a39623b862c7929ccc5ab5
train
function
@register.filter def timetable_remove_first(timetable, tag): if not tag: return timetable start = None for time, events in timetable.iterOnTimes(): stop = False for e in events: if tag not in e['tags']: stop = True break start = tim...
@register.filter def timetable_remove_first(timetable, tag):
if not tag: return timetable start = None for time, events in timetable.iterOnTimes(): stop = False for e in events: if tag not in e['tags']: stop = True break start = time.time() if stop: break return timet...
t['events_id'] ]) talks[t['id']] = t ctx.update({ 'conference': conference, 'talks': sorted(list(talks.values()), key=lambda x: x['title']), }) return ctx @register.filter def timetable_remove_first(timetable, tag):
64
64
86
13
50
zevaverbach/epcon
p3/templatetags/p3.py
Python
timetable_remove_first
timetable_remove_first
639
654
639
640
efa49262e84e4c1ea930b8f5a1cd9361c68d7280
bigcode/the-stack
train
25f344285ec037f165b9cc2f
train
function
@register.inclusion_tag('p3/box_download.html', takes_context = True) def box_download(context, fname, label=None): if '..' in fname: raise template.TemplateSyntaxError("file path cannot contains ..") if fname.startswith('/'): raise template.TemplateSyntaxError("file path cannot starts with /") ...
@register.inclusion_tag('p3/box_download.html', takes_context = True) def box_download(context, fname, label=None):
if '..' in fname: raise template.TemplateSyntaxError("file path cannot contains ..") if fname.startswith('/'): raise template.TemplateSyntaxError("file path cannot starts with /") if label is None: label = os.path.basename(fname) try: fpath = os.path.join(settings.STUFF_D...
LANGUAGE_CODE'])) for d in deadlines ] } @register.inclusion_tag('p3/render_cal.html', takes_context=True) def render_cal(context): return context @register.inclusion_tag('p3/box_download.html', takes_context = True) def box_download(context, fname, label=None):
64
64
194
28
35
zevaverbach/epcon
p3/templatetags/p3.py
Python
box_download
box_download
64
86
64
65
72f6e831d74cf05afffc8c8dc8abaeee4102bac5
bigcode/the-stack
train
ba50be0dc96e9b5afd546bec
train
function
@register.inclusion_tag('p3/box_latest_tweets.html', takes_context=True) def box_latest_tweets(context): ctx = context.flatten() ctx.update({ 'screen_name': settings.P3_TWITTER_USER, }) return ctx
@register.inclusion_tag('p3/box_latest_tweets.html', takes_context=True) def box_latest_tweets(context):
ctx = context.flatten() ctx.update({ 'screen_name': settings.P3_TWITTER_USER, }) return ctx
.conference].append(t) talks = [] for c in reversed(sorted(conf.keys())): talks.append((c, conf[c])) return { 'talks': talks } @register.inclusion_tag('p3/box_latest_tweets.html', takes_context=True) def box_latest_tweets(context):
64
64
55
26
38
zevaverbach/epcon
p3/templatetags/p3.py
Python
box_latest_tweets
box_latest_tweets
123
129
123
124
9fb411bdcef70422f577b7c01c998e75e40ee55f
bigcode/the-stack
train
0bf59ee8b753c8ef056941d4
train
function
@register.inclusion_tag('p3/box_talks_conference.html', takes_context = True) def box_talks_conference(context, talks): """ mostra i talk passati raggruppati per conferenza """ conf = defaultdict(list) for t in talks: conf[t.conference].append(t) talks = [] for c in reversed(sorted(...
@register.inclusion_tag('p3/box_talks_conference.html', takes_context = True) def box_talks_conference(context, talks):
""" mostra i talk passati raggruppati per conferenza """ conf = defaultdict(list) for t in talks: conf[t.conference].append(t) talks = [] for c in reversed(sorted(conf.keys())): talks.append((c, conf[c])) return { 'talks': talks }
{ 'rand': random.randint(0, sys.maxsize - 1), 'what': what, 'zoom': zoom } @register.inclusion_tag('p3/box_talks_conference.html', takes_context = True) def box_talks_conference(context, talks):
64
64
104
33
31
zevaverbach/epcon
p3/templatetags/p3.py
Python
box_talks_conference
box_talks_conference
108
121
108
109
cfaad4a4628d1b4b32672f6258a33c5e5f01ca9b
bigcode/the-stack
train
6d9d64ae531c5ca97a70eeff
train
function
@register.filter def schedule_to_be_splitted(s): tracks = ConferenceModels.Track.objects.by_schedule(s) s = [] for t in tracks: if t.track.startswith('partner') or t.track.startswith('sprint'): s.append(t) return len(tracks) != len(s)
@register.filter def schedule_to_be_splitted(s):
tracks = ConferenceModels.Track.objects.by_schedule(s) s = [] for t in tracks: if t.track.startswith('partner') or t.track.startswith('sprint'): s.append(t) return len(tracks) != len(s)
(): c[str(f.id)] = f fare = c[fare_id.group(1)] return mark_safe('<a href="/partner-program/#%s">%s</a>' % (slugify(fare.name), event.custom,)) @register.filter def schedule_to_be_splitted(s):
63
64
65
13
51
zevaverbach/epcon
p3/templatetags/p3.py
Python
schedule_to_be_splitted
schedule_to_be_splitted
371
378
371
372
692b7154e228b6d5251160b236b34c7578c700bb
bigcode/the-stack
train
c31ca60f97c5b809eae593e1
train
function
@register.inclusion_tag('p3/fragments/render_ticket.html', takes_context=True) def render_ticket(context, ticket): from p3 import forms user = context['request'].user if ticket.fare.ticket_type == 'conference': try: inst = ticket.p3_conference except: inst = None ...
@register.inclusion_tag('p3/fragments/render_ticket.html', takes_context=True) def render_ticket(context, ticket):
from p3 import forms user = context['request'].user if ticket.fare.ticket_type == 'conference': try: inst = ticket.p3_conference except: inst = None form = forms.FormTicket( instance=inst, initial={ 'ticket_name': ticket...
return time.strftime("%d-%m-%y @ %H:%M") @register.filter def check_map(page): """ controlla se la pagina passata richiede o meno una mappa """ if page: return '{% render_map' in page.expose_content() return False @register.inclusion_tag('p3/render_map.html', takes_context=True) def rende...
114
114
380
25
89
zevaverbach/epcon
p3/templatetags/p3.py
Python
render_ticket
render_ticket
150
205
150
151
95bfb016da8ece4ac2d746c0bfd03a0787a4d7d7
bigcode/the-stack
train
60691ccffaf5832100499e4e
train
function
@register.simple_tag(takes_context=True) def fares_available(context, fare_type, sort=None): """ Restituisce l'elenco delle tariffe attive in questo momento per la tipologia specificata. """ assert fare_type in ('all', 'conference', 'goodies', 'partner', 'hotel-room', 'hotel-room-sharing', 'other') ...
@register.simple_tag(takes_context=True) def fares_available(context, fare_type, sort=None):
""" Restituisce l'elenco delle tariffe attive in questo momento per la tipologia specificata. """ assert fare_type in ('all', 'conference', 'goodies', 'partner', 'hotel-room', 'hotel-room-sharing', 'other') fares_list = [f for f in cdataaccess.fares(settings.CONFERENCE_CONFERENCE) if f['valid']...
blocked = False else: form = forms.FormTicketPartner(instance=ticket, prefix='t%d' % (ticket.id,)) blocked = False ctx = context.flatten() ctx.update({ 'ticket': ticket, 'form': form, 'user': user, 'blocked': blocked, }) return ctx @register.simple_ta...
93
93
310
20
72
zevaverbach/epcon
p3/templatetags/p3.py
Python
fares_available
fares_available
207
230
207
208
61400bb6bffdc27ca70171ad9c9d661605ab6f60
bigcode/the-stack
train
edf295d263f490cc8cfae539
train
function
@register.filter def frozen_reason(ticket): if not ticket.frozen: return '' if amodels.RefundOrderItem.objects.filter(orderitem=ticket.orderitem).exists(): return 'refund pending' else: return ''
@register.filter def frozen_reason(ticket):
if not ticket.frozen: return '' if amodels.RefundOrderItem.objects.filter(orderitem=ticket.orderitem).exists(): return 'refund pending' else: return ''
akers': dict([ (x['id'], x) for x in dataaccess.profiles_data(speakers) ]), 'talks': dict([ (x['id'], x) for x in cdataaccess.talks_data(talks) ]), } @register.filter def frozen_reason(ticket):
64
64
51
9
55
zevaverbach/epcon
p3/templatetags/p3.py
Python
frozen_reason
frozen_reason
568
575
568
569
ca86ff9104a55c2f6cbee3945a6104fac2b2c874
bigcode/the-stack
train
9a5da6bc7307b9d050bb3cf9
train
function
@register.simple_tag() def p3_tags(): return dataaccess.tags()
@register.simple_tag() def p3_tags():
return dataaccess.tags()
]] elif status == 'incomplete': tickets = [x for x in tickets if not x[3]] if fare_type != "all": tickets = [x for x in tickets if x[1] == fare_type] return tickets @register.simple_tag() def p3_tags():
64
64
16
10
53
zevaverbach/epcon
p3/templatetags/p3.py
Python
p3_tags
p3_tags
596
598
596
597
5be9b6487d0daca401797cffbc2cd33a3e2b0ba0
bigcode/the-stack
train
2aa4503b2f58195ef1c2ae83
train
function
@register.filter def com_com_registration(user): url = 'https://hotspot.com-com.it/signup/?' name = user.name() try: fn, ln = name.split(' ', 1) except ValueError: fn = name ln = '' params = { 'autofill': 'yes', 'firstname': fn, 'lastname': ln, ...
@register.filter def com_com_registration(user):
url = 'https://hotspot.com-com.it/signup/?' name = user.name() try: fn, ln = name.split(' ', 1) except ValueError: fn = name ln = '' params = { 'autofill': 'yes', 'firstname': fn, 'lastname': ln, 'email': user.user.email, } if user.coun...
c = None if p3c and p3c.assigned_to: from assopy.utils import get_user_account_from_email return get_user_account_from_email(p3c.assigned_to) else: return ticket.orderitem.order.user @register.filter def com_com_registration(user):
64
64
181
10
53
zevaverbach/epcon
p3/templatetags/p3.py
Python
com_com_registration
com_com_registration
404
426
404
405
de22bbc1e2bfc600c945026352f3430b0b339aba
bigcode/the-stack
train
e85842f3a38ebb74d42a194d
train
function
@register.inclusion_tag('p3/box_pycon_italia.html') def box_pycon_italia(): return {}
@register.inclusion_tag('p3/box_pycon_italia.html') def box_pycon_italia():
return {}
models as amodels from p3 import dataaccess from p3 import forms as p3forms from p3 import models mimetypes.init() register = template.Library() @register.inclusion_tag('p3/box_pycon_italia.html') def box_pycon_italia():
64
64
28
25
39
zevaverbach/epcon
p3/templatetags/p3.py
Python
box_pycon_italia
box_pycon_italia
35
37
35
36
ea60e6c144dbbd5c6707d99104b22072fa8de965
bigcode/the-stack
train
06b2fb96ee18cbe60017ed68
train
function
@register.inclusion_tag('p3/box_image_gallery.html', takes_context=True) def box_image_gallery(context): images = [] for f in os.listdir(STUFF_DIR): images.append('%s%s' % (STUFF_URL, f)) context.update({ 'images': images, }) return context
@register.inclusion_tag('p3/box_image_gallery.html', takes_context=True) def box_image_gallery(context):
images = [] for f in os.listdir(STUFF_DIR): images.append('%s%s' % (STUFF_URL, f)) context.update({ 'images': images, }) return context
_partner_ticket_row.html' ctx['fares'] = [ f for f in fares_list if f['ticket_type'] in 'partner' ] return render_to_string(tpl, ctx) @register.inclusion_tag('p3/box_image_gallery.html', takes_context=True) def box_image_gallery(context):
64
64
69
24
40
zevaverbach/epcon
p3/templatetags/p3.py
Python
box_image_gallery
box_image_gallery
332
341
332
333
61b7c825168c38bed41e77958007946760fc0f0f
bigcode/the-stack
train
4d06475ecb231aa51434195d
train
function
@register.simple_tag(takes_context=True) def event_partner_program(context, event): fare_id = re.search(r'f(\d+)', event.track) if fare_id is None: return '' from conference.templatetags.conference import _request_cache c = _request_cache(context['request'], 'fares') if not c: for f ...
@register.simple_tag(takes_context=True) def event_partner_program(context, event):
fare_id = re.search(r'f(\d+)', event.track) if fare_id is None: return '' from conference.templatetags.conference import _request_cache c = _request_cache(context['request'], 'fares') if not c: for f in ConferenceModels.Fare.objects.all(): c[str(f.id)] = f fare = c[fa...
[ (k, list(v)) for k, v in groupby(fares, key=lambda x: slugify(x['name'])) ], }) return render_to_string('p3/fragments/render_partner_program.html', ctx) @register.simple_tag(takes_context=True) def event_partner_program(context, event):
64
64
135
17
47
zevaverbach/epcon
p3/templatetags/p3.py
Python
event_partner_program
event_partner_program
358
369
358
359
3add26a3d51a0413e65067c9f65e554cbd5346f9
bigcode/the-stack
train
88fcae850d8acc18fc95b9bb
train
function
@register.inclusion_tag('p3/box_next_events.html', takes_context=True) def box_next_events(context): from conference.templatetags import conference as ctags t = datetime.now() try: sch = ConferenceModels.Schedule.objects.get(date=t.date()) except ConferenceModels.Schedule.DoesNotExist: c...
@register.inclusion_tag('p3/box_next_events.html', takes_context=True) def box_next_events(context):
from conference.templatetags import conference as ctags t = datetime.now() try: sch = ConferenceModels.Schedule.objects.get(date=t.date()) except ConferenceModels.Schedule.DoesNotExist: current = next = {} else: current = ctags.current_events(context, t) next = ctags....
('+39'): params['ita_mobile'] = user.phone params['username'] = name.lower().replace(' ', '').replace('.', '')[:12] for k, v in params.items(): params[k] = v.encode('utf-8') return url + urllib.parse.urlencode(params) @register.inclusion_tag('p3/box_next_events.html', takes_context=True) def...
87
87
292
24
63
zevaverbach/epcon
p3/templatetags/p3.py
Python
box_next_events
box_next_events
428
469
428
429
ccd14dcf73d053c1da328a8954e479c2248528e1
bigcode/the-stack
train
a215d8d1dcb7f7fb59f5b0f6
train
function
@register.inclusion_tag('p3/box_toc.html', takes_context=True) def box_toc(context): return context
@register.inclusion_tag('p3/box_toc.html', takes_context=True) def box_toc(context):
return context
models mimetypes.init() register = template.Library() @register.inclusion_tag('p3/box_pycon_italia.html') def box_pycon_italia(): return {} @register.inclusion_tag('p3/box_toc.html', takes_context=True) def box_toc(context):
64
64
28
24
40
zevaverbach/epcon
p3/templatetags/p3.py
Python
box_toc
box_toc
39
41
39
40
893d78c6eab2a16403310db64b4549e5e62bd622
bigcode/the-stack
train
b2a1bc7703289429fd0924d0
train
function
@register.filter def check_map(page): """ controlla se la pagina passata richiede o meno una mappa """ if page: return '{% render_map' in page.expose_content() return False
@register.filter def check_map(page):
""" controlla se la pagina passata richiede o meno una mappa """ if page: return '{% render_map' in page.expose_content() return False
_TWITTER_USER, }) return ctx @register.filter def render_time(tweet, args=None): time = tweet["timestamp"] time = datetime.datetime.fromtimestamp(time) return time.strftime("%d-%m-%y @ %H:%M") @register.filter def check_map(page):
64
64
50
9
55
zevaverbach/epcon
p3/templatetags/p3.py
Python
check_map
check_map
137
144
137
138
9490e57e53cf0bdd02f08b08d7b6861d8dd526d4
bigcode/the-stack
train
855585c539c456fdb14fdcfb
train
function
@register.inclusion_tag('p3/render_cal.html', takes_context=True) def render_cal(context): return context
@register.inclusion_tag('p3/render_cal.html', takes_context=True) def render_cal(context):
return context
.objects.valid_news() if limit: deadlines = deadlines[:int(limit)] return { 'deadlines': [ (d, d.content(context['LANGUAGE_CODE'])) for d in deadlines ] } @register.inclusion_tag('p3/render_cal.html', takes_context=True) def render_cal(context):
64
64
25
21
43
zevaverbach/epcon
p3/templatetags/p3.py
Python
render_cal
render_cal
60
62
60
61
b53b746d26d8e459d7b935c9bc843a4ca7280406
bigcode/the-stack
train
f651ee5ebaa3aad6369ac903
train
function
@register.simple_tag() def p3_profile_data(uid): return dataaccess.profile_data(uid)
@register.simple_tag() def p3_profile_data(uid):
return dataaccess.profile_data(uid)
'next': (n, n_time), } events = sorted(list(tracks.items()), key=lambda x: x[0].order) ctx = context.flatten() ctx.update({ 'events': events, }) return ctx @register.simple_tag() def p3_profile_data(uid):
64
64
20
12
51
zevaverbach/epcon
p3/templatetags/p3.py
Python
p3_profile_data
p3_profile_data
471
473
471
472
309fe7701c8a77b737dfd9aa942c11d912076753
bigcode/the-stack
train
da19a5a86de01986e31921bf
train
function
@register.inclusion_tag('p3/box_googlemaps.html', takes_context = True) def box_googlemaps(context, what='', zoom=13): what = ','.join([ "'%s'" % w for w in what.split(',') ]) return { 'rand': random.randint(0, sys.maxsize - 1), 'what': what, 'zoom': zoom }
@register.inclusion_tag('p3/box_googlemaps.html', takes_context = True) def box_googlemaps(context, what='', zoom=13):
what = ','.join([ "'%s'" % w for w in what.split(',') ]) return { 'rand': random.randint(0, sys.maxsize - 1), 'what': what, 'zoom': zoom }
except IndexError: d = None return { 'd': d, 'LANGUAGE_CODE': context.get('LANGUAGE_CODE'), } @register.inclusion_tag('p3/box_googlemaps.html', takes_context = True) def box_googlemaps(context, what='', zoom=13):
64
64
85
31
33
zevaverbach/epcon
p3/templatetags/p3.py
Python
box_googlemaps
box_googlemaps
99
106
99
100
9fd76bc43a042aa3a505e76e758a6e96db1673ba
bigcode/the-stack
train
88dfce2d570dc376969ddec2
train
function
@register.inclusion_tag('p3/box_cal.html', takes_context = True) def box_cal(context, limit=None): deadlines = ConferenceModels.Deadline.objects.valid_news() if limit: deadlines = deadlines[:int(limit)] return { 'deadlines': [ (d, d.content(context['LANGUAGE_CODE'])) for d in deadlines ] ...
@register.inclusion_tag('p3/box_cal.html', takes_context = True) def box_cal(context, limit=None):
deadlines = ConferenceModels.Deadline.objects.valid_news() if limit: deadlines = deadlines[:int(limit)] return { 'deadlines': [ (d, d.content(context['LANGUAGE_CODE'])) for d in deadlines ] }
def box_sponsor(context): return context @register.inclusion_tag('p3/box_newsletter.html', takes_context=True) def box_newsletter(context): return context @register.inclusion_tag('p3/box_cal.html', takes_context = True) def box_cal(context, limit=None):
64
64
77
26
37
zevaverbach/epcon
p3/templatetags/p3.py
Python
box_cal
box_cal
51
58
51
52
da9f884f71a6b234738d04fd9467e3608ed78571
bigcode/the-stack
train
5919da7a1f8b33209042c421
train
function
@register.simple_tag() def admin_ticketroom_overall_status(): status = models.TicketRoom.objects.overall_status() labels = dict(models.HOTELROOM_ROOM_TYPE) days = sorted(status.keys()) rooms = {} for day in days: dst = status[day] for room_type, dst in status[day].items(): ...
@register.simple_tag() def admin_ticketroom_overall_status():
status = models.TicketRoom.objects.overall_status() labels = dict(models.HOTELROOM_ROOM_TYPE) days = sorted(status.keys()) rooms = {} for day in days: dst = status[day] for room_type, dst in status[day].items(): try: r = rooms[room_type] excep...
@register.simple_tag() def pending_email_change(user): try: t = amodels.Token.objects.get(ctype='e', user=user) except amodels.Token.DoesNotExist: return None return t.payload @register.simple_tag() def admin_ticketroom_overall_status():
64
64
154
13
50
zevaverbach/epcon
p3/templatetags/p3.py
Python
admin_ticketroom_overall_status
admin_ticketroom_overall_status
523
545
523
524
730d1cfa1d4a1e91b0d6a53a1e7e264ae8e271eb
bigcode/the-stack
train
1ea81e39d1d1cc8a11243677
train
function
@register.inclusion_tag('p3/fragments/archive.html', takes_context=True) def render_archive(context, conference): ctx = context.flatten() def match(e, exclude_tags=set(('partner0', 'partner1', 'sprint1', 'sprint2', 'sprint3'))): if e['tags'] & exclude_tags: return False if not e['ta...
@register.inclusion_tag('p3/fragments/archive.html', takes_context=True) def render_archive(context, conference):
ctx = context.flatten() def match(e, exclude_tags=set(('partner0', 'partner1', 'sprint1', 'sprint2', 'sprint3'))): if e['tags'] & exclude_tags: return False if not e['talk']: return False return True events = { x['id']:x for x in filter(match, cdataaccess.eve...
'user_message': user_message if user_message in ('auto', 'always', 'none') else 'auto', }) return render_to_string('p3/fragments/render_profile_box.html', ctx) @register.inclusion_tag('p3/fragments/archive.html', takes_context=True) def render_archive(context, conference):
66
66
221
24
42
zevaverbach/epcon
p3/templatetags/p3.py
Python
render_archive
render_archive
614
637
614
615
ec64e4512a861634771fcf3382456961a4f8cace
bigcode/the-stack
train
7ab87eebd42cbebe9fa82be0
train
function
@register.simple_tag(takes_context=True) def all_user_tickets(context, uid=None, conference=None, status="complete", fare_type="conference"): if uid is None: uid = context['request'].user.id if conference is None: conference = settings.CONFERENCE_CONFERENCE tickets = dat...
@register.simple_tag(takes_context=True) def all_user_tickets(context, uid=None, conference=None, status="complete", fare_type="conference"):
if uid is None: uid = context['request'].user.id if conference is None: conference = settings.CONFERENCE_CONFERENCE tickets = dataaccess.all_user_tickets(uid, conference) if status == 'complete': tickets = [x for x in tickets if x[3]] elif status == 'incomplete': tick...
if amodels.RefundOrderItem.objects.filter(orderitem=ticket.orderitem).exists(): return 'refund pending' else: return '' @register.simple_tag(takes_context=True) def all_user_tickets(context, uid=None, conference=None, status="complete", fare_type="conference"):
63
64
150
32
31
zevaverbach/epcon
p3/templatetags/p3.py
Python
all_user_tickets
all_user_tickets
578
593
578
580
566679b6ea5184ad50da9cd7fc13143f8df1027c
bigcode/the-stack
train
ed81bfd9895440659011ffe4
train
function
@register.filter def ticket_user(ticket): try: p3c = ticket.p3_conference except models.TicketConference.DoesNotExist: p3c = None if p3c and p3c.assigned_to: from assopy.utils import get_user_account_from_email return get_user_account_from_email(p3c.assigned_to) else: ...
@register.filter def ticket_user(ticket):
try: p3c = ticket.p3_conference except models.TicketConference.DoesNotExist: p3c = None if p3c and p3c.assigned_to: from assopy.utils import get_user_account_from_email return get_user_account_from_email(p3c.assigned_to) else: return ticket.orderitem.order.user
sua pagina ticket """ if user.assopy_user.token: u = reverse('p3-user', kwargs={'token': user.assopy_user.token}) else: u = reverse('p3-tickets') return settings.DEFAULT_URL_PREFIX + u @register.filter def ticket_user(ticket):
64
64
90
9
54
zevaverbach/epcon
p3/templatetags/p3.py
Python
ticket_user
ticket_user
392
402
392
393
caa807f1a329cd69546ebccfa34c8fe3b19f6c9f
bigcode/the-stack
train
5299ec23bcfbba5f7528c66a
train
function
@register.simple_tag() def warmup_conference_cache(conference=None): """ """ if conference is None: conference = settings.CONFERENCE_CONFERENCE qs = ConferenceModels.TalkSpeaker.objects\ .filter(talk__conference=conference)\ .values_list('talk', 'speaker') talks = set() ...
@register.simple_tag() def warmup_conference_cache(conference=None):
""" """ if conference is None: conference = settings.CONFERENCE_CONFERENCE qs = ConferenceModels.TalkSpeaker.objects\ .filter(talk__conference=conference)\ .values_list('talk', 'speaker') talks = set() speakers = set() for row in qs: talks.add(row[0]) ...
_type, 'label': labels.get(room_type, room_type), 'days': [], } r['days'].append(dst) return { 'days': days, 'rooms': list(rooms.values()), } @register.simple_tag() def warmup_conference_cache(conference=None):
64
64
155
15
49
zevaverbach/epcon
p3/templatetags/p3.py
Python
warmup_conference_cache
warmup_conference_cache
547
566
547
548
18bda38a7e3e9193b17a068806b8f2363b136082
bigcode/the-stack
train
d2edfe58dee1373a68baa917
train
function
@register.simple_tag(takes_context=True) def render_profile_box(context, profile, conference=None, user_message="auto"): if conference is None: conference = settings.CONFERENCE_CONFERENCE if isinstance(profile, int): profile = dataaccess.profile_data(profile) ctx = context.flatten() ctx....
@register.simple_tag(takes_context=True) def render_profile_box(context, profile, conference=None, user_message="auto"):
if conference is None: conference = settings.CONFERENCE_CONFERENCE if isinstance(profile, int): profile = dataaccess.profile_data(profile) ctx = context.flatten() ctx.update({ 'profile': profile, 'conference': conference, 'user_message': user_message if user_messa...
": tickets = [x for x in tickets if x[1] == fare_type] return tickets @register.simple_tag() def p3_tags(): return dataaccess.tags() @register.simple_tag(takes_context=True) def render_profile_box(context, profile, conference=None, user_message="auto"):
64
64
121
25
39
zevaverbach/epcon
p3/templatetags/p3.py
Python
render_profile_box
render_profile_box
600
612
600
601
7cbac5f96c14f19e110482802215a99222d3fa37
bigcode/the-stack
train
d5789c5f94c84cc91b52bd34
train
function
@register.simple_tag() def pending_email_change(user): try: t = amodels.Token.objects.get(ctype='e', user=user) except amodels.Token.DoesNotExist: return None return t.payload
@register.simple_tag() def pending_email_change(user):
try: t = amodels.Token.objects.get(ctype='e', user=user) except amodels.Token.DoesNotExist: return None return t.payload
) else: data = bound if bound_field and bound_field not in data: data = None else: data = None form = fc(data=data) if data: form.is_valid() return form @register.simple_tag() def pending_email_change(user):
64
64
50
11
52
zevaverbach/epcon
p3/templatetags/p3.py
Python
pending_email_change
pending_email_change
515
521
515
516
cdc9a99320b2238d2e287889286e029a0a939066
bigcode/the-stack
train
26e2c832086513146ba7f3dc
train
function
def network_thread(ctx, port, command_port, inqueues, outqueue, finished_bricks, qname): # Set my process name try: import setproctitle setproctitle.setproctitle('farm: network') except: pass # Set up ZeroMQ socket for communicating with workers import socket me = socket...
def network_thread(ctx, port, command_port, inqueues, outqueue, finished_bricks, qname): # Set my process name
try: import setproctitle setproctitle.setproctitle('farm: network') except: pass # Set up ZeroMQ socket for communicating with workers import socket me = socket.gethostname() if ctx is None: ctx = zmq.Context() sock = ctx.socket(zmq.REP) addr = 'tcp://*:'...
bigqueue, checkpointqueue, blobsizes, opt, i), daemon=True) inthreads.append(inthread) inthread.start() outthread = mp.Process(target=output_thread, args=(queuename, outqueue, checkpointqueue, blobsi...
256
256
3,156
30
226
legacysurvey/pipeline
py/legacypipe/farm.py
Python
network_thread
network_thread
275
630
275
276
bb31c3e5474f22455af0c5d24132ba47f3bd7fc1
bigcode/the-stack
train
9d82b816c79057ba894b72cf
train
function
def queue_work(brickname, inqueue, bigqueue, checkpointqueue, opt): ''' Called from the input thread to generate work packets for the given *brickname*. ''' from astrometry.util.file import unpickle_from_file pickle_fn = opt.pickle % dict(brick=brickname, brickpre=brickname[:3]) info('Looking f...
def queue_work(brickname, inqueue, bigqueue, checkpointqueue, opt):
''' Called from the input thread to generate work packets for the given *brickname*. ''' from astrometry.util.file import unpickle_from_file pickle_fn = opt.pickle % dict(brick=brickname, brickpre=brickname[:3]) info('Looking for', pickle_fn) if not os.path.exists(pickle_fn): raise ...
item=None): self.priority = priority self.item = item def __lt__(self, other): return self.priority < other.priority # we switched to multiprocessing and mp.Queue, so don't need this any more # class ThreadSafeDict(object): # def __init__(self): # import threading # sel...
224
224
749
17
207
legacysurvey/pipeline
py/legacypipe/farm.py
Python
queue_work
queue_work
876
956
876
876
e35903c5831306814709eb6f5ad66d24e203fb80
bigcode/the-stack
train
0ec55efd7cc7798805692b6d
train
function
def output_thread(queuename, outqueue, checkpointqueue, blobsizes, finished_bricks, opt): try: import setproctitle setproctitle.setproctitle('farm: output') except: pass import qdo q = qdo.connect(queuename) allresults = {} # Stored values from the 'b...
def output_thread(queuename, outqueue, checkpointqueue, blobsizes, finished_bricks, opt):
try: import setproctitle setproctitle.setproctitle('farm: output') except: pass import qdo q = qdo.connect(queuename) allresults = {} # Stored values from the 'blobsizes' queue. # brick -> (nblobs, qdo_taskid) brick_info = {} # Local mapping of brickname -...
-empty result') resultsreceived += 1 # Parse metadata of the result. (brick,iblob,cpu,wall,overhead) = pickle.loads(meta) brick_cputime[brick] += cpu brick_nblobs [brick] += 1 status_cputime += cpu status_walltime += wall status_overhead += overhead ...
256
256
1,430
24
232
legacysurvey/pipeline
py/legacypipe/farm.py
Python
output_thread
output_thread
632
796
632
633
3079a0d543c175fd603485cf48eacaf4123d61e0
bigcode/the-stack
train
1ec655d8a694ed0fd546e2f5
train
function
def input_thread(queuename, inqueue, bigqueue, checkpointqueue, blobsizes, opt, input_num): try: import setproctitle setproctitle.setproctitle('farm: input_%i' % input_num) except: pass #info('Input process', os.getpid(), 'starting') import qdo q = qdo.connect(queuename) ...
def input_thread(queuename, inqueue, bigqueue, checkpointqueue, blobsizes, opt, input_num):
try: import setproctitle setproctitle.setproctitle('farm: input_%i' % input_num) except: pass #info('Input process', os.getpid(), 'starting') import qdo q = qdo.connect(queuename) while True: task = q.get(timeout=10) if task is None: #- no mo...
', inqueue.qsize()) nq += 1 dest_queue.put(qitem) # Finished queuing all blobs for this brick -- record how many blobs we sent out. return nchk + nq def input_thread(queuename, inqueue, bigqueue, checkpointqueue, blobsizes, opt, input_num):
70
70
234
25
44
legacysurvey/pipeline
py/legacypipe/farm.py
Python
input_thread
input_thread
958
987
958
959
43b5016f973d8e7d3d6b1b5168621dcd42a49708
bigcode/the-stack
train
c92d2ba80e19da098706331b
train
function
def main(): import argparse parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('queue', help='QDO queue name to get brick names from') parser.add_argument('--pickle', default='pickles/runbrick-%(brick)s-srcs.pickle', ...
def main():
import argparse parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('queue', help='QDO queue name to get brick names from') parser.add_argument('--pickle', default='pickles/runbrick-%(brick)s-srcs.pickle', help='Pi...
them share a single queue. There is no particular reason they need to share a queue; we would then have to implement a simple round-robin scheme to pull work from the different input_queues. - currently, the worker.py processes are synchronous: they ask for work, wait for the reply, do the work, and send in t...
256
256
1,037
3
253
legacysurvey/pipeline
py/legacypipe/farm.py
Python
main
main
165
272
165
165
bbd541f7b29a1286e62eaff3cf48678b5a597cb7
bigcode/the-stack
train
53edd324791d834cc30d6fbc
train
function
def info(*args): from legacypipe.utils import log_info log_info(logger, args)
def info(*args):
from legacypipe.utils import log_info log_info(logger, args)
import sys import os import pickle import time from collections import Counter, OrderedDict import multiprocessing as mp import queue import zmq from legacypipe.runbrick import _blob_iter, _write_checkpoint import logging logger = logging.getLogger('farm') def info(*args):
64
64
23
5
59
legacysurvey/pipeline
py/legacypipe/farm.py
Python
info
info
158
160
158
158
383c957cef9df9c2f7b7bd4be192f218ccb8f56f
bigcode/the-stack
train
b5e098baf5da0e81f4723863
train
function
def debug(*args): from legacypipe.utils import log_debug log_debug(logger, args)
def debug(*args):
from legacypipe.utils import log_debug log_debug(logger, args)
mp import queue import zmq from legacypipe.runbrick import _blob_iter, _write_checkpoint import logging logger = logging.getLogger('farm') def info(*args): from legacypipe.utils import log_info log_info(logger, args) def debug(*args):
64
64
23
5
59
legacysurvey/pipeline
py/legacypipe/farm.py
Python
debug
debug
161
163
161
161
d5dfd8aa5eeecdccdf939e7936ef32cdb05d8a77
bigcode/the-stack
train
6ecb4f7ebd35022a817417f9
train
class
class PrioritizedItem(object): def __init__(self, priority=0, item=None): self.priority = priority self.item = item def __lt__(self, other): return self.priority < other.priority
class PrioritizedItem(object):
def __init__(self, priority=0, item=None): self.priority = priority self.item = item def __lt__(self, other): return self.priority < other.priority
refmap, large_galaxies_force_pointsource, less_masking, brick, frozen_galaxies, max_blobsize=max_blobsize, custom_brick=custom_brick, skipblobs=skipblobs) retu...
64
64
49
6
57
legacysurvey/pipeline
py/legacypipe/farm.py
Python
PrioritizedItem
PrioritizedItem
845
850
845
845
0e5d336f24bb421b97377ed19c9e0f9d859520d8
bigcode/the-stack
train
d3b45cac3e2e617d72b971cd
train
function
def get_blob_iter(skipblobs=None, brickname=None, brick=None, blobsrcs=None, blobslices=None, blobmap=None, cat=None, targetwcs=None, W=None,H=None, bands=None, ps=None, tims=None, ...
def get_blob_iter(skipblobs=None, brickname=None, brick=None, blobsrcs=None, blobslices=None, blobmap=None, cat=None, targetwcs=None, W=None,H=None, bands=None, ps=None, tims=None, ...
from legacypipe.runbrick import get_frozen_galaxies, get_blobiter_ref_map if skipblobs is None: skipblobs = [] # drop any cached data before we start pickling/multiprocessing survey.drop_cache() frozen_galaxies = get_frozen_galaxies(T, blobsrcs, blobmap, targetwcs, cat) refmap = get_bl...
def get_blob_iter(skipblobs=None, brickname=None, brick=None, blobsrcs=None, blobslices=None, blobmap=None, cat=None, targetwcs=None, W=None,H=None, bands=None, ps=None, tims=None, ...
138
109
364
138
0
legacysurvey/pipeline
py/legacypipe/farm.py
Python
get_blob_iter
get_blob_iter
799
843
799
820
34d3ccf0ccc5e8303d46f61714f5d891c36eb3cd
bigcode/the-stack
train
6e2b27a140ce7044e4bf8b10
train
function
@loglevel_command() @click.option("-c", "--cluster-name", help="cluster name", required=True) @click.option("--force", "force_deletion", help="Force deletion of the cluster", is_flag=True) def rm(cluster_name: str, force_deletion: bool): """Delete a Red Hat OpenShift on IBM Cloud cluster""" delete_ibmcloud_clu...
@loglevel_command() @click.option("-c", "--cluster-name", help="cluster name", required=True) @click.option("--force", "force_deletion", help="Force deletion of the cluster", is_flag=True) def rm(cluster_name: str, force_deletion: bool):
"""Delete a Red Hat OpenShift on IBM Cloud cluster""" delete_ibmcloud_cluster(cluster_name, force_deletion)
.utils.logging import loglevel_command @loglevel_command() @click.option("-c", "--cluster-name", help="cluster name", required=True) @click.option("--force", "force_deletion", help="Force deletion of the cluster", is_flag=True) def rm(cluster_name: str, force_deletion: bool):
64
64
83
57
6
IBM/data-gate-cli
cpo/commands/ibmcloud/oc/cluster/rm.py
Python
rm
rm
21
27
21
24
86bd11b79c5b5e5808670e153b4f0e28f882ca38
bigcode/the-stack
train
a4a874305cd0ab0090072ffd
train
class
class NaiveSumModel(AttalosModel): """ This model performs linear regression via NN using the naive sum of word vectors as targets. """ def _construct_model_info(self, input_size, output_size, learning_rate, hidden_units=[200]): logger.info("Input size: %s" % input_...
class NaiveSumModel(AttalosModel):
""" This model performs linear regression via NN using the naive sum of word vectors as targets. """ def _construct_model_info(self, input_size, output_size, learning_rate, hidden_units=[200]): logger.info("Input size: %s" % input_size) logger.info("Output s...
import numpy as np import tensorflow as tf from attalos.util.transformers.newnaivew2v import NaiveW2V import attalos.util.log.log as l from attalos.imgtxt_algorithms.approaches.base import AttalosModel from attalos.util.transformers.onehot import OneHot from attalos.imgtxt_algorithms.correlation.correlation import con...
104
256
948
10
94
Lab41/attalos
attalos/imgtxt_algorithms/approaches/naivesum.py
Python
NaiveSumModel
NaiveSumModel
13
108
13
13
b7e4720084b75e630f386aea0aa6c9945911c05c
bigcode/the-stack
train