text stringlengths 1 927k |
|---|
# coding=utf-8
from sqlalchemy import Column, String
from .base import Base
class NsfHerdFederalAgency(Base):
""" map to a table name in db """
__tablename__ = "nsf_herd_federal_agencies"
""" create columns """
agency_key = Column(String(3), primary_key = True)
agency_name = Column(String(64), n... |
import random
from time import sleep
print('=' *15, 'JOKENPO', '='*15)
opcoes = print('''
[ 0 ] - PEDRA
[ 1 ] - PAPEL
[ 2 ] - TESOURA ''')
jogador = int(input('Qual vai ser sua jogada? '))
itens = ('Pedra', 'Papel', 'Tesoura')
maquina = random.randint(0,2)
print('JO')
sleep(1)
print('KEN')
sleep(1)
print('PO')
sleep(1... |
from http.client import HTTPSConnection, HTTPConnection
import datetime
import os
import urllib.parse
from PIL import Image
import bs4
import copy
import emailhandler
SUBSCRIBED_COMICS = [
173,
873,
359,
1227,
991,
]
MAIL_SENDER = os.environ.get("MAIL_SENDER")
SMTP_HOST = os.environ.get("SMTP_HOST... |
import tensorflow as tf
import numpy as np
from cae_input_brain import *
from utils import *
# Define custom API for creating and adding layers to NN Model
# Wrapper around Tensorflow API, for ease of use and readibility
class Layers(object):
def __init__(self):
self.stdDev = 0.35
''' Initializes t... |
# Use Python 2.7
# This script to run once per week the day that the PDFs are updated
# 1. Download latest PDF on the WA Police website [x]
# 2. Convert PDF into CSV [x]
import tabula
import urllib
import os
from datetime import datetime
import csv
import psycopg2
import sys
import urlparse
import tempfile
import re
f... |
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from assets.models import Asset, AssetTag, AssetGroup
# Create your models here.
class Profile(models.Model):
ACCOUNT_CHOICES = (
(0, 'private'),
(1, 'public'),
... |
from unittest import TestCase
from giosg.crypter import (
symmetric_encrypt, symmetric_decrypt,
asymmetric_encrypt, asymmetric_decrypt)
from giosg.crypter import AESKey
from Cryptodome.PublicKey import RSA
class CrypterTest(TestCase):
def setUp(self):
self.plaintext = "The Line is Open!"
def... |
# ============================================================================
# FILE: tag.py
# AUTHOR: Shougo Matsushita <Shougo.Matsu at gmail.com>
# License: MIT license
# ============================================================================
from .base import Base
from denite.util import parse_tagline
from o... |
import spacy
nlp = spacy.load("en_core_web_sm")
text = "It’s official: Apple is the first U.S. public company to reach a $1 trillion market value"
# Processar o texto the text
doc = nlp(text)
# Iterar nas entidades previstas
for ent in doc.ents:
# Imprimir o texto e a etiqueta da entidade
print(ent.text, en... |
#!/bin/env python
"""
This file defines a set of system_info classes for getting
information about various resources (libraries, library directories,
include directories, etc.) in the system. Currently, the following
classes are available:
atlas_info
atlas_threads_info
atlas_blas_info
atlas_blas_threads_info
... |
import socket
import sys
import cv2
import pickle
import numpy as np
import struct
from datetime import datetime
HOST = '127.0.0.1'
PORT = 8083
cliente = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Cliente iniciado!')
cliente.connect((HOST, PORT))
print('Cliente conectado.')
print('Endereco do servidor:... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# 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 modifications or derivative wo... |
from dataclasses import dataclass
from typing import Set, List
from extractors.CharacterFactory import Character, CharacterFactory
@dataclass
class Block(object):
name: str
start: int
end: int
characters: List[Character]
class BlockFactory(object):
def __init__(self: 'BlockFactory', character_f... |
import numpy as np
def iou_point_np(box, boxes):
"""
Find intersection over union
:param box: (tensor) One box [xmin, ymin, xmax, ymax], shape: [4].
:param boxes: (tensor) Shape:[N, 4].
:return: intersection over union. Shape: [N]
"""
A = np.maximum(box[:2], boxes[:, :2])
B = np.minim... |
"""This superclass represents our get_value abstract class"""
from abc import abstractmethod
from typing import List
from utils.setting import Setting
class SettingSFA(Setting):
"""Each setting (topology) has to implements methods to obtain
the bounds"""
@abstractmethod
def sfa_arr_bound(self, param... |
# @pytest.mark.parametrize(参数名, [参数值 1,参数值 2,....])
# def test_xxx(self, 参数名)
# @pytest.mark.parametrize( [参数名1,参数名2,...], [ (参数值 1,参数值 2), (参数值 3,参数值 4),...])
# def test_yyy(self, 参数名1,参数名2,...)
import pytest
@pytest.mark.parametrize('a', [1, 2, 3])
def test_1(a):
print(a)
print('test 1')
@pytest.mark.p... |
from collections import Counter
anzZweier, anzDreier = 0,0
with open('AdventOfCode_02_1_Input.txt') as f:
for zeile in f:
zweierGefunden, dreierGefunden = False, False
counter = Counter(zeile)
for key,value in counter.items():
if value == 3 and not dreierGefunden:
anzDreier += 1
dr... |
"""Lemmatization module—includes several classes for different
lemmatizing approaches--based on training data, regex pattern matching,
etc. These can be chained together using the backoff parameter. Also,
includes a pre-built chain that uses models in cltk_data.
The logic behind the backoff lemmatizer is based on back... |
import asyncio
import inspect
import logging
from typing import Dict, List, Callable
from . import api
from .channel import public_channel_factory, PublicChannel
from .gateway import Gateway, Requestable
from .guild import Guild
from .interface import AsyncRunnable, MessageTypes
from .message import RawMessage, Event,... |
import os
from django.contrib import auth
from django.contrib.auth import get_user_model
from django.contrib.auth.tokens import default_token_generator
from django.core import mail
from django.test import TestCase
from django.urls import resolve
from django.utils.encoding import force_bytes
from django.utils.http impo... |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.11.3
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
... |
from __future__ import absolute_import, print_function, division
from ufoLib.pointPen import AbstractPointPen
def replayRecording(recording, pen):
"""Replay a recording, as produced by RecordingPointPen, to a pointpen.
Note that recording does not have to be produced by those pens.
It can be any iterabl... |
import tensorflow as tf
from Samplers.sampler import Sampler
class MirrorSlice(Sampler):
"""
An implementation of the Mirror Slice Sampling MCMC sampler. This sampler
works by picking a random direction, moving a set distance in that
direction, then reflecting off the gradient of the distribution if i... |
#!/usr/bin/env python
# Darwin Bautista
# HomographyNet, from https://arxiv.org/pdf/1606.03798.pdf
import os.path
from tensorflow.keras.applications import MobileNet
from tensorflow.keras import Model
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layer... |
"""
Copyright 2020 The OneFlow 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 applicable law or agr... |
# -*- coding: utf-8 -*-
"""Functions searching in IMAP account"""
import ast
import codecs
import datetime
import email
from email import header
import logging
import re
import sys
import docopt
import six
import imap_cli
from imap_cli import config
from imap_cli import const
from imap_cli import fetch
log = lo... |
# Copyright 2021 QuantumBlack Visual Analytics 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 License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# THE SOFTWARE IS PROVIDED "AS IS",... |
import argparse
import os
import sys
# Hack to work around Python 3.8+ secure dll loading
# See https://docs.python.org/3/whatsnew/3.8.html#bpo-36085-whatsnew
if hasattr(os, "add_dll_directory"):
for directory in os.environ.get("PATH", "").split(os.pathsep):
if os.path.isdir(directory):
os.add_... |
import pytest
from django.test import Client
from applications.tests.conftest import * # noqa
from oidc.tests.factories import EAuthorizationProfileFactory, OIDCProfileFactory
@pytest.fixture
def oidc_profile():
return OIDCProfileFactory()
@pytest.fixture
def eauthorization_profile():
return EAuthorizatio... |
import setuptools
with open("README.rst", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="chesstutor-Ceasar",
version="0.0.6",
author="Ceasar Bautista",
author_email="cbautista2010@gmail.com",
description="Play chess on the command line.",
install_requires=['click', 'pytho... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: publishers.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _re... |
from python_framework import SqlAlchemyProxy as sap
from ModelAssociation import QUEUE, SUBSCRIPTION, MODEL
from util import ModelUtil
class QueueModel(MODEL):
__tablename__ = QUEUE
id = sap.Column(sap.Integer(), sap.Sequence(f'{__tablename__}{sap.ID}{sap.SEQ}'), primary_key=True)
key = sap.Column(sap.S... |
# flake8: noqa I201
from Token import SYNTAX_TOKEN_MAP
from kinds import kind_to_type
class Child(object):
"""
A child of a node, that may be declared optional or a token with a
restricted subset of acceptable kinds or texts.
"""
def __init__(self, name, kind, is_optional=False,
t... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021. Jeffrey Nirschl. All rights reserved.
#
# Licensed under the MIT license. See the LICENSE file in the project
# root directory for license information.
#
# Time-stamp: <>
# ======================================================================
import argparse... |
import subprocess
import json
import os
p = subprocess.check_output(["terraform", "output", "-json"], cwd="../.")
json = json.loads(p.decode("utf-8"))
if not os.path.isdir("../certs"):
os.mkdir("../certs", mode=0o755)
os.chmod("../certs", mode=0o755)
if not os.path.isdir("../config"):
os.mkdir("../confi... |
from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.orm import relationship
from .base import Base
from .given_title import GivenTitle
from .shuffled_title import ShuffledTitle
class GivenShuffledTitle(GivenTitle):
__tablename__ = f"{Base.TABLENAME_PREFIX}given_shuffled_titles"
title_id = Col... |
from data.detection.voc import VOCDataset
from neodroidvision.detection.single_stage.ssd.config.ssd_base_config import base_cfg
base_cfg.data_dir = base_cfg.data_dir / "PASCAL" / "Train"
base_cfg.model.backbone.update(out_channels=(512, 1024, 512, 256, 256, 256, 256))
base_cfg.model.box_head.priors.update(
featu... |
'''ResNet in PyTorch.
For Pre-activation ResNet, see 'preact_resnet.py'.
Reference:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Deep Residual Learning for Image Recognition. arXiv:1512.03385
resnet same as the origin paper
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
import num... |
i = random.n
print (i) |
"""Register WS API endpoints for HACS."""
from homeassistant.components import websocket_api
from custom_components.hacs.api.acknowledge_critical_repository import (
acknowledge_critical_repository,
)
from custom_components.hacs.api.check_local_path import check_local_path
from custom_components.hacs.api.get_criti... |
"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W... |
def sequence_generator(n):
"""
Generates sequence of numbers for a given positive integer 'n' by iterative process as specified in Goldbach
conjecture.
:param n: positive
:return: list of numbers in the generated sequence, boolean indicating whether last element of sequence is 1
"""
if not i... |
from .tutti import * |
"""
This class provide an interface for other libraries to specific modules. For example, the evolutionary operations
can be used easily just by calling a function and providing the lower and upper bounds of the problem.
"""
import copy
import types
import numpy as np
from pymoo.model.algorithm import filter_optimum... |
#!/usr/bin/python3
# Copyright 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... |
import scipy.io as sio
import numpy as np
import torch.nn as nn
import torch
from models.BCNN import BCNN
#matlab文件名
class IQANet_trancated(nn.Module):
def __init__(self, matfile):
super(IQANet_trancated, self).__init__()
# matfile = r"C:\Users\chengyu\Desktop\IQAloss\Hu\matlab_code\net.mat"
... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: mesh/v1alpha1/config.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from... |
from django.contrib import admin
from django.urls import path, re_path, include
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
re_path(r'^', include('apps.movimientos.urls')),
path('admin/', admin.site.urls),
]+ static(settings.MEDIA_URL, document_root=settings.ME... |
"""Config flow to configure Renault component."""
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from .const import ( # pylint: disable=unused-import
AVAILABLE_LOCALES,
CONF_GIGYA_APIKEY,
CONF_KAMEREON_ACCOUNT_ID,
CONF_KA... |
"""
Data structure for 1-dimensional cross-sectional and time series data
"""
from __future__ import division
# pylint: disable=E1101,E1103
# pylint: disable=W0703,W0622,W0613,W0201
import types
import warnings
from numpy import nan, ndarray
import numpy as np
import numpy.ma as ma
from pandas.core.common import (i... |
# -*- coding: utf-8 -*-
import hashlib
DEFAULT_CHUNK_SIZE = 1 << 6
def get_text_fingerprint(text, hash_meth, encoding="utf-8"): # pragma: no cover
"""
Use default hash method to return hash value of a piece of string
default setting use 'utf-8' encoding.
"""
m = hash_meth()
m.update(text.en... |
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import utils.network as net_utils
import cfgs.config as cfg
from layers.reorg.reorg_layer import ReorgLayer
from utils.cython_bbox import bbox_ious, anchor_intersections
from utils.cython_yolo import yolo_to_bbox
from functools impor... |
class Solution(object):
def numIslands2(self, m, n, positions):
"""
:type m: int
:type n: int
:type positions: List[List[int]]
:rtype: List[int]
"""
## union-find
h = m
w = n
t = [None for x in range(h * w)]
res=[]
... |
#!/usr/bin/env python
# Siconos is a program dedicated to modeling, simulation and control
# of non smooth dynamical systems.
#
# Copyright 2021 INRIA.
#
# 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 L... |
from Shared import Net
def main():
sock = Net("127.0.0.1", 8000) # Opens a UDP connection
sock.start_server()
try:
while True:
print(sock.read_message())
except KeyboardInterrupt:
return
main() |
# Copyright 2019-present MongoDB, 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 wri... |
import os
import sys
import crispy_forms
from setuptools import setup, find_packages
if sys.argv[-1] == 'publish':
if os.system("pip freeze | grep wheel"):
print("wheel not installed.\nUse `pip install wheel`.\nExiting.")
sys.exit()
if os.system("pip freeze | grep twine"):
print("twin... |
"""
Copyright Zapata Computing, Inc. All rights reserved.
This module manipulates data.
"""
import sys
import json
import numpy as np
import pandas as pd
from typing import TextIO
def noisy_sine_generation(time_range:float, time_step:float, noise_std:float) -> dict:
"""
Generates noisy sine data.
Args... |
'''
Created on 28 apr 2012
@author: hbergk
Contains the basic syntax to produce makefile
'''
#
# Imports
#
import os
import casual.make.plumbing
import casual.make.porcelain
from casual.make.output import Output
#
# Select specific version or leave empty for latest
#
_plumbing = casual.make... |
from __future__ import division
import cctbx.eltbx.fp_fdp # import dependency
import boost.python
ext = boost.python.import_ext("cctbx_eltbx_sasaki_ext")
from cctbx_eltbx_sasaki_ext import * |
"""
This module enables log functionality inside the CLI
"""
from termcolor import colored
import datetime
from prompt_toolkit.document import Document
from core.Event import Event
from prompt_toolkit import print_formatted_text
from filelock import Timeout, FileLock
class Log:
"""
Define simple info, debug ... |
"""
homeassistant.components.thermostat.heat_control
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Adds support for a thermostat.
Specify a start time, end time and a target temperature.
If the the current temperature is lower than the target temperature,
and the time is between start time and end time, the heater ... |
# ----------------------------------------------------------------------------
# - Open3D: www.open3d.org -
# ----------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2018-2021 www.open3d.org
#
# Permission i... |
#!usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Pilot pen adapters module.
"""
__author__ = 'Ziang Lu'
from friend import PilotPen
from myself.adapters.adapter import Adapter
from myself.assignment_work import Pen
class _PilotPenAsPen(Pen):
"""
Concrete PilotPenAsPen class that works as "Adapter".
N... |
from zope.interface import implements
from twisted.application.service import IServiceMaker
from twisted.application import internet
from twisted.plugin import IPlugin
from twisted.python import usage
from twistedcv import DetectorServerFactory
class Options(usage.Options):
optParameters = [
["port","p",9000,"The... |
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import add_days, date_diff
from erpnext.hotels.doctype.hotel_room_reservation.hotel_room_reservation impor... |
devices = dict(
selector_speed = device('nicos.devices.generic.VirtualMotor',
abslimits = (0, 28500),
precision = 10,
unit = 'rpm',
),
selcradle = device('nicos.devices.generic.VirtualMotor',
abslimits = (-10, 10),
precision = 0.001,
unit = 'deg',
),
s... |
from django.shortcuts import redirect
import jwt
import datetime
from jwt import exceptions
import base64
from influxweb.settings import JWT_SALT
# Create your code here.
# 验证登录状态
def login_required(fun):
def inner(request,*args,**kwargs):
request.session['is_login'] = True
request.session['user_i... |
from rest_framework.status import HTTP_201_CREATED, HTTP_200_OK
from rest_framework.generics import GenericAPIView, CreateAPIView, UpdateAPIView
from rest_framework.response import Response
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_fra... |
# Lint as: python3
# Copyright 2019 The TensorFlow 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 r... |
#!/usr/bin/env python
import unittest
from graph import Graph
from graph_exceptions import DigraphError, NotDigraphError
class TestBasicOperations(unittest.TestCase):
def test_construct_with_params(self):
graph = Graph({
"a": set(["b", "d"]),
"b": set(["a"]),
"c": set([]),
"d": set(["a"]),
"e": set... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 - 2018 -- Lars Heuer - Semagia <http://www.semagia.com/>.
# All rights reserved.
#
# License: BSD License
#
"""\
Standard serializers and utility functions for serializers.
The serializers are independent of the :py:class:`segno.QRCode` (and the
:py:class:`segno.encoder.C... |
import filecmp
import os
import platform
import posixpath
import tempfile
import pytest
from dvc.fs.ssh.connection import SSHConnection
from dvc.info import get_fs_type
from dvc.system import System
here = os.path.abspath(os.path.dirname(__file__))
SRC_PATH_WITH_SPECIAL_CHARACTERS = "Escape me [' , ']"
ESCAPED_SRC_... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# Copyright (c) 2018-2019 NVIDIA CORPORATION. All rights reserved.
import torch
import apex
from .optimizers.schedulers import WarmupMultiStepLR
from .optimizers.schedulers import CosineAnnealingWarmUpRestarts
from .optimizers import MLPerfFusedS... |
#!/usr/bin/env python3
"""This is an example to train PPO on ML1 Push environment."""
# pylint: disable=no-value-for-parameter
import click
import metaworld
import torch
from garage import wrap_experiment
from garage.envs import normalize
from garage.envs.multi_env_wrapper import MultiEnvWrapper, round_robin_strategy
... |
import keras
from keras.layers import Dense, Dropout, Flatten
from keras.models import Sequential
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
import requests
import os
import pickle
from fedn.client import AllianceRuntimeClient
from scaleout.repository.helpers import... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from tradeapi.utils import *
class APIResponseBase(object):
def __init__(self, apikey, return_code, return_msg,
result_code, result_msg, out_trade_no, trx_bill_no, **kwargs):
self.return_code = return_code
self.return_msg = return_msg
self.... |
import os
import sys
from baselines.ibcc import IBCC
from baselines.majority_voting import MajorityVoting
from bsc.bsc import BSC
from data import data_utils
from evaluation.experiment import Experiment, calculate_scores
import data.load_data as load_data
import numpy as np
import pandas as pd
output_dir = '../../dat... |
import pandas as pd
from pathlib import Path
from tqdm.auto import tqdm
tqdm.pandas()
path = Path('../data-truth/COVID-19/deconvoluted/')
files = sorted([f.name for f in path.glob('**/*')])
dates = [f[:10] for f in files]
dfs = []
for f in files:
date = f[:10]
df_temp = pd.read_csv(path/f)
df_temp = df_te... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
import cin_constants
import cin_register_map
import cin_functions
import time
cin_functions.WriteReg(cin_register_map.REG_TRIGGERMASK_REG, "0003", 0) |
# 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... |
''' Script for downloading all GLUE data.
Note: for legal reasons, we are unable to host MRPC.
You can either use the version hosted by the SentEval team, which is already tokenized,
or you can download the original data from (https://download.microsoft.com/download/D/4/6/D46FF87A-F6B9-4252-AA8B-3604ED519838/MSRParaphr... |
from overrides import overrides
import numpy as np
from transformers import BertTokenizer
from stog.data.vocabulary import DEFAULT_PADDING_TOKEN, DEFAULT_OOV_TOKEN
class AMRBertTokenizer(BertTokenizer):
def __init__(self, *args, **kwargs):
super(AMRBertTokenizer, self).__init__(*args, **kwargs)
@o... |
from flask import Flask, jsonify, request, render_template, Response, send_file
# from prefix_and_wsgi_proxy_fix import ReverseProxied
from base64 import urlsafe_b64encode
import gpxpy.gpx
import geojson
import werkzeug.exceptions
import os
from werkzeug.datastructures import Headers
from db_functions import get_waypoi... |
from .api import * |
'''
fast scnn
author: zacario li
date: 2020-03-27
'''
import time
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
class FastSCNN(nn.Module):
def __init__(self, numClasses, aux=False, **kwargs):
super(FastSCNN, self).__init__()
# auxiliary, use to accelarate the conver... |
class Solution:
def minCostClimbingStairs(self, cost):
"""
:type cost: List[int]
:rtype: int
"""
len1 = len(cost)
ans = [3000000000] * len1
ans[0], ans[1] = cost[0], cost[1]
for i in range(2, len1):
ans[i] = min(ans[i - 2], ans[i - 1]) + co... |
#!/usr/bin/env python3
"""
Annotate VEP hits with GO terms using the Monarch API, which queries the
Amigo solr instance - http://amigo.geneontology.org/amigo
Note there is an official VEP plugin to do this:
https://uswest.ensembl.org/info/docs/tools/vep/script/vep_plugins.html
but this does not return any GO terms
T... |
# Copyright (C) 2010-2011 Richard Lincoln
#
# 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, publish... |
#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(marks) / len(marks)
def friend(self, friend_name):
return Student(friend_name, self.school)
anna = Student("Anna", "Oxford")
frien... |
larg = float(input('Lagura da parade: '))
altu = float(input('Altura da parade: '))
area = larg * altu
tinta = area / 2
print(f'Sua parede tem a dimensão {larg}x{altu} e tem a area {area}m²')
print(f'Para pintar essa parede você precisará de {tinta:.1f}l de tinta') |
from modulefinder import ModuleFinder
# 有时候很多人导入直接用*,这时候就可以使用ModuleFinder来分析了
finder = ModuleFinder()
finder.run_script('模块名.py')
print('加载的模块:')
for name, mod in finder.modules.items():
print('%s: ' % name, end='')
print(','.join(list(mod.globalnames.keys())[:3]))
print('-'*50)
print('未导入模块:')
print('\n'.jo... |
import json
import random
vocablury_file = open("vocablury.json", "r")
sent_words_file = open("sent_words.txt", "r+")
dictionary_file = open("dictionary.json", "r")
sent_words_read = sent_words_file.readlines()
vocablury_data = json.load(vocablury_file)
dictionary_data = json.load(dictionary_file)
sent_words = list(m... |
# Copyright 2021 Modelyst 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
import argparse
import os
from os.path import join
import mmcv
import torch
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import (get_dist_info, init_dist, load_checkpoint,
wrap_fp16_model)
from mmcv.utils import DictAction
from mmseg.apis import multi_g... |
import numpy as np
import matplotlib.pyplot as plt
import getCSVdata
# LINEAR CHARACTERISTIC - No DYNAMICS
#inputFileName = '../data/SimulationData_StuckValve_lin_noDyn.csv'
#outputFileName = '../data/NoisyData_StuckValve_lin_noDyn.csv'
# LINEAR CHARACTERISTIC - DYNAMICS
#inputFileName = '../data/SimulationData_Stuck... |
import poplib
import email
import time
class MailHelper:
def __init__(self, app):
self.app = app
def get_mail(self, username, password, subject):
for i in range(5):
pop = poplib.POP3(self.app.config['james']['host'])
pop.user(username)
pop.pass_(password)
... |
class Solution:
def romanToInt(self, s: str) -> int:
num = { 'M': 1000, 'CM': 900, 'D': 500, 'CD': 400, 'C': 100, 'XC': 90, 'L': 50, 'XL': 40, 'X': 10, 'IX': 9, 'V': 5, 'IV': 4, 'I': 1 }
ans = 0
for key, value in num.items():
while s.startswith(key):
ans += value... |
import argparse
import getpass
import os
import sys
from copy import deepcopy
from typing import List, Optional, Union
from .constants import DEFAULT_FORMAT_OPTIONS, SEPARATOR_CREDENTIALS
from ..sessions import VALID_SESSION_NAME_PATTERN
class KeyValueArg:
"""Base key-value pair parsed from CLI."""
def __in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.