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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d73629194d496280149320db | train | function | def main(argv):
if sys.hexversion < 0x02060000:
print('\nYour python version %s is unsupported, please upgrade.\n'
% (sys.version.split(' ', 1)[0],),
file=sys.stderr)
return 2
dispatcher = subcommand.CommandDispatcher(__name__)
return dispatcher.execute(OptionParser(), argv)
| def main(argv):
| if sys.hexversion < 0x02060000:
print('\nYour python version %s is unsupported, please upgrade.\n'
% (sys.version.split(' ', 1)[0],),
file=sys.stderr)
return 2
dispatcher = subcommand.CommandDispatcher(__name__)
return dispatcher.execute(OptionParser(), argv)
| , args, values)
# Host is always required
assert options.host, "--host not defined."
levels = [logging.WARNING, logging.INFO, logging.DEBUG]
logging.basicConfig(level=levels[min(options.verbose, len(levels) - 1)])
return options, args
def main(argv):
| 64 | 64 | 78 | 4 | 59 | yefengfang/depot_tools | gerrit_client.py | Python | main | main | 191 | 198 | 191 | 191 | bf4da90c4f590f0b7685e539260d122dba637ab3 | bigcode/the-stack | train |
2105e68171af4dfaac83197c | train | function | @subcommand.usage('[args ...]')
def CMDbranch(parser, args):
parser.add_option('--branch', dest='branch', help='branch name')
parser.add_option('--commit', dest='commit', help='commit hash')
(opt, args) = parser.parse_args(args)
assert opt.project, "--project not defined"
assert opt.branch, "--branch not def... | @subcommand.usage('[args ...]')
def CMDbranch(parser, args):
| parser.add_option('--branch', dest='branch', help='branch name')
parser.add_option('--commit', dest='commit', help='commit hash')
(opt, args) = parser.parse_args(args)
assert opt.project, "--project not defined"
assert opt.branch, "--branch not defined"
assert opt.commit, "--commit not defined"
project ... | loc
project = quote_plus(opt.project)
branch = quote_plus(opt.branch)
result = gerrit_util.GetGerritBranch(host, project, branch)
logging.info(result)
write_result(result, opt)
@subcommand.usage('[args ...]')
def CMDbranch(parser, args):
| 64 | 64 | 159 | 16 | 48 | yefengfang/depot_tools | gerrit_client.py | Python | CMDbranch | CMDbranch | 81 | 97 | 81 | 82 | d2ca4ed570da3b291092c78571a598f6b9cf3704 | bigcode/the-stack | train |
0532922ea4dbae5967422188 | train | function | @subcommand.usage('[args ...]')
def CMDbranchinfo(parser, args):
parser.add_option('--branch', dest='branch', help='branch name')
(opt, args) = parser.parse_args(args)
host = urlparse.urlparse(opt.host).netloc
project = quote_plus(opt.project)
branch = quote_plus(opt.branch)
result = gerrit_util.GetGerritB... | @subcommand.usage('[args ...]')
def CMDbranchinfo(parser, args):
| parser.add_option('--branch', dest='branch', help='branch name')
(opt, args) = parser.parse_args(args)
host = urlparse.urlparse(opt.host).netloc
project = quote_plus(opt.project)
branch = quote_plus(opt.branch)
result = gerrit_util.GetGerritBranch(host, project, branch)
logging.info(result)
write_resul... | limit=limit,
)
for change in result:
gerrit_util.MoveChange(host, change['id'], opt.destination_branch)
if len(result) < limit:
break
logging.info("Done")
@subcommand.usage('[args ...]')
def CMDbranchinfo(parser, args):
| 64 | 64 | 104 | 17 | 47 | yefengfang/depot_tools | gerrit_client.py | Python | CMDbranchinfo | CMDbranchinfo | 68 | 78 | 68 | 69 | c7a99ecfe787867c90147983e0360d98a36f3998 | bigcode/the-stack | train |
97ee9a34333318530afcbaba | train | function | @subcommand.usage('[args ...]')
def CMDheadinfo(parser, args):
(opt, args) = parser.parse_args(args)
assert opt.project, "--project not defined"
project = quote_plus(opt.project)
host = urlparse.urlparse(opt.host).netloc
result = gerrit_util.GetHead(host, project)
logging.info(result)
write_result(resul... | @subcommand.usage('[args ...]')
def CMDheadinfo(parser, args):
| (opt, args) = parser.parse_args(args)
assert opt.project, "--project not defined"
project = quote_plus(opt.project)
host = urlparse.urlparse(opt.host).netloc
result = gerrit_util.GetHead(host, project)
logging.info(result)
write_result(result, opt)
| host = urlparse.urlparse(opt.host).netloc
branch = quote_plus(opt.branch)
result = gerrit_util.UpdateHead(host, project, branch)
logging.info(result)
write_result(result, opt)
@subcommand.usage('[args ...]')
def CMDheadinfo(parser, args):
| 64 | 64 | 85 | 17 | 47 | yefengfang/depot_tools | gerrit_client.py | Python | CMDheadinfo | CMDheadinfo | 116 | 126 | 116 | 118 | ec5b9324ee020e353476ac5520672e6f953df4bc | bigcode/the-stack | train |
30dc845cfb12b706a00d427f | train | function | @subcommand.usage('[args ...]')
def CMDhead(parser, args):
parser.add_option('--branch', dest='branch', help='branch name')
(opt, args) = parser.parse_args(args)
assert opt.project, "--project not defined"
assert opt.branch, "--branch not defined"
project = quote_plus(opt.project)
host = urlparse.urlparse... | @subcommand.usage('[args ...]')
def CMDhead(parser, args):
| parser.add_option('--branch', dest='branch', help='branch name')
(opt, args) = parser.parse_args(args)
assert opt.project, "--project not defined"
assert opt.branch, "--branch not defined"
project = quote_plus(opt.project)
host = urlparse.urlparse(opt.host).netloc
branch = quote_plus(opt.branch)
resul... | branch = quote_plus(opt.branch)
commit = quote_plus(opt.commit)
result = gerrit_util.CreateGerritBranch(host, project, branch, commit)
logging.info(result)
write_result(result, opt)
@subcommand.usage('[args ...]')
def CMDhead(parser, args):
| 64 | 64 | 120 | 16 | 48 | yefengfang/depot_tools | gerrit_client.py | Python | CMDhead | CMDhead | 100 | 113 | 100 | 101 | 490ad31ce94f5b4436f8d862124cbc47defad65d | bigcode/the-stack | train |
a8df989a72ef4ff8825a5e98 | train | function | @subcommand.usage('[args ...]')
def CMDchanges(parser, args):
parser.add_option('-p', '--param', dest='params', action='append',
help='repeatable query parameter, format: -p key=value')
parser.add_option('-o', '--o-param', dest='o_params', action='append',
help='gerrit output... | @subcommand.usage('[args ...]')
def CMDchanges(parser, args):
| parser.add_option('-p', '--param', dest='params', action='append',
help='repeatable query parameter, format: -p key=value')
parser.add_option('-o', '--o-param', dest='o_params', action='append',
help='gerrit output parameters, e.g. ALL_REVISIONS')
parser.add_option('--limit... | (opt, args) = parser.parse_args(args)
assert opt.project, "--project not defined"
project = quote_plus(opt.project)
host = urlparse.urlparse(opt.host).netloc
result = gerrit_util.GetHead(host, project)
logging.info(result)
write_result(result, opt)
@subcommand.usage('[args ...]')
def CMDchanges(parser, ar... | 83 | 83 | 278 | 16 | 67 | yefengfang/depot_tools | gerrit_client.py | Python | CMDchanges | CMDchanges | 129 | 153 | 129 | 130 | 638e6f3cbc6027596c60c9dde33a5827a05e4c51 | bigcode/the-stack | train |
c31d6c5fb4f5a08963db129d | train | function | def write_result(result, opt):
if opt.json_file:
with open(opt.json_file, 'w') as json_file:
json_file.write(json.dumps(result))
| def write_result(result, opt):
| if opt.json_file:
with open(opt.json_file, 'w') as json_file:
json_file.write(json.dumps(result))
| == 2:
import urlparse
from urllib import quote_plus
else:
from urllib.parse import quote_plus
import urllib.parse as urlparse
import fix_encoding
import gerrit_util
import setup_color
__version__ = '0.1'
def write_result(result, opt):
| 64 | 64 | 35 | 7 | 57 | yefengfang/depot_tools | gerrit_client.py | Python | write_result | write_result | 34 | 37 | 34 | 34 | 4eec0a9f52798c9d66cf02ba0a5a61464b2d1c3c | bigcode/the-stack | train |
9a67d6bbe43059c3eb4be8e6 | train | function | def gini(array):
# based on bottom eq:
# http://www.statsdirect.com/help/generatedimages/equations/equation154.svg
# from:
# http://www.statsdirect.com/help/default.htm#nonparametric_methods/gini.htm
# All values are treated equally, arrays must be 1d:
array = np.array(array.flatten(), dtype=np.... | def gini(array):
# based on bottom eq:
# http://www.statsdirect.com/help/generatedimages/equations/equation154.svg
# from:
# http://www.statsdirect.com/help/default.htm#nonparametric_methods/gini.htm
# All values are treated equally, arrays must be 1d:
| array = np.array(array.flatten(), dtype=np.float64)
array = np.abs(array)
# Values cannot be 0:
array += 0.0000001
# Values must be sorted:
array = np.sort(array)
# Index per array element:
index = np.arange(1, array.shape[0] + 1)
# Number of array elements:
n = array.shape[0]
... | def gini(array):
# based on bottom eq:
# http://www.statsdirect.com/help/generatedimages/equations/equation154.svg
# from:
# http://www.statsdirect.com/help/default.htm#nonparametric_methods/gini.htm
# All values are treated equally, arrays must be 1d:
| 71 | 64 | 194 | 71 | 0 | pinjutien/DeepExplain | examples/run_gini.py | Python | gini | gini | 15 | 32 | 15 | 20 | 1bb96ad8bdad64e5337734b43f19f904b95649b1 | bigcode/the-stack | train |
0f366f8ac85549c592de014c | train | function | def setup(bot):
bot.add_cog(Setup(bot)) | def setup(bot):
| bot.add_cog(Setup(bot)) | .set_permissions(ctx.guild.default_role, send_messages=False, read_messages=False)
log_channel_id = logs.id
self.db.execute("INSERT INTO Logging VALUES (?, ?)", (ctx.guild.id, logs.id))
await ctx.send(f"Successfully setup the server, <#{logs.id}>")
def setup(bot):
| 64 | 64 | 12 | 4 | 60 | plun1331/Coffee | cogs/setup.py | Python | setup | setup | 23 | 24 | 23 | 23 | a5d01dee29ce247014246da1b1262bf703564f33 | bigcode/the-stack | train |
be90b308b3a2b2e387f69805 | train | class | class Setup(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.db = sqlite.Database()
@commands.command(
name = "setup",
help = "Setup the bot for the server."
)
async def setup_(self, ctx : commands.Context):
await ctx.guild.create_text_channel('coffee-logs')
logs = discord.ut... | class Setup(commands.Cog):
| def __init__(self, bot):
self.bot = bot
self.db = sqlite.Database()
@commands.command(
name = "setup",
help = "Setup the bot for the server."
)
async def setup_(self, ctx : commands.Context):
await ctx.guild.create_text_channel('coffee-logs')
logs = discord.utils.get(ctx.guild.channels,... | import discord
from discord.ext import commands
from utils.database import create_tables, sqlite
tables = create_tables.creation(debug=True)
class Setup(commands.Cog):
| 32 | 64 | 155 | 6 | 26 | plun1331/Coffee | cogs/setup.py | Python | Setup | Setup | 6 | 21 | 6 | 6 | 53e4b7fa52762ad4ad3dfe9cd303a11e47589309 | bigcode/the-stack | train |
6346b4658fb25e2d7b0c1df7 | train | class | class PostLoginFlowMixin:
"""
Helpers for post login flow
"""
def login_flow(self) -> bool:
"""
Emulation mobile app behaivor after login
Returns
-------
bool
A boolean value
"""
check_flow = []
# chance = random.randint(1, 10... | class PostLoginFlowMixin:
| """
Helpers for post login flow
"""
def login_flow(self) -> bool:
"""
Emulation mobile app behaivor after login
Returns
-------
bool
A boolean value
"""
check_flow = []
# chance = random.randint(1, 100) % 2 == 0
# reas... | login=login)
def sync_launcher(self, login: bool = False) -> Dict:
"""
Sync Launcher
Parameters
----------
login: bool, optional
Whether to login or not
Returns
-------
Dict
A dictionary of response from the call
"""... | 256 | 256 | 1,084 | 6 | 250 | Helow19274/instagrapi | instagrapi/mixins/auth.py | Python | PostLoginFlowMixin | PostLoginFlowMixin | 150 | 244 | 150 | 150 | ce4dd7c8e08615c5c4f1a760b2a29fe29e1d303e | bigcode/the-stack | train |
6ccedc7f7f0010bea9d08e5b | train | class | class LoginMixin(PreLoginFlowMixin, PostLoginFlowMixin):
username = None
password = None
authorization = "" # Bearer IGT:2:<base64:authorization_data>
authorization_data = {} # decoded authorization header
last_login = None
relogin_attempt = 0
device_settings = {}
client_session_id = "... | class LoginMixin(PreLoginFlowMixin, PostLoginFlowMixin):
| username = None
password = None
authorization = "" # Bearer IGT:2:<base64:authorization_data>
authorization_data = {} # decoded authorization header
last_login = None
relogin_attempt = 0
device_settings = {}
client_session_id = ""
tray_session_id = ""
advertising_id = ""
an... | \",\"2634303181452199341\",\"2634303245482345741\",\"2634303317473473894\",\"2634303382971517344\",\"2634303441062726263\",\"2634303502039423893\",\"2634303754729475501\"]"},{"reel_id":"4357392188","media_count":"4","timestamp":1628250613,"media_ids":"[\"2634142331579781054\",\"2634142839803515356\",\"26341507865751258... | 256 | 256 | 3,903 | 14 | 242 | Helow19274/instagrapi | instagrapi/mixins/auth.py | Python | LoginMixin | LoginMixin | 247 | 814 | 247 | 247 | 06d931ac509a17ef77e85910efec5d009d245324 | bigcode/the-stack | train |
fa349acba02158a638b00919 | train | class | class PreLoginFlowMixin:
"""
Helpers for pre login flow
"""
def pre_login_flow(self) -> bool:
"""
Emulation mobile app behavior before login
Returns
-------
bool
A boolean value
"""
# self.set_contact_point_prefill("prefill")
... | class PreLoginFlowMixin:
| """
Helpers for pre login flow
"""
def pre_login_flow(self) -> bool:
"""
Emulation mobile app behavior before login
Returns
-------
bool
A boolean value
"""
# self.set_contact_point_prefill("prefill")
# self.get_prefill_candid... | import base64
# import datetime
import hashlib
import hmac
import json
import random
import re
import time
import uuid
from pathlib import Path
from typing import Dict, List
from uuid import uuid4
import requests
from pydantic import ValidationError
from instagrapi import config
from instagrapi.exceptions import (
... | 139 | 214 | 716 | 6 | 132 | Helow19274/instagrapi | instagrapi/mixins/auth.py | Python | PreLoginFlowMixin | PreLoginFlowMixin | 31 | 147 | 31 | 31 | e83dfb4818bbecc6e3216e5ec5e11bb5154e71c0 | bigcode/the-stack | train |
21a5a32c1b005cb8d31fea6a | train | class | class GenshiCheckboxRenderingTest(RadiobuttonRenderingTest):
template_engine = 'genshi'
| class GenshiCheckboxRenderingTest(RadiobuttonRenderingTest):
| template_engine = 'genshi'
| (self):
radiobutton = self._radiobutton()
expected = '<input type="radio" style="margin-top: 10px"/>'
assert_same_html(expected, radiobutton.display(attrs={'style': 'margin-top: 10px'}))
class GenshiCheckboxRenderingTest(RadiobuttonRenderingTest):
| 64 | 64 | 20 | 12 | 52 | FelixSchwarz/grumpywidgets | grumpyforms/fields/tests/radiobutton_test.py | Python | GenshiCheckboxRenderingTest | GenshiCheckboxRenderingTest | 71 | 72 | 71 | 71 | d726de6a90d69bed876b82879df03de7ee57db0d | bigcode/the-stack | train |
38ac7dab3cb6d5f73d6f9c70 | train | class | class RadiobuttonRenderingTest(PythonicTestCase):
template_engine = 'jinja2'
def _radiobutton(self, **kwargs):
return template_widget(Radiobutton, self.template_engine, kwargs)
def test_can_render_unchecked_radiobutton(self):
assert_same_html('<input type="radio" />', self._radiobutton().d... | class RadiobuttonRenderingTest(PythonicTestCase):
| template_engine = 'jinja2'
def _radiobutton(self, **kwargs):
return template_widget(Radiobutton, self.template_engine, kwargs)
def test_can_render_unchecked_radiobutton(self):
assert_same_html('<input type="radio" />', self._radiobutton().display())
assert_same_html('<input type="r... | # This file is a part of GrumpyWidgets.
# The source code contained in this file is licensed under the MIT license.
# See LICENSE.txt in the main project directory, for more information.
from pythonic_testcase import *
from grumpyforms.fields import Radiobutton
from grumpywidgets.testhelpers import assert_same_html, ... | 81 | 199 | 664 | 11 | 69 | FelixSchwarz/grumpywidgets | grumpyforms/fields/tests/radiobutton_test.py | Python | RadiobuttonRenderingTest | RadiobuttonRenderingTest | 12 | 68 | 12 | 12 | 160eeb636937f0521532afb5586d23e6ab47e378 | bigcode/the-stack | train |
b6787132ac6218f02869d588 | train | function | def submit_login(form):
user = User.query.filter_by(email=form.email.data).first()
if user is None or not user.check_password(form.password.data):
flash('Invalid username or password')
return redirect(url_for('login'))
login_user(user)
return redirect(url_for('playlist'))
| def submit_login(form):
| user = User.query.filter_by(email=form.email.data).first()
if user is None or not user.check_password(form.password.data):
flash('Invalid username or password')
return redirect(url_for('login'))
login_user(user)
return redirect(url_for('playlist'))
| from flask import render_template, url_for, flash, redirect
from flask_login import current_user, login_user
from socialPlaylist.models import User, Playlists
def submit_login(form):
| 38 | 64 | 62 | 5 | 32 | Roy-05/social-playlist | socialPlaylist/helpers/login_helpers.py | Python | submit_login | submit_login | 6 | 12 | 6 | 6 | 7cf7ff54bf49d5b716671a90fcc641258ee0f1d0 | bigcode/the-stack | train |
4f9f370a79a3e0c2040ab1ae | train | function | def show_login_form(form):
return render_template('login.html', title='Login', form=form)
| def show_login_form(form):
| return render_template('login.html', title='Login', form=form)
| user = User.query.filter_by(email=form.email.data).first()
if user is None or not user.check_password(form.password.data):
flash('Invalid username or password')
return redirect(url_for('login'))
login_user(user)
return redirect(url_for('playlist'))
def show_login_form(form):
| 63 | 64 | 21 | 6 | 57 | Roy-05/social-playlist | socialPlaylist/helpers/login_helpers.py | Python | show_login_form | show_login_form | 15 | 16 | 15 | 15 | 2e903a1b7256506c8e03cb4624db51edfdf6ddb6 | bigcode/the-stack | train |
78fda86533b177a5f00366cf | train | function | def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f
# NOTE: use multi_control_toffoli_gate ('noancilla' mode)
# https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html
# https://quantumcomputing.stackexchange.com/questions/3943/how-do-yo... | def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f
# NOTE: use multi_control_toffoli_gate ('noancilla' mode)
# https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html
# https://quantumcomputing.stackexchange.com/questions/3943/how-do-yo... | controls = QuantumRegister(n, "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name="Of")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(... | def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f
# NOTE: use multi_control_toffoli_gate ('noancilla' mode)
# https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html
# https://quantumcomputing.stackexchange.com/questions/3943/how-do-yo... | 138 | 83 | 278 | 138 | 0 | UCLA-SEAL/QDiff | benchmark/startQiskit_Class2180.py | Python | build_oracle | build_oracle | 29 | 49 | 29 | 34 | b7a8ed7a88aaeae13a59b1564c24bee83d544220 | bigcode/the-stack | train |
6990b907625b7d076587e51c | train | function | def make_circuit(n:int,f) -> QuantumCircuit:
# circuit begin
input_qubit = QuantumRegister(n,"qc")
classical = ClassicalRegister(n, "qm")
prog = QuantumCircuit(input_qubit, classical)
prog.h(input_qubit[3]) # number=32
prog.cz(input_qubit[0],input_qubit[3]) # number=33
prog.h(input_qubit[3])... | def make_circuit(n:int,f) -> QuantumCircuit:
# circuit begin
| input_qubit = QuantumRegister(n,"qc")
classical = ClassicalRegister(n, "qm")
prog = QuantumCircuit(input_qubit, classical)
prog.h(input_qubit[3]) # number=32
prog.cz(input_qubit[0],input_qubit[3]) # number=33
prog.h(input_qubit[3]) # number=34
prog.h(input_qubit[3]) # number=26
prog.cz(i... | exchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate
controls = QuantumRegister(n, "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name="Of")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in ran... | 177 | 177 | 591 | 17 | 159 | UCLA-SEAL/QDiff | benchmark/startQiskit_Class2180.py | Python | make_circuit | make_circuit | 51 | 94 | 51 | 52 | 5aa8f363ef3a9e0d5524fe31406d5f61a1af34a8 | bigcode/the-stack | train |
4db71e593d859f6bfe10e577 | train | function | def bitwise_xor(s: str, t: str) -> str:
length = len(s)
res = []
for i in range(length):
res.append(str(int(s[i]) ^ int(t[i])))
return ''.join(res[::-1])
| def bitwise_xor(s: str, t: str) -> str:
| length = len(s)
res = []
for i in range(length):
res.append(str(int(s[i]) ^ int(t[i])))
return ''.join(res[::-1])
| Register
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2
import numpy as np
import networkx as nx
def bitwise_xor(s: str, t: str) -> str:
| 64 | 64 | 54 | 16 | 47 | UCLA-SEAL/QDiff | benchmark/startQiskit_Class2180.py | Python | bitwise_xor | bitwise_xor | 14 | 19 | 14 | 14 | 643dca80c9054c8a7c10bfe226d5dd994f1f8215 | bigcode/the-stack | train |
bcec76a2d498badeba877da0 | train | function | def bitwise_dot(s: str, t: str) -> str:
length = len(s)
res = 0
for i in range(length):
res += int(s[i]) * int(t[i])
return str(res % 2)
| def bitwise_dot(s: str, t: str) -> str:
| length = len(s)
res = 0
for i in range(length):
res += int(s[i]) * int(t[i])
return str(res % 2)
| (s: str, t: str) -> str:
length = len(s)
res = []
for i in range(length):
res.append(str(int(s[i]) ^ int(t[i])))
return ''.join(res[::-1])
def bitwise_dot(s: str, t: str) -> str:
| 64 | 64 | 54 | 15 | 49 | UCLA-SEAL/QDiff | benchmark/startQiskit_Class2180.py | Python | bitwise_dot | bitwise_dot | 22 | 27 | 22 | 22 | 078fbe078cfdf1766c9b9ac20f7a3207be47445c | bigcode/the-stack | train |
422ba28343d66d5d3cafa73b | train | class | class TestBuild(unittest.TestCase):
def test_name_clash(self):
# For setup.py, all translation units need distinct names, so we
# cannot have foo.cu and foo.cpp, even in different directories.
source_dir = get_pytorch3d_dir() / "pytorch3d"
stems = []
for extension in [".cu",... | class TestBuild(unittest.TestCase):
| def test_name_clash(self):
# For setup.py, all translation units need distinct names, so we
# cannot have foo.cu and foo.cpp, even in different directories.
source_dir = get_pytorch3d_dir() / "pytorch3d"
stems = []
for extension in [".cu", ".cpp"]:
files = source... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import importlib
import json
import os
import sys
import unittest
import unittest.mock
from collections import Co... | 141 | 256 | 1,055 | 7 | 133 | jkxing/pytorch3d | tests/test_build.py | Python | TestBuild | TestBuild | 23 | 136 | 23 | 23 | 25d27d0d9515d2d06fa491adecc6d4df22b5826d | bigcode/the-stack | train |
79b97bca698ff9eff2436824 | train | function | def init_app(app):
SimpleLogin(app, login_checker=verify_login)
| def init_app(app):
| SimpleLogin(app, login_checker=verify_login)
| ):
"""Creates a new user"""
if User.query.filter_by(username=username).first():
raise RuntimeError(f"{username} already exists")
user = User(username=username, password=generate_password_hash(password))
db.session.add(user)
db.session.commit()
return user
def init_app(app):
| 64 | 64 | 16 | 5 | 58 | RobinCHoffpauir/app | app/ext/auth.py | Python | init_app | init_app | 32 | 33 | 32 | 32 | ef734dadf663d0c3cacbac6ead228a8f86b33cd9 | bigcode/the-stack | train |
31caaeecb8db5877e4d5bd6b | train | function | def verify_login(user):
"""Validates user login"""
username = user.get("username")
password = user.get("password")
if not username or not password:
return False
existing_user = User.query.filter_by(username=username).first()
if not existing_user:
return False
if check_passwor... | def verify_login(user):
| """Validates user login"""
username = user.get("username")
password = user.get("password")
if not username or not password:
return False
existing_user = User.query.filter_by(username=username).first()
if not existing_user:
return False
if check_password_hash(existing_user.pas... | from flask_simplelogin import SimpleLogin
from werkzeug.security import check_password_hash, generate_password_hash
from app.ext.database import db
from app.models import User
def verify_login(user):
| 39 | 64 | 82 | 5 | 33 | RobinCHoffpauir/app | app/ext/auth.py | Python | verify_login | verify_login | 8 | 19 | 8 | 8 | 9567e2451ba4c95853816f85f0ebacbe395ce9b1 | bigcode/the-stack | train |
4bad99128fcbbbf73eb4ce5a | train | function | def create_user(username, password):
"""Creates a new user"""
if User.query.filter_by(username=username).first():
raise RuntimeError(f"{username} already exists")
user = User(username=username, password=generate_password_hash(password))
db.session.add(user)
db.session.commit()
return use... | def create_user(username, password):
| """Creates a new user"""
if User.query.filter_by(username=username).first():
raise RuntimeError(f"{username} already exists")
user = User(username=username, password=generate_password_hash(password))
db.session.add(user)
db.session.commit()
return user
| ("password")
if not username or not password:
return False
existing_user = User.query.filter_by(username=username).first()
if not existing_user:
return False
if check_password_hash(existing_user.password, password):
return True
return False
def create_user(username, password)... | 64 | 64 | 65 | 7 | 56 | RobinCHoffpauir/app | app/ext/auth.py | Python | create_user | create_user | 22 | 29 | 22 | 22 | 07b6ca76a8b495992a90e9b981a968d6a50db4d5 | bigcode/the-stack | train |
d687f9afa6d68f04002a1da5 | train | function | def name_to_ipv6(addr):
if len(addr)>6 and addr.endswith('.onion'):
vchAddr = b32decode(addr[0:-6], True)
if len(vchAddr) != 16-len(pchOnionCat):
raise ValueError('Invalid onion %s' % s)
return pchOnionCat + vchAddr
elif '.' in addr: # IPv4
return pchIPv4 + bytearray(... | def name_to_ipv6(addr):
| if len(addr)>6 and addr.endswith('.onion'):
vchAddr = b32decode(addr[0:-6], True)
if len(vchAddr) != 16-len(pchOnionCat):
raise ValueError('Invalid onion %s' % s)
return pchOnionCat + vchAddr
elif '.' in addr: # IPv4
return pchIPv4 + bytearray((int(x) for x in addr.sp... | import sys, os
import re
# ipv4 in ipv6 prefix
pchIPv4 = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff])
# tor-specific ipv6 prefix
pchOnionCat = bytearray([0xFD,0x87,0xD8,0x7E,0xEB,0x43])
def name_to_ipv6(addr):
| 108 | 108 | 363 | 7 | 101 | worgon12/Galleoncoin | contrib/seeds/generate-seeds.py | Python | name_to_ipv6 | name_to_ipv6 | 45 | 73 | 45 | 45 | 2e80f2c9f04d5ed5acb45ee10216dfdff6b1eba7 | bigcode/the-stack | train |
39ee859c7dab26b415c4b882 | train | function | def process_nodes(g, f, structname, defaultport):
g.write('static SeedSpec6 %s[] = {\n' % structname)
first = True
for line in f:
comment = line.find('#')
if comment != -1:
line = line[0:comment]
line = line.strip()
if not line:
continue
if not... | def process_nodes(g, f, structname, defaultport):
| g.write('static SeedSpec6 %s[] = {\n' % structname)
first = True
for line in f:
comment = line.find('#')
if comment != -1:
line = line[0:comment]
line = line.strip()
if not line:
continue
if not first:
g.write(',\n')
first =... | else:
(host,_,port) = s.partition(':')
if not port:
port = defaultport
else:
port = int(port)
host = name_to_ipv6(host)
return (host,port)
def process_nodes(g, f, structname, defaultport):
| 64 | 64 | 161 | 13 | 51 | worgon12/Galleoncoin | contrib/seeds/generate-seeds.py | Python | process_nodes | process_nodes | 95 | 112 | 95 | 95 | 3dbce44502830f85f28bc4c7456018b89dd95fb8 | bigcode/the-stack | train |
7f445a8afd59d868cc92897c | train | function | def parse_spec(s, defaultport):
match = re.match('\[([0-9a-fA-F:]+)\](?::([0-9]+))?$', s)
if match: # ipv6
host = match.group(1)
port = match.group(2)
elif s.count(':') > 1: # ipv6, no port
host = s
port = ''
else:
(host,_,port) = s.partition(':')
if not port... | def parse_spec(s, defaultport):
| match = re.match('\[([0-9a-fA-F:]+)\](?::([0-9]+))?$', s)
if match: # ipv6
host = match.group(1)
port = match.group(2)
elif s.count(':') > 1: # ipv6, no port
host = s
port = ''
else:
(host,_,port) = s.partition(':')
if not port:
port = defaultport
... | ])
elif addr.startswith('0x'): # IPv4-in-little-endian
return pchIPv4 + bytearray(reversed(a2b_hex(addr[2:])))
else:
raise ValueError('Could not parse address %s' % addr)
def parse_spec(s, defaultport):
| 64 | 64 | 141 | 8 | 56 | worgon12/Galleoncoin | contrib/seeds/generate-seeds.py | Python | parse_spec | parse_spec | 75 | 93 | 75 | 75 | dd000d35b717ae4c4e4581d24307f0f33a3c07dc | bigcode/the-stack | train |
0550c821d38c3adb8525f1c1 | train | function | def main():
if len(sys.argv)<2:
print(('Usage: %s <path_to_nodes_txt>' % sys.argv[0]), file=sys.stderr)
exit(1)
g = sys.stdout
indir = sys.argv[1]
g.write('#ifndef BITCOIN_CHAINPARAMSSEEDS_H\n')
g.write('#define BITCOIN_CHAINPARAMSSEEDS_H\n')
g.write('/**\n')
g.write(' * List... | def main():
| if len(sys.argv)<2:
print(('Usage: %s <path_to_nodes_txt>' % sys.argv[0]), file=sys.stderr)
exit(1)
g = sys.stdout
indir = sys.argv[1]
g.write('#ifndef BITCOIN_CHAINPARAMSSEEDS_H\n')
g.write('#define BITCOIN_CHAINPARAMSSEEDS_H\n')
g.write('/**\n')
g.write(' * List of fixed se... | if not first:
g.write(',\n')
first = False
(host,port) = parse_spec(line, defaultport)
hoststr = ','.join(('0x%02x' % b) for b in host)
g.write(' {{%s}, %i}' % (hoststr, port))
g.write('\n};\n')
def main():
| 84 | 84 | 282 | 3 | 81 | worgon12/Galleoncoin | contrib/seeds/generate-seeds.py | Python | main | main | 114 | 134 | 114 | 114 | f724688069020ee4e48f1a76d0b4eeed1ee19185 | bigcode/the-stack | train |
3d37750333d10cd267a15568 | train | class | @LOSSES.register_module()
class SmoothL1Loss(nn.Module):
"""Smooth L1 loss.
Args:
beta (float, optional): The threshold in the piecewise function.
Defaults to 1.0.
reduction (str, optional): The method to reduce the loss.
Options are "none", "mean" and "sum". Def... | @LOSSES.register_module()
class SmoothL1Loss(nn.Module):
| """Smooth L1 loss.
Args:
beta (float, optional): The threshold in the piecewise function.
Defaults to 1.0.
reduction (str, optional): The method to reduce the loss.
Options are "none", "mean" and "sum". Defaults to "mean".
loss_weight (float, optional): Th... | it(derivate=True, coderize=True)
@weighted_loss
def l1_loss(pred, target):
"""L1 loss.
Args:
pred (torch.Tensor): The prediction.
target (torch.Tensor): The learning target of the prediction.
Returns:
torch.Tensor: Calculated loss
"""
assert pred.size() == targe... | 111 | 111 | 370 | 14 | 96 | yypurpose/mmdetection | mmdet/models/losses/smooth_l1_loss.py | Python | SmoothL1Loss | SmoothL1Loss | 48 | 97 | 48 | 49 | 7235d1b737188315ad2dc4a65fd70066fe8d73da | bigcode/the-stack | train |
f3bf005a041ddccba31df388 | train | class | @LOSSES.register_module()
class L1Loss(nn.Module):
"""L1 loss.
Args:
reduction (str, optional): The method to reduce the loss.
Options are "none", "mean" and "sum".
loss_weight (float, optional): The weight of loss.
"""
def __init__(self, reduction='mean', loss_we... | @LOSSES.register_module()
class L1Loss(nn.Module):
| """L1 loss.
Args:
reduction (str, optional): The method to reduce the loss.
Options are "none", "mean" and "sum".
loss_weight (float, optional): The weight of loss.
"""
def __init__(self, reduction='mean', loss_weight=1.0):
super(L1Loss, self).__init__()
... | assert reduction_override in (None, 'none', 'mean', 'sum')
reduction = (
reduction_override if reduction_override else self.reduction)
loss_bbox = self.loss_weight * smooth_l1_loss(
pred,
target,
weight,
beta=self.beta,
red... | 92 | 92 | 308 | 13 | 78 | yypurpose/mmdetection | mmdet/models/losses/smooth_l1_loss.py | Python | L1Loss | L1Loss | 100 | 139 | 100 | 101 | d4bf543d96a49da59eb6ab922d6fbdd90f0dc335 | bigcode/the-stack | train |
a98c1cd3fa31b4ca5e1c17a7 | train | function | @mmcv.jit(derivate=True, coderize=True)
@weighted_loss
def l1_loss(pred, target):
"""L1 loss.
Args:
pred (torch.Tensor): The prediction.
target (torch.Tensor): The learning target of the prediction.
Returns:
torch.Tensor: Calculated loss
"""
assert pred.size() =... | @mmcv.jit(derivate=True, coderize=True)
@weighted_loss
def l1_loss(pred, target):
| """L1 loss.
Args:
pred (torch.Tensor): The prediction.
target (torch.Tensor): The learning target of the prediction.
Returns:
torch.Tensor: Calculated loss
"""
assert pred.size() == target.size() and target.numel() > 0
loss = torch.abs(pred - target)
retu... | (pred - target)
loss = torch.where(diff < beta, 0.5 * diff * diff / beta,
diff - 0.5 * beta)
return loss
@mmcv.jit(derivate=True, coderize=True)
@weighted_loss
def l1_loss(pred, target):
| 64 | 64 | 101 | 26 | 37 | yypurpose/mmdetection | mmdet/models/losses/smooth_l1_loss.py | Python | l1_loss | l1_loss | 31 | 45 | 31 | 33 | b9666a595a3170d95883df0ad9def6a8c16c0e4f | bigcode/the-stack | train |
838eb2163b1fe22e632ef65f | train | function | @mmcv.jit(derivate=True, coderize=True)
@weighted_loss
def smooth_l1_loss(pred, target, beta=1.0):
"""Smooth L1 loss.
Args:
pred (torch.Tensor): The prediction.
target (torch.Tensor): The learning target of the prediction.
beta (float, optional): The threshold in the piecewise f... | @mmcv.jit(derivate=True, coderize=True)
@weighted_loss
def smooth_l1_loss(pred, target, beta=1.0):
| """Smooth L1 loss.
Args:
pred (torch.Tensor): The prediction.
target (torch.Tensor): The learning target of the prediction.
beta (float, optional): The threshold in the piecewise function.
Defaults to 1.0.
Returns:
torch.Tensor: Calculated loss
"""... | import mmcv
import torch
import torch.nn as nn
from ..builder import LOSSES
from .utils import weighted_loss
@mmcv.jit(derivate=True, coderize=True)
@weighted_loss
def smooth_l1_loss(pred, target, beta=1.0):
| 60 | 64 | 169 | 33 | 26 | yypurpose/mmdetection | mmdet/models/losses/smooth_l1_loss.py | Python | smooth_l1_loss | smooth_l1_loss | 9 | 28 | 9 | 11 | 5933950c82b3c18e67bd5c72a5a8074b6b085d02 | bigcode/the-stack | train |
1c76eb94ffe0d0769c8dabb9 | train | class | class LayerArtist(LayerArtistBase):
# NOTE: this class can be removed and replaced with
# glue.viewers.common.layer_artist.LayerArtist once glue 0.15 is out.
zorder = CallbackProperty()
visible = CallbackProperty()
_layer_state_cls = LayerState
def __init__(self, viewer_state, layer_state=No... | class LayerArtist(LayerArtistBase):
# NOTE: this class can be removed and replaced with
# glue.viewers.common.layer_artist.LayerArtist once glue 0.15 is out.
| zorder = CallbackProperty()
visible = CallbackProperty()
_layer_state_cls = LayerState
def __init__(self, viewer_state, layer_state=None, layer=None):
super(LayerArtist, self).__init__(layer)
self._viewer_state = viewer_state
self.layer = layer or layer_state.layer
s... | # This file is for any compatibility code that can be removed once new releases
# of glue become available
from __future__ import absolute_import, division, print_function
from glue.external.echo import keep_in_sync, CallbackProperty
from glue.core.layer_artist import LayerArtistBase
from glue.viewers.common.state im... | 125 | 172 | 576 | 40 | 85 | sk1p/glue-jupyter | glue_jupyter/compat.py | Python | LayerArtist | LayerArtist | 14 | 87 | 14 | 18 | b3178ae859c66f79a2ad96742687637ce8b16b9e | bigcode/the-stack | train |
a46c424c4964e3b15b471dc6 | train | function | def cdb(shot=None, time=1060, revision=1, variant=''):
"""
:param shot: number of shot in cdb, defaults to last
:param time: closest time [ms] of target equilibrium, defaults to 10 ms after shaping
if None then an EFITSlices instance is returned
:param revision: EFIT revision, default... | def cdb(shot=None, time=1060, revision=1, variant=''):
| """
:param shot: number of shot in cdb, defaults to last
:param time: closest time [ms] of target equilibrium, defaults to 10 ms after shaping
if None then an EFITSlices instance is returned
:param revision: EFIT revision, defaults to first (post-shot standard)
:param variant: EFI... | import h5py
import numpy as np
import os
import pkg_resources
import xarray as xr
from pleque.core import Equilibrium
from pleque.io._geqdsk import read, data_as_ds
from pleque.io.tools import EquilibriaTimeSlices
def cdb(shot=None, time=1060, revision=1, variant=''):
| 77 | 85 | 284 | 19 | 57 | kripnerl/pleque | pleque/io/compass.py | Python | cdb | cdb | 12 | 42 | 12 | 12 | 981cd3cc791d1dbcc7249404b86163e88b03cf50 | bigcode/the-stack | train |
b7f85ddf20291e7bcc5e18f8 | train | function | def cudb(shot, time=None, revision=-1, variant='', time_unit='s', first_wall=None,
cdb_host='cudb.tok.ipp.cas.cz', cdb_data_root='/compass/CC19_COMPASS-U_data/'):
"""
:param shot:
:param time:
:param revision:
:param variant:
:param time_unit:
:param first_wall:
:pa... | def cudb(shot, time=None, revision=-1, variant='', time_unit='s', first_wall=None,
cdb_host='cudb.tok.ipp.cas.cz', cdb_data_root='/compass/CC19_COMPASS-U_data/'):
| """
:param shot:
:param time:
:param revision:
:param variant:
:param time_unit:
:param first_wall:
:param cdb_host:
:param cdb_data_root:
:return:
"""
eq_time = time
if time_unit == 'ms' and time is not None:
eq_time /= 1000 # convert time to seconds as the... | df5(data_ref.full_path, time=time)
return eq
def cudb(shot, time=None, revision=-1, variant='', time_unit='s', first_wall=None,
cdb_host='cudb.tok.ipp.cas.cz', cdb_data_root='/compass/CC19_COMPASS-U_data/'):
| 69 | 69 | 231 | 55 | 13 | kripnerl/pleque | pleque/io/compass.py | Python | cudb | cudb | 45 | 73 | 45 | 46 | a1715ca5dd8b1abb448b3554fa892e3b314f8565 | bigcode/the-stack | train |
bb3c820ec3bb4e37b035d7fb | train | function | def read_efithdf5(file_path, time=None):
"""
Loads Equilibrium information from an efit file.
:param file_path: path to the hdf5 compass efit file
:param time: closest time [ms] of target equilibrium,
if None then an EFITSlices instance is returned
:return: Equilibrium
"""
... | def read_efithdf5(file_path, time=None):
| """
Loads Equilibrium information from an efit file.
:param file_path: path to the hdf5 compass efit file
:param time: closest time [ms] of target equilibrium,
if None then an EFITSlices instance is returned
:return: Equilibrium
"""
with h5py.File(file_path, 'r') as f5efit... | + strid_postfix)
first_wall = np.array([r_limiter.data, z_limiter.data]).T
except CDBException:
first_wall = 'IBAv3.1'
if isinstance(first_wall, str) and first_wall == 'IBAv3.1':
resource_package = 'pleque'
print('--- No limiter specified. The IBA v3.1 limiter will ... | 256 | 256 | 867 | 13 | 242 | kripnerl/pleque | pleque/io/compass.py | Python | read_efithdf5 | read_efithdf5 | 184 | 245 | 184 | 184 | 671fe0d7a140d64ab9e01facd6cbf46c77f556b0 | bigcode/the-stack | train |
440c1b152030a0c5f61d50ba | train | function | def read_fiesta_equilibrium(filepath, first_wall=None):
"""
Current versions of the equilibria are stored in
`/compass/Shared/Common/COMPASS-UPGRADE/RP1 Design/Equilibria/v3.1`
:param filepath: Path to fiesta g-file equilibria
:param first_wall: Path to datafile with limiter line. (Fiesta doesn't s... | def read_fiesta_equilibrium(filepath, first_wall=None):
| """
Current versions of the equilibria are stored in
`/compass/Shared/Common/COMPASS-UPGRADE/RP1 Design/Equilibria/v3.1`
:param filepath: Path to fiesta g-file equilibria
:param first_wall: Path to datafile with limiter line. (Fiesta doesn't store limiter contour into g-file).
If `None` IBA... | = np.column_stack([f5efit['input/limiter/{}Values'.format(x)][0, :]
for x in 'rz'])
dst.load()
efit_slices = EquilibriaTimeSlices(dst, limiter)
if time is not None:
eq = efit_slices.get_time_slice(time)
return eq
else:
return efit_slices
d... | 96 | 96 | 322 | 13 | 82 | kripnerl/pleque | pleque/io/compass.py | Python | read_fiesta_equilibrium | read_fiesta_equilibrium | 248 | 281 | 248 | 248 | 4968c124c73f34497b31b7e21aa24529292faa18 | bigcode/the-stack | train |
d5232e70cd9299523b2794e6 | train | function | def get_ds_from_cudb(shot, time=None, revision=-1, variant='', time_unit='s', first_wall=None,
cdb_host='cudb.tok.ipp.cas.cz',
cdb_data_root='/compass/CC19_COMPASS-U_data/:/compass/CC20_COMPASS-U_data/'):
"""
Load data from CUDB Fiesta signal.
Note: for the con... | def get_ds_from_cudb(shot, time=None, revision=-1, variant='', time_unit='s', first_wall=None,
cdb_host='cudb.tok.ipp.cas.cz',
cdb_data_root='/compass/CC19_COMPASS-U_data/:/compass/CC20_COMPASS-U_data/'):
| """
Load data from CUDB Fiesta signal.
Note: for the convenience CUDB environment is hard set.
:param shot:
:param time:
:param revision:
:param variant:
:param time_unit:
:return:
"""
from pyCDB.pyCDBBase import CDBException
cdb_host_def = os.getenv('CD... | /CC19_COMPASS-U_data/'):
"""
:param shot:
:param time:
:param revision:
:param variant:
:param time_unit:
:param first_wall:
:param cdb_host:
:param cdb_data_root:
:return:
"""
eq_time = time
if time_unit == 'ms' and time is not None:
eq_time /= 1000 # conve... | 256 | 256 | 1,271 | 71 | 184 | kripnerl/pleque | pleque/io/compass.py | Python | get_ds_from_cudb | get_ds_from_cudb | 76 | 181 | 76 | 78 | edcd697dcce00cc96f21a74175534a0158bdf632 | bigcode/the-stack | train |
4ecd36ad52438c16615f5e5a | train | class | class FunctionDecorator:
"""
Decorator of methods found in the SUL class.
"""
def __init__(self, function, args=None):
"""
Args:
function: function of the class to be learned
args: arguments to be passed to the function. Either a single argument, or a list of a... | class FunctionDecorator:
| """
Decorator of methods found in the SUL class.
"""
def __init__(self, function, args=None):
"""
Args:
function: function of the class to be learned
args: arguments to be passed to the function. Either a single argument, or a list of arguments if
... | from aalpy.base import SUL
class FunctionDecorator:
| 12 | 64 | 146 | 4 | 7 | MDrey101/AALpy | aalpy/SULs/PyMethodSUL.py | Python | FunctionDecorator | FunctionDecorator | 4 | 27 | 4 | 4 | b1702347663b66336d2828fb7e9b6d0357d39ac3 | bigcode/the-stack | train |
d8455fd47a53d5a25f9b7fd8 | train | class | class PyClassSUL(SUL):
"""
System under learning for inferring python classes.
"""
def __init__(self, python_class):
"""
Args:
python_class: class to be learned
"""
super().__init__()
self._class = python_class
self.sul: object = None
def... | class PyClassSUL(SUL):
| """
System under learning for inferring python classes.
"""
def __init__(self, python_class):
"""
Args:
python_class: class to be learned
"""
super().__init__()
self._class = python_class
self.sul: object = None
def pre(self):
"""... | None
if args:
self.args = [args] if not isinstance(args, list) else args
def __repr__(self):
if self.args:
return f'{self.function.__name__}{self.args}'
return self.function.__name__
class PyClassSUL(SUL):
| 63 | 64 | 199 | 8 | 55 | MDrey101/AALpy | aalpy/SULs/PyMethodSUL.py | Python | PyClassSUL | PyClassSUL | 30 | 68 | 30 | 30 | 6ac76550796bfd8daccc3c5b1555835b02c5f094 | bigcode/the-stack | train |
d5b1924a435275bdfa0d2c7a | train | function | @task(alias="foo_aliased")
def foo():
pass
| @task(alias="foo_aliased")
def foo():
| pass
| from fabric.api import task
@task(alias="foo_aliased")
def foo():
| 18 | 64 | 15 | 12 | 5 | bitmonk/fabric | tests/support/flat_alias.py | Python | foo | foo | 3 | 5 | 3 | 4 | fc7e6067a4c45b277bec621327af5661e91d7a9e | bigcode/the-stack | train |
24832d1e7988d6a9bbd52359 | train | function | def collect_addon_css(node, visited=None):
"""Collect CSS includes for all addons-ons implementing Hgrid views.
:return: List of CSS include paths
:rtype: list
"""
css = []
for addon_config in settings.ADDONS_AVAILABLE_DICT.values():
# CSS modules configured in each addon's __init__ fil... | def collect_addon_css(node, visited=None):
| """Collect CSS includes for all addons-ons implementing Hgrid views.
:return: List of CSS include paths
:rtype: list
"""
css = []
for addon_config in settings.ADDONS_AVAILABLE_DICT.values():
# CSS modules configured in each addon's __init__ file
css.extend(addon_config.include_c... | init__ file
js.extend(addon_config.include_js.get(config_entry, []))
# Webpack bundle
js_path = paths.resolve_addon_path(addon_config, filename)
if js_path:
js.append(js_path)
return js
def collect_addon_css(node, visited=None):
| 64 | 64 | 90 | 10 | 53 | alexschiller/osf.io | website/util/rubeus.py | Python | collect_addon_css | collect_addon_css | 299 | 309 | 299 | 299 | 14dca2ba6534cfc7582ea8fe5102af7d34cdc33d | bigcode/the-stack | train |
95e887b70ef07f15b2ef9c12 | train | function | def default_urls(node_api, short_name):
return {
'fetch': u'{node_api}{addonshort}/hgrid/'.format(node_api=node_api, addonshort=short_name),
'upload': u'{node_api}{addonshort}/'.format(node_api=node_api, addonshort=short_name),
}
| def default_urls(node_api, short_name):
| return {
'fetch': u'{node_api}{addonshort}/hgrid/'.format(node_api=node_api, addonshort=short_name),
'upload': u'{node_api}{addonshort}/'.format(node_api=node_api, addonshort=short_name),
}
| kind'
# TODO: Validate the JSON schema, esp. for addons
DEFAULT_PERMISSIONS = {
'view': True,
'edit': False,
}
def format_filesize(size):
return hurry.filesize.size(size, system=hurry.filesize.alternative)
def default_urls(node_api, short_name):
| 64 | 64 | 66 | 9 | 55 | alexschiller/osf.io | website/util/rubeus.py | Python | default_urls | default_urls | 38 | 42 | 38 | 38 | 0ff32b4f96357b7a062371926b132d0ddc343eb9 | bigcode/the-stack | train |
86d1e2974378d98c524a10ed | train | function | def delta_date(d):
diff = d - timezone.now()
s = diff.total_seconds()
return s
| def delta_date(d):
| diff = d - timezone.now()
s = diff.total_seconds()
return s
| include paths
:rtype: list
"""
css = []
for addon_config in settings.ADDONS_AVAILABLE_DICT.values():
# CSS modules configured in each addon's __init__ file
css.extend(addon_config.include_css.get('files', []))
return css
def delta_date(d):
| 64 | 64 | 24 | 5 | 58 | alexschiller/osf.io | website/util/rubeus.py | Python | delta_date | delta_date | 312 | 315 | 312 | 312 | 4f06850015894aeb41dcac634f5a07664b6915bc | bigcode/the-stack | train |
12dacd955694ef53f1c01cfd | train | function | def collect_addon_js(node, visited=None, filename='files.js', config_entry='files'):
"""Collect JavaScript includes for all add-ons implementing HGrid views.
:return list: List of JavaScript include paths
"""
js = []
for addon_config in settings.ADDONS_AVAILABLE_DICT.values():
# JS modules... | def collect_addon_js(node, visited=None, filename='files.js', config_entry='files'):
| """Collect JavaScript includes for all add-ons implementing HGrid views.
:return list: List of JavaScript include paths
"""
js = []
for addon_config in settings.ADDONS_AVAILABLE_DICT.values():
# JS modules configured in each addon's __init__ file
js.extend(addon_config.include_js.g... | of CSS files>}
"""
return {
'tree_js': list(collect_addon_js(node)),
'tree_css': list(collect_addon_css(node)),
}
# TODO: Abstract static collectors
def collect_addon_js(node, visited=None, filename='files.js', config_entry='files'):
| 64 | 64 | 129 | 20 | 43 | alexschiller/osf.io | website/util/rubeus.py | Python | collect_addon_js | collect_addon_js | 282 | 296 | 282 | 282 | e563a226d372efece54113fefbf55b235693ca4f | bigcode/the-stack | train |
6510572f879b560b46e31fdc | train | function | def collect_addon_assets(node):
"""Return a dictionary containing lists of JS and CSS assets for a node's
addons.
:rtype: {'tree_js': <list of JS scripts>, 'tree_css': <list of CSS files>}
"""
return {
'tree_js': list(collect_addon_js(node)),
'tree_css': list(collect_addon_css(node)... | def collect_addon_assets(node):
| """Return a dictionary containing lists of JS and CSS assets for a node's
addons.
:rtype: {'tree_js': <list of JS scripts>, 'tree_css': <list of CSS files>}
"""
return {
'tree_js': list(collect_addon_js(node)),
'tree_css': list(collect_addon_css(node)),
}
| permissions': {'view': False, 'edit': False},
'name': '{} is currently unavailable'.format(addon.config.full_name),
})
continue
rv.extend(sort_by_name(temp) or [])
return rv
# TODO: these might belong in addons module
def collect_... | 64 | 64 | 84 | 7 | 56 | alexschiller/osf.io | website/util/rubeus.py | Python | collect_addon_assets | collect_addon_assets | 269 | 278 | 269 | 269 | 0b3bd2d3528ddc20cab18b52c4ffb644ece5d28a | bigcode/the-stack | train |
10a390e5262f380f6f44f771 | train | function | def sort_by_name(hgrid_data):
return_value = hgrid_data
if hgrid_data is not None:
return_value = sorted(hgrid_data, key=lambda item: item['name'].lower())
return return_value
| def sort_by_name(hgrid_data):
| return_value = hgrid_data
if hgrid_data is not None:
return_value = sorted(hgrid_data, key=lambda item: item['name'].lower())
return return_value
|
"""
button = {
'text': text,
'action': action,
}
if title:
button['attributes'] = 'title="{title}" data-toggle="tooltip" data-placement="right" '.format(title=title)
return button
def sort_by_name(hgrid_data):
| 64 | 64 | 49 | 8 | 55 | alexschiller/osf.io | website/util/rubeus.py | Python | sort_by_name | sort_by_name | 144 | 148 | 144 | 144 | d78ec8f4262c833028d91cd5ecabc3284f54bc04 | bigcode/the-stack | train |
337ca310cd94443182af43e1 | train | function | def format_filesize(size):
return hurry.filesize.size(size, system=hurry.filesize.alternative)
| def format_filesize(size):
| return hurry.filesize.size(size, system=hurry.filesize.alternative)
| _MODE
logger = logging.getLogger(__name__)
FOLDER = 'folder'
FILE = 'file'
KIND = 'kind'
# TODO: Validate the JSON schema, esp. for addons
DEFAULT_PERMISSIONS = {
'view': True,
'edit': False,
}
def format_filesize(size):
| 64 | 64 | 22 | 6 | 58 | alexschiller/osf.io | website/util/rubeus.py | Python | format_filesize | format_filesize | 34 | 35 | 34 | 34 | e82c18334bed00bb377732d407319d85b1812415 | bigcode/the-stack | train |
9746d8162e857ff625aa030f | train | function | def build_addon_root(node_settings, name, permissions=None,
urls=None, extra=None, buttons=None, user=None,
private_key=None, **kwargs):
"""Builds the root or "dummy" folder for an addon.
:param addonNodeSettingsBase node_settings: Addon settings
:param String name... | def build_addon_root(node_settings, name, permissions=None,
urls=None, extra=None, buttons=None, user=None,
private_key=None, **kwargs):
| """Builds the root or "dummy" folder for an addon.
:param addonNodeSettingsBase node_settings: Addon settings
:param String name: Additional information for the folder title
eg. Repo name for Github or bucket name for S3
:param dict or Auth permissions: Dictionary of permissions for the addon's... | ):
return hurry.filesize.size(size, system=hurry.filesize.alternative)
def default_urls(node_api, short_name):
return {
'fetch': u'{node_api}{addonshort}/hgrid/'.format(node_api=node_api, addonshort=short_name),
'upload': u'{node_api}{addonshort}/'.format(node_api=node_api, addonshort=short_na... | 194 | 194 | 649 | 34 | 160 | alexschiller/osf.io | website/util/rubeus.py | Python | build_addon_root | build_addon_root | 56 | 123 | 56 | 58 | 0e28b50821174de39b8fe2498fcb34aa107cf141 | bigcode/the-stack | train |
fee747467536fd2828ea79f4 | train | function | def build_addon_button(text, action, title=''):
"""Builds am action button to be rendered in HGrid
:param str text: A string or html to appear on the button itself
:param str action: The name of the HGrid action for the button to call.
The callback for the HGrid action must be defined as a member o... | def build_addon_button(text, action, title=''):
| """Builds am action button to be rendered in HGrid
:param str text: A string or html to appear on the button itself
:param str action: The name of the HGrid action for the button to call.
The callback for the HGrid action must be defined as a member of HGrid.Actions
:return dict: Hgrid formatte... | ,
'isPointer': False,
'nodeId': node_settings.owner._id,
'nodeUrl': node_settings.owner.url,
'nodeApiUrl': node_settings.owner.api_url,
}
ret.update(kwargs)
return ret
def build_addon_button(text, action, title=''):
| 64 | 64 | 149 | 12 | 51 | alexschiller/osf.io | website/util/rubeus.py | Python | build_addon_button | build_addon_button | 126 | 141 | 126 | 126 | 4cc54e8c75419b4d17b9c1fa1dabf13b74022aac | bigcode/the-stack | train |
eff50a9ac1ac24fc06096692 | train | function | def to_hgrid(node, auth, **data):
"""Converts a node into a rubeus grid format
:param Node node: the node to be parsed
:param Auth auth: the user authorization object
:returns: rubeus-formatted dict
"""
return NodeFileCollector(node, auth, **data).to_hgrid()
| def to_hgrid(node, auth, **data):
| """Converts a node into a rubeus grid format
:param Node node: the node to be parsed
:param Auth auth: the user authorization object
:returns: rubeus-formatted dict
"""
return NodeFileCollector(node, auth, **data).to_hgrid()
| 'fetch': u'{node_api}{addonshort}/hgrid/'.format(node_api=node_api, addonshort=short_name),
'upload': u'{node_api}{addonshort}/'.format(node_api=node_api, addonshort=short_name),
}
def to_hgrid(node, auth, **data):
| 64 | 64 | 77 | 11 | 53 | alexschiller/osf.io | website/util/rubeus.py | Python | to_hgrid | to_hgrid | 45 | 53 | 45 | 45 | 8e1d00c710955e716f98038e08a832c25f956fb5 | bigcode/the-stack | train |
dc4bcbe8c6cd1ea9c9a1f528 | train | class | class NodeFileCollector(object):
"""A utility class for creating rubeus formatted node data"""
def __init__(self, node, auth, **kwargs):
NodeRelation = apps.get_model('osf.NodeRelation')
self.node = node.child if isinstance(node, NodeRelation) else node
self.auth = auth
self.ext... | class NodeFileCollector(object):
| """A utility class for creating rubeus formatted node data"""
def __init__(self, node, auth, **kwargs):
NodeRelation = apps.get_model('osf.NodeRelation')
self.node = node.child if isinstance(node, NodeRelation) else node
self.auth = auth
self.extra = kwargs
self.can_view ... | ,
'isPointer': False,
'nodeId': node_settings.owner._id,
'nodeUrl': node_settings.owner.url,
'nodeApiUrl': node_settings.owner.api_url,
}
ret.update(kwargs)
return ret
def build_addon_button(text, action, title=''):
"""Builds am action button to be rendered in HGrid
... | 256 | 256 | 895 | 6 | 249 | alexschiller/osf.io | website/util/rubeus.py | Python | NodeFileCollector | NodeFileCollector | 151 | 265 | 151 | 152 | 1429d77a6e8e5e2cc18418e35dcef2f7485680d1 | bigcode/the-stack | train |
fd862eb882ef665aa37585b5 | train | function | def make_circuit(n:int) -> QuantumCircuit:
# circuit begin
input_qubit = QuantumRegister(n,"qc")
prog = QuantumCircuit(input_qubit)
prog.h(input_qubit[0]) # number=1
prog.h(input_qubit[1]) # number=2
prog.h(input_qubit[2]) # number=3
prog.cx(input_qubit[0],input_qubit[2]) # number=9
pro... | def make_circuit(n:int) -> QuantumCircuit:
# circuit begin
| input_qubit = QuantumRegister(n,"qc")
prog = QuantumCircuit(input_qubit)
prog.h(input_qubit[0]) # number=1
prog.h(input_qubit[1]) # number=2
prog.h(input_qubit[2]) # number=3
prog.cx(input_qubit[0],input_qubit[2]) # number=9
prog.x(input_qubit[2]) # number=10
prog.cx(input_qubit[0],inpu... | , ClassicalRegister, transpile, BasicAer, IBMQ
import networkx as nx
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collections import Counter
from qiskit.test.mock import FakeVigo, FakeYorktown
kernel = 'circuit/bernstein'
def make_circuit(n:i... | 90 | 90 | 301 | 16 | 74 | UCLA-SEAL/QDiff | data/p4VQE/R4/benchmark/startQiskit_QC275.py | Python | make_circuit | make_circuit | 18 | 47 | 18 | 19 | ccca1467760e73fed0f894bc8a0193d36f0c1c37 | bigcode/the-stack | train |
2f861d4f65813b82344f8244 | train | class | class TestQuantizedConv2dRelu(utils.TorchGlowTestCase):
def _test_quantized_conv2d_relu_packed(self, groups):
"""Basic test of PyTorch quantized::conv2d_relu Node with packed weights on Glow."""
with torch.no_grad():
x = torch.tensor(range(5), dtype=torch.float) / 3
x = torch... | class TestQuantizedConv2dRelu(utils.TorchGlowTestCase):
| def _test_quantized_conv2d_relu_packed(self, groups):
"""Basic test of PyTorch quantized::conv2d_relu Node with packed weights on Glow."""
with torch.no_grad():
x = torch.tensor(range(5), dtype=torch.float) / 3
x = torch.cat((x, x, x, x, x))
x = torch.cat((x, x, x... | from __future__ import absolute_import, division, print_function, unicode_literals
from collections import OrderedDict
import torch
from tests import utils
class TestQuantizedConv2dRelu(utils.TorchGlowTestCase):
| 46 | 256 | 990 | 16 | 29 | mciprian13/glow | torch_glow/tests/nodes/quantized_conv2d_relu_test.py | Python | TestQuantizedConv2dRelu | TestQuantizedConv2dRelu | 9 | 114 | 9 | 9 | bfb6658261c8f0dc87a72fafbb019a14b34edb78 | bigcode/the-stack | train |
21702306de4291240bdf6bfa | train | function | def upgrade():
""" Alter the DB schema for the changes related to colored tags. """
engine = op.get_bind()
Session = sa.orm.scoped_session(sa.orm.sessionmaker())
Session.configure(bind=engine)
session = Session()
projects = collections.defaultdict(list)
for issue in session.query(model.Issu... | def upgrade():
| """ Alter the DB schema for the changes related to colored tags. """
engine = op.get_bind()
Session = sa.orm.scoped_session(sa.orm.sessionmaker())
Session.configure(bind=engine)
session = Session()
projects = collections.defaultdict(list)
for issue in session.query(model.Issue).all():
... | ic.
revision = '208b0cd232ab'
down_revision = '588eabcd394c'
import collections
import datetime
from alembic import op
import sqlalchemy as sa
try:
from pagure.lib import model
except ImportError:
import sys
sys.path.insert(0, '.')
from pagure.lib import model
def upgrade():
| 78 | 78 | 261 | 3 | 74 | yifengyou/learn-pagure | src/alembic/versions/208b0cd232ab_colored_tags.py | Python | upgrade | upgrade | 29 | 65 | 29 | 29 | ef956fc1b793c228972a6f59018535b3b2de32e3 | bigcode/the-stack | train |
9bf32d3d1d3207012d1a9d1a | train | function | def downgrade():
raise ValueError("The colored tags feature can not be un-done")
| def downgrade():
| raise ValueError("The colored tags feature can not be un-done")
| Link the tag to the ticket as it was
tagissueobj = model.TagIssueColored(
tag_id=tagobj.id,
issue_uid=issue.uid,
date_created=tagobj.date_created,
)
session.add(tagissueobj)
session.flush()
session.commit()
def downgrad... | 64 | 64 | 19 | 3 | 61 | yifengyou/learn-pagure | src/alembic/versions/208b0cd232ab_colored_tags.py | Python | downgrade | downgrade | 68 | 69 | 68 | 68 | 4dc616ebe0699701cc1ad630151df62d740f3168 | bigcode/the-stack | train |
5bfe29da5808c2b29d0a3e80 | train | class | class GetV1TestCase(unittest.TestCase):
def setUp(self):
self.component = components.recording.RecordingComponent(
base_uri="http://foo.com",
config={
'api_key': 'KEY',
'api_secret': 'SECRET'
}
)
def test_can_get(self):
... | class GetV1TestCase(unittest.TestCase):
| def setUp(self):
self.component = components.recording.RecordingComponent(
base_uri="http://foo.com",
config={
'api_key': 'KEY',
'api_secret': 'SECRET'
}
)
def test_can_get(self):
with patch.object(components.base.BaseC... | import unittest
from mock import patch
from zoomus import components
def suite():
"""Define all the tests of the module."""
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(GetV1TestCase))
return suite
class GetV1TestCase(unittest.TestCase):
| 61 | 64 | 170 | 10 | 50 | karthikkommindala1995/zoomus | tests/zoomus/components/recording/test_get.py | Python | GetV1TestCase | GetV1TestCase | 15 | 43 | 15 | 16 | b50dad62bb40b4395ace51b1abc6d24a4d84b277 | bigcode/the-stack | train |
e2e7a4ea10b1cf10b40f5b70 | train | function | def suite():
"""Define all the tests of the module."""
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(GetV1TestCase))
return suite
| def suite():
| """Define all the tests of the module."""
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(GetV1TestCase))
return suite
| import unittest
from mock import patch
from zoomus import components
def suite():
| 17 | 64 | 37 | 3 | 13 | karthikkommindala1995/zoomus | tests/zoomus/components/recording/test_get.py | Python | suite | suite | 8 | 12 | 8 | 8 | 4549c1057c6a0b159b2d8791280c2bafb879b16b | bigcode/the-stack | train |
2457f174db76b0f76da2fe01 | train | class | class GetV2TestCase(unittest.TestCase):
def setUp(self):
self.component = components.recording.RecordingComponentV2(
base_uri="http://foo.com",
config={
'api_key': 'KEY',
'api_secret': 'SECRET'
}
)
@patch.object(components.bas... | class GetV2TestCase(unittest.TestCase):
| def setUp(self):
self.component = components.recording.RecordingComponentV2(
base_uri="http://foo.com",
config={
'api_key': 'KEY',
'api_secret': 'SECRET'
}
)
@patch.object(components.base.BaseComponent, 'get_request', return_va... | ={
'meeting_id': 'ID'
}
)
def test_requires_id(self):
with self.assertRaises(ValueError) as context:
self.component.get()
self.assertEqual(
context.exception.message, "'meeting_id' must be set")
class GetV2TestCase(unit... | 64 | 64 | 162 | 10 | 54 | karthikkommindala1995/zoomus | tests/zoomus/components/recording/test_get.py | Python | GetV2TestCase | GetV2TestCase | 46 | 69 | 46 | 47 | 09b670e779b99eddd89d3932034cfa0b57835680 | bigcode/the-stack | train |
a745f5cc9d3ed144d454486e | train | class | @add_prepare_function_and_summary_method
@add_explain_global_method
class LIMEExplainer(BlackBoxExplainer):
available_explanations = [Extension.GLOBAL, Extension.LOCAL]
explainer_type = Extension.BLACKBOX
"""Defines the LIME Explainer for explaining black box models or functions.
:param model: The mod... | @add_prepare_function_and_summary_method
@add_explain_global_method
class LIMEExplainer(BlackBoxExplainer):
| available_explanations = [Extension.GLOBAL, Extension.LOCAL]
explainer_type = Extension.BLACKBOX
"""Defines the LIME Explainer for explaining black box models or functions.
:param model: The model to explain or function if is_function is True.
A model that implements sklearn.predict or sklearn... | import add_explain_global_method
from interpret_community.common.model_wrapper import _wrap_model
from interpret_community.common.blackbox_explainer import BlackBoxExplainer, \
add_prepare_function_and_summary_method, init_blackbox_decorator
from interpret_community.dataset.decorator import tabular_decorator, init... | 256 | 256 | 4,011 | 26 | 229 | luckystar9111/interpret-community | python/interpret_community/lime/lime_explainer.py | Python | LIMEExplainer | LIMEExplainer | 37 | 393 | 37 | 39 | 499e4ccd2e156dfd743c86d269fffaf0f53c9910 | bigcode/the-stack | train |
b9eaef6a458fccadfcff5ff8 | train | class | class FakeTime(object):
def __init__(self):
self.timestamp_now = 1000.0
def time_fn(self):
self.timestamp_now += 0.2
return self.timestamp_now
| class FakeTime(object):
| def __init__(self):
self.timestamp_now = 1000.0
def time_fn(self):
self.timestamp_now += 0.2
return self.timestamp_now
| POST='foo')
fields = {'name': '^/$', 'status': 200, 'is_robot': False}
self.assertEqual(1, http_metrics.server_response_status.get(fields))
self.assertEqual(
len('foo'), http_metrics.server_request_bytes.get(fields).sum)
class FakeTime(object):
| 64 | 64 | 45 | 5 | 59 | eunchong/infra | appengine_module/gae_ts_mon/test/config_test.py | Python | FakeTime | FakeTime | 376 | 382 | 376 | 376 | a1ce8084f6b0df76a945870c946afd80871d8971 | bigcode/the-stack | train |
7ec0a614fbef406e67a92de5 | train | class | @endpoints.api(name='testapi', version='v1')
class TestEndpoint(remote.Service):
@gae_ts_mon.instrument_endpoint(time_fn=FakeTime().time_fn)
@endpoints.method(message_types.VoidMessage, message_types.VoidMessage,
name='method_good')
def do_good(self, request):
return request
@gae_ts_mo... | @endpoints.api(name='testapi', version='v1')
class TestEndpoint(remote.Service):
@gae_ts_mon.instrument_endpoint(time_fn=FakeTime().time_fn)
@endpoints.method(message_types.VoidMessage, message_types.VoidMessage,
name='method_good')
| def do_good(self, request):
return request
@gae_ts_mon.instrument_endpoint(time_fn=FakeTime().time_fn)
@endpoints.method(message_types.VoidMessage, message_types.VoidMessage,
name='method_bad')
def do_bad(self, request):
raise Exception
@gae_ts_mon.instrument_endpoint(time_fn=Fak... | 2
return self.timestamp_now
@endpoints.api(name='testapi', version='v1')
class TestEndpoint(remote.Service):
@gae_ts_mon.instrument_endpoint(time_fn=FakeTime().time_fn)
@endpoints.method(message_types.VoidMessage, message_types.VoidMessage,
name='method_good')
| 64 | 64 | 174 | 56 | 7 | eunchong/infra | appengine_module/gae_ts_mon/test/config_test.py | Python | TestEndpoint | TestEndpoint | 385 | 404 | 385 | 390 | 9351d3ed89597e850a5c5c4586faa2f1b1f7029b | bigcode/the-stack | train |
b942b9073c30b220cdc5470b | train | class | class InstrumentTest(testing.AppengineTestCase):
def setUp(self):
super(InstrumentTest, self).setUp()
interface.reset_for_unittest()
self.next_time = 42.0
self.time_increment = 3.0
def fake_time(self):
ret = self.next_time
self.next_time += self.time_increment
return ret
def test_s... | class InstrumentTest(testing.AppengineTestCase):
| def setUp(self):
super(InstrumentTest, self).setUp()
interface.reset_for_unittest()
self.next_time = 42.0
self.time_increment = 3.0
def fake_time(self):
ret = self.next_time
self.next_time += self.time_increment
return ret
def test_success(self):
class Handler(webapp2.RequestHa... | (time_now))
self.assertEqual(0, mock_flush.call_count)
@mock.patch('gae_ts_mon.config.flush_metrics_if_needed', autospec=True,
return_value=True)
def test_shutdown_hook_flushed(self, _mock_flush):
time_now = 10000
id = shared.get_instance_entity().key.id()
with shared.instance_namespa... | 256 | 256 | 1,065 | 10 | 246 | eunchong/infra | appengine_module/gae_ts_mon/test/config_test.py | Python | InstrumentTest | InstrumentTest | 225 | 373 | 225 | 225 | f5b1c8f65222eb1fc9baafc3c4954cd213861cba | bigcode/the-stack | train |
417e6b68775a29fc383dd70e | train | class | class InitializeTest(testing.AppengineTestCase):
def setUp(self):
super(InitializeTest, self).setUp()
config.reset_for_unittest()
target = targets.TaskTarget('test_service', 'test_job',
'test_region', 'test_host')
self.mock_state = interface.State(target=target)
se... | class InitializeTest(testing.AppengineTestCase):
| def setUp(self):
super(InitializeTest, self).setUp()
config.reset_for_unittest()
target = targets.TaskTarget('test_service', 'test_job',
'test_region', 'test_host')
self.mock_state = interface.State(target=target)
self.mock_state.metrics = copy.copy(interface.state... | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import copy
import datetime
import os
import time
import unittest
import endpoints
import gae_ts_mon
import mock
import webapp2
from infra_libs.ts_mon impo... | 171 | 256 | 1,753 | 10 | 160 | eunchong/infra | appengine_module/gae_ts_mon/test/config_test.py | Python | InitializeTest | InitializeTest | 28 | 222 | 28 | 28 | 8be851e61a990f83caed5e1d9795e51ab630d6f7 | bigcode/the-stack | train |
74c968e16d1f9238cbe7a213 | train | class | class InstrumentEndpointTest(testing.EndpointsTestCase):
api_service_cls = TestEndpoint
def setUp(self):
super(InstrumentEndpointTest, self).setUp()
config.reset_for_unittest()
target = targets.TaskTarget('test_service', 'test_job',
'test_region', 'test_host')
self.... | class InstrumentEndpointTest(testing.EndpointsTestCase):
| api_service_cls = TestEndpoint
def setUp(self):
super(InstrumentEndpointTest, self).setUp()
config.reset_for_unittest()
target = targets.TaskTarget('test_service', 'test_job',
'test_region', 'test_host')
self.mock_state = interface.State(target=target)
self.mock... | gae_ts_mon.instrument_endpoint(time_fn=FakeTime().time_fn)
@endpoints.method(message_types.VoidMessage, message_types.VoidMessage,
name='method_good')
def do_good(self, request):
return request
@gae_ts_mon.instrument_endpoint(time_fn=FakeTime().time_fn)
@endpoints.method(message_types.V... | 164 | 164 | 547 | 11 | 153 | eunchong/infra | appengine_module/gae_ts_mon/test/config_test.py | Python | InstrumentEndpointTest | InstrumentEndpointTest | 407 | 462 | 407 | 407 | cce9d01703e86d324ddba8c02b8957df54348172 | bigcode/the-stack | train |
65cb6a76b7c773161cc322f3 | train | class | class Block(nn.Module):
def __init__(self,in_filters,out_filters,strides=1,atrous=None,grow_first=True,activate_first=True,inplace=True):
super(Block, self).__init__()
if atrous == None:
atrous = [1]*3
elif isinstance(atrous, int):
atrous_list = [atrous]*3
... | class Block(nn.Module):
| def __init__(self,in_filters,out_filters,strides=1,atrous=None,grow_first=True,activate_first=True,inplace=True):
super(Block, self).__init__()
if atrous == None:
atrous = [1]*3
elif isinstance(atrous, int):
atrous_list = [atrous]*3
atrous = atrous_list
... | self.bn2 = nn.BatchNorm2d(out_channels, momentum=bn_mom)
self.relu2 = nn.ReLU(inplace=True)
self.activate_first = activate_first
def forward(self,x):
if self.activate_first:
x = self.relu0(x)
x = self.depthwise(x)
x = self.bn1(x)
if not self.activa... | 129 | 129 | 430 | 5 | 123 | juranccc/CVerrr | deeplabv3-water/nets/xception.py | Python | Block | Block | 39 | 79 | 39 | 39 | 4ab58c37c13b642f171ec836b85dcc89a5ae5371 | bigcode/the-stack | train |
3661f445fdc333f56f83238e | train | function | def xception(pretrained=True, downsample_factor=16):
model = Xception(downsample_factor=downsample_factor)
if pretrained:
old_dict = model_zoo.load_url(model_urls['xception'],model_dir='./model_data')
model_dict = model.state_dict()
old_dict = {k: v for k,v in old_dict.items() if ('itr' ... | def xception(pretrained=True, downsample_factor=16):
| model = Xception(downsample_factor=downsample_factor)
if pretrained:
old_dict = model_zoo.load_url(model_urls['xception'],model_dir='./model_data')
model_dict = model.state_dict()
old_dict = {k: v for k,v in old_dict.items() if ('itr' not in k and 'tmp' not in k and 'track' not in k)}
... | cached_file = os.path.join(model_dir, filename)
if os.path.exists(cached_file):
return torch.load(cached_file, map_location=map_location)
else:
return model_zoo.load_url(url,model_dir=model_dir)
def xception(pretrained=True, downsample_factor=16):
| 64 | 64 | 118 | 13 | 51 | juranccc/CVerrr | deeplabv3-water/nets/xception.py | Python | xception | xception | 200 | 208 | 200 | 200 | 2ba0d7696fccdfffc47ef54588640685d56055f5 | bigcode/the-stack | train |
6f7a268668d8fc3e0da3b08a | train | class | class SeparableConv2d(nn.Module):
def __init__(self,in_channels,out_channels,kernel_size=1,stride=1,padding=0,dilation=1,bias=False,activate_first=True,inplace=True):
super(SeparableConv2d,self).__init__()
self.relu0 = nn.ReLU(inplace=inplace)
self.depthwise = nn.Conv2d(in_channels,in_channe... | class SeparableConv2d(nn.Module):
| def __init__(self,in_channels,out_channels,kernel_size=1,stride=1,padding=0,dilation=1,bias=False,activate_first=True,inplace=True):
super(SeparableConv2d,self).__init__()
self.relu0 = nn.ReLU(inplace=inplace)
self.depthwise = nn.Conv2d(in_channels,in_channels,kernel_size,stride,padding,dila... | as nn
import torch.utils.model_zoo as model_zoo
bn_mom = 0.0003
model_urls = {
'xception': '/home/wangyude/.torch/models/xception_pytorch_imagenet.pth'#'http://data.lip6.fr/cadene/pretrainedmodels/xception-b5690688.pth'
}
class SeparableConv2d(nn.Module):
| 85 | 85 | 284 | 9 | 76 | juranccc/CVerrr | deeplabv3-water/nets/xception.py | Python | SeparableConv2d | SeparableConv2d | 14 | 36 | 14 | 14 | d9fe035bd8561957786e95d985d6e9585ad977b0 | bigcode/the-stack | train |
878131324198d9696f8e568a | train | function | def load_url(url, model_dir='./model_data', map_location=None):
if not os.path.exists(model_dir):
os.makedirs(model_dir)
filename = url.split('/')[-1]
cached_file = os.path.join(model_dir, filename)
if os.path.exists(cached_file):
return torch.load(cached_file, map_location=map_location)... | def load_url(url, model_dir='./model_data', map_location=None):
| if not os.path.exists(model_dir):
os.makedirs(model_dir)
filename = url.split('/')[-1]
cached_file = os.path.join(model_dir, filename)
if os.path.exists(cached_file):
return torch.load(cached_file, map_location=map_location)
else:
return model_zoo.load_url(url,model_dir=model... | = self.block19(x)
x = self.block20(x)
x = self.conv3(x)
x = self.conv4(x)
x = self.conv5(x)
return low_featrue_layer,x
def load_url(url, model_dir='./model_data', map_location=None):
| 64 | 64 | 91 | 15 | 48 | juranccc/CVerrr | deeplabv3-water/nets/xception.py | Python | load_url | load_url | 190 | 198 | 190 | 190 | 7cb047934b1d20a5a9ea04e31222a15a39e914a9 | bigcode/the-stack | train |
ab616f07d581060aa96b752c | train | class | class Xception(nn.Module):
"""
Xception optimized for the ImageNet dataset, as specified in
https://arxiv.org/pdf/1610.02357.pdf
"""
def __init__(self, downsample_factor):
""" Constructor
Args:
num_classes: number of classes
"""
super(Xception, self).__ini... | class Xception(nn.Module):
| """
Xception optimized for the ImageNet dataset, as specified in
https://arxiv.org/pdf/1610.02357.pdf
"""
def __init__(self, downsample_factor):
""" Constructor
Args:
num_classes: number of classes
"""
super(Xception, self).__init__()
stride_list ... | filters = out_filters
else:
filters = in_filters
self.sepconv1 = SeparableConv2d(in_filters,filters,3,stride=1,padding=1*atrous[0],dilation=atrous[0],bias=False,activate_first=activate_first,inplace=self.head_relu)
self.sepconv2 = SeparableConv2d(filters,out_filters,3,str... | 256 | 256 | 1,130 | 6 | 249 | juranccc/CVerrr | deeplabv3-water/nets/xception.py | Python | Xception | Xception | 82 | 188 | 82 | 82 | ae35f0fdf535b00c81fa75342fc1da8729d7f698 | bigcode/the-stack | train |
b0922d4f60c1bdc60e14697f | train | function | def test_call():
n_z = 32
model = FCEncoder(n_z, 100)
n_batch = 16
n_x = 256
x = np.random.randn(n_batch, n_x).astype('f')
y = model(x)
assert y.shape == (n_batch, n_z)
| def test_call():
| n_z = 32
model = FCEncoder(n_z, 100)
n_batch = 16
n_x = 256
x = np.random.randn(n_batch, n_x).astype('f')
y = model(x)
assert y.shape == (n_batch, n_z)
| import numpy as np
from iaf.model import FCEncoder
def test_call():
| 17 | 64 | 70 | 4 | 12 | nel215/chainer-iaf | iaf/model/test_encoder.py | Python | test_call | test_call | 5 | 13 | 5 | 5 | f5cf924cdfba3a03bfbb7ac5085bf52f3f5f64bb | bigcode/the-stack | train |
6e60540423685bdb1733e51d | train | class | class Migration(migrations.Migration):
dependencies = [
('taggit', '0002_auto_20150616_2121'),
('flis_horison_scanning', '0021_auto_20170320_1458'),
]
operations = [
migrations.CreateModel(
name='EUStrategy',
fields=[
('id', models.AutoField(a... | class Migration(migrations.Migration):
| dependencies = [
('taggit', '0002_auto_20150616_2121'),
('flis_horison_scanning', '0021_auto_20170320_1458'),
]
operations = [
migrations.CreateModel(
name='EUStrategy',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, ser... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-03 13:02
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import modelcluster.fields
import taggit.managers
class Migration(migrations.Migration):
| 72 | 170 | 568 | 7 | 64 | eea/eea.docker.flis | code/flis_horison_scanning/migrations/0022_auto_20170403_1302.py | Python | Migration | Migration | 11 | 81 | 11 | 11 | 53a9782261dd938e13edac54105a75d43bf3cd50 | bigcode/the-stack | train |
1aaef93fb343dbad5add7923 | train | function | def calibcamera_engine(app_args, interproc_dict=None, ve=None, cq=None):
camcalib_info("camera calibration started..")
cameraName = app_args
if cameraName is "":
PrintMsg.print_error("Input camera name is not available.")
sys.exit()
bridge_ip = BridgeInterprocess(interproc_dict, ve, c... | def calibcamera_engine(app_args, interproc_dict=None, ve=None, cq=None):
| camcalib_info("camera calibration started..")
cameraName = app_args
if cameraName is "":
PrintMsg.print_error("Input camera name is not available.")
sys.exit()
bridge_ip = BridgeInterprocess(interproc_dict, ve, cq)
try:
camcalib_info("grpahql client parsing started..")
... | import CalibrationCamera
from pyaidoop.calibration.calibcamera_aruco import CalibrationCameraAruco
from pyaidoop.log import Logger
from applications.config.appconfig import AppConfig
from applications.etc.util import ObjectTrackerErrMsg, DisplayInfoText, PrintMsg
from applications.keyhandler.calibcamera_keyhandler im... | 255 | 256 | 1,300 | 18 | 237 | aidoop/CoboMarkerTracking | object_tracker/applications/calibcamera_engine.py | Python | calibcamera_engine | calibcamera_engine | 41 | 223 | 41 | 42 | 818153596afa69c4b4aa809754d041caaaefffca | bigcode/the-stack | train |
35ffef87fc7169fdc1b27764 | train | function | def makeFrameImageDirectory():
now = datetime.datetime.now()
dirString = now.strftime("%Y%m%d%H%M%S")
try:
if not (os.path.isdir(dirString)):
os.makedirs(os.path.join("./", "Captured", dirString))
except OSError as e:
print(f"Can't make new generated directory")
raise... | def makeFrameImageDirectory():
| now = datetime.datetime.now()
dirString = now.strftime("%Y%m%d%H%M%S")
try:
if not (os.path.isdir(dirString)):
os.makedirs(os.path.join("./", "Captured", dirString))
except OSError as e:
print(f"Can't make new generated directory")
raise
return os.path.join("./", ... | from applications.visiongql.visiongql_client import VisonGqlDataClient
from applications.bridge.bridge_interprocess import BridgeInterprocess
camcalib_info = Logger.get("camcalib").info
camcalib_err = Logger.get("camcalib").error
def makeFrameImageDirectory():
| 64 | 64 | 90 | 6 | 57 | aidoop/CoboMarkerTracking | object_tracker/applications/calibcamera_engine.py | Python | makeFrameImageDirectory | makeFrameImageDirectory | 23 | 32 | 23 | 23 | 8d2d8fba3869f8a8c1a52b1a3c090b1cf49000cb | bigcode/the-stack | train |
45589ec984a4d62b630d14fe | train | class | class Timer(object):
def __init__(self, verbose=False):
self.verbose = verbose
self.start = None
self.end = None
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
self.end = time.time()
self.time = self.end - self.s... | class Timer(object):
| def __init__(self, verbose=False):
self.verbose = verbose
self.start = None
self.end = None
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
self.end = time.time()
self.time = self.end - self.start
if self.... | = []
name_space = 95
params_space = 15
macs_space = 15
bytes_space = 15
bitops_space = 15
energy_space = 15
latency_space = 15
seconds_space = 15
num_forwards = 10
class Timer(object):
| 64 | 64 | 96 | 4 | 59 | deJQK/AdaBits | utils/model_profiling.py | Python | Timer | Timer | 25 | 39 | 25 | 25 | 5d8b689bb91c42197f2954bbf100ab9549715a68 | bigcode/the-stack | train |
44221db4c25c9ea209c5de23 | train | function | def remove_profiling_hooks():
global model_profiling_hooks
for h in model_profiling_hooks:
h.remove()
model_profiling_hooks = []
| def remove_profiling_hooks():
| global model_profiling_hooks
for h in model_profiling_hooks:
h.remove()
model_profiling_hooks = []
| def add_profiling_hooks(m, verbose):
global model_profiling_hooks
model_profiling_hooks.append(
m.register_forward_hook(
lambda m, input, output: module_profiling(
m, input, output, verbose=verbose)))
def remove_profiling_hooks():
| 63 | 64 | 37 | 7 | 56 | deJQK/AdaBits | utils/model_profiling.py | Python | remove_profiling_hooks | remove_profiling_hooks | 227 | 231 | 227 | 227 | 43eb4ff51e286ea08192788da59fc2a96a2fd6bc | bigcode/the-stack | train |
a0197650882d3fdee67bdb37 | train | function | def get_params(self):
"""get number of params in module"""
return np.sum(
[np.prod(list(w.size())) for w in self.parameters()])
| def get_params(self):
| """get number of params in module"""
return np.sum(
[np.prod(list(w.size())) for w in self.parameters()])
| self):
self.start = time.time()
return self
def __exit__(self, *args):
self.end = time.time()
self.time = self.end - self.start
if self.verbose:
print('Elapsed time: %f ms.' % self.time)
def get_params(self):
| 64 | 64 | 33 | 5 | 59 | deJQK/AdaBits | utils/model_profiling.py | Python | get_params | get_params | 42 | 45 | 42 | 42 | b32cae283d9276bc4a070505d9c6a84f2b0752ec | bigcode/the-stack | train |
d794c82150ed75d6971efed8 | train | function | def model_profiling(model, height, width, batch=1, channel=3, use_cuda=True,
verbose=True):
""" Pytorch model profiling with input image size
(batch, channel, height, width).
The function exams the number of multiply-accumulates (n_macs).
Args:
model: pytorch model
h... | def model_profiling(model, height, width, batch=1, channel=3, use_cuda=True,
verbose=True):
| """ Pytorch model profiling with input image size
(batch, channel, height, width).
The function exams the number of multiply-accumulates (n_macs).
Args:
model: pytorch model
height: int
width: int
batch: int
channel: int
use_cuda: bool
Returns:
... | (energy_space, ' ') +
'{:.2f}'.format(self.latency).rjust(latency_space, ' ') +
'{:,}'.format(self.n_seconds).rjust(seconds_space, ' '))
return
def add_profiling_hooks(m, verbose):
global model_profiling_hooks
model_profiling_hooks.append(
m.register_forward_hook(
lam... | 167 | 168 | 561 | 27 | 140 | deJQK/AdaBits | utils/model_profiling.py | Python | model_profiling | model_profiling | 234 | 284 | 234 | 235 | 7be1120ce9aef68ecf5260004a3626843a95a1d6 | bigcode/the-stack | train |
e805df156425afa7dd625eec | train | function | def module_profiling(self, input, output, verbose):
ins = input[0].size()
outs = output.size()
# NOTE: There are some difference between type and isinstance, thus please
# be careful.
t = type(self)
if isinstance(self, nn.Conv2d):
self.n_macs = (ins[1] * outs[1] *
... | def module_profiling(self, input, output, verbose):
| ins = input[0].size()
outs = output.size()
# NOTE: There are some difference between type and isinstance, thus please
# be careful.
t = type(self)
if isinstance(self, nn.Conv2d):
self.n_macs = (ins[1] * outs[1] *
self.kernel_size[0] * self.kernel_size[1] *
... | = verbose
self.start = None
self.end = None
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
self.end = time.time()
self.time = self.end - self.start
if self.verbose:
print('Elapsed time: %f ms.' % self.ti... | 256 | 256 | 1,907 | 13 | 242 | deJQK/AdaBits | utils/model_profiling.py | Python | module_profiling | module_profiling | 70 | 216 | 70 | 70 | 0bf5f242b52e6fede44ff28996c78357f049a1a4 | bigcode/the-stack | train |
0cbd58c3532d4f351bdd9b61 | train | function | def add_profiling_hooks(m, verbose):
global model_profiling_hooks
model_profiling_hooks.append(
m.register_forward_hook(
lambda m, input, output: module_profiling(
m, input, output, verbose=verbose)))
| def add_profiling_hooks(m, verbose):
| global model_profiling_hooks
model_profiling_hooks.append(
m.register_forward_hook(
lambda m, input, output: module_profiling(
m, input, output, verbose=verbose)))
| f}'.format(self.energy).rjust(energy_space, ' ') +
'{:.2f}'.format(self.latency).rjust(latency_space, ' ') +
'{:,}'.format(self.n_seconds).rjust(seconds_space, ' '))
return
def add_profiling_hooks(m, verbose):
| 64 | 64 | 56 | 10 | 53 | deJQK/AdaBits | utils/model_profiling.py | Python | add_profiling_hooks | add_profiling_hooks | 219 | 224 | 219 | 219 | 43b2e312811394658d290d539541a102a9a05b39 | bigcode/the-stack | train |
775dd7e37f3a0a41613b34d6 | train | function | def conv_module_name_filter(name):
"""filter module name to have a short view"""
filters = {
'kernel_size': 'k',
'stride': 's',
'padding': 'pad',
'bias': 'b',
'groups': 'g',
}
for k in filters:
name = name.replace(k, filters[k])
return name
| def conv_module_name_filter(name):
| """filter module name to have a short view"""
filters = {
'kernel_size': 'k',
'stride': 's',
'padding': 'pad',
'bias': 'b',
'groups': 'g',
}
for k in filters:
name = name.replace(k, filters[k])
return name
| for w in self.parameters()])
def run_forward(self, input):
with Timer() as t:
for _ in range(num_forwards):
self.forward(*input)
torch.cuda.synchronize()
return int(t.time * 1e9 / num_forwards)
def conv_module_name_filter(name):
| 64 | 64 | 80 | 7 | 57 | deJQK/AdaBits | utils/model_profiling.py | Python | conv_module_name_filter | conv_module_name_filter | 56 | 67 | 56 | 56 | b2fb4595dfeba064e708484adfb4b92bb1fa45c5 | bigcode/the-stack | train |
10e3b9556f557d22e4c25be1 | train | function | def run_forward(self, input):
with Timer() as t:
for _ in range(num_forwards):
self.forward(*input)
torch.cuda.synchronize()
return int(t.time * 1e9 / num_forwards)
| def run_forward(self, input):
| with Timer() as t:
for _ in range(num_forwards):
self.forward(*input)
torch.cuda.synchronize()
return int(t.time * 1e9 / num_forwards)
| - self.start
if self.verbose:
print('Elapsed time: %f ms.' % self.time)
def get_params(self):
"""get number of params in module"""
return np.sum(
[np.prod(list(w.size())) for w in self.parameters()])
def run_forward(self, input):
| 63 | 64 | 50 | 7 | 57 | deJQK/AdaBits | utils/model_profiling.py | Python | run_forward | run_forward | 48 | 53 | 48 | 48 | 50913c1bcf0b5fb85a4036488380966a646da423 | bigcode/the-stack | train |
1a1191b671ed283c6fe65f0e | train | function | @app.shell_context_processor
def make_shell_context():
return {'db': db, 'User': User, 'Post': Post}
| @app.shell_context_processor
def make_shell_context():
| return {'db': db, 'User': User, 'Post': Post}
| from app import app, db
from app.models import User, Post
@app.shell_context_processor
def make_shell_context():
| 25 | 64 | 27 | 10 | 14 | dm1tr/microblog_flask | microblog.py | Python | make_shell_context | make_shell_context | 5 | 7 | 5 | 6 | 455b9facf27aa8aaf059129b8b580d40daee76ec | bigcode/the-stack | train |
eefde1493cb30e6c3d584044 | train | function | def _to_gpu(td):
if NUM_GPUS > 1:
return td
for k in td:
if k != 'metadata':
td[k] = {k2: v.cuda(non_blocking=True) for k2, v in td[k].items()} if isinstance(td[k], dict) else td[k].cuda(
non_blocking=True)
return td
| def _to_gpu(td):
| if NUM_GPUS > 1:
return td
for k in td:
if k != 'metadata':
td[k] = {k2: v.cuda(non_blocking=True) for k2, v in td[k].items()} if isinstance(td[k], dict) else td[k].cuda(
non_blocking=True)
return td
| only_use_relevant_dets=params['dataset_reader'].get('only_use_relevant_dets', True))
NUM_GPUS = torch.cuda.device_count()
NUM_CPUS = multiprocessing.cpu_count()
if NUM_GPUS == 0:
raise ValueError("you need gpus!")
def _to_gpu(td):
| 64 | 64 | 82 | 6 | 58 | alfred100p/VC-R-CNN | downstream/r2c_vc/train.py | Python | _to_gpu | _to_gpu | 72 | 79 | 72 | 72 | da48c92cd2312c1e3801b2f0cd37f800ba56fdfe | bigcode/the-stack | train |
8ea52c2eada9a9b6ca664daa | train | class | class FrozenLake(object):
def __init__(self):
self.env = gym.make(environment)
action_space_size = self.env.action_space.n
state_space_size = self.env.observation_space.n
self.q_table = np.zeros((state_space_size,action_space_size))
def train(self):
global eps
r... | class FrozenLake(object):
| def __init__(self):
self.env = gym.make(environment)
action_space_size = self.env.action_space.n
state_space_size = self.env.observation_space.n
self.q_table = np.zeros((state_space_size,action_space_size))
def train(self):
global eps
rewards_all_episodes = []
... | import os
import gym
gym.logger.set_level(40)
import time
import random
import numpy as np
import matplotlib.pyplot as plt
from IPython import display
from variables import*
class FrozenLake(object):
| 45 | 183 | 612 | 5 | 40 | Zuu97/Artifitial-Intelligence-with-Q-Learning-Examples | FrozenLake Q-learning Agent/frozenlake.py | Python | FrozenLake | FrozenLake | 12 | 97 | 12 | 12 | 1e7e1e1787b99816a6ca9d684b49d296a5ba735b | bigcode/the-stack | train |
11dcd17425d8a15eb809cf3f | train | function | @_f
@_p.types(None,_cs.GLenum,_cs.GLenum,_cs.GLuint,_cs.GLenum,_cs.GLsizei,arrays.GLcharArray)
def glDebugMessageInsert(source,type,id,severity,length,buf):pass
| @_f
@_p.types(None,_cs.GLenum,_cs.GLenum,_cs.GLuint,_cs.GLenum,_cs.GLsizei,arrays.GLcharArray)
def glDebugMessageInsert(source,type,id,severity,length,buf): | pass
| (source,type,severity,count,ids,enabled):pass
@_f
@_p.types(None,_cs.GLenum,_cs.GLenum,_cs.GLuint,_cs.GLenum,_cs.GLsizei,arrays.GLcharArray)
def glDebugMessageInsert(source,type,id,severity,length,buf): | 64 | 64 | 54 | 52 | 11 | 5gconnectedbike/Navio2 | env/Lib/site-packages/OpenGL/raw/GLES2/KHR/debug.py | Python | glDebugMessageInsert | glDebugMessageInsert | 107 | 109 | 107 | 109 | f0b917c42e476894afcc128d74996004a457fd4b | bigcode/the-stack | train |
7c845d69409dccc42f4c1b63 | train | function | @_f
@_p.types(None,_cs.GLDEBUGPROC,ctypes.c_void_p)
def glDebugMessageCallback(callback,userParam):pass
| @_f
@_p.types(None,_cs.GLDEBUGPROC,ctypes.c_void_p)
def glDebugMessageCallback(callback,userParam): | pass
| GL_VERTEX_ARRAY=_C('GL_VERTEX_ARRAY',0x8074)
GL_VERTEX_ARRAY_KHR=_C('GL_VERTEX_ARRAY_KHR',0x8074)
@_f
@_p.types(None,_cs.GLDEBUGPROC,ctypes.c_void_p)
def glDebugMessageCallback(callback,userParam): | 64 | 64 | 32 | 30 | 34 | 5gconnectedbike/Navio2 | env/Lib/site-packages/OpenGL/raw/GLES2/KHR/debug.py | Python | glDebugMessageCallback | glDebugMessageCallback | 95 | 97 | 95 | 97 | 42f0949d35b0156cc21b82f24bc60e2f9ca54236 | bigcode/the-stack | train |
f51215ac0a5fb983c47a0461 | train | function | @_f
@_p.types(None,)
def glPopDebugGroupKHR():pass
| @_f
@_p.types(None,)
def glPopDebugGroupKHR(): | pass
| (None,ctypes.c_void_p,_cs.GLsizei,arrays.GLcharArray)
def glObjectPtrLabelKHR(ptr,length,label):pass
@_f
@_p.types(None,)
def glPopDebugGroup():pass
@_f
@_p.types(None,)
def glPopDebugGroupKHR(): | 64 | 64 | 19 | 17 | 46 | 5gconnectedbike/Navio2 | env/Lib/site-packages/OpenGL/raw/GLES2/KHR/debug.py | Python | glPopDebugGroupKHR | glPopDebugGroupKHR | 152 | 154 | 152 | 154 | ab8496e0c96a3f5b9edf2779fbb70416920857cf | bigcode/the-stack | train |
dd26a6c98add76372b2d5fee | train | function | @_f
@_p.types(None,)
def glPopDebugGroup():pass
| @_f
@_p.types(None,)
def glPopDebugGroup(): | pass
| def glObjectPtrLabel(ptr,length,label):pass
@_f
@_p.types(None,ctypes.c_void_p,_cs.GLsizei,arrays.GLcharArray)
def glObjectPtrLabelKHR(ptr,length,label):pass
@_f
@_p.types(None,)
def glPopDebugGroup(): | 64 | 64 | 18 | 16 | 47 | 5gconnectedbike/Navio2 | env/Lib/site-packages/OpenGL/raw/GLES2/KHR/debug.py | Python | glPopDebugGroup | glPopDebugGroup | 149 | 151 | 149 | 151 | 535580e8de12393514da597b6dd67c9d0aa87c60 | bigcode/the-stack | train |
ed90cac96055eae8b5c17bd7 | train | function | @_f
@_p.types(None,ctypes.c_void_p,_cs.GLsizei,arrays.GLcharArray)
def glObjectPtrLabelKHR(ptr,length,label):pass
| @_f
@_p.types(None,ctypes.c_void_p,_cs.GLsizei,arrays.GLcharArray)
def glObjectPtrLabelKHR(ptr,length,label): | pass
| .types(None,ctypes.c_void_p,_cs.GLsizei,arrays.GLcharArray)
def glObjectPtrLabel(ptr,length,label):pass
@_f
@_p.types(None,ctypes.c_void_p,_cs.GLsizei,arrays.GLcharArray)
def glObjectPtrLabelKHR(ptr,length,label): | 64 | 64 | 37 | 35 | 28 | 5gconnectedbike/Navio2 | env/Lib/site-packages/OpenGL/raw/GLES2/KHR/debug.py | Python | glObjectPtrLabelKHR | glObjectPtrLabelKHR | 146 | 148 | 146 | 148 | aea72b980279faa549f7fb4f2942320a1a865af3 | bigcode/the-stack | train |
395edf6458f148d1eeefa094 | train | function | @_f
@_p.types(None,_cs.GLenum,_cs.GLuint,_cs.GLsizei,arrays.GLcharArray)
def glPushDebugGroupKHR(source,id,length,message):pass
| @_f
@_p.types(None,_cs.GLenum,_cs.GLuint,_cs.GLsizei,arrays.GLcharArray)
def glPushDebugGroupKHR(source,id,length,message): | pass
| cs.GLuint,_cs.GLsizei,arrays.GLcharArray)
def glPushDebugGroup(source,id,length,message):pass
@_f
@_p.types(None,_cs.GLenum,_cs.GLuint,_cs.GLsizei,arrays.GLcharArray)
def glPushDebugGroupKHR(source,id,length,message): | 64 | 64 | 41 | 39 | 24 | 5gconnectedbike/Navio2 | env/Lib/site-packages/OpenGL/raw/GLES2/KHR/debug.py | Python | glPushDebugGroupKHR | glPushDebugGroupKHR | 158 | 160 | 158 | 160 | 1c528d4c78ca2e7e2618d6fbceb4785cb46b3a10 | bigcode/the-stack | train |
7729480e4c4212462ae20ec2 | train | function | @_f
@_p.types(None,_cs.GLDEBUGPROCKHR,ctypes.c_void_p)
def glDebugMessageCallbackKHR(callback,userParam):pass
| @_f
@_p.types(None,_cs.GLDEBUGPROCKHR,ctypes.c_void_p)
def glDebugMessageCallbackKHR(callback,userParam): | pass
| _f
@_p.types(None,_cs.GLDEBUGPROC,ctypes.c_void_p)
def glDebugMessageCallback(callback,userParam):pass
@_f
@_p.types(None,_cs.GLDEBUGPROCKHR,ctypes.c_void_p)
def glDebugMessageCallbackKHR(callback,userParam): | 63 | 64 | 35 | 33 | 29 | 5gconnectedbike/Navio2 | env/Lib/site-packages/OpenGL/raw/GLES2/KHR/debug.py | Python | glDebugMessageCallbackKHR | glDebugMessageCallbackKHR | 98 | 100 | 98 | 100 | 6e873b60b35efaf18a4531809316bf83c4f1a975 | bigcode/the-stack | train |
b8350fd4653b4492dec2a8e2 | train | function | @_f
@_p.types(None,_cs.GLenum,_cs.GLuint,_cs.GLsizei,arrays.GLsizeiArray,arrays.GLcharArray)
def glGetObjectLabel(identifier,name,bufSize,length,label):pass
| @_f
@_p.types(None,_cs.GLenum,_cs.GLuint,_cs.GLsizei,arrays.GLsizeiArray,arrays.GLcharArray)
def glGetObjectLabel(identifier,name,bufSize,length,label): | pass
| bufSize,sources,types,ids,severities,lengths,messageLog):pass
@_f
@_p.types(None,_cs.GLenum,_cs.GLuint,_cs.GLsizei,arrays.GLsizeiArray,arrays.GLcharArray)
def glGetObjectLabel(identifier,name,bufSize,length,label): | 64 | 64 | 48 | 46 | 17 | 5gconnectedbike/Navio2 | env/Lib/site-packages/OpenGL/raw/GLES2/KHR/debug.py | Python | glGetObjectLabel | glGetObjectLabel | 119 | 121 | 119 | 121 | b8b68cfcb9f57d949cd91d24980393d4c1897d10 | bigcode/the-stack | train |
a89909ab12c18199e88b032d | train | function | @_f
@_p.types(None,_cs.GLenum,_cs.GLenum,_cs.GLuint,_cs.GLenum,_cs.GLsizei,arrays.GLcharArray)
def glDebugMessageInsertKHR(source,type,id,severity,length,buf):pass
| @_f
@_p.types(None,_cs.GLenum,_cs.GLenum,_cs.GLuint,_cs.GLenum,_cs.GLsizei,arrays.GLcharArray)
def glDebugMessageInsertKHR(source,type,id,severity,length,buf): | pass
| (source,type,id,severity,length,buf):pass
@_f
@_p.types(None,_cs.GLenum,_cs.GLenum,_cs.GLuint,_cs.GLenum,_cs.GLsizei,arrays.GLcharArray)
def glDebugMessageInsertKHR(source,type,id,severity,length,buf): | 64 | 64 | 55 | 53 | 10 | 5gconnectedbike/Navio2 | env/Lib/site-packages/OpenGL/raw/GLES2/KHR/debug.py | Python | glDebugMessageInsertKHR | glDebugMessageInsertKHR | 110 | 112 | 110 | 112 | ec1b078c0bd43d1bc780cbcfd77b9ca5b3030a0a | bigcode/the-stack | train |
124d3235ed574c7124295f1b | train | function | @_f
@_p.types(None,ctypes.c_void_p,_cs.GLsizei,arrays.GLsizeiArray,arrays.GLcharArray)
def glGetObjectPtrLabel(ptr,bufSize,length,label):pass
| @_f
@_p.types(None,ctypes.c_void_p,_cs.GLsizei,arrays.GLsizeiArray,arrays.GLcharArray)
def glGetObjectPtrLabel(ptr,bufSize,length,label): | pass
| arrays.GLcharArray)
def glGetObjectLabelKHR(identifier,name,bufSize,length,label):pass
@_f
@_p.types(None,ctypes.c_void_p,_cs.GLsizei,arrays.GLsizeiArray,arrays.GLcharArray)
def glGetObjectPtrLabel(ptr,bufSize,length,label): | 64 | 64 | 45 | 43 | 20 | 5gconnectedbike/Navio2 | env/Lib/site-packages/OpenGL/raw/GLES2/KHR/debug.py | Python | glGetObjectPtrLabel | glGetObjectPtrLabel | 125 | 127 | 125 | 127 | c7036ada9544cb372fa3d350d834c476a226c62b | bigcode/the-stack | train |
7f756136f0d6533f43d5ac00 | train | function | @_f
@_p.types(None,_cs.GLenum,_cs.GLuint,_cs.GLsizei,arrays.GLcharArray)
def glObjectLabel(identifier,name,length,label):pass
| @_f
@_p.types(None,_cs.GLenum,_cs.GLuint,_cs.GLsizei,arrays.GLcharArray)
def glObjectLabel(identifier,name,length,label): | pass
| .types(None,_cs.GLenum,arrays.GLvoidpArray)
def glGetPointervKHR(pname,params):pass
@_f
@_p.types(None,_cs.GLenum,_cs.GLuint,_cs.GLsizei,arrays.GLcharArray)
def glObjectLabel(identifier,name,length,label): | 64 | 64 | 39 | 37 | 26 | 5gconnectedbike/Navio2 | env/Lib/site-packages/OpenGL/raw/GLES2/KHR/debug.py | Python | glObjectLabel | glObjectLabel | 137 | 139 | 137 | 139 | 738e12ec461ae2353171b41d2235897fbc80ec35 | bigcode/the-stack | train |
b256cadaa767e99ed6618deb | train | function | @_f
@_p.types(None,_cs.GLenum,_cs.GLuint,_cs.GLsizei,arrays.GLsizeiArray,arrays.GLcharArray)
def glGetObjectLabelKHR(identifier,name,bufSize,length,label):pass
| @_f
@_p.types(None,_cs.GLenum,_cs.GLuint,_cs.GLsizei,arrays.GLsizeiArray,arrays.GLcharArray)
def glGetObjectLabelKHR(identifier,name,bufSize,length,label): | pass
| Array)
def glGetObjectLabel(identifier,name,bufSize,length,label):pass
@_f
@_p.types(None,_cs.GLenum,_cs.GLuint,_cs.GLsizei,arrays.GLsizeiArray,arrays.GLcharArray)
def glGetObjectLabelKHR(identifier,name,bufSize,length,label): | 64 | 64 | 49 | 47 | 16 | 5gconnectedbike/Navio2 | env/Lib/site-packages/OpenGL/raw/GLES2/KHR/debug.py | Python | glGetObjectLabelKHR | glGetObjectLabelKHR | 122 | 124 | 122 | 124 | 1b3c540dd92ce491ca4293ba25a52a1017282f9d | bigcode/the-stack | train |
2960e17b854ecc5ca22d3c29 | train | function | @_f
@_p.types(None,ctypes.c_void_p,_cs.GLsizei,arrays.GLcharArray)
def glObjectPtrLabel(ptr,length,label):pass
| @_f
@_p.types(None,ctypes.c_void_p,_cs.GLsizei,arrays.GLcharArray)
def glObjectPtrLabel(ptr,length,label): | pass
| cs.GLenum,_cs.GLuint,_cs.GLsizei,arrays.GLcharArray)
def glObjectLabelKHR(identifier,name,length,label):pass
@_f
@_p.types(None,ctypes.c_void_p,_cs.GLsizei,arrays.GLcharArray)
def glObjectPtrLabel(ptr,length,label): | 64 | 64 | 36 | 34 | 29 | 5gconnectedbike/Navio2 | env/Lib/site-packages/OpenGL/raw/GLES2/KHR/debug.py | Python | glObjectPtrLabel | glObjectPtrLabel | 143 | 145 | 143 | 145 | 97c41107184d1df5968b8152102c9085ff22a4d8 | bigcode/the-stack | train |
b0311990540a083048004e33 | train | function | @_f
@_p.types(_cs.GLuint,_cs.GLuint,_cs.GLsizei,arrays.GLuintArray,arrays.GLuintArray,arrays.GLuintArray,arrays.GLuintArray,arrays.GLsizeiArray,arrays.GLcharArray)
def glGetDebugMessageLog(count,bufSize,sources,types,ids,severities,lengths,messageLog):pass
| @_f
@_p.types(_cs.GLuint,_cs.GLuint,_cs.GLsizei,arrays.GLuintArray,arrays.GLuintArray,arrays.GLuintArray,arrays.GLuintArray,arrays.GLsizeiArray,arrays.GLcharArray)
def glGetDebugMessageLog(count,bufSize,sources,types,ids,severities,lengths,messageLog): | pass
| @_f
@_p.types(_cs.GLuint,_cs.GLuint,_cs.GLsizei,arrays.GLuintArray,arrays.GLuintArray,arrays.GLuintArray,arrays.GLuintArray,arrays.GLsizeiArray,arrays.GLcharArray)
def glGetDebugMessageLog(count,bufSize,sources,types,ids,severities,lengths,messageLog): | 75 | 64 | 77 | 75 | 0 | 5gconnectedbike/Navio2 | env/Lib/site-packages/OpenGL/raw/GLES2/KHR/debug.py | Python | glGetDebugMessageLog | glGetDebugMessageLog | 113 | 115 | 113 | 115 | 2538e757a74cd0914a633e552c21ae5eb41fe25b | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.