content stringlengths 5 1.05M |
|---|
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from .views import (
CustomerOrderCreateAPIView,
AcceptOrderCreateAPIView,
)
urlpatterns = [
path('customer/create/', CustomerOrderCreateAPIView.as_view(), name='order create'),
path('accept/', AcceptOrderCreate... |
# https://www.acmicpc.net/problem/12865
# 2020-11-1 Chul-Woong Yang
# 0-1 knapsack
import sys
#from typing import List, NamedTuple
from collections import namedtuple
def mi():
return map(int, sys.stdin.readline().split())
def milines():
return map(int, sys.stdin.readlines())
class Item(NamedTuple):
weigh... |
import subprocess
import csv
from pathlib import Path
from os import listdir
from os.path import isdir, isfile
def getTestCasesNames(dir):
files = []
for file in listdir(dir):
if not isdir(file):
files.append(file)
return files
def readFile(dir, file):
content = None
if isfile... |
from collections import defaultdict
import random
import copy
import numpy as np
from torch.utils.data.sampler import Sampler
class TripletSampler(Sampler):
def __init__(self, labels, batch_size, p, k):
super(TripletSampler, self).__init__(None)
self.labels = labels
self.batch... |
# Because Python is a reference counted language, it's important not to create
# reference cycles! Weakref is used to hold a reference to the parent
# GameState object.
import weakref
# Everything that happens is associated with an event. The event processing
# system keeps events to be processed in a queue.
from colle... |
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.stats as ss
from bcodes.ratevector import create_rate_vector
from bcodes.stoichiometrymatrix import build_stoichiometry_matrix
from model.batch_growth import batch_growth as m
####################... |
#!/usr/bin/env python
import argparse
import os
import sys
import tempfile
def compare_pattern(pattern, filename, offset):
with open(filename, "r+b") as fd:
fd.seek(offset)
return pattern == fd.read(len(pattern)).decode("ascii")
def write_pattern(pattern, filename, offset):
with open(filena... |
from tvm import cpp as tvm
def test_basic():
a = tvm.Var('a', 0)
b = tvm.Var('b', 0)
z = tvm.max(a, b)
assert tvm.format_str(z) == 'max(%s, %s)' % (a.name, b.name)
if __name__ == "__main__":
test_basic()
|
DATA_LIST_SIZE = 10
COLOR_CODE_LIST = ["#CD2626", "#FF7F0F", "#FF9CEE", "#6EB5FF", "#B10501",
"#4B11A8", "#1A73E8", "#617C58", "#827B60", "#C47451"]
OFFER_LIST = [5, 7, 10, 12, 15, 20, 25, 30, 35, 40]
|
"""
Some usefuls objects for doing unit tests.
Async test system is based on https://github.com/kwarunek/aiounittest
Copyright (C) 2017 The Pylp Authors.
This file is under the MIT License.
"""
import unittest
import asyncio
import inspect
from pylp.lib.runner import TaskEndTransformer
from pylp import Stream
# ... |
# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/beta_utils.ipynb (unless otherwise specified).
__all__ = ['get_beta_parameters', 'convolve_betas_fft', 'convolve_betas', 'balanced_accuracy_expected', 'beta_sum_pdf',
'beta_avg_pdf', 'beta_sum_cdf', 'beta_avg_cdf', 'beta_avg_inv_cdf', 'recall', 'precisio... |
"""
Exposes regular shell commands as services.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/shell_command/
"""
import logging
import subprocess
from homeassistant.util import slugify
DOMAIN = 'shell_command'
_LOGGER = logging.getLogger(__name__)
... |
# This file is part of rinohtype, the Python document preparation system.
#
# Copyright (c) Brecht Machiels.
#
# Use of this source code is subject to the terms of the GNU Affero General
# Public License v3. See the LICENSE file or http://www.gnu.org/licenses/.
from .annotation import NamedDestination
from .warnings ... |
# coding: utf-8
import argparse
import time
import math
import torch
import torch.nn as nn
from torch import optim
import data
import sys
from utils import *
from setproctitle import setproctitle
from splitcross import *
sys.path.append("../")
from model import TrellisNetModel
parser = argparse.ArgumentParser(descrip... |
"""
File: preprocessing.py
Author: Team ohia.ai
Description: Preprocess data for the HAAC 2018 Challenge.
"""
import os, re, glob, multiprocessing, click
import numpy as np
from PIL import Image
from collections import Counter
from ohia.utils import resize_smaller_dim, crop_square, make_dir
from functools import parti... |
import tensorflow as tf
import numpy as np
import collections
from malaya_speech.utils import featurization
from malaya_speech.model.frame import Frame
from malaya_speech.utils.padding import (
sequence_nd as padding_sequence_nd,
sequence_1d,
)
from malaya_speech.utils.char import decode as char_decode
from mal... |
from model.unet import UNet
from tools.data import train_generator, test_generator, save_results, is_file, prepare_dataset
from tools.generator3 import DataGenerator
from tools.generator3 import DataGenerator
import os
# TODO: move to config .json files
img_height = 576
img_width = 729
img_size = (img_height, img_width... |
class ExtraAttributesMixin:
"""Adds extra attributes to a forms fields
Value in the ``extra_attributes`` property will be added to the corresponding Key in fields dictionary
property
"""
extra_attributes = {}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
... |
import movelist
import NotationParser
from NotationParser import ParseMoveList
from movelist import MoveList
gp = MoveList(28)
m = gp.GetPunishers(10, True)
print(m)
#moves = gp.getGameplan(1)
#for move in gp.gameplan:
# try:
# command = ParseMoveList(gp.getMoveCommand(move))
# except:
# print(m... |
from dgllife.data import JTVAEDataset, JTVAECollator
from torch.utils.data import DataLoader
from dgllife.model import load_pretrained
import torch
import numpy as np
#from tqdm import tqdm
from tqdm.notebook import tqdm
class JTNNWapper:
def __init__(self,
model=None):
if model i... |
"""
read_row_by_row.py
:copyright: (c) 2014-2017 by Onni Software Ltd.
:license: New BSD License, see LICENSE for more details
This shows a pythonic way to use **Reader** class to go through a single
page spreadsheet row by row. The output is::
[1.0, 2.0, 3.0]
[4.0, 5.0, 6.0]
[7.0, 8.0, 9.0]
Please insta... |
from output.models.nist_data.list_pkg.language.schema_instance.nistschema_sv_iv_list_language_max_length_1_xsd.nistschema_sv_iv_list_language_max_length_1 import NistschemaSvIvListLanguageMaxLength1
__all__ = [
"NistschemaSvIvListLanguageMaxLength1",
]
|
#!/usr/bin/env python
# BSD 3-Clause License; see https://github.com/scikit-hep/uproot-methods/blob/master/LICENSE
import numpy
import uproot_methods.base
class Methods(uproot_methods.base.ROOTMethods):
def hello(self):
return "world", len(dir(self))
|
# ----------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License
# ----------------------------------------------------------------------
"""Contains the Plugin object"""
import itertools
import os
import sys
... |
# ----------------------------------------------------------------------------
# GS Widget Kit Copyright 2021 by Noah Rahm and contributors
#
# 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
#
#... |
#!/usr/bin/env python
# Wenchang Yang (wenchang@princeton.edu)
# Wed Jun 30 17:02:45 EDT 2021
if __name__ == '__main__':
from misc.timer import Timer
tt = Timer(f'start {__file__}')
import sys, os.path, os, glob, datetime
import xarray as xr, numpy as np, pandas as pd, matplotlib.pyplot as plt
#more imports
fro... |
# If you use more than one instance, pass tuples to assign different
# values. For example, for two instances use zones
# `('europe-west4-a', 'europe-west4-c')`.
NUM_INSTANCES = 8
# These paths are relative to the file `distribute_multi.py` as a tuple
# that will be `os.path.join`ed or single string. Don't forget to w... |
"""
https://github.com/onnx/onnx/blob/09ada0f107f1cc1877f9194475c98d2d8512e188/onnx/defs/nn/defs.cc
"""
from webdnn.graph.axis import Axis
from webdnn.frontend.onnx.converter import ONNXConverter, attribute_dict
from webdnn.frontend.onnx.type_hint import INodeProto
from webdnn.graph.operators.average_pooling_2d import ... |
from app.api.now_applications.models.activity_detail.activity_detail_base import ActivityDetailBase
class StagingAreaDetail(ActivityDetailBase):
__mapper_args__ = {'polymorphic_identity': 'camp'}
def __repr__(self):
return f'<{self.__class__.__name__} {self.activity_detail_id}>'
|
from django.urls import path
from . import views
from django.contrib import admin
admin.site.index_title = 'Chatops administration'
urlpatterns = [
path('', views.index, name='index')
]
|
# `engine` dependencies span across the entire project, so it's better to
# leave this __init__.py empty, and use `from matchzoo.engine.package import
# x` or `from matchzoo.engine import package` instead of `from matchzoo
# import engine`.
|
'''
Poker.py 는
포커 작동관련 모든 함수를 정의 해 놓은 곳이다.
'''
import Tools
# 가지고있는 핸드중 가장 높은 숫자의 카드를 돌려주는 함수
def findTopCard(hands:list):
topnumber = 0
cards = hands.copy()
cards = changeRoyal(cards)
cards = removeShape(cards)
cards.sort()
topnumber = int(cards[4])
if topnumber < 10:
... |
# Imports
import keras_ocr
import helpers
# Prepare OCR recognizer
recognizer = keras_ocr.recognition.Recognizer()
# Load images and their labels
dataset_folder = 'Dataset'
image_file_filter = '*.jpg'
images_with_labels = helpers.load_images_from_folder(
dataset_folder, image_file_filter)
# Perform OCR recognit... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .base import * # noqa
# don't use an unicode string
localeID = 'de_DE'
dateSep = ['.']
timeSep = [':']
meridian = []
usesMeridian = False
uses24 = True
decimal_mark = ','
Weekdays = [
'montag', 'dienstag', 'mittwoch',
'donnerstag', 'freitag... |
def leiaint(a):
n = str(input(a))
while not n.isnumeric():
print('\033[1;31mERRO! Digite um valor válido!\033[0;0m')
n = str(input(a))
if n.isnumeric():
int(n)
print(f'Ok, o número {n} é inteiro.')
leiaint('Digite um número: ')
|
import pytest
from .dict_serialization_helpers import *
class TestTupleKeysSerializers(object):
class ExampleObj(object):
def __init__(self, foo, bar):
self.foo = foo
self.bar = bar
def __eq__(self, other):
return self.foo == other.foo and self.bar == other.bar... |
# Copyright 2015 Ufora 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 i... |
# -*- encoding: utf-8 -*-
from contextlib import contextmanager
from datetime import datetime
import sys
from traceback import format_exception
import colorama
def warn(title):
sys.stderr.write('{warn} [WARN] {title}{rest}\n'.format(
warn=colorama.Back.RED + colorama.Fore.WHITE + colorama.Style.BRIGHT,
titl... |
#from pydub import AudioSegment
import numpy, scipy, matplotlib.pyplot as plt, sklearn, librosa, mir_eval, urllib
from scipy.io.wavfile import write
import os,sys
#feature extractor
def extract_features(x, fs):
zcr = librosa.zero_crossings(x).sum()
energy = scipy.linalg.norm(x)
return [zcr, energy]
#These... |
class Treinamento:
|
r"""
Hall Algebras
AUTHORS:
- Travis Scrimshaw (2013-10-17): Initial version
"""
#*****************************************************************************
# Copyright (C) 2013 Travis Scrimshaw <tscrim at ucdavis.edu>
#
# Distributed under the terms of the GNU General Public License (GPL)
# htt... |
from typing import *
class Solution:
# 80 ms, faster than 58.31% of Python3 online submissions for Sort Array By Parity.
# 15.2 MB, less than 22.91% of Python3 online submissions for Sort Array By Parity.
def sortArrayByParity(self, nums: List[int]) -> List[int]:
even = []
odd = []
f... |
import pytest
from pytest import raises
from vyper import compiler
from vyper.exceptions import TypeMismatchException
fail_list = [
"""
@public
def foo():
y = min(7, 0x1234567890123456789012345678901234567890)
"""
]
@pytest.mark.parametrize('bad_code', fail_list)
def test_block_fail(bad_code):
wit... |
"""
Copyright (c) 2018-2020 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... |
#!/usr/bin/env python
# IRC Cryptocurrency Exchange (IRCCEX) - Developed by acidvegas in Python (https://acid.vegas/irccex)
# constants.py
# Control Characters
bold = '\x02'
color = '\x03'
italic = '\x1D'
underline = '\x1F'
reverse = '\x16'
reset = '\x0f'
# Color Codes
white = '00'
black ... |
# Generated by Django 2.2.3 on 2019-07-26 08:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("kiss_cache", "0002_alter_resources")]
operations = [
migrations.AlterField(
model_name="resource",
name="state",
fiel... |
#Nishaant Goswamy
import collections
from CompressDecompress import Text_Encoding,Letter_Decoding
import cryptAlg as crypt
print("This is ElGamal Signature")
p = int(input("Enter a prime value p: "))
if not crypt.primeCheck(p): quit()
g = crypt.Generator((p-1), p)
print("Generator g:", g )
r = in... |
# pylint: disable=C0111,R0902,R0904,R0912,R0913,R0915,E1101
# Smartsheet Python SDK.
#
# Copyright 2016 Smartsheet.com, 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.... |
"""
A PyQt5 custom widget used by Morse Trainer.
Used to select overall word speed for the Send tab only.
speed = SendSpeeds()
speed.setState(wpm) # sets the speed display
The widget generates a signal '.changed' when some value changes.
"""
import platform
from PyQt5.QtWidgets import QWidget, QPushButton, QH... |
# pylint: disable=W0212
import logging
import os
import sys
from loguru import logger as _logger
logger = _logger
CONSOLE_LOG_FORMAT = "{level.icon} {time:MM-DD HH:mm:ss} <lvl>{level}\t{message}</lvl>"
FILE_LOG_FORMAT = "{time:YYYY-MM-DD HH:mm} {level}\t{message}"
FILE_LOG_PATH_NAMING = "./logs/{time}.log"
def log... |
# @time: 2022/1/12 10:07 AM
# Author: pan
# @File: src.py
# @Software: PyCharm
"""
核心代码文件
"""
from db import db_handle
from lib import common
# 存储用户信息
user_data = []
# 注册功能
def register():
"""
项目注册功能 如果已经注册提示已经注册
密码需要两次输入的密码一致才可以
:return:
"""
while True:
inp_name = input("请输入用户名:(输入q退出... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from django.shortcuts import render
from rest_framework import generics
from rest_framework.views import APIView, Response
from celery import task
@task
def test(*args, **kwargs):
print('args: ', args)
print('kwargs: ', kwargs)
... |
"""Configuration module.
This module provides functions for finding, reading, and creating user
configuration files. It also provides an object, CONFIG, for easy access
to the loaded config.
"""
import os
import shutil
from configparser import ConfigParser
DEFAULT_CONFIG_FILE = "~/.config/reddit-wall.conf"
# FIXME:... |
# coding: utf-8
import os
from setuptools import setup
import lspy
this_dir = os.path.dirname(os.path.abspath(__file__))
keywords = [
"rpc", "json", "json-rpc", "2.0", "lsp"
]
classifiers = [
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python... |
from dateutil import parser
from time import mktime
from bamboo.lib.utils import combine_dicts, replace_keys
def parse_order_by(order_by):
if order_by:
if order_by[0] in ('-', '+'):
sort_dir, field = -1 if order_by[0] == '-' else 1, order_by[1:]
else:
sort_dir, field = 1, ... |
"""teset."""
from homeassistant import config_entries
import homeassistant.helpers.config_validation as cv
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import *
from .deps.const import (
DOMAIN,
CONF_UPDATE_INSTANT,
CONF_MAPPING,
CONF_CONTROL_PARAMS,
CON... |
from datetime import datetime, timezone
def parse_youtube_datetime(datetime_str: str) -> datetime:
return datetime.fromisoformat(datetime_str.replace("Z", "+00:00")).astimezone(
timezone.utc
)
|
"""
:copyright: © 2019 by the Lin team.
:license: MIT, see LICENSE for more details.
"""
from datetime import timedelta
class BaseConfig(object):
"""
基础配置
"""
# 分页配置
COUNT_DEFAULT = 10
PAGE_DEFAULT = 0
# 屏蔽 sql alchemy 的 FSADeprecationWarning
SQLALCHEMY_TRACK_MODIFICATIONS = ... |
import pytest
import os
import re
import ssg.build_cpe
import ssg.xml
ET = ssg.xml.ElementTree
def test_extract_element():
obj = """<?xml version="1.0"?>
<variables>
<var>
<subelement>
<random id="test">This</random>
</subelement>
</var>
<var>
... |
import sys
import os
import click
from .. import shared
@shared.cli.command()
@click.argument("path", required=True)
@click.option("--kind", "-k", required=False)
@click.option("--force", "-f", is_flag=True, required=False)
@click.option("--symlink", "-s", is_flag=True, required=False)
@click.pass_context
def take(... |
import re
import core.functions
from cgi import escape
class MarkdownParser:
def __init__(self, resource_path, **kwargs):
self.resource_path = resource_path
self.options = kwargs
self.codeblocks = []
self.table_blocks = []
self.tables = []
def _render_italics(self, matc... |
# -*- coding: utf8 -*-
__author__ = 'wangqiang'
'''
多进程方式的生成者-消费者模型
多进程的实现,借助外部存储(如redis)实现数据共享
pip install redis
'''
import redis
import multiprocessing
import time
import uuid
import random
def producer(name, share_cache, cache_key):
'''
生产者,执行业务逻辑,并向共享缓存写入消息
:param name: 生产者名字代号
:param share_cac... |
from time import sleep
from data_sources.aa_residues import aa_residues
from data_sources.coguk_me import coguk_me
from data_sources.our_sequence_annotations import our_sequence_annotations
from data_sources.ruba_aa_change_effects import effects_of_aa_changes
from data_sources.ruba_variant_effects import effects_of_var... |
import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
__all__ = [
'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn',
'vgg19_bn', 'vgg19',
]
model_urls = {
'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',
'vgg13': 'https://download.pytorch.o... |
# Seq de Fibonacci
print('-=-'*8)
print('Sequência de Fibonacci')
print('-=-'*8)
# 0, 0+1, 0+1, 1+1, 2+1, ..., n = (n-1) + (n-2)
n = int(input('Quantos termos você quer ver? '))
t1 = 0
t2 = 1
print('~'*30)
print(f'{t1} -> {t2}', end='')
cont = 3 # Começa no 3, pois o primeiro e segundo termos já foram mostrados
while ... |
import ctypes
import epicscorelibs.path
# Necessary unless [DY]LD_LIBRARY_PATH is set for epicscorelibs
ctypes.CDLL(epicscorelibs.path.get_lib("Com"))
ctypes.CDLL(epicscorelibs.path.get_lib("dbCore"))
del epicscorelibs.path
del ctypes
# from . import iocsh, macro
# __all__ = ["iocsh", "macro"]
|
import unittest
from unittest.mock import MagicMock, call
import kleat.misc.settings as S
from kleat.hexamer.hexamer import extract_seq
def test_with_skipped_region_for_plus_strand_clv():
"""
AAA <-tail of suffix contig
ACGG--GC┘|| <-suffix contig with skip
01... |
"""Definition of wrapperobject CPython's structure in ctypes. With this you can
get into wrapperobject internals without going to the C level.
See descrobject.c for reference:
http://svn.python.org/view/python/trunk/Objects/descrobject.c?view=markup
Note that not all fields are defined, only those that I needed.
""... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-05-18 09:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('filter', '0022_auto_20180413_1120'),
]
operations = [
migrations.AddField(
... |
import os
# OAuth Settings
AUTH0_CALLBACK_URL = 'http://localhost:8000/callback'
AUTH0_CLIENT_ID = os.environ.get('AUTH0_CLIENT_ID')
AUTH0_CLIENT_SECRET = os.environ.get('AUTH0_CLIENT_SECRET')
AUTH0_DOMAIN = os.environ.get('AUTH0_DOMAIN')
# Flask settings
FLASK_SERVER_ADDRESS = '0.0.0.0'
FLASK_SERVER_PORT = 5000
FLAS... |
import numpy as np
from ci_framework import FlopyTestSetup, base_test_dir
import flopy
from flopy.utils.util_array import Util2d
base_dir = base_test_dir(__file__, rel_path="temp", verbose=True)
def test_rchload():
model_ws = f"{base_dir}_test_rchload"
test_setup = FlopyTestSetup(verbose=True, test_dirs=mod... |
#! /usr/bin/env python
# encoding: utf-8
# WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file
import sys
from waflib.Tools import ar,d
from waflib.Configure import conf
@conf
def find_gdc(conf):
conf.find_program('gdc',var='D')
out=conf.cmd_and_log([conf.en... |
from elasticsearch import Elasticsearch
from elastic_feeder.csv_reader import CsvReader
from elastic_feeder.exception import ElkConnectionError
from elastic_feeder.elastic import Elastic
from elasticsearch.exceptions import AuthenticationException
from elastic_feeder.helper import logger
from http import HTTPStatus... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A script to create the directory structure of each country and three of the "orig" files.
Typically you would run this file from a command line like this:
ipython3.exe -i -- /deploy/cbmcfs3_runner/scripts/orig/copy_orig_files.py
"""
# Third party modules #
# ... |
import numpy as np
import matplotlib.pyplot as plt
import scprep
import pandas as pd
from TrajectoryNet.dataset import EBData
from EB_dataset_prior import get_prior_EB
from gp_sinkhorn.SDE_solver import solve_sde_RK
from gp_sinkhorn.MLE_drift import *
from gp_sinkhorn.utils import plot_trajectories_2
import torch
fro... |
tup_numbers = (1,2,3,4,5,6,7)
lst_numbers = [1,2,3,4,5,6,7,1,1,1,1,1,1]
str_numbers = '1234567'
numbers = set(list(str_numbers))
print(numbers) |
# use beautifulsoup to scrap the following cnbc rss feed https://www.cnbc.com/id/100003114/device/rss/rss.html
from typing import List
import requests
from bs4 import BeautifulSoup
def get_feed_data(request_url: str ='https://www.cnbc.com/id/100003114/device/rss/rss.html'):
# feeds the cnbc feeds for investing and... |
#! /usr/bin/python2.7
import os
import sys
sys.stdout.write(sys.stdin.read()[::-1])
|
from Source.task4.Rect import Rect
def task4():
f = open('input.txt', 'r')
lines = f.readlines()
f.close()
n = int(lines[0])
count = 0
for i in range(1, n+1):
px, py, x1, y1, x2, y2, x3, y3, x4, y4 = [int(s) for s in lines[i].split(' ')]
count += Rect(x1, y1, x2, y2, x3, y3, x4... |
#from pyon.ion.endpoint import ProcessRPCClient
from pyon.public import Container, IonObject
from pyon.util.int_test import IonIntegrationTestCase
from pyon.core.exception import BadRequest, NotFound, Conflict
from pyon.public import RT, LCS, PRED
from mock import Mock, patch
from pyon.util.unit_test import PyonTestCas... |
#!/usr/bin/env python
import re
from binaryninja.log import log_info
from binaryninja.architecture import Architecture
from binaryninja.function import RegisterInfo, InstructionInfo, InstructionTextToken
from binaryninja.enums import InstructionTextTokenType, BranchType, FlagRole, LowLevelILFlagCondition
from breach... |
import imp
from flask import Flask
from config import config_options
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_uploads import UploadSet, configure_uploads, IMAGES
from flask_mail import Mail
from flask_simplemde import SimpleMDE
bootst... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 16 16:03:42 2022
@author: Admin
"""
#!/usr/bin/env python3
import datetime
import time
import random
import sys
start = datetime.datetime.strptime("31-10-2019", "%d-%m-%Y")
end = datetime.datetime.strptime("17-01-2022","%d-%m-%Y")
date_generated = [start + ... |
import json
import urllib2
import requests
def refresh_data():
f = open('/Users/boswald/Sites/gcloudsite/appengine-django-skeleton/league/tools/data/champdata.json', 'w')
data = requests.get('https://na.api.pvp.net/api/lol/static-data/na/v1.2/champion?champData=all&api_key=80a03926-6e55-4045-bf6f-692ec7007ca1')
da... |
from bs4 import BeautifulSoup
import showtimes
import datetime
import re
import requests
MONDAY = 0
SUNDAY = 6
SATURDAY = 5
def scrape(site_url="https://afisilver.afi.com/films/calendar.aspx"):
"""
"""
# scrape from site
page = requests.get(site_url)
soup = BeautifulSoup(page.content, "html.pars... |
import ast
import asyncio
import collections
import copy
import html
import logging
import os
from typing import Dict, List, Optional, Tuple
import graphviz as gv
from .common import (FullLoadContext, LoadContext, PVRelations,
ScriptPVRelations, dataclass)
from .db import RecordField, RecordInsta... |
""" APIs of data """
from .mean_var_data import MeanVarData
from .mean_var_data_rep import MeanVarDataRep
from .ld_transform_data import LDTransformData
from .ld_transform_bayes_data import LDTransformBayesData
from .mlmc_data import MLMCData
from .mlqmc_data import MLQMCData
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os
import numpy as np
import torch
from tqdm import tqdm
from definitions import Keyframe, path_data
from training_config import Train_Co... |
from flask import Flask, request, jsonify
from decouple import config
from flask_cors import CORS
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from nltk import tokenize
def create_app():
app =Flask(__name__)
CORS(app)
sid = SentimentIntensityAnalyzer()
@app.route('/')
def root():
... |
print('=' * 12 + 'Desafio 84' + '=' * 12)
info = []
temp = []
resp = 'S'
menor = -1
maior = -1
contador = 0
while resp in 'sS':
temp.append(input('Digite o nome: '))
temp.append(float(input('Digite o peso: ')))
info.append(temp[:])
if menor == -1:
menor = temp[1]
maior = temp[1]
if t... |
def celsius_to_fahrenheit(temperature):
return (temperature * (9 / 5) + 32)
|
# NOTE: diluted https://github.com/jic-dtool/dtool-lookup-server/blob/master/tests/__init__.py
import random
import string
import os
import sys
import pytest
# Pytest does not add the working directory to the path so we do it here.
_HERE = os.path.dirname(os.path.abspath(__file__))
_ROOT = os.path.join(_HERE, "..")
s... |
# Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: david@reciprocitylabs.com
# Maintained By: david@reciprocitylabs.com
import sys
from ggrc import settings
import ggrc
def get_extension_name(exte... |
from datetime import datetime
from unittest import TestCase
from hl7.datatypes import _UTCOffset, parse_datetime
class DatetimeTest(TestCase):
def test_parse_date(self):
self.assertEqual(datetime(1901, 2, 13), parse_datetime("19010213"))
def test_parse_datetime(self):
self.assertEqual(
... |
# Copyright 2017 OpenStack.org
#
# 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... |
import aiohttp
import asyncio
import websockets
import json
import logging
import traceback
from collections import defaultdict
from typing import Any, Awaitable, DefaultDict, Dict, Iterable, List, Optional, Type
from ._rules import SlackRule, SlackID
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
c... |
x = 0
y = 1
for i in range(10):
x += y
y += x
print(x)
|
from typing import Any, Dict, cast
import httpx
import pytest
from fastapi import FastAPI, status
from httpx_oauth.oauth2 import BaseOAuth2, OAuth2
from fastapi_users.authentication import AuthenticationBackend
from fastapi_users.router.oauth import generate_state_token, get_oauth_router
from tests.conftest import As... |
import pandas
from urllib.parse import quote
import requests
import xml.etree.ElementTree as ET
METADATA_PATH = ''
apis = [('https://api.crossref.org/works/{}', 'crossref'), ('https://api.medra.org/metadata/{}', 'medra')]
preprint_doi_count = 0
not_found_list = []
invalid_doi_list = []
def get_journal(api, response):... |
import torch
from torch import nn
class ConvBlock(nn.Module):
def __init__(self, input_dim, output_dim, dropout=0.1):
super().__init__()
self.conv1 = self._create_conv_sequence(input_dim, output_dim, 128, dropout)
self.conv2 = self._create_conv_sequence(input_dim, output_dim, 256, dropout... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.