content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import gzip
import numpy as np
import scipy
import scipy.signal
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import seaborn as sns
def load_log(filename):
"""Load data from logs generated from limtoc. Returns
a numpy record array.
""... |
# =========================================================
# For more info, see https://hoseinkh.github.io/projects/
# =========================================================
import pickle
import numpy as np
import pandas as pd
from sortedcontainers import SortedList
from tqdm import tqdm
## ************************... |
"""
Useful recipes from various internet sources (thanks)
mostly decorator patterns
"""
import os.path as op
import re
import sys
import logging
import functools
from collections import defaultdict
class memoized(object):
"""
Decorator that caches a function's return value each time it is called.
If call... |
# coding=utf-8
# Copyright 2021 The Google Research 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 applicab... |
import threading
import time
import datetime as dt
import socket # Import socket module
import G_Check_Time as chk_time
from H_Derived_Values import tech_heat_load
def record_pulse(lstArgs):
GPIO_read = lstArgs[0]
Pulse_Val = lstArgs[1]
strTech = lstArgs[2]
strPulseMeter = lstArgs[3]
... |
from tests.integration.integration_test_case import IntegrationTestCase
from tests.integration.questionnaire import SUBMIT_URL_PATH, THANK_YOU_URL_PATH
class TestQuestionnaireInterstitial(IntegrationTestCase):
BASE_URL = "/questionnaire/"
def test_interstitial_page_button_text_is_continue(self):
self... |
from io import BytesIO
import pickle
import platform
import numpy as np
import pytest
from matplotlib import cm
from matplotlib.testing.decorators import image_comparison
from matplotlib.dates import rrulewrapper
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
import matplotlib.figure as m... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020/12/31 4:01 下午
# @File : compare_eval_result.py
# @Author: johnson
# @Contact : github: johnson7788
# @Desc :
import collections
import json
import os
import pandas as pd
import requests
def collect_data(devfile="../data_root_dir/newcos/dev.json", eval_res... |
from ._fft import ( # irfft,; irfft2,; irfftn,
fft,
fft2,
fftn,
ifft,
ifft2,
ifftn,
rfft,
rfft2,
rfftn,
)
# from ._fftconvolve import fftconvolve
# from ._fftshift import fftshift, ifftshift
__all__ = [
"fft",
"fft",
"fft2",
"fftconvolve",
"fftn",
"fftshift... |
import unittest
from alg_euclid import euclid, euclidMutualSubst
class EuclidTest(unittest.TestCase):
def testEuclid_8_6(self):
assert euclid(8, 6) == 2
def testEuclid_12_8(self):
assert euclid(12, 8) == 4
def testEuclid_180_168(self):
assert euclid(180, 168) == 12
def testE... |
"""
`NASA EARTHDATA ORNL DAAC Daymet`_ web services
.. _NASA EARTHDATA ORNL DAAC Daymet: https://daymet.ornl.gov/dataaccess.html
"""
from __future__ import absolute_import
from . import core
from .core import (get_daymet_singlepixel)
from .core import (get_variables)
from .core import (get_daymet_gridded)
... |
from termplanner.planner_cli import PlannerRunner
def cli():
"""Creates and calls Planner."""
planner_runner = PlannerRunner()
planner_runner.cli()
if __name__ == "__main__":
cli()
|
from _pytest.config.argparsing import Parser
def pytest_addoption(parser: Parser, pluginmanager):
"""
Adds command line options used by the Seekret plugin.
"""
_ = pluginmanager # Unused.
group = parser.getgroup('seekret')
group.addoption('--run-profile',
dest='run_profi... |
# Copyright(c) 2018 WindRiver Systems
#
# 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 ... |
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import i2c, sensor
from esphome.const import CONF_HUMIDITY, CONF_ID, CONF_TEMPERATURE, \
ICON_THERMOMETER, ICON_WATER_PERCENT, UNIT_CELSIUS, UNIT_PERCENT
DEPENDENCIES = ['i2c']
hdc1080_ns = cg.esphome_ns.namespace('hdc1080... |
# coding: utf-8
# 演示如何批量调用API检测是否换脸
# In[1]:
import requests
import cv2
import os
import shutil
import glob
import argparse
import time
# 解析命令行参数
parser = argparse.ArgumentParser(description = 'Benchmarking deapfake imgs')
parser.add_argument('--in_dir', default = 'IN',help="Raw imgs dir")
parser.add_argument('--... |
n=int(input("Enter the size of the board : "))
counter=0
def reset():
global board
board=[[0]*n for i in range(n)]
if(marker(board, 0)==False and counter==1):
print("No feasible solution exists for the given dimensions")
def display(board):
global counter
counter+=1
for ... |
# coding: utf-8
from dataset_translation.dataset import Dataset
class TestDataset:
@staticmethod
def test_fill_intents():
intents = [{
'slug': 'greetings',
'created_at': '2021-02-10T12:56:05.547Z',
'updated_at': '2021-07-01T13:09:12.057Z',
'description': 'Says hello',
'name': 'g... |
"""
Copyright (c) 2019-2020 Uber Technologies, 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... |
from flask import Blueprint
# 创建蓝图对象
profile_blue = Blueprint('profile',__name__,url_prefix='/user')
# 导入视图函数
from . import views |
import pendulum
from flask import jsonify, Blueprint, current_app, abort
from ..core.models import FastDictTimeseries
bp = Blueprint('base', __name__)
@bp.route('/')
def base_root():
db = current_app.cdb
return jsonify(db.info())
@bp.route('/metrics')
def metrics():
db = current_app.cdb
connection... |
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from config import Config
engine = create_engine(Config.SQLALCHEMY_DATABASE_URI, convert_unicode=True)
# print(Config.SQLALCHEMY_DATABASE_URI)
db_sessio... |
# ------------------------------------------------------------------
# Copyright (c) 2020 PyInstaller Development Team.
#
# This file is distributed under the terms of the GNU General Public
# License (version 2.0 or later).
#
# The full license is available in LICENSE.GPL.txt, distributed with
# this software.
#
# SPD... |
"""
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you ... |
from keep_current_storage.use_cases import request_objects as ro
def test_build_document_list_request_object_without_parameters():
req = ro.DocumentListRequestObject()
assert req.filters is None
assert bool(req) is True
def test_build_document_list_request_object_from_empty_dict():
req = ro.Document... |
import os
import math
from typing import List
import numpy as np
import cv2
from detection.acuro_markers.obstacle_detection import ObstacleDetection
from detection.acuro_markers.robot_detection import RobotDetection
from detection.acuro_markers.marker_position import MarkerPosition
from detection.position_calculator i... |
import pytest # type: ignore
from conflow.node import NodeList, T, Node # type: ignore
NESTED_VALUES = [
['a', ['b', 'c', ['d', 'e']]]
]
@pytest.mark.parametrize('value,representation', [
([1, 2, 3], "NodeList('test', [1, 2, 3])"),
([42, 3.3, 'abc'], "NodeList('test', [42, 3.3, 'abc'])"),
])
def test_n... |
from unittest import TestCase
import os
import gcnvkernel.io.io_vcf_parsing as io
class test_io_vcf_parsing(TestCase):
def test_read_sample_segments_and_calls(self):
current_dir = os.getcwd()
#for GATK PythonUnitTestRunner/Java tests
test_sub_dir = current_dir + "/src/test/resources/org/b... |
from binance_f import RequestClient
from binance_f.constant.test import *
from binance_f.base.printobject import *
from binance_f.model.constant import *
import pyotp
import pprint
import tweepy
import secrets
#Uses Tweetpy to access Twitter API
print("Logging in Twitter's API...")
auth = tweepy.OAuthHandle... |
from collections import deque
class ConvertItem(set):
def __str__(self):
return "NFAStates: {0}".format(" ".join(str(state.index) for state in self))
class Converter:
def __init__(self):
self.dfa_class = None
self.nfa = None
self.eq_symbol_set = None
self.d... |
import torch.nn as nn
from pytorch_tools.modules import bn_from_name
from pytorch_tools.modules.residual import conv1x1
from pytorch_tools.modules.residual import conv3x3
from pytorch_tools.modules.decoder import UnetDecoderBlock
from pytorch_tools.utils.misc import initialize
from .base import EncoderDecoder
from .enc... |
from .preview import Preview
|
import os ,sys,subprocess
from messagebox import Message
class Agent(object):
def __init__(self,specfile,null):
spec = specfile
cmd = 'pyinstaller --onefile %s' %spec
compiles = os.system(cmd)
esc = os.getcwd() + '\\dist\\'
esc2 = os.listdir(esc)
... |
# -*- coding: utf-8 -*-
# --------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2016 Jonathan Labéjof <jonathan.labejof@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation fi... |
import bs4 as bs
import pickle
import requests
import datetime as dt
import os
import pandas as pd
import pandas_datareader.data as web
def save_sp500_tickers():
resp=requests.get('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')
soup=bs.BeautifulSoup(resp.text)
table=soup.find('table',{'class':'wikit... |
from binance.websocket.spot.websocket_client import SpotWebsocketClient
from binance.lib.utils import config_logging
import time
import logging
config_logging(logging, logging.DEBUG)
def message_handler(message):
print(message)
ws_client = SpotWebsocketClient()
ws_client.start()
ws_client.mini_ticker(
symbo... |
#
# Autogenerated by Thrift
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
# @generated
#
from __future__ import absolute_import
import six
from thrift.util.Recursive import fix_spec
from thrift.Thrift import *
from thrift.protocol.TProtocol import TProtocolException
from .ttypes import *
from... |
import smtplib
import mimetypes
from email import encoders
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from programy.utils.logging.ylogger import YLogger
from progra... |
from starepandas.io.granules.granule import Granule
import starepandas.io.s3
import datetime
import numpy
def get_hdfeos_metadata(file_path):
hdf= starepandas.io.s3.sd_wrapper(file_path)
metadata = {}
metadata['ArchiveMetadata'] = get_metadata_group(hdf, 'ArchiveMetadata')
metadata['StructMetadata... |
#!/usr/bin/env python3
#
# utils.py
"""
Utility functions.
"""
#
# Copyright © 2020 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
# 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 wi... |
"""Classes for writing to and reading from TFRecord datasets."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import multiprocessing
import os
import numpy as np
import tensorflow as tf
def tfrecord_path_to_metadata_path(tfrecord_path):
... |
#
# Copyright (c) 2008-2015 Thierry Florac <tflorac AT ulthar.net>
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRAN... |
import numpy as np
from .hmanifold import HomogenousManifold
from ..liealgebra import soLieAlgebra
from ..liegroup import SOLieGroup
class HomogenousSphere(HomogenousManifold):
"""The S2 sphere. Corresponding Lie group SO(n)."""
def __init__(self, y=np.array([0, 0, 1])):
if not isinstance(y, np.ndarr... |
import sys
import numpy as np
import os
from copy import deepcopy
import scipy.io as sio
import imageio
import time
import gc
import tensorflow as tf
import tensorflow.keras as keras
import tensorflow.keras.losses as keras_losses
from tensorflow.keras.models import load_model, Model
from tensorflow.keras.optimizers im... |
# Sentinel workflow event to help determine sample cherrypicked status
EVENT_CHERRYPICK_LAYOUT_SET = "cherrypick_layout_set"
###
# Cherrypicking source and destination plate events detailed here:
# Beckman: https://ssg-confluence.internal.sanger.ac.uk/display/PSDPUB/%5BBeckman%5D+Cherrypicking+Events
# Biosero: see li... |
import cv2
import numpy as np
import random
def grayscale(image):
return cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
def normalize_(image, mean, std):
image -= mean
image /= std
def lighting_(data_rng, image, alphastd, eigval, eigvec):
alpha = data_rng.normal(scale=alphastd, size=(3, ))
image += np.d... |
from inspect import signature, Parameter
from functools import wraps
class Unsupplied:
pass
_ = Unsupplied()
def _reinsert_kwargs(fn, args, kwargs):
params = signature(fn).parameters
param_position_mapping = {name: i for i, (name, param) in enumerate(params.items())
if param.default... |
from Tokenizer import *
from enum import Enum
class I(Enum):
# Do nothing code
NO_OP = 1
"""
STACK OPERATIONS
[2-7] Range; [2-6] Full, [7] Empty
"""
# Removes the top-of-stack (TOS) item.
POP_TOP = 2
# Swaps the two top-most stack items
ROT_TWO = 3
# Lifts second and th... |
# -*- coding: utf-8 -*-
"""
This module returns the constants of the code inclduing the info of sets and
parameter filese
"""
# Sorted connection parameter sheets
list_connection_operation = ["V_OM","F_OM","Line_efficiency",
"AnnualProd_perunit_capacity","Residual_capacity","Capacity_factor_line"]
list_connection_pl... |
from zeit.cms.i18n import MessageFactory as _
import grokcore.component as grok
import pkg_resources
import zeit.cms.content.dav
import zeit.cms.content.metadata
import zeit.cms.content.reference
import zeit.cms.interfaces
import zeit.cms.relation.interfaces
import zeit.content.video.interfaces
import zope.interface
... |
#!/usr/bin/env python
"""
dbase.py: instance methods for extending database classes
"""
# ----------------------ABSTRACT-BASE-CLASS-DATABASE----------------------#
class DBase:
"""
import sqlite3 module in extended module
Vars curs and conn should be declared in extended class
Values for both... |
from __future__ import absolute_import
from datetime import datetime
from dateutil.relativedelta import relativedelta
import pytz
from sqlalchemy.sql import and_
from ensconce import model, exc
from ensconce.model import meta
from ensconce.autolog import log
from ensconce.util import pwhash
def get(password_id, as... |
import torch
import torch.nn as nn
import torch.nn.functional as F
#from .aspp import build_aspp
#from .decoder import build_decoder
from .resnet import ResNet101
class ASPP(nn.Module):
def __init__(self, num_classes):
super(ASPP, self).__init__()
dilations = [6, 12, 18, 24]
inplanes = 204... |
#Sean Billings, 2015
import random
import numpy
import subprocess
from backend import constraints
from backend.experiment import W1Experiment
from backend.objectiveFunctions import WeightedSumObjectiveFunction, IdealDifferentialObjectiveFunction
import math
from backend.spea_optimizer import SpeaOptimizer
from backend.... |
import numpy as np
from kalman_estimation import Kalman4FROLS, Selector, get_mat_data
from tqdm import trange, tqdm, tqdm_notebook
import matplotlib.pyplot as plt
def corr_term(y_coef, terms_set, Kalman_S_No, var_name: str = 'x', step_name: str = 't'):
n_dim, n_term = y_coef.shape
func_repr = []
for var i... |
"""
This class can be instantiated directly, or subclassed to change signature / add methods
"""
import logging
from abstract_http_client.http_clients.http_client_base import HttpClientBase
from abstract_http_client.http_services.requests_service import RequestsService
class RequestsClient(HttpClientBase):
""" I... |
#!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
This script requires the nipy-data package to run. It is an example of
simultaneous motion correction and slice timing correction in
multi-session fMRI data from the FIAC 2005 data... |
from invoke import task
from tasks.util.env import (
AZURE_RESOURCE_GROUP,
AZURE_SGX_VM_SIZE,
AZURE_SGX_LOCATION,
AZURE_SGX_VM_IMAGE,
AZURE_SGX_VM_NAME,
AZURE_SGX_VM_ADMIN_USERNAME,
AZURE_SGX_VM_SSH_KEY_FILE,
)
from subprocess import check_output, run
def _run_vm_cmd(name, az_args=None, ca... |
# Copyright 2020 The TensorFlow 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
import os
import random
from PIL import Image
from torch.utils.data import Dataset
import torchvision.transforms.functional as TF
IMG_EXTENSIONS = [
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',
]
def is_image_file(filename):
return any(filename.endswith(extension) fo... |
# -*- coding: utf-8 -*-
"""
RIMM, ROMM and ERIMM Encodings
==============================
Defines the *RIMM, ROMM and ERIMM* encodings:
- :attr:`colour.models.RGB_COLOURSPACE_ROMM_RGB`.
- :attr:`colour.models.RGB_COLOURSPACE_RIMM_RGB`.
- :attr:`colour.models.RGB_COLOURSPACE_ERIMM_RGB`.
- :attr:`colour.models.... |
from kubernetes import config, config
# from _future_import print_function
import time
import kubernetes.client
from kubernetes.client.rest import ApiException
from pprint import pprint
# Configure API key authorization: BearerToken
configuration = kubernetes.client.Configuration()
configuration.api_key['authorizatio... |
"""
Module containing code to work with Move observational data
"""
from netCDF4 import Dataset, num2date, date2num
import datetime
import numpy as np
import metric.utils
class MoveObs(object):
""" Template class to interface with observed ocean transports """
def __init__(self, f, time_avg=None, mindt=None... |
"""
NSLS2 V2
---------
"""
# :author: Lingyun Yang <lyyang@bnl.gov>
import logging
#APHLA_LOG = os.path.join(tempfile.gettempdir(), "aphla.log")
#APHLA_LOG = 'aphla.nsls2v2.log'
#logging.basicConfig(filename=APHLA_LOG,
# format='%(asctime)s - %(name)s [%(levelname)s]: %(message)s',
# level=logging.DEBUG)
#_lgf... |
from nltk.util import ngrams
from collections import Counter
from xdnlp.utils import read_lines
import math
import joblib
import tqdm
class Gibberish(object):
def __init__(self):
self.counts = Counter()
self.total = 0
self.threshold = 0
def adapt(self, filename: str, total=None):
... |
'''
如果要获得一个对象的所有属性和方法, 可以使用dir()函数,
它返回一个包含字符串的list, 比如, 获得一个str对象的所有属性和方法
hasattr测试该对象的属性
setattr设置一个属性
getattr获取属性 getattr(obj, 'y')相当于obj.y
'''
a = 'ABC'
print(dir('ABC'), '\n',
len('ABC'), 'ABC'.__len__())
print('ABC'.__eq__(a), 'ABC'.__format__('123')) # output: True
class MyDog(object):
def __init__(self, l... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from svgplotlib.SVG.Parsers import Lexer, EOF
class ParsePathError(Exception):
pass
class Path(Lexer):
"""
Break SVG path data into tokens.
The SVG spec requires that tokens are greedy.
This lexer relies on Python's regexes defaulting to greedine... |
import sys
from PyQt5 import QtWidgets,QtCore
from PyQt5.QtWidgets import QApplication, QWidget
app = QApplication(sys.argv)
fen = QWidget()
fen.setWindowTitle("M2I&MQT PyQt Test")
fen.resize(300,200)
fen.move(300,50)
lineEdit = QtWidgets.QLineEdit(fen)
lineEdit.setGeometry(QtCore.QRect(100, 60, 111, 21))
l... |
"""
Created on Sat Jan 7 14:53:57 2017
@author: kamila
Load data(all .npy) for layer layer in data_folder
Input: layer,data_folder
Output: data
Choose patch pick num_regions=2 3x3xdepth regions and reshape data
Input: data - batchxdepthxwidthxheight
Output: Reshaped array of selected patches - nxm
... |
import re
from typing import List, Type
from os.path import exists, isfile, join
from ..util.Locale import Locale, ROOT_LOCALE, from_iso
from ..exceptions import NotInResourceBundleError, MissingResourceBundleError
_STANDARD_FILE_EXTENSION = "properties"
class RawResourceBundle:
_cached_bundles = {}
def _... |
"""
MIT License
Copyright (c) 2021 AlexFlipnote
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, ... |
"""Create list of dicts with time transfer between all hubs of each European city (city with more than 100.000 inhabitants or with an airport)."""
transfers_raw_one_dir_DE = [
{'city': 'DE-AAH', 'orig_hub': '01-1', 'dest_hub': '01-1', 'trip_duration': 0, 'freq': 0},
{'city': 'DE-AAH', 'orig_hub': '01-1', 'de... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 2 19:15:26 2020
@author: Diego
"""
import pandas as pd
import sqlite3
import wget
import os
from urllib.request import urlopen
from bs4 import BeautifulSoup
import urllib.request
import datetime
import zipfile
import io
import requests
if not os.path.exists('data'):
... |
#!Measurement
'''
baseline:
after: true
before: false
counts: 30
detector: H1
mass: 39.59
default_fits: nominal
multicollect:
counts: 60
detector: H1
isotope: Ar40
peakcenter:
after: false
before: false
detector: H1
isotope: Ar40
equilibration:
inlet: R
outlet: O
inlet_delay: 3
eqtime: 2... |
"""Custom exceptions."""
class EmptyGroupResult(Exception):
"""Exception raised when group AnalysisModule is run with <= 1 samples."""
pass
class UnsupportedAnalysisMode(NotImplementedError):
"""
Error raised when AnalysisModule is called in the wrong context.
Example: an AnalysisModule that pr... |
import pendulum
def ts_to_utc(ts):
return ts
def rfc_3339_to_local_string(string):
dt = pendulum.parse(string)
local = dt.in_timezone("local")
return local.strftime("%c") |
import pandas as pd
import numpy as np
import matplotlib
#from google.colab import drive
#drive.mount('/content/drive', force_remount=True)
import pickle
from os import listdir
PATH = '/home/graspinglab/NCS_data/updated_data/'
all_files = listdir(PATH)
files = []
for f in all_files:
if "pkl" in str(f):
fi... |
# coding=utf-8
__author__ = 'jiataogu'
from emolga.dataset.build_dataset import deserialize_from_file, serialize_to_file
import numpy.random as n_rng
class BSTnode(object):
"""
Representation of a node in a binary search tree.
Has a left child, right child, and key value, and stores its subtree size.
"""
def ... |
from setuptools import setup
setup(
name='savant_get',
version='0.0.1',
description='Go get all that data from Baseball Savant',
author='Jared Martin',
author_email='jared.martin@mlb.com',
py_modules=['savant_get'],
entry_points={'console_scripts': ['savant-get=savant_get:main']},
pytho... |
#!/usr/bin/python
import re
import subprocess
script = '''
if [ "$GIT_AUTHOR_EMAIL" = "" ]; then
GIT_COMMITTER_NAME="Ghost";
GIT_AUTHOR_NAME="Ghost";
GIT_COMMITTER_EMAIL="ghost@xinhua.dev";
GIT_AUTHOR_EMAIL="ghost@xinhua.dev";
git commit-tree "$@";
'''
with open('./authors.... |
from django.db import models
from django_fsm import FSMField, transition
from enum import Enum
from jsonfield import JSONField
from .managers import MessageManager
_received, _started, _failed, _submitted, _delivered = (
"received",
"started",
"failed",
"submitted",
"delivered",
)
class ChoicesE... |
from reportlab.lib.enums import TA_JUSTIFY, TA_CENTER, TA_LEFT
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.units import cm
styles = getSampleStyleSheet()
styles.add(
ParagraphStyle(
name="ai_other", parent=styles["Normal"], fontSize=11
)
)
styles.add(
Pa... |
import sqlite3
from aiogram import Dispatcher, types
from aiogram.dispatcher.filters.state import State, StatesGroup
from app.config_reader import load_config
from app.localization import lang
config = load_config("config/bot.ini")
conn = sqlite3.connect(config.bot.way)
cur = conn.cursor()
class Lang(... |
import threading
import logging
import io
class CapturingHandler(logging.StreamHandler):
@property
def content(self) -> str:
return self.stream.getvalue()
def __init__(self):
super().__init__(stream=io.StringIO())
def clear(self):
self.stream.truncate(0)
self.stream.s... |
# (C) Copyright 2007-2021 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at... |
print('='*5, 'Exercício 006', '='*5)
n = int(input(' Digite um número: '))
print(' O número digitado foi: {}. \n seu dobro é: {}. \n seu triplo é: {}.'.format(n, (n*2), (n*3)))
print(' sua raiz quadrada é: {:.3f}.'.format((n**(1/2))))
print('='*10, 'Fim', '='*10)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.28 on 2020-12-03 08:06
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('proposals', '0022_auto_20... |
import os
import csv
def get_all_data():
all_data = dict()
all_data["users"] = get_users()
all_data["movies"] = get_movies()
all_data["ratings"] = get_ratings()
return all_data
def get_users():
return get_file_data(
get_cwd() + "/movies_example/users.csv",
["UserId", "Name"]
... |
"""supervisr mod provider PowerDNS Record Translator"""
from logging import getLogger
from typing import Generator
from supervisr.core.providers.exceptions import ProviderObjectNotFoundException
from supervisr.core.providers.objects import (ProviderObject,
ProviderObjectTr... |
#!/usr/bin/env python
# coding: utf-8
# created by hevlhayt@foxmail.com
# Date: 2016/12/7
# Time: 16:58
from django.conf.urls import url
from welcome import views
urlpatterns = [
url(r'^welcome/$', views.welcome, name='welcome'),
]
|
from ._WriteMsg import *
|
import logging
import os
import dashpy.util.commons as commons
import dashpy.util.user_interaction_commons as ui_commons
import requests
import json
def clear_console():
os.system('cls' if os.name=='nt' else 'clear')
def assert_bytes(data):
assert isinstance(data, bytes)
def to_bytes(data, encoding='utf-8')... |
# -*- coding: utf-8 -*-
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('payment', '0003_auto_20150328_1600'),
]
operations = [
migrations.RemoveField(
model_name='payment',
name='instant_payment',
),
... |
# --------------------------------------------------------
# THOR
# Licensed under The MIT License
# Written by Axel Sauer (axel.sauer@tum.de)
# --------------------------------------------------------
import abc
from types import SimpleNamespace
import numpy as np
import torch
import torch.nn.functional as F
import ... |
class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
ans, codex = [], defaultdict()
def translate(c: str) -> str:
if c not in codex:
codex[c] = chr(97 + len(codex))
return codex[c]
def compare(word: str) -> None... |
srtFormat = {
'Elaps' : 'Elpas time:{0}', # This is special header created by OpenTX2SRT
'Date' : '%Y/%m/%d', # datetime.srtftime
'Time' : '%H:%M:%S', # datetime.srtftime
'1RSS(dB)' : '{0}dB',
'2RSS(dB)' : '{0}dB',
'RQly(%)' : 'RQly:{0}%',
'RSNR(dB)' : '{0}dB',
'ANT' : 'ANT:{0}',
... |
import requests
import csv
import os
def get_api_key():
"""
Function reading api key
from key.txt
"""
with open('key.txt', 'r') as file:
api_key = file.readline()
return api_key
def parse_value(value):
"""
function parsing given
str to int
"""
value = value.strip()
if value == 'N/A':
return 0
va... |
import argparse
import sched, time
import syslog
from runner import Runner
class PeriodicScheduler(sched.scheduler):
def enter_periodic(self, interval, func, initial_delay=None, prio=1):
args = {'func':func, 'interval':interval, 'prio':prio}
if initial_delay:
self.enter(initial_delay, p... |
# A function to read in an ASCII XYC file and return a numpy (pronounced as written) array of pixels
import numpy as np
def read(filename):
frame = np.zeros((256, 256))
f = open(filename)
for line in f.readlines():
vals = line.split("\t")
x = int(float(vals[0].strip()))
y = int(float(vals[1].strip()))
c = ... |
################################################################################
# Project : AuShadha
# Description : Models for AuShadha OPD Visits.
# Author : Dr. Easwar TR
# Date : 17-09-2013
# LICENSE : GNU-GPL Version 3, Please see AuShadha/LICENSE.txt
####################################... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.