text string | size int64 | token_count int64 |
|---|---|---|
import discord
import random
from discord.ext import commands
class Meme:
"""
Meme commands.
"""
def __init__(self, bot):
self.bot = bot
print('Addon "{}" loaded'.format(self.__class__.__name__))
@commands.command(pass_context=True, hidden=True, name="bam")
async def bam_memb... | 972 | 357 |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... | 3,180 | 987 |
import os
import glob
from catsndogs.data import get_training_data
folder = get_training_data()
cats = glob.glob(os.path.join(get_training_data(), "cat", "*.jpg"))
dogs = glob.glob(os.path.join(get_training_data(), "dog", "*.jpg"))
| 232 | 84 |
# -*- coding: utf-8 -*-
# ========================================
# Author: wjh
# Date:2021/1/19
# FILE: ir_module
# ========================================
from odoo import api, fields, models, _
from odoo.exceptions import UserError
ACTION_DICT = {
'view_type': 'form',
'view_mode': 'form',
... | 1,893 | 597 |
import logging
from cinp import client
MCP_API_VERSIONS = ( '0.10', '0.11', )
class MCP( object ):
def __init__( self, host, proxy, job_id, instance_id, cookie, stop_event ):
self.cinp = client.CInP( host, '/api/v1/', proxy, retry_event=stop_event )
self.job_id = job_id
self.instance_id = instance_id
... | 4,978 | 1,707 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from sklearn.metrics import r2_score
import datetime
def func(x, a, b):
return a + b*x
def exp_regression(x, y):
p, _ = curve_fit(func, x, np.log(y))
p[0] = np.exp(p[0])
return p
def r2(coe... | 803 | 315 |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Flatten(nn.Module):
def __init__(self, dim_start=-3):
super().__init__()
self.dim_start = dim_start
def forward(self, x):
return x.view(x.shape[:self.dim_start] + (-1,))
class View(nn.Module):
def __init__(se... | 1,546 | 574 |
"""Tests for IPython.utils.path.py"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from contextlib import contextmanager
from unittest.mock import patch
import pytest
from IPython.lib import latextools
from IPython.testing.decorators import (
onlyif_cmds_ex... | 5,738 | 2,044 |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^search/$', views.ip_search, name='crits-ips-views-ip_search'),
url(r'^search/(?P<ip_str>\S+)/$', views.ip_search, name='crits-ips-views-ip_search'),
url(r'^details/(?P<ip>\S+)/$', views.ip_detail, name='crits-ips-views-ip_detail')... | 736 | 309 |
"""
pennies.py
Computer Science 50 in Python (Hacker Edition)
Problem Set 1
Get num of days in month then works out how many $$ you'd have by end of the month
if you received a penny on the first day, two on second, four on third and so on
"""
def get_input(question):
"""Get the days input from the user """
... | 2,869 | 884 |
#!/usr/bin/python3
#
# This is a Hello World example of BPF.
from bcc import BPF
# define BPF program
prog = """
int kprobe__sys_clone(void *ctx)
{
bpf_trace_printk("Hello, World!\\n");
return 0;
}
"""
# load BPF program
b = BPF(text=prog)
b.trace_print()
| 266 | 109 |
from django.contrib import admin
from accounts.models import *
admin.site.register(UserProfile)
admin.site.register(ProjectPage)
admin.site.register(Comment)
| 159 | 45 |
"""
Created By: Alex J. Gatz
Date: 06/07/2018
This is some code playing with the usage of a python
"Generator" which is really very cool. Another use case
I want to play with is properly ordering installation of
packages to ensure that if there are dependencies that they are installed in the proper order.
Created a... | 697 | 225 |
from enum import IntFlag as _IntFlag
from . import _inotify
__all__ = ('Mask',)
class Mask(_IntFlag):
show_help: bool
def __new__(cls, value, doc=None, show_help=True):
# int.__new__ needs a stub in the typeshed
# https://github.com/python/typeshed/issues/2686
#
# but that ... | 2,753 | 997 |
################################################
# --- Day 24: Immune System Simulator 20XX --- #
################################################
import AOCUtils
def getTargets(atkArmy, defArmy):
targeted = set()
for atkGroup in atkArmy:
if len(targeted) < len(defArmy):
dmgGiven = []
... | 4,991 | 1,700 |
from io import BytesIO
import requests
from celery import Celery
from api import send_message, send_photo
from imdb2_api import get_movie_by_imdb_id
from imdb_api import IMDBAPIClient
# celery -A tasks worker --log-level INFO
app = Celery(
"tasks", backend="redis://localhost:6379/0", broker="redis://localhost:63... | 2,552 | 913 |
import imaplib
import email
from email import message
import time
username = 'gmail_id'
password = 'gmail_password'
new_message = email.message.Message()
new_message.set_unixfrom('satheesh')
new_message['Subject'] = 'Sample Message'
# from gmail id
new_message['From'] = 'eppalapellisatheesh1@gmail.com'
# to gmail id... | 1,279 | 407 |
from copy import deepcopy
from typing import Dict
from autoflow.workflow.components.classification_base import AutoFlowClassificationAlgorithm
__all__=["LinearDiscriminantAnalysis"]
class LinearDiscriminantAnalysis(AutoFlowClassificationAlgorithm):
class__ = "LinearDiscriminantAnalysis"
module__ = "sklearn.d... | 361 | 109 |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright (c) 2011-2019, wradlib developers.
# Distributed under the MIT License. See LICENSE.txt for more info.
"""
Miscellaneous
^^^^^^^^^^^^^
.. autosummary::
:nosignatures:
:toctree: generated/
bin_altitude
bin_distance
site_distance
"""
import numpy... | 4,362 | 1,412 |
# Copyright 2019-2020 Abien Fred Agarap
#
# 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 i... | 1,860 | 579 |
import numpy as np
import tensorflow as tf
from tensorflow import keras
from keras.applications.xception import Xception
import h5py
import json
import cv2
import math
import logging
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.xception import preprocess_input, decode_pr... | 1,985 | 748 |
import os
import pytest
import fakeredis
from db_transfer.adapter_redis import Redis
from db_transfer.transfer import Transfer, sent_env
@pytest.fixture()
def fake_redis(monkeypatch):
fake_redis = lambda *args, **kwargs: fakeredis.FakeStrictRedis(decode_responses=True)
monkeypatch.setattr(Redis, 'connect', f... | 3,773 | 1,457 |
___assertIs(isinstance(True, bool), True)
___assertIs(isinstance(False, bool), True)
___assertIs(isinstance(True, int), True)
___assertIs(isinstance(False, int), True)
___assertIs(isinstance(1, bool), False)
___assertIs(isinstance(0, bool), False)
| 248 | 86 |
from pydantic.types import Json
import json
from sqlalchemy.orm import Session
from sqlalchemy import desc
from . import models, schemas
def get_questions(db: Session, skip: int = 0, limit: int = 100):
return db.query(models.Question).offset(skip).all()
def get_top_questions(db: Session, limit: int = 5):
re... | 2,051 | 685 |
from django.contrib.auth.models import User
from django.core import serializers
from django.core.exceptions import ObjectDoesNotExist
from django.db import DataError
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view
fr... | 3,044 | 891 |
from telethon import TelegramClient
from telethon.events import NewMessage, CallbackQuery, MessageEdited
from telethon.events import StopPropagation
from telethon.tl import types, functions
from telethon.tl.custom import Button
from telethon.errors.rpcerrorlist import ChannelPrivateError
import os
import re
import shl... | 11,295 | 3,550 |
# from django.db.models.signals import post_save
# from django.dispatch import receiver
# from onadata.apps.logger.models import XForm
#
# from onadata.apps.fsforms.models import FieldSightXF
#
#
# @receiver(post_save, sender=XForm)
# def save_to_fieldsight_form(sender, instance, **kwargs):
# FieldSightXF.objects.c... | 339 | 113 |
# -*- coding: utf-8 -*-
#
# Copyright 2013 - Mirantis, Inc.
#
# 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 requir... | 2,383 | 732 |
import json
import requests
import os
import subprocess
import platform
HTTP = requests.session()
class ClientException(Exception):
message = 'unhandled error'
def __init__(self, message=None):
if message is not None:
self.message = message
def getURL(address):
url = "https://api.e... | 3,030 | 936 |
from collections import namedtuple
import os
from six.moves import configparser
DEFAULT_CONFIG = {
('jenkins', 'host', 'jenkins.ovirt.org'),
('gerrit', 'host', 'gerrit.ovirt.org')}
Jenkins = namedtuple('jenkins', 'host, user_id, api_token')
Gerrit = namedtuple('gerrit', 'host')
Config = namedtuple('config', '... | 1,193 | 382 |
import os
from datetime import timedelta
UPLOAD_FOLDER = ''
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
MAX_CONTENT_LENGTH = 16 * 1024 * 1024
class Config:
ROOT_PATH = os.path.abspath('.')
LOG_PATH = ROOT_PATH + '/logs'
APP_LOG_FILE = ROOT_PATH + '/logs/admin.log'
SECRET... | 2,148 | 1,031 |
import unittest
from mock import Mock
from foundations_spec import *
from foundations_aws.aws_bucket import AWSBucket
class TestAWSBucket(Spec):
class MockListing(object):
def __init__(self, bucket, files):
self._bucket = bucket
self._files = files
def __call__(self, B... | 8,087 | 2,547 |
"""
Support for an interface to work with a remote instance of Home Assistant.
If a connection error occurs while communicating with the API a
HomeAssistantError will be raised.
For more details about the Python API, please refer to the documentation at
https://home-assistant.io/developers/python_api/
"""
import date... | 11,948 | 3,703 |
# Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... | 4,305 | 1,972 |
from molecules.dna_molecule import DNAMolecule
from molecules.dna_sequence import DNASequence
class GelElectrophoresis:
"""
Produce the Gel Electrophoresis procedure to sort DNA molecules by their size.
"""
@staticmethod
def run_gel(dna_molecules):
"""
Runs the Gel Electrophoresis... | 1,413 | 495 |
# -*- coding: utf-8 -*-
"""Top-level package for stocks."""
__author__ = """Jianye Xu"""
__email__ = 'jianye.xu.stats@gmail.com'
__version__ = '0.1.0'
| 153 | 72 |
from itertools import product
from pyutils import *
def parse(lines):
return [ints(line) for line in lines]
def neighbors(r, c, d):
return ((r+dr, c+dc) for dr in [-1, 0, 1] for dc in [-1, 0, 1] if (dc != 0 or dr != 0) and 0 <= r+dr < d and 0 <= c+dc < d)
def update_and_store(grid, r, c, sto... | 1,147 | 477 |
from edl.expressions import *
def test_accession_re():
with open('test/data/sample.1.blastx.b50.m8') as F:
try:
for line in F:
acc = accessionRE.search(line).group(1)
except AttributeError:
# There should have been a match in every line of this file
... | 1,462 | 579 |
# @lc app=leetcode id=230 lang=python3
#
# [230] Kth Smallest Element in a BST
#
# https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/
#
# algorithms
# Medium (63.45%)
# Likes: 4133
# Dislikes: 90
# Total Accepted: 558.7K
# Total Submissions: 876.8K
# Testcase Example: '[3,1,4,null,2]\n1'
#
... | 2,969 | 1,285 |
"""
Replace With Alphabet Position
Welcome.
In this kata you are required to, given a string, replace every letter with its position in the alphabet.
If anything in the text isn't a letter, ignore it and don't return it.
"a" = 1, "b" = 2, etc.
Example
alphabet_position("The sunset sets at twelve o' clock.")
Should... | 592 | 243 |
import time
import os
from pykafka.test.kafka_instance import KafkaInstance, KafkaConnection
def get_cluster():
"""Gets a Kafka cluster for testing, using one already running is possible.
An already-running cluster is determined by environment variables:
BROKERS, ZOOKEEPER, KAFKA_BIN. This is used prim... | 1,463 | 442 |
# Copyright (c) 2015 VMware. All rights reserved
import prettytable
import six
import sys
from oslo_utils import encodeutils
def _print(pt, order):
if sys.version_info >= (3, 0):
print(pt.get_string(sortby=order))
else:
print(encodeutils.safe_encode(pt.get_string(sortby=order)))
def print_... | 2,107 | 631 |
# python test.py 500 /workspace/images/test.png 7000
import sys
import time
import requests
args = sys.argv[1:]
command = " ".join(args)
times = int(args[0])
data = {"image": [args[1]] * 2}
url = f"http://localhost:{args[2]}/predict"
headers = {"content-type": "application/x-www-form-urlencoded"}
oks = 0
start_ti... | 707 | 265 |
from typing import List
from pydantic import BaseSettings
class ApiConfig(BaseSettings):
title: str = "AITA"
version: str = "/api/v1"
openapi: str = "/api/v1/openapi.json"
class PostgresConfig(BaseSettings):
user: str
password: str
host: str
db: str
class Config:
env_prefix... | 1,048 | 354 |
import base64
from scapy.layers.inet import *
from scapy.layers.dns import *
import dissector
class SIPStartField(StrField):
"""
field class for handling sip start field
@attention: it inherets StrField from Scapy library
"""
holds_packets = 1
name = "SIPStartField"
def getfield(self, pk... | 11,756 | 3,310 |
from starfish.pipeline import import_all_submodules
from ._base import Segmentation
import_all_submodules(__file__, __package__)
| 129 | 39 |
from collections import namedtuple
import numpy as np
import scipy as sp
from scipy.sparse.csgraph import minimum_spanning_tree
from .. import logging as logg
from ..neighbors import Neighbors
from .. import utils
from .. import settings
def paga(
adata,
groups='louvain',
use_rna_velocity=Fals... | 19,335 | 5,957 |
# Generated by Django 2.1.7 on 2019-08-07 19:45
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('nfl_package', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='nflplayersummary',
old_name='player',
... | 650 | 210 |
#!/usr/bin/env python3
import os
import pytest
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../lib"))
import dartsense.player
player_list = None
def test_player_list_init(setup_db):
player_list = dartsense.player.PlayerList()
assert isinstance(player_list, dartsense.player.Player... | 982 | 341 |
from models.contact import Contacts
import random
def test_edit_some_contact(app, db, check_ui):
if len(db.get_contact_list()) == 0:
app.contacts.create_contact(Contacts(lastname="LastNameUser", firstname="User Modify"))
old_contacts = db.get_contact_list()
randomcontact = random.choice(old_contact... | 937 | 316 |
"""
This demo will fill the screen with white, draw a black box on top
and then print Hello World! in the center of the display
This example is for use on (Linux) computers that are using CPython with
Adafruit Blinka to support CircuitPython libraries. CircuitPython does
not support PIL/pillow (python imaging library)... | 1,875 | 668 |
# Nested package modules
from . import Atest
__packageAname__ = 'packageA' | 75 | 24 |
from freezegun import freeze_time
from rest_framework import test
from rest_framework.exceptions import ValidationError
from waldur_core.core.tests.helpers import override_waldur_core_settings
from waldur_core.media.utils import decode_attachment_token, encode_attachment_token
from waldur_core.structure.tests.factorie... | 1,205 | 377 |
from pygame import mixer
import speech_recognition as sr
import pyttsx3
import pyjokes
import boto3
import pyglet
import winsound
import datetime
import pywhatkit
import datetime
import time
import os
from PIL import Image
import random
import wikipedia
import smtplib, ssl
from mutagen.mp3 import MP3
import requests, ... | 19,620 | 6,043 |
"""Test fixture files, using the ``DocutilsRenderer``.
Note, the output AST is before any transforms are applied.
"""
import shlex
from io import StringIO
from pathlib import Path
import pytest
from docutils.core import Publisher, publish_doctree
from myst_parser.parsers.docutils_ import Parser
FIXTURE_PATH = Path(... | 2,993 | 954 |
import os
import json
from .base import CommunityBaseSettings
class EnvironmentSettings(CommunityBaseSettings):
"""Settings for local development"""
DEBUG = os.environ.get('DEBUG') == 'true'
ALLOW_PRIVATE_REPOS = os.environ['ALLOW_PRIVATE_REPOS'] == 'true'
PRODUCTION_DOMAIN = os.environ['PROD_HOST'... | 6,095 | 1,972 |
from unittest import TestCase
from logger import get_logger
from config import get_config
from .runner import JobsRunner
logger = get_logger(__name__, log_level=("TEST", "LOGLEVEL"))
config = get_config()
def test_run(self, config, job_config, date):
print("Running test job")
class JobRunnerTests(TestCase):
... | 583 | 195 |
import weka.core.jvm as jvm
jvm.start()
from weka.core.converters import Loader, Saver
loader = Loader(classname="weka.core.converters.ArffLoader")
data = loader.load_file("./Listas/train.arff")
print data
jvm.stop() | 220 | 87 |
# Copyright (c) 2013 Huan Do, http://huan.do
class Declaration(object):
def __init__(self, name):
self.name = name
self.delete = False
self._conditional = None
@property
def conditional(self):
assert self._conditional is not None
return self.delete or self._conditio... | 463 | 140 |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import torch.nn as nn
def r2plus1_unit(
dim_in,
dim_out,
temporal_stride,
... | 2,567 | 872 |
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
class CamaraWindow(BoxLayout):
def __init__(self, **kwargs):
super().__init__(**kwargs)
class CamaraApp(App):
def build(self):
return CamaraWindow()
if __name__ == '__main__':
CamaraApp().run() | 312 | 110 |
import unittest
from datetime import datetime, timezone
from src.entity.count_entity import CountEntity
from src.interface_adapter.in_memory_count_repository import \
InMemoryCountRepository
from src.use_case.record_count_input_data import RecordCountInputData
from src.use_case.record_count_use_case_interactor imp... | 1,685 | 520 |
all = ['GeneratorLoss',
'ClassfierLoss']
from generator import GeneratorLoss
from classfier import ClassfierLoss
| 120 | 37 |
line = '-' * 30
print(line)
print('{:^30}'.format('LOJA SUPER BARATÃO'))
print(line)
total = more1000 = 0
productMaisBarato = ''
priceMaisBarato = 0
primeiraVez = True
while True:
name = str(input('Nome do produto: '))
price = float(input('Preço: R$'))
moreProducts = ' '
while moreProducts not in 'SN':
... | 972 | 362 |
from setuptools import setup
setup(
name='nd',
py_modules=['nd'],
version='1.0.0',
description='user friendly emulation game selection',
license="MIT",
author='Mark Hellmer',
author_email='mchellmer@gmail.com',
install_requires=['tkinter', 'nltk', 'pymongo'],
scripts=[]
)
| 310 | 106 |
"""add class of delete
Revision ID: f83defd9c5ed
Revises: 1060ee5817c7
Create Date: 2019-03-04 17:50:54.573744
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f83defd9c5ed'
down_revision = '1060ee5817c7'
branch_labels = None
depends_on = None
def upgrade():
... | 703 | 274 |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 5 01:34:00 2021
@author: yrc2
"""
import biosteam as bst
import biorefineries.oilcane as oc
from biosteam.utils import CABBI_colors, colors
from thermosteam.utils import set_figure_size, set_font, roundsigfigs
from thermosteam.units_of_measure import format_units
from co... | 57,497 | 21,995 |
DOMAIN = "yoosee"
PLATFORMS = ["camera"]
DEFAULT_NAME = "Yoosee摄像头"
VERSION = "1.1"
SERVICE_PTZ = 'ptz' | 103 | 53 |
"""
TODO description.
Author: Spencer M. Richards
Autonomous Systems Lab (ASL), Stanford
(GitHub: spenrich)
"""
if __name__ == "__main__":
import pickle
import jax
import jax.numpy as jnp
from jax.experimental.ode import odeint
from utils import spline, random_ragged_spline
fro... | 4,729 | 1,908 |
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from django.http.response import JsonResponse
import base64
from numpy import random
# Create your views here.
@csrf_exempt
def algo(req):
if req.method == "POST":
data = J... | 674 | 206 |
from typing import NamedTuple
# scVI Manager Store Constants
# ----------------------------
# Keys for UUIDs used for referencing model class manager stores.
_SCVI_UUID_KEY = "_scvi_uuid"
_SOURCE_SCVI_UUID_KEY = "_source_scvi_uuid"
# scVI Registry Constants
# -----------------------
# Keys used in the scVI registry.... | 1,024 | 396 |
from hummingbot.client.config.config_var import ConfigVar
from hummingbot.client.config.config_methods import using_exchange
CENTRALIZED = True
EXAMPLE_PAIR = "BTC-USD"
DEFAULT_FEES = [0.05, 0.2]
KEYS = {
"dydx_perpetual_api_key":
ConfigVar(key="dydx_perpetual_api_key",
prompt="Ent... | 1,994 | 637 |
# Generated by Django 3.1.12 on 2021-07-28 21:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('reports', '0016_auto_20210727_2156'),
]
operations = [
migrations.AddIndex(
model_name='report',
index=models.Index... | 546 | 187 |
from django.apps import AppConfig
class MfsapiappConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'mfsapiapp'
| 150 | 53 |
#--------------------------------------------------
# mqtt_control.py
# MQTT_Control is a database model to control subscriptions
# and publications
# introduced in u8
# ToraNova
#--------------------------------------------------
from pkg.resrc import res_import as r
from pkg.system.database import dbms
Base = dbms.m... | 5,633 | 1,712 |
# SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
#
# SPDX-License-Identifier: MIT
import usb_cdc
import rotaryio
import board
import digitalio
serial = usb_cdc.data
encoder = rotaryio.IncrementalEncoder(board.ROTA, board.ROTB)
button = digitalio.DigitalInOut(board.SWITCH)
button.switch_... | 799 | 268 |
import fiona
import rasterio
import rasterio.plot
import matplotlib as mpl
import matplotlib.pyplot
from descartes import PolygonPatch
from shapely.geometry import LineString
import numpy as np
import sys
from multiprocessing import Pool
np.set_printoptions(threshold=np.inf)
import matplotlib.pyplot as plt
import matpl... | 2,753 | 1,065 |
import numpy as np
from ..layers.Layer import LayerTrainable
class LayeredModel(object):
def __init__(self, layers):
"""
layers : a list of layers. Treated as a feed-forward model
"""
assert len(layers) > 0, "Model layers must be non-empty"
# check that the output of ... | 5,895 | 1,857 |
#!/usr/bin/env python3
from flask import Flask, send_file, make_response, Response, g, request, stream_with_context
from io import BytesIO
import atexit
import errno
import os
import subprocess
import threading
INPUT = '/dev/video0'
FFMPEG = "/home/test/ffmpeg-nvenc/ffmpeg"
app = Flask(__name__)
@app.route('/pic')
... | 6,269 | 1,950 |
from unittest import TestCase
from eccCh02 import Point
class PointTest(TestCase):
def test_ne(self):
a = Point(x=3, y=-7, a=5, b=7)
b = Point(x=18, y=77, a=5, b=7)
self.assertTrue(a != b)
self.assertFalse(a != a)
| 252 | 103 |
from DefinesX import x
print(x)
| 33 | 14 |
import Adafruit_DHT
humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, 17)
if humidity is not None and temperature is not None:
print(str(temperature) + "," + str(humidity))
else:
print('-1,-1') | 220 | 89 |
import torch.nn as nn
from torch import Tensor
from typing import Optional
from .lovasz_loss import CustomizeLovaszLoss, LovaszLoss
from .binary_cross_entropy import (
MaskBinaryCrossEntropyIgnoreIndex,
MaskBinaryCrossEntropy,
)
from .dice_loss import CustomizeDiceLoss
from .jaccard import CustomiseJaccardLoss
... | 3,067 | 1,109 |
from .about_embed import AboutEmbed
from .event_embed import EventEmbed
from .help_embed import HelpEmbed
from .select_channel_embed import SelectChannelEmbed
from .start_time_embed import StartTimeEmbed
from .time_zone_embed import TimeZoneEmbed
| 247 | 70 |
#%%
import numpy as np
from sapai.data import data
from sapai.rand import MockRandomState
#%%
class Food():
def __init__(self,
name="food-none",
shop=None,
team=[],
seed_state = None):
"""
Food class definition the types of ... | 4,180 | 1,200 |
from pygit2 import Commit
from git_lint_branch.linter_output import *
from git_lint_branch.single.example_linter import *
from git_lint_branch.single.regex_linter import *
from git_lint_branch.single.diff_size_linter import diff_size_linter
from git_lint_branch.single.tense_linter import *
from git_lint_branch.single.b... | 459 | 158 |
"""
pyNonin package initalization file
(c) Charles Fracchia 2013
charlesfracchia@gmail.com
Permission granted for experimental and personal use;
license for commercial sale available from the author.
"""
#Import main Device base class
from pynonin.packet import Packet
| 271 | 78 |
# Require: input_dim, z_dim, hidden_dim, lag
# Input: {f_i}_i=1^T: [BS, len=T, dim=8]
# Output: {z_i}_i=1^T: [BS, len=T, dim=8]
# Bidirectional GRU/LSTM (1 layer)
# Sequential sampling & reparameterization
import pyro
import torch
import ipdb as pdb
import numpy as np
import torch.nn as nn
import torch.nn.init as init... | 6,004 | 2,004 |
#!/usr/bin/env python
import numpy as np
from kalman_helpers import ObservationKind
from ekf_sym import EKF_sym
from laika.raw_gnss import GNSSMeasurement
def parse_prr(m):
sat_pos_vel_i = np.concatenate((m[GNSSMeasurement.SAT_POS],
m[GNSSMeasurement.SAT_VEL]))
R_i = np.atleast_2... | 4,103 | 1,804 |
# -*- coding: utf-8 -*- #
# Copyright 2021 Google LLC. All Rights Reserved.
#
# 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 requir... | 3,728 | 1,103 |
"""
3.Question 3
In this programming problem you'll code up Prim's minimum spanning tree algorithm.
This file (edges.txt) describes an undirected graph with integer edge costs. It has the format
[number_of_nodes] [number_of_edges]
[one_node_of_edge_1] [other_node_of_edge_1] [edge_1_cost]
[one_node_of_edge... | 3,107 | 1,061 |
from time import sleep
from selenium.common.exceptions import NoSuchElementException
from .vulcan_webdriver import VulcanWebdriver
class VulcanAgent:
""" Class to perform actions on Vulcan Uonet page """
def __init__(self, credentials: dict, vulcan_data = None):
self.driver = VulcanWebdriver()
... | 2,108 | 610 |
import sys
def progress_bar(it, prefix="", suffix="", width=60, file=sys.stdout):
"""An iterable-like obj for command line progress_bar
Usage:
for i in progress_bar(range(15), "Processing: ", "Part ", 40):
<some long running calculation>
Processing: [####################################] Pa... | 695 | 240 |
#!/usr/bin/env python3
import turtle
t = turtle.Pen()
for x in range(400):
t.forward(x)
t.left(90)
input("press enter to exit")
| 136 | 60 |
# (C) Datadog, Inc. 2018-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import os
from datadog_checks.utils.common import get_docker_hostname
HERE = os.path.dirname(os.path.abspath(__file__))
# Networking
HOST = get_docker_hostname()
GITLAB_TEST_PASSWORD = "testroot"
GITL... | 1,655 | 614 |
# -------------------------------------------------------------------------------------
# Library
import tempfile
import rasterio
import numpy as np
from os import remove
from os.path import join, exists
from scipy.interpolate import griddata
from src.hyde.algorithm.utils.satellite.hsaf.lib_ascat_generic import rando... | 8,248 | 2,567 |
class Solution(object):
def XXX(self, s, numRows):
if numRows==1:
return s
res = ['' for _ in range(numRows)]
# 周期
T = numRows + numRows -2
for i in range(len(s)):
t_num = i%T
temp = t_num if t_num<numRows else numRows-(t_num)%numRows-2
... | 378 | 132 |
description = 'Verify the user can add an action to the teardown'
pages = ['common',
'index',
'tests',
'test_builder']
def setup(data):
common.access_golem(data.env.url, data.env.admin)
index.create_access_project('test')
common.navigate_menu('Tests')
tests.create_access_ra... | 515 | 170 |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 23 19:43:56 2019
@author: MiaoLi
"""
#%%
import sys, os
import pandas as pd
# import seaborn as sns
# from shapely.geometry import Polygon, Point
sys.path.append('C:\\Users\\MiaoLi\\Desktop\\SCALab\\Programming\\crowdingnumerositygit\\GenerationAlgorithm\\VirtualEllipseF... | 9,829 | 5,009 |
import scrapy
from urllib.parse import urljoin
from text_formatting import format_mileage, format_year, format_price
class GumtreeSpider(scrapy.Spider):
name = 'gumtree'
base_url = 'https://www.gumtree.co.za/'
start_urls = [
urljoin(base_url, 's-cars-bakkies/v1c9077p1'),
]
def parse(self, r... | 1,366 | 381 |