content stringlengths 5 1.05M |
|---|
from pymongo import MongoClient
CLIENT = "mongodb://localhost:27017/"
DB = "demo"
COLLECTION = "watch"
class DatabaseHandler:
client = MongoClient(CLIENT)
db = client[DB]
collection = db[COLLECTION]
def _init_(self):
print(self.collection)
def get_collection(self):
return... |
#!/usr/bin/env python3
#
# file: main.py
# author: Michael Brockus
# gmail: <michaelbrockus@gmail.com>
#
import sys
def main():
print('Hello, World!')
if __name__ == '__main__':
sys.exit(main())
|
import socket
import threading
import time
def tcplink(sock, addr):
print('accept new connection form %s:%s' %addr)
sock.send(b'welcome!')
while True:
data = sock.recv(1024)
time.sleep(1)
if not data or data.decode('utf-8') == 'exit':
break
sock.send(('hello, {}!... |
from collections import Counter
## def get_before(tab,i,cnt=1):
## return tab[max(0,i-cnt):i]
## def get_after(tab,i,cnt=1):
## return tab[i+1:i+1+cnt]
## # 15/s
## def get_context(tokens, cnt):
## before = {}
## after = {}
## tf = Counter()
## for i,t in enumerate(tokens):
## b = get_before(tokens, i, cnt)... |
from wrappers.update import Update
from games.base_class import Game
from util import loader
class PUBG(Game):
def __init__(self):
super().__init__("PUBG", homepage='https://playbattlegrounds.com/')
def scan(self):
soup = loader.soup("https://www.pubg.com/category/patch-notes/")
table = soup.find(attrs={"cla... |
from gazette.spiders.base import FecamGazetteSpider
class ScArabutaSpider(FecamGazetteSpider):
name = "sc_arabuta"
FECAM_QUERY = "cod_entidade:20"
TERRITORY_ID = "4201273"
|
def rl(infile):
return map(int,infile.readline().split())
def f1(x,y):
return sum([max(y-v,0) for v in x])
def ok(b,n,x,s,y):
need = f1(x[:s],y) + f1(x[s:],y+1)
return need <= b
def go(b,n,x,s):
if len(x) < 37:
x = x + [0]*(37-len(x))
x = sorted(x)
lo = min(x... |
from setuptools import setup
package_name = 'flex_nav_pure_pursuit'
setup(
name=package_name,
version='0.3.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
... |
import logging
import requests
from nuheat.config import Config
from nuheat.thermostat import NuHeatThermostat
_LOGGER = logging.getLogger(__name__)
_LOGGER.setLevel(logging.DEBUG)
class NuHeat(object):
def __init__(self, region, username, password, session_id=None):
"""
Initialize a NuHeat API ... |
# The MIT License (MIT)
#
# Copyright (c) 2015 Dialogue Systems Group, University of Bielefeld
#
# 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 limitat... |
import frappe
def before_insert(doc):
total_sessions = 0
for entry in doc.therapy_plan_details:
if entry.no_of_sessions:
total_sessions += entry.no_of_sessions
doc.total_sessions = total_sessions
def validate(doc, method):
set_totals(doc)
set_status(doc)
def set_status(doc):
... |
# Copyright (c) 2017 The Verde Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
#
# This code is part of the Fatiando a Terra project (https://www.fatiando.org)
#
"""
Functions for automating model selection through cross-validation.
"""
import warnings
imp... |
def binaryToNumber(b):
return int(b, 2)
def seatId(row, seat):
return binaryToNumber(row) * 8 + binaryToNumber(seat)
with open("./input.txt", "r") as f:
seats = []
for line in f:
line = line.rstrip()
row = line[:7].replace('F','0').replace('B','1')
seat = line[7:].replace('R',... |
import os
import json
import time
import random
import click
import cv2
import torch
import numpy as np
from PIL import Image
from deepliif.data import create_dataset, transform
from deepliif.models import inference, postprocess, compute_overlap, init_nets, DeepLIIFModel
from deepliif.util import allowed_file, Visual... |
# Source : https://leetcode.com/problems/high-five/
# Author : foxfromworld
# Date : 20/11/2020
# Second attempt
import collections
class Solution:
def highFive(self, items: List[List[int]]) -> List[List[int]]:
new_dict = collections.defaultdict(list)
for item in items:
new_dict[item[0]].append(item[1... |
"""Module to handle various kinds of parsing."""
|
#!/usr/bin/env python
from paasta_tools import chronos_tools
if __name__ == '__main__':
config = chronos_tools.load_chronos_config()
client = chronos_tools.get_chronos_client(config)
jobs = [job['name'] for job in client.list()]
for job in jobs:
client.delete(job)
|
from typing import Union
from mongomapper import Schema, Reference
from .utils import Timestamp, Status, status_codes
from .data import PaymentData
from .user import User
from .campaign import Campaign
from .product import Product
class Payment(Schema, Timestamp, PaymentData):
transaction: Union[str, int, None] = ... |
import nvmeclieraser
import confirmView
import completeView
class NVMeEraser:
def erase(self, selected, model, serial):
erased = False
try:
confirm = confirmView.ConfirmView(True, model, serial).agree()
erased = nvmeclieraser.NVMeCLIEraser().erase(confirm, selected)
f... |
# tests/test_provider_hashicorp_googleworkspace.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:17:22 UTC)
def test_provider_import():
import terrascript.provider.hashicorp.googleworkspace
def test_resource_import():
from terrascript.resource.hashicorp.googleworkspace import (
goog... |
#
# Autogenerated by Thrift Compiler (1.0.0-dev)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py:new_style1
#
#from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException
from thrift.Thrift import TType, TMessageType, TException, TApplicati... |
# -*- coding: utf-8 -*-
import os
import json
import urllib
import zipfile
from flask import Blueprint, render_template, abort, g, request, flash, Response, redirect, url_for, jsonify
from flask import current_app as APP
from flask_login import login_required, current_user
from werkzeug.utils import secure_filename
... |
#!/usr/bin/env python3
import json
import logging
import urllib.parse
import urllib3
from flask import current_app
logger = logging.getLogger('coverurl')
class CoverURL:
SEARCH_URL = "https://ws.audioscrobbler.com/2.0/?"
def __init__(self, api_key):
self.params = {
'format': 'json',
... |
import jwt
import re
import time
from .cookie import CookieBackendMixin
from .exceptions import AuthenticationException
from .model import ModelBackend
_AUTH_HEADER = 'Authorization'
_AUTH_TOKEN_REGEX = re.compile('Bearer (.+)', re.IGNORECASE)
DEFAULT_VALIDITY_SECONDS = 3600 * 24 * 30
JWT_ALG = 'HS256'
class JWT... |
# -*- coding: utf-8 -*-
from djangoplus.tools import terminal
from djangoplus.ui.components import Component
from django.core.management.base import BaseCommand
from djangoplus.docs.utils import extract_documentation
class Command(BaseCommand):
def handle(self, *args, **options):
for cls in Component.sub... |
from copy import copy
def append(list1, list2):
return list1 + list2
def concat(lists):
if not lists:
return lists
end = lists[0]
for list in lists[1:]:
end = append(end, list)
return end
def filter(function, list):
new_list = []
for element in list:
if func... |
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext import declarative
from sqlalchemy import Index
Base = declarative.declarative_base()
class User(Base):
"""User table"""
__tablename__ = 'user'
__table_args__ = (
Index('ix_user_user_id', 'user_id'),
)
id = Column(Integ... |
#A simple demonstration for a multiplied output I often use to check the main algorithms are working somewhat correctly
from sys import *
path.append('D:/NetworkLib/tools')
path.append('D:/NetworkLib/networks')
from functions import *
from dnn import *
from random import *
from time import sleep
#Create v... |
def remove_duplicates(lst: list | tuple) -> list:
return list(set(lst))
def remove_duplicates_test():
my_lst = [1, 1, 1, 1, 1, 2, 2, 2, 3, 3]
print(f"Old list: {my_lst} / Filtered list: {remove_duplicates(my_lst)}")
if __name__ == "__main__":
remove_duplicates_test()
|
from helper.py import *
greeting("hello")
greeting("second stuff")
|
import types
from abc import abstractmethod
from rx import config
from rx.concurrency import current_thread_scheduler
from . import Observer, Observable, Disposable
from .anonymousobserver import AnonymousObserver
from .autodetachobserver import AutoDetachObserver
class ObservableBase(Observable):
"""Represents... |
"""
*Script plots climate modes for CESM Control in a time series (Selected case year).*
"""
import numpy as np
from netCDF4 import Dataset
import matplotlib.pyplot as plt
### Path may be broken...
directory = '/volumes/data/zml5/cesm/'
files = 'CESM1_CAM5.2_LENS_Control.cvdp_data.401-2200.nc'
filename = directory + ... |
#!/usr/bin/env python
import time
from NmeaEvents import NmeaEventPrinter
from NmeaSerialGps import NmeaSerialGps
def main():
try:
gps = NmeaSerialGps('/dev/ttyUSB0')
printer = NmeaEventPrinter()
gps.registerListener(printer)
gps.start()
while True:
ti... |
import numpy as np
#! Mixup 0.3
file = '/home/remote/u7076589/ATSPrivacy/benchmark_copy/mixup/metric_Mixup_0.3_.npy'
result = np.load(file,allow_pickle=True)
sum_ = 0
max_psnr = 0
for i in range(len(result)):
sum_+=result[i]['test_psnr']
if result[i]['test_psnr']>max_psnr:
max_psnr = result[i]['test_ps... |
# coding: utf-8
# see: https://tinyurl.com/yc67tywv
def enum_class_new_flex(cls, value):
"""
New (__new__) method enum classes that are created from attrib value
Args:
value (object): Can be Enum, Enum.value, str
Raises:
ValueError: if unable to match enum instance
Returns:
... |
import logging
from autogluon.core.constants import BINARY, MULTICLASS, REGRESSION
from autogluon.core.metrics import mean_squared_error
from .presets import get_preset_models, get_preset_models_softclass
logger = logging.getLogger(__name__)
# Higher values indicate higher priority, priority dictates the order model... |
# Generated by Django 3.0.14 on 2021-05-28 14:13
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("iaso", "0088_group_domain"),
("polio", "0004_auto_20210505_1813"),
]
operations = [
migrations.Add... |
import numpy as np
import scipy.signal
def mean_relative_error(y, x):
return np.mean(np.absolute(y - x) / (1 + np.absolute(y)))
def mean_absolute_error(y, x):
return np.mean(np.absolute(y - x))
def mean_squared_error(y, x):
return np.mean(np.square(y - x))
def root_mean_squared_error(y, x):
return ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import warnings
import getopt
from shutil import move
from os import remove, close
"""Modify meta information in raw experimental data.
While comparing algorithms with the bbob_proc package, it is sometimes
needed to change the algorithm name (given ... |
import logging
import os
from pathlib import Path
import openhivenpy
logging.basicConfig(level=logging.DEBUG)
openhivenpy.env.load_env(search_other=False)
default_env_vars = openhivenpy.env.env_vars # <== openhivenpy.env
class TestENV:
CORRECT_PATH = str(Path(f'{os.path.dirname(__file__)}') / f'correct.env')
... |
from __future__ import division, print_function, absolute_import
from os.path import join
def configuration(parent_package='', top_path=None):
import warnings
from numpy.distutils.misc_util import Configuration
from scipy._build_utils.system_info import get_info, BlasNotFoundError
config = Configurat... |
#! /usr/bin/env python3
# coding: utf-8
import unittest
import numpy
from src.helpers.resize import resize_data
class Test_Resize(unittest.TestCase):
def test_resize_2D(self):
arr = numpy.zeros((10, 20))
for x in range(10):
for y in range(20):
arr[x, y] = x + y
... |
#!/usr/bin/env python3
#
# Copyright (c) 2021, The OpenThread Authors.
# 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. Redistributions of source code must retain the above copyright
# ... |
from datetime import datetime, date, timezone
import factory
from factory import fuzzy
from dataactcore.models import jobModels
from dataactcore.models.lookups import JOB_STATUS_DICT, JOB_TYPE_DICT, FILE_TYPE_DICT
from tests.unit.dataactcore.factories.user import UserFactory
class SubmissionFactory(factory.Factory):... |
def weight(value):
""" Make able to put weight in classes or functions by decorator @weight"""
def decorator(func):
func.weight = value
return func
return decorator
|
#!/usr/bin/env python3
# despite not a script...
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import (Column, Integer, String, ForeignKey, DateTime,
MetaData, Boolean, CheckConstraint, Index, Table, Enum)
from sqlalchemy import create_engine, func # noqa: F401
from s... |
import operator as op
from dataclasses import dataclass
from io import BytesIO
from typing import BinaryIO, Iterable, Callable
CODE_iconst_m1 = b"\x02"
CODE_iconst_0 = b"\x03"
CODE_iconst_1 = b"\x04"
CODE_iconst_2 = b"\x05"
CODE_iconst_3 = b"\x06"
CODE_iconst_4 = b"\x07"
CODE_iconst_5 = b"\x08"
CODE_bipush = b"\x10"
C... |
# -*- coding: utf-8 -*
from __future__ import print_function
from behave import given, when, then, step
from behave_manners.step_utils import implies
import time
@given(u'I am at the "{page}"')
def step_impl1(context, page):
context.site.navigate_by_title(context, page)
context.cur_element = context.cur_page
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import RPi.GPIO as GPIO
import time
# define RGB-LED state
RGB_ENABLE = GPIO.LOW
RGB_DISABLE = GPIO.HIGH
# define RGB-LED pin
RGB_RED = 11
RGB_GREEN = 12
RGB_BLUE = 13
# define RGB-LED colors
RGB = [RGB_RED, RGB_GREEN, RGB_BLUE]
RGB_CYAN = [RGB_GREEN, RGB_BLUE]
RGB_MAGENTA =... |
import operator
from collections import Counter, defaultdict
import numpy as np
from multi_rake.stopwords import STOPWORDS
from multi_rake.utils import (
detect_language, keep_only_letters, separate_words, split_sentences,
)
class Rake:
def __init__(
self,
min_chars=3,
max_words=3,
... |
#!/usr/bin/env python
""" generated source for module HumanNewMovesEvent """
# package: org.ggp.base.player.gamer.statemachine.human.event
import java.util.Collections
import java.util.Comparator
import java.util.List
import org.ggp.base.util.observer.Event
import org.ggp.base.util.statemachine.Move
class HumanNew... |
import paramiko
import os.path
from utilities import error
class PluginDeployer:
def __init__(self, remote_connect_details):
self.ssh = SshClient(
remote_connect_details['url'],
remote_connect_details['ssh_username'],
remote_connect_details['ssh_password'],
... |
#
# PySNMP MIB module A3COM-HUAWEI-8021PAE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-8021PAE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:48:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
import bulk_admin
from cms.models import Store, StoreContent
@admin.register(Store)
class StoreAdmin(bulk_admin.BulkModelAdmin):
"""Using bulk_admin module here. BulkModelAdmin makes it easier for
content manag... |
from .mycalculator import add, subtract
from .myrandom import random_1d, random_2d
from .advcalc.advcalculator import sqrt, log, ln |
import math
n=input("Input check number:")
try:
n = int(eval(n))
except:
print("Your input isn't a number")
exit()
k = n
sent = str(n) + "="
m = 2 # start division with 2
while n > 1: # keep dividing till the number is greater than 1
if m > k / 2 + 1:
break
i = 0
while n % m == 0:
... |
from flask import Flask
from flask_restful import reqparse, abort, Api, Resource
from IBCMusicClient import IBCMusicClient
import errors
"""
Created by: Andrew Copeland
"""
MC = IBCMusicClient()
# Start Flask and the REST API
app = Flask(__name__)
api = Api(app)
class PlaySong(Resource):
"""
Plays a song from... |
from .tagify import *
|
number = int(input('Введите натуральное число: '))
'''
while number > 0:
print(number % 10)
number = number // 10
'''
while number > 0:
print(number // (10 ** (len(str(number)) - 1)))
number = number % (10 ** (len(str(number)) - 1))
|
import numpy as np
from spatialmath import SE3
import roboticstoolbox as rtb
import timeit
from ansitable import ANSITable, Column
# change for the robot IK under test, must set:
# * robot, the DHRobot object
# * T, the end-effector pose
# * q0, the initial joint angles for solution
example = 'puma' # 'panda'
if... |
# Copyright 2021 DeepMind Technologies Limited. 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 required by ... |
# -*- coding: utf-8 -*-
import os
try:
from configparser import ConfigParser
except ImportError:
from ConfigParser import ConfigParser # ver. < 3.0
PROJECT_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
MONGO_SETTINGS = {
'host': 'articlemeta-mongo', # ver hostname: docker-compose... |
import random
from math import sqrt
# Notes
# Each node will do anything it can to stay away from a wall
# Each node will move towards the closest node (only if it's in front)
#### CONFIG ####
num_nodes = 10
win_size = (800,600)
nodes = []
#### Script ####
def getClosestNode(current_node):
# copy the list to a ... |
from modulefinder import ModuleFinder
f = ModuleFinder()
# Run the main script
f.run_script('main.py')
# Get names of all the imported modules
names = list(f.modules.keys())
# Get a sorted list of the root modules imported
basemods = sorted(set([name.split('.')[0] for name in names]))
# Print it nicely
print("\n".j... |
# Copyright (c) 2021 PaddlePaddle Authors. 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 required by app... |
import pytest
from python.code_challenges.merge_sort.merge_sort import insertion_sort
def test_empty_list():
list = []
actual = insertion_sort(list)
expected = 'List is empty. Nothing to sort'
assert actual == expected
|
import unittest
from sainofirst import Sainofirst
class TestSms(unittest.TestCase):
def test_sms(self):
sf = Sainofirst("7878")
sms = sf.sms
def callback(success, error):
self.assertFalse(error['status'],False)
(
sms.message("yo... |
from azure.identity import AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.storage import StorageManagementClient
from azure.common.credentials import ServicePrincipa... |
# Authors: Robert Luke <mail@robertluke.net>
#
# License: BSD-3-Clause
import os.path as op
import pytest
import numpy as np
from numpy.testing import assert_allclose
from mne.datasets.testing import data_path
from mne.io import read_raw_nirx
from mne.preprocessing.nirs import beer_lambert_law, optical_density, tddr... |
import torch
import os
import random
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
from torchvision import transforms, datasets
from torchvision.datasets import ImageFolder
from PIL import Image
import h5py
import numpy as np
import collections
import numbers
import math
import pandas as ... |
from django.http import HttpResponse
from django.http import HttpResponseNotFound
from django.http import HttpResponseRedirect
from django.template import loader
from django.contrib.auth import authenticate
from django.shortcuts import render
from Models_MVC.models import User
from Models_MVC.models import Project
def... |
import sys
import os
import argparse
from io import StringIO
from pdfminer.converter import TextConverter, PDFConverter, PDFPageAggregator
from pdfminer.layout import LTTextBox, LAParams
from pdfminer.layout import LTTextLine
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfinterp import PDFResourceManager... |
"""
Solution for Leet Code 1021.
"""
class Solution:
def removeOuterParentheses(self, S: str) -> str:
result = []
state, last = 0, 0
for i, word in enumerate(S):
if word is '(':
state += 1
if word is ')':
state -= 1
if sta... |
import pandas as pd
import numpy as np
import requests
import zlib
import os
import shelve
import magic #pip install python-magic
from multiprocessing import Pool
from tqdm import tqdm
headers = {
#'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.... |
import torch
import random
from dataloader import Dataloader
import utils
import os
from datetime import datetime
import argparse
import math
import numpy as np
from torch import nn
import models
import torch.optim as optim
result_path = "results/"
result_path = os.path.join(result_path, datetime.now().strftime('%Y-%m... |
from __future__ import print_function
import time
import math
import thread
# Dk imports
from pymavlink import mavutil
from dronekit import connect, VehicleMode, LocationGlobal, LocationGlobalRelative
# Mux and TOF imports
import I2CMultiplexer
import VL53L1X
# CV imports
import cv2
import numpy as np
from picamer... |
import pygame, pybutton, pymenu, sys
from constants import *
pygame.init()
def callback(index):
if index == 1:
pygame.quit()
sys.exit()
print (index)
def setUpMenu():
# create the window
window = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption("My Game")
... |
from .. import measure
from .. import utils
from .scatter import scatter
@utils._with_pkg(pkg="matplotlib", min_version=3)
def plot_gene_variability(
data,
kernel_size=0.005,
smooth=5,
cutoff=None,
percentile=90,
ax=None,
figsize=None,
xlabel="Gene mean",
ylabel="Standardized varia... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
import logging
from cohesity_management_sdk.api_helper import APIHelper
from cohesity_management_sdk.configuration import Configuration
from cohesity_management_sdk.controllers.base_controller import BaseController
from cohesity_management_sdk.http.auth.auth_manag... |
import random
import math
import numpy as np
import pandas as pd
import json
import sys
import os
from opendp.smartnoise.sql import PandasReader, PrivateReader
from opendp.smartnoise.sql._mechanisms.gaussian import Gaussian
from pandasql import sqldf
class Aggregation:
"""
Implement different aggregation fu... |
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import pytest
from ....testing import example_data
from ...niftyreg import get_custom_path
from ...niftyreg.tests.test_regutils import no_nifty_tool
from ..qt1 import FitQt1
@pyt... |
from datetime import datetime
from hashlib import md5
import requests
from pandas import DataFrame
from .base_platform import BasePlatform
class PrivateScrapingPlatform2(BasePlatform):
API_URL = 'http://api.url'
ACTION_REPORT = 'routePage.php'
def __init__(self, username: str, password: str, start_date... |
#
# clara_setup.py
# ~~~~~~~~~~~~~~
#
# Expected environmental variables are:
# AIAA: DNS name of AIAA server that will download MMAR, e.g. 'blahblah.us-west-2.elb.amazonaws.com/'
# MODEL: THE NVIDIA MMAR name, e.g. clara_mri_seg_brain_tumors_br16_t1c2tc_no_amp
# DATABUCKET: S3 bucket containing model trai... |
import time
from discord.ext import commands
import discord
import orjson
import config
IMAGE_BASE = "https://upload.wikimedia.org/wikipedia/commons/thumb/"
HANGMAN_IMAGES = {
0: f"{IMAGE_BASE}8/8b/Hangman-0.png/60px-Hangman-0.png",
1: f"{IMAGE_BASE}3/30/Hangman-1.png/60px-Hangman-1.png",
2: f"{IMAGE_BA... |
from pprint import pprint
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
p1 = { key:value for key, value in prices.items() if value > 200 }
print("All prices over 200")
print(p1)
tech_names = { 'AAPL', 'IBM', 'HPQ', 'MSFT' }
p2 = { key:value for key, value in pri... |
"""
pytest_html 生成测试报告的插件
命令行:
pytest -v pytest_html_test.py --html=report/report.html
"""
def add(x,y):
return x+y
class TestAdd():
def test_add1(self):
assert add(1,2) == 3
def test_add2(self):
assert add(1,3) == 0
def test_add3(self):
assert add('a','b') == 'ab'
|
import os
import itertools
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from uncertainty_library.data import (
read_format_data,
fashionMNIST_idx2label as idx2label,
ds2numpy
)
from uncertainty_library.mc_drop import get_mc_predictions
from uncertainty_library.attribution_metho... |
from django.db import models
from django.utils import timezone
from django.contrib.auth import get_user_model
# Create your models here.
class Project(models.Model):
author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
title = models.CharField(max_length=255)
created_date = models.DateTim... |
def partition(a, l, r):
x = a[r-1]
i = l - 1
for j in range(l, r):
if a[j] <= x:
i += 1
a[i], a[j] = a[j], a[i]
a[i + 1], a[r-1] = a[r-1], a[i + 1]
return i + 1
def hore(a, start, end):
x = a[start]
i = start - 1
if end == len(a):
j = end
else:
j = end + 1
while True:
while True:
j -= 1
i... |
"""Model for a PaymentChannelFund transaction type."""
from dataclasses import dataclass, field
from typing import Optional
from xrpl.models.required import REQUIRED
from xrpl.models.transactions.transaction import Transaction, TransactionType
from xrpl.models.utils import require_kwargs_on_init
@require_kwargs_on_i... |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import ast
import contextlib
import gc
import logging
import os
import sys
import tempfile
import traceback
import uuid
from py_trace_event import trace_eve... |
#!/usr/bin/python
"""
Quasigroup completion in Numberjack.
See Carla P. Gomes and David Shmoys:
"Completing Quasigroups or Latin Squares: Structured Graph Coloring Problem"
See also
Ivars Peterson "Completing Latin Squares"
http://www.maa.org/mathland/mathtrek_5_8_00.html
'''
Using only the numbers 1, 2, 3, and 4, ar... |
# Python standard libraries
import os
from flask import Flask
from os import environ as env
# Import SQL
from flask_sqlalchemy import SQLAlchemy
application = Flask(__name__, template_folder='templates')
# Location where database will be and created
# /// means relative path from current file
application.config["SQL... |
from setuptools import find_packages
from setuptools import setup
install_requires = ['numpy', 'matplotlib', 'pandas']
tests_require = ['pytest']
setup_requires = ["pytest-runner"]
setup(
name='utils',
version='0.0.1',
description='Useful functions for my research',
author='Shunichi Sekiguchi',
au... |
from ..abstract_transformation import *
from ..tasks import *
import collections
import pattern
from pattern import en
import spacy
import en_core_web_sm
import numpy as np
class AddNegation(AbstractTransformation):
"""
Defines a transformation that negates a string.
"""
def __init__(self, return_meta... |
"""``cubi-tk isa-tab``: ISA-tab tooling.
Sub Commands
------------
``validate``
Validate ISA-tab files for correctness and perform sanity checks.
``resolve-hpo``
Resolve lists of HPO terms to TSV suitable for copy-and-paste into ISA-tab.
``add-ped``
Given a germline DNA sequencing ISA-tab file and a PED... |
# -*- coding: UTF8 -*-
import datetime as dt
import math
months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep',
'oct', 'nov', 'dec']
def between(string, start, beginTag, endTag):
'''resturns a substring between two tags'''
begin = string.find(beginTag, start) + len(beginTag)
end = string.find(en... |
import numpy as np
import glm
WIDTH = 64
HEIGHT = 64
vertex_0 = glm.vec4((0.1, 0.1, 0.0, 1))
vertex_1 = glm.vec4((0.8, 0.5, 0.0, 1))
vertex_2 = glm.vec4((0.2, 0.8, 0.0, 1))
triangle = [vertex_0, vertex_1, vertex_2]
model_matrix = glm.mat4(1.0)
# model_matrix = glm.scale(model_matrix, glm.vec3(0.9))
or... |
__import__('pkg_resources').declare_namespace(__name__)
# THE FOLLOWING LINES ARE EDITED BY THE BUILD PROCESS
__build__ = ''
__commit__ = ''
__branch__ = ''
|
import os
from aiotg import Bot
import requests
import urllib
import socket
import json
import threading
import asyncio
import datetime
import aiocron
import re
DB_VERSION = '0.2'
bot = Bot(os.environ["API_TOKEN"])
def save_urls():
dump = json.dumps(db)
with open('urls.json', 'w') as f:
f.write(dump)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.