text stringlengths 2 999k |
|---|
#!/usr/bin/env python
# coding: utf-8
# # Robot Class
#
# In this project, we'll be localizing a robot in a 2D grid world. The basis for simultaneous localization and mapping (SLAM) is to gather information from a robot's sensors and motions over time, and then use information about measurements and motion to re-cons... |
# mssql/information_schema.py
# Copyright (C) 2005-2013 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
# TODO: should be using the sys. catalog with SQL Server, not information ... |
from .base import LinearRegression |
from __future__ import annotations
import dataclasses
import re
from collections import defaultdict
from types import MappingProxyType
from typing import Dict, List, ClassVar, Pattern, Match, Mapping, Set, Optional
from urllib import parse
from typic.util import cached_property, slotted
from .secret import SecretStr
... |
from __future__ import division
import contextlib
import json
import numbers
try:
import requests
except ImportError:
requests = None
from jsonschema import _utils, _validators
from jsonschema.compat import (
Sequence, urljoin, urlsplit, urldefrag, unquote, urlopen,
str_types, int_types, iteritems, l... |
def infoGAN_encoder(params,is_training):
is_training = tf.constant(is_training, dtype=tf.bool)
def encoder(x):
with tf.variable_scope('model/encoder',['x'], reuse=tf.AUTO_REUSE):
net = lrelu(conv2d(x, 64, 4, 4, 2, 2, name='conv1', use_sn=True))
net = conv2d(net, 128, 4, 4, 2... |
"""
Copyright (C) 2018-2019 Intel Corporation
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 wri... |
# stdlib
from typing import Any
from typing import List
from typing import Optional
# third party
from google.protobuf.reflection import GeneratedProtocolMessageType
# syft relative
from ... import deserialize
from ... import serialize
from ...core.common import UID
from ...core.store.storeable_object import Storable... |
from BaseSpacePy.model.AppSessionSemiCompact import AppSessionSemiCompact
class AppSession(AppSessionSemiCompact):
'''
Returned from getAppSessionById() and getAppSesssion()
'''
def __init__(self):
self.swaggerTypes = {
'Id':'str',
'Href': 'str',
'Type': 'st... |
# -*- coding: utf-8 -*-
# MUC component service.
#
# Copyright (c) 2005-2013 Christopher Zorn
# See LICENSE.txt for details
from twisted.words.protocols.jabber import jid, xmlstream
from twisted.internet import defer
from twisted.python import components, log
from twisted.words.xish import domish
try:
from twiste... |
import ctypes
import glob
import os
from ctypes import wintypes
_GetShortPathNameW = ctypes.windll.kernel32.GetShortPathNameW
_GetShortPathNameW.argtypes = [
wintypes.LPCWSTR,
wintypes.LPWSTR,
wintypes.DWORD,
]
_GetShortPathNameW.restype = wintypes.DWORD
from mlshim.consts import _APPDATA
fr... |
# Generate a portmantout word
# Peter Norvig
# See https://github.com/norvig/pytudes/blob/master/ipynb/Portmantout.ipynb
from collections import defaultdict, Counter
from typing import List, Tuple, Set, Dict, Any
Word = str
class Wordset(set): """A set of words."""
Step = Tuple[int, str] # An (overlap, word) pair.
O... |
#!/usr/bin/env python3
# Copyright (c) 2014-2020 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:
- getrawtransaction
- createrawtransactio... |
import json
import plotly
import pandas as pd
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
from flask import Flask
from flask import render_template, request, jsonify
from plotly.graph_objs import Bar
from sklearn.externals import joblib
from sqlalchemy import create_engine
app = ... |
# model settings
model = dict(
type='FasterRCNN',
pretrained='/mnt/workspace/hrnetv2_w32_imagenet_pretrained.pth',
backbone=dict(
type='SyncHighResolutionNet',
extra=dict(
stage1=dict(
num_modules=1,
num_branches=1,
block='BOTTLENEC... |
from PyQt5.QtWidgets import QTreeWidgetItem, QTreeWidget
from PyQt5.QtCore import Qt
class QtTreeWidgetPrinter:
def __init__(self):
pass
@staticmethod
def printer(widget: QTreeWidget):
for i in range(widget.topLevelItemCount()):
QtTreeWidgetPrinter.dig_item(widget.topLevelIte... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import click
from PIL import Image
from utils.misc import get_file_list
@click.command()
@click.argument('path', type=click.Path(exists=True))
def is_eq_size(path):
"""
Test all pictures in folder (recursive) for size equality.
"""
files = get_file_list(p... |
from easygraphics.turtle import *
import random
def random_move(d1, d2, a1, a2):
while is_run():
d = random.randint(a1, a2)
lt(d)
fd(random.randint(d1, d2))
create_world(800, 600)
set_speed(10)
random.seed()
# random_move(1,10,0,10)
# random_move(1,10,-10,5)
random_move(1, 10, -10, 10)... |
import unittest
import test.test_support
mutex = test.test_support.import_module("mutex", deprecated=True)
class MutexTest(unittest.TestCase):
def test_lock_and_unlock(self):
def called_by_mutex(some_data):
self.assertEqual(some_data, "spam")
self.assertTrue(m.test(), "mutex not ... |
# 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 ... |
import requests
domain = 'ucdenver.instructure.com'
token = ''
course_id = '' # course id
response = requests.get('https://'+domain+'/api/v1/courses/'+course_id+'/analytics/activity', headers={'Authorization': 'Bearer '+token})
print response.status_code
print response.json()
|
import os
from cs50 import SQL
from flask import Flask, flash, jsonify, redirect, render_template, request, session
# Configure application
app = Flask(__name__)
# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True
# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///birthd... |
# 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 ... |
#!/usr/bin/env python
###############################################################################
# #
# stackedBarGraph.py - code for creating purdy stacked bar graphs #
# ... |
from functools import wraps
from django.core.cache import cache as djcache
from django.core.cache import caches
from django.conf import settings
from django.db.models import Q
from django.core.cache.backends.base import BaseCache
from typing import cast, Any, Callable, Dict, Iterable, List, Optional, Union, Set, Typ... |
# Copyright 2013-2018 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Opus(AutotoolsPackage):
"""Opus is a totally open, royalty-free, highly versatile audio co... |
from django.urls import path
from etat_civil.deeds.views import (
geojson_view,
flowmap_flows_view,
flowmap_locations_view,
)
app_name = "deeds"
urlpatterns = [
path("flowmap/flows/", view=flowmap_flows_view, name="flowmap_flows"),
path("flowmap/locations/", view=flowmap_locations_view, name="flo... |
def Proposal_layer(preprocessed_inputs, box_encodings, class_prediction):
from platformx.plat_tensorflow.tools.processor.test.test_tf_custom_layer import TensorflowProposal
image_shape = preprocessed_inputs.shape
inputs = [
class_prediction,
box_encodings,
image_shape
... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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 a... |
import numpy as np
import pandas as pd
from gym.utils import seeding
import gym
from gym import spaces
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pickle
# shares normalization factor
# 100 shares per trade
HMAX_NORMALIZE = 100
# initial amount of money we have in our account
INITIAL... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Make a sample animation."""
import argparse
from cairomovie import anim
class Animation(anim.Animation):
def duration(self, config):
return 10
def draw_frame(self, c, t, config):
"""Draw one animation frame to the cairo context."""
c.... |
# Copyright 2018 Google 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
##########################################################################
#
# Copyright (c) 2007-2010, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redis... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-02-09 12:49
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Dummy... |
# Copyright 2018-2021 Xanadu Quantum Technologies 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 or... |
# Generated by Django 3.2.4 on 2021-07-30 21:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0012_favorite'),
]
operations = [
migrations.AddField(
model_name='manga',
name='is_mature',
fie... |
# 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... |
#!/usr/bin/env python
# Copyright (c) 2018-2019 Intel Corporation
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
"""
This module contains the result gatherer and write for CARLA scenarios.
It shall be used from the ScenarioManager only.
"""
impo... |
# Django settings for testrunner project.
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
PERSON_ACCOUNT_ACTIVATED = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'salesforce_testrunner_db',
},
#... |
# This is the Python adaptation and derivative work of Myia (https://github.com/mila-iqia/myia/).
#
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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 ... |
"""
This module defines QuarelWorld, with a simple domain theory for reasoning about
qualitative relations.
"""
from typing import List, Dict, Set
import re
from nltk.sem.logic import Type
from overrides import overrides
from allennlp.semparse import util as semparse_util
from allennlp.semparse.contexts.knowledge_gra... |
# sdr.py - top level of instantiated Verilog SDR function
# 2020-08-16 E. Brombaugh
from migen import *
from litex.soc.interconnect.csr import AutoCSR, CSRStorage, CSRField, CSRStatus
class sdr(Module, AutoCSR):
def __init__(self, adc_pins, pdm_pins):
# DDC control registers
self.ddc_fre... |
"""Preprocessing functions and pipeline
The pipeline is three steps
1) create / load tasks, which includes
a) load raw data
b) tokenize raw data
2) create / load all vocabularies (word, char, task-specific target vocabs)
a) count tokens of a vocab
b) take the N most frequent tok... |
def plotclaw():
"""
Basic plotting script. Execute from unix by
$ python plotclaw.py
Additional plot parameters are set in setplot.py.
"""
from pyclaw.data import ClawPlotData
from pyclaw.plotting import printframes
plotdata = ClawPlotData()
plotdata.plotdir = 'plots' # ... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'poormans_twitter.settings')
try:
from django.core.management import execute_from_command_line
ex... |
from io import StringIO
import os
import unittest
import sys
import yaml
import mock
from tests.mock_data import *
import maccli.service.macfile
import maccli.helper.macfile
import maccli.dao.inheritance
from maccli.helper.exception import MacParseEnvException, MacParseParamException
class MacfileServiceTestCase(un... |
#-*- coding: utf-8 -*-
from django.db import models
# Create your models here.
#######################用户信息#############################################################
class userpwd(models.Model):
username= models.CharField(max_length=30)
userpwd = models.CharField(max_length=50)
usermail= models.CharField... |
#! /usr/bin/env python
"""
Created on Mon Jan 4 2016
Anna M. Kedzierska
"""
from matplotlib import pyplot
from shapely.geometry import LineString
from descartes.patch import PolygonPatch
BLUE = '#6699cc'
GRAY = '#999999'
def lines_multiplot(list_in, list_out, out_name):
line_in = LineString(list_in)
line_out ... |
__author__ = "Marc-André Vigneault"
__copyright__ = "Copyright 2019, Marc-André Vigneault"
__credits__ = ["Marc-André Vigneault"]
__license__ = "GPL"
__version__ = "0.1"
__maintainer__ = "Marc-André Vigneault"
__email__ = "marc-andre.vigneault@ulaval.ca"
__status__ = "Production"
from PyQt5.QtWidgets import QApplicati... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="card-game-engine", # Replace with your own username
version="0.0.1",
author="Karthik Raveendran",
author_email="karthik.panicker@gmail.com",
description="A card game engine",
long_desc... |
from .client import Client
from .connection import *
from .http_requests import *
|
# Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not u... |
import os
import sdl2
from math import ceil
from ui_element import UIElement
from art import UV_FLIPY
from key_shifts import SHIFT_MAP
from image_convert import ImageConverter
from palette import PaletteFromFile
from image_export import export_still_image, export_animation
from renderable_sprite import SpriteRender... |
"""trydjango URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/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')
Class-bas... |
from random import randint
import matplotlib.pyplot as plt
def generate_list(length: int) -> list:
"""Generate a list with given length with random integer values in the interval [0, length]
Args:
length (int): List length
Returns:
list: List generated with random values
"""
retu... |
from test.support import verbose, TestFailed
import locale
import sys
import test.support as support
import unittest
maxsize = support.MAX_Py_ssize_t
# test string formatting operator (I am not sure if this is being tested
# elsewhere but, surely, some of the given cases are *not* tested because
# they crash python)
... |
#!/usr/bin/env python3
import binascii
import packbits
import serial
import sys
import time
import bluetooth
from labelmaker_encode import encode_raster_transfer, read_png, unsigned_char
from text_to_image import label
STATUS_OFFSET_BATTERY = 6
STATUS_OFFSET_EXTENDED_ERROR = 7
STATUS_OFFSET_ERROR_INFO_1 = 8
STATUS_O... |
"""croundfunding URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/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')
Class... |
import sys
from json import load
from math import floor
import os
from PIL import Image
import requests
import tensorflow as tf
def fail_for_missing_file():
print('You must provide the path to export.json file.')
sys.exit(1)
if __name__ == '__main__':
if len(sys.argv) < 2:
fail_for_missing_file... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import mock
import requests
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from .. import models
from .helpers import mock_re... |
# Generated by Django 3.0.3 on 2020-04-06 08:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0006_logentry_outingreason'),
]
operations = [
migrations.AlterField(
model_name='logentry',
name='crowded_p... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
img=cv2.imread("photos/mycat.jpg")
#cv2.imshow("my cat",img)
#resize
resize=cv2.resize(img,(700,500))
cv2.imshow("resize",resize)
#gray scale
gray=cv2.cvtColor(resize,cv2.COLOR_BGR2GRAY)
cv2.imshow("gray",gray)
#blur
blur=cv2.GaussianBl... |
from pretf.aws import terraform_backend_s3
def pretf_blocks(var):
yield terraform_backend_s3(
bucket="pretf-examples-aws",
dynamodb_table="pretf-examples-aws",
key="terraform.tfstate",
region=var.aws_region,
**var.aws_credentials["nonprod"],
)
|
# -*- coding: utf-8 -*-
"""Supports ACE Magnetometer data
Properties
----------
platform
'ace' Advanced Composition Explorer
name
'mag' Magnetometer
tag
- 'realtime' Real-time data from the Space Weather Prediction Center (SWPC)
- 'historic' Historic data from the SWPC
inst_id
- ''
Note
----
This ... |
"""
Copyright Digisim, Computer Architecture team of South China University of Technology,
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
... |
#
# Module for starting a process object using os.fork() or CreateProcess()
#
# multiprocessing/forking.py
#
# Copyright (c) 2006-2008, R Oudkerk
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
... |
# Copyright (c) 2016-2021, Thomas Larsson
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of con... |
class Splitter(object):
def __init__(self, data):
n_data = len(data)
n_test = int(n_data * 0.15)
n_dev = int(n_data * 0.15)
n_train = n_data - (n_test + n_dev)
self.train = data[:n_train]
self.dev = data[n_train:n_train+n_dev]
self.test = data[n_train+n_dev:]... |
from django.shortcuts import render
from home.views import BaseView
# Create your views here.
class AgendaView(BaseView):
template_name = 'agenda/agenda.html'
title = 'Agenda'
def get(self, request, *args, **kwargs):
context = self.get_context_data()
context['title'] = self.title + ' - ' +... |
# attempt at writing some of the declarative helpers and tie them into the
# context and the reactor. This is a bit of a first attempt.
# Note files here needs tests before going into the library.
import collections
import os
import json
import yaml
from charmhelpers.core import hookenv
import reactor
def config... |
import os
import nibabel as nib
import numpy as np
import tables
from .training import load_old_model
from .utils import pickle_load
from .utils.patches import reconstruct_from_patches, get_patch_from_3d_data, compute_patch_indices
from .augment import permute_data, generate_permutation_keys, reverse_permute_data
d... |
import io
import os
import base64
from io import StringIO
from pathlib import Path
from typing import Dict, List
import dash
import dash_html_components as html
import flask
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
from pangtreebuild.affinity_tree.parameters import B... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
"""Agent wrapper for CyberBattle envrionments exposing additional
features extracted from the environment observations"""
import numpy
from cyberbattle._env.cyberbattle_env import EnvironmentBounds
from typing import Optional, List
import enum
i... |
import pandas as pd
from ast import literal_eval
from pprint import pprint
from nltk.tokenize import TweetTokenizer
import re
tTokenizer = TweetTokenizer()
def csv_to_df(data):
train = pd.read_csv("tsd_" + data + ".csv")
train["spans"] = train.spans.apply(literal_eval)
return train
def separate_spans(df):
sep_sp... |
"""Runway config file module."""
# pylint: disable=super-init-not-called,too-many-lines
from typing import (Any, Dict, List, Optional, # pylint: disable=unused-import
Union, Iterator, TYPE_CHECKING)
# python2 supported pylint is unable to load this when in a venv
from distutils.util import strtobo... |
# ==============================================================================
# Load data
# Copyright 2017 Kyoto Univ. Okuno lab. . All Rights Reserved.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __fut... |
from django.db import models
class Position(models.Model):
title = models.CharField(max_length=100, null=True, blank=True)
def __str__(self):
return self.title
class Gender(models.Model):
g_type=(
( "Male" , "Male"),
( "Female" , "Female"),
( "Other's" , "Other's")
)
gende... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from abc import abstractmethod
from compas.utilities import is_color_rgb
from .artist import Artist
class NetworkArtist(Artist):
"""Artist for drawing network data structures.
Parameters
-------... |
# Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from color import Color
import unittest
class ColorTest(unittest.TestCase):
def testHexColors(self):
c = Color('#0102ff')
self.assertEq... |
# Copyright 2020 Antonin Jousson
#
# 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 the "license" file accompanying this file. This fi... |
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def preorder(self):
print(self.value),
if self.left: self.left.preorder()
if self.right: self.right.preorder()
def invert(node):
right = node.right
left = no... |
from astropy import units as u
from astropy.coordinates import Angle
from astropy.time import Time
from ctapipe.io.eventsource import EventSource
from ctapipe.io.containers import DataContainer
from ctapipe.instrument import TelescopeDescription, SubarrayDescription
__all__ = ['HESSIOEventSource']
class HESSIOEventS... |
import os
import datetime
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'fake-key'
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django... |
# P3405 [USACO16DEC]Cities and States S https://www.luogu.com.cn/problem/P3405
from typing import Dict
N = int(input())
cities: Dict[str, Dict[str, int]] = {}
for _ in range(N):
city = input()
city_name, state_code = city.split()
city_abbr = city_name[:2]
if state_code in cities:
state = citie... |
#!/usr/bin/env python
import hashlib
import json
import logging
import os
import sys
import urllib
from functools import wraps
import bcrypt
import sqlite3
from flask import Flask, session, request, redirect, render_template, g, abort
from flask import make_response
import db
import settings
app = Flask(__name__)
ap... |
"""
Class containing error conditions that are exposed to the user.
"""
import click
class ConfigException(click.ClickException):
"""
Exception class when configuration file fails checks.
"""
class UserException(click.ClickException):
"""
Base class for all exceptions that need to be surfaced t... |
# Game states
INTRO = 'intro'
LVLSELECT = 'levelselecting'
MAPSELECT = 'mapselecting'
HOLD = 'hold'
PLAYING = 'playing'
WINNING = 'winning'
SURRENDER = 'surrender'
GAMEOVER = 'gameover'
# Level gameplay
INP = 'INPUT'
LVL1 = 'Level_1'
LVL2 = 'Level_2'
LVL3 = 'Level_3'
LVL4 = 'Level_4'
MAPNO1 = 5
MAPNO2... |
from enum import Enum
from typing import (
List,
Optional,
)
from pydantic import (
BaseModel,
Field,
)
from galaxy.schema.fields import (
EncodedDatabaseIdField,
ModelClassField,
)
from galaxy.schema.schema import (
GroupModel,
UserModel,
)
QUOTA_MODEL_CLASS_NAME = "Quota"
USER_QUOTA... |
import datetime
import requests
class Popads():
def __init__(self, token):
self.token = token
def report_advertiser(self, quick):
url = 'https://www.popads.net/api/report_advertiser'
query = {
"key": self.token,
'groups': 'campaign,datetime:day',
... |
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
convert = {
'M': 1000,
'D': 500,
'C': 100,
'L': 50,
'X': 10,
'V': 5,
'I': 1
}
integer = 0
prev = N... |
"""
Unused: initial very slow version using PIL before I used matplotlib
"""
from PIL import Image
class ImageIter:
def __init__(self, fname=None, inst=None):
"""
Create a PIL PyAccess.PyAccess-like object that has a few improvements.
Create from an image on file (fname) or from a PIL.Ima... |
def setup ():
size (300, 300)
smooth ()
strokeWeight (30)
stroke (100)
#noLoop ()'
def draw ():
background (0)
line(frameCount ,100, 100+ frameCount , 200)
line (100+ frameCount ,100, frameCount , 200)
#println(frameCount)'
|
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modif... |
try:
# from urllib3.request import urlopen
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
import os
import urlparse
import tarfile
import sys
import shutil
import tempfile
import platform
import subprocess
import time
import fnmatch
import signal
from sys import argv
from su... |
# -*- coding: utf-8 -*-
"""
Module for managing the LXD daemon and its containers.
.. versionadded:: 2019.2.0
`LXD(1)`_ is a container "hypervisor". This execution module provides
several functions to help manage it and its containers.
.. note::
- `pylxd(2)`_ version >=2.2.5 is required to let this work,
... |
#!/usr/bin/python
"""Utility functions for rgi parser"""
import json
# gets value from row
def get_cell(sheet, row, col):
"""Get excel cell value, convert floats to floats and pass missing values"""
val = sheet.cell(row, col).value
# cast e.g. "12.0" as string
if type(val) is float:
val = "%... |
# *****************************************************************************
# * | File : epd2in13_V2.py
# * | Author : Waveshare team
# * | Function : Electronic paper driver
# * | Info :
# *----------------
# * | This version: V4.0
# * | Date : 2019-06-20
# # | Info : ... |
from __future__ import with_statement
from functools import partial
import numpy as np
from ...._common import get_label_length, open_file
from ..._common import read_record
from .._common import to_output
__all__ = [
"read",
]
def read(filename, file_type, file_format, labels_order, label_length=None):
"... |
"""
This file offers the methods to automatically retrieve the graph Devosia sp. 172E8.
The graph is automatically retrieved from the STRING repository.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datetime: 2021-02-0... |
#!/usr/bin/env python
'''
Copyright (C) 2020, WAFW00F Developers.
See the LICENSE file for copying permission.
'''
NAME = 'PT Application Firewall (Positive Technologies)'
def is_waf(self):
schemes = [
self.matchContent(r'<h1.{0,10}?Forbidden'),
self.matchContent(r'<pre>Request.ID:.{0,10}?\d{4}\-... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.