content stringlengths 5 1.05M |
|---|
import time
import fitlog
def random_tmp_name():
#random is useless for seed has been fixed
a = (time.time() * 1000) % 19260817
return "tmp_%d.txt" % a
|
import numpy as np
import myrand
import scipy.stats
import sys
import random
import pytest
class TestRandoms( ):
@classmethod
@pytest.fixture(scope="class")
def setUpClass(cls):
print("Doing setUpClass")
cls.numVals = 10000
#print(vars(self))
#print(self)
@pytest.fixtu... |
"""Proxy objects for sending commands to transports"""
import logging
# We need to offset the pin numbers to CR and LF which are control characters to us
# NOTE: this *must* be same as in ardubus.h
# TODO: Use hex encoded values everywhere to avoid this
IDX_OFFSET = 32
LOGGER = logging.getLogger(__name__)
def idx2by... |
import numpy as np
import itertools as itr
import os as os
import sys as sys
import matplotlib.pyplot as plt
class GridTopology:
r"""
Control the layout/connectivity of the lattice the models are based on.
This can be used as a parent class for other topologies.
Here sites are assigned unique indice... |
# -*- coding: utf-8 -*-
import unittest
from mcfly.models import DeepConvLSTM
from test_modelgen import get_default
class DeepConvLSTMSuite(unittest.TestCase):
"""
Tests cases for DeepconvLSTM models.
"""
def test_deepconvlstm_batchnorm_dim(self):
"""The output shape of the batchnorm should be... |
from collections import namedtuple
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd.function import InplaceFunction, Function
from sklearn.metrics.pairwise import cosine_similarity
from scipy.spatial.distance import cosine
import scipy.optimize as opt
__all__ = ['CPTC... |
import pytest
from astropy import units as u
from astropy.coordinates import SkyCoord
from imephu.annotation.general import CircleAnnotation, RectangleAnnotation
from imephu.finder_chart import FinderChart
def test_rectangle_annotation(fits_file, check_finder):
"""Test rectangle annotations."""
finder_chart ... |
#!/usr/bin/env python
# This file should be available from
# http://www.pobox.com/~asl2/software/Pinefs
# and is licensed under the X Consortium license:
# Copyright (c) 2003, Aaron S. Lav, asl2@pobox.com
# All rights reserved.
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this ... |
#!/usr/bin/env python
import rospy
import cv2
from sensor_msgs.msg import Image
from std_msgs.msg import Float64MultiArray, UInt8
from std_srvs.srv import Trigger, TriggerResponse
from cv_bridge import CvBridge, CvBridgeError
import numpy as np
from scipy import optimize
import time
class linear_controller(object):
... |
#!/bin/python
import datetime
YAHOO_ENDPOINT = 'https://fantasysports.yahooapis.com/fantasy/v2'
class YHandler:
"""Class that constructs the APIs to send to Yahoo"""
def __init__(self, sc):
self.sc = sc
def __getattribute__(self, attr):
cred = super(YHandler, self).__getattribute__(att... |
#!/usr/bin/env python3
import os
import time
import math
import atexit
import numpy as np
import threading
import random
import cereal.messaging as messaging
import argparse
from common.params import Params
from common.realtime import Ratekeeper
import queue
import requests
import cereal.messaging.messaging_pyx as mess... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
from django.conf import settings
import uuid
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('... |
"""
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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 a... |
# -*- coding: utf-8 -*-
# Licensed to Anthony Shaw (anthonyshaw@apache.org) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Li... |
from datetime import datetime
from caselawclient.Client import api_client
from requests_toolbelt.multipart import decoder
from .models import SearchResults
def format_date(date):
if date == "" or date is None:
return None
time = datetime.strptime(date, "%Y-%m-%d")
return time.strftime("%d-%m-%Y... |
""" https://adventofcode.com/2018/day/6 """
def readFile():
with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f:
lines = [line[:-1].split(", ") for line in f.readlines()]
return [Point(int(line[0]), int(line[1])) for line in lines]
class Point:
n = 0
def __init__(self, x, y):
... |
import os
from helpers import dist_init, getData, getLossFun, getModel
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
import torch.optim as optim
import fairscale
from fairscale.nn.model_parallel import initialize_model_parallel
DEVICE = "cuda" if torch.cuda.is_available() else "cpu... |
###############################################################################
# Copyright (c) 2021, Milan Neubert (milan.neuber@gmail.com)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. ... |
from typing import Optional
from datetime import datetime
BETFAIR_DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
basestring = (str, bytes)
numeric_types = (int, float)
integer_types = (int,)
# will attempt to use C/Rust libraries if installed
try:
import orjson as json
except ImportError:
import json
try:
imp... |
from random import random
from matplotlib import pyplot as plt
import numpy as np
def discrete(a):
t = sum(a)*random()
subtotal = 0.0
for j in range(len(a)):
subtotal += a[j]
if subtotal > t:
return j
def tabler():
n, *m = map(int, input().split(' '))
... |
import pygame as pg
import sys
import time
from pygame.locals import *
# Setting up few properties
XO = 'x'
winner = None
draw = None
width = 500
height = 450
white = (255, 255, 255)
line_color = (130, 0, 0)
board = [[None]*3, [None]*3, [None]*3]
pg.init()
fps = 30
CLOCK = pg.time.Clock()
screen = pg.display.s... |
import os
from datetime import timedelta
DEBUG = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
PROPAGATE_EXCEPTIONS = True
JWT_BLACK_LIST_ENABLED = True
UPLOADED_IMAGES_DEST = os.path.join("static", "images")
JWT_BLACK_LIST_TOKEN_CHECKS = ["access", "refresh"]
JWT_SECRET_KEY = os.environ["JWT_SECRET_KEY"]
JWT_ACCESS_TOK... |
import os
from tqdm import tqdm
import subprocess
def alphafold(path):
# run alphafold
print("Running for path {}...".format(path))
subprocess.run(['bash', '/opt/alphafold/run.sh', '-d /lambda_stor/data/hsyoo/AlphaFoldData',
'-o ~/mutate_msa/folding_results/',
'-f {... |
# -*- coding: utf-8 -*-
import unittest
import random
from pygorithm.data_structures import (
stack,
queue,
linked_list,
tree,
graph,
heap,
trie,
quadtree,
)
from pygorithm.geometry import vector2, rect2
class TestStack(unittest.TestCase):
def test_stack(self):
myStack = ... |
# coding: utf-8
# # Projects markdown generator for academicpages
#
# Takes a TSV of projects with metadata and converts them for use with [academicpages.github.io](academicpages.github.io). This is an interactive Jupyter notebook, with the core python code in projects.py. Run either from the `markdown_generator` fo... |
from six.moves.urllib.parse import urljoin
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.views import APIView
from rest_framework.viewsets import ReadOnlyModelViewSet, ModelViewSet
from rest_framework.response import Response
from rest_framework import status
from rest_framework.ex... |
import click
from django.conf import settings
from django.contrib.sites.models import Site
def setup_current_site(site_name=None, domain=None):
'''
Sets up the user with the current site.
'''
site_id = settings.SITE_ID
click.secho('\nA site has not been configured for this CMS. Please answer the q... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/10/12 17:00
# @Author : Iydon
# @File : matlab.py
# `matlab -nodesktop' -> `from matlab import *'
# tic, toc, disp
import time
def tic(): globals()['TIC+TIME'] = time.time()
toc = lambda :time.time()-globals()['TIC+TIME']
disp = print
tic()
# numpy
i... |
import base64
import numpy as np
import os
import pathlib
import re
import shutil
from urllib.request import urlopen
raw = urlopen("https://www.quantconnect.com/services/inspector?type=T:QuantConnect.Algorithm.QCAlgorithm").read().decode("utf-8") \
.replace("true", "True") \
.replace("false", "False") \
.r... |
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import seaborn as sns
import pandas as pd
import numpy as np
import math
import os
from scipy.cluster.hierarchy import dendrogram
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
import umap
from matp... |
# --------------
# Importing header files
import numpy as np
# Path of the file has been stored in variable called 'path'
#data_file='file.csv' # path for the file
data=np.genfromtxt(path, delimiter=",", skip_header=1)
#print("\nData: \n\n", data)
#print("\nType of data: \n\n", type(data))
#New record
new... |
# -*- coding: utf-8 -*-
import pandas as pd
import requests
from zvdata.api import df_to_db
from zvdata.recorder import Recorder
from zvt.api.common import china_stock_code_to_id
from zvt.api.quote import get_entities
from zvt.domain import StockIndex, StockCategory
from zvt.domain.stock_meta import Index
from zvdata.... |
import json
import re
import string
try: # ST3
from .elm_plugin import *
from .elm_project import ElmProject
except: # ST2
from elm_plugin import *
from elm_project import ElmProject
default_exec = import_module('Default.exec')
@replace_base_class('Highlight Build Errors.HighlightBuildErrors.Exec... |
import numpy as np
import matplotlib.pyplot as plt
def get_steps_colors(values):
values = 1 / values
_range = np.max(values) - np.min(values)
_values = (values - np.min(values)) / _range
colors_data = plt.cm.Wistia(_values)
return colors_data
def paint_table(df, title_cols, title_text, result_pa... |
import binascii
import logging
from lbrynet.core.cryptoutils import get_lbry_hash_obj, verify_signature
from twisted.internet import defer, threads
from lbrynet.core.Error import DuplicateStreamHashError, InvalidStreamDescriptorError
from lbrynet.lbrylive.LiveBlob import LiveBlobInfo
from lbrynet.interfaces import IStr... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class JdZhilianItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
companyname = scrapy.Field()
jobl... |
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from django_plotly_dash import DjangoDash
import dash_table
import dash_bootstrap_components as dbc
import plotly.graph_objs as go
import plotly.express as px
import random
import json
... |
# 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 pulumi
import pulumi.runtime
from .. import utilities, tables
class Lien(pulumi.CustomResource):
def __init__(__self__, __n... |
from glob import glob
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
def main():
file = "./cpp/tests/bin/Distribution_bucket_0_15_08_2021.dat"
df = pd.read_csv(
file, delim_whitespace=True, header=None, names=["id", "x", "px", "y", "py", "t", "delta"]
)
df["turn"]... |
dividendo=int(input("Dividendo es: "))
divisor=int(input("Divisor es: "))
if dividendo>0 and divisor>0:
coc=0
residuo=dividendo
while (residuo>=divisor):
residuo-=divisor
coc+=1
print(residuo)
print(coc) |
from __future__ import unicode_literals
from sideboard.lib import mainloop
if __name__ == '__main__':
mainloop()
|
import json
from helper import OuraModel, from_json
class UserInfo(OuraModel):
_KEYS = ['age', 'weight', 'gender', 'email']
if __name__ == '__main__':
test = """
{
"age": 27,
"weight": 80,
"email": "john.doe@the.domain",
"surprise" : "wow this is new"
}"""
u = from_json(test, UserInfo)
... |
# Date: 05/10/2018
# Author: Pure-L0G1C
# Description: Wrapper for gimme object
from .gimme import Gimme
class Wrapper(object):
def __init__(self, kwargs):
self.gimme = Gimme(kwargs)
@property
def start(self):
self.gimme.start()
@property
def stop(self):
self.gimme.stop()
@property
def get(self):
... |
def implode(lst):
s = ""
for e in lst:
s = s+e
return s
print(implode(['h', 'e', 'l', 'l', 'o']))
|
# Generated by Django 3.2.3 on 2021-05-21 21:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('cities', '0002_phone'),
]
operations = [
migrations.RenameField(
model_name='phone',
old_name='phone_model',
new... |
from __future__ import absolute_import, division, print_function, unicode_literals
import os.path
import warnings
import shutil
import json
import tests.test_helpers as th
import submission_validator
class TestSubmissionValidatorValidateDetections(th.ExtendedTestCase):
def test_errors_for_missing_label_probs(s... |
import requests
use_paragraphs = True
def main():
url = "http://0.0.0.0:8100/model"
if use_paragraphs:
request_data = [
{
"human_sentences": ["Who played Sheldon Cooper in The Big Bang Theory?"],
"dialog_history": ["Who played Sheldon Cooper in The Big Bang... |
# -*- coding: utf-8 -*-
import os
import sys
import argparse
import platform
from subprocess import run
def is_macos():
"""
:return: True if system is MacOS, False otherwise
"""
return platform.system() == 'Darwin'
def is_windows():
"""
:return: True if system is Windows, False otherwise
... |
from django.db import models
# Create your models here.
class SigninModel(models.Model):
username = models.CharField(max_length=10)
password = models.CharField(max_length=50)
class BookTicketModel(models.Model):
post = models.CharField(max_length=10)
class AdjustTicketModel(models.Model):
post = mode... |
from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource, GMapOptions
from bokeh.plotting import gmap
output_file("gmap.html")
map_options = GMapOptions(lat=30.2861, lng=-97.7394, map_type="roadmap", zoom=11)
# For GMaps to function, Google requires you obtain and enable an API key:
#
# h... |
"""
Common utility functions for NPP/SNPP
"""
import os
import numpy as np
from pathlib import Path
# Country enumerations
EN = "en"
WA = "wa"
SC = "sc"
NI = "ni"
# Aggregations
EW = [EN, WA]
GB = [EN, WA, SC]
UK = [EN, WA, SC, NI]
# ONS country codes
CODES = {
EN: "E92000001",
WA: "W92000004",
SC: "S92... |
from __future__ import print_function
from utensor_cgen.ir import uTensorGraph
from utensor_cgen.ir.utils import graph_check
from utensor_cgen.transformer import CMSIS_NN_Transformer
def test_cmsisnn_trnasformer(fusion_graph_tuple):
(ugraph, ugraph1) = fusion_graph_tuple
transformer = CMSIS_NN_Transformer()
... |
import requests
import json
import execjs # 必须,需要先用pip 安装,用来执行js脚本
from urllib.parse import quote
# 用来判断是否需要打印日志
debug = True
class Py4Js:
def __init__(self):
self.ctx = execjs.compile("""
function TL(a) {
var k = "";
var b = 406644;
var b1 ... |
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import matplotlib.pylab as plt
import random
from celluloid import Camera
class Energy(nn.Module):
def __init__(self):
super(Energy, self).__init__()
self.sigma = nn.Parameter(torch.tensor([0.5]))
self.mu = nn.Parameter(torch.tens... |
import scrapy
from celery import Celery
from scrapy.settings import Settings
from scrapy.spiders import Spider
from scrapyscript import Job, Processor, ScrapyScriptException
from spiders import ItemSpider, TitleSpider
app = Celery("hello", broker="amqp://guest@localhost//")
@app.task
def celery_job(url):
job = ... |
from copy import copy
from Cat.utils.collections_ import ChainedList
from model.commands.argumentTypes import *
from model.commands.command import CommandSchema, KeywordSchema, ArgumentSchema, TERMINAL, COMMANDS_ROOT, SwitchSchema
from model.data.mcVersions import MCVersion
def fillCommandsFor1_17(version: MCVersion... |
# -*- coding: utf-8 -*-
# Port of the official ttgo library for the LilyGo TTGO T-Watch 2020.
# Author: Nikita Selin (Anodev)[https://github.com/OPHoperHPO]
import gc
import _thread
import axp202
import lvgl as lv
import st7789_lvgl
import ft6x36
from bma42x import BMA42X
from pcf8563 import PCF8563
from machine import... |
# https://leetcode.com/problems/longest-common-prefix/
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ''
# since list of string will be sorted and retrieved min max by alphebetic order
s1, s2 = min(strs), max(strs)
for i, c in... |
from django.apps import AppConfig
class S3FileConfig(AppConfig):
name = 'apps.s3file'
|
"""
test_django-oci api
-------------------
Tests for `django-oci` api.
"""
from django.urls import reverse
from django.contrib.auth.models import User
from django_oci import settings
from rest_framework import status
from rest_framework.test import APITestCase
from django.test.utils import override_settings
from tim... |
from _todefrost import package_md5sum
md5 = None
try:
with open('/flash/package.md5') as f:
md5 = f.read().strip()
except Exception as e:
pass
if md5 != package_md5sum.md5sum:
print("package md5 changed....defrosting...")
from _todefrost import microwave
microwave.defrost()
import mach... |
#!/usr/bin/env python
import pytest
from clichain import cli, pipeline
import click
from click.testing import CliRunner
import sys
import ast
import logging
from difflib import SequenceMatcher
def test_main_help():
tasks = cli.Tasks()
args = ['--help']
result = cli.test(tasks, args)
print('>> test_ma... |
compiler = 'C:\\Users\\Public\\Documents\\Mikroelektronika\\mikroC PRO for PIC\\mikroCPIC1618.exe'
settings = {
'cmdln0': '"{compiler}" -MSF -DBG -p{device} -GC -DL -O11111110 -fo{clock} -N"{project}" "{filename}"',
'cmdlnSP': '-SP"{path}"',
'cmdlnIP': '-IP"{path}"',
'cmdlnLIBS': '"__Lib_Math.mcl" "__L... |
from rest_framework import serializers
from .models import Post, Category
class BlogCategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = [
'name',
'created_at',
'updated_at',
]
class BlogPostSerializer(serializers.Mode... |
from dictpy.dict_search import DictSearch
from dictpy.serializer import Serializer
__all__ = ["DictSearch", "Serializer"]
|
import pandas as pd
class TrainDataSampler:
def name(self):
raise NotImplementedError
def sample(self, df):
raise NotImplementedError
class CompleteData(TrainDataSampler):
def name(self):
return 'complete_data'
def sample(self, df):
return df
class BalancedExampl... |
from unbillit_project import app
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8000, debug=True)
############## set envirnment variable for secret key #############
# Add password strength validators later to user/form.py
# work on putting everything together
# implement password reset functiona... |
import psycopg2
import pandas as pd
import numpy as np
import pickle
import matplotlib.pyplot as plt
from numpy import random
from sklearn.preprocessing import StandardScaler
import os
os.chdir('/home/rafalb/work/molecules/chemicalSmilesSpace/src')
from keras.layers import LSTM, TimeDistributed, concatenate, Input, ... |
from django.db import models
class Contact(models.Model):
first_name = models.CharField(null=False, blank=False, max_length=50)
last_name = models.CharField(null=False, blank=False, max_length=50)
email = models.CharField(null=False, blank=False, max_length=50)
ip = models.CharField(null=False, blank=... |
"""
Provides animated GIF images of weather-radar imagery derived the Australian
Bureau of Meteorology (http://www.bom.gov.au/australia/radar/).
"""
import datetime as dt
import io
import logging
import os
import re
import time
import PIL.Image
import requests
# Legend:
#
# NSW: http://www.bom.gov.au/australia/radar... |
from AttachmentFetcherGUI import runGUI
runGUI()
|
from typing import Tuple
import numpy as np
import tensorflow as tf
from absl import logging
from xain.datasets import prep
from xain.types import KerasHistory, KerasWeights, Metrics, VolumeByClass
from . import ModelProvider
class Participant:
# pylint: disable-msg=too-many-arguments
# pylint: disable=too... |
#!/usr/bin/env python3
import sys
import heapq
# Generates gawk code. Run this manually and update hinter.awk if you don't like current alphabet or want to increase number of hints.
#
# This script builds prefix code for given number of hints using n-aray Huffman Coding.
# We precompute hints for hinter.awk to make it... |
#!/usr/bin/python2.7
# -*- coding=utf-8 -*-
##################################################################
# WaterLevelTree Test
# Goal: Test script for WaterLevelTree algorithm
# Author: wenchieh
#
# Project: eaglemine
# waterleveltree.py
# Version:
# Date: November 29 2017
# Main Contact... |
from restaurant import Restaurant
rest1 = Restaurant('Alitas y Costillas', 'BBQ')
print(rest1.describe_restaurant())
print(rest1.open_restaurant())
from user import Admin
admin1 = Admin('Antonio', 'Perez', '25', 'Monterrey, Nuevo Leon')
admin1.privileges = ['Edit', 'Delete', 'Ban']
print(admin1.describe_User())
admin... |
#!/usr/bin/env python3
"""
See freq_response.md for details
"""
from dataclasses import dataclass
import fractions
import math
from typing import Iterable, Optional, Tuple, Union
import numpy as np
from analysis import linearity, time_domain_response
from utils import utils
from unit_test import unit_test
from pro... |
"""
2019/12/23 23:42
162.【正则表达式】开始结束和或语法
"""
import re
# TODO: 1. ^托字号: 表示以...开始
"""
如果是在中括号中,那么代表取反操作.
"""
text1 = 'hello'
ret_text1 = re.match('^h', text1)
print('^托字号: 表示以...开始...')
print(ret_text1.group())
# TODO: 2.$ 表示以...结束
email = 'hynever@163.com'
ret_email = re.match('\w+@163\.com$', email)
print('$ 表示以..... |
import paddle
import paddle.nn.functional as F
import random
import numpy as np
import math
from PIL import Image
from ..registry import PIPELINES
from collections.abc import Sequence
import cv2
import random
@PIPELINES.register()
class Toskeleton(object):
"""
transpose (M,T,V,2) to (2,T,V,... |
class RoundEdge:
def __init__(self, r, obj):
self.r = r
self.obj = obj
self.material = obj.material
self.color = obj.color
def signedDistance(self, point):
return self.obj.signedDistance(point) - self.r
def evalColorAtPoint(self, point):
return self.obj.ev... |
# -*- coding: utf-8 -*-
"""
unistorage.adapters.amazon
~~~~~~~~~~~~~~~~~~~~~~~~~~
This module an adapter for Amazon Simple Storage Service (S3).
:copyright: (c) 2012 by Janne Vanhala.
:license: BSD, see LICENSE for more details.
"""
from datetime import datetime, timedelta
from email.utils import... |
import numpy as np
import time
#Note, all modes should have a return to forward, to prevent stucks
def forward_mode(Rover):
# Calm the roll and pitch
if (Rover.roll >= 1.5 and Rover.roll <= 358.5) or (Rover.pitch >= 1.5 and Rover.pitch <= 359):
Rover.max_vel = 0.5
else:
Rover.max_vel = 5
... |
# License: MIT License
import typing
import numpy as np
class Trajectory(object):
""" Abstracts the infos about a complete set of trajectories, represented as a numpy array of doubles
(the time deltas) and a numpy matrix of ints (the changes of states).
:param list_of_columns: the list containing the... |
# -*- coding: utf-8 -*-
# Copyright 2016 Battelle Energy Alliance, 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 ... |
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Conversions between formats."""
import numpy as np
import pytest
from .. import linear as _l
from ..io import LinearTransformArray as LTA
@pytest.mark.parametrize(
"filename",
[
"f... |
import sys
import os
class Configuration:
######################################
###### Configuration parameters ######
######################################
# Change them if required
# path to the root of ExaHyPe from this file
pathToExaHyPERoot = os.path.abspath(os.path.join(os.pa... |
from socket import socket, AF_INET, SOCK_STREAM
from message_handler import MessageHandler
from string_match import match
from rsa_ops import init_rsa
class Client:
def __init__(self, server_adr, bsize=1024):
self.server_adr = server_adr # a tuple
self.bsize = bsize
self.pubkey, self.priv... |
from django.db import models
from datetime import date
class CompletionDate(models.Model):
"""Store a task completion on a certain date"""
completion_date = models.DateField(auto_now_add=True, primary_key=True)
class Task(models.Model):
"""Daily task model and related functions"""
task_id = models.A... |
#!/usr/bin/env python
import keras
import numpy as np
from imgaug import augmenters as iaa
from keras.applications.mobilenet import preprocess_input
from keras.preprocessing.image import image
class CustomDataGenerator(keras.utils.Sequence):
"""
Takes input of image paths and corresponding labels and generat... |
# Generated by Django 3.2.7 on 2021-10-06 22:44
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0008_alter_review_reviewer'),
]
operations = [
migrations.AlterField(
model_name='watchl... |
#
# PySNMP MIB module APPACCELERATION-STATUS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/APPACCELERATION-STATUS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:07:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version ... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import os
import sys
if os.name == 'posix' and sys.version_info[0] < 3:
import subprocess32 as subprocess
else:
import subprocess
from . import common as cmn
task_registry = {}
def task(task_func):
""... |
#!/usr/bin/env python
"""Test for near equality
"""
import unittest
class AlmostEqualTest(unittest.TestCase):
def testNotAlmostEqual(self):
self.failIfAlmostEqual(1.1, 3.3 - 2.0, places=1)
def testAlmostEqual(self):
self.failUnlessAlmostEqual(1.1, 3.3 - 2.0, places=0)
if __name__ == '__m... |
import pytest
from generalizer import generalize_label
test_data = [
('enter the email associated with your account', 'email'),
('zip code', 'ZIPcode'),
('postal code', 'ZIPcode'),
('first name', 'firstname'),
('last name', 'surname'),
('city', 'city'),
('reference name', 'name'),
('pas... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import sys
from json import loads as json_loads
from wolframclient.utils import six
from wolframclient.utils.encoding import force_text
# Python 3.4 and 3.5 json loads only accept str.
if sys.version_info[0] == 3 and sy... |
from csc148_queue import Queue
class Tree:
"""
A bare-bones Tree ADT that identifies the root with the entire tree.
"""
def __init__(self, value=None, children=None):
"""
Create Tree self with content value and 0 or more children
@param Tree self: this tree
@param obj... |
pythonic_machine_ages = [19, 22, 34, 26, 32, 30, 24, 24]
def mean(dataset):
return sum(dataset) / len(dataset)
print(mean(pythonic_machine_ages))
print(sum(pythonic_machine_ages)) |
""" business days module """
from datetime import timedelta, date
from collections.abc import Generator
import holidays
def business_days_list(sdate: date, edate: date) -> list[date]:
""" get business days for start and end date inclusive """
days = []
us_holidays = holidays.UnitedStates()
for num ... |
from random import randint
from math import hypot, fabs, ceil
class AudioSource:
def __init__(self, pos, tile):
self.pos = pos
self.tile = tile
def ValidatedMove(self, velocity, map):
new_location = {'tile' : [self.tile.pos[0], self.tile.pos[1]], 'position' : [0, 0]}
if... |
*
* *
* *
* *
* *
* *
* * * * * * *
PRINT TRIANGLE LOOK LIKE THIS
===========================================
for row in range(7):
for col in range(7):
if(row-col==row)or(row==6)or(row==col):
print("*",end=" ")
else:
... |
DEPARTMENTS_MAP = {
"che": "Chemical",
"che-idd": "Chemical IDD",
"cer": "Ceramic",
"cer-idd": "Ceramic IDD",
"civ": "Civil",
"civ-idd": "Civil IDD",
"cse": "Computer Science",
"cse-idd": "Computer Science IDD",
"eee": "Electrical",
"eee-idd": "Electrical IDD",
"ece": "Electr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.