text stringlengths 2 999k |
|---|
"""SCons.Tool.rmic
Tool-specific initialization for rmic.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007 The SCons Foundation
#
# Permission is her... |
# coding=utf-8
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
setup(
name='pubplot',
version='0.2.4',
description='Seamless LaTeX and Matplotlib integration for publication plots',
long_description=readme,
packages=find_packages(... |
import converter
converter.convert_to_utf8("splitted/%s.csv" % 'zongheng') |
from app import app
from flask_script import Manager, Server
manage = Manager(app)
# manage.add_command("runserver", Server(
# host = '0.0.0.0')
# )
if __name__ == "__main__":
manage.run()
|
# Copyright 2022 Cruise LLC
import warnings
from collections import OrderedDict
import logging
import torch.distributed as dist
import torch.distributed.algorithms.model_averaging.utils as utils
logger = logging.getLogger(__name__)
class HierarchicalModelAverager:
r"""
A group of model averagers used for hi... |
from UnetModel import *
def get_params_dict(logDir):
file = open(logDir, 'r')
logText = file.read()
file.close()
filterText = re.findall('parameters_search : (\w.*)', logText)[2:-2]
splitedText = [item.split(' : ') for item in filterText]
dictParams = dict()
for item in splitedText:
... |
from configparser import ConfigParser
from contextlib import contextmanager
import os
from dotenv import load_dotenv
from mop2.utils.atomic_writes import atomic_write
from mop2.utils.files import change_dir
CONFVARIABLES = "app.config.ini"
OPERATIONSPATH = "../../../data"
TESTVARIABLES = "test.app.config.ini"
TESTIN... |
from sqlobject import *
__connection__ = connectionForURI("sqlite:///:memory:")
hub = __connection__
class Genre(SQLObject):
name = StringCol()
artists = RelatedJoin('Artist')
class Artist(SQLObject):
name = StringCol()
genres = RelatedJoin('Genre')
albums = MultipleJoin('Album')
plays_instr... |
import numpy as np
from random import randrange
def eval_numerical_gradient(f, x, verbose=True, h=0.00001):
"""
a naive implementation of numerical gradient of f at x
- f should be a function that takes a single argument
- x is the point (numpy array) to evaluate the gradient at
"""
fx = f(x) ... |
import contextlib
import os
from typing import Optional, cast, Callable, Generator, IO, Any
from pathlib import Path
from pacu import settings
get_active_session: Optional[Callable] = None
class PacuException(Exception):
pass
def strip_lines(text: str) -> str:
out = []
for line in text.splitlines():
... |
_base_ = [
'../_base_/datasets/coco_detection.py', '../_base_/default_runtime.py'
]
model = dict(
type='SingleStageDetector',
backbone=dict(
type='MobileNetV2',
out_indices=(4, 7),
norm_cfg=dict(type='BN', eps=0.001, momentum=0.03),
init_cfg=dict(type='TruncNormal'... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 31 19:06:00 2017
@author: Thomas
"""
#%%
import numpy as np
import scipy.io
mat = scipy.io.loadmat('mnist_all.mat')
print("MAT file loaded. Contains", len(mat), "datasets. Example size:", mat['train1'].shape)
scipy.io.savemat('test.mat', mat) |
# Generated by Django 2.2.10 on 2020-10-19 16:12
from django.db import migrations
import wagtail.core.fields
class Migration(migrations.Migration):
dependencies = [
('core', '0008_remove_personpage_name'),
]
operations = [
migrations.AddField(
model_name='administrationindex... |
from dataclasses import dataclass
from openpersonen.api.enum import IndicatieGezagMinderjarigeChoices
from .in_onderzoek import GezagsVerhoudingInOnderzoek
@dataclass
class GezagsVerhouding:
indicatieCurateleRegister: bool
indicatieGezagMinderjarige: str
inOnderzoek: GezagsVerhoudingInOnderzoek
def... |
# -*- coding: utf-8 -*-
"""
chemdataextractor.tests.test_reader_els.py
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test reader for Elsevier.
Juraj Mavračić (jm2111@cam.ac.uk)
"""
import unittest
import logging
import io
import os
from chemdataextractor import Document
from chemdataextractor.reader.elsevier import ElsevierXmlRe... |
# Testing code
import numpy as np
import unittest
import subprocess
from .. import netcdf_read_write
class Tests(unittest.TestCase):
def test_pixel_node_writer(self):
"""
See if the writing function for pixel-node files produces a pixel-node file.
The behavior has been finicky for float3... |
#!/usr/bin/env python3
#
# Copyright 2021 Red Hat, Inc.
# 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
... |
from bilibili import bilibili
import datetime
import time
import asyncio
import traceback
import os
import configloader
import utils
from printer import Printer
class Tasks:
def __init__(self):
fileDir = os.path.dirname(os.path.realpath('__file__'))
file_user = fileDir + "/conf/user.conf"
... |
# -*- coding: utf-8 -*-
"""
Enforce state for SSL/TLS
=========================
"""
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
import datetime
import logging
import time
__virtualname__ = "tls"
log = logging.getLogger(__name__)
def __virtual__():
if "tls.cert... |
"""Adding feature vectors
Revision ID: f4249b4ba6fa
Revises: 863114f0c659
Create Date: 2020-11-24 14:43:08.789873
"""
import sqlalchemy as sa
from alembic import op
from mlrun.api.utils.db.sql_collation import SQLCollationUtil
# revision identifiers, used by Alembic.
revision = "f4249b4ba6fa"
down_revision = "86311... |
import warnings
import numpy as np
from .utils_moments import moments
from .velocity import velocity, ss_estimation
from .utils import (
get_mapper,
get_valid_bools,
get_data_for_kin_params_estimation,
get_U_S_for_velocity_estimation,
)
from .utils import set_velocity, set_param_ss, set_param_kinetic
fr... |
class DeviceIdentifierType:
FIT = "fit"
TCX = "tcx"
class FITDeviceIdentifier:
def __init__(self, manufacturer, product=None):
self.Type = DeviceIdentifierType.FIT
self.Manufacturer = manufacturer
self.Product = product
class TCXDeviceIdentifier:
def __init__(self, name, productId=None):
self.Type = Devic... |
import random
import json
import pickle
import numpy as np
import nltk
nltk.download('punkt')
nltk.download('wordnet')
from nltk.stem import WordNetLemmatizer
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, Dropout
from tensorflow.keras.optimizers import SGD
lemm... |
import os
import json
import numpy as np
import pandas as pd
import datetime
import SAVIZ.situation_awareness_visualization as saviz
with open("tempfile.json", 'r') as f:
json_file = f.readlines()[0]
has_type = True
has_time = False
timeRange = [0, 1]
with open("tempconfig.json", 'r') as f:
config = f.readlines... |
"""
To understand why this file is here, please read:
http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django
"""
from django.conf import settings
from django.db import migrations
def update_site_forward(apps, schema_editor):
"""Set site d... |
'''
several running examples, run with
python3 runGan.py 1 # the last number is the run case number
runcase == 1 inference a trained model
runcase == 2 calculate the metrics, and save the numbers in csv
runcase == 3 training TecoGAN
runcase == 4 training FRVSR
runcase == ... coming... data prepara... |
from django.apps import AppConfig
class MycrudappConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'mycrudApp'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:mod:`Quantulum` parser.
"""
# Standard library
import re
import logging
from fractions import Fraction
from collections import defaultdict
from math import pow
# Quantulum
from . import load
from . import regex as reg
from . import classes as cls
from . import disamb... |
from Plots import *
#PlotNearRays( measure='SM' )
PlotFarRays( measure='SM', plot_mean=True, uniform=True, save_mean=True )# False )
#PlotFarRays( measure='SM', mean=True, uniform=True, overestimate=True )
PlotFarRays( measure='DM', plot_mean=True, uniform=True, save_mean=True )# False )
#PlotFarRays( measure='DM', ... |
# --------------------------------------------------------
# Compute metrics for trackers using ground-truth data
# Written by Wang Xueyang (wangxuey19@mails.tsinghua.edu.cn), Version 20200321
# Based on motmetrics (https://github.com/cheind/py-motmetrics/)
# --------------------------------------------------------
im... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 14 11:30:55 2019
@author: Mortis Huang
"""
# import the necessary packages
from PIL import Image
import numpy as np
import datetime
import os
import pandas as pd
#%% Set the output file location
run_data = datetime.datetime.now().strftime("%Y_%m_%d")
resul... |
MAXIMUM_ARRAY_LENGTH = 1024
def Main(operation, args):
if operation == 'DynamicListTest':
return DynamicListTest()
return False
def DynamicListTest():
dynamicList = DynamicList()
added = DynamicAppend(dynamicList, 1)
assert(added)
count = len(dynamicList["packed"][0]["array"])
a... |
# 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 ... |
from agents.common import PLAYER1, PLAYER2, initialize_game_state, evaluate_antidiagonals, is_player_blocking_opponent, \
is_player_winning
def test_evaluate_antidiagonals_uppertriangle_True_Player1_is_player_blocking_opponent():
game = initialize_game_state()
num_rows = game.shape[0]
num_cols = game.... |
"""This script downloads all of the data located in the AWS S3 bucket, given the proper
access key and secret key. Assumes that this script will be run from the root of the repository.
Usage: get-data.py --access_key=<access_key> --secret_key=<secret_key>
Options:
--access_key=<access_key> The AWS access key provid... |
# Generated by Django 3.0.8 on 2020-07-22 12:11
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('Home', '0010_auto_20200722_1738'),
]
operations = [
migrations.RenameField(
model_name='student',
old_name='fathermobileno',... |
import torch
from torch import nn
from torch.nn import functional as F
from torchutils import to_device
class FocalLoss(nn.Module):
"""weighted version of Focal Loss"""
def __init__(self, alpha=.25, gamma=2, device=None):
super(FocalLoss, self).__init__()
self.alpha = torch.tensor([alpha, 1 ... |
# Natural Language Toolkit: Aligner Utilities
#
# Copyright (C) 2001-2013 NLTK Project
# Author:
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
|
from tornado.web import HTTPError
from ddtrace import config
from ...constants import ANALYTICS_SAMPLE_RATE_KEY
from ...constants import SPAN_MEASURED_KEY
from ...ext import SpanTypes
from ...ext import http
from ...propagation.http import HTTPPropagator
from .constants import CONFIG_KEY
from .constants import REQUES... |
import os
import random
import cherrypy
"""
This is a simple Battlesnake server written in Python.
For instructions see https://github.com/BattlesnakeOfficial/starter-snake-python/README.md
"""
class Battlesnake(object):
@cherrypy.expose
@cherrypy.tools.json_out()
def index(self):
# This functio... |
"""
test the group model from zoom.models
"""
import unittest
import zoom
from zoom.database import setup_test
from zoom.models import Groups
from zoom.utils import Bunch
class TestGroup(unittest.TestCase):
"""Test the Zoom Group and Groups models"""
def setUp(self):
self.db = setup_test()
... |
# -*- coding: utf-8 -*-
import util
import sys, decode, datetime, os
apikey = '*****'
apisec = '*****'
def date2int(datestr):
date = datetime.datetime.strptime(datestr, "%a %b %d %H:%M:%S %z %Y")
return date
class timeline:
time_begin = 0
time_end = 0
hashtag = ''
tweetlist = []
... |
from django.apps import AppConfig
class CranworthSiteConfig(AppConfig):
name = 'cranworth_site'
verbose_name = 'Website' |
#
#
#
import re
import random
import time
COMMA_DELIMITER_1 = ',(?=([^"]*"[^"]*")*[^"]*$)'
COMMA_DELIMITER_2 = ',(?=([^"\\]*"\\[^"\\]*"\\)*[^"\\]*$)'
#
#
def print_separator():
print(" " * 30)
print(" #" * 30)
print(" " * 30)
#
# line2 = '1;"Goroka";"Goroka";"Papua New Guinea";"GKA";"AYGA";-6.081689;145.... |
#!/usr/bin/python3
# encoding='utf-8'
# author:weibk
# @time:2021/9/23 19:10
import pymysql
import random
con = pymysql.connect(host="localhost",
user="root",
password="123456",
database="db",
charset="utf8")
cursor = con.cursor(c... |
import zipfile # noqa: F401
from zipfile import ZipFile # noqa: F401
|
from sys import maxsize
class User:
def __init__(self, firstname=None, lastname=None, address=None, email=None, email2=None, email3=None, user_id=None,
homephone=None, workphone=None, mobilephone=None, additionalphone=None,
all_phones_from_home_page=None, all_emails_from_home_pa... |
# Copyright (c) 2013 Mirantis, Inc.
#
# 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... |
'''
This Example uses scikits-learn to do a binary classfication of images
of nuts vs. bolts. Only the area, height, and width are used to classify
the actual images but data is extracted from the images using blobs.
This is a very crude example and could easily be built upon, but is just
meant to give an introductor... |
from __future__ import unicode_literals
from collections import OrderedDict
from datetime import datetime
from dateutil.tz import tzstr
import pytest
from javaproperties import PropertiesFile, dumps
INPUT = '''\
# A comment before the timestamp
#Thu Mar 16 17:06:52 EDT 2017
# A comment after ... |
import strawberry
from typing import Callable, List, Optional, Dict
import dataclasses
from . import utils, queries
@dataclasses.dataclass
class DjangoField:
resolver: Callable
field_name: Optional[str]
kwargs: dict
def resolve(self, is_relation, is_m2m):
resolver = queries.resolvers.get_resol... |
# Authored by Tiantian Liu, Taichi Graphics.
import math
import taichi as ti
ti.init(arch=ti.cpu)
# global control
paused = ti.field(ti.i32, ())
# gravitational constant 6.67408e-11, using 1 for simplicity
G = 1
# number of planets
N = 3000
# unit mass
m = 1
# galaxy size
galaxy_size = 0.4
# planet radius (for ren... |
import torch
from torch_geometric.nn.functional import gini
def test_gini():
w = torch.tensor(
[
[0., 0., 0., 0.],
[0., 0., 0., 1000.0]
]
)
assert torch.isclose(gini(w), torch.tensor(0.5))
|
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
REQUIREMENTS = [i.strip() for i in open("requirements.txt").readlines()]
setuptools.setup(
name="saltbox",
version="0.1.3",
author="Björn Orri Saemundsson",
author_email="bjornorri@gmail.com",
description="Inter... |
#!/usr/bin/env python
import sys
import base64
def jwt_base64url_decode(s: str) -> str:
return base64.urlsafe_b64decode(s + '='*(-len(s)%4))
def jwt_decode(jwt_str: str, pos: int=None,
hex_sig: bool=False, verbose: bool=False) -> str:
def _decode(s: str, pos: int) -> str:
r = jwt_base6... |
__author__ = 'Pavel Ageyev'
class Groups:
def __init__(self, name , header, footer):
self.name=name
self.header=header
self.footer=footer
class Formfields:
def __init__(self, firstName, lastName, companyName, email, mobile):
self.firstName=firstName
self.lastName=lastNa... |
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import nowdate
def update_last(doc, method):
frappe.db.sql("""update `tabVehicle Income` set age='old' where vehicle=%s
and age=%s""", (doc.vehicle, doc.age))
|
__author__ = 'dstogsdill'
_name_ = 'pypalo'
"""A Python library for interacting with Palo Alto devices"""
#: Version info (major, minor, maintenance, status)
VERSION = (0, 0, 7)
__version__ = '%d.%d.%d' % VERSION[0:3]
from .pan import Panorama
__all__ = [Panorama]
|
import numpy as np
import json
prefixes = ['softmax', 'fc', 'conv', 'max_pool', 'avg_pool', 'relu'] # TODO: ADD CONCAT
# Validate that every dictionary key is the name of a valid layer format
def validate_prefixes(names):
for name in names:
index = name.rfind('/')
if index != -1: section = name[... |
"""Unit test package for multi_notifier."""
|
default_app_config = 'glitter.blocks.form.apps.FormConfig'
|
from StringIO import StringIO
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
json = None
import unittest
from robot.utils.asserts import assert_equals, assert_raises
from robot.htmldata.jsonwriter import JsonDumper
class TestJsonDumper(unittest.Tes... |
"""A module for defining WORKSPACE dependencies required for rules_foreign_cc"""
load("//for_workspace:repositories.bzl", "repositories")
load("//toolchains:toolchains.bzl", "prebuilt_toolchains", "preinstalled_toolchains")
load(
"//tools/build_defs/shell_toolchain/toolchains:ws_defs.bzl",
shell_toolchain_work... |
# Generated by Django 2.1.1 on 2018-09-16 04:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('partners', '0002_auto_20180915_2328'),
]
operations = [
migrations.AlterField(
model_name='communitypartner',
name='... |
# 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
fro... |
import pandas as pd
import geopandas
import json
import altair as alt
def make_metrics_df():
GEOJSON = 'geojson/wi_map_plan_{}.geojson'
mm_gaps = []
sl_indices = []
efficiency_gaps = []
plan_number = [i for i in range(1,84)]
for i in range(1,84):
plan = geopandas.read_file(GEOJSON.forma... |
# The following comment should be removed at some point in the future.
# mypy: disallow-untyped-defs=False
from __future__ import absolute_import
import hashlib
import logging
import sys
from pip._internal.cli.base_command import Command
from pip._internal.cli.status_codes import ERROR
from pip._internal.... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-10-08 15:32
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gram', '0011_auto_20181008_1505'),
]
operations = [
migrations.AlterField(
... |
import sys
import os
import json
import azure.functions as func
import google.protobuf as proto
import grpc
# Load dependency manager from customer' context
from azure_functions_worker.utils.dependency import DependencyManager as dm
def main(req: func.HttpRequest) -> func.HttpResponse:
"""This function is an Htt... |
# coding: utf-8
"""
"""
import logging
from .utils import find_migrations, should_skip_by_index, update_migration_index
def run(db):
logger = logging.getLogger('sampledb.migrations')
for index, name, function in find_migrations():
logger.info('Migration #{} "{}":'.format(index, name))
# Sk... |
import sys, fileinput, json
import numpy as np
fir_p = {} # 某字符出现在句首的概率对数 {str: float}
dou_count = {} # 字符的二元出现次数 {(str, str): int}
tri_count = {} # 字符的三元出现次数 {str: {str: {str: int}}}
sin_count = {} # 字符出现计数 {str: int}
pch = {} # 拼音到字符的dict {pinyin: [chs]}
sin_total = 396468407
def preload3():
def add3(dic... |
#!/usr/bin/env python3
# Copyright (c) 2014-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the rawtransaction RPCs.
Test the following RPCs:
- createrawtransaction
- signrawtransacti... |
# Generated by Django 2.1.15 on 2020-12-12 13:14
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0009_alter_user_last_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
... |
from typing import List, Optional
import aiosqlite
from btcgreen.util.db_wrapper import DBWrapper
from btcgreen.util.ints import uint32
from btcgreen.wallet.util.wallet_types import WalletType
from btcgreen.wallet.wallet_action import WalletAction
class WalletActionStore:
"""
WalletActionStore keeps track o... |
import math
import random
import geocoder
import gpxpy.geo
from geopy import Point, distance
from s2sphere import CellId, LatLng
from .custom_exceptions import GeneralPogoException
from .util import is_float
DEFAULT_RADIUS = 70
# Wrapper for location
class Location(object):
def __init__(self, locationLookup, geo_k... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
from pygcgen import ChangelogGenerator
base_options = [
"--quiet",
# "-h",
# "-v",
# "-vv", # or "-v", "-v",
# "-vvv",
# "--options-file", ".pygcgen_example",
# "-u", "topic2k",
# "-p", "pygcgen",
# '-s', "*... |
import numpy as np
import pandas as pd
def tanhderiv(K):
"""
used to calculate the derivative of tanh function.
"""
return 1- (np.tanh(K)**2)
def initialisetheta(m,n,nodes,yn):
"""
used to randomly initialise the weights matrix and store it in the
form of a list. Note that the bias term has been directly a... |
"""
Logistic Regression
"""
# Author: Gael Varoquaux <gael.varoquaux@normalesup.org>
# Fabian Pedregosa <f@bianp.net>
# Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Manoj Kumar <manojkumarsivaraj334@gmail.com>
# Lars Buitinck
# Simon Wu <s8wu@uwaterloo.ca>
# ... |
# Generated by Django 2.1.4 on 2019-02-09 15:20
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('society_bureau', '0002_sitesettings'),
]
operations = [
migrations.AlterFi... |
"""The dagster-airflow operators."""
from dagster_airflow.operators.util import invoke_steps_within_python_operator
from dagster_airflow.vendor.python_operator import PythonOperator
class DagsterPythonOperator(PythonOperator):
def __init__(self, dagster_operator_parameters, *args, **kwargs):
def python_ca... |
# Copyright(C) 2011, 2015, 2018 by
# Ben Edwards <bedwards@cs.unm.edu>
# Aric Hagberg <hagberg@lanl.gov>
# Konstantinos Karakatsanis <dinoskarakas@gmail.com>
# All rights reserved.
# BSD license.
#
# Authors: Ben Edwards (bedwards@cs.unm.edu)
# Aric Hagberg (hagberg@lanl.gov)
# Ko... |
import os
import sys
path = os.environ.get('TRAVIS_BUILD_DIR')
sys.path.insert(0, path+'/protlearn')
import numpy as np
from preprocessing import txt_to_df
from feature_engineering import length
def test_lengths():
"Test sequence lengths"
# load data
df = txt_to_df(path+'/tests/docs/test_seq.txt', 0... |
import gym
import matplotlib.pyplot as plt
import numpy as np
import time
import brs_envs
env = gym.make('RocketLanderBRSEnv-v0',
render=True,
max_lateral_offset=0,
max_pitch_offset=0,
max_roll_offset=0,
max_yaw_offset=0,
mean_r... |
from classes.Humanoid import Humanoid
class Player(Humanoid):
def __init__(self, name, room, dmg=1, hp=10):
super().__init__(name, room, dmg, hp)
self.equipped = None
def __str__(self):
return f'{self.name}: ', '{\n', f'\t[\n\t\thp: {self.hp}/{self.max_hp},\n\t\tdmg: {self.dmg}\n\tequ... |
from ravenrpc import Ravencoin
import ipfshttpclient
from credentials import USER, PASSWORD
rvn = Ravencoin(USER, PASSWORD)
ipfs = ipfshttpclient.connect()
ASSETNAME = "POLITICOIN"
IPFSDIRPATH = "/opt/squawker/ipfs"
|
from django.contrib import admin
# Register your models here.
from library.models import Book, Author
@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
list_display = ('name', 'id', 'author', 'publication_date', 'is_active')
@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
list_display =... |
# -*- coding: utf-8-*-
import random
import re
from client import jasperpath
import RPi.GPIO as GPIO
import time
import sys
import vibrate
WORDS = ["HELLO"]
def handle(text, mic, profile):
vibrate.retrieve_from_DOA('low')
print("hello module")
mic.say('hello')
def isValid(text):
... |
from unittest import mock
import pytest
from django.http import Http404
from know_me import serializers, views
def test_get_queryset(api_rf, km_user_accessor_factory, km_user_factory):
"""
The queryset for the view should include all accessors granting
access to the requesting user's Know Me user.
"... |
"""Tests for 1-Wire sensor platform."""
from unittest.mock import patch
from pyownet.protocol import Error as ProtocolError
import pytest
from homeassistant.components.onewire.const import (
DEFAULT_SYSBUS_MOUNT_DIR,
DOMAIN,
PLATFORMS,
)
from homeassistant.components.sensor import ATTR_STATE_CLASS, DOMAIN... |
import uuid
from django.test import TestCase, SimpleTestCase
from casexml.apps.case.exceptions import IllegalCaseId
from casexml.apps.case.mock import CaseBlock
from casexml.apps.case.models import CommCareCase
from casexml.apps.case.xform import CaseDbCache
from casexml.apps.case.xml import V2
from corehq.form_process... |
import unittest
import os
import sys
import subprocess
from dimod import sym, BINARY, INTEGER, ConstrainedQuadraticModel
from job_shop_scheduler import JSSCQM
from data import Data
import utils.plot_schedule as job_plotter
project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
class TestSmoke(un... |
from IPython.display import Image
#%matplotlib inline
from distutils.version import LooseVersion as Version
from sklearn import __version__ as sklearn_version
#Image(filename='./images/10_01.png', width=500)
import pandas as pd
df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/'
... |
import numpy as np
import pandas as pd
from weatherClass import weatherClass
from IdentifierClass import identifierClass
from eventsClass import eventsClass
import datetime
### load some data:
#read the ticket+complaint data, combined for location:
# events fields: date, lat, lng, address, identifier, index
tem... |
from datetime import datetime
from unittest.mock import ANY, patch
from django.urls import reverse
from django.utils.dateparse import parse_datetime
from rest_framework import status
from internal.tests.base_test import tz
from playlist.date_stop import KARAOKE_JOB_NAME, clear_date_stop
from playlist.models import Ka... |
# -*- coding: utf-8 -*-
"""
Salt compatibility code
"""
# pylint: disable=import-error,unused-import,invalid-name,W0231,W0233
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import binascii
import logging
import sys
# Import 3rd-party libs
from salt.exceptions import Sal... |
import pygame
class ControlManager(object):
@classmethod
def up(cls):
raise NotImplementedError('Error: Abstract class')
@classmethod
def down(cls):
raise NotImplementedError('Error: Abstract class')
@classmethod
def left(cls):
raise NotImplementedError('E... |
import random
import mysql.connector
import yaml
from os import path as os_path
config_path = os_path.abspath(os_path.join(os_path.dirname(__file__), 'config.yml'))
data = yaml.safe_load(open(config_path))
def extract_fact(user_id):
mydb = mysql.connector.connect(
host=data['DB_HOST'],
user=data['DB_USERNAME'... |
import json
import logging
import random
import requests
from hashlib import sha1 as sha_constructor
from django.conf import settings
from gluu_ecommerce.connectors.uma_access import obtain_authorized_rpt_token
logger = logging.getLogger('idp')
SCIM_CREATE_USER_ENDPOINT = 'https://idp.gluu.org/identit... |
"""
CryptoAPIs
Crypto APIs 2.0 is a complex and innovative infrastructure layer that radically simplifies the development of any Blockchain and Crypto related applications. Organized around REST, Crypto APIs 2.0 can assist both novice Bitcoin/Ethereum enthusiasts and crypto experts with the development of thei... |
"""Standalone Authenticator."""
import collections
import errno
import logging
import socket
from typing import Any
from typing import Callable
from typing import DefaultDict
from typing import Dict
from typing import Iterable
from typing import List
from typing import Mapping
from typing import Set
from typing import ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.