content stringlengths 5 1.05M |
|---|
# todo rename
# todo docstring
# todo validate incoming data
# todo support multiple tests with arrays
import sys
sys.path.append('../src')
import logging
from pathlib import Path
import json
import requests
from dataclasses import dataclass
from app import routes
from models import Item
from models import Rating
... |
import os
import sys
import time
import argparse
from glob import glob
import torch
import torch.nn as nn
from torch.utils.tensorboard import SummaryWriter
import numpy as np
import random
from PIL import Image
from thop import profile
import model
from utils import torch_msssim, ops
from anchors import balle
from to... |
from .statistics import Statistics
async def setup(bot):
cog = Statistics(bot)
await cog.initialize()
bot.add_cog(cog)
|
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 09 13:06:12 2016
@author: jrl276
"""
import geojson
from descartes import PolygonPatch
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import matplotlib.cm as cm
import matplotlib as mpl
import numpy as np
#Define GCAM regions
re... |
class Manipulation():
''' Data Manipulation '''
def __init__(self, data):
self.data = data
self.badPattern = '''
self.goodPattern = "'"
self.filteredKey = ['artist_name', 'title']
### STATIC METHODS
def findStringAndReplace(self, oldStr, pattern, newStr):
return oldStr.replace(... |
from .alarm_clock import alarm_clock |
from precise.skaters.managers.ppomanagerfactory import ppo_ewa_long_manager_factory, ppo_pm_long_manager_factory, ppo_long_manager_factory
from precise.skaters.covariance.bufsk import buf_sk_glcv_pcov_d0_n100, buf_sk_glcv_pcov_d0_n100_t0, buf_sk_lw_pcov_d0_n100, buf_sk_mcd_pcov_d0_n100, buf_sk_lw_pcov_d1_n100
# PyPort... |
import sys
import time
from pathlib import Path
from loguru import logger
from magic import from_file
from scribepy.pybass.pybass import *
from scribepy.pybass.pybass_aac import (
BASS_AAC_StreamCreateFile,
BASS_MP4_StreamCreateFile,
)
from scribepy.pybass.pybassflac import BASS_FLAC_StreamCreateFile
from scr... |
import heapq
n, k = map(int, input().split())
hq = []
for _ in range(n):
a, b = map(int, input().split())
heapq.heappush(hq, (a, b))
# print(hq)
ans = 0
for _ in range(k):
time = heapq.heappop(hq)
ans += time[0]
heapq.heappush(hq, (time[0]+time[1], time[1]))
print(ans)
|
"""Update test files
Temporary helper script
Copyright (c) 2020 Peter Triesberger.
For further information see https://github.com/peter88213/yW2OO
Published under the MIT License (https://opensource.org/licenses/mit-license.php)
"""
import os
find = '''<office:font-face-decls>
<style:font-face style:nam... |
#!/usr/bin/python
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = r'''
module: goodbye_world
short_description: goodbye world
author:
- "Nathan Weatherly (@nathanweat... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 11 01:28:18 2019
@author: Byen23
"""
# 7th Program to be uploaded to github
"""Using Variables and Assign Statements"""
'''Write a script that will use distance in kilometers and time in hours to calculate and print out speed in kilometers per hour, miles pe... |
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.db.models import Q
from django.core.exceptions import ObjectDoesNotExist
# UserModel = get_user_model
# class EmailBackend(ModelBackend):
# def authenticate(self, request, username = None, password = N... |
from sources.source_gym import source_gym
import numpy as np
##### SOURCE GYM HOPPER
class source_gym_hopper( source_gym ):
### __INIT__
def __init__( self ):
source_gym.__init__( self , 'Hopper-v2' )
### INFORMATION
def num_actions( self ): return self.env.action_space.shape[0]
def ran... |
from django.urls import include, path
from . import views
urlpatterns = [
path('', views.ListUsuario.as_view()),
path('<int:pk>/', views.DetailUsuario.as_view()),
path('rest-auth/', include('rest_auth.urls')),
path('signin',views.signin)
#path('rest-auth/', include('django_expiring_token.urls')),
... |
# Generated by Django 2.2.13 on 2020-09-27 14:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orders', '0003_OrderBundles'),
]
operations = [
migrations.CreateModel(
name='PromoCode',
fields=[
... |
from selenium import webdriver
from bs4 import BeautifulSoup
from pymongo import MongoClient
import re
#database setting
client = MongoClient('localhost',27017)
db = client.dbsparta
melon_ticket = db.melon_ticket.find() #creating collection named melon_ticket
#find artist
artist_number=698776 #yerin baek's artist num... |
"""
Test 'conditioner.models' file
"""
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.test import TestCase
from conditioner.models import Rule
from conditioner.tests.factories import RuleFactory, BaseActionFactory, BaseConditionFactory
from conditioner.utils import ... |
# Generated by Django 3.2.3 on 2021-05-27 22:33
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),
('beershareapp', '0001_ini... |
import os, sys, logging, copy
import signal
import json
import binascii, base64
import argparse
import requests, jwt
from colorama import Fore, Back, Style
from cryptography import x509
from cryptography.hazmat.backends import default_backend
import res.const as const
def read_jwt(url, token):
#
# Call r... |
x = 100
def hello(a):
print a
|
"""
Purpose: Sample size
Date created: 2020-11-19
Ref:
https://www.qualtrics.com/experience-management/research/determine-sample-size/
https://github.com/shawnohare/samplesize/blob/master/samplesize.py
Contributor(s):
Mark M.
"""
try:
from secrets import SystemRandom
except ModuleNotFoundError:
... |
import datetime
from collections import OrderedDict
from pathlib import Path
from typing import Mapping, Tuple
import dateutil.parser
import pytz
from synctogit.filename_sanitizer import denormalize_filename
from synctogit.service.notes.stored_note import CorruptedNoteError, StoredNote
from .models import OneNotePag... |
"""
Outras linguagens de programação:
Public, Private, Protected
-Public: Consegue acessar o atributo ou método dentro ou fora da classe
+Private: Consegue acessar o atributo ou método apenas dentro da classe
#Protected: Consegue acessar o atributo ou método apenas dentro da classe ou dentro das classes filhas da clas... |
from vip_provider.credentials.base import CredentialBase, CredentialAdd
class CredentialNetworkAPI(CredentialBase):
pass
class CredentialAddNetworkAPI(CredentialAdd):
def valid_fields(self):
return [
'user', 'password', 'endpoint', 'business', 'cache_group',
'destination', 'en... |
import web
import sqlite3
import jsonpickle
urls = ('/users', 'users')
class users:
def GET(self):
connection = sqlite3.connect('DOSDATA.sqlite')
sqlite3.connect("DOSDATA.sqlite", check_same_thread=False)
cursor = connection.cursor()
sql_query = "SELECT * FROM dosuser"
rows = cursor.execute(sql_quer... |
from os import urandom, environ
S3_BUCKET_NAME = "wedding-app-images"
S3_ACCESS_KEY_ID = environ.get('S3_ACCESS_KEY_ID')
S3_ACCESS_SECRET_KEY = environ.get('S3_ACCESS_SECRET_KEY')
S3_LOCATION = 'https://{}.s3-sa-east-1.amazonaws.com/'.format(S3_BUCKET_NAME)
SECRET_KEY = urandom(32)
DEBUG = True
API_ADDRESS = "https:/... |
# coding=utf-8
import signal
from Xlib.display import Display
from Xlib import X
display = Display()
root = display.screen().root
counter = 0
def swallow_keystroke(event):
print("s")
display.allow_events(X.AsyncKeyboard, event.time)
def passthru_keystroke(event):
print("p")
display.allow_events(X... |
import boto3
import botocore
import json
import logging
import os
from botocore.exceptions import ClientError
region = os.environ["AWS_REGION"]
events_channel = os.environ["EVENTS_CHANNEL"].split(",")
logger = logging.getLogger()
#logger.setLevel(logging.INFO)
ssm = boto3.client("ssm", region_name=region)
slack_even... |
# Copyright (c) 2020 NVIDIA Corporation. All rights reserved.
# This work is licensed under the NVIDIA Source Code License - Non-commercial. Full
# text can be found in LICENSE.md
from sdf_optimizer import *
from transforms3d.quaternions import mat2quat, quat2mat
import cv2
def Twc_np(pose):
Twc = np.zeros((4, 4... |
def target_game(values):
|
# Copyright (c) 2013 OpenStack Foundation.
# 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... |
from kubernetes import client
def request(func, *args, catch=False, **kwargs):
if catch:
try:
return True, func(*args, **kwargs)
except client.rest.ApiException as err:
return False, err
else:
return True, func(*args, **kwargs)
|
#!/usr/bin/env python
import json
import os
import shutil
# EXTRACT
################################################################################
EXPORTED_DIRNAME = 'Exported'
EXTRACT_DIRNAME = 'Courses'
FILES_TO_SKIP = ['.DS_Store', 'Thumbs.db', 'ehthumbs.db', 'ehthumbs_vista.db', '.gitkeep']
def extract_cours... |
#!/usr/bin/env python
# Copyright JS Foundation and other contributors, http://js.foundation
#
# 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.... |
# -*- coding: utf-8 -*-
import scrapy
import pandas as pd
from basic1.items import Basic1Item
df = pd.read_csv("stock50.csv", encoding="big5", header=None)
class B1Spider(scrapy.Spider):
name = 'b1'
allowed_domains = ['tw.stock.yahoo.com']
start_urls = []
codes = df[0]
for code in codes:
... |
class OrderUpdateReasonEnum:
ORDER_UPDATE_REASON_UNSET = 0
OPEN_ORDERS_REQUEST_RESPONSE = 1
NEW_ORDER_ACCEPTED = 2
GENERAL_ORDER_UPDATE = 3
ORDER_FILLED = 4
ORDER_FILLED_PARTIALLY = 5
ORDER_CANCELED = 6
ORDER_CANCEL_REPLACE_COMPLETE = 7
NEW_ORDER_REJECTED = 8
ORDER_CANCEL_REJECT... |
"""FileTailer Python Class"""
from __future__ import print_function
import os
import sys
import argparse
import time
import math
from collections import Counter
# Third Party Imports
import pandas as pd
from sklearn.ensemble import IsolationForest
from sklearn.cluster import KMeans
# Local imports
from bat import bro... |
import datetime
from django.utils import timezone
from django.test import TestCase
from django.urls import reverse
from .models import Account
# Create your tests here.
class AccountMethodTests(TestCase):
def test_was_added_recently_with_future_account(self):
"""
was_added_recently() should retur... |
from typing import List
from prompt_toolkit import HTML
from prompt_toolkit.completion import Completion
from empire.client.src.EmpireCliState import state
from empire.client.src.menus.Menu import Menu
from empire.client.src.utils import print_util, table_util
from empire.client.src.utils.autocomplete_util import (
... |
from django.test import TestCase
from core.tests.utils import sample_user
from ..models import Tag
class TagModelTest(TestCase):
def test_tag_str(self):
"""Test the tag string representation"""
tag = Tag.objects.create(
user=sample_user(),
name='Meat Lover'
)
... |
from selenium.webdriver.common.by import By
class LoginLocators(object):
INPUT_USERNAME = (By.ID, 'user-name')
INPUT_PASSWORD = (By.ID, 'password')
BUTTON_LOGIN = (By.ID, 'login-button')
LABEL_MESSAGE = (By.XPATH, '//*[@id="login_button_container"]/div/form/h3')
|
import os, torch, numpy as np
from torch_geometric.data import InMemoryDataset, Data, download_url, extract_zip
import shutil
import networkx as nx
import pickle
class CyclesDataset(InMemoryDataset):
url = 'https://drive.switch.ch/index.php/s/hv65hmY48GrRAoN/download'
def __init__(self, root, train, k=8, n=50... |
from pathlib import Path
from typing import Dict, Optional, Sequence, Tuple
import numpy as np
import pandas as pd
from etl import *
from epimargin.utils import cwd, days
if __name__ == '__main__':
root = cwd()
data = root/'data'
figs = root/'figs'
# load meta data for metro-state aggregations & fi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
import win32com.client as _win
import pywintypes as _pywintypes
except:
raise Exception()
import pandas as _pd
import os as _os
import datetime as _datetime
import pytz as _pytz
import numpy as _np
from copy import copy as _copy
from pyXL.excel_utils imp... |
""" ABM-CALM: Qi Zhang (qz@unc.edu;qz@bu.edu) """
### Output Functions [awrite.py] ####
"""
O-Function 0a: Write dataframe headlines
O-Function 0b: Write initialized agent attributes
O-Function 1a: Derive stats for population
O-Function 1b: Write out stats for migration
O-Function 2a: Store stats of farm... |
"""
.. module:: message_handling
:platform: Unix
:synopsis: A module that processes V2GTP messages.
.. Copyright 2022 EDF
.. moduleauthor:: Oscar RODRIGUEZ INFANTE, Tony ZHOU, Trang PHAM, Efflam OLLIVIER
.. License:: This source code is licensed under the MIT License.
"""
from xsdata.formats.dataclass.con... |
# https://leetcode.com/problems/factorial-trailing-zeroes/
#
# algorithms
# Easy (37.09%)
# Total Accepted: 140,770
# Total Submissions: 379,570
class Solution(object):
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
res = 0
while n > 0:
... |
from django.contrib.auth.models import User
from django.db import models
class UserData(models.Model):
auth_user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
id = models.IntegerField(primary_key=True)
balance = models.FloatField(default=0.0, null=False)
language = models.CharField(... |
# coding: utf-8
from __future__ import unicode_literals
import unittest
import io
import os
from tempfile import NamedTemporaryFile
from lxml import etree
from packtools import domain
def setup_tmpfile(method):
def wrapper(self):
valid_tmpfile = NamedTemporaryFile()
valid_tmpfile.write(b'<a><b>ba... |
from conans import ConanFile, tools
import os
import shutil
class TestPackageConan(ConanFile):
settings = "os", "arch", "compiler", "build_type"
exports_sources = "hello.c", "text.s"
_targets = ("c64", "apple2")
def build(self):
if not tools.cross_building(self.settings):
for sr... |
from sklearn import datasets
from sklearn.cluster import KMeans
from sklearn.cluster import DBSCAN
# load data
iris = datasets.load_iris()
x = iris.data
x = (x-x.min(axis=0))/(x.max(axis=0)-x.min(axis=0))
y = iris.target
fig = plt.figure(figsize=(15,5))
# original distribution
plt.subplot(131)
plt.scatter([xi[2] for ... |
import api_permission_mappings_api9 as api9
import api_permission_mappings_api10 as api10
import api_permission_mappings_api14 as api14
import api_permission_mappings_api15 as api15
import api_permission_mappings_api16 as api16
import api_permission_mappings_api17 as api17
import api_permission_mappings_api18 as api18
... |
import os
from setuptools import find_packages, setup # noqa: H301
NAME = "svix-ksuid"
VERSION = "0.6.0"
# To install the library, run the following
#
# python setup.py install
#
# prerequisite: setuptools
# http://pypi.python.org/pypi/setuptools
REQUIRES = [
"python-baseconv",
]
with open(os.path.join(os.path... |
# Example of a mailing list manager
# We can run a testing SMTP server using:
# python3 -m smtpd -n -c DebuggingServer localhost:1025
from collections import defaultdict
from contextlib import suppress
from send_email import send_email
class MailingList:
"Manage groups of e-mail addresses for sending e-mails."
... |
import numpy as np
import multiprocessing as mp
import pyfftw
from numpy import pi, exp, sqrt, sin, cos, conj, arctan, tanh, tan
from numpy import heaviside as heav
from include import helper
import h5py
# ---------Spatial and potential parameters--------------
Mx = My = 64
Nx = Ny = 128 # Number of grid pts
dx = dy... |
#from src.evaluation.test import test
from training.train import train
session_name = train("batch16")
# test(session_name=session_name, is_visualize=False)
# test(session_name='test', is_visualize=True)
|
#-*-coding:utf8;-*-
#qpy:console
import sys
import os
import time
import socket
import random
#Code Time
from datetime import datetime
now = datetime.now()
hour = now.hour
minute = now.minute
day = now.day
month = now.month
year = now.year
##############
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
bytes =... |
from ..common.optim import SGD as optimizer
from ..common.coco_schedule import lr_multiplier_1x as lr_multiplier
from ..common.data.coco_keypoint import dataloader
from ..common.models.keypoint_rcnn_fpn import model
from ..common.train import train
model.backbone.bottom_up.freeze_at = 2
train.init_checkpoint = "detect... |
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.models import User
from rest_framework.views import APIView
from rest_framework import generics
from rest_framework.response import Response
from rest_framework import status
from api.serializers import CompanySerializer... |
from gpitch.matern12_spectral_mixture import MercerMatern12sm
from gpitch.myplots import plot_predict
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import gpitch
import gpflow
def per_fun(xin, npartials, freq):
"""Function to generate sum os sines"""
f = np.zeros(xin.shape)
fo... |
import time
import math
import unicodedata
import torch
import re
try:
from .config import MAX_LENGTH, EOS_token
except ImportError:
from config import MAX_LENGTH, EOS_token
def asMinutes(s):
m = math.floor(s / 60)
s -= m * 60
return '%dm %ds' % (m, s)
def timeSince(since, percent):
now = ti... |
'''
Author : now more
Connect : lin.honghui@qq.com
LastEditors : now more
Description : build_transforms
LastEditTime: 2019-07-06 20:07:26
'''
from .build import *
|
"""A setuptools-based setup module for kairos-yaml."""
from pathlib import Path
from setuptools import find_packages, setup
import sdf
long_description = Path("README.md").read_text(encoding="utf-8")
classifiers = [
"Development Status :: 4 - Beta",
"Environment :: Console",
"Intended Audience :: Devel... |
from gazette.spiders.base import FecamGazetteSpider
class ScGuabirubaSpider(FecamGazetteSpider):
name = "sc_guabiruba"
FECAM_QUERY = 'entidade:"Prefeitura municipal de Guabiruba"'
TERRITORY_ID = "4206306"
|
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 19 18:28:05 2021
@author: amrut
"""
import math
import cv2
import numpy as np
#import matplotlib.pyplot as plt
#import pytesseract
class ImageDataTransform:
def __init__(self,img):
self.img = img
def resize(self,im):
#im = cv2.resize(im,(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2016, Jianfeng Chen <jchen37@ncsu.edu>
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
#
# 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 t... |
from sims.sim_info_tests import SimInfoTest
import caches
import sims.sim_info_types
@caches.cached
def get_disallowed_ages(affordance):
disallowed_ages = set()
for test in affordance.test_globals:
if isinstance(test, SimInfoTest):
if test.ages is None:
continue
... |
# DRUNKWATER TEMPLATE(add description and prototypes)
# Question Title and Description on leetcode.com
# Function Declaration and Function Prototypes on leetcode.com
#67. Add Binary
#Given two binary strings, return their sum (also a binary string).
#The input strings are both non-empty and contains only characters 1 o... |
SIZE_PROPERTIES = [
"scale",
"width",
"length",
"unit_dz",
"period",
"fraction",
"area",
"n_xy",
"nz",
"q",
"indexer"
]
class NanowireSizeCompound:
"""
A size container that combines one or more NanowireSize objects
"""
def __init__(self, **kwargs):
... |
# Copyright 2014 Google Inc. All Rights Reserved.
"""Command for removing instances from target pools."""
from googlecloudsdk.calliope import exceptions as calliope_exceptions
from googlecloudsdk.compute.lib import base_classes
from googlecloudsdk.compute.lib import utils
class RemoveInstances(base_classes.NoOutputAs... |
#!/usr/bin/env python
import sys
sys.setdlopenflags(0x100|0x2)
import fvm
import fvm.fvmbaseExt as fvmbaseExt
import fvm.importers as importers
fvm.set_atype('double')
import math
if fvm.atype == 'double':
import fvm.models_atyped_double as models
import fvm.exporters_atyped_double as exporter... |
#!/usr/bin/env python
from graph_obj import Graph, Node, Edge
from graph_utils import revcomp
import argparse
def parse_args():
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("-b", "--bialfil... |
import pygame, sys
from pygame.locals import *
import traceback
import jaime
pygame.init()
pygame.mixer.init()
BLACK = pygame.Color("black")
speed = [2, 0]
size = width, height = 600, 400
screen = pygame.display.set_mode(size, RESIZABLE)
pygame.display.set_caption("Jaime walking --- Lee Demo")
clock = pygame.time.Cl... |
from django.apps import AppConfig
class ReplyConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'reply'
|
import runpy
from setuptools import setup, find_packages
__version__ = runpy.run_path("batchlib/__version__.py")["__version__"]
setup(
name="batchlib",
packages=find_packages(exclude=["test"]),
version=__version__,
url="https://github.com/hci-unihd/batchlib.git",
author="Constantin Pape, Roman Rem... |
# Biased Covering Array Algorithm - Andrew Ragland - 2021
import itertools
import random
# calculate a candidate's benefit value
def calc_candidate_benefit(tuples, candidate):
can_benefit = 0
tuple_count = 0
pairs = list(itertools.combinations(candidate, 2))
for pair in pairs:
for tup in list... |
import numpy as np
from opexebo import errors
def walk_filter(speed:np.ndarray, speed_cutoff:float, *args, fmt="remove"):
"""
It is common practice when studying a freely moving subject to exclude data
from periods when the subject was stationary, or nearly stationary. This
method is described as a "w... |
import torch
import torch.nn as nn
from torch.nn import init
from torch.autograd import Variable
import numpy as np
import time
import random
from sklearn.metrics import f1_score
from collections import defaultdict
from graphsage.encoders import Encoder
from graphsage.aggregators import MeanAggregator
"""
Simple sup... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Set of some useful management commands,
based on :py:mod:`script extension <flask.ext.script>`
(:py:class:`flask.ext.Manager`)
A set of scripts, based on :py:mod:`script extension <flask.ext.script>`
that you may find useful.
Amount of command... |
from typing import Tuple
from click._unicodefun import click
from exaslct_src.cli.cli import cli
from exaslct_src.cli.common import set_build_config, set_docker_repository_config, run_tasks, add_options, \
import_build_steps
from exaslct_src.cli.options \
import build_options, flavor_options, system_options, ... |
from django.db.models.signals import pre_save, post_save, post_delete
from django.dispatch import receiver
from django.utils import timezone
from slugify import slugify
from .models import Category, Document, FileStatistic
@receiver(pre_save, sender=Document)
def presave_fields(sender, instance, *args, **kwargs):
... |
import random
import itertools
# from deck_of_cards import deck_of_cards # pip install deck-of-cards
ranks = ("Ace", 2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King")
suits = ("Clubs", "Diamonds", "Hearts", "Spades")
cards = list(itertools.product(ranks, suits))
print("\nKāršu kava:\n", cards)
def get_shuff... |
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
widget = QtWidgets.QWidget()
self.setCentralWidget(widget)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
... |
import argparse
import base64
import glob
import io
import json
import os
import random
import pycocotools
import cv2
import imageio
from PIL import Image, ImageColor, ImageDraw
import numpy as np
from pycocotools import mask
from skimage import measure
CAT_TO_ID = dict(egg=1, blob=2)
CAT_TO_COLOR = dict(egg="#f00562"... |
"""
The Building Energy Modeling Extreme Weather Simulator (BEMEWS)
weather module reads in, alters, and writes out weather files
to account for extreme events or climate change.
"""
from mews.weather.alter import Alter
|
#amara3.uxml.parser
'''
Hand-crafted parser for MicroXML [1], inspired to some extent by James Clark's Javascript work [2].
[1] https://dvcs.w3.org/hg/microxml/raw-file/tip/spec/microxml.html
[2] https://github.com/jclark/microxml-js/blob/master/microxml.js
'''
import re
from enum import Enum #https://docs.python.or... |
# Various utils and helpers related to the WooKey tokens
from smartcard.CardType import AnyCardType
from smartcard.CardRequest import CardRequest
from smartcard.util import toHexString, toBytes
import datetime
from copy import deepcopy
from common_utils import *
from crypto_utils import *
# Helper to communicate w... |
import unittest
from datetime import datetime
from test.support import captured_stdout
from src.entity.count_entity import CountEntity
from src.interface_adapter.in_memory_count_repository import \
InMemoryCountRepository
from src.interface_adapter.report_count_presenter import ReportCountPresenter
from src.use_ca... |
import numpy as np
import os
import utils.utils as util
import pylab
def setFigLinesBW(fig):
"""
Take each axes in the figure, and for each line in the axes, make the
line viewable in black and white.
"""
for ax in fig.get_axes():
setAxLinesBW(ax)
def setAxLinesBW(ax):
"""
Take eac... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# droxi
# Copyright (c) 2014, Andrew Robbins, All rights reserved.
#
# This library ("it") is free software; it is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; you can redistribute it and/or modify it under the terms of the
# GNU Lesser Gen... |
import random
def double(x):
return x * 2
def test_executor_basic(fx, try_tutorial_endpoint):
"""Test executor interface"""
x = random.randint(0, 100)
fut = fx.submit(double, x, endpoint_id=try_tutorial_endpoint)
assert fut.result(timeout=10) == x * 2, "Got wrong answer"
|
def binarySearch(array, key):
start = 0
end = len(array) - 1
while start <= end:
mid = (start + end) // 2
guess = array[mid]
# Guess => low
if guess < key:
start = mid + 1
# Guess => High
elif guess > key:
end = mid - 1
else:
... |
import numpy as np
#######################################################
# put `sigmoid_forward` and `sigmoid_grad_input` here #
#######################################################
def sigmoid_forward(x_input):
"""sigmoid nonlinearity
# Arguments
x_input: np.array of size `(n_objects, n_in)`
... |
import re
from dataclasses import dataclass
from inspect import isclass
from numbers import Number
from typing import Any, Iterable, Tuple, Type, TypeVar
import numpy as np
from numpy.typing import NDArray
T = TypeVar("T", bound="RecordBase")
_CAMEL_CASE_REGEX: re.Pattern = re.compile(r"([A-Z0-9][a-z0-9... |
import unittest
import numpy as np
from io import StringIO
from ase.quaternions import Quaternion
from muspinsim.input import MuSpinInput
from muspinsim.simconfig import MuSpinConfig, MuSpinConfigError
class TestConfig(unittest.TestCase):
def test_config(self):
stest = StringIO(
"""
spins
... |
from .study_manager import main
main()
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
# -*- coding: utf-8 -*-
from datetime import datetime
from naomi import app_utils
from naomi import plugin
# The Notification Client Plugin contains a method called
# "gather()" that runs every 30 seconds. If the plugin
# does not have a gather() method at the end of the __init__
# method, then it will not be added t... |
from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="aptbps",
version=1.0,
description="Density-adaptive distance encoding for machine learning on point clouds",
long_description=long_description,
long_description_content_type="text/markdown... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.