content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the 'License'). All use of this software is governed by the License,
# or, if provided, by the license below or th... | python |
from src.targets import *
from src.states import GameLevelState
from src.spawner import Spawner
def create_level_two(game):
spawners = list()
spawners.append(Spawner(spawn_type=Strawberry, ammunition=3, initial_delay=3.0, cooldown=2.0,
min_velocity=(160., -10.), max_velocity=(200.,... | python |
import time
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivymd.app import MDApp
from kivymd.uix.button import MDRectangleFlatButton, MDRoundFlatIconButton, MDTextButton
from kivymd.uix.label import MDLabel, MDIcon
from kivymd.uix.screen import MDScreen
from kivy.app import App
Builder.l... | python |
import logging
l = logging.getLogger("archinfo.arch_mips64")
try:
import capstone as _capstone
except ImportError:
_capstone = None
try:
import keystone as _keystone
except ImportError:
_keystone = None
try:
import unicorn as _unicorn
except ImportError:
_unicorn = None
from .arch import Ar... | python |
# Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | python |
class Solution:
def trap(self, height: [int]) -> int:
n = len(height)
l = [0]*(n+1)
r = [0]*(n+1)
for i in range(n):
l[i+1] = max(l[i], height[i])
for i in range(n-2, -1, -1):
r[i] = max(r[i+1], height[i+1])
print(l, r)
ans = 0
... | python |
#source, from django-tracking
from django.conf import settings
import re
# threadlocals middleware for global usage
# if this is used elsewhere in your system, consider using that instead of this.
try:
from threading import local
except ImportError:
from django.utils._threading_local import local
_thread_l... | python |
#Import Flask, dependencies, sessions, basics like from titanic example
import numpy as numpy
import os
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
#Setup database
engine = create_eng... | python |
from mutation_variants.helpers import *
def fair_rank( x ):
#ranks = []
ix = np.argsort(x)
sx = x[ix]
rnk = 0
old_x = sx[0]
ranks = [rnk]
cnter = 1
for xi in sx[1:]:
if xi > old_x:
rnk += 1 #cnter
cnter = 1
else:
cnter += 1
old_x = xi
ranks.append(rnk)
ranks = np.arr... | python |
from .lfads import LFADS
from .tndm import TNDM
| python |
import collections
import sys
def anagram(string1, string2):
if not len(string1)==len(string2):
return False
def create_counter(from_string):
counter = collections.Counter()
for symbol in from_string:
counter[symbol] +=1
return counter
counter1 = create_counter(s... | python |
#start menu of Game of Life
import pygame, sys, time, random
sys.path.append('../widgets')
from pygame.locals import *
from pygame import gfxdraw
from ListView import ListView
from Button import Button
from InputBox import InputBox
from Grid import Grid
FPS = 5
WINDOWWIDTH = 640
WINDOWHEIGHT = 480
CELLSIZE = 20
asse... | python |
''' image '''
import cv2
import numpy as np
def parse_image(f: bytes):
''' parse image '''
nparr = np.frombuffer(f, np.uint8)
return cv2.imdecode(nparr, cv2.IMREAD_COLOR)
def load_image(path: str):
''' load image '''
return cv2.imread(path)
def a_hash(img) -> int:
''' 均值... | python |
from .tADT_h import TADT_h
from .tClass1_h import TClass1_h
from .tADT_c import TADT_c
from .tMemoryPool_ADT_c import TMemoryPool_ADT_c
| python |
from django.db import models
# This model refers to contact us page in the site
class CoachingContact(models.Model):
username = models.CharField(max_length=100, unique=True, blank=False, default='')
address = models.CharField(max_length=500, default='')
city = models.CharField(max_length=500, default='')
... | python |
x = float(input("Enter your first number: "))
y = float(input("Enter your second number: "))
print("The sum of ",x," and ",y, "is equal to ",x+y) | python |
# Copyright 2016 ClusterHQ Inc. See LICENSE file for details.
from zope.interface import implementer
from twisted.internet.defer import succeed
from twisted.internet.task import Clock
from flocker.testtools import TestCase
from benchmark._interfaces import IRequest
from benchmark.scenarios._request_load import Req... | python |
# Generated by Django 2.2.7 on 2019-11-16 17:58
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('resource_data', '0004_auto_20191116_2233'),
]
operations = [
migrations.AlterModelOptions(
name='course',
options={'ordering... | python |
#!/usr/bin/env python3
import coiled
coiled.create_software_environment(
name="coiled-science-thursdays-itk",
conda="environment.yml",
)
| python |
import sys
import json
import asyncio
import websockets
URI = 'ws://harmony-1.hackable.software:3380/chat'
async def register(ws, name: str) -> str:
await ws.send(json.dumps({'type': 'register', 'displayName': name}))
uid_msg = await ws.recv()
parsed_msg = json.loads(uid_msg)
if not 'uid' in pars... | python |
#!/usr/bin/env python3
# Picross Puzzle Solver (CLI version)
#
# Author: Ibb Marsh
# Created: 2018-06-25
#
# Description: Accepts a JSON of 2 2D arrays of counts of bit blocks in each row/column.
# Solves for, and then outputs, all grids which fit those constraints.
import sys, argparse, json
from solver_logic import ... | python |
import time
import numpy
from ..Instruments import EG_G_7265
#from ..Instruments import SRS_SR830
from ..UserInterfaces.Loggers import NullLogger
class VSMController2(object):
#Controlador y sensor del VSM
def __init__(self, Logger = None):
self.LockIn = EG_G_7265(RemoteOnly = False)
... | python |
# -*- coding: utf-8 -*-
from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
app_name = 'interface'
urlpatterns = [
url(r'^$', views.MainPageView.as_view(), name='main'),
url(r'^game/(?P<uuid>[^/]+)/$', views.GameView.as_view(), name='game'),
url(r'^game/(?P<u... | python |
# -*- coding: utf-8 -*-
"""
Justin Clark
CSYS 300
Final Project
popularityPrediction.py
Use different ML methods to predict song popularity
Outline:
"""
### 1. Imports ###
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
from sklearn import preprocessing
from sk... | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: dm.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf i... | python |
print("Ausgangsabundanz der Bakterienpopulation 100 Exemplare")
print("Verdopplung alle 30 min")
abundanz=100
stunde=0
while stunde<=48:
stunde+=1
abundanz=abundanz*4
print("Stunde",stunde,abundanz,"Ind.")
abundanz1=100
for zeit in range(49):
print("Stunde",zeit,"",abundanz1,"Ind.")
... | python |
"""
Zip() -> cria um iterável (zip object), formando pares com cada elemento do 2 iteráveis passados
"""
l1 = [1, 2, 3]
l2 = [4, 5, 6]
zip1 = zip(l1, l2)
print(type(zip1))
print(zip1)
# print(list(zip1))
"""
OBS.: Some da memória após o primeiro uso
Se estiver com iteráveis de tamanhos diferentes, ele consid... | python |
from flask import Flask, render_template, request, Response, redirect, url_for
from flask_socketio import SocketIO, emit
from crazyivan import CrazyIvan
import utils
import datetime
import logging
from functools import wraps
import time
utils.init_logger()
async_mode = None
app = Flask(__name__)
app.config['SECRET_KEY... | python |
from enum import IntEnum
from .exceptions import *
from .board import Board, Item, CellState
from .difficulties import Difficulty, DifficultyConfig
class PlayState(IntEnum):
INITIAL_STATE = 0
MAKE_MOVE = 1
FAILED = 2
VICTORY = 3
class ThrillDigger:
__board = None
__price = 0
__score = 0
... | python |
import FWCore.ParameterSet.Config as cms
from Configuration.EventContent.EventContent_cff import *
btagDijetEventContent = cms.PSet(
outputCommands = cms.untracked.vstring()
)
AODSIMbtagDijetEventContent = cms.PSet(
outputCommands = cms.untracked.vstring()
)
RECOSIMbtagDijetEventContent = cms.PSet(
outputC... | python |
def reverse_delete(s,c):
"""Task
We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
then check if the result string is palindrome.
A string is called palindrome if it reads the same backward as forward.
You should return a tuple contain... | python |
"""Package broker."""
from . import Broker, python3, load_output
from jujuna.exporters import Exporter
import logging
log = logging.getLogger('jujuna.tests.broker')
class Package(Broker):
"""Mount broker."""
def __init__(self):
"""Init broker."""
super().__init__()
async def run(self, ... | python |
# from ..GenericInstrument import GenericInstrument
from ..IEEE488 import IEEE488
from ..SCPI import SCPI
'''
opts = inst.query('OO').split(',') # Anritsu output options
fmin, fmax = 2e9, 10e9
amin, amax = -30, 21
if '5' in opts:
fmin = 10e6
if '2A' in opts:
amin = -110
print(amin, amax, fmin, fmax)
testva... | python |
from gensim.models import Word2Vec
def word_embedding(corpus):
"""Construct the word embedding model for a given corpus.
:param corpus: List of sentences.
:returns: Word2Vec model.
"""
sentences = [[x for x in t.split()] for t in corpus]
return Word2Vec(sentences, min_count = 1)
if __name__ ... | python |
# Problem: https://www.hackerrank.com/challenges/itertools-product/problem
# Score: 10
| python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Jeremy Parks
# Note: Requires Python 3.3.x or higher
desc = "gems"
# Base type : settings pair
items = {
"01 Quality Gem 20": {"class": "Gems", "other": ["Quality >= 20"], "type": "currency normal"},
"02 Quality Gem High": {"class": "Gems", "other": ["Quality >= 10... | python |
N = int(input())
S = list(str(N))
S_num_sum = sum(list(map(int, S)))
if N % S_num_sum == 0:
print("Yes")
else:
print("No")
| python |
from os import name
from service.database.models import Notice
from requests import post
"""
TG 消息推送
"""
def post_tg(config,admin_account,data):
#默认为文本消息
TG_TOKEN = config['TG_TOKEN']
CHAT_ID = admin_account
telegram_message = f"管理员您好:{data['contact']}购买的{data['name']}卡密发送成功!"
p... | python |
# Generated by Django 3.2.13 on 2022-05-26 13:39
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("core", "0007_auto_20220... | python |
"""Route to all common guilds between the bot and the user"""
import requests
import json
from databases.token import Token
from helpers.crypt import hash_str
import constants
API_ENDPOINT = 'https://discordapp.com/api/v6'
def get(handler, parameters, url_parameters, ids_parameters):
"""GET method"""
token = handl... | python |
from arena import auth
auth.signout()
| python |
import datetime
import time
import serial
if __name__ == "__main__":
ser = serial.Serial(
port='/dev/ttyACM0',
baudrate=115200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
while True:
byte_response = ser.readline()
... | python |
RANDOM_SEED = 42
| python |
import re
text='isa python l earn and \n itis easy to'
#my_pat='^i[ts]'
#my_pat="learn$"
#my_pat=r"\blearn\b"
#my_pat=r"\Blearn\B"
my_pat=r"\n"
print(re.findall(my_pat,text)) | python |
from datetime import datetime
import os
import socket
import subprocess
import time
from celery import chain, chord
from celery.exceptions import Reject
import numpy as np
import csv
from .worker import simulate_pendulum_instance
from ..app import app
## Monitoring tasks
@app.task
def monitor_queues(ignore_result=... | python |
#!usr/bin/python
# --coding: utf-8 —**
# this is a inner script of subdata_by_dur.sh, which obtain a bash function
import sys
import os
from random import shuffle
def sub_set(srcdir):
f = open(srcdir+'/spk2utt', 'r')
spk2utt = f.readlines()
f.close()
f = open(srcdir+'/feats_vad.ark', 'r')
scp = f... | python |
#Escreva um programa que pergunte a quantidade de Km percorridos por um carro alugado
#e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$60 por dia e R$0,15 por Km rodado.
from time import sleep #import sleep
print('\033[36m---------------ALUGUEL DE CARROS---------... | python |
from app import db, ma
from app.mixins import CRUDMixin
from app.api.contact.models import Contact
from app.api.user.models import User
class Task(db.Model, CRUDMixin):
__tablename__ = 'tasks'
id = db.Column(db.Integer, primary_key=True)
type = db.Column(db.String)
text = db.Column(db.String)
sta... | python |
import numpy as np
import matplotlib.pyplot as plt
from pandas.stats.moments import rolling_mean, rolling_std
def plot(sample_file_name, window):
data = open(sample_file_name, 'r').read()
data = data.split('\n')
x, y = np.loadtxt(data, delimiter=';', unpack=True)
sma = rolling_mean(y, window)
rol... | python |
from flask import Blueprint,render_template,request,flash,redirect,url_for,session,jsonify
from models import *
from utils.constand import admin_news_count
from utils.response_code import RET,error_map
import re
#生成密码
from werkzeug.security import generate_password_hash,check_password_hash
#初始化
admin_blue = Blueprint('... | python |
import numpy as np
import config
import tensorflow as tf
DEBUG = False
def create_labels_overlap(feat_size, y_crops):
batch_labels, batch_weights = \
tf.py_func(create_labels_overlap_py,
[feat_size, tf.reshape(y_crops, [-1, 4]), (feat_size - 1)/2],
[tf.float32, tf.flo... | python |
#-----------------------------------------------------------------------------
"""
SoC file for Nordic devices
Read in the SVD file for a named SoC.
Run fixup functions to correct any SVD inadequecies.
"""
#-----------------------------------------------------------------------------
import soc
import cmregs
#----... | python |
import json
from app.inference import app
def test_uploadfile():
client = app.test_client()
response = client.post("/upload_file", data=json.dumps(dict(f='f')))
assert response.status_code == 400
response1 = client.get("/upload_file", data=json.dumps(dict(f='f')))
assert response1.status_code == 4... | python |
from unittest import result
import requests
from urllib.parse import urljoin
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
import json
#import statsmodels.api as sm
#import statsmodels.formula.api as smf
from PyBlakemere.PyMemoize.MemoizationDecorator import memoize
from PyBlakemere.Py... | python |
# -*- coding: utf-8 -*-
from inferbeddings.knowledgebase.base import Fact, KnowledgeBaseParser
__all__ = ['Fact', 'KnowledgeBaseParser']
| python |
def fr_mean(spike_trains, **kwargs):
pass
| python |
#!/usr/bin/env python
#
# Start the Rhinohawk mission
#
import sys
from rh_autonomy.util import get_proxy
from rh_msgs.srv import StartMission
start_mission = get_proxy('/rh/command/start_mission', StartMission)
res = start_mission()
if res and res.success:
print("Successfully started mission")
sys.exit(0)
... | python |
# -*- coding: utf-8 -*-
import pytest
import rsa # type: ignore
from mtpylon import long
from mtpylon.crypto.rsa_fingerprint import get_fingerprint
public_keys_with_fingerprint = [
pytest.param(
rsa.PublicKey.load_pkcs1(
"""
-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEA... | python |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from silksnake.remote.proto import kv_pb2 as silksnake_dot_remote_dot_proto_dot_kv__pb2
class KVStub(object):
"""Provides methods to access key-value data
... | python |
#!/usr/bin/env python3
"""
Script to call api endpoints
Author: Megan McGee
Date: October 9, 2021
"""
import requests
import os
import json
with open('config.json','r') as f:
config = json.load(f)
model_path = os.path.join(config['output_model_path'])
# Specify a URL that resolves to your wo... | python |
from django.db import models
class Tag(models.Model):
identifier = models.CharField(max_length=100, unique=True)
description = models.TextField(blank=True, default='')
meta = models.TextField(blank=True, default='')
is_abstract = models.BooleanField(blank=True, default=False)
"""Abstract tags are ... | python |
'''This module contains the ComplexityVisitor class which is where all the
analysis concerning Cyclomatic Complexity is done. There is also the class
HalsteadVisitor, that counts Halstead metrics.'''
import ast
import operator
import collections
# Helper functions to use in combination with map()
GET_COMPLEXITY = op... | python |
import os
from glob import glob
from torch import Tensor
from typing import Tuple
import subprocess
import torchaudio
from abc import abstractmethod
from clmr.datasets import Dataset
import random
def preprocess_audio(source, target, sample_rate):
p = subprocess.Popen(
["ffmpeg", "-i", source, "-ac", "1",... | python |
# -------------------------------------------------------------
# Authors: Tim van Zalingen (10784012)
# Maico Timmerman (10542590)
# Date: 12 April 2016
# File: 21.py
#
# The file for assignment 2.1. Plots N number pairs using
# uniform.
# -------------------------------------------------------------
im... | python |
#!/usr/bin/env python3
from Bio import SeqIO
import argparse
import glob, os
import sys
def GetArguments():
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--fasta_folder", type=str, required=True, help="The folder that holds the nfcongeneus outputted fasta files.")
parser.add_argument("-m"... | python |
import torch.nn as nn
import torch.nn.functional as F
import torch
import numpy as np
def load_embedding_model(pt_file, embedding_size):
"""Return an EmbeddingNet model with saved model weights, usable for inference only."""
model = EmbeddingNet(embedding_size)
# Explicitly map CUDA-trained models to CPU ... | python |
import utils
import glob
import os
import pandas as pd
import numpy as np
import math
import pca as p
def getbytes(dataframe, payload_length=810):
values = dataframe['bytes'].values
bytes = np.zeros((values.shape[0], payload_length))
for i, v in enumerate(values):
payload = np.zeros(payload_length... | python |
import requests
import youtube_dl
from bs4 import BeautifulSoup
import json
from constants import JSON_FORMAT_KWARGS
from utils import slugify
base_url = 'https://www.youtube.com/playlist?list=PLGVZCDnMOq0qLoYpkeySVtfdbQg1A_GiB'
conf_url = 'http://pydata.org/dc2016/schedule/'
conf_base_url = 'http://pydata.org'
video... | python |
SUMMARY = '/summary'
ASSETS = '/assets'
ORDERBOOK = '/orderbook/{symbol}'
TRADES = '/trades/{symbol}'
SYMBOLS = '/symbols/{symbol}'
TICKERS = '/tickers/{symbol}'
| python |
"""
Created on 8 Jul 2021
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
Based-on code
https://invensense.tdk.com/download-pdf/icp-10101-datasheet/
"""
from scs_core.climate.pressure_datum import PressureDatum
# -------------------------------------------------------------------------------------------... | python |
import pandas
import datetime
dataPath = '/Users/nikki/Dev/CIWS-Data/src/Age Study/'
inputFileName = 'datalog_Snow_Hall_2017-6-6_12-52-2.csv'
df_SnowHall = pandas.read_csv(dataPath + inputFileName,
header=1, sep=',', index_col=0, parse_dates=True,
infer_datet... | python |
from setuptools import setup, find_packages
with open("README.md", "r") as stream:
long_description = stream.read()
setup(
name="may",
version="1.0.0",
description="this is a FTP wrapper library, like as built in file system library.",
long_description=long_description,
long_description_conte... | python |
"""Rule for launching a Scala REPL with dependencies"""
load("@bazel_skylib//lib:dicts.bzl", _dicts = "dicts")
load(
"@io_bazel_rules_scala//scala/private:common_attributes.bzl",
"common_attrs",
"implicit_deps",
"launcher_template",
"resolve_deps",
)
load("@io_bazel_rules_scala//scala/private:commo... | python |
import coinbase
import requests
import json
import email.utils
import smtplib, smtpd
import imaplib
import asyncore
import sys
import getpass
from email.mime.text import MIMEText
import email
#Conversion of 1 bitcoin = MUR
url = "http://blockchain.info/ticker"
response = requests.get(url)
USD = (json.loads(response.... | python |
# for comeplte calibratio, in this we will consider base(B), camera(C), gripper(G) and AR Tag(A) frames
# trasform from B<-->G and C<-->A is known
# need to figure out transform between G<-->A and B<-->C
# P_X_Y --> represent origin of Y frame in X frame of reference
import torch
from torch import optim
import numpy a... | python |
import os
import json
import logging
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse
from . import bot
HUB_VERIFY_TOKEN = os.environ.get('WAHLTRAUD_HUB_VERIFY_TOKEN', 'na')
logger = logging.getLogger(__name__)
@csrf_exempt
def webhook(re... | python |
import pytest
@pytest.fixture(params=[True, False])
def opt_einsum(request, monkeypatch):
if not request.param:
monkeypatch.delattr("opt_einsum.contract")
@pytest.fixture(params=[1, 2])
def channels(request):
return request.param
| python |
# Copyright 2021 Universität Tübingen, DKFZ and EMBL for the German Human Genome-Phenome Archive (GHGA)
#
# 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
#
# https://www.apache.org/licenses... | python |
import json, os, time
import openshift as oc
from subprocess import check_output
def env_set(env_var, default):
if env_var in os.environ:
return os.environ[env_var]
elif os.path.exists(env_var) and os.path.getsize(env_var) > 0:
with open(env_var, 'r') as env_file:
var = env_file.re... | python |
"""
A module with internal/private models that are not thought to be used outside the MAUS package itself.
"""
from typing import Callable, List, Optional
from xml.etree.ElementTree import Element
import attrs
from lxml import etree # type:ignore[import]
from maus.models.edifact_components import EdifactS... | python |
# Dash packages
import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
# Graphing packages
import plotly.graph_objs as go
import plotly.express as px
from mapboxgl.utils import *
from mapboxgl.viz import *
# Other packages
import numpy as np
impo... | python |
'''
Warehouse - a library of segments
===================================
A warehouse manages a library of fashion segments. Their is a local warehouse
for each fashion project under the ./fashion/warehouse directory in the
project, created by 'fashion init'.
There is also a shared global warehouse located where fa... | python |
# =============================================================================
# IMPORTS
# =============================================================================
import torch
import pinot
import abc
import math
import numpy as np
# =============================================================================
#... | python |
"""
Hello World
=========================
"""
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
import pyqtgraph.console
from layer_viewer import dcolors
from layer_viewer import LayerViewerWidget
from layer_viewer.layers import *
import numpy
import skimage.data
app = pg.mkQApp()
im... | python |
# proxy module
from __future__ import absolute_import
from enable.tools.base_zoom_tool import *
| python |
#
# derl: CLI Utility for searching for dead URLs <https://github.com/tpiekarski/derl>
# ---
# Copyright 2020 Thomas Piekarski <t.piekarski@deloquencia.de>
#
from io import StringIO
from unittest import TestCase
from unittest.mock import patch
from pytest import raises
from conftest import (_TEST_DIRECTORY, _TEST_RE... | python |
"""Provides a Discord bot cog containing a collection of simple help commands."""
from typing import Optional
# Third party imports
import discord
from discord.ext import commands
# First party imports
import botpumpkin.discord.message as message_util
from botpumpkin.config import config
# *** Help ****************... | python |
"""Tests for Ajax API views in the landingzones app"""
from django.urls import reverse
from landingzones.tests.test_views import TestViewsBase
class TestLandingZoneStatusGetAjaxView(TestViewsBase):
"""Tests for the landing zone status getting Ajax view"""
def test_get(self):
"""Test GET request for... | python |
# -*- coding: utf-8 -*-
from django.contrib import admin
from .models import Project, Category, Post, Contact
@admin.register(Project)
class ProjectAdmin(admin.ModelAdmin):
list_display = (
'id',
'title',
'slug',
'image',
'live_site',
'github_link',
'descri... | python |
from mysql.connector import Error
import mysql.connector
from utils import configs
from database.connection import conn
from loguru import logger
def create_employee(employee):
c = conn.cursor()
try:
query = ("INSERT INTO employees(name, user_id, check_in, check_out,"
" work_date, pr... | python |
import click
from itertools import tee
from . import fasta
def load(msafp, reference, seqtype):
sequences = fasta.load(msafp, seqtype)
ref_finder, sequences = tee(sequences, 2)
if reference:
try:
refseq = next(
ref
for ref in ref_finder
... | python |
import heterocl as hcl
import os, sys
import numpy as np
def test_stages():
A = hcl.placeholder((32, 32), "A")
# C = hcl.placeholder((32, 32), "C")
def kernel(A):
B = hcl.compute(A.shape, lambda i, j : A[i, j] + 1, "B")
C = hcl.compute(A.shape, lambda i, j : A[i, j] + 1, "C")
D = ... | python |
import jax
import jax.numpy as jnp
def standardize_signs(v: jnp.ndarray) -> jnp.ndarray:
"""Get `w = s*v` such that `max(abs(w)) == max(w) >= 0` and `abs(s) == 1`."""
val = v[jnp.argmax(jnp.abs(v))]
if v.dtype in (jnp.complex64, jnp.complex128):
return v * jnp.abs(val) / val # make real
retur... | python |
# -*- coding: utf-8 -*-
# (C) 2013-2018,2020 Muthiah Annamalai
#
# This file is part of 'open-tamil' package tests
#
# setup the paths
import unittest
from opentamiltests import *
from tamil.utf8 import get_letters
from transliterate import azhagi, jaffna, combinational, UOM, ISO, itrans, algorithm
class ReverseTra... | python |
from userinput import userinput
import pytest
def test_hostname(monkeypatch):
monkeypatch.setattr('builtins.input', lambda x: "localhost")
assert userinput("user_input", validator="hostname", cache=False)
monkeypatch.setattr('builtins.input', lambda x: "guguwgjwgdwkdjgwkjdgj")
with pytest.raises(Value... | python |
from django.db import models
from .managers import StatusManager
class OsnovniPodatki(models.Model):
oznaka = models.CharField(max_length=100, blank=True, null=True)
oznaka_gen = models.CharField(max_length=100, blank=True, null=True)
naziv = models.CharField(max_length=255, blank=True, null=True)
o... | python |
import pandas as pd
import glob
data_path = 'E:/GenderClassification/PycharmProjects/GenderClassification/home/abeer/Dropbox/Dataset_HAR project/*'
addrs = glob.glob(data_path)
for i in addrs:
folders = glob.glob(i + '/Walk/Esphalt/Alone/*')
for j in folders:
csv_files = glob.glob(j + '/*... | python |
#! usr/bin/env python3
# -*- coding: utf-8 -*-
'''
#-------------------------------------------------------------------------------
Project : Project JaaS
Module : membership_manager
Purpose : Add new users & check membership status of existing ones
Version : 0.1.1 beta
Status : Development
Modified : 2020 Mar... | python |
import inspect
from copy import deepcopy
import re
class ConfigManage:
"""
Provides methods for managing parameter configuration for all DataWorker/DataInterface classes
(must inherit this class).
Each parameter:
specifies some documentation (or retrieves with super().doc(param_name)) for the ... | python |
#!/usr/bin/env python
# __BEGIN_LICENSE__
# Copyright (C) 2006-2011 United States Government as represented by
# the Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# __END_LICENSE__
from __future__ import with_statement
import sys
import os
from subprocess import Popen, PI... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.