content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import sys, logging, time, resource, gc, os
import multiprocessing
from multiprocessing import Pool
from util import print_datetime
import numpy as np
import gurobipy as grb
import torch
def estimate_weights_no_neighbors(YT, M, XT, prior_x_parameter_set, sigma_yx_inverse, X_constraint, dropout_mode, replicate):
"... | python |
# visualizer.py
# Contains functions for image visualization
import cv2 as cv
import matplotlib.pyplot as plt
import numpy as np
import random
import skimage.io as io
import torch
from operator import itemgetter
from PIL import Image
from torchvision import datasets, models, transforms
from metrics import getPercent... | python |
import os
import pandas as pd
# Configuration and constant definitions for the API
# Search
TEMPLATES_INDEX_FILENAME = 'templates.pkl'
SEARCH_INDEX_FILENAME = 'index_clean.pkl'#os.path.join('images', 'index_4.df')
SEARCH_READER_FN = pd.read_pickle
SEARCH_COLUMNS = ['fusion_text_glove', 'title_glove', 'ocr_glove', 'i... | python |
from setuptools import setup, find_packages
setup(
name='acl-iitbbs',
version='0.1',
description='Fetch attendance and result from ERP and Pretty Print it on Terminal.',
author='Aman Pratap Singh',
author_email='amanprtpsingh@gmail.com',
url='https://github.com/apsknight/acl',
py_modules=['... | python |
'''helper functions to deal wit datetime strings'''
from __future__ import unicode_literals, print_function
import re
from datetime import datetime
# REGEX!
DATE_RE = r'(\d{4}-\d{2}-\d{2})|(\d{4}-\d{3})'
SEC_RE = r'(:(?P<second>\d{2})(\.\d+)?)'
RAWTIME_RE = r'(?P<hour>\d{1,2})(:(?P<minute>\d{2})%s?)?' % (SEC_RE)
AMP... | python |
class SofaException(Exception):
def __init__(self, message):
super(SofaException, self).__init__(message)
class ConfigurationException(SofaException):
def __init__(self, message):
super(ConfigurationException, self).__init__(message)
| python |
#!/usr/bin/env python
#
# Copyright (c) 2013-2018 Nest Labs, 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/licen... | python |
#!/usr/bin/env python
# -*- Coding: UTF-8 -*-
# @Time : 12/8/18 7:02 PM
# @Author : Terry LAI
# @Email : terry.lai@hotmail.com
# @File : keyboard.py
from pymouse import PyMouse
from pykeyboard import PyKeyboard
from socket import socket, AF_INET, SOCK_STREAM
port = 20000
# -*- coding: utf-8 -*-
client_addr... | python |
from mock import MagicMock, patch
import unittest
from cassandras3.cli.restore import do_restore
from cassandras3.util.nodetool import NodeTool
class TestRestoreClient(unittest.TestCase):
@patch('cassandras3.cli.restore.ClientCache')
@patch('cassandras3.cli.restore.NodeTool')
def test_restore(self, nodet... | python |
import csv
import datetime
import json
import logging
import os
import time
import click
import structlog
from dsaps import helpers
from dsaps.models import Client, Collection
logger = structlog.get_logger()
def validate_path(ctx, param, value):
"""Validates the formatting of the submitted path"""
if value... | python |
from datetime import date, datetime, timedelta
#Yesterday as the request date for the client
def get_request_date():
dt = datetime.today() - timedelta(days=1)
return dt.strftime('%Y-%m-%d') | python |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import print_function
from astropy.extern.six import BytesIO
from astropy.table import Table
from ..query import BaseQuery
from ..utils import commons
from ..utils import async_to_sync
from . import conf
__all__ = ['Heasarc', 'HeasarcClass... | python |
"""
'FRAUDAR: Bounding Graph Fraud in the Face of camouflage'
Spot fraudsters in the presence of camouflage or hijacked accounts. An algorithm that is camouflage-resistant,
provides upper bounds on the effectiveness of fraudsters, and the algorithm is effective in real-world data.
Article: https://bhooi.github.io/p... | python |
"""
dear Nessus dev, if you want to see where there is issues with your REST API, please modify `lying_type` and
`lying_exist` to become NOP
"""
import functools
from typing import TypeVar, Mapping, Union, Callable, Any, Optional
T = TypeVar('T')
U = TypeVar('U')
V = TypeVar('V')
JsonType = Union[int, str, bool]
c... | python |
from .models import redshiftdata_backends
from ..core.models import base_decorator
mock_redshiftdata = base_decorator(redshiftdata_backends)
| python |
import time
import unittest
from cryptography.shell_game import ShellGame
class ShellGameTests(unittest.TestCase):
def setUp(self):
self.start_time = time.time()
def tearDown(self):
t = self.start_time - time.time()
print("%s: %.3f" % (self.id(), t))
def test_1(self):
ti... | python |
"""
Functions for interacting with timestamps and datetime objects
"""
import datetime
from typing import Optional
def to_utc_ms(dt: datetime.datetime) -> Optional[int]:
"""
Convert a datetime object to UTC epoch milliseconds
Returns
-------
timstamp_ms : int
Timestamp
"""
if dt i... | python |
import datetime
import uuid
from typing import cast
from unittest import mock
from unittest.mock import ANY, patch
import pytest
import pytz
from constance.test import override_config
from django.core import mail
from django.urls.base import reverse
from django.utils import timezone
from rest_framework import status
... | python |
name = 'libseq'
from libseq.libseq import *
| python |
import eel
if __name__ == '__main__':
eel.init('web')
eel.start('index.html', mode="chrome", size=(1296, 775))
| python |
import os
def create_termuxconfig():
ATTR = ["API_ID", "API_HASH", "SESSION", "DB_URI", "LOG_CHAT", "TOKEN"]
file = open("termuxconfig.py", "w+")
file.write("class Termuxconfig:\n\ttemp = 'value'\n")
for x in ATTR:
myvar = vars() # string to variable
if x == "DB_URI":
value = createdb()
else:
data = ... | python |
# GUI frame for the sineTransformations_function.py
try:
# for Python2
from Tkinter import * ## notice capitalized T in Tkinter
import tkFileDialog, tkMessageBox
except ImportError:
# for Python3
from tkinter import * ## notice lowercase 't' in tkinter here
from tkinter import filedialog as... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 1 18:44:04 2018
@author: JavaWizards
"""
import numpy as np
file = "/Users/nuno_chicoria/Downloads/b_should_be_easy.in"
handle = open(file)
R, C, F, N, B, T = handle.readline().split()
rides = []
index = []
for i in range(int(N)):
index.a... | python |
""""
Animation code source:
https://gist.github.com/DanielTakeshi/fec9a5cd957eb05b04b6d06a16cc88ae
"""
import argparse
import time
import imageio
from PIL import Image
import numpy as np
import torch as T
import gym
import rl.environments
def evaluate(agent, env, EE, max_el, exp_name, gif=False):
print('[ Ev... | python |
import numpy as np
from .Classifier import Classifier
class NearestNeighbourClassifier(Classifier):
def __init__(self) -> None:
self.x = np.array([])
self.y = np.array([])
def fit(self, x: np.ndarray, y: np.ndarray) -> None:
""" Fit the training data to the classifier.
Args:
... | python |
from sys import platform
import sys
try:
import caffe
except ImportError:
print("This sample can only be run if Python Caffe if available on your system")
print("Currently OpenPose does not compile Python Caffe. This may be supported in the future")
sys.exit(-1)
import os
os.environ["GLOG_minloglev... | python |
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import os
import sys
import json
from src.api_reader import get_members
from src.intellisense import IntellisenseSchema
from src.version import schema_version, sdk_go_version
if __name__ == '__main__':
... | python |
from setuptools import setup
import platform
if platform.system() == 'Windows':
setup(
name='imagesimilarity',
version='0.1.2',
packages=[''],
url='https://github.com/marvinferber/imagesimilarity',
license='Apache License 2.0',
author='Marvin Ferber',
author_... | python |
from bytecodemanipulation import (
CodeOptimiser,
Emulator,
InstructionMatchers,
MutableCodeObject,
OptimiserAnnotations,
)
from bytecodemanipulation.TransformationHelper import BytecodePatchHelper
from bytecodemanipulation.Transformers import TransformationHandler
from bytecodemanipulation.util imp... | python |
#o objetivo desse programa é escrever na tela a taboada do número que o usuário digitar.
n = int(input('Digite um número para ver sua taboada: '))
print('-=' * 10)
print("{} x {:2} = {} ".format(n,1, n*1))
print("{} x {:2} = {} ".format(n,2, n*2))
print("{} x {:2} = {} ".format(n,3, n*3))
print("{} x {:2} = {} ".format... | python |
# project/server/models.py
from flask import current_app
from project.server import db, bcrypt
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
email = db.Column(db.String(255), unique=True, nullable=False)
password = db.Column(db.Stri... | python |
# Copyright (C) 2021 Satoru SATOH <satoru.satoh@gmail.com>
# SPDX-License-Identifier: MIT
#
"""Entry point of tests.common.*.
"""
from .base import (
MaybeModT, Base
)
from .constants import (
TESTS_DIR, TESTS_RES_DIR, RULES_DIR,
)
from .testcases import (
RuleTestCase, CliTestCase
)
__all__ = [
'TESTS... | python |
import pytest
import logging
from multiprocessing.process import current_process
from threading import current_thread
import time
logging.basicConfig(filename="log.txt", filemode="w")
log = logging.getLogger()
log.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
formatter = lo... | python |
from os import listdir
import core.log as log
async def main(message, client, serverdata):
#Part 1
commandfiles = listdir("./core/commands")
commandList = []
#Check if Command is a file
for commands in commandfiles:
if commands.endswith('.py'):
commandList.append(commands.replac... | python |
"""
=====================
Fitting a light curve
=====================
This example shows how to fit the parameters of a SALT2 model to photometric
light curve data.
First, we'll load an example of some photometric data.
"""
import sncosmo
data = sncosmo.load_example_data()
print(data)
############################... | python |
#!/bin/python3
# Copyright (C) 2017 Quentin "Naccyde" Deslandes.
# Redistribution and use of this file is allowed according to the terms of the MIT license.
# For details see the LICENSE file distributed with yall.
import sys
import os
import requests
import json
import argparse
import subprocess
import fnmatch
owne... | python |
# reverse words in a string
# " " output is wrong lol
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
reverse = []
temp = ""
for i in s:
if i == " ":
if temp != "":
reverse.app... | python |
import sys
from os.path import join, isfile
import threading
import importlib.util as iutil
from uuid import uuid4
from multiprocessing.dummy import Pool as ThreadPool
from datetime import datetime
from aequilibrae.project.data import Matrices
from aequilibrae.paths.multi_threaded_skimming import MultiThreadedNetworkSk... | python |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or module... | python |
# License: BSD 3 clause
import tick.base
import tick.base_model.build.base_model
from .model_hawkes_expkern_leastsq import ModelHawkesExpKernLeastSq
from .model_hawkes_expkern_loglik import ModelHawkesExpKernLogLik
from .model_hawkes_sumexpkern_leastsq import ModelHawkesSumExpKernLeastSq
from .model_hawkes_sumexpkern... | python |
from radar import db
__all__ = ['Commit']
class Commit(db.Model):
id = db.Column(db.Integer, primary_key=True)
commit_hash = db.Column(db.String(40))
summary = db.Column(db.String(100))
branch = db.Column(db.String(50))
author = db.Column(db.String(100))
commit_time = db.Column(db.DateTime)
... | python |
from django.contrib.gis.db import models
class Mansion(models.Model):
class Meta:
db_table = 'mansion'
gid = models.BigAutoField(primary_key=True)
housing_area_code = models.BigIntegerField(null=False)
facility_key = models.CharField(max_length=4000, null=True)
shape_wkt = models.MultiLin... | python |
"""Create svg images from a keyboard definition."""
import xml.etree.ElementTree as ET
import io
from math import sin, cos, atan2, degrees, radians
from kbtb.plate import generate_plate
def shape_to_svg_element(shape, props={}, x_scale=1, y_scale=-1):
return ET.Element(
"path", {
"d":
... | python |
# 工具类,字符串处理
import re
class BFStringDeal(object):
def __init__(self,arg):
self.arg = arg
@classmethod
# 删除垃圾字符 -- 比如:\n
def specialTXT(cls, text):
return text.replace("\n", "")
@classmethod
# 正则表达式处理,字符串
def getAssignContent(cls, text, assignContent):
# 获取正则表达式实例,其... | python |
__author__ = 'Alexander Horkun'
__email__ = 'mindkilleralexs@gmail.com'
from django.conf.urls import patterns, url
from xanderhorkunspider.web.websites.views import websites, auth
urlpatterns = patterns('',
url(r'^$', websites.index_view, name='index'),
url(r'^add-websi... | python |
"""
opbeat.contrib.django.celery
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2011-2012 Opbeat
Large portions are
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from opbeat.contrib.celery import CeleryMixin
from opbeat.contrib.django import Dja... | python |
# from glob import glob
from setuptools import setup
setup(
name='pybrightsign',
version='0.9.4',
description='BrightSign APIs for humans. Python module to simplify using the BrightSign BSN/BSNEE API.',
long_description=open('../README.md').read(),
long_description_content_type='text/markdown',
... | python |
# coding: utf-8
# 2019/10/17 @ tongshiwei | python |
from curses import meta
import shutil
from unittest import TestCase
import sys
import os
import metadata_mp3
import shutil
import unittest
from mutagen.easyid3 import EasyID3
class TestRenameSongName(TestCase):
def test_1(self):
songNameBefore = "Counting Crows - Colorblind (Official Video)"
songN... | python |
#!/usr/bin/env python
# coding=utf-8
"""Writes uninstallation SQL script to stdout."""
from os.path import abspath, join, dirname
import sys
def uninstall():
with open(join(dirname(abspath(__file__)), 'uninstall.sql')) as f:
sys.stdout.write(f.read())
if __name__ == '__main__':
uninstall()
| python |
import os
from PIL import Image, ImageDraw
from pylab import *
import csv
class ImageScatterPlot:
def __init__(self):
self.h, self.w = 20000,20000
self.resize_h = 275
self.resize_w = 275
def create_save_fig(self, image_paths, projected_features, out_file):
img_scatter = self.create_fig(image_paths... | python |
# Lagoon (2400004) | Zero's Temple (320000000)
from net.swordie.ms.loaders import StringData
options = []
al = chr.getAvatarData().getAvatarLook()
selection = sm.sendNext("Hello. How can I help you? #b\r\n"
"#L0#Change hair colour#l\r\n"
"#L1#Change eye colour#l\r\n"
"#L2#Change ... | python |
def a_method():
pass
class AClass:
pass
var = "A Variable"
print("Support library name: {}".format(__name__))
if __name__ == '__main__':
age = 0
while age <= 0:
age = int(input("How old are you? "))
| python |
'''
Manage file shares that use the SMB 3.0 protocol.
'''
from ... pyaz_utils import _call_az
from . import copy, metadata
def list(share_name, account_key=None, account_name=None, connection_string=None, exclude_dir=None, marker=None, num_results=None, path=None, sas_token=None, snapshot=None, timeout=None):
'''... | python |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import uuid
from django.core.urlresolvers import reverse
from rest_framework.test import APITestCase
from kolibri.core.auth.models import FacilityUser
from kolibri.core.auth.test.helpers import setup_... | python |
"""Tests for the config.config-module
"""
# System library imports
from collections import namedtuple
from datetime import date, datetime
import pathlib
import re
import sys
# Third party imports
import pytest
# Midgard imports
from midgard.config import config
from midgard.collections import enums
from midgard.dev ... | python |
#!/usr/bin/python3
# Created by Jared Dunbar, April 4th, 2020
# Use this as an example for a basic game.
import pyxel, random, math
import os.path
from os import path
# Width and height of game screen, in tiles
WIDTH = 16
HEIGHT = 12
# Width and height of the game level
GL_WIDTH = 170
GL_HEIGHT = 150
# Window offs... | python |
import os
from urllib.parse import urljoin, urlparse
import urllib
import ntpath
is_win32 = os.name == "nt"
def createDirectory(base, new_dir):
if is_win32:
new_dir = cleanName(new_dir, ".")
if not base.startswith("\\\\?\\"): base = "\\\\?\\" + base
path_new_dir = os.path.join(base, new_dir)
... | python |
# This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | python |
import json
import logging
from platform import system
from ctypes import (c_char_p, c_int, c_uint, c_long, Structure, cdll, POINTER)
from typing import Any, TYPE_CHECKING, Tuple, List, AnyStr
from rita.engine.translate_standalone import rules_to_patterns, RuleExecutor
from rita.types import Rules
logger = logging.... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from codecs import open
import json
import opengraph
from repos import final_theses as thesis_slugs
template = open('_template.html', 'r', 'utf-8').read()
theses = []
for thesis_slug in thesis_slugs:
url = 'http://kabk.github.... | python |
import matplotlib
matplotlib.use('TkAgg')
from collections import namedtuple
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import ode
def f(x, y):
""" Правая часть ДУ y'=f(x, y) """
return x/4-1/(1+y**2)
def on_move(event):
""" Обработчик событий мыши """
... | python |
# Generated by Django 2.2.8 on 2019-12-11 16:24
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('django_eveonline_connector', '0010_auto_20191211_1514'),
]
operations = [
migrations.AlterField(
... | python |
import time
import numpy as np
from yaaf.evaluation import Metric
class SecondsPerTimestepMetric(Metric):
def __init__(self):
super(SecondsPerTimestepMetric, self).__init__(f"Seconds Per Timestep")
self._deltas = []
self._last = None
def reset(self):
self._deltas = []
... | python |
from pytest import raises
from async_cog.tags import Tag
def test_tag_format() -> None:
tag = Tag(code=254, type=4, length=13)
assert tag.format_str == "13I"
assert tag.data_pointer is None
def test_tag_size() -> None:
tag = Tag(code=254, type=4, length=13)
assert tag.data_size == 52
def test... | python |
"""
RenameWidget:
This widget permit the rename of the output files in the MKVCommand
Also if files are drop from directories in the OS it will rename them.
"""
# LOG FW0013
import logging
import re
from pathlib import Path
from PySide2.QtCore import Signal, Qt, Slot
from PySide2.QtWidgets import (
QGridLayou... | python |
# Copyright (c) 2013 Stian Lode
#
# 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, distrib... | python |
"""
@author: Hasan Albinsaid
@site: https://github.com/hasanabs
"""
import matplotlib.pyplot as plt
import numpy as np
import itertools
import os
def nck(n,k):
return np.math.factorial(n)/np.math.factorial(k)/np.math.factorial(n-k)
def nchoosek(arr, k):
return np.array(list(itertools.combinations(arr, k)))
d... | python |
#! /usr/bin/env python
#-----------------------------------------------------------------------
# COPYRIGHT_BEGIN
# Copyright (C) 2016, FixFlyer, LLC.
# All rights reserved.
# COPYRIGHT_END
#-----------------------------------------------------------------------
class SessionStore(object):
""" """
class Liste... | python |
"""Process the markdown files.
The purpose of the script is to create a duplicate src directory within which
all of the markdown files are processed to match the specifications of building
a pdf from multiple markdown files using the pandoc library (***add link to
pandoc library documentation***) with pdf specific text... | python |
# django
from hashlib import sha256
from uuid import uuid4
from django.utils.text import slugify
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags
# python
from bs4 import BeautifulSoup
from ... | python |
import attr
from jstruct import JStruct, JList, REQUIRED
from typing import Optional, List
@attr.s(auto_attribs=True)
class Appointment:
type: str
date: Optional[str] = None
time: Optional[str] = None
phone: Optional[str] = None
@attr.s(auto_attribs=True)
class Address:
postalCode: str
provi... | python |
# Project Euler Problem 19 Solution
#
# Problem statement:
# You are given the following information, but you may prefer to
# do some research for yourself.
# 1 Jan 1900 was a Monday.
# Thirty days has September,
# April, June and November.
# All the rest have thirty-one,
# Saving February alone,
# Which has twenty-ei... | python |
#!/usr/bin/python
"""Executes Android Monkey stress test over adb to attached Android device."""
__author__ = 'jeff.carollo@gmail.com (Jeff Carollo)'
import datetime
import json
import logging
import os
import subprocess
import sys
import time
from tasklib import apklib
ADB_COMMAND = apklib.ADB_COMMAND
MONKEY_COMM... | python |
from vol import Vol
from net import Net
from trainers import Trainer
from util import *
import os
from random import shuffle, sample, random
from sys import exit
embeddings = None
training_data = None
testing_data = None
network = None
t = None
N = None
tokens_l = None
def load_data():
global embeddings, N, tok... | python |
#
# Copyright(c) 2019 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause-Clear
#
from enum import Enum
class OutputFormat(Enum):
table = 0
csv = 1
class StatsFilter(Enum):
all = 0
conf = 1
usage = 2
req = 3
blk = 4
err = 5
| python |
import networkx as nx
import numpy as np
import math
def create_network (correct_answers, data, p_factor, realmodelQ, n_edges_score):
#correct_answers is a string which assumes the following values: True, False, "All"
#p_factor is a bool that assumes the value True if the factor (1-p) is to be considered for... | python |
from django.contrib import admin
from .models import (
EconomicAssessment,
EconomicImpactAssessment,
ResolvabilityAssessment,
StrategicAssessment,
)
@admin.register(EconomicImpactAssessment)
class EconomicImpactAssessmentAdmin(admin.ModelAdmin):
pass
@admin.register(EconomicAssessment)
class Ec... | python |
import textwrap
from pathlib import Path
import pyexasol
import pytest
from exasol_udf_mock_python.column import Column
from exasol_udf_mock_python.connection import Connection
from exasol_udf_mock_python.group import Group
from exasol_udf_mock_python.mock_exa_environment import MockExaEnvironment
from exasol_udf_mock... | python |
# -*- coding: utf-8 -*-
import ast
# This has to be a global due to `exec` shenanigans :-(
current_spec = {}
# SQL types
SQL_TYPES = [
'TEXT',
'DATE',
'DATETIME',
'INTEGER',
'BIGINT',
'UNSIGNED_BIGINT',
'DOUBLE',
'BLOB',
]
# Functions that we don't need
DUMMY_FUNCTIONS = [
'Forei... | python |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Copyright © 2021, Spyder Bot
#
# Licensed under the terms of the MIT license
# ----------------------------------------------------------------------------
"""
Status bar widgets.
"""
# Third-party imports
from qt... | python |
from .. import Provider as CreditCardProvider
class Provider(CreditCardProvider):
pass
| python |
import collections
import time
import warnings
from collections import namedtuple
import numpy as np
import torch
from tianshou.data import Batch, ReplayBuffer
from tianshou.env import BaseVectorEnv, VectorEnv
Experience = namedtuple('Exp', ['hidden', 'obs', 'act', 'reward', 'obs_next', 'done'])
HIDDEN_SIZE = 256
... | python |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 23 13:56:25 2020
Authors: Pavan Kota, Daniel LeJeune
Reference:
P. K. Kota, D. LeJeune, R. A. Drezek, and R. G. Baraniuk, "Extreme Compressed
Sensing of Poisson Rates from Multiple Measurements," Mar. 2021.
arXiv ID:
"""
# Multiple Measurement Vector Compressed Sensi... | python |
import torch
import torch.nn as nn
from lazytorch import (
LazyConv2dInChannelModule,
create_lazy_signature,
NamedSequential,
)
from .depth_sep_conv import DepthwiseConv2d, PointwiseConv2d
from .squeeze_excitation import SqueezeExcitation
from typing import Optional
class InvertedBottleneck(nn.Module):
... | python |
from rest_framework import generics, status
from rest_framework import viewsets
from rest_framework.exceptions import (
ValidationError
)
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from .models import (
Category, Recipe
)
from .serializers import (
Categor... | python |
import shutil
from tokenizers.normalizers import NFKC
from autonmt.preprocessing import tokenizers
from autonmt.bundle import utils
from autonmt.bundle.utils import *
def normalize_file(input_file, output_file, normalizer, force_overwrite, limit=None):
if force_overwrite or not os.path.exists(output_file):
... | python |
"""PythonHere app."""
# pylint: disable=wrong-import-order,wrong-import-position
from launcher_here import try_startup_script
try:
try_startup_script() # run script entrypoint, if it was passed
except Exception as exc:
startup_script_exception = exc # pylint: disable=invalid-name
else:
startup_script_ex... | python |
#!/usr/bin/env python3
import random
#random.seed(1) # comment-out this line to change sequence each time
# Write a program that stores random DNA sequence in a string
# The sequence should be 30 nt long
# On average, the sequence should be 60% AT
# Calculate the actual AT fraction while generating the sequence
# Rep... | python |
import numpy as np
import typing as tp
import matplotlib.pyplot as plt
import pickle
import scipy.signal as signal
import shapely.geometry
import scipy.interpolate as interp
from taylor import PointAccumulator
from dataclasses import dataclass
def find_datapoints(image, start=0):
# _image = 255 - image
... | python |
"""
Tests for the GeniusZone class
"""
import unittest
from unittest.mock import Mock
from geniushubclient.const import IMODE_TO_MODE, ZONE_MODE, ZONE_TYPE
from geniushubclient.zone import GeniusZone
class GeniusZoneDataStateTests(unittest.TestCase):
"""
Test for the GeniusZone Class, state data... | python |
from django.conf.urls import url, include
from . import views
from django.urls import path
urlpatterns = [
path('', views.index, name = 'index'),
path('allcomment/',views.allcomment, name = 'allcomment'),
path('allexpert/',views.allexpert, name = 'allexpert'),
path('apply/',views.apply, name = 'apply')... | python |
# -*- coding: utf-8 -*-
import wx
import wx.xrc
import time
import pyperclip
import os
import sys
import platform
import data
###########################################################################
## Class MyFrame1
###########################################################################
class MyFrame1 ( wx.... | python |
'''
'''
import os
import numpy as np
from provabgs import models as Models
def test_DESIspeculator():
''' script to test the trained speculator model for DESI
'''
# initiate desi model
Mdesi = Models.DESIspeculator()
# load test parameter and spectrum
test_theta = np.load('/Users/cha... | python |
import datetime
import difflib
# import datefinder
from dateparser.search import search_dates
from dateutil.parser import parse
from SMELT.validators.twitter.tweets import get_tweets
from SMELT.Validation import Validator
# from twitterscraper import
import twint
def fetch_closest_matching_tweet(username, message, t... | python |
#
# This file is part of Brazil Data Cube Collection Builder.
# Copyright (C) 2019-2020 INPE.
#
# Brazil Data Cube Collection Builder is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#
"""Define the Collection Builder utilities for Land... | python |
"""Custom CSV-related functionality."""
import csv
import os
def create_csv():
"""Create new csv to store git-geo result
Delete any existing csv and the create new csv.
Args:
None
Returns:
None
"""
# delete csv if it already exists
filename = "git-geo-results.csv"
i... | python |
from __future__ import absolute_import, division, print_function, with_statement
from __future__ import unicode_literals
from tornado import ioloop, web, websocket, httpserver, concurrent
from collections import defaultdict
import mock
class DeepstreamHandler(websocket.WebSocketHandler):
connections = defaultd... | python |
# -*- coding: utf-8 -*-
import json
import logging
from pathlib import Path
from questionary import prompt
from ... import constants as C
from ...core import display
from ...core.app import App
from ...core.arguments import get_args
from ...core.crawler import Crawler
from .open_folder_prompt import display_open_fold... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.