content stringlengths 5 1.05M |
|---|
import gzip
import os
import random
import tempfile
import uuid
from io import BytesIO
from unittest import TestCase
import corehq.blobs.util as mod
from corehq.blobs.exceptions import GzipStreamError
class TestRandomUrlId(TestCase):
sample_size = 100
def setUp(self):
self.ids = [mod.random_url_id(... |
from itertools import product
from datetime import datetime
from django.db import IntegrityError
from django.urls import reverse
from .base import TestBase
from ..models import Task, Event, Role, Person, Organization
class TestTask(TestBase):
"Tests for the task model, its manager and views"
def setUp(self... |
"""An async reimplementation of the blocking elements from botocore.retries.bucket."""
import asyncio
from botocore.exceptions import CapacityNotAvailableError
from botocore.retries.bucket import Clock as Clock # reexport # noqa
class AsyncTokenBucket:
"""A reimplementation of TokenBucket that doesn't block."""... |
# 96
# Faça um programa que tenha uma função chamada área(), que receba as dimensões de um terreno retangular (largura e comprimento) e mostre a área do terreno.
def area(larg, comp):
area = larg * comp
print(f'A área de um terreno de \33[36m{larg}\33[m x \33[36m{comp}\33[m é de \33[36m{area}\33[m m²')
print... |
from django.shortcuts import render, redirect
from .models import Url, BoundingBox
import cv2
from imutils import url_to_image
face_cascade = cv2.CascadeClassifier('/haarcascade_frontalface_default.xml')
def index(request):
if request.method == 'POST':
url = Url.objects.create(image_url=request.POST.ge... |
from armulator.armv6.opcodes.abstract_opcode import AbstractOpcode
from armulator.armv6.bits_ops import add_with_carry
from armulator.armv6.enums import InstrSet
class SubsPcLrThumb(AbstractOpcode):
def __init__(self, imm32, n):
super(SubsPcLrThumb, self).__init__()
self.imm32 = imm32
self... |
"""
Copyright 2020 TrialDataSolutions
"""
import requests
import json
class CastorApi(object):
def __init__(self, config):
'''
Takes a config-dictionary as parameter. To create an object of this class
the dictionary should at least have Values for Keys api_url, client_id and cl... |
#!/usr/bin/env python
import math
import string
import subprocess
import roslib; roslib.load_manifest('mav_fcs')
import rospy
#===============================================================================
def getCpuUsage():
usage = 0.0
f = open('/proc/loadavg', 'r')
line = f.readline()
tokens = l... |
# Most of the code below is shamelessly copied from the six library from
# Benjamin Peterson
import sys
import types
PY3 = sys.version_info[0] == 3
def _import_module(name):
"""Import module, returning the module after the last dot."""
__import__(name)
return sys.modules[name]
class _LazyDescr(object):
... |
from hestia.list_utils import to_list
from rest_framework.exceptions import ValidationError
from schemas import PersistenceConfig
from stores.exceptions import StoreNotFoundError
from stores.validators import validate_persistence_data, validate_persistence_outputs
def _set_persistence(instance, default_persistence_d... |
#! /usr/bin/env python3
import sys
import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file", dest="file", type=str,
help="Markdown location (within repository)")
parser.add_argument("-o","--output", dest="output", type=str,
help="Output doc... |
# -*- coding: utf-8 -*-
"""
The view of the hive-node and vault management.
"""
from flask_restful import Resource
from src.modules.provider.provider import Provider
class Vaults(Resource):
def __init__(self):
self.provider = Provider()
def get(self):
""" Get all vault information in this h... |
# Copyright (c) 2018, NVIDIA CORPORATION. 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... |
from . import newsapi_wrapper
from .newsapi_wrapper import NewsApiWrapper
__all__ = ['NewsApiWrapper']
|
"""Tests for ocsp.py"""
# pylint: disable=protected-access
import unittest
import mock
from certbot import errors
out = """Missing = in header key=value
ocsp: Use -help for summary.
"""
class OCSPTest(unittest.TestCase):
_multiprocess_can_split_ = True
def setUp(self):
from certbot import ocsp
... |
from chp5.browser_render import BrowserRender
br = BrowserRender()
br.download('http://example.python-scraping.com/search')
br.attr('#search_term', 'value', '.')
br.text('#page_size option:checked', '1000')
br.click('#search')
elements = br.wait_load('#results a')
countries_or_districts = [e.toPlainText().strip() for... |
import emoji
from time import sleep
print('\33[31m=' * 20, 'Contagem Regressiva para os Fogos de Artíficio', '=' * 20, '\33[m')
for c in range(10, -1, -1):
print(c)
sleep(1)
print(emoji.emojize('\33[34mOs fogos estão explodindo :fireworks:\33[m', use_aliases= True))
print('\33[35mBUM, BUM, BUM, BUM, BUM, BUM, ... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import datetime as dt
import json
import os
import attr
import boto3
import requests
@attr.s
class CurrencyAmount:
unit = attr.ib()
# Turning strings like '233.205000000000012505552149377763271331787109375'
# into floats is a little cheaty, but a floating... |
#!/home/mercer/receipts-dates/venv/bin/python3
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
|
# pylint: disable=E1101,E0611,F0401
# E1101: Pylint cannot resolve specific win32 modules.
# E0611: "shell" exists in win32com but Pylint cannot detect it.
# F0401: "win32com.shell" exists but Pylint cannot import.
#
# $Filename$
# $Authors$
# Last Changed: $Date$ $Committer$ $Revision-Id$
#
# Copyright (c) 2... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This file contains functions
"""
from llist import dllist
import numpy as np
def rotate_teams(entities, stay_chance, eval_time, dt):
"""
Args:
entities: tuple with pointers to teams, boxes and agents objects.
eval_time: current time step of si... |
'''
/*
* @Author: Shawn Zhang
* @Date: 2019-09-08 17:15:03
* @Last Modified by: Shawn Zhang
* @Last Modified time: 2019-09-08 22:50:07
*/
'''
from flask import current_app
from . import index_bp
import os
@index_bp.route('/', methods=['GET'])
def index():
return os.path.abspath(os.path.dirname(__file__)) |
import os
from cv2 import cv2
from .config import MODEL_PATH, CLASSES_PATH, USE_GPU
modelConfig = os.path.join(MODEL_PATH, "yolov3.cfg")
modelWeights = os.path.join(MODEL_PATH, "yolov3.weights")
modelClass = os.path.join(CLASSES_PATH, "coco.names")
backend = cv2.dnn.DNN_BACKEND_OPENCV
target = cv2.dnn.DNN_TARGET_CPU
... |
n = int(input(":"))
if n<=1:
print("None")
else:
listn=[]
i=2
while i<=n:
listn.append(i)
i+=1
for x in range(n):
l=len(listn)
for y in listn[x+1:l]:
if y%listn[x]==0:
listn.remove(y)
listn.append(-3)
listt=[]
for i in ran... |
# Adversarial autoencoder
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy
import tensorflow as tf
import matplotlib.pyplot as plt
import time
from tfutil_deprecated import LayerManager
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_in... |
from fastapi import APIRouter
from apis.login.controller import login_router
from apis.users.controller import user_router
from apis.record.controller import record_router
from apis.role.controller import role_router
from apis.menu.controller import menu_router
from apis.perm.controller import perm_router
from apis.cmd... |
from core import views
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from rest_framework.authtoken import views as authtoken_views
router = DefaultRouter()
router.register(r'category', views.CategoryViewSet)
router.register(r'provider', views.ProviderViewSet)
router.regist... |
###
### Author: David Wallin, Daniel Costa
### Time-stamp: <2020-03-26 15:47:00 dwa>
from multicorn import ForeignDataWrapper
from multicorn.utils import log_to_postgres as log2pg
from pymongo import MongoClient
from dateutil.parser import parse
from functools import partial, reduce
dict_traverser = partial(reduce,... |
#!/usr/bin/env python3
# -- coding:utf-8 --
# @Author: markushammered@gmail.com
# @Development Tool: Pycharm
# @Create Time: 2022/5/2
# @File Name: auth.py
import os
from flask import request
from flask_httpauth import HTTPTokenAuth
auth = HTTPTokenAuth()
@auth.verify_token
def verify_token(token):
secret_key ... |
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class FormDesignerConfig(AppConfig):
name = 'form_designer'
verbose_name = _("Form Designer")
|
#__LICENSE_GOES_HERE__
'''
A script that drives buildexts.py and installs the built extension into a platform
subdir of the main ext dir. This way we won't have cgui.py or cgui.pyd/so for various
platforms overwriting each other.
'''
import sys, os, glob
scriptDir = os.path.abspath(sys.path[0])
opj = os.path.join
digs... |
from typing import List
from typing_extensions import Annotated
from alpyro_msgs import RosMessage, float64, string
from alpyro_msgs.std_msgs.header import Header
class JointJog(RosMessage):
__msg_typ__ = "control_msgs/JointJog"
__msg_def__ = "c3RkX21zZ3MvSGVhZGVyIGhlYWRlcgogIHVpbnQzMiBzZXEKICB0aW1lIHN0YW1wCiAgc3... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"helloworld": "helloWorld.ipynb"}
modules = ["helloworld.py"]
doc_url = "https://thanakijwanavit.github.io/src/"
git_url = "https://github.com/thanakijwanavit/src/tree/main/"
def custom_doc_links(name): r... |
# Source : https://github.com/GuessWhatGame/generic/tree/master/data_provider
import numpy as np
from utils.file_handlers import pickle_loader
class GloveEmbeddings(object):
def __init__(self, file, glove_dim=300):
self.glove = pickle_loader(file)
self.glove_dim = glove_dim
def get_embedding... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
mslib.mswms.mswms
~~~~~~~~~~~~~~~~~
The module can be run with the Python Flask framework and can be run as
python mswms.py.
:copyright: Copyright 2016 Reimar Bauer
:copyright: Copyright 2016-2021 by the mss team, see AUTHORS.
:license: AP... |
# -*- coding: utf-8 -*-
""" IPython extension: add %clear magic """
from IPython.core import ipapi
import gc
ip = ipapi.get()
def clear_f(self,arg):
""" Clear various data (e.g. stored history data)
%clear in - clear input history
%clear out - clear output history
%clear shadow_compress - Compre... |
from __future__ import absolute_import, unicode_literals
from django.conf import settings
settings.configure(
SESSION_ENGINE='redis_sessions_fork.session',
# SESSION_SERIALIZER='redis_sessions_fork.serializers.UjsonSerializer',
SESSION_REDIS_PREFIX='django_sessions_tests',
INSTALLED_APPS=(
'd... |
from enum import Enum
class Topics(Enum):
SEISMIC = "/pi/test"
T_AND_H = "/pi/temp"
ULTRASOUND = "/pi/ultrasound"
EXAMPLE = "/example"
|
# Runs after normalization and per_person_ratio_and_factor and pre_plot_aggregation.
import shutil
from pathlib import Path
import itertools
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import collections
from scipy.optimize import minimize_scalar
cols1 = ['F1_' + str(i) for i in range(3... |
### Tools
__all__ = ["Dtool_ObjectToDict", "Dtool_funcToMethod", "Dtool_PreloadDLL"]
import imp, sys, os
# The following code exists to work around a problem that exists
# with Python 2.5 or greater.
# Specifically, Python 2.5 is designed to import files named *.pyd
# only; it will not import files named *.dll (or ... |
''' The flipper GUI application. '''
from . import main
from . import pieces
from . import options
from . import inputbox
from . import choicebox
from . import progress
from . import widgets
# Set up shorter names for all of the different classes and some common constructors.
start = main.start
Options = options.Opt... |
import gc
from collections import defaultdict
from typing import Any, Dict, Tuple
import numpy as np
import pandas as pd
# Funcion for user stats with loops
def add_features(
df: pd.DataFrame,
answered_correctly_u_count: Dict[int, int],
answered_correctly_u_sum: Dict[int, int],
elapsed_time_u_sum: Di... |
# Generated by Django 2.2.13 on 2020-10-30 17:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('publications', '0002_initial_data'),
('origins', '0003_site_references'),
]
operations = [
migrations.AddField(
model_n... |
"""The file system abstraction."""
import urllib.parse
from io import BytesIO
from flask import current_app
from .eatfirst_osfs import EatFirstOSFS
from .eatfirst_s3 import EatFirstS3
class EFS:
"""The EatFirst File system."""
def __init__(self, *args, storage="local", **kwargs):
"""The constructor... |
#! /usr/bin python3
import numpy as np
import math
class Net(object):
def __init__(self):
self.inputSize = 3
self.outputSize = 3
self.hiddenSize = 5
# Weights
self.W1 = np.random.rand(self.inputSize, self.hiddenSize)
self.W2 = np.random.rand(self.hiddenSize, self.ou... |
__version_tuple__ = (0, 7, 0, 'alpha.5')
__version__ = '0.7.0-alpha.5'
|
import os
from random import randrange
# data
root = '/home/ales/Documents/Extended/datasets/STYRIA/output/articles+comments-workshop-2500-samples/articles_only'
# lead baseline
tgt_folder = 'output/articles+comments-workshop-2500-samples/baseline-lead'
os.makedirs(tgt_folder, exist_ok=True)
for file in os.scandir(ro... |
# Copyright 2018 Google, 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 agreed to in writin... |
"""
I need a *what* An *inverted sphere*? What in tarnation is an
inverted sphere, and where do I find one?
This files writes out a .BAM file of a Skybox, pasting together
six PNG files into a crude SkySphere.
Note there are several hardcoded full filepaths here - I had a
lot of problems with relative-paths, they wer... |
import subprocess
import os
from report.models import *
import utils.report_handle as report_handle
import utils.cmd as cmd
"""
Lay danh sach cac tool
"""
def get_tool_list():
return ['Qark', 'Dependency Check', 'Sniffgit', 'AndroBugs', 'DB Parser']
"""
Lay danh sach cac app trong dien thoai
"""
def get_app_list... |
""" Utilities for CumulusCI Core"""
import copy
import glob
import time
import typing as T
import warnings
from datetime import datetime, timedelta
from logging import getLogger
from pathlib import Path
import pytz
from cumulusci.core.exceptions import ConfigMergeError, TaskOptionsError
def import_global(path: str... |
"""
This file will populate the tables using Faker
"""
import random
import decimal
from datetime import datetime
from django.db import models
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
from faker import Faker
from shop.models import Cart, Customer, Li... |
from django.db import models
from .teachers import teachers
class UniqueClasses(models.Model):
Strength = models.IntegerField()
Teacher = models.ForeignKey(teachers) |
#
# Copyright (c) 2020 Xilinx, Inc. All rights reserved.
# SPDX-License-Identifier: MIT
#
from roast.machines.microblaze import *
PLNX_BSP = "xilinx-kc705-v{version}-final.bsp"
plnx_proj = "xilinx-kc705-{version}"
|
import os
import sys
from samplerunner.source import get_sources
from samplerunner.project import requires_params, get_project_type_by_name
def run(args):
if args.language:
_run_language(args.language)
elif args.project:
_run_project(args.project)
elif args.source:
_run_source(arg... |
import os
class RenderHTML:
def __init__(self, file):
self._file = file
if not os.path.exists(self._file):
raise FileNotFoundError(f"No such HTML file: {self._file}")
with open(file, 'r') as f:
self._html = f.read()
def __repr__(self):
return "<%s... |
import tornado.web
import tornado.ioloop
import json
import os
import datetime
import base64
import requests # pip install requests
from tornado.options import define, options
define("port", default=8888, help="run on the given port", type=int)
define("users", default="./users.json", help="path to the file with... |
import uuid as generator
import numpy as np
import math
from utils import *
ANGLE_RES = 50 #resolution for the rounded corners
class Straight:
#id
#startNode = id
#startNode = id
#nextStraight = id
#previousStraight = id
def __init__(self, start, end):
self.id = generator.uuid1().in... |
import click
from clickhouse_migrate.common.db import DbRegister
from clickhouse_migrate.conf.settings import Settings
from clickhouse_migrate.interfaces.service import MigrationService
@click.group()
def cli():
pass
@click.command(name="migrate")
@click.option("-c", "--config", help="Path to config *.ini file... |
# The usage of __init__.py file is it indicates that the files in this dir are part of python package.
# Without an __init__.py file, you cannot import files from another directory in a Python project.
#__init__ can be empty but can also be used to set up imports. There are 3 kinds of imports:
# 1. example_package/_... |
from .Action import Action
class DropMsg(Exception):
def __init__(self):
super(type(self), self).__init__()
class DropAction(Action):
def __init__(self):
super(DropAction, self).__init__(actionId = "drop", actionType = "drop")
def run(self, record):
super(type(self), self).run(rec... |
#!/usr/bin/env python3
import os
from aws_cdk import aws_codebuild as codebuild
from aws_cdk import aws_codepipeline as codepipeline
from aws_cdk import aws_codepipeline_actions as codepipeline_actions
from aws_cdk import aws_codestarnotifications as notifications
from aws_cdk import aws_iam as iam
from aws_cdk impor... |
a = input("Which file?")
if a == "main":
import main.py
elif a == "gui":
import gui.py
elif a == "commands":
import commands.py
elif a == "admin":
print ("There is no admin, you fool!") |
import io
import os
from shutil import rmtree
import tempfile
import pytest
from extractnet import data_processing
FIXTURES = os.path.join('test', 'datafiles')
@pytest.fixture(scope="module")
def fileroots():
return ["bbc.co.story", "f1", "sad8-2sdkfj"]
@pytest.fixture(scope="class")
def datadir(fileroots):
... |
from collections import OrderedDict
import json
from gui.tree_widget_configuration import *
from nodes import *
from core.node_edge import Edge
# TODO melhorar comandos para undo e redo
class Serialization:
def __init__(self, Session=None, currentInstance=None, sender=None, filename=None):
self.Session ... |
import ee
from ee_plugin import Map
# Load an image.
image = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_044034_20140318')
centroid = image.geometry().centroid().coordinates()
lon = centroid.get(0).getInfo()
lat = centroid.get(1).getInfo()
# print(centroid.getInfo())
# Create an NDWI image, define visualization parameters... |
"""
Encrypt a file using GPG, then FTP
it to a remote server.
"""
from gnupg import GPG
from ftplib import FPT
# Create instance and set gpg working directory
gpg = GPG(gnupghome=".gpg")
# import an existing public key
with open("mykey.asc", 'r') as fp:
key_data = fp.read()
import_status = gpg.import_keys(ke... |
from setuptools import setup, find_packages
setup(
name='ethsign-cli',
packages=find_packages(),
entry_points={
'console_scripts': ['ethsign-cli=eth_sign_cli:cli']
},
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
... |
# Copyright (c) 2017 The sqlalchemy-bigquery Authors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, mer... |
import sys
from . import logger
from . import cli
from . import input_
from . import process
from . import format_
from . import output
def main():
try:
options = cli.parse_options()
logger.init_logger(options.verbose)
history = input_.input_git_history(
options.repo,
... |
QUALITY_SCORE_STRING = '''
!"#$%&'()*+,-./0123456789:;<=>?@
ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`
abcdefghijklmnopqrstuvwxyz{|}~
'''
QUALITY_SCORE = 29 # threshold quality_score must be between 0 and 93
TRANSLATION_CODE = {
'AAA':'K','AAC':'N','AAG':'K','AAU':'N',
'ACA':'T','ACC':'T','ACG':'T','AC... |
from importlib import import_module
class Base:
pass
def load_alarm_model(model):
try:
return import_module('alerta.models.alarms.%s' % model.lower())
except Exception:
raise ImportError('Failed to load %s alarm model' % model)
class AlarmModel(Base):
Severity = {} # type: ignore... |
from model_mommy import mommy
from django.core.urlresolvers import reverse
from decisiontree.multitenancy import models as link_models
from .. import models
from .cases import DecisionTreeTestCase, DeleteViewTestMixin
class TestAnswerDelete(DeleteViewTestMixin, DecisionTreeTestCase):
link_model = link_models.A... |
# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import argparse
from mo.utils.error import Error
from mo.utils.cli_parser import parse_transform
def get_available_transformations():
try:
from openvino.offline_transformations import ApplyLowLatencyTransformation # pylint: di... |
#!/usr/bin/env python3
# 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.
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from typing import L... |
from gamepack.item.Item import Item
class StackableItem(Item):
def __init__(self, name = '', count = 0, value = 0):
Item.__init__(self, name, count, value)
self.stackable = True
def add_to_stack(self, item):
if item.name == self.name:
self.count += item.count
... |
import unittest
from affine_cipher import decode, encode
# Tests adapted from `problem-specifications//canonical-data.json`
class AffineCipherTest(unittest.TestCase):
def test_encode_yes(self):
self.assertEqual(encode("yes", 5, 7), "xbt")
def test_encode_no(self):
self.assertEqual(encode("n... |
peso = float(input("Qual seu peso(kg)? "))
altura = float(input("Qual sua altura(m)? "))
imc = round(peso / (altura**2),2)
print(f"Com IMC = {imc}, o usíario esta", end=" ")
if imc < 18.5:
print("abaixo do peso")
elif imc < 25:
print("no peso ideal")
elif imc < 30:
print("com sobrepeso")
elif imc < 40:
... |
#Get a string which is n (non-negative integer) copies of a given string
#
#function to display the string
def dispfunc(iteration):
output=str("")
for i in range(iteration):
output=output+entry
print(output)
#
entry=str(input("\nenter a string : "))
displaynumber=int(input("how many times must it be... |
from aoc2019.intcode_computer import IntCodeComputer
import multiprocessing as mp
def part1():
comp = IntCodeComputer(stdio=False)
iq = mp.Queue()
oq = mp.Queue()
with open('input.txt') as f:
instructions = f.read()
iq.put(1)
comp.run_program(instructions, mem=10000, input_queue=iq, ou... |
# -*- coding: utf-8
from django.apps import AppConfig
class HvadCleanerversionConfig(AppConfig):
name = 'hvad_cleanerversion'
|
import sys
alfabetoMay = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S','T', 'U', 'V', 'W', 'X', 'Y', 'Z']
alfabetoMin = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def main(argv = sys.argv):
num = int(ar... |
import google.oauth2.service_account
import pytest
@pytest.fixture(params=["env"])
def project(request, project_id):
if request.param == "env":
return project_id
elif request.param == "none":
return None
@pytest.fixture()
def credentials(private_key_path):
return google.oauth2.service_ac... |
import torch
import math
from .vqa_model import VQAModel
class Clean_Uniter(torch.nn.Module):
def __init__(self):
super(Clean_Uniter, self).__init__()
# Load pretrained UNITER
self.uniter = VQAModel(num_answers = 69, model = 'uniter')
self.uniter.encoder.load('./Transformers_VQA/mod... |
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
class HomeHandler(webapp.RequestHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), 'templates/home.html')
self.response.out.write(template.render(path, {}))
|
# MIT License
#
# Copyright (c) 2020 Andrew Krepps
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge... |
from .core import DirMap
|
# Script to run experiments using CHKMRT strategy
import copy
import random
from timeit import default_timer as timer
import networkx as nx
import csv
import sys
sys.path.append('../code')
from probesim.evaluation import seqstats2 as stats
from probesim.strategy import chkmrt as strategy
from probesim.topology impor... |
# Generated by Django 4.0.2 on 2022-02-15 15:52
import datetime
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
fields... |
from .__head__ import *
class ICUDomain(BaseDomain):
def __init__(self, y_dim=2):
self.base_name = "icu"
self.name = self.base_name + f"_{y_dim}"
self.static_in_dim = 32
self.series_in_dim = 37
self.static_bin_dim = 29
self.static_con_dim = 3
self.out_dim =... |
from time import sleep
from typing import List, Tuple
from asciimatics.constants import COLOUR_RED
from asciimatics.screen import Screen
from player import Player
class Level:
"""Framework for levels"""
def __init__(self, screen: Screen):
"""Initiates a level"""
self.screen = screen
... |
import logging.config
LOGGING_CONFIG = {
'version': 1,
'loggers': {
'': {
'level': 'DEBUG',
'handlers': ['console', 'mail'],
},
'console': {
'level': 'DEBUG',
'handlers': ['console'],
}
},
'handlers': {
'console':... |
#!/usr/bin/env python
u"""
gesdisc_merra_download.py
Written by Tyler Sutterley (09/2019)
This program downloads MERRA-2 products using a links list provided by the
Goddard Earth Sciences Data and Information Server Center
https://gmao.gsfc.nasa.gov/reanalysis/MERRA-2/
https://wiki.earthdata.nasa.gov/displ... |
##Drone Start##
import time, sys
import ps_drone
drone = ps_drone.Drone()
drone.startup()
drone.reset()
while (drone.getBattery()[0]==-1): time.sleep(0.1) #Reset completed?
print "Battery: "+str(drone.getBattery()[0])+"%" +str(drone.getBattery()[1])
if drone.getBattery()[1]=="empty": sys.exit() #If battery low, abort... |
import pygame
pygame.init()
screenWidth=720
screenHeight=720
run=True
bl=(255,105,180)
white=(255,255, 255)
x=50
y=50
width=50
height=50
speed=40
isJump= False
jumpCount=10
win=pygame.display.set_mode((screenHeight, screenWidth))
pygame.display.set_caption("New", "My")
while run:
#for (this) event
pygame.time.d... |
import os
import importlib
import requests
import self as self
import urllib3
# importlib.import_module("python-twitter")
print(os.system('pip install python-twitter'))
print(os.system('pip install requests'))
print(os.system('pip install urllib3'))
def parse_sites(filename):
with open(filename, "r", encoding='UT... |
# Copyright 2017 by Kurt Rathjen. All Rights Reserved.
#
# This library is free software: you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation, either
# version 3 of the License, or (at your option) any later version.
# This l... |
# -*- coding: UTF-8 -*-
"""
爱丽丝和鲍勃一起玩游戏,他们轮流行动。爱丽丝先手开局。
最初,黑板上有一个数字 N 。在每个玩家的回合,玩家需要执行以下操作:
选出任一 x,满足 0 < x < N 且 N % x == 0 。
用 N - x 替换黑板上的数字 N 。
如果玩家无法执行这些操作,就会输掉游戏
只有在爱丽丝在游戏中取得胜利时才返回 True,否则返回 false。假设两个玩家都以最佳状态参与游戏。
示例 1:
输入:2
输出:true
解释:爱丽丝选择 1,鲍勃无法进行操作。
示例 2:
输入:3
输出:false
解释:爱丽丝选择 1,鲍勃也... |
"""blog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/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-based vi... |
from django.core.management.base import BaseCommand
from django.db.models import Count
from data_refinery_common.job_lookup import ProcessorPipeline
from data_refinery_common.logging import get_and_configure_logger
from data_refinery_common.message_queue import send_job
from data_refinery_common.models import (
Co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.