text string | size int64 | token_count int64 |
|---|---|---|
import json
import logging
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler, ConversationHandler
import os
from googletrans import Translator
import Controller as controller
import DBController as dbController... | 6,745 | 1,923 |
num = 1
num1 = 1111
num2 = 2222
num3 = 3333
num4 = 4444
| 60 | 46 |
from .django_request import Request
__all__ = ('Request',)
| 60 | 19 |
"""
Source: https://github.com/vlukiyanov/pt-dec/blob/master/tests/test_cluster.py
"""
import torch
from unittest import TestCase
from module import ClusterAssignment
class TestClusterAssignment(TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.cluster = ClusterAssignment(
clu... | 871 | 313 |
from django.db import models
from django.urls import reverse
import random,os
from ecommerce_src.utils import unique_slug_generator,get_filename
from django.db.models.signals import pre_save
from django.utils.encoding import smart_str
from django.core.files.storage import FileSystemStorage
from django.conf import setti... | 2,789 | 869 |
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
class SeleniumCrosswordHelper:
"""
A class to determine the web-operations of Selenium.
Methods
---------
get_clues()
Returns the data of the clues using the tags that are embedded... | 5,473 | 1,699 |
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs
from cowpy import cow
import os
import json
httpcow = '''<!DOCTYPE html>
<html>
<head>
<title> cowsay </title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="/cow">cowsay</a></li... | 3,930 | 1,155 |
"""
byceps.services.site.dbmodels.site
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from typing import Optional
from ....database import db
from ....typing import BrandID, PartyID
from ....util.instances import ReprBuilder
f... | 2,873 | 938 |
import setuptools
setuptools.setup(
name='pipupgradeall',
py_modules=['pipupgradeall'],
entry_points={"console_scripts": ["pipupgradeall = pipupgradeall:_main"],},
)
| 178 | 62 |
from flask import Blueprint
from api.json_dataclient import AppliancesDataClient
from api.remoclient import NatureRemoClient
air_controller = Blueprint('air_controller', __name__, url_prefix='/air/api')
@air_controller.route('/send/power/<appliance_id>/<signal>', methods=['POST'])
def send_power(appliance_id,signal... | 1,799 | 588 |
from django.conf import settings
from django.contrib.staticfiles.management.commands.runserver import Command as BaseCommand
class Command(BaseCommand):
def execute(self, *args, **options):
settings.DEBUG = True
return super().execute(*args, **options)
| 275 | 69 |
from flask import Flask, request, jsonify
import json, os
from threading import Timer
from api_controlers import base_function, image_encode_ctl, delete_encode_ctl,\
text_search_ctl, image_search_ctl, semantic_localization_ctl, utils
def api_run(cfg):
app = Flask(__name__) # Flask 初始化
# ================... | 1,952 | 650 |
import atnp.utils as utils
import requests
import csv
import re
import os
def slice_url(url):
match = re.search(utils.LINK_PATTERN, url)
return match.group(1), match.group(2), match.group(3)
def gen_unique_name(domain, path):
return "{}__{}".format(domain, path.replace("/", "_"))
def makerequest(row, ... | 2,440 | 809 |
"""add otp column
Revision ID: 5ce477cd7ee3
Revises: 54f029830204
Create Date: 2020-05-12 19:04:09.302116
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5ce477cd7ee3'
down_revision = '54f029830204'
branch_labels = None
depends_on = None
def upgrade():
#... | 754 | 303 |
#!/usr/bin/env python
from setuptools import setup
setup(
name='boto-source-profile-mfa',
version='0.0.11',
description='AWS boto helper library for reusing MFA tokens in profiles with the same source profile',
author='Raymond Butcher',
author_email='ray.butcher@claranet.uk',
url='https://gith... | 631 | 214 |
#!/usr/bin/python
import json
import base64
from st2actions.runners.pythonrunner import Action
from lib import k8s
from datetime import datetime
deleteoptions = {}
class SecretDelete(Action):
def run(self, ns, name):
k8suser = self.config.get('user')
k8spass = self.config.get('password')
... | 870 | 281 |
#!/usr/bin/env python
import tensorflow
import pandas as pd
import numpy as np
from time import time
from keras.models import Sequential
from keras.layers import Dense
from keras.callbacks import TensorBoard
from keras.wrappers.scikit_learn import KerasRegressor
from sklearn.model_selection import train_test... | 3,087 | 1,157 |
# -*- coding: utf-8 -*
"""信号処理一般関数"""
def gen_chirp(duration, fs=96, **kwargs):
"""Generate chirp signal.
特定の長さのチャープ信号を返します.
Args:
duration (float) : 生成する信号の持続時間 (単位は sec).
fs (int, optional) : 生成する信号のサンプリング周波数
(単位は kHz. デフォルトでは 96kHz)
**kwargs: scipy.signal.chirp 関数に... | 1,725 | 867 |
set_saya = {1,2,3,4,5}
set_saya.clear()
print(set_saya) | 55 | 33 |
from .uci_datasets import fetch_drugscom | 40 | 14 |
from pyautoeasy import cli
cli.main() | 37 | 13 |
from datetime import date, timedelta
from decimal import Decimal
from contact.models import Contact
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from geo.models import Country, Locality
from invoice.models import (INVOICE_STATUSTYPE_DRAFT, VAT, CompanyInvoice,
... | 39,009 | 11,654 |
import random
from pyrival.ordersort import *
def test_ordersort():
for _ in range(10000):
l = random.randint(1, 100)
arr = [random.randint(0, 1000) for _ in range(l)]
got = ordersort(range(l), arr)
expected = sorted(range(l), key=arr.__getitem__)
assert [arr[i] for i i... | 1,412 | 542 |
from PIL import Image, ImageDraw, ImageFont
import random
im = Image.new('RGBA',(120,50),(255,255,255))
text = random.sample('abcdefghijklmnopqrstuvwxyz\
ABCDEFGHIJKLMNOPQRSTUVWXYZ',4)
draw = ImageDraw.Draw(im)
font = ImageFont.truetype("msyh.ttf",40)
x=0
y=0
for i in xrange(200):
x1 = random.randint(0,120)
... | 912 | 454 |
from functools import reduce
from django import template
register = template.Library()
def rank_leg(scores):
points = {}
ranked = sorted(scores, key=lambda x: x[1], reverse=True)
for i in range(0, len(ranked)):
if ranked[i][1] != (0, 0, 0):
points[ranked[i][0]] = (len(ranked) - i, r... | 8,292 | 2,890 |
from Songlist import Songlist
import random
class Playlist(Songlist):
def __init__(self, songpool, n_minimum=3, n_maximum=7):
super().__init__("Playlist")
random.seed(539)
self.songpool = songpool
self.n_minimum = min((n_minimum, len(songpool.data)))
self.n_maximum = ma... | 1,893 | 608 |
import inspect
from dataclasses import dataclass
from typing import Callable, Optional, OrderedDict
import aiohttp
import discord
from discord.member import Member
from discord.role import Role
from discord.user import User
from exceptions import InvaildArgument
SUB_COMMAND = 1
SUB_COMMAND_GROUP = 2
STRING = 3
INTEG... | 4,131 | 1,095 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions.normal import Normal
from monai.networks.nets import UNet,Classifier,DenseNet,BasicUNet,DynUNet
import numpy as np
import math
from kornia.geometry.transform import get_perspective_transform,get_affine_matrix2d
from .MultiLevelN... | 20,192 | 6,763 |
# Copyright (c) 2020 Antti Kivi
# Licensed under the MIT License
"""A module that contains the class for the object that
represents LLVM and various LLVM tools in the toolchain of the
build script.
"""
import os
import stat
from argparse import Namespace
from ...util import http, shell
from ...build_directory impo... | 9,672 | 2,911 |
class DataProcessingError(RuntimeError):
def __init__(self, text, data=None):
self.text = text
self.data = data
def __str__(self):
return self.text
def __repr__(self):
return self.text
class AuthenticationError(PermissionError):
pass
class BadRequestError(ValueError... | 435 | 128 |
#!/opt/local/bin/python
import os, sys
import numpy as np
import cv, cv2
import CVAnalysis
from Board import Board
from util import print_message, print_status
#==========[ Global Data ]==========
corner_keypoints = []
corner_image_points = []
corner_board_points = []
corner_sift_desc = []
def get_closest_keyp... | 3,269 | 1,284 |
from time import sleep
import urllib.request
import webbrowser
try:
urllib.request.urlopen("https://www.youtube.com/watch?v=ffbI0JMW7g4")
except Exception as erro: # Desligando o wifi, ou o site não estiver no ar
print('\033[1; 31mO melhor vídeo do youtube não está acessível no momento.\033[m')
er = erro ... | 607 | 243 |
from fractions import Fraction
from dash import html
import numpy as np
from dash import callback_context
from dash.dependencies import Input, Output
from pymatgen.core.structure import Structure
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
from pymatgen.util.string import unicodeify_spacegroup, unicodeif... | 5,546 | 1,526 |
from xeger import Xeger
import api_signer
import protocol_formatter
import aws_api_shapeshifter
""" The operation_obj will be the primary location where parameters are altered and configured.
Every user generated modification will pass throug here. As a result this code is ugly and I'm
only partially sorry. "... | 14,306 | 3,751 |
import settings
def get_confluence_page_latex_path(space_key, page_id):
confluence_page_latex_path = \
f"{settings.LOCAL_CONFLUENCE_PAGE_LATEX_FOLDER}/" \
f"{space_key}_{page_id}.tex"
return confluence_page_latex_path
| 244 | 97 |
# uci.py
# Copyright 2015 Roger Marsh
# License: See LICENSE.TXT (BSD licence)
"""Control multiple UCI compliant chess engines."""
import tkinter
import tkinter.messagebox
import tkinter.filedialog
from solentware_grid.core.dataclient import DataSource
from solentware_misc.gui.exceptionhandler import ExceptionHandl... | 29,064 | 7,743 |
# python -m venv venv
# source venv/Scripts/activate
# pip install pylint
# pip install ipython
# pip install flask
# pip install flask_debugtoolbar
# pip install pylint-flask
# pip install psycopg2-binary
# pip install flask-sqlalchemy
# pip install pylint_flask_sqlalchemy
# pip install pylint-sqlalchemy
# pip install... | 4,704 | 1,723 |
"""
Copyright (c) 2020 School of Math and Computer Science, University of Havana
COOL compiler project
"""
LEXER_ERRORS = []
PARSER_ERRORS = []
SEMANTIC_ERRORS = []
def add_lexer_error(line, column, message):
LEXER_ERRORS.append(f'({line}, {column}) - LexicographicError: {message}')
def add_parser_error(line,... | 541 | 199 |
# Generated by Django 2.1.3 on 2018-12-12 10:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tokens', '0007_auto_20181205_1024'),
]
operations = [
migrations.AddField(
model_name='priceoracleticker',
name='inv... | 398 | 144 |
from ..scanner_utils import is_space
class SelectItemModel:
__slots__ = ('start', 'end', 'ranges')
def __init__(self, start: int, end: int, ranges: list=None):
self.start = start
self.end = end
self.ranges = ranges
def to_json(self):
return {
'start': self.sta... | 1,177 | 389 |
class NoDialogError(Exception):
"""
Occurs when the user has not inputted any dialog.
"""
pass
class DialogTooBigError(Exception):
"""
Occurs when the user has inputted too big of a dialog.
"""
pass
class DiscordRPCFailed(Exception):
"""
Occurs when pypresence fails to connect to Discord.
"""
... | 434 | 149 |
import time, pytest, inspect
from utils import *
from PIL import Image
def test_effect_overlay_visible_after_creation(run_brave):
run_brave()
time.sleep(0.5)
check_brave_is_running()
add_overlay({'type': 'effect', 'props': {'effect_name': 'edgetv'}})
time.sleep(0.1)
assert_overlays([{'id': 0,... | 2,765 | 1,002 |
import json
from numpy import ndarray
from tensorflow.python.keras import Sequential
from ...helpers.segmentation import split_characters
from .text_field import TextArea
class Tree(TextArea):
def __init__(self, frame: ndarray, model: Sequential, inverted: bool = False):
"""
Constrctor for a tre... | 1,659 | 471 |
# Copyright 2017, Juniper Networks Pvt Ltd.
# All rights reserved.
from jnpr.junos import Device
from jnpr.junos.utils.config import Config
from lxml import etree
import dill
import xmltodict
from io import StringIO
from contextlib import redirect_stdout
from collections import defaultdict
from operator import itemget... | 2,742 | 827 |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... | 21,869 | 6,191 |
import json
from typing import List, Tuple, Optional
from iconservice.base.block import Block
from tools.precommit_converter.data.icon_service_info import IconServiceInfo
from tools.precommit_converter.data.key_value import KeyValue
class NotSupportFileException(Exception):
pass
class ExtractException(Exceptio... | 3,484 | 924 |
# Collection of patterns used for parsing the input workload test file.
# Used by the method: TransactionSimulator.parse_transaction_from_test_line(..)
# Used by the method: TransactionSimulator.parse_and_add_operation(..)
class TransactionParsingPatterns:
number_pattern = '(([1-9][0-9]*)|0)'
identifier_patte... | 2,389 | 764 |
import os
import sys
def set_runpath(repo):
repo = '/' + repo
if os.getcwd()[:13] =='/home/runner/':
os.chdir(os.getcwd()[:(os.getcwd().index(repo) + ((len(repo)*2)+1))] )
else:
os.chdir(os.getcwd()[:(os.getcwd().index(repo) + ((len(repo))+1))] )
return os.getcwd() | 298 | 129 |
from django.test import TestCase
class HomeTests(TestCase):
def test_home_page(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
| 185 | 60 |
from django.contrib import admin
from crudexample.models import employee
admin.site.register(employee)
| 104 | 27 |
from datetime import datetime
from PIL import Image
from torchvision import transforms
from urllib.request import urlopen
import requests
import logging
import os
import sys
import torch
model = torch.hub.load('pytorch/vision:v0.5.0', 'resnet18', pretrained=True)
model.eval()
def get_class_labels():
class_dict = ... | 2,325 | 742 |
import os
import shutil
def main():
"""
Removes any and all files generated from eml_localizer_pipeline.py,
resetting the repository back to it's native state w/r/t code and data.
Will NOT get rid of your zipped data.
WiLL get rid of your unzipped data. So, beware if you're working with a lot,
... | 643 | 216 |
from pathlib import Path
import logging
logging.basicConfig(level=logging.DEBUG)
def split_text_into_columns(nlp_models, df) -> None:
"""
Takes Text Content of one DataFrame Cell and splits into multiple Columns
Args:
nlp_models (list): List of Spacy Language Models
df (Pandas DataFrame):... | 1,471 | 429 |
#!/usr/bin/env python3
from PIL import Image, ImageFont, ImageDraw
base_fields = ["x", "y", "chain", "segid", "seqpos", "name"]
def base_info_of(line):
"""
Line format:
x y chain segid seqpos name
205.500 -150.750 C AB 0 L14
"""
return dict(zip(... | 5,592 | 2,013 |
outfile = codecs.open('out.html', mode='w', encoding='ascii',
errors='html_replace')
| 108 | 32 |
import numbers
import os
import sys
import warnings
from typing import List
import numpy as np
import scipy.signal
import scipy.sparse
from scipy.sparse.linalg import cg, LinearOperator
from . import Backend, ComputeDevice
from ._backend_helper import combined_dim
from ._dtype import from_numpy_dtype, to_numpy_dtype,... | 14,969 | 4,905 |
from flask import Flask, render_template, request, redirect, url_for, session
from flask_mysqldb import MySQL
from sql_helper import *
from html_helper import *
app = Flask(__name__)
app.debug = True
app.secret_key = 'mango'
# Enter your database connection details below
app.config['MYSQL_HOST'] = 'localhost'
app.co... | 5,560 | 1,652 |
import os
import re
from victim_module.victim_config import IMDB_Config
from torch.utils.data import Dataset
from tools import logging
from transformers import AutoTokenizer
from nltk.stem import WordNetLemmatizer
from nltk.corpus import stopwords
os.environ["TOKENIZERS_PARALLELISM"] = "false"
# Setup stopwords list ... | 4,379 | 1,302 |
from django import test
from django.conf import settings
from django.utils import timezone
from django.utils.dateparse import parse_date
from model_mommy import mommy
from .importer_testcase_mixin import ImporterTestCaseMixin
from devilry.devilry_import_v2database.modelimporters.qualifiesforexam_importer import \
... | 14,285 | 4,492 |
from typing import Optional
from botocore.client import BaseClient
from typing import Dict
from botocore.paginate import Paginator
from botocore.waiter import Waiter
from typing import Union
from typing import List
class Client(BaseClient):
def can_paginate(self, operation_name: str = None):
"""
C... | 197,887 | 49,054 |
# -*- coding: utf-8 -*-
import unittest
import sys
sys.path.append("../sqliteminor/")
sys.path.append("../temp/")
import sqliteminor
import setup_db
class ReadHeadTest(unittest.TestCase):
def setUp(self):
self.conn = setup_db.setup_db()
self.read_head_comp = [(1, u'Ash'), (2, u'Yew'), (3, u'White Pine'), (4... | 771 | 346 |
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.urls import reverse
from django.views import generic
from django.views.generic.edit import FormMixin
from .models import *
from Gallery.form import ClientC... | 5,955 | 1,784 |
from kat.lib.tag import Tag
from kat.lib.file import File
from kat.lib.scope import Scope
from kat.tracer import ccscanner as ccs
from kat.tracer import ccparser as ccp
from kat.tracer import ppscanner as pps
from kat.tracer import ppparser as ppp
from kat.ui.tabpage import *
import kat.ui.filetree as ft
import kat.ui.... | 4,766 | 1,656 |
#!/usr/bin/python2.7
# Create the gnuplot script for MO energy diagrams
# This script is released under MIT license.
# Usage: plotMO.py <datefile> > <tol>
# Date file structure:
# 1) different molecules diveded by blank line,
# 2) for each molecule section, start with molecule name
# 3) second line for HOMO number... | 7,709 | 3,116 |
import hashlib
from django.test import TestCase
from django.test.client import Client
from hq.models import ExtUser, Domain, Organization, ReporterProfile
from hq.tests.util import create_user_and_domain
from receiver.models import Submission
from reporters.models import Reporter
class AuthenticationTestCase(TestCase)... | 2,024 | 562 |
from typing import List, Optional
from django.utils.translation import ugettext as _
from couchdbkit import ResourceNotFound
from soil import DownloadBase
from corehq.apps.casegroups.models import CommCareCaseGroup
from corehq.apps.hqcase.utils import get_case_by_identifier
from corehq.form_processor.interfaces.dba... | 7,015 | 2,005 |
import argparse
import json
import sys
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MultiLabelBinarizer
import sklearn.metrics
from coronacode import DocumentClassifier
def main():
parser = argparse.ArgumentParser('Build a model for a classifier')
parser.add_argument('-... | 4,725 | 1,842 |
"""
This class makes it easier to deal with cube tapped events in a procedural way using if statements.
"""
from __future__ import with_statement
__all__ = ["LightCubesEventsSerializer"]
__author__ = "Shitalkumar Sawant"
__copyright__ = "Copyright(c) 2018 All rights reserved"
from threading import Lock
import cozmo... | 1,930 | 686 |
import pytest
import os
import shutil
import sqlite3
import tempfile
import psycopg2
from mergin import MerginClient, ClientError
import sys
sys.path.insert(0, '/home/martin/lutra/mergin-db-sync')
from dbsync import dbsync_init, dbsync_pull, dbsync_push, dbsync_status, config
GEODIFFINFO_EXE = os.environ.get('TES... | 7,771 | 2,637 |
#!/bin/env python3
import sys
import os
import traceback
import asyncio
from biothings_explorer.user_query_dispatcher import SingleEdgeQueryDispatcher
sys.path.append(os.path.dirname(os.path.abspath(__file__))+"/../../UI/OpenAPI/python-flask-server/")
from swagger_server.models.node import Node
from swagger_server.mo... | 20,773 | 6,342 |
#FFT
p = 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001
field = GF(p)
R = field(0xe0a77c19a07df2f666ea36f7879462e36fc76959f60cd29ac96341c4ffffffb)
root_of_unity = field(0x1860ef942963f9e756452ac01eb203d8a22bf3742445ffd6636e735580d13d9c) / R
FILE_LOCATION = "/home/k/TestCuda3/benches.txt"
unity_ord... | 1,679 | 765 |
"""Linkind sensors."""
from zigpy.quirks import CustomCluster
import zigpy.types as t
from zigpy.zcl.clusters.general import Basic
class LinkindBasicCluster(CustomCluster, Basic):
"""Linkind Basic cluster."""
attributes = Basic.attributes.copy()
attributes.update({0x0400A: ("linkind", t.uint8_t, True)})
| 320 | 109 |
import tkinter as tk
def menubar(ui):
pass
| 48 | 19 |
### FILE HADLING #############
## File OPen
""""
Use open() to manipulate files. Open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
===================================================================
"r" - Read - Default value. Opens a file for reading... | 2,088 | 709 |
import os
import sys
import socket
import time
import argparse
import pickle
import datetime
import multiprocessing
import numpy as np
import torch
import torch.optim as optim
import torch.nn.functional as torchF
from torch.optim import lr_scheduler
from torch.utils.data import DataLoader
import torch.multiprocessing... | 5,046 | 1,584 |
#!/usr/bin/python
#####################################
# Name : Daily Check
# Language : Python
# Create date : 2017.03.23
# Version : 0.1
######################################
import csv
import platform
import commands
######################################
# Variables
# 0. System_ENV
# 1. SyslogChecke... | 2,684 | 860 |
import math
n = int(input('Digite um número:'))
resul = n % 2
if resul == 0:
print('O número é par')
else:
print('O número é impar') | 140 | 54 |
"""Faça um programa que pergunte o preço de três produtos e informe qual produto você deve comprar,
sabendo que a decisão é sempre pelo mais barato"""
p1 = float(input('Digite a 1º valor R$ : ').replace(',', '.'))
p2 = float(input('Digite a 2º valor R$ : ').replace(',', '.'))
p3 = float(input('Digite a 3º valor R$ : ... | 933 | 368 |
# -*- coding: utf-8 -*-
"""
@author: jmzhao
"""
from pdr import *
import test | 79 | 39 |
# Copyright 2018 The Fuego Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | 3,677 | 1,128 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 30/03/2019
@author: Maurizio Ferrari Dacrema
"""
import sys, glob, traceback, os
from CythonCompiler.run_compile_subprocess import run_compile_subprocess
if __name__ == '__main__':
# cython_file_list = glob.glob('**/*.pyx', recursive=True)
subf... | 2,578 | 895 |
import random
import numpy as np
from scipy.stats import bernoulli
# TODO: how best to assign rewards? Should "too soon" of use be penalized? Should max reward be > 1?
# what if something is used twice? Shouldn't this increase reward? for now no extra reward is given
class ContextBandit:
def __init__(self, state... | 3,822 | 1,108 |
import angr
######################################
# getenv
######################################
class getenv(angr.SimProcedure):
'''
The getenv() function searches the environment list to find the
environment variable name, and returns a pointer to the
corresponding value string.
'''
#pylin... | 1,473 | 482 |
# pylint: disable=missing-docstring
import torch
import torch.optim as optim
from torch.utils.data.dataset import TensorDataset
import matplotlib.pyplot as plt
import pyblaze.nn as xnn
import pyblaze.plot as P
def train(engine, data, lr=1e-2, epochs=1000):
data_ = torch.as_tensor(data, dtype=torch.float)
# pyl... | 1,571 | 588 |
import numpy as np
from . import params
from . import scrape
from . import utils
from . import league
class BoxScores(league.BoxScores):
def __init__(
self, *, scraper,
season=params.Season.default(),
season_type=params.SeasonType.default(),
date_from=params.DateFro... | 4,896 | 1,498 |
"""
Change Control module URLs
"""
from django.conf.urls import url, patterns
from anaf.changes import views
urlpatterns = patterns('anaf.changes.views',
url(r'^(\.(?P<response_format>\w+))?$', views.index, name='changes_index'),
url(r'^owned(\.(?P<response_format>\w+))?$... | 2,192 | 679 |
# Generated by Django 2.2.4 on 2019-08-09 17:28
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('editor', '0003_auto_20190809_1724'),
]
operations = [
migrations.RenameModel(
old_name='PythonLabs',
new_name='PythonLab',
... | 336 | 129 |
"""
Command : prepare_data.py --src [...] --dst [...]
"""
import argparse
import os
import sys
from tqdm import tqdm
def findaudiofiles(dir):
files = []
for dirpath, _, filenames in os.walk(dir):
for filename in filenames:
if filename.endswith(".wav"):
files.append(os.path.... | 3,429 | 1,190 |
def Obj(): return lambda: None
INFURA_URL = 'https://mainnet.infura.io/v3/81a17a01107e4ac9bf8a556da267ae2d'
BLANKDAO_PUBLIC_KEY = '117f893e-9184-427a-892c-6993e88981f0'
BLANK_TOKEN_ABI = '[{"constant": true, "inputs": [], "name": "mintingFinished", "outputs": [{"name": "", "type": "bool"}], "payable": false,... | 5,317 | 1,957 |
""" Simple wrapper for sklearn regession classes that scales features to have
zero mean and unit variance. Can also easily unscale features of predicted data.
"""
import numpy as np
class regress():
def __init__(self, regressor):
self.regressor = regressor
def add_training_data(self, train_X, train_... | 1,034 | 371 |
import time
import numpy as np
from replayBuffer import Memory
from network import *
class DDPG:
"""docstring for DDPG"""
def __init__(self, sess, env, args):
self.s_dim = env.observation_space.shape[0]
self.act_dim = env.action_space.shape[0]
self.sess = sess
self.args = args... | 7,717 | 2,532 |
import itertools
import unittest
from chainlet.dataflow import MergeLink
from chainlet_unittests.utility import Adder
class ChainSubscription(unittest.TestCase):
def test_pair(self):
"""Subscribe chain[i:j:k] for `a >> b`"""
elements = [Adder(val) for val in (0, -2, -1E6)]
for elements i... | 3,025 | 853 |
# -*- coding: utf-8
import re
import six
from richtypo import Richtypo
from richtypo.rules import ABRule, Rule
try:
from unittest.mock import patch
except ImportError:
from mock import patch
def test_rule_generic():
r = Rule(
pattern='b{2}',
replacement='c'
)
assert r.apply('abb... | 2,727 | 999 |
from django.contrib.auth import views as auth_views
from django.urls import path
from .views import *
app_name = 'accounts'
urlpatterns = [
path('signup/', SignUpView.as_view(), name='signup'),
path('activation/<key>/', ActivationView.as_view(), name='activation'),
path('login/', auth_views.LoginView.as_v... | 786 | 259 |
import time
from dronekit import VehicleMode, connect
from pymavlink import mavutil
fly=False
landing = False
lat = 49.2778638
lon = -123.0633418
vehicle = connect('tcp:127.0.0.1:5763', wait_ready=True)
print "Read channels individually:"
print " Ch1: %s" % vehicle.channels['1']
print " Ch2: %s" % vehicle.channels['2... | 2,230 | 865 |
#------------------------------------------------------------------------------
# Copyright (c) 2013, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------------------------------------------------... | 1,806 | 446 |
from flask import (
Blueprint, flash, g, redirect, render_template, request, url_for
)
from web.login import login_required
from werkzeug.utils import secure_filename
import sqlite3
import web.webscore
import web.system
import time
import server.arcscore
import os
UPLOAD_FOLDER = 'database'
ALLOWED_EXTENSIONS = {'... | 10,940 | 3,523 |
"""
Malformed Atom fallback
"""
from feedreader.fallback.base import (PREFERRED_LINK_TYPES, PREFERRED_CONTENT_TYPES,
Feed, Item, get_element_text, get_attribute, search_child,
get_xpath_node, get_xpath_text, get_xpath_datetime,
... | 3,271 | 1,039 |
"""
Runs taggd, a tool to demultiplex (link molecular barcodes back to) a file of genetic reads,
typically obtained by sequencing. For matched reads, the barcode and its related properties
are added to the read. Unmatched reads, ambiguously matched reads, and stats are by default
produced as output files as well.
The... | 14,122 | 3,980 |
# THIS TAKES AN ALREADY FORMATED DATA TABLE from matlab AND DOES THE REGRESSIONS
# IT ALSO MAKES THE PLOTS
# LAST EDITED 11-29-17
import pandas
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from pylab import *
from pyteomics import mass # can do cool isotope math stuff, not us... | 18,586 | 9,186 |