text stringlengths 2 999k |
|---|
from abc import ABC, abstractmethod
import numpy as np
class Vectorizer(ABC):
@abstractmethod
def _vectorize(self, token: str):
pass
@abstractmethod
def _get_keras_layer(self, trainable):
pass
class Token:
def __init__(self, text: str, vectorizer: Vectorizer):
self._text = t... |
# Copyright 2012 Nebula, 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 agree... |
#binary tree python
class BinaryTree:
def __init__(self, content):
self.content = content
self.left = None
self.right = None
self.parent = None
def __str__(self):
return "( " + str(self.content) + " ( " + str(self.left) + " | " + str(self.right) + "))"
#write an algori... |
from PySide6 import QtWidgets
class ActionBar(QtWidgets.QWidget):
def __init__(self, actions):
super().__init__()
self._layout = QtWidgets.QHBoxLayout()
self.setLayout(self._layout)
for action in actions:
btn = QtWidgets.QPushButton(action[0])
btn.clicked.... |
import base64
import hmac
from hashlib import sha1
from six import PY3
from twilio.compat import izip, urlparse
def compare(string1, string2):
"""Compare two strings while protecting against timing attacks
:param str string1: the first string
:param str string2: the second string
:returns: True if... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='callback'),
] |
class PropertyChangingEventHandler(MulticastDelegate, ICloneable, ISerializable):
"""
Represents the method that will handle the System.ComponentModel.INotifyPropertyChanging.PropertyChanging event of an System.ComponentModel.INotifyPropertyChanging interface.
PropertyChangingEventHandler(object: object... |
from django.urls import path
from . import views
urlpatterns = [
path('organization-lc/', views.OrganizationListCreateAPIView.as_view(),
name='organization_lc'),
path('organization-creator-l/', views.OrganizationCreatorListAPIView.as_view(),
name='organization_creator_l'),
path('organiz... |
from sympy import (Lambda, Symbol, Function, Derivative, Subs, sqrt,
log, exp, Rational, Float, sin, cos, acos, diff, I, re, im,
E, expand, pi, O, Sum, S, polygamma, loggamma, expint,
Tuple, Dummy, Eq, Expr, symbols, nfloat)
from sympy.utilities.pytest import XFAIL, raises
from sympy.abc import ... |
#!/usr/bin/env python
# Copyright (c) 2017-present, Facebook, 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 a... |
"""Auto-generated file, do not edit by hand. SA metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_SA = PhoneMetadata(id='SA', country_code=966, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='1\\d{7,8}|(?:[2-467]|92)\\d{7}|5\\d{8}|8... |
# swift_build_support/products/clang.py -------------------------*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See http://swift.org/LICENSE.txt... |
import torch
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import DataLoader, Dataset
class _SequenceDataset(Dataset):
def __init__(self, seqs, tokenizer):
self.data = seqs
self.tokenizer = tokenizer
def __len__(self):
return len(self.data)
def __getitem__(sel... |
"""
module for healthcheck api tests
Copyright (c) 2018-2019 Qualcomm Technologies, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met:
Redistri... |
#!/usr/bin/env/python3
# -*- coding: utf-8 -*-
from typing import Dict, Iterable
from pslrp import GramError, Grammar, Production
class LLToken:
def __init__(self, name, value=None):
self.name = name
self.value = value
def __str__(self):
return self.name
def dumps_t... |
from otp.otpbase import OTPGlobals
from otp.otpbase import OTPLauncherGlobals
from otp.otpbase import OTPLocalizer
from direct.gui.DirectGui import *
from pandac.PandaModules import *
import os
import webbrowser
class LeaveToPayDialog:
def __init__(self, paidUser, destructorHook = None, doneFunc = None):
... |
# Copyright 2015 IBM 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 License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""This file contains tests for the mrt_installer.py file.
For speciifics on each test, see the docstrings under each function.
Note that if tests are failing, the self.start and self.end may need
updating to be more recent. Possibly same with the api_param_mods.
"""
__... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import logging
import math
import numpy as np
from typing import List
import torch
from fvcore.nn import giou_loss, sigmoid_focal_loss_jit, smooth_l1_loss
from torch import nn
from torch.nn import functional as F
from detectron2.config import confi... |
# coding: utf-8
"""
Server API
Reference for Server API (REST/Json)
OpenAPI spec version: 1.4.58
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class RegistrationField(object):
"""
NOTE: This class i... |
import typing as tp
import jax
import jax.numpy as jnp
import numpy as np
from flax.linen import linear as flax_module
from treex import types
from treex.module import Module
class Linear(Module):
"""A linear transformation applied over the last dimension of the input.
`Linear` is implemented as a wrapper ... |
"""
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.
https://github.com/facebookresearch/fastMRI/blob/master/data/transforms.py
"""
import numpy as np
import torch
def to_tensor(data):
"""
... |
#!/usr/bin/env python3
import datetime
import logging
import os
import socket
import subprocess
import sys
# trunk-ignore(flake8/F401)
import time
from base64 import b64encode
from pathlib import Path
# trunk-ignore(flake8/F401)
import click
import requests
import urllib3
from dateutil import parser
from dotenv impor... |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 21 10:49:01 2018
@author: utke.markus
"""
import numpy as np
np.random.seed(7)
from scipy import stats
from sklearn import metrics
from sklearn import ensemble
from sklearn import svm
import tensorflow as tf
tf.Session()
tf.set_random_seed(9)
from keras.activations impor... |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# #########################################################################
# Copyright (c) 2015, UChicago Argonne, LLC. All rights reserved. #
# #
# Copyright 2015. UChicago Argonne, LLC. This... |
from collections import Iterable
from mathsat import msat_term, msat_env
from mathsat import msat_make_true, msat_make_false
from mathsat import msat_make_constant, msat_declare_function
from mathsat import msat_get_rational_type
from mathsat import msat_make_and as _msat_make_and
from mathsat import msat_make_or as _... |
'''
This is a crummy little script for me to debug stuff
It's not well-written and ugly
'''
import joblib
# from rlkit.envs import get_env
from rlkit.samplers.in_place import InPlacePathSampler
from wrapped_goal_envs import WrappedFetchPickAndPlaceEnv, DebugReachFetchPickAndPlaceEnv, DebugFetchReachAndLiftEnv, WrappedR... |
import click
import time
import urllib.request
import webbrowser
import sys
def _start_browser(url, debug=False):
from lnt.util import logger
def url_is_up(url):
try:
o = urllib.request.urlopen(url)
except IOError:
return False
o.close()
return True
... |
from srd import add_params_as_attr
import os
from srd.oas import template
module_dir = os.path.dirname(os.path.dirname(__file__))
# wrapper to pick correct year
def program(year, federal):
"""
Fonction qui permet de sélectionner le programme par année.
Parameters
----------
year: int... |
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"label": _("BSC Indicator"),
"items": [
{
"type": "doctype",
"name": "BSC Initiative Log",
"description":_("BSC Initiative Log"),
"onboard": 1,
"dependencies": ["BSC Initiative"],
},
{
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
from pyamf.remoting.gateway.wsgi import WSGIGateway
def echo(data):
return data
services = {
'echo': echo,
# Add other exposed functions here
}
gateway = WSGIGateway(services)
|
import torch
from torch import nn
from exptorch.utils.itertools import pairwise
class LinearNet(nn.Module):
"""Linear feed-forward neural network, i.e. linear regression model."""
def __init__(self, input_dim, output_dim):
super().__init__()
self.linear = nn.Linear(input_dim, output_dim)
... |
"""Executable Python script for running Python actions.
/*
* 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... |
"""NetDaemon class."""
from typing import TYPE_CHECKING, List
from homeassistant.helpers import entity_registry
from homeassistant.helpers.json import JSONEncoder
from homeassistant.helpers.storage import Store
from .const import (
ATTR_ATTRIBUTES,
ATTR_ENTITY_ID,
ATTR_ICON,
ATTR_STATE,
ATTR_UNIT,... |
r"""
Solve Poisson equation on the 4-dimensional (0, 2pi)^4 with periodic bcs
\nabla^2 u = f,
Use Fourier basis and find u in V^4 such that
(v, div(grad(u))) = (v, f) for all v in V^4
where V is the Fourier space span{exp(1jkx)}_{k=-N/2}^{N/2-1} and
V^4 is a 4-dimensional tensorproductspace.
"""
import ... |
log_level = 'INFO'
load_from = None
resume_from = None
dist_params = dict(backend='nccl')
workflow = [('train', 1)]
checkpoint_config = dict(interval=10)
evaluation = dict(interval=10, metric='PCK', save_best='PCK')
optimizer = dict(
type='Adam',
lr=5e-4,
)
optimizer_config = dict(grad_clip=None)
# learning po... |
# fname = raw_input("Enter file name: ")
# if len(fname) < 1 : fname = "mbox-short.txt"
fname = "mbox-short.txt"
fh = open(fname)
count = 0
def getMail(line):
lst = line.split()
return lst[1]
for line in fh:
if line.startswith("From "):
count += 1
print getMail(line)
print "There were"... |
import requests
import base64
sess = requests.session()
URL="127.0.0.1"
PORT="43478"
r = sess.get("http://%s:%s/static/dict.txt" % (URL, PORT))
ordering = {}
for line in r.text.split('\n'):
line = line.strip()
if len(line) == 0:
pass
test = sess.get("http://%s:%s/%s" % (URL, PORT, line))
if... |
#!/usr/bin/env python3
import scipy
import os
import argparse
import numpy as np
from skimage.restoration import unwrap_phase
from scipy import io
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='''Unwrap phase using M. A. Herráez, D. R. Burton, M. J.
Lalor, and M. A. Gde... |
#PROGRAMA QUE CADASTRE VARIAS PESSOAS EM UMA LISTA E CADA PESSOA CADASTRADA EM UM DICIONARIO DENTRO DESSA LISTA,
# E NO FINAL MOSTRE: QUANTAS PESSSOAS FORAM CADASTRADAS, A MEDIA DE IDADE DO GRUPO, LISTA COM TODAS AS MULHERES, LISTA COM TODAS PESSOAS ACIMA DA MÉDIA de idade
pessoas = []
dados = {}
mulheres = []
media... |
import requests
import os
class BaseHelper(object):
def exception(self, problem):
raise BaseException(problem)
class Resource(BaseHelper):
def __init__(self, _type, required_keys, optional_keys, **kwargs):
self.type = _type
self.keys = {
"Required": {key: required_keys[ke... |
'''
.. currentmodule:: pgreaper
'''
from io import StringIO
from collections import OrderedDict
import builtins
import csv
import zipfile
import gzip
import bz2
import lzma
from pgreaper._globals import DEFAULT_ENCODING, ReusableContextManager
def open(file_or_path, compression=None, binary=False, *args, **kwargs):... |
# 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 u... |
import class_0529.class_0529_1
|
# Generated by Django 2.1.7 on 2019-03-23 01:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('piony', '0021_auto_20190323_0250'),
]
operations = [
migrations.AddField(
model_name='dostepnoscogolnapionu',
name='... |
# The MIT License (MIT)
# Copyright (c) 2018 by the xcube development team and contributors
#
# 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... |
# 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 u... |
# Copyright (c) 2016-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
"""Defines a cluster prui... |
import pathlib
from tempfile import TemporaryDirectory
from unittest.mock import patch
import geopandas as gp
import pandas
import pytest
from shapely.geometry import Polygon
from gerrychain.graph import Graph
from gerrychain.graph.geo import GeometryError
@pytest.fixture
def geodataframe():
a = Polygon([(0, 0)... |
with open("text.txt", "r+") as my_file:
my_file.write("Adding to file")
# with... as... with automatically close the file
|
"""This is the Bokeh charts interface. It gives you a high level API to build
complex plot is a simple way.
This is the Scatter class which lets you build your scatter plots just passing
the arguments to the Chart class and calling the proper functions.
It also add detection of the incomming input to see if it is a pa... |
import logging
import os
from converter import Converter
from converter.ffmpeg import FFMpeg, FFMpegConvertError
from django.conf import settings
#ffmpeg_cmd = "/opt/local/bin/ffmpeg"
from dataset_manager.enums import EmotionType, ComputingStateType
logger = logging.getLogger(__name__)
def mkdir_if_not_exists(path):... |
"""
This script simply prints all received HTTP Trailers.
HTTP requests and responses can container trailing headers which are sent after
the body is fully transmitted. Such trailers need to be announced in the initial
headers by name, so the receiving endpoint can wait and read them after the
body.
"""
from mitmprox... |
import copy
from rpython.rlib import jit
from rpython.rlib.objectmodel import compute_unique_id
from topaz import mapdict
from topaz.module import ClassDef
from topaz.scope import StaticScope
class ObjectMetaclass(type):
def __new__(cls, name, bases, attrs):
new_cls = super(ObjectMetaclass, cls).__new__... |
#!/usr/bin/python
# *****************************************************************************
#
# Copyright (c) 2016, EPAM SYSTEMS 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
#
#... |
# Copyright The PyTorch Lightning team.
#
# 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... |
#!c:\users\jaoribe\documents\github\uber-style-platform\uber-mock-env\scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'ipdb==0.11','console_scripts','ipdb3'
import re
import sys
# for compatibility with easy_install; see #2198
__requires__ = 'ipdb==0.11'
try:
from importlib.metadata import distribution
except Imp... |
#!/usr/bin/python3
import sys
from PyQt5.QtWidgets import (QWidget, QPushButton, QLineEdit, QComboBox, QApplication, QLabel)
xl= []
yl= []
class Actividad7(QWidget):
def __init__(self):
super().__init__()
self.ventana()
def ventana(self):
#Etiquetas
self.entrada = QLineEdit("Numero de datos", self)
sel... |
import argparse
import os
from time import sleep
import infolog
import tensorflow as tf
from hparams import hparams
from infolog import log
from tacotron.synthesize import tacotron_synthesize
from tacotron.train import tacotron_train
log = infolog.log
def save_seq(file, sequence, input_path):
'''Save Tacotron-2 tr... |
"""
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... |
from I2C_mutex import Mutex
import time
# needed for duck typing
import gopigo3
import operator
mutex = Mutex()
try:
from di_sensors import easy_line_follower, easy_distance_sensor
di_sensors_available = True
except ImportError as err:
di_sensors_available = False
print(str(err))
except Exception as ... |
import ssl
from datetime import timezone
from typing import Any, Dict, Tuple, List, Optional
from dateparser import parse
from mailparser import parse_from_bytes
from imap_tools import OR
from imapclient import IMAPClient
import demistomock as demisto
from CommonServerPython import *
class Email(object):
def __... |
from .common import *
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ')!lb4$ln(6_mkd)^qrf#xw%6^^gtbjo2syjlz)=)tkrt!d9@il'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = [
'localhost',
'127.0.0.1',
'0.0.0.0',
'nostechprob... |
"""
This class models the redirect page i.e the view buses page of the redBus Main Page
URL: selenium-tutorial-redirect
The page consists of a header, footer and some text
"""
from .Base_Page import Base_Page
from .redBus_header_object import redBus_Header_Object
from .redBus_footer_object import redBus_Footer_Object
... |
#!/usr/bin/env python
# Copyright 2019 D-Wave Systems 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 ... |
# Copyright 2011 Grid Dynamics
# Copyright 2011 OpenStack Foundation
# 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... |
import json
from hc.api.models import Channel, Check, Notification, Ping
from hc.test import BaseTestCase
class LogTestCase(BaseTestCase):
def setUp(self):
super(LogTestCase, self).setUp()
self.check = Check.objects.create(project=self.project)
ping = Ping.objects.create(owner=self.check... |
def turtle(coord, direction):
cord = list(coord)
direct = direction
order = yield cord
while order:
if order == "f":
cord[direct % 2] += 1 if direct < 2 else -1
elif order == "l":
direct += 1
else:
direct -= 1
direct %= 4
... |
def resolve():
'''
code here
'''
N, M, C = [int(item) for item in input().split()]
Bs = [int(item) for item in input().split()]
grid = [[int(item) for item in input().split()] for _ in range(N)]
cnt = 0
for i in range(N):
temp = C
for j in range(M):
temp +=... |
# -*- coding: utf-8 -*-
#
# Seed documentation build configuration file, created by
# sphinx-quickstart on Fri Feb 10 12:11:25 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All co... |
from . import Device, Command
from pysgutils import sg_pt, sg_lib, AlignedBuffer
import struct
class SCSIDevice(Device):
command_fields = ['cdb', 'sense', 'sense_len', 'data_in_len', 'data_in', 'data_out', 'result']
def __init__(self, path):
self.path = path
self._open_depth = 0
self.... |
#!/usr/bin/env python3
from yateto import *
def add(g):
N = 8
A = Tensor('A', (N, N))
B = Tensor('B', (N, N, N))
w = Tensor('w', (N,))
C = Tensor('C', (N, N))
kernel = C['ij'] <= 2.0 * C['ij'] + A['lj'] * B['ikl'] * w['k']
g.add('kernel', kernel)
|
class script(object):
START_MSG = """ <b>Hi {}
Am Just A Advance Auto Filter Bot....😉
I have 4m movies 🔥🔥😝
For More movies first update & Upload..
@Tentkotta_Tamil
For more click <i>help</i></b>"""
HELP_MSG = """<b>How to use the bot??</b>
<i>
* Add bot to your group with admin rights.
* Add bot t... |
from django.db import models
from django.db.models import Avg, Count
from src.category.models import Category
from src.accounts.models import Account
from django.urls import reverse
class Product(models.Model):
product_name = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=20... |
from __future__ import print_function
import sys
import re
import binascii
import struct
from .. import database
from .utils import format_message_by_frame_id
# Matches 'candump' output, i.e. "vcan0 1F0 [8] 00 00 00 00 00 00 1B C1".
RE_CANDUMP = re.compile(r'^.*\s+([0-9A-F]+)\s+\[[0-9]+\]\s*([0-9A-F ]*)$')
def... |
from inferno.io.volumetric import TIFVolumeLoader, HDF5VolumeLoader
from inferno.io.transform import Compose
from inferno.io.transform.generic import Cast, Normalize
from inferno.io.transform.image import AdditiveGaussianNoise
class RawVolume(TIFVolumeLoader):
def __init__(self, path, dtype='float32', **slicing_c... |
#!/usr/bin/env python
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import with_statement
import argparse
import logging
import os
# import sys
# import platform
from imagededup.methods import PHash
from imagededup.methods import AHash
... |
import pandas as pd
import numpy as np
from pandas import DataFrame
from typing import Iterable, Optional
from sklearn import linear_model, preprocessing
from .utils import corr_na, zscore
def collapse_possible_regulators(
reg_data: DataFrame,
corr_threshold: float = 0.95
) -> DataFrame:
"""Uses m... |
import pandas as pd
from sklearn.metrics import mean_squared_error, mean_absolute_error
class Metrics:
def __init__(self):
pass
def calculate_regression(self, y_true, y_pred):
'''
Calculate the metrics from a regression problem
:param y_true: Numpy.ndarray or Pandas... |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the wallet backup features.
Test case is:
4 nodes. 1 2 and 3 send transactions between each other... |
"""Generator of dynamically typed draft stubs for arbitrary modules.
Basic usage:
$ mkdir out
$ python3 -m mypy.stubgen urllib.parse
=> Generate out/urllib/parse.py.
For C modules, you can get more precise function signatures by parsing .rst (Sphinx)
documentation for extra information. For this, use the --do... |
# Copyright 2015 Tesora 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 by a... |
import os
import sys
import pwiki.err as err
def add_path(path, check_existence=True):
if check_existence and not os.path.isdir(os.path.abspath(path)):
raise err.FileError('Not a directory: %s' % path)
sys.path.append(os.path.abspath(path))
def find_dump():
for path in ('dump.xml.bz2', 'dump.xml')... |
# -*- coding: utf-8 -*-
import sys
from os.path import dirname
sys.path.append(dirname(dirname(__file__)))
from tensorflow.keras import initializers
# from tensorflow.keras.engine import InputSpec, Layer
from tensorflow.keras.layers import Layer, InputSpec
from tensorflow.keras import backend as K
class AttentionWe... |
import os
import argparse
import json
import xml.etree.ElementTree as ET
from typing import Dict, List
from tqdm import tqdm
import re
def get_label2id(labels_path: str) -> Dict[str, int]:
"""id is 1 start"""
with open(labels_path, 'r') as f:
labels_str = f.read().split()
labels_ids = list(range(1... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1.23.6
Generated by: https://openapi-generator.tech
"""
try:
from inspect import getfullargspec
except Im... |
import datetime
import inspect
import os
import pickle
import threading
import uuid
from collections import OrderedDict
from concurrent.futures import Executor
from contextlib import contextmanager
from dataclasses import fields, is_dataclass
from functools import partial
from hashlib import md5
from numbers import Int... |
import os
import numpy as np
import pandas as pd
import pickle as pkl
from tqdm import tqdm
from sklearn.metrics import r2_score
from behavenet import get_user_dir
from behavenet.fitting.eval import export_latents
from behavenet.fitting.utils import (
get_expt_dir,
get_session_dir,
get_lab_example
)
def a... |
# Copyright 2020 The TensorFlow Probability Authors.
#
# 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 o... |
# -*- coding:utf-8 -*-
"""
@file orientation.py
@brief 检测模块的朝向,传感器能检测到以下六种事件:
@n Z轴正向朝上
@n Z轴正向朝下
@n Y轴正向朝上
@n Y轴正向朝下
@n X轴正向朝上
@n X轴正向朝下
@n 在使用SPI时,片选引脚时可以通过改变RASPBERRY_PIN_CS的值修改
@copyright Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com)
@licence The MIT License (MIT)
... |
import pyforest
import os
import logging
from dataclasses import dataclass, field
from typing import Dict, List, Optional
import sys
import torch
import nlp
from transformers import T5Tokenizer, BartTokenizer, HfArgumentParser
from datasets import list_datasets, load_dataset, list_metrics, load_metric, Dataset
import ... |
#!/usr/bin/env python3
import os
from setuptools import setup, find_packages
try:
'''
in no case, setup should fail.
take care of it that setup.py should not fail due to change in other files.
if it fails it will cause a serious problem
we can detect that from version number that will be installed ... |
from flask import render_template, flash, redirect, url_for, request, current_app, Blueprint, abort
from flask_login import current_user
from bluelog.emails import send_new_comment_email, send_new_reply_email
from bluelog.extensions import db
from bluelog.forms import CommentForm, AdminCommentForm
from bluelog.models ... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2015, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# unde... |
from datetime import datetime, time
from dateutil import tz
from namex.constants import DATE_FORMAT_NAMEX_SEARCH
def get_server_now():
"""Get the server now datetime object with local timezone"""
return datetime.now().astimezone(tz.tzlocal())
def get_server_now_str():
"""Get the server now date as a st... |
"""
WSGI config for psycho-server 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/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO... |
#!/usr/bin/env python2
# Copyright (c) 2014-2015 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Exercise the listtransactions API
from test_framework.test_framework import BitcoinTestFramework
from ... |
import requests
import json
from xlwt import *
# url = "https://reports.sem-o.com/api/v1/documents/static-reports"
url = "https://reports.sem-o.com/api/v1/documents/static-reports?ReportName=Balancing%20and%20Imbalance%20Market%20Cost%20View"
response = requests.get(url)
data = response.json()
totalPages = dat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.