text string | size int64 | token_count int64 |
|---|---|---|
# Python3
from solution1 import arrayReplace as f
qa = [
([1, 2, 1], 1, 3,
[3, 2, 3]),
([1, 2, 3, 4, 5], 3, 0,
[1, 2, 0, 4, 5]),
([1, 1, 1], 1, 10,
[10, 10, 10]),
([1, 2, 1, 2, 1], 2, 1,
[1, 1, 1, 1, 1]),
([1, 2, 1, 2, 1], 2, 2,
[1, 2, 1, 2, 1]),
([3, 1], 3, 9,
[9... | 633 | 338 |
from avatar2 import *
import sys
import os
import logging
import serial
import time
import argparse
import pyudev
import struct
import ctypes
from random import randint
# For profiling
import pstats
logging.basicConfig(filename='/tmp/inception-tests.log', level=logging.INFO)
# ************************************... | 8,563 | 2,928 |
import gym
import numpy as np
from typing import List, Callable, Optional, Any
from tianshou.env.worker import EnvWorker
class DummyEnvWorker(EnvWorker):
"""Dummy worker used in sequential vector environments."""
def __init__(self, env_fn: Callable[[], gym.Env]) -> None:
super().__init__(env_fn)
... | 1,164 | 365 |
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2021 Beartype authors.
# See "LICENSE" for further details.
'''
**Beartype decorator configuration API** (i.e., enumerations, classes,
singletons, and other attributes enabling external callers t... | 6,687 | 1,858 |
ref = set('123456789')
def pans(n):
r = str(n)
i = 1
while True:
i += 1
r += str(i * n)
if len(r) > 9:
break
if len(r) == 9 and set(r) == ref:
yield i, r
m = 0
for i in xrange(2, 1000000000):
for z, n in pans(i):
if n > m:
m =... | 349 | 156 |
#!/usr/bin/env python3
VERSION = "v0.22.0"
| 43 | 22 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import typing # NOQA: F401
__all__ = [] # type: typing.List[typing.Text]
| 187 | 65 |
import os
import io
import json
from flask import current_app
from hed import models
from hed.errors import HedFileError
from hed import schema as hedschema
from hedweb.constants import base_constants
from hedweb import events, spreadsheet, sidecar, strings
app_config = current_app.config
def get_inpu... | 11,196 | 3,335 |
# 22/06/2021
import itertools
def nonogramrow(seq):
return [sum(g) for k, g in itertools.groupby(seq) if k]
assert nonogramrow([]) == []
assert nonogramrow([0, 0, 0, 0, 0]) == []
assert nonogramrow([1, 1, 1, 1, 1]) == [5]
assert nonogramrow([0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1]) == [5, 4]
assert nonogramrow([1, 1, ... | 563 | 341 |
# paura_lite:
# An ultra-simple command-line audio recorder with real-time
# spectrogram visualization
import numpy as np
import pyaudio
import struct
import scipy.fftpack as scp
import termplotlib as tpl
import os
# get window's dimensions
rows, columns = os.popen('stty size', 'r').read().split()
buff_size = 0.2 ... | 2,191 | 787 |
# -*- coding: utf-8 -*-
from flask import Blueprint, render_template, g, request, make_response
from dataviva.apps.general.views import get_locale
from dataviva.translations.dictionary import dictionary
from dataviva import datavivadir
from config import GZIP_DATA
from dataviva.utils.cached_query import cached_qu... | 3,398 | 1,107 |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright: Fabien Rosso
# Version 0.1.1 - 19 Avril 2016
# Version 0.1.2 - 29 Avril 2016
## Debug VisualStudio
# import ptvsd
# ptvsd.enable_attach(None)
from __future__ import unicode_literals
from __future__ import print_function
import os
import s... | 6,364 | 2,064 |
from django.conf.urls import include, url
urlpatterns = [
url(r'^admin/(?P<slug>[\w\-]+)/', 'posts.views.post_preview', name='post_preview'),
url(r'^tag/(?P<slug>[\w\-]+)/', 'posts.views.posts_view_tag', name='posts_tag'),
url(r'^popular/', 'posts.views.posts_view_popular', name='posts_popular'),
url(r... | 388 | 158 |
from hlt.positionals import Position, Direction
from hlt import constants
import random
import logging
# Import my stuff
import helpers
def navigate_old(ship, destination, game_map):
curr_pos = ship.position
move_cost = game_map[curr_pos].halite_amount/constants.MOVE_COST_RATIO
if ship.halite_amount >=... | 14,320 | 4,479 |
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.svm import SVR
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import HuberRegressor
import numpy as np
import pickle
from dataloader import HeadlineDataset
from csv import writer
import os, subprocess
im... | 2,569 | 949 |
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^', include('apps.blog.urls')),
) | 108 | 39 |
import wikipediaapi
import os
import json
import progressbar
CATEGORY = 'Category:Feminist artists'
#CATEGORY = 'Category:Contemporary artists'
def traverse_categories_tree(categorymembers, level=0, max_level=100):
for c in categorymembers.values():
#print("%s: %s (ns: %d)" % ("*" * (level + 1), c.title,... | 2,285 | 728 |
from os import getcwd
from os.path import join
from src.handlers.yamlHandler import YAMLHandler
from tests.test_utils import returnFiles
__author__ = 'jmeline'
class TestYAMLHandler:
def setup(self):
self.path = join(getcwd(), 'test_handlers', 'test_yamlHandler', 'yamlFiles')
assert self.path
... | 730 | 228 |
from mcpi_e.minecraft import Minecraft
from mcpi_e import block
from time import sleep
from random import *
from math import *
def draw_donut(mcx,mcy,mcz,R,r,mcblock):
for x in range(-R-r,R+r):
for y in range(-R-r,R+r):
xy_dist = sqrt(x**2 + y**2)
if (xy_dist > 0):
ringx = x / xy_dist... | 1,031 | 412 |
"""
Define ORM classes.
"""
from sqlobject import *
class RiskType(SQLObject):
"""Define RiskType ORM class."""
riskTypeName = StringCol()
fields = RelatedJoin('Field')
class Field(SQLObject):
"""Define Field ORM class."""
fieldName = StringCol()
fieldType = ForeignKey('FieldType')
risks =... | 582 | 183 |
# -*- coding: UTF-8 -*-
"""
Usage:
plumbum <template> <namespace> [region] [options]...
Options:
template path to the jinja2 template
namespace AWS namespace. Currently supports: elasticache, elb, ec2, rds, asg, sqs
region AWS region [default: us-east-1]
options key value combinations, they can be ... | 16,178 | 5,517 |
# fabfile
# Fabric command definitions for running anti-entropy reinforcement learning.
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: Tue Jun 13 22:26:00 2017 -0400
#
# Copyright (C) 2017 Bengfort.com
# For license information, see LICENSE.txt
#
# ID: fabfile.py [] benjamin@bengfort.com $
"""
Fab... | 10,440 | 3,294 |
#
# @lc app=leetcode id=657 lang=python3
#
# [657] Robot Return to Origin
#
# https://leetcode.com/problems/robot-return-to-origin/description/
#
# algorithms
# Easy (73.67%)
# Likes: 1228
# Dislikes: 692
# Total Accepted: 274.1K
# Total Submissions: 371K
# Testcase Example: '"UD"'
#
# There is a robot starting ... | 2,275 | 836 |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable
from pants.backend.swift.target_types import SWIFT_FILE_EXTENSIONS, SwiftSourcesGenerator... | 2,171 | 689 |
# get_incrementer.py
"""Helper function to create counter strings with a set length throughout."""
__version__ = '0.2'
__author__ = 'Rob Dupre (KU)'
def get_incrementer(num, num_digits):
if num >= 10**num_digits:
print('NUMBER IS LARGER THAN THE MAX POSSIBLE BASED ON num_digits')
return -1
els... | 1,059 | 361 |
def main():
n = int(input("Digite um número inteiro: "))
resto = n % 2
if resto == 0:
print("Par")
else:
print("Impar")
main()
| 179 | 77 |
"""
The :mod:`pyro.contrib.oed` module provides tools to create optimal experiment
designs for pyro models. In particular, it provides estimators for the
expected information gain (EIG) criterion.
To estimate the EIG for a particular design, use::
def model(design):
...
# Select an appropriate EIG es... | 536 | 166 |
import pytest
from tempo.serve.metadata import KubernetesRuntimeOptions
@pytest.mark.parametrize(
"runtime, replicas",
[
({"replicas": 2}, 2),
({}, 1),
],
)
def test_runtime_options(runtime, replicas):
r = KubernetesRuntimeOptions(**runtime)
assert r.replicas == replicas
| 311 | 108 |
import factory
from faker import Faker
from referral.models import Campaign
faker = Faker()
class FakeCampaignFactory(factory.django.DjangoModelFactory):
class Meta:
model = Campaign
campaign_id = factory.LazyAttribute(lambda x: faker.sha1())
name = factory.LazyAttribute(lambda x: faker.word(... | 323 | 102 |
import json
import requests
import time
from flask import Flask, render_template, request
app = Flask(__name__)
API_KEY='<insert_api_key_here>'
@app.route('/')
def index():
background, style, message = setParams()
return render_template('index.html', background=background, style=style, message=message)
#fun... | 3,703 | 1,172 |
import torch
def magic_box(x):
"""DiCE operation that saves computation graph inside tensor
See ``Implementation of DiCE'' section in the DiCE Paper for details
Args:
x (tensor): Input tensor
Returns:
1 (tensor): Tensor that has computation graph saved
References:
https://g... | 2,587 | 817 |
from django.apps import AppConfig
class CoreapisConfig(AppConfig):
name = 'coreapis'
| 91 | 28 |
from .request import datastore_search
def get_data_from_datastore(expression):
"""Returns a list of records found in a datastore search"""
response = datastore_search(expression)
result = response.get("result", dict())
return result.get("records", dict())
| 274 | 81 |
# File auto-generated against equivalent DynamicSerialize Java class
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# Sep 16, 2016 pmoyer Generated
import numpy
class... | 1,486 | 442 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# dbcluster.py
# GGHC cluster class
# Copyright (c) 2021 Chinasoft International Co., Ltd.
#
# gghc is licensed under Mulan PSL v2.
# You can use this software according to the terms
# and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#
... | 4,051 | 1,323 |
# Blender directX importer
# version baby
# litterature explaining the parser directions :
# I don't want to load the whole file as it can be huge : go chunks
# also I want random access to 3d datas to import pieces, not always everything
# so step1 is a whole file fast parsing, retrieving tokens name and building en... | 36,892 | 10,810 |
# coding: utf8
"""Test cases for text.py file"""
| 49 | 19 |
"""Preprocessing for tag generation"""
from tag_generation.util import utils
import jsonlines
import csv
# For test
FILE_LOC = '/home/krispin/data/improved-happiness/'
# For dev
#FILE_LOC = '/home/krispin/data/improved-happiness/proto/'
skipped, wrote = 0, 0
def get_recipe_tags(file_name: str,
c... | 1,987 | 661 |
import gfootball.env as football_env
from gfootball.env import observation_preprocessing
import gym
import numpy as np
import matplotlib.pyplot as plt
class GoogleFootballMultiAgentEnv(object):
"""An wrapper for GFootball to make it compatible with our codebase."""
def __init__(self, dense_reward, dump_freq,... | 8,263 | 2,761 |
from cache_control_helper import CacheControlHelper
import time
import sys
import requests
import requests_cache
requests_cache.install_cache('performance_test')
def get_request(url):
requests = CacheControlHelper()
try:
res = requests.get(url, timeout=120)
except requests.exceptions.Timeout:
... | 2,136 | 733 |
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import numpy as np
freq = {}
def read_file(filename='corpora.txt'):
f = open(filename, "r", encoding="utf-8")
for character in f.read():
if (character in freq):
freq[character] += 1
... | 1,731 | 761 |
from caffe2.proto import caffe2_pb2
from caffe2.python import core, workspace
import os
import tempfile
from zipfile import ZipFile
'''
Generates a document in markdown format summrizing the coverage of serialized
testing. The document lives in
`caffe2/python/serialized_test/SerializedTestCoverage.m... | 3,925 | 1,354 |
# -*- coding: utf-8 -*-
"""Test MEA."""
#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------
from pathlib import Path
from pytest import raises
import numpy as np
from numpy.testing import assert_arr... | 3,081 | 1,196 |
# <<BEGIN-copyright>>
# Copyright 2021, Lawrence Livermore National Security, LLC.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
# <<END-copyright>>
"""
This module contains useful fudge math routines that do not fit into any other module.
"""
from pqu import PQU
from fudg... | 4,233 | 1,443 |
# 7.6: Jigsaw
| 14 | 11 |
#!/usr/bin/env python3
import os
import time
import shutil
import signal
import yaml
import sass
import pyinotify
from colorama import init, Fore, Style
from jsmin import jsmin
from csscompressor import compress
VERSION = '1.4.7'
class Kyk(object):
"""Kyk
Build JS
- if min: minify in place, append _m... | 9,502 | 2,725 |
# Ejercicio 3
# Crea un script llamado descomposicion.py que realice las siguientes tareas:
#
# Debe tomar 1 argumento que será un número entero positivo.
# En caso de no recibir un argumento, debe mostrar información acerca de cómo utilizar el script.
# El objetivo del script es descomponer el número en unidades, dece... | 1,311 | 461 |
import os
import sys
import argparse
_version_ = '0.0.1'
class scaffold():
result = []
def new_project(self):
if os.path.exists(self.result.project):
print("project has been existed")
exit(1)
os.mkdir(self.result.project)
os.chdir(self.result.project)
... | 2,616 | 809 |
import os
import socket
import threading
import json
import sys
import math
IP = socket.gethostbyname_ex(socket.gethostname())[-1][-1]
PORT = 4450
ADDR = (IP, PORT)
SIZE = 2**10
FORMAT = "utf-8"
SERVER_PATH = "server"
LOGIN = "admin"
PASS = "admin"
def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr}... | 7,131 | 2,159 |
from pyPhenology import utils
observations, temp = utils.load_test_data(name='vaccinium')
import pandas as pd
import time
models_to_use = ['ThermalTime','Alternating','Uniforc','MSB','Unichill']
methods_to_use = ['DE','BF']
sensible_defaults = ['testing','practical','intensive']
timings=[]
for m in models_to_use:
... | 1,160 | 339 |
import keras
import random
import numpy as np
from glob import glob
from keras.models import Model
from keras.utils import np_utils
from keras.models import load_model
import matplotlib.pyplot as plt
import os
import keras.backend as K
import tensorflow as tf
from keras.utils import to_categorical
from tqdm import tqdm... | 9,394 | 4,201 |
from decouple import Module
from .events import MetricEvent
from ..model import ModelLossEndEvent
class LossMetric(Module):
def __init__(self):
super().__init__()
self.sub(ModelLossEndEvent, self.loss)
def loss(self, event: ModelLossEndEvent):
metric_value = event.loss.item()
... | 758 | 195 |
import json
from collections import OrderedDict
def json_file(filename, converter):
with open(filename, 'r') as file:
raw = json.load(
file,
object_pairs_hook=OrderedDict # to insure that order of items in json won't be broken
)
return converter(raw)
| 303 | 87 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# board.py
# Author: Germain GAILLARD <gaillard.germain@gmail.com>
# Version: 0.1
# License: MIT
"""Import modules"""
from random import sample
class Board:
"""board object which regroup the coordinates of the game's elements
(walls, start, end, guard, compo... | 1,963 | 606 |
# -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
#
# Copyright 2018, 8minutenergy / Kisensum.
#
# 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.apa... | 9,362 | 3,033 |
def test_open_home_page(driver, request):
url = 'opencart/'
return driver.get("".join([request.config.getoption("--address"), url]))
element = driver.find_elements_by_xpath("//base[contains(@href, 'http://192.168.56.103/opencart/]")
assert element == 'http://192.168.56.103/opencart/'
assert driver.f... | 381 | 144 |
from django.test import TestCase
from ..middleware import FrontendContextMiddleware
class MockRequest:
pass
class FrontendContextMiddlewareTests(TestCase):
def test_middleware_frontend_context_dict(self):
"""Middleware sets frontend_context dict on request"""
request = MockRequest()
... | 430 | 115 |
"""
tests.test_parser
~~~~~~~~~~~~~~~~~
Parser tests for Drowsy.
"""
# :copyright: (c) 2016-2020 by Nicholas Repole and contributors.
# See AUTHORS for more details.
# :license: MIT - See LICENSE for more details.
from marshmallow import fields
from marshmallow.exceptions import ValidationErro... | 11,589 | 3,298 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v3.2.3),
on Sun Oct 13 21:34:23 2019
If you publish work using this script the most relevant publication is:
Peirce J, Gray JR, Simpson S, MacAskill M, Höchenberger R, Sogo H, Kastman E, Lindeløv ... | 66,893 | 20,472 |
import sys
sys.path.insert(0, './')
sys.path.insert(0, './common')
sys.path.insert(0, './ML-FW')
sys.path.insert(0, './ML-OPE')
sys.path.insert(0, './Online-FW')
sys.path.insert(0, './Online-OPE')
sys.path.insert(0, './Streaming-FW')
sys.path.insert(0, './Streaming-OPE')
import time
import shutil
import utilities as ut... | 1,996 | 825 |
# -*- coding: utf-8 -*-
# python std lib
import logging
import logging.config
log = logging.getLogger()
# Set the root logger to be silent so all code that uses the python logger
# will not print anything unless we want it to, then it should be specified
# in each test and reseted after that test
def _set_log_lv(le... | 1,006 | 273 |
from distutils.core import setup
setup(
name='RL-EmsPy',
version='0.0.1',
packages=['emspy'],
url='https://github.com/mechyai/RL-EmsPy',
license='Apache License 2.0',
author='Chris Eubel',
)
| 216 | 86 |
from math import pi, sqrt
from openmdao.core.component import Component
class InletGeom(Component):
'''Calculates the dimensions for the inlet and compressor entrance'''
def __init__(self):
super(InletGeom, self).__init__()
self.add_param('wall_thickness', 0.05, desc='thickness of inlet wall',... | 2,017 | 713 |
#!/usr/bin/env python
#
# DNS gameplay
from scapy.all import *
import sys,os,time
import nfqueue
import socket
from gzacommon import GZA
# time.windows, damballa, damballa, local
WHITELIST_IPS = ["207.46.232.", "172.22.0.", "172.22.10.", "192.168.", "0.0.0.0", "255.255.255.255"]
seen_ips = []
class TCPGZA(GZA):
... | 2,988 | 1,036 |
import os
from cv2 import cv2
for d in os.listdir():
if not d.endswith(".png"): continue
img = cv2.imread(d)
cv2.imwrite(d.replace(".png",".webp"), img)
os.remove(d) | 170 | 73 |
"""Tests for compiler options processing functions."""
load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest")
load("//test:utils.bzl", "stringify_dict")
# buildifier: disable=bzl-visibility
load("//xcodeproj/internal:opts.bzl", "testable")
process_compiler_opts = testable.process_compiler_opts
def _process_... | 16,328 | 5,522 |
"""
NLTK DRT module extended with presuppositions
"""
__author__ = "Alex Kislev, Emma Li, Peter Makarov"
__version__ = "1.0"
__date__ = "Tue, 24 Aug 2010"
import re
import operator
from nltk.sem.logic import Variable
from nltk.sem.logic import EqualityExpression, ApplicationExpression, ExistsExpression, AndExpress... | 58,821 | 16,357 |
from openem.models import ImageModel
from openem.models import Preprocessor
import cv2
import numpy as np
import tensorflow as tf
from collections import namedtuple
import csv
Detection=namedtuple('Detection', ['location',
'confidence',
'species',... | 1,669 | 419 |
import os
import re
filenames = sorted([frame for frame in os.listdir("frames")], key=lambda x: int(re.search(r'\d+', os.path.splitext(x)[0]).group()))
print("creating gif")
import imageio
with imageio.get_writer('storage/pi.gif', mode='I') as writer:
for filename in filenames:
image = imageio.imread(os.p... | 515 | 180 |
import os
import psycopg2
from psycopg2 import extras
import json
import pandas as pd
from dotenv import load_dotenv
def execute_values(conn, df, table):
"""
Using psycopg2.extras.execute_values() to insert the dataframe
"""
# Create a list of tupples from the dataframe values
tuples = [tuple(x) ... | 2,283 | 811 |
# -*- coding: utf-8 -*-
import asyncio
import datetime
import importlib
import io
import json
import logging
import os
import platform
import re
import subprocess
import sys
import textwrap
import traceback
from contextlib import redirect_stderr, redirect_stdout
from functools import partial
from glob i... | 118,682 | 35,862 |
import pytest
grblas = pytest.importorskip("grblas")
from metagraph.tests.util import default_plugin_resolver
from . import RoundTripper
from metagraph.plugins.numpy.types import NumpyMatrixType
from metagraph.plugins.graphblas.types import GrblasMatrixType
import numpy as np
def test_matrix_roundtrip_dense_square(... | 1,573 | 725 |
#!/usr/bin/env python
""" This file is a Python translation of the MATLAB file acm.m
Python version by RDL 29 Mar 2012
Copyright notice from acm.m:
copyright 1996, by M.H. Hayes. For use with the book
"Statistical Digital Signal Processing and Modeling"
(John Wiley & Sons, 1996).
"""
from __future__ import prin... | 1,259 | 487 |
import os
import shutil
import doctest
from crds.core import log, utils
from crds import tests, data_file
from crds.tests import test_config
from crds.refactoring import checksum
from crds.refactoring.checksum import ChecksumScript
def dt_checksum_script_fits_add():
"""
>>> old_state = test_config.setup()
... | 9,153 | 3,284 |
from fsspec import AbstractFileSystem # type: ignore
from fsspec.implementations.local import LocalFileSystem # type: ignore
from typing import Callable, Optional
class Pipe(object):
"""A container for piping data through transformations.
Args:
src_fs (AbstractFileSystem): The source file system.
... | 2,955 | 864 |
import os
from time import sleep
import sys
from sys import platform
import subprocess
import platform
#Main Service Initalizations
#def upcred():
#def multirep():
def clonehistory():
print(">>>>>>>> History >>>>>>>>")
print(" repositories cloned")
print(">>>>>>>>> ----- >>>>>>>>")
... | 2,677 | 822 |
# from os import listdir
# from os.path import isfile, join
#
# from save import xht_files_dir, txt_files_dir_converted
# from utils import convert_xht_to_txt,convert_xht_to_txt_2
# only_files = [f for f in listdir(xht_files_dir) if isfile(join(xht_files_dir, f))]
# for index,file_ in enumerate(only_files):
# pri... | 1,163 | 467 |
"""
Regression tests for custom manager classes.
"""
from django.db import models
class RestrictedManager(models.Manager):
"""
A manager that filters out non-public instances.
"""
def get_query_set(self):
return super(RestrictedManager, self).get_query_set().filter(is_public=True)
class Relat... | 2,757 | 836 |
import serial
import matplotlib.pyplot as plt
import numpy as np
import time
pd = "/dev/tty.wchusbserial1410"
#pd = "/dev/tty.usbmodem1421"
p = serial.Serial(port=pd, baudrate=115200,
bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE)
p.flush()
time.sleep(0.5)
#plt.axis([0, 10, 0, 1])
plt.ion()
s... | 1,685 | 673 |
import unittest
import collections
from typing import List
class Solution:
"""
This solution performs a topological sort using Kahn's algorithm.
First a graph is constructed in the form of a dictionary which contains the
courses, their requirements and the courses that they themselves enable. Then
... | 2,203 | 579 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-09-01 14:28
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('investment_report', '0025_howwecanhelp_smartworkforcesector'),
]
operations = [
mi... | 425 | 155 |
import torch
import torch.nn.functional as f
from torch import nn
from einops import rearrange
def scaled_dot_product_attention(query, key, value):
attention = torch.einsum('bdtc,beuc->bdteu',[query,key])
mask = torch.zeros_like(attention)
for frame in torch.arange(mask.size(-2)):
mask[:, frame, :... | 3,740 | 1,289 |
TOMASULO_DEFAULT_PARAMETERS = {
"num_register": 32,
"num_rob": 128,
"num_cdb": 1,
"cdb_buffer_size": 0,
"nop_latency": 1,
"nop_unit_pipelined": 1,
"integer_adder_latency": 1,
"integer_adder_rs": 5,
"integer_adder_pipelined": 0,
"float_adder_latency": 3,
"float_adder_rs": 3... | 628 | 304 |
# -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-08-24 22:12
from . import rules
def ls_resource_in_module(root) -> dict:
res = dict()
for k, v in root.__dict__.items():
if k.startswith('_') or v == root:
continue
if isinstance(v, str):
if v.startswith('http') and n... | 639 | 225 |
import config
import models
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine, inspect
engine = create_engine(config.DATABASE_URI)
Session = sessionmaker(bind=engine)
class crudOps:
def createTable(self):
models.Base.metadata.create_all(engine)
def recreate_database(self):... | 1,174 | 362 |
"""
License: Apache-2.0
Author: Aite Zhao
E-mail: aitezhao@qq.com
"""
import tensorflow as tf
import rnn_cell_GRU as rnn_cell
import rnn
import numpy as np
from config import cfg
from utils import get_batch_data
from capsLayer import CapsLayer
from sklearn import metrics
import pickle
from sklearn.cross_validation i... | 14,270 | 5,265 |
# 设置类
class Settings():
'''保存设置信息'''
def __init__(self):
'''初始化游戏的静态设置'''
self.screen_width = 850
self.screen_heght = 600
self.bg_color = (230, 230, 230)
# 玩家飞船数量设置
self.ship_limit = 3
# 子弹设置
self.bullet_width = 3
self.bullet_... | 1,001 | 444 |
# Based on code shamelessly stolen from https://picamera.readthedocs.io/en/latest/recipes2.html#web-streaming
import io
import picamera
import logging
import socketserver
import configparser
import json
from threading import Condition
from http import server
from string import Template
from gpiozero import LED
PAGE="... | 11,564 | 3,670 |
import sys
import pandas as pd
import requests
import pprint
from requests_toolbelt.threaded import pool
# Generate your own at https://www.last.fm/api/account/create
LASTFM_API_KEY = None
LASTFM_USER_NAME = None
TEXT = "#text"
ESTIMATED_TIME_FOR_PROCESSING_PAGE = 352
ESTIMATED_TIME_FOR_PROCESSING_DATAFRAME_PER_PAGE_... | 3,811 | 1,268 |
import numpy as np
from modeler.fasttextmodel import FastTextModel
from trainer.tftrainer import TFTrainer
class FastTextTrainer(TFTrainer):
def __init__(self):
self.num_classes = 19
self.learning_rate = 0.01
self.batch_size = 8
self.decay_steps = 1000
self.decay_rate = 0.... | 1,652 | 582 |
# encoding: utf-8
# module Autodesk.Revit.DB.Structure calls itself Structure
# from RevitAPI,Version=17.0.0.0,Culture=neutral,PublicKeyToken=null
# by generator 1.145
# no doc
# no imports
# no functions
# classes
from __init___parts.AnalyticalAlignmentMethod import AnalyticalAlignmentMethod
from __init___p... | 13,358 | 3,758 |
from .pedal import BasePedal
from enum import IntEnum
class BoosterType(IntEnum):
DEFAULT = 10
MID_BOOST = 0
CLEAN_BOOST = 1
TREBLE_BOOST = 2
CRUNCH = 3
NATURAL_OD = 4
WARM_OD = 5
FAT_DS = 6
LEAD_DS = 7
METAL_DS = 8
OCT_FUZZ = 9
BLUES_OD = 10
OD_1 = 11
TUBESCREAM... | 1,700 | 632 |
import numpy as np
import cv2
img = cv2.imread("test_image.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
camera = cv2.VideoCaptu... | 867 | 428 |
import os
import sys
import torch
from torch import nn
from torch.nn import functional as F, init
from src.utils import bernoulli_log_pdf
from src.objectives.elbo import \
log_bernoulli_marginal_estimate_sets
class Statistician(nn.Module):
def __init__(self, c_dim, z_dim, hidden_dim_statistic=3, hidden_dim=40... | 9,159 | 3,479 |
from django.core.paginator import Paginator
from django.shortcuts import render, get_object_or_404, redirect
from .models import Post, Groups
from django.contrib.auth import get_user_model, get_user
from .forms import NewPost
from django.contrib.auth.decorators import login_required
# Create your views here.
def fi... | 3,795 | 1,287 |
# NLP written by GAMS Convert at 04/21/18 13:54:04
#
# Equation counts
# Total E G L N X C B
# 1603 1603 0 0 0 0 0 0
#
# Variable counts
# x b i s1s s2s sc ... | 291,404 | 190,712 |
#!/usr/bin/env python
"""
docstring
"""
# Authors: Henrik Linusson
import abc
import numpy as np
from sklearn.base import BaseEstimator
class RegressorMixin(object):
def __init__(self):
super(RegressorMixin, self).__init__()
@classmethod
def get_problem_type(cls):
return 'regression'
class ClassifierMix... | 3,379 | 1,306 |
from corehq.project_limits.rate_limiter import RateDefinition, RateLimiter, \
PerUserRateDefinition
from corehq.util.datadog.gauges import datadog_counter
from corehq.util.datadog.utils import bucket_value
from corehq.util.decorators import silence_and_report_error, enterprise_skip
from corehq.util.timer import Ti... | 1,890 | 650 |
from django.shortcuts import render, redirect
from django.views.generic import UpdateView, DeleteView
from .models import Storage
from django_tables2 import RequestConfig
from .tables import StorageTable
from django.contrib.auth.decorators import login_required
from .forms import StorageForm, QuestionForm
def index(r... | 2,263 | 642 |
from django.apps import apps
from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.dispatch import receiver, Signal
from rest_framework_security.deny_repeat_password import config
from rest_framework_security.deny_repeat_password.emails import ChangedPasswordEmail
fr... | 1,282 | 361 |