content stringlengths 5 1.05M |
|---|
"""
PyGirl Emulator
Audio Processor Unit (Sharp LR35902 APU)
There are two sound channels connected to the output
terminals SO1 and SO2. There is also a input terminal Vin
connected to the cartridge. It can be routed to either of
both output terminals. GameBoy circuitry allows producing
sound in four different ways:... |
from Bio.Blast.Applications import NcbiblastpCommandline, NcbiblastnCommandline, NcbimakeblastdbCommandline
class Blast:
'''
class for each column of line from blast = 8 or blast+ = 6
'''
def __init__(self, line, q, db):
blastSplit = line.split("\t")
self.parsed = blastSplit
... |
# Powered by https://newsapi.org
# Import essentials
import requests
import json
import os
from pymessenger.bot import Bot
from pymessenger import Element
# Definitons
class getNewsHeadlines:
# Get news headlines from various news sources
def __init__(self):
self.inp = 'news_sources'
self.o... |
import json
from mcoding_youtube.app_config import config
from mcoding_youtube.youtube import paginated_results, get_authenticated_readonly_service
def dump_json_to_file(obj, filename):
with open(filename, 'w', encoding='utf-8') as f:
json.dump(obj, f)
def get_my_uploads_playlist_id(youtube):
# see... |
import numpy as np
a = np.array([[1,-3,-2],[0,2,4],[0,0,-10]])
print("A :",a)
b = np.array([7,4,12])
c = np.linalg.solve(a,b)
print("C :",c)
|
class DataNotFound(RuntimeError):
pass
class DataError(RuntimeError):
pass
class InvalidAge(RuntimeError):
pass
class InvalidMeasurement(RuntimeError):
pass |
import os
import sys
import dynaconf
def test_djdt_382(tmpdir):
settings_file = tmpdir.join("settings.py")
settings_file.write("\n".join(["SECRET_KEY = 'dasfadfds2'"]))
tmpdir.join("__init__.py").write("")
os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
sys.path.append(str(tmpdir))
__import... |
"""
Solve a problem with SLOPE and compare to R
"""
from __future__ import print_function
import numpy as np
import nose.tools as nt
try:
import rpy2.robjects as rpy
rpy2_available = True
import rpy2.robjects.numpy2ri
from rpy2.robjects.packages import importr
from rpy2 import robjects
except Imp... |
import math
from annogesiclib.gff3 import Gff3Parser
from annogesiclib.lib_reader import read_libs, read_wig
def read_gff(input_file):
datas = []
gff_parser = Gff3Parser()
f_h = open(input_file, "r")
for entry in gff_parser.entries(f_h):
entry.attributes["print"] = False
datas.append(e... |
class Clock(object):
def __init__(self):
self.igt = None
self.rta = None
|
from setuptools import setup
package_name = 'cair_client'
setup(
name=package_name,
version='0.0.0',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
],
ins... |
# 487. Max Consecutive Ones II
# Runtime: 388 ms, faster than 37.74% of Python3 online submissions for Max Consecutive Ones II.
# Memory Usage: 14.4 MB, less than 27.64% of Python3 online submissions for Max Consecutive Ones II.
class Solution:
# Linear Scan
def findMaxConsecutiveOnes(self, nums: list[int])... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 23 16:15:51 2018
@author: jean-mi
"""
import IsochroneClass as IC
import sys
sys.path.append("../model")
from weatherTLKT import Weather
import numpy as np
import simulatorTLKT as SimC
from simulatorTLKT import Simulator
import matplotlib.pyplot as... |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.7
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (2, 6, 0):
def swig_import_helper():
from os.path imp... |
#!/usr/bin/env monkeyrunner
import time
... |
"""Authentication & Authorization."""
from conduit.auth.models import User
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.config import Configurator
from pyramid.request import Request
from pyramid.security import Allow
import typing as t
def includeme(config: Configurator) -> None:
"""Py... |
from functools import wraps
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql import expression
from sqlalchemy.types import DateTime
from pygmy.config import config
def dbconnection(func):
@wraps(func)
def _wrapped(*args, **kwargs):
try:
... |
import asyncio
import random
import sqlite3
from pathlib import Path
import aiosqlite
import pytest
from achi.consensus.blockchain import Blockchain
from achi.full_node.block_store import BlockStore
from achi.full_node.coin_store import CoinStore
from achi.util.db_wrapper import DBWrapper
from tests.setup_nodes impor... |
"""Estimates the semilinear Choo and Siow homoskedastic (2006) model
using Poisson GLM.
"""
from typing import Optional
from math import sqrt
import numpy as np
import scipy.linalg as spla
import scipy.sparse as spr
from sklearn import linear_model
from .matching_utils import Matching, _make_XY_K_mat, _variance_muhat... |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 ... |
import csv
import hashlib
import io
import os
import random
import re
import time
from functools import partial
from multiprocessing import current_process
from typing import Dict
from urllib.parse import urlparse
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
import requests... |
import cv2
import numpy as np
img = cv2.imread("ferrari.jpg", 0)
row, col = img.shape
M = np.float32([[1, 0, 53], [0, 1, 35]])
dst = cv2.warpAffine(img, M, (row, col))
cv2.imshow("dst", dst)
cv2.waitKey(0)
cv2.destroyAllWindows() |
import networkx as nx
from Bio import SeqIO
G = nx.DiGraph()
seq_DNA = {}
for seq_record in SeqIO.parse("rosalind_grph.txt", "fasta"):
G.add_node(seq_record.id)
seq_DNA[seq_record.id] = str(seq_record.seq)
for i in seq_DNA.keys():
for j in seq_DNA.keys():
if i != j:
if seq_DNA[i][-3:... |
#!/usr/bin/python2.6
'''
### SEYED YAHYA NIKOUEI
dns2proxy for offensive cybersecurity v1.0
python dns2proxy.py -h for Usage.
Example:
python2.6 dns2proxy.py -i eth0 -u 192.168.1.101 -d 192.168.1.200
Example for no forwarding (only configured domain based queries and spoofed hosts):
python2.6 dns2proxy.py -i et... |
import asyncio
import functools
def futurized(o):
''' Makes the given object to be awaitable.
:param any o: Object to wrap
:return: awaitable that resolves to provided object
:rtype: asyncio.Future
Anything passed to :code:`futurized` is wrapped in :code:`asyncio.Future`.
This makes it await... |
from items.Item import Item, Cool_Down_Item
from items.Amplifying_Tome import Amplifying_Tome
class Fiendish_Codex(Item, Cool_Down_Item):
def __init__(self):
Item.__init__(self, name='Fiendish Codex', code=3108, cost=900, sell=630)
self.sub_items = [Amplifying_Tome()]
def stats(self, champ):
champ.ap_dmg += 3... |
class SingletonMeta(type):
def __getattr__(cls, name):
return (super() if name == "INSTANCE" else cls.INSTANCE).__getattribute__(name)
def __setattr__(cls, name, value):
(super() if name == "INSTANCE" else cls.INSTANCE).__setattr__(name, value)
class Singleton(metaclass = SingletonMeta):
def ... |
import plt_tools
import numpy as _np
def clouds():
bmax = plt_tools.colors.Color((0 ,0 ,0.1))
bmin = plt_tools.colors.Color((0 ,0 ,1))
colors = _np.array([bmin.rgb , bmax.rgb])
cmap = plt_tools.colormap.creat_cmap(colors=colors, norm = 'linear',
log_min= 0.1,
... |
from api.models.attachments import Attachment # noqa: F401
from api.models.platform_settings import PlatformPost # noqa: F401
from api.models.publications import Publication # noqa: F401
|
from __future__ import generator_stop
from typing import Tuple
from genutility.fileformats.srt import MalformedFile, SRTFile
from plug import Filetypes
@Filetypes.plugin(["srt"])
class SRT(object):
def __init__(self):
pass
def validate(self, path, ext):
# type: (str, str) -> Tuple[int, str]
try:
with ... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Donny You(youansheng@gmail.com)
# Loss function for Semantic Segmentation.
import torch
import torch.nn as nn
import torch.nn.functional as F
class FSCELoss(nn.Module):
def __init__(self, configer=None):
super(FSCELoss, self).__init__()
self... |
# Crowdsrc imports
from crowdsrc.src.models import *
from crowdsrc.src.serializers import *
from crowdsrc.settings import CREATE, DELETE
from .views import *
# Django imports
from django.db.models import Count, Prefetch
from rest_framework.generics import GenericAPIView, ListAPIView, UpdateAPIView
from rest_framework.... |
import logging
from dataclasses import dataclass
from pathlib import PurePath
from pants.core.goals.package import BuiltPackage, BuiltPackageArtifact
from pants.core.util_rules.external_tool import (DownloadedExternalTool,
ExternalToolRequest)
from pants.core.util_rules... |
import logging
import os
import threading
import webbrowser
from typing import Any, Dict, List
import toml
import typer
import uvicorn
from fps_uvicorn.config import UvicornConfig
from fps.config import Config
from fps.logging import configure_loggers, get_loggers_config
from fps.utils import merge_dicts
app = typer... |
#!/usr/bin/env python3
# Copyright 2017 Jian Wang
# License: Apache 2.0.
import os
import argparse
import sys
sys.stdout = open(1, 'w', encoding='latin-1', closefd=False)
import re
tab_or_space = re.compile('[ \t]+')
parser = argparse.ArgumentParser(description="This script get a vocab from unigram counts "
... |
import os
import pytest
from datadog_checks.dev import docker_run
from .common import INSTANCES
HERE = os.path.dirname(os.path.abspath(__file__))
DOCKER_DIR = os.path.join(HERE, 'docker')
@pytest.fixture(scope='session', autouse=True)
def dd_environment():
flavor = os.getenv('FLAVOR', 'default')
instance =... |
from ..api import get_many, ApiVersion, int_field, date_field
from datetime import date
from typing import Iterator, List, Optional
class OckovaniDistribuceSklad:
""" Přehled distribuce očkovacích látek v ČR z centrálního skladu
Datová sada obsahuje přehled distribuce očkovacích látek proti onemocnění COVID-1... |
from sklearn.utils import all_estimators
from sklearn.utils.estimator_checks import _construct_instance
from sklearn.utils._testing import SkipTest
from docutils import nodes
from contextlib import suppress
from docutils.parsers.rst import Directive
class AllowNanEstimators(Directive):
@staticmethod
def make... |
# --------------
import pandas as pd
from sklearn.model_selection import train_test_split
#path - Path of file
# Code starts here
df=pd.read_csv(path)
X=df.drop(['customerID','Churn'], 1).copy()
y=df.Churn
X_train,X_test,y_train,y_test=train_test_split(X, y, test_size = 0.3, random_state = 0)
# --------------
imp... |
from unet3d.config import load_config
import os
import torch
import torch.nn as nn
import datetime
from datasets.hdf5 import BratsDataset
from unet3d.model import get_model
from unet3d import utils
from tensorboardX import SummaryWriter
from visualization import board_add_images, board_add_image
def get_job_name():
... |
import mock
import unittest
from tests.tests_data import fake_talk_json
from tests.tests_data import fake_empty_talk_json
from worker.api import API
def mocked_requests_get(*args, **kwargs):
class MockResponse:
def __init__(self, json_data, status_code):
self.json_data = json_data
... |
from __future__ import print_function, division
from evoltier.optimizer import Optimizer
from evoltier.model.bernoulli import Bernoulli
class BernoulliNaturalGradientOptimizer(Optimizer):
def __init__(self, weight_function, lr, distribution=None, dim=None):
if dim is None and distribution is None:
... |
# 802.1X Authentication
|
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
x=""
k=0
while k<(min(len(word1),len(word2))):
x+=word1[k]+word2[k]
k+=1
if word1:
x+=word1[len(word2):]
if word2:
x+=word2[len(word1):]
return x... |
expected_output = {
"acl": {
"acl_name": {"total_aces_configured": 1},
"ipv4_ext": {"total_aces_configured": 0},
},
"attachment_points": {
"Ethernet1/1": {
"egress": {
"ipv4_acl": {
"total_aces_configured": 3,
"activ... |
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children if children is not None else []
"""
class Solution:
def findRoot(self, tree: List['Node']) -> 'Node':
node_indegree = {}
for node in tr... |
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in ... |
# undervolt.py
"""
Undervolt related stuff
"""
import os
import sys
import pathlib
import argparse
import thinkpad_tools_assets.classes
from thinkpad_tools_assets.utils import ApplyValueFailedException, NotSudo
try:
if os.getuid() != 0:
raise NotSudo("Script must be run as superuser/sudo")
except NotSud... |
from flask import Flask, render_template, redirect, url_for, request, flash
from sqlalchemy import Column, Integer, String, ForeignKey, Text, DateTime
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext import wtf
from flask.ext.login import LoginManager, login_required, UserMixin, login_user, logout_user
from d... |
# Automagic LatLong Stereo for Maxwell Studio
# --------------------------------------------
# 2015-11-30 9:15 am v0.3
# By Andrew Hazelden
# Email: andrew@andrewhazelden.com
# Blog: http://www.andrewhazelden.com
# Description
# -----------
# The automagicLatLongStereo.py script is used to quickly prepare your Maxwel... |
#!/usr/bin/env python3
import numpy as np
import torch
from itypes import TorchStruct
device = torch.device('cuda:0')
print()
s = TorchStruct(dims="hwc")
s.x = torch.tensor([[[1, 2, 3], [4, np.nan, np.inf]]], device=device)
s.y = TorchStruct(dims="hwc")
s.y.z = torch.tensor([[7, 8, 9], [10, np.nan, np.inf]], device=... |
import pygame as pg
import logging
from random import randint
from flappy.configs.configs import Configs
from flappy.controlador.pg_utils import carregar_sprites, som
from flappy.entidades.flappy import Flappy
from flappy.entidades.score import Score
from flappy.entidades.terreno import Terreno
from flappy.entidades.ca... |
from django.contrib import admin
from . import models
@admin.register(models.Cabinet)
class CabinetAdmin(admin.ModelAdmin):
list_display_links = ('cabinet_number', )
search_fields = ('cabinet_number', )
list_filter = ('cabinet_set__branch', )
list_display = ('id', 'cabinet_number', 'cabinet_set', ... |
import numpy as np #https://numpy.org/
import chemparse #https://pypi.org/project/chemparse/
from mendeleev import element #https://github.com/lmmentel/mendeleev
version = 0.12
date = "02/2022"
def printHelp():
'''Print the help dialog'''
print('================= Manuca Help =================')
print('Usa... |
"""Definition of command codes used in communication with APNs."""
NOTIFICATION = 2
ERROR_RESPONSE = 8
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import requests
from addthis.exceptions import AddthisError, AddthisValidationError
class Addthis(object):
"""Base class that keeps authentication parameters and instantiates
an ``AddthisEndpoint`` object.
"""
def __ini... |
# Please run bert-serving-start before running this notebook
# Setup: https://github.com/hanxiao/bert-as-service
# Examples (change folders to your locals)
# english cased: bert-serving-start -model_dir /bert-as-service/cased_L-24_H-1024_A-16/ -num_worker=4
# multi cased: bert-serving-start -model_dir /bert-as-service/... |
from machine import Pin, I2C
from neopixel import NeoPixel
from time import sleep, ticks_ms, ticks_diff
import framebuf
import gc
import sh1106
# Wemos pins - for our and our users' convenience
D0 = const(16)
D1 = const(5)
D2 = const(4)
D3 = const(0)
D4 = const(2)
D5 = const(14)
D6 = const(12)
D7 = const(13)
D8 = con... |
# https://deeplearningcourses.com/c/artificial-intelligence-reinforcement-learning-in-python
# https://www.udemy.com/artificial-intelligence-reinforcement-learning-in-python
#from __future__ import print_function, division
#from builtins import range
# Note: you may need to update your version of future
# sudo pip inst... |
# -*- coding: utf-8 -*-
"""Test the evaluators."""
import dataclasses
import logging
import unittest
from typing import Any, ClassVar, Dict, Mapping, Optional, Tuple, Type
import torch
from pykeen.datasets import Nations
from pykeen.evaluation import Evaluator, MetricResults, RankBasedEvaluator, RankBasedMetricResu... |
# -*- coding: utf-8 -*-
import socket
from threading import Lock
def public_ipv4():
"""
take first public interface
sorted by getaddrinfo - see RFC 3484
should have the real public IPv4 address as first address.
At the moment the test layer is not able to handle v6 addresses
"""
for addri... |
# -*- coding: utf8 -*-
"""
This is part of shot detector.
Produced by w495 at 2017.05.04 04:18:27
"""
from __future__ import absolute_import, division, print_function
from .base_shot_detector import BaseShotDetector
class CommonDetector(BaseShotDetector):
"""
...
"""
pass
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 3rd party imports
from matplotlib.transforms import TransformedBbox, blended_transform_factory
from mpl_toolkits.axes_grid1.inset_locator import (BboxPatch, BboxConnector,
BboxConnectorPatch)
__author__ = "Louis Richard... |
def test_concurrent_fixture(testdir):
testdir.makepyfile("""
import pytest
import time
from six import print_
@pytest.fixture
def driver(request):
fn_name = request.function.__name__
if fn_name == 'test_1':
time.sleep(.05)
... |
import torch.nn as nn
import torch
from ..modeling.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d
def init_params(models, mode='xv'):
assert mode in {'xv', 'net2net'}
if not isinstance(models, list):
models = [models]
for model in models:
for m in model.modules():
if isinstance(m, (nn.C... |
def parse_delaunay(fname):
import h5py
import numpy
res = {}
with h5py.File(fname,'r+') as f:
for field in f:
res[field] = numpy.array(f[field])
res['facets'] = numpy.reshape(res['triangles'],(-1,3))
return res
def locate_point(x_list, y_list, xp, yp, tol = 1e-10):
im... |
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
import util
import copy
def merge(a, b, idx=None):
i = 0
j = 0
n = len(a)
m = len(b)
c = []
while i < n and j < m:
if a[i] <= b[j]:
c.append(a[i])
if idx is not None:
i... |
#!/usr/bin/env python3
import PySimpleGUI as sg
# This example would work great as A desktop
# double-click executable in windows. Just
# create shortcut(send-to Desktop) this file,
# and run it using pythonw.exe(no prompt) instead
# of python.exe(or open-with).
# Change default in files properties.
# Two arguments a... |
"""phial Slack Bot."""
from phial.bot import Phial
from phial.globals import command
from phial.scheduler import Schedule
from phial.wrappers import Attachment, Message, PhialResponse, Response
__version__ = "0.10.1"
__all__ = [
"Phial",
"command",
"Response",
"Attachment",
"Schedule",
"Message... |
from CGSearchRace.Unit import Unit
class Checkpoint(Unit):
def __init__(self, x, y):
super().__init__(x, y)
|
from . import sparsematrix
import numpy as np
import numpy.random as npr
import scipy as sp
import scipy.sparse
from . import simplefac
import sys
import tensorflow as tf
def test_sparse():
A=npr.randn(30,42)
A[npr.randn(*A.shape)>0]=0
A=sp.sparse.csr_matrix(A)
A2=sparsematrix.SparseMatrix.from_scipy_s... |
"""
フォントリスト表示
"""
import tkinter as tk
from tkinter.constants import HORIZONTAL, VERTICAL
import tkinter.font
import sys
class FontLib():
"""
フォントリスト表示用クラス
"""
def __init__(self, text:str="sample サンプル ", font_size:int=14) -> None:
"""
コンストラクタ
Args:
str: 出力文字
... |
import discord
import pytest
import discord.ext.test as dpytest
@pytest.mark.asyncio
async def test_message(bot):
guild = bot.guilds[0]
channel = guild.text_channels[0]
await channel.send("Test Message")
@pytest.mark.asyncio
async def test_embed(bot):
guild = bot.guilds[0]
channel = guild.text_... |
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager
)
import datetime
"""
CITIES AND COUNTRIES
1. cities = > name country longitude latitude
2. countries = > name iso1 iso2 phone currency
"""
class Country(models.Model):
name = models.CharField(max_lengt... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
from os import path
import requests
from settings import ES_HOST as HOST
from settings import INDEX
# (unguarded) singleton for lazy init
MAPPINGS = None
def delete_index(host, index_name):
index_res = requests.delete(path.join(host, index_name))
if n... |
import Core.Projection as core
import numpy as np
def getRaw2D(points, view):
points2d = []
for el in points:
points2d.append(el.get2d(view))
raw = []
for el in points2d:
raw.append([el.x, el.y])
return np.array(raw, dtype=np.int64)
class AnchorPointsManager:
def __init__(se... |
from compas_ags.diagrams import FormDiagram
from compas_ags.diagrams import ForceDiagram
from compas_igs.rhino import Scene
from compas.rpc import Proxy
import compas_rhino
from compas_igs.utilities import compute_force_drawinglocation
from compas_igs.utilities import compute_force_drawingscale
from compas_igs.utiliti... |
from unittest import TestCase
from Interpretator import *
class InterpretatorTest(TestCase):
def testEmpty(self):
pass
|
#!/usr/bin/env python
"""
@file coi-services/mi/idk/platform/driver_generator.py
@author Bill French
@brief Generate directory structure and code stubs for a driver
"""
__author__ = 'Bill French'
__license__ = 'Apache 2.0'
import os
import sys
import re
from string import Template
import random
import string
import... |
from dexy.exceptions import UserFeedback
from dexy.filters.git import repo_from_path
from dexy.filters.git import repo_from_url
from dexy.filters.git import generate_commit_info
from tests.utils import assert_in_output
from tests.utils import runfilter
from tests.utils import tempdir
from nose.exc import SkipTest
impor... |
import warnings
from functools import partial
from typing import Any, Optional, Union
from torchvision.transforms.functional import InterpolationMode
from ....models.quantization.inception import (
QuantizableInception3,
_replace_relu,
quantize_model,
)
from ...transforms.presets import ImageNetEval
from ... |
# TEST GPU SET UP via commands
'''
run commands below:
1. nvcc -V --> nvidia cuda compiler driver
2. nvidia-smi --> about GPU
cudNN version can be found at C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\include\cudnn.h as below:
#define CUDNN_MAJOR 7
#define CUDNN_MINOR 6
#define CUDNN_PATCHL... |
import asyncio
import inspect
async def main():
pass
print(type(main))
print(inspect.iscoroutinefunction(main))
print(type(main()))
print(dir(main()))
|
from typing import Iterable
from django.db import models
from django.contrib.auth.models import User
class Player(models.Model):
address = models.CharField(max_length=200)
city = models.CharField(max_length=200)
state = models.CharField(max_length=2)
zipcode = models.CharField(max_length=10)
home... |
import logging
import logging.handlers
import os
import os.path
import exiftool
import numpy as np
import requests
from scipy.spatial import distance
import ownphotos.settings
logger = logging.getLogger("ownphotos")
fomatter = logging.Formatter(
"%(asctime)s : %(filename)s : %(funcName)s : %(lineno)s : %(levelna... |
import urllib.request, urllib.error, urllib.parse
from bs4 import BeautifulSoup
import string
import json
import requests
import calendar
def _getVanilla():
url = "https://launchermeta.mojang.com/mc/game/version_manifest.json"
f = json.loads(requests.get(url).text)
versions = []
for v in f['versions'... |
# Copyright (c) 2022 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 appli... |
class Caesar:
def __init__(self, shift):
self.shift = shift
def crypt(self, inputString, decrypt=False):
message = [ord(c) for c in inputString]
result = []
for i in range(len(message)):
if decrypt:
result.append((message[i] - self.shift)%111... |
# warncheck.py
#
import warnings
import unittest
from sys import version_info
from dicom.test.version_dep import capture_warnings
def assertWarns(self, warn_msg, function, *func_args, **func_kwargs):
"""
Check that the function generates the expected warning
with the arguments given.
warn_msg -- part... |
import time
#This class is a singletion class
#timer: calcualte the time elasepd between each 2 call
#In this project is used to calculte the fps of the video
#or camear, and the fps of captured face frame
class timer():
__instance = None
@staticmethod
def timerInstance():
if timer.__instance ... |
from google.appengine.ext import db
from catnado.properties.key_property import KeyProperty
class UniquePropertyRecordExistsError(Exception):
"""Raise when attempting to create a property that already exists."""
pass
class UniquePropertyRecord(db.Model):
"""Datastore model for keeping particular properties ... |
import tempfile
from dffml.record import Record
from dffml.source.source import Sources
from dffml import train, accuracy, predict
from dffml.util.asynctestcase import AsyncTestCase
from dffml.source.memory import MemorySource, MemorySourceConfig
from dffml_model_transformers.qa.qa_model import QAModel, QAModelConfig
... |
"""Main file
N-word Counter bot
"""
import os
from json import load
from pathlib import Path
import discord
from discord.ext import commands
# Fetch bot token.
with Path("../config.json").open() as f:
config = load(f)
TOKEN = config["DISCORD_TOKEN"]
# Me and my alt account(s).
owner_ids = (354783154126716938, ... |
import heapq
from collections import namedtuple
Node = namedtuple('Node', ('weight','index'))
def read_file(name):
"""Given the path/name of the text file, return the heap with nodes.
"""
tree = []
file = open(name, 'r')
data = file.readlines()
for index, line in enumerate(data[... |
from typing import Optional, List
from rlai.actions import Action
from rlai.meta import rl_text
@rl_text(chapter='States', page=1)
class State:
"""
State.
"""
def is_feasible(
self,
a: Action
) -> bool:
"""
Check whether an action is feasible from the curr... |
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you ma... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class UnfreezeOrderDetail(object):
def __init__(self):
self._alipay_order_no = None
self._create_time = None
self._memo = None
self._merchant_order_no = None
sel... |
import langbrainscore
import xarray as xr
from langbrainscore.interface.encoder import _Encoder
class BrainEncoder(_Encoder):
"""
This class is used to extract the relevant contents of a given
`langbrainscore.dataset.Dataset` object and maintains the Encoder interface.
"""
def __init__(self) -> "... |
# 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 may ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.