text stringlengths 2 999k |
|---|
from __future__ import print_function
import os
import sys
import json
import yaml
from twisted.python import usage
from twisted.internet import defer, task, reactor
from ooni.constants import CANONICAL_BOUNCER_ONION
from ooni.reporter import OONIBReporter, OONIBReportLog
from ooni.utils import log
from ooni.settin... |
"""empty message
Revision ID: 34531bfd7cab
Revises: bb91fb332c36
Create Date: 2018-03-19 16:59:42.235474
"""
from alembic import op
import sqlalchemy as sa
from GeoHealthCheck.migrations import alembic_helpers
# revision identifiers, used by Alembic.
revision = '34531bfd7cab'
down_revision = 'bb91fb332c36'
branch_la... |
"""Common test functions."""
from unittest.mock import MagicMock, PropertyMock, patch
import pytest
from supervisor.bootstrap import initialize_coresys
# pylint: disable=redefined-outer-name
@pytest.fixture
def docker():
"""Mock Docker API."""
with patch("supervisor.coresys.DockerAPI") as mock:
yie... |
"""Bayesian encoding and decoding"""
__all__ = ['decode1D',
'decode2D',
'k_fold_cross_validation',
'cumulative_dist_decoding_error_using_xval',
'cumulative_dist_decoding_error',
'get_mode_pth_from_array',
'get_mean_pth_from_array']
import numpy as np
f... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
if __name__ == '__main__':
# Ввести список одной строкой.
a = list(map(int, input().split()))
# Если список пуст, завершить программу.
if not a:
print("Заданный список пуст", file=sys.stderr)
exit(1)
# Определить индексы минимального и ма... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Train a network across multiple GPUs.
"""
import contextlib
import logging
import sys
import time
from argparse import Namespace
from ite... |
"""initial
Revision ID: 54df04b13657
Revises:
Create Date: 2018-09-17 19:19:36.655516
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '54df04b13657'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated ... |
# 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 python2
# OpenPOWER Automated Test Project
#
# Contributors Listed Below - COPYRIGHT 2017
# [+] International Business Machines Corp.
#
#
# 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 Lic... |
#------------------------------------------------------------------------------
# pycparser: c_generator.py
#
# C code generator from pycparser AST nodes.
#
# Eli Bendersky [https://eli.thegreenplace.net/]
# License: BSD
#------------------------------------------------------------------------------
from . import c_ast... |
import fakeid
import unittest
from json import loads
class FakeIdTestCase(unittest.TestCase):
def setUp(self):
fakeid.app.config['TESTING'] = True
self.app = fakeid.app.test_client()
def test_landing(self):
result = self.app.get('/')
assert result.status_code == 200
def ... |
"""
Убраны часовые пояса
Revision ID: aff6badb8f87
Revises: 22d32aac74f7
Create Date: 2021-09-07 01:05:37.881411
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'aff6badb8f87'
down_revision = '22d32aac74f7'
branch_labels = None
depends_on = None
def upgrade()... |
from os import path
from urlparse import urlparse
from random import sample, randrange
from jinja import Environment, FileSystemLoader
from werkzeug import Response, Local, LocalManager, cached_property
from werkzeug.routing import Map, Rule
TEMPLATE_PATH = path.join(path.dirname(__file__), 'templates')
STATIC_PATH = ... |
# Based Plugins
# Ported For Lord-Userbot By liualvinas/Alvin
# If You Kang It Don't Delete / Warning!! Jangan Hapus Ini!!!
from userbot import CMD_HANDLER as cmd
from userbot import CMD_HELP, bot
from userbot.events import poci_cmd
@bot.on(poci_cmd(outgoing=True, pattern=r"xogame(?: |$)(.*)"))
async def _(event):
... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
# Given a string, return a "rotated left 2" version where the first 2 chars are moved to the end. The string
# length will be at least 2.
#
# left2('Hello') → 'lloHe'
# left2('java') → 'vaja'
# left2('Hi') → 'Hi'
def left2(str):
return str[2:] + str[:2]
|
from torch import nn
from torch.nn import init
import torch.nn.functional as F
from core.config import cfg
from modeling.generate_anchors import generate_anchors
from modeling.generate_proposals import GenerateProposalsOp
from modeling.generate_proposal_labels import GenerateProposalLabelsOp
import modeling.FPN as FPN... |
# 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
from ... import _utilities, _tables
from... |
from channels.db import database_sync_to_async
from .exceptions import ClientError
from .models import Game
@database_sync_to_async
def get_game_or_error(game_id, user):
if not user.is_authenticated:
raise ClientError("USER_HAS_TO_LOGIN")
try:
game = Game.objects.get(pk=game_id)
except Game... |
def prepare_data(data_df):
data_df['male'] = data_df.apply(lambda row: row['gender'] == "Male", axis=1)
data_df['female'] = data_df.apply(lambda row: row['gender'] == "Female", axis=1)
data_df['partner'] = data_df.apply(lambda row: row['Partner'] == "Yes", axis=1)
data_df['dependents'] = data_df.apply(l... |
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import os, socket
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URI']
db = SQLAlchemy(app)
hostname = socket.gethostname()
@app.route('/')
def index():
return 'Hello, from sunny %s!\n' % hostname
@app.route('/d... |
#!/usr/bin/env python3
# Copyright (c) 2019 The Zcash developers
# Copyright (c) 2020 The PIVX developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or https://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import GamefragTestFramework
from test_f... |
# 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
from ... import _utilities, _tables
from... |
import os
import xml.etree.ElementTree as ET
from PIL import Image
from tqdm import tqdm
from utils.utils import get_classes
from utils.utils_map import get_coco_map, get_map
from frcnn import FRCNN
if __name__ == "__main__":
'''
Recall和Precision不像AP是一个面积的概念,在门限值不同时,网络的Recall和Precision值是不同的。
... |
# Generated by Django 2.1.15 on 2022-02-08 05:37
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',
... |
#!/usr/bin/env python3
import numpy as np
matrix = np.array([[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12],
[13, 14, 15, 16, 17, 18], [19, 20, 21, 22, 23, 24]])
mat1 = matrix[1:3]
mat2 = matrix[:, 2:4]
mat3 = matrix[1:, 3:]
print("The middle two rows of the matrix are:\n{}".format(mat1))
print("The middl... |
import argparse
import time
import csv
import yaml
import os
import logging
from pathlib import Path
import numpy as np
from tqdm import tqdm
from tensorboardX import SummaryWriter
import cv2
import matplotlib.pyplot as plt
class plot_results(object):
def __init__(self, frame_list=[100], mode='base'):
#... |
class _GLUECLAMP_:
_imports_ = (
'_root:os',
'_root:webbrowser',
)
default_doc_file = 'guppy.html'
def doc(self, subject=None, *args, **kwds):
"""\
This doesnt work well or at all
There are painful were where-to-find the files issues
for the distributed ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Auther: Xiaowei Deng
#
# This file is part of Mini Proxy Pool
#
# This program is free software and it is distributed under
# the terms of the MIT license. Please see LICENSE file for details.
from .sqlitedb import SqliteDB
import logging
import miniproxypo... |
from collections import Counter
with open('wordlist.txt') as f:
letters = f.read().replace('\n', '')
f.seek(0)
words = f.readlines()
c = Counter(letters)
def score_word(word, c):
score = 0
for l in set(word):
score += c[l]
return score
words.sort(key=lambda x: score_word(x, c), rever... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from calaccess_raw import models
from .base import BaseAdmin
@admin.register(models.RawDataVersion)
class RawDataVersionAdmin(BaseAdmin):
list_display = (
"id",
"release_datetime"... |
# Source : https://leetcode.com/problems/power-of-two/
# Author : foxfromworld
# Date : 27/11/2021
# First attempt
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return not (n & (n-1)) if n > 0 else 0
|
import sys
from s3sync.main import main
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
|
#!/usr/bin/env python
#
# AzureMonitoringLinuxAgent Extension
#
# Copyright 2019 Microsoft 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/L... |
# tutorialTestClasses.py
# ----------------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to
... |
"""
ASGI config for collabinn project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SET... |
from user_script import operate_on_bits
import sys
import json
import base64
import math
import binascii
import os
BIT_MASKS = [
0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01
]
INVERSE_BIT_MASKS = [
0x7f, 0xbf, 0xdf, 0xef, 0xf7, 0xfb, 0xfd, 0xfe
]
class OperationCancelled(Exception):
"""Raised when the ... |
from pyrogram import Client as LuciferMoringstar_Robot, filters as Worker
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from pyrogram.errors import UserIsBlocked, PeerIdInvalid
from LuciferMoringstar_Robot.database.autofilter_db import is_subscribed, get_file_details
from LuciferMoringstar_Robot... |
from typing import TYPE_CHECKING, Any, Optional, Type, Union, cast
from pypika import Case, Table, functions
from pypika.functions import DistinctOptionFunction
from pypika.terms import ArithmeticExpression
from pypika.terms import Function as BaseFunction
from tortoise.exceptions import ConfigurationError
from torto... |
model = dict(
type='FastRCNN',
backbone=dict(
type='ResNet3dSlowFast',
pretrained=None,
resample_rate=4,
speed_ratio=4,
channel_ratio=8,
slow_pathway=dict(
type='resnet3d',
depth=50,
pretrained=None,
lateral=True,
... |
from django.http import HttpResponse
from cms.test_utils.testcases import CMSTestCase
from cms.test_utils.util.mock import AttributeObject
from menus.templatetags.menu_tags import PageLanguageUrl
from menus.utils import (simple_language_changer, find_selected,
language_changer_decorator)
cla... |
#!/usr/bin/python
#
# Copyright (c) 2009 Google 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:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of ... |
"""
WSGI config for socialApp project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SET... |
#!/usr/bin/env python2.7
from __future__ import print_function
import os
from pddlstream.algorithms.search import solve_from_pddl
from pddlstream.algorithms.focused import solve_focused
from pddlstream.algorithms.incremental import solve_incremental
from pddlstream.utils import print_solution, read
def read_pddl(... |
import pygame
import sys
pygame.init()
screen = pygame.display.set_mode((640, 480))
#right = pygame.transform(screen, 45)
#left = pygame.transform(screen, -45)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# screen.fill((255,0,0))
screen.fill((40, ... |
import pytest
from ..validators import DictListValidator, Field, TextField, TimestampField
def test_dict_list_validator_eq_with_empty_instances():
assert DictListValidator({}) == DictListValidator({})
def test_dict_list_validator_eq_with_simple_equal_instances():
a = DictListValidator({
'foo': Time... |
import unittest
from strix.gca import GCA
from strix.file_formats import csv
from tests.file_formats.variables import csv_vars, gca_vars
class TestFromGCA(unittest.TestCase):
def test_from_gca_point(self):
# Valid Point
pt = GCA(gca_vars.pt_geom, gca_vars.pt_coords, gca_vars.pt_attrs)
sel... |
import time
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer, test as _test
from SocketServer import ThreadingMixIn
import BaseHTTPServer
from urlparse import urlparse, parse_qs
from selenium import webdriver
import numpy as np
import PIL
import re
from PIL import Image
from PIL import ImageFile
import thr... |
# encoding: utf-8
# Identifier, Equivalency
import logging
import random
from abc import ABCMeta, abstractmethod
from collections import defaultdict
from functools import total_ordering
from urllib.parse import quote, unquote
import isbnlib
from sqlalchemy import (
Boolean,
Column,
Float,
ForeignKey,
... |
from django.http import HttpResponse
from django.shortcuts import render
import pandas_gbq
from google.oauth2 import service_account
import json
import sys
import os
# Make sure you have installed pandas-gbq at first;
# You can use the other way to query BigQuery.
# please have a look at
# https://cloud.google.com/big... |
""" Init file for Netwave Camera """
from .netwave import NetwaveCamera
__all__ = ['NetwaveCamera']
|
#-*-coding:utf-8-*-
# date:2020-03-28
# Author: xiang li
import torch # 加载torch库
import numpy as np # 加载Numpy库
if __name__ == "__main__":
print(torch.__version__)# 查看 torch 版本
print('-----------------------')
y = torch.rand(2,3)# 随机矩阵
print(y)
print(y.size())
print('----------------... |
# coding=utf-8
import os,subprocess,time
import pub.settings as s
import pub.functions.token as t
tmp_path = os.path.join(s.EXE_PATH,'tmp')
compiler = os.path.join(s.EXE_PATH,'EG.exe')
reference = os.path.join(s.EXE_PATH,'src.pub.dll')
def compile(code):
_clean_tmp()
filename = _get_random_file_name('.cs')
... |
from django.apps import AppConfig
class RiskConfig(AppConfig):
name = 'risk'
|
#!/usr/bin/env python3
import os
import subprocess
schemadir = os.path.join(os.environ["MESON_INSTALL_PREFIX"], "share", "glib-2.0", "schemas")
if not os.environ.get("DESTDIR"):
print("Compiling gsettings schemas...")
subprocess.call(["glib-compile-schemas", schemadir])
|
"""
Transcritical flow over a bump without a shock.
Ref1: Houghton & Kasahara, Nonlinear shallow fluid flow over an isolated ridge.
Comm. Pure and Applied Math. DOI:10.1002/cpa.3160210103
Ref2: Delestre et al, 2012, SWASHES: a compilation of shallow water
analytic solutions..., Int J Numer Meth Fluids, DOI:10.10... |
from nose2.tools.decorators import with_teardown
from smb.SMBConnection import SMBConnection
from smb import smb_structs
from .util import getConnectionInfo
conn, conn2, conn3 = None, None, None
def teardown_func():
global conn, conn2, conn3
if conn:
conn.close()
if conn2:
conn2.close()
... |
import pytest
# from app import application as flask_app
from app.application import app as flask_app
@pytest.fixture
def app():
yield flask_app
@pytest.fixture
def client(app):
return app.test_client() |
import codecs
import re
import textwrap
from typing import Dict
import warnings
import numpy as np
import pandas._libs.lib as lib
import pandas._libs.ops as libops
from pandas.util._decorators import Appender, deprecate_kwarg
from pandas.core.dtypes.common import (
ensure_object, is_bool_dtype, is_categorical_dt... |
import torch as th
import torch.nn as nn
import argparse
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
from torch.utils.data import DataLoader, TensorDataset
import pandas as pd
import numpy as np
import copy
class Net(nn.Module):
def __init__(self, ... |
from .DVGeo import DVGeometry
from .DVGeoAxi import DVGeometryAxi
try:
from .DVGeoVSP import DVGeometryVSP
except ImportError:
pass
try:
from .DVGeoESP import DVGeometryESP
except ImportError:
pass
|
#!/usr/bin/env python3
"""
Downloads the latest Polymer v1 iconset version for materialdesignicons.com
"""
import os
import re
import requests
import sys
GETTING_STARTED_URL = ('https://raw.githubusercontent.com/Templarian/'
'MaterialDesign/master/site/getting-started.savvy')
DOWNLOAD_LINK = re... |
import re
"""
Determine whether a protein function is hypothetical.
"""
def is_hypothetical(func):
"""
Returns True if the function is hypothetical. Otherwise returns false
:param func: string
:return: boolean
"""
if not func: return True
if func.lower() == 'hypothetical protein': retu... |
# Copyright (c) 2019 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 app... |
import speech_recognition as sr
from pydub import AudioSegment
import os
from datetime import date
import sounddevice as sd
from scipy.io.wavfile import write
from random import choice, randint
import pyttsx3
import time
import webbrowser
from playsound import playsound
# Commands
hello = ["hi", "Hi", "hello", "Hello... |
"""
Log parsing exceptions
"""
class ParsingError(Exception):
pass
class RegexParsingError(ParsingError):
pass
|
from setuptools import find_packages, setup, Command
import os
# get the dependencies and installs
with open("requirements.txt", "r", encoding="utf-8") as f:
requires = []
for line in f:
req = line.split("#", 1)[0].strip()
if req and not req.startswith("--"):
requires.append(req)
... |
from .manager import main, run
from .mock import context
from .mock.plugin_manager import PluginView, caller_info
from .mock.handlers.handler_context import HandlerContext
from .mock import plugin_manager
from blinker import Signal
import os
from .event import CustomEventReceiver
from .checker import event
from .checke... |
import math
class Vector2:
def __init__(self,x,y):
self.x = x
self.y = y
def __getitem__(self, key):
if(key == 0):
return self.x
elif(key == 1):
return self.y
else:
raise IndexError("vector index out of range")
def __setitem__(self,... |
# Copyright 2020 InterDigital Communications, 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 ... |
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# ScanCode is a trademark of nexB Inc.
# SPDX-License-Identifier: Apache-2.0
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
# See https://github.com/nexB/scancode-toolkit for support or download.
# See https://aboutcode.org for more in... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
app.config['PAGINATION_PER_PAGE'] = 20
db = SQLAlchemy(app)
from library import routes
|
#!/usr/local/bin/python3
#
# Copyright (c) 2001-2019, Arm Limited and Contributors. All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
#
from ctypes import *
from dmpu_util_helper import *
# oem key request certificate struct is:
# token || version || size || main N+Np || enc N + Np || signature
# 4 ... |
"""
Django settings for TA project.
Generated by 'django-admin startproject' using Django 1.11.24.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
imp... |
'''
Problem 121 : Disc game prize fund
Problem Statement
==================
A bag contains one red disc and one blue disc.
In a game of chance a player takes a disc at random and its colour is noted.
After each turn the disc is returned to the bag, an extra red disc is added, and another disc is taken at random.
The ... |
# Copyright 2015 Hewlett-Packard Development Company, L.P.
# 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... |
# (C) Datadog, Inc. 2010-2017
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
# stdlib
import os
from urlparse import urlparse, parse_qsl
from urllib import unquote_plus
from urlparse import urljoin
import json
import BaseHTTPServer
import threading
import ssl
import time
import requests
i... |
### COMMAND FORMATS
__description__ = \
"""
PyCmdMessenger
Class for communication with an arduino using the CmdMessenger serial
communication library.
"""
__author__ = "Michael J. Harms"
__date__ = "2016-05-20"
import re, warnings, time, struct
class CmdMessenger:
"""
Basic interface for interfacing over... |
import logging
import aiosqlite
import discord
from bot.consts import Claims
from bot.data.base_repository import BaseRepository
log = logging.getLogger(__name__)
class ClaimsRepository(BaseRepository):
async def fetch_all_claims_user(self, user: discord.Member):
claims = set()
for r in user.r... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="people-finder",
version="0.2.5-beta",
author="derogab",
author_email="derosagabriele@outlook.it",
description="A tool to recognize people in images",
long_description=long_description,... |
"""Internal utilities."""
from .internal import *
from .data import *
from .checks import *
from .shared_mem import *
from .filter import *
from .exception import *
from .pin_memory import *
|
import pymysql
#database connection
connection = pymysql.connect(host="localhost",user="root",passwd="",database="restart" )
cursor = connection.cursor()
# some other statements with the help of cursor
connection.close() |
'''
Created on Jul 6, 2013
@author: Yubin Bai
All rights reserved.
'''
import time
from multiprocessing.pool import Pool
parallelSolve = False
INF = 1 << 31
def solve(par):
def find(i):
if parent[i] != i:
parent[i] = find(parent[i])
return parent[i]
def union(i, j):
p1... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI Limited
#
# 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 ... |
import pygame
import sys
import time
from dots_and_boxes.settings.GUI_settings import *
from dots_and_boxes.settings.colors import *
class GUI:
def __init__(self):
self.exists = SHOW_GUI
if self.exists:
pygame.init()
pygame.display.set_caption("Dots and Boxes")
... |
from django.shortcuts import render
from django.urls import reverse
def request_access(request):
"""
This endpoint alerts the user that an admin hasn't created a
user with the email they used with social auth. This also gives
them a link they can use to resume the login once an admin has
done this... |
import requests
URL_shortening_service="https://nvg.li/php/a/shorturl.php?url="
URL=input("What URL would you like to make shorten?")
query=r.post(URL_shortening_service+URL)
print(query.text) |
import datetime
from django.utils import timezone
from django.contrib.contenttypes.models import ContentType
from .models import Action
def create_action(user, verb, target=None):
# check for any similar action made in the last minute
now = timezone.now()
last_minute = now - datetime.timedelta(seconds=60*... |
###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2021, John McNamara, jmcnamara@cpan.org
#
import unittest
from ...compatibility import StringIO
from ...vml import Vml
class TestWriteDiv(unittest.TestCase):
"""
Test the Vml _wri... |
from django.apps import AppConfig
class PostsAppConfig(AppConfig):
name = 'post'
label = 'post'
verbose_name = 'Posts'
def ready(self):
import post.signals
default_app_config = 'post.PostsAppConfig'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# king_phisher/sphinxext/graphql.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice... |
import sys
sys.path.insert(1,"../../")
import h2o
from tests import pyunit_utils
def upload_file():
a = h2o.upload_file(pyunit_utils.locate("smalldata/logreg/prostate.csv"))
print a.describe()
from h2o import H2OFrame
# using lists []
py_list_to_h2o = H2OFrame(zip(*[[0, 1, 2, 3, 4]]))
... |
# 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 writing, software
# d... |
import tflite_runtime.interpreter as tflite
from PIL import Image
from io import BytesIO
from urllib import request
import numpy as np
#import model
interpreter = tflite.Interpreter(model_path='cats-dogs-v2.tflite')
interpreter.allocate_tensors()
# get input and output index
input_index = interpreter.g... |
class HermiteFace(Face,IDisposable):
""" A cubic hermite spline face of a 3d solid or open shell. """
def Dispose(self):
""" Dispose(self: APIObject,A_0: bool) """
pass
def ReleaseManagedResources(self,*args):
""" ReleaseManagedResources(self: APIObject) """
pass
def ReleaseUnmanagedResources(self,*... |
#!/usr/bin/env python
# LICENSE
# Copyright (c) 2014, South African Astronomical Observatory (SAAO)
# All rights reserved. See License file for more details
"""
SALTMOSAIC is a task to apply the CCD geometric corrections to MEF style SALT
data.
Author Version Date
------------------------------... |
"""Core object-file mapping functionality."""
import functools
from pprint import pformat
import logging
from . import common, diskutils, exceptions, types, settings
from .bases import Container
log = logging.getLogger(__name__)
def file_required(method):
"""Decorate methods that require the file to exist."""
... |
# base16-qutebrowser (https://github.com/theova/base16-qutebrowser)
# Base16 qutebrowser template by theova and Daniel Mulford
# Windows 95 scheme by Fergus Collins (https://github.com/C-Fergus)
base00 = "#000000"
base01 = "#1C1C1C"
base02 = "#383838"
base03 = "#545454"
base04 = "#7e7e7e"
base05 = "#a8a8a8"
base06 = "... |
#!/usr/local/bin/python3
"""
Copyright (c) 2020 Ad Schellevis <ad@opnsense.org>
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 abo... |
import pandas as pd
import numpy as np
import os
import matplotlib.pyplot as plt
import sys
plt.rcParams['figure.figsize'] = (19.2, 8.7)
index = 0
def show_accuracy(df):
global index
df.plot(kind='line')
plt.xlabel('iterations')
plt.ylabel('accuracy')
plt.savefig(str(index) + '.png', bbox_inches='tight')
pr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.