content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
r'''This module contains implementations of common regularizers.
In ``theanets`` regularizers are thought of as additional terms that get
combined with the :class:`Loss <theanets.losses.Loss>` for a model at
optimization time. Regularizer terms in the loss are usually used to "encourage"
a mod... |
#!/usr/bin/python
# coding=utf-8
# File Name: 5.SingleNum/single_num.py
# Developer: VVgege
# Data: Tue Feb 3 22:30:56 2015
'''
Question
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it wi... |
import multiprocessing as mp
import subprocess as sp
import os
import time
import parse
import signal
from tqdm import tqdm
UPDATE = 1
DONE = 2
NEW = 3
queue = mp.Queue()
def execute(args):
with open('overnight/{0}-{2}-{4} {3}-{5}-{1}.timing'.format(*args), "w+") as timing_file:
current = mp.current_pro... |
from typing import List, Tuple, AsyncGenerator, Optional
from unittest.mock import Mock
from wcpan.drive.abc import RemoteDriver, ReadableFile, WritableFile, Hasher
from wcpan.drive.types import Node, ChangeDict, PrivateDict
from wcpan.drive.cache import node_from_dict
from .util import create_root
class FakeDriver... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainui/mainwindow.ui'
#
# Created: Thu Sep 24 15:01:53 2015
# by: pyside-uic 0.2.15 running on PySide 1.2.2
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_MainWindow(object):
def... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import distance_matrix
from copy import deepcopy
from common.utils import RunningMeanStd
import gym
class Env():
def __init__(self, normalize):
#shared parameters
self.env = gym.make('Pendulum-v0')
self.T = 200
s... |
# Generated by Django 2.2.6 on 2019-10-29 07:38
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('app', '0002_auto_20191029_0737'),
]
operations = [
migrations.RemoveField(
model_name='weather',
name='dewPointTemperature',... |
# -*- coding: utf-8 -*-
"""Concentrate the heavy business logic of the operations of an application.
It knows all Models that should be part of the flow and knows
the API/services of those models. It also orchestrate all the side-effects
and therefore can make the use of other use cases/services.
"""
from django.utils... |
# -*- coding: utf-8 -*-
'''
@Time : 2021/9/8
@Author : Yanyuxiang
@Email : yanyuxiangtoday@163.com
@FileName: cprofile_quick_start.py
@Software: PyCharm
'''
import time
def a():
time.sleep(3)
def b():
for _ in range(10**6):
pass
def main():
a()
b()
print('done')
if __name__ == '... |
import random
from .models import MaterialRequestSignature,MaterialRequest,Material,MaterialInStock,MaterialWareHouse, Assignment, Project, Event, OrganizationUnit, Employee, Contractor, ManagerPage, ArchiveDocument
from authentication.repo import ProfileRepo
from dashboard.models import Icon
from dashboard.enums impor... |
import os
from typing import List
from dotenv import load_dotenv
load_dotenv()
commands: List[str] = ['mkdir /home/ubuntu/AOGuildSite/certs/',
'wget {0} -O /home/ubuntu/AOGuildSite/certs/backend_cert.pem'.format(os.getenv('BACKEND_CERT')),
'wget {0} -O /home/ubuntu/AOGui... |
from flask import abort, Blueprint, render_template, send_from_directory, \
jsonify, request, redirect, url_for, flash, current_app, send_file
from flask_login import login_required, current_user
import sqlalchemy as sa
from spreadsheetcompiler.extensions import login_manager, db
from .. import models
from .users impo... |
/home/runner/.cache/pip/pool/47/5c/17/1e750cb5e8e9c342671ff24ef177586ac304eb08d5aa9d733fb4ca2e08 |
from __future__ import print_function, absolute_import, division, generators, nested_scopes
import sys
import os.path
import logging
import ply.yacc
from jsonpath_ng.jsonpath import *
from jsonpath_ng.lexer import JsonPathLexer
logger = logging.getLogger(__name__)
def parse(string):
return JsonPathParser().pars... |
from .base import BaseMetric
import GPUtil
class GPUs(BaseMetric):
def __init__(self):
pass
def measure(self):
all = []
gpus = GPUtil.getGPUs()
for g in gpus:
all.append(g.__dict__)
return {
"gpus_data": all,
"gpus_averages": self._... |
from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend as DjangoModelBackend
class ModelBackend(DjangoModelBackend):
def authenticate(self, username=None, password=None):
""" Case insensitive username """
try:
user = User.objects.get(username__... |
#!/usr/bin/env python3
"""
Author: Ken Youens-Clark <kyclark@gmail.com>
Purpose: Filter Swissprot file for keywords, taxa
"""
import argparse
import os
import sys
from Bio import SeqIO
# --------------------------------------------------
def get_args():
"""get args"""
parser = argparse.ArgumentParser(
... |
import json
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s,%(msecs)d %(levelname)s: %(message)s",
datefmt="%H:%M:%S",
)
log = logging
def write_JSON_file(output_file_name_w_path, arr_of_objs, json_lines=False):
with open(output_file_name_w_path, mode="a", encoding='utf8'... |
import os
import pickle
import json
import numpy as np
def main():
artifacts_dir = 'artifacts/filter_experiment/'
artifacts_baseline_dir = 'artifacts/filter_baseline_experiment/'
epsilons = ['0.001', '0.005', '0.01', '0.05']
use_filters = ['True', 'False']
table = {}
table['f'] = []
table[... |
from django.core.exceptions import ImproperlyConfigured
from django.template import engines
from django.test import SimpleTestCase, override_settings
class TemplateUtilsTests(SimpleTestCase):
@override_settings(TEMPLATES=[{'BACKEND': 'raise.import.error'}])
def test_backend_import_error(self):
... |
from .Adafruit_LSM303 import Adafruit_LSM303
|
from typing import List
def strip_punctuation(word: str):
res = word.strip(".,;-/!?:\\—()[]{}\"'")
return res
def strip_punctuation_words(words: List[str]) -> List[str]:
# keep
res = [strip_punctuation(x) for x in words]
res = [x for x in res if x != ""]
return res
def strip_punctuation_utterance(utte... |
from django.contrib.auth.models import User
from django.db import models
from steemconnect.client import Client
class SteemConnectUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
refresh_token = models.CharField(
max_length=500, help_text="steemconnect user code / to get... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2022 TU Wien.
#
# Invenio-Users-Resources is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
"""Definitions that are used by both users and user groups services."""
from invenio_records_resourc... |
"""
The http server implementation
"""
import BaseHTTPServer
import SocketServer
import socket #for socket.error
import re
import os
import sys
import urlparse
import traceback
import threading
import drapache
from drapache import util
class DropboxHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""
T... |
import pandas as pd
from matplotlib import pyplot as plt
import numpy as np
import math
from matplotlib import pyplot as plt
from sklearn.preprocessing import LabelEncoder
feature_dict = {i:label for i,label in zip(
range(4),
('sepal length in cm',
'sepal width in c... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Provide an interface to the Drupal 6 CMS database.
This module provides a wrapper to interfacing with the
content management system database.
Supports Drupal 6 only.
"""
import MySQLdb as mdb
import logging
import os, subprocess
from phpserialize import unserialize
#import ... |
# plugin to select a new replica based on the "priority"
# assigned by users in the server definitions
# as with all replica selection, it returns a LIST
# of replicas
# sorts replicas first by status ( healthy then lagged)
# then sorts them by priority
from plugins.handyrepplugin import HandyRepPlugin
class select_r... |
# -*- coding: utf-8 -*-
from peewee import ForeignKeyField, DateTimeField, TextField, SmallIntegerField
from models.base import BaseModel
from models.users import Users
from models.articles import Articles
from datetime import datetime
class ArticleComments(BaseModel):
owner = ForeignKeyField(Users, related_name... |
import subprocess
import pytest
@pytest.fixture
def with_packages(capsys, request):
with capsys.disabled():
subprocess.run(
["poetry", "add"] + request.param,
stdout=subprocess.DEVNULL,
)
yield
with capsys.disabled():
subprocess.run(
["poetry", ... |
from __future__ import absolute_import
from __future__ import print_function
import os
import sys
import functools
import math
import numpy as np
# the next line can be removed after installation
sys.path.insert(0, os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__)))))
import nngen as ng
... |
# An indexer using the DIALS methods.
import copy
import logging
import math
import os
import string
import libtbx
from cctbx import crystal, sgtbx
# wrappers for programs that this needs: DIALS
from dials.array_family import flex
from xia2.Wrappers.Dials.GenerateMask import GenerateMask as _GenerateMask
from xia... |
"""
Metaball Demo Effect
by luis2048. (Adapted to Python by Jonathan Feinberg)
Organic-looking n-dimensional objects. The technique for rendering
metaballs was invented by Jim Blinn in the early 1980s. Each metaball
is defined as a function in n-dimensions.
"""
numBlobs = 3
# Position vector for each blob
... |
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from highlight import Highlighter
'''
调用了QCompleter, 不知道有没有起作用。。。。
参考文章地址:http://blog.sina.com.cn/s/blog_a6fb6cc90101gu7w.html
2017年11月17日12点56分
自动补全已经工作了, 是因为文件相对地址打错了。。。。。
2017年11月18日17点18分
@acytoo
'''
class TextEdit(QTextEdit):
... |
import contextlib
with contextlib.redirect_stdout(None):
import pygame
from utils import sin, cos
from tiles import Wall
def handle_collisions(droid, all_sprites):
col_dirs = set()
for sprite in all_sprites:
if isinstance(sprite, Wall):
col_dirs.update(get_collision_directions(droid, sp... |
# coding=utf-8
class Fake:
def __init__(self, d, spec=None):
for key, value in d.items():
if isinstance(value, dict):
setattr(self, key, Fake(value))
else:
setattr(self, key, value)
if spec:
self.__class__ = spec
|
import os
import bpy
import time
import json
import urllib
import shutil
import pathlib
import zipfile
import addon_utils
from threading import Thread
from collections import OrderedDict
from bpy.app.handlers import persistent
from .translations import t
no_ver_check = False
fake_update = False
is_checking_for_update... |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorbayes.layers import Constant, Placeholder, Dense, GaussianSample
from tensorbayes.distributions import log_bernoulli_with_logits, log_normal
from tensorbayes.tbutils import cross_entropy_with_logits
from tensorbayes.nbutils im... |
import json, sys, util
from xml.dom.minidom import parse
dom = parse(sys.argv[1])
imageries = dom.getElementsByTagName('entry')
for imagery in imageries:
entry = {
'name': util.textelem(imagery, 'name'),
'type': util.textelem(imagery, 'type'),
'url': util.textelem(imagery, 'url'),
... |
# Numeros favoritos: Modifique o seu programa do Exercicio 02.py para que cada pessoa possa ter mais de um numero favorito. Em seguida, apresente o nome de cada pessoa, juntamente com seus numeros favoritos.
favorite_numbers = dict()
favorite_numbers["Jaoa"] = [12, 23, 45, 14, 75, 43]
favorite_numbers["Alberto"] = [4,... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Time:
2021-02-26 17:17
Author:
huayang
Subject:
Notes:
现象:
class C(A, B)
C类 继承了 A 和 B,
在此之前,A 和 B 没有任何关系
但在 C 同时继承了 A 和 B 后,A 就能调用 B 中的代码
说明:
1. 先继承 B,此时可以访问 B 的所有成员;
2. 然后继承 A,如果 A 中存在与 B 同名的方法... |
import pandas as pd
import numpy as np
import pickle
import ast
import requests
import re
import json
import warnings
import time
class recipe_data_class:
def __init__(self, raw_recipes_file, pp_recipes_file, ingr_map_file):
self.raw_recipes_file = raw_recipes_file
self.pp_recipes_file = pp_recipes... |
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Book
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ('title', 'author', 'pdf', 'cover')
class CreateUserForm(UserCreationForm):
... |
import factory
import datetime
from django.utils.text import slugify
from .constants import *
from .models import (
Investor,
Shareholder,
Security,
Addition,
Certificate)
class InvestorFactory(factory.DjangoModelFactory):
FACTORY_FOR = Investor
FACTORY_DJANGO_GET_OR_CREATE = ('slug',)... |
from .return_class import AbstractApiClass
class Project(AbstractApiClass):
"""
A project is a container which holds datasets, models and deployments
"""
def __init__(self, client, projectId=None, name=None, useCase=None, createdAt=None, featureGroupsEnabled=None):
super().__init__(client... |
'''
Author: linghaol
Tools package
'''
from markdown2 import markdown
class FileParser:
def parse(fpath=None, ftype=None):
'''
File parts are seperated by '//////'.
Output is a dictionary.
'''
if fpath == None:
print('Please specify a file path!')
... |
from . import subsubpkg21 # noqa: F401
from . import mod # noqa: F401
|
# For image output to bmp file
import os
# For image operation
from library.image_tool_box import *
# For math/statistic operation
from library.math_tool_box import StatMaker
import math
### Prelude: Downlaod and unpack those 4 test data from MNIST database.
# train-images-idx3-ubyte.gz: training set images (... |
#!/usr/bin/env python3
import sys
from cx_Freeze import Executable, setup # type: ignore
# cx_Freeze options, see documentation:
# https://cx-freeze.readthedocs.io/en/latest/distutils.html#build-exe
build_exe_options = {
"packages": [],
"excludes": [
"numpy.core.tests",
"numpy.distutils",
... |
'''utils -- contains utility/support members.
CertificateAuthority: class for faking SSL keys for any site
safe_split_http_response_line - parse HTTP response codes
safe_split_http_request_line - parse HTTP request
'''
import shutil
import os
import logging
import tempfile
import uuid
try:
import urlparse
except I... |
# Using single formatter
print("{}, My name is John".format("Hi"))
str1 = "This is John. I am learning {} scripting language."
print(str1.format("Python"))
print("Hi, My name is Sara and I am {} years old !!".format(26))
# Using multiple formatters
str2 = "This is Mary {}. I work at {} Resource department. I am {} y... |
import torch
import torch.nn as nn
from torch import distributions as dist
from .encoder import ResnetPointnet
from .decoder import DecoderONet
class Network(nn.Module):
def __init__(self,latent_size=256, VAE=False, decoder_insize=3, outsize=1):
super().__init__()
self.encoder = ResnetPointnet(d... |
import pg_utils.sound.SADLStreamPlayer
import pg_utils.sound.SMDLStreamPlayer
from pg_utils.rom.rom_extract import load_sadl, load_smd
class EventSound:
def __init__(self):
self.sadl_player = pg_utils.sound.SADLStreamPlayer.SADLStreamPlayer()
self.sadl_player.set_volume(0.5)
self.bg_player... |
"""test_backend URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')... |
import os
import os.path
import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage
import scipy.spatial.distance
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def caption(track):
if track.title and track.artist:
return "%s - %s" % (track.artist, track.title)
... |
from sqlalchemy import text, UniqueConstraint
from werkzeug.security import check_password_hash, generate_password_hash
from db import db
from models.mixin import ModelMixin
class AppUserModel(ModelMixin, db.Model):
__tablename__ = 'app_user'
__table_args__ = (UniqueConstraint('username',
... |
import numpy as np
import pandas as pd
import os
from scipy.stats import linregress
from sympy import diff
from sympy.abc import P
def compute_diffusivity(gas_path, mode):
"""Obtém os dados dos arquivos de saída do lammps e calcula as difusividades corrigidas
Args:
gas_path (str): caminho da pasta do ... |
from core.management.functions.update_database import update_database
from core.management.functions.get_data_from_api import get_data_from_api
from django.core.management.base import BaseCommand
class Command(BaseCommand):
"""Django command for updating the database from igdb API"""
def handle(self, *args, ... |
from enum import Enum
from django.contrib.auth import get_user_model
from django.db import models as m
from discuss_api.apps.tag.models import Tag
User = get_user_model()
class Updown(str, Enum):
UP = 'up'
DOWN = 'down'
class VoteChoice(Enum):
AGREE = 'agree'
NOT_AGREE = 'not_agree'
NOT_SURE... |
#!/usr/bin/env python
from rapidsms.contrib.handlers.handlers.keyword import KeywordHandler
class GenderHandler(KeywordHandler):
keyword = "gender"
def help(self):
self.respond("To save the child gender, send gender <M/F/O> where M for male, \
F for female and O for other")
def ha... |
# Radové číslovky
# Napíšte definíciu funkcie ordinal, ktorá ako argument prijme prirodzené číslo a vráti zodpovedajúcu radovú číslovku v angličtine (tj. 1st, 2nd, 3rd, 4th, 11th, 20th, 23rd, 151st, 2012th a pod.).
def ordinal(number: int) -> str:
"""
>>> ordinal(5)
'5th'
>>> ordinal(151)
'151st'
... |
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from operacion import models as operacion
class Operario(User):
turno = models.ForeignKey(operacion.Turno)
# end class
|
import numpy as np
import random
import quanguru as qt
qub1Sz = qt.tensorProd(qt.sigmaz(), qt.identity(2))
qub2Sz = qt.tensorProd(qt.identity(2), qt.sigmaz())
# store the real and imaginary parts for each coeffiecient at each step
def comp(sim, states):
st = states[0]
sim.qRes.result = ("sz1", qt.expectation(q... |
# coding: utf-8
"""
Container Security APIs
All features of the Container Security are available through REST APIs.<br/>Access support information at www.qualys.com/support/<br/><br/><b>Permissions:</b><br/>User must have the Container module enabled<br/>User must have API ACCESS permission # noqa: E501
... |
from mnist import MNIST
from galaxies import Galaxies
from mnist_pca import MnistPca
import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
def get_mnist_data(digits, num_per_digit):
mnist = MNIST()
x, y = mnist.get_flattened_train_data(digits, num_per_digit)
x_test, y_test = mnist.g... |
import pathlib
from setuptools import setup
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
# This call to setup() does all the work
setup(
name="cloudfile",
version="0.2.10",
description="Upload and restore... |
import urllib.parse
import mlflow.tracking
from mlflow.exceptions import MlflowException
from mlflow.utils.uri import get_databricks_profile_uri_from_artifact_uri, is_databricks_uri
from mlflow.entities.model_registry.model_version_stages import ALL_STAGES
_MODELS_URI_SUFFIX_LATEST = "latest"
def is_using_databrick... |
from git_remote_dropbox.constants import (
PROCESSES,
CHUNK_SIZE,
MAX_RETRIES,
)
from git_remote_dropbox.util import (
readline,
Level,
stdout,
stderr,
Binder,
Poison,
)
import git_remote_dropbox.git as git
import dropbox
import multiprocessing
import multiprocessing.dummy
import m... |
# Copyright 2018 Capital One Services, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
"""Module for fand exceptions"""
class FandError(Exception):
"""Base class for all exceptions in fand"""
class TerminatingError(FandError):
"""Daemon is terminating"""
# Communication related errors
class CommunicationError(FandError):
"""Base class for communication related errors"""
class SendRec... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Demographic',
fields=[
('raw_hispanic', models.... |
import random
import string
import time
import os
try:
import telepot
from telepot.loop import MessageLoop
except:
os.system('pip install telepot --user')
try:
import requests
except:
os.system('pip install requests --user')
class host:
def __init__(self, host):
h = ho... |
__all__ = ('ChannelMetadataGuildMainBase',)
from scarletio import copy_docs, include
from ...core import GUILDS
from ...permission import Permission
from ...permission.permission import (
PERMISSION_ALL, PERMISSION_MASK_ADMINISTRATOR, PERMISSION_MASK_VIEW_CHANNEL, PERMISSION_NONE
)
from ...permission.utils import... |
from django.shortcuts import render, redirect, get_object_or_404
from .forms import NoteModelForm
from .models import Note
# CRUD
# create, update, retrieve, delete
def create_view(request):
form = NoteModelForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.instance.user = request.user
... |
# Copyright 2020 KCL-BMEIS - King's College London
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed... |
from csv import reader, writer
from datetime import date
import os
import subprocess
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from app import db, create_app
from app.constants import FILE_HANDLES
from app.models import Users, RepExercisesTaxonomy, RepExercisesHistory, TimeExe... |
#!/usr/bin/env python
from setuptools import setup
from setuptools.extension import Extension
from setuptools.command.build_ext import build_ext
from setuptools.command.egg_info import egg_info
from setuptools.command.sdist import sdist
from distutils import errors
import os
import sys
# ========================== c... |
import datetime
import email
# import time
from datetime import datetime
from email.utils import parsedate
def convert_to_http_date_format(date_time):
# def httpdate(dt)
# https://stackoverflow.com/questions/225086/rfc-1123-date-representation-in-python
# A manual way to format it which is identical with... |
from collections import OrderedDict
from types import MethodType
from django.db.models import Field
from django.db.models import sql
from django.db.models.sql.compiler import *
class SQLCompiler:
def get_return_fields(self):
cols, params = [], []
col_idx = 1
for _, (s_sql, s_params), alia... |
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse
from django.utils import six
from django.conf import settings
import json
class OpenIDConnectConfigurationTestCase(TestCase):
"""
Test OpenIDConnectConfiguration URI
"""
def setUp(self)... |
from asciisciit import lut
import pytest
@pytest.mark.parametrize("lut_name", ("simple", "binary", "\u3105\u3106\u3107"))
def test_bars(lut_name):
lut.bars(lut_name)
def test_linear_lut():
l = lut.linear_lut("123456789")
assert(len(l._chars) == 9)
assert(len(l._bins) == 8)
def test_get_lut():
... |
import asyncio
@asyncio.coroutine
def test_async():
print((yield from func()))
@asyncio.coroutine
def func():
return "Hello, async world!"
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(test_async()) |
from math import copysign
import pxng
from pxng.colors import *
from pxng.keys import *
def update(window: pxng.Window):
handle_input(window)
window.draw_grid(tint=DARK_GREY)
window.draw_text(10, 10, 'Text Rendering', tint=LIGHT_BLUE)
# Use the bitmap font as something interesting to scroll through... |
import logging
from ..extended_properties import ExtendedProperty
from ..fields import BooleanField, ExtendedPropertyField, BodyField, MailboxField, MailboxListField, EWSElementField, \
CharField, IdElementField, AttachmentField
from ..properties import InvalidField, IdChangeKeyMixIn, EWSElement, ReferenceItemId, ... |
# ---------------------------------------------------------------------
# Iskratel.MSAN.get_version
# ---------------------------------------------------------------------
# Copyright (C) 2007-2018 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# Pyth... |
"""Write a model protocol buffer to mat file."""
from deepnet import util
import numpy as np
import sys
import scipy.io
import scipy.io as sio
import gzip
import os
def Convert(mat_file, out_file):
""" Create the necesarry things"""
matfile = sio.loadmat(mat_file)
# get the weight matrix
weight = np.... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import (absolute_import, division, print_function, unicode_literals)
|
import copy
import json
from pytests.basetestcase import BaseTestCase
from pytests.security.x509_multiple_CA_util import x509main, Validation
class MultipleCANegative(BaseTestCase):
def setUp(self):
super(MultipleCANegative, self).setUp()
self.x509 = x509main(host=self.master)
for server... |
# -*- coding=utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the ... |
# Test file for each of the component of CRUD operation of API routers |
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
# ALLOWED_HOSTS must be correct in production!
# See https://docs.djangoproject.com/en/dev/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ['*']
# Databases
DATABASES['default']['NAME'] = 'hobo'
DATABASES['default']['USER'] = 'hobo'
DATABASES[... |
import argparse
import sys
from datetime import datetime
import badget
def parse_args():
parser = argparse.ArgumentParser(
description='Simple transactional budget app',
epilog=f'Example: python3 {sys.argv[0]} "./budgets/2019" -w "2019-12-01 12:30:00" -sc -sa -v')
parser.add_argument('budget_... |
# coding: utf-8
"""
DFC
DFC is a scalable object-storage based caching system with Amazon and Google Cloud backends. # noqa: E501
OpenAPI spec version: 1.1.0
Contact: dfcdev@exchange.nvidia.com
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
... |
from segtypes.n64.segment import N64Segment
from segtypes.linker_entry import LinkerEntry
from util import options, log
class CommonSegLib(N64Segment):
def __init__(self, rom_start, rom_end, type, name, vram_start, extract, given_subalign, given_is_overlay, given_dir, args, yaml):
super().__init__(rom_st... |
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
if __name__ == '__main__':
number_of_trials = [0, 2, 10, 20, 50, 500]
data = stats.bernoulli.rvs(0.5, size=number_of_trials[-1])
x = np.linspace(0, 1, 100)
for i, N in enumerate(number_of_trials):
heads = data[:N].sum... |
import enum
class appErrorCodes(enum.Enum):
OK = 0
METER_NOT_FOUND = 431
MISSING_INPUT = 432
INVALID_INPUT = 433
BAD_DB_INSERT = 434
|
from pytorch_lightning import LightningModule
import torch
from torch.utils.data import Dataset
class RandomDataset(Dataset):
def __init__(self, size, num_samples):
self.len = num_samples
self.data = torch.randn(num_samples, size)
def __getitem__(self, index):
return self.data[index]
... |
# Generated by Django 3.0.13 on 2021-04-08 09:59
import django.db.models.deletion
import i18nfield.fields
from django.db import migrations, models
import pretix.base.models.base
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0184_customer'),
]
operations = [
mi... |
# Contains dictionaries that map English letters to braille.
letters = {
"a": chr(10241),
"b": chr(10243),
"c": chr(10249),
"d": chr(10265),
"e": chr(10257),
"f": chr(10251),
"g": chr(10267),
"h": chr(10259),
"i": chr(10250),
"j": chr(10266),
"k": chr(10245),
"l": chr(10... |
import os
import pandas as pd
import numpy as np
import warnings
import math
from sklearn.ensemble import ExtraTreesRegressor, AdaBoostRegressor, GradientBoostingRegressor, RandomForestRegressor
from sklearn.model_selection import KFold, LeaveOneGroupOut, GroupKFold
from sklearn.model_selection import cross_val_score,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.