content stringlengths 5 1.05M |
|---|
### This file contains function 'importdata', which:
# - takes latitude, longitude, time of recording and accuracy from the location history json;
# - converts these attributes to appropriate format;
# - returns a dataframe with these attributes.
def importdata(data_folder, filename):
import pandas as pd
... |
"""
Escribir un programa que convierta dolares a las siguientes 3 monedas
a partir del input del usuario:
Cotizaciones:
1 USD 0.94 CHF
1 USD 200 ARS
1 USD 6.75 CNY
User input:
dollars: dolares a convertir
coin: moneda a convertir
"""
def usd_to_cny(dollars: float) -> ... |
s, t, x = map(int, input().split())
lst = [False]*24
if s < t:
for i in range(s, t+1):
lst[i] = True
else:
for i in range(s, 24):
lst[i] = True
for i in range(0, t):
lst[i] = True
print("Yes") if lst[x] == True else print("No")
|
# -*- coding: utf-8 -*-
"""compatibleversion module.
This module determines if a version is permitted by a specifier.
"""
from packaging.specifiers import SpecifierSet
from packaging.version import Version
__version__ = "0.2.17"
def check_version(version, specifier, allow_pre=True):
"""Check version against s... |
import pandas as pd
def deleteYELPduplicates():
df = pd.read_csv('YELP_CANADA.csv')
df.drop_duplicates(subset="id", keep="last", inplace=True)
df.to_csv('YELP_CANADA_clean.csv')
deleteYELPduplicates()
|
list1=[]
list2=[]
f = open('player_vs_player_info.txt', 'w')
y=open('player_vs_player_wickets.txt','w')
list_ip=['980901.txt','980903.txt','980905.txt','980907.txt','980909.txt','980911.txt','980913.txt','980915.txt','980917.txt','980919.txt','980921.txt','980923.txt','980925.txt','980927.txt','980929.txt','980931.... |
"""Tests for events.py."""
import collections.abc
import concurrent.futures
import functools
import io
import os
import platform
import re
import signal
import socket
try:
import ssl
except ImportError:
ssl = None
import subprocess
import sys
import tempfile
import threading
import time
import errno
import uni... |
from api import db
from api.models.free_company import FreeCompany
from api.scrapers.context_managers import HTMLFromLoadstone
from api.scrapers.character import scrape_character
import datetime
import re
def scrape_free_company(lodestone_id, basics_only=False):
url = 'http://na.finalfantasyxiv.com/lodestone/fre... |
# -*- coding: utf-8 -*-
import pyasge
class MyASGEGame(pyasge.ASGEGame):
def __init__(self, settings):
pyasge.ASGEGame.__init__(self, settings)
self.inputs.addCallback(pyasge.EventType.E_KEY, self.input)
"""a sprite to render in to the offscreen target"""
self.sprite = pyasge.Spr... |
# -*- coding: utf-8 -*-
from datetime import datetime as dt
import json
import logging
from airflow.models import BaseOperator
from debussy.metadata import DatastoreMetadataReader, DatastoreMetadataWriter, DatastoreMetadataCopy
class DatastoreGetObjectOperator(BaseOperator):
def __init__(self, project, contro... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Functions for performing aperture photometry on 2-D arrays."""
import math
import abc
import copy
import numpy as np
__all__ = ["CircularAperture", "CircularAnnulus",
"EllipticalAperture", "EllipticalAnnulus",
"aperture_photome... |
from flask_jwt_extended import jwt_required, jwt_refresh_token_required, get_jwt_identity, get_raw_jwt
from flask import jsonify, request, Flask
from twit import users, tokens
def login_user():
payload = request.get_json()
login_state = users.login(payload.get("login"), payload.get("password"))
if login_... |
import os
import inspect
from functools import partial
from datasets.camvid import CamVidDataset
from torchvision.transforms import Resize
from test import main
if __name__ == '__main__':
project_dir = os.path.dirname(inspect.getabsfile(main))
exp_name = os.path.splitext(os.path.basename(__file__))[0] # Make... |
# -*- coding: utf-8 -*-
from django.shortcuts import render
def proof(request):
return render(request, 'tpl/keybase/proof.txt', content_type='text/plaintext')
|
import os
import shutil
from io import StringIO, BytesIO, open
import codecs
from copy import deepcopy
from fontTools.misc.py23 import basestring, unicode
from ufoLib.glifLib import GlyphSet
from ufoLib.validators import *
from ufoLib.filenames import userNameToFileName
from ufoLib.converters import convertUFO1OrUFO2Ke... |
#!/usr/bin/env python3
# coding:utf-8
import pymysql
from SendMail import *
import logging
sqlservername='ServerNameHere'
sqluser='usernamehere'
sqlpasswd='passwordhere'
sqldatabase='ExchangeRoom'
HtmlCode='''
<table width="auto" border="1">
<tr>
<td>姓名</td>
<td>性别</td>
<td>地址</td>
<td>户型</td>
<td>联系信息... |
"""Since pickle apparently doesn't know how to pickle methods/classes defined
in __main__
"""
import numpy as np
def PickAndPlace1DEnvObjectOnlyRewardFn(obs_dict, actions, next_obs_dict,
new_contexts, context_key, mask_key):
achieved_goals = next_obs_dict['state_achieved... |
# Copyright 2018 The go-python Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
try:
from math import to_ulps
except ImportError:
import struct
def to_ulps(x):
"""Convert a non-NaN float x to an integer, in such a w... |
"""
Functions for debugging purposes.
"""
import os
from pprint import pprint
import sys
import maya.cmds as cmds
def reload_python_modules(script_path):
"""
This reloads all currently loaded python modules that are located inside the given scriptPath.
This is mainly meant to be a developer tool so no "r... |
from roslib.packages import get_pkg_dir
from python_qt_binding.QtGui import *
from python_qt_binding.QtCore import *
from airbus_cobot_gui.context import Context
from plugin_provider import PluginProvider
from plugin import Plugin
from xml.etree import ElementTree as ET
def getStandAloneInstance(pkg_name, plugin_class... |
"""
Module for data analyze.
"""
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import os
from typing import Any
def output_csv(df: pd.DataFrame, output_data_path: str):
"""
Output df as a csv file to output_data_path.
Args:
df:Data
output_data_path:Output path ... |
import sys
from svgpathtools import wsvg, Line, QuadraticBezier, Path
from freetype import Face
def tuple_to_imag(t):
return t[0] + t[1] * 1j
ttf_filename = sys.argv[1]
face = Face(ttf_filename)
print(dir(face))
print('A', face.get_name_index(b'A'))
print('V', face.get_name_index(b'V'))
print('kern', face.get_... |
# Importing Application and Scene
from mithril import Application, Scene
# Creating a basic application
app = Application("Example01", (1280, 720), Scene())
# Running application
app.run()
|
"""ThreatConnect Batch Import Module"""
# standard library
import json
class Tag:
"""ThreatConnect Batch Tag Object"""
__slots__ = ['_tag_data', '_valid']
def __init__(self, name, formatter=None):
"""Initialize Class Properties.
Args:
name (str): The value for this tag.
... |
import numpy as np
import random
import os
from pathlib import Path
import torch
import torch.nn as nn
from torch import optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
from sklearn.model_selection import train_test_split
from transformers import DistilBertTokenizerFast
from transform... |
from .LabelEditor import LabelEditor
|
from setup_python_package.queries import get_sonar_code
def test_get_sonar_code(monkeypatch):
monkeypatch.setattr(
'builtins.input', lambda x: "1111111111111111111111111111111111111111")
get_sonar_code(False, "LucaCappelletti94_setup_python_package")
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 CERN.
#
# invenio-app-ils is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Ils series API."""
from functools import partial
from flask import current_app
from invenio_pidstore.models i... |
#!/usr/bin/env python3
import os.path
import tensorflow as tf
import helper
import warnings
from distutils.version import LooseVersion
import random
from glob import glob
import numpy as np
import scipy.misc
np.set_printoptions(threshold=np.nan)
CLOUD_MODE = True
if CLOUD_MODE:
data_dir = '/input'
else:
data_d... |
import numpy as np
import h5py
def get_images_rotation_according_to_rotation_label(images, rotations_list):
"""rotate images according to rotation list.
:arg:
rotationsList: expected list with length of 1-8. each number converts to binary and
represent a 90 degrees rotation through the axis. For examp... |
# Copyright 2017 Battelle Energy Alliance, 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 t... |
from protorpc import messages as api_messages
class ChannelResponseMessage(api_messages.Message):
"""ProtoRPC message definition to represent an application event."""
items = api_messages.StringField(1)
class SubscribeResponseMessage(api_messages.Message):
"""
ProtoRPC message definition to repr... |
import numpy as np
import cv2
import time
import socket
import io
from PIL import Image
import math
SERVER_IP = '192.xxx.xxx.xxx'
SERVER_PORT = 12397
SERVER_ADDR = (SERVER_IP, SERVER_PORT)
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]
def recvall(sock, count):
buf = b''
while count:
newbuf = soc... |
import json
import shutil
import tarfile
from os import rename
from os.path import join, splitext
import py7zr
import requests
from gemini import settings
def extract_file(archive, src, dest):
ext = splitext(archive)[1]
if ext == '.7z':
with py7zr.SevenZipFile(archive, 'r') as archive:
fo... |
import logging
import os
ROOT_DIR = os.environ['ROOT_DIR']
class LoggerFactory:
""" This class handles the different loggers according to a singleton factory pattern """
logger_dict = dict()
# Set levels for display / writing to logfile. Levels are in ascending order:
# NOTSET
# DEBUG
# INFO
... |
"""
This module contains functions for preprocessing neural recordings
"""
from yass.preprocess.run import run
__all__ = ['run']
|
import re
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as f:
readme = f.read()
# This hack is from http://stackoverflow.com/a/7071358/1231454;
# the version is kept in a seperate file and gets parsed - this
# way, setup.py doesn't have to... |
import uuid
from unittest import TestCase
from mock import patch, Mock, call
from pika.exceptions import AMQPError
from app.submitter.submitter import RabbitMQSubmitter, PubSubSubmitter, GCSSubmitter
class TestRabbitMQSubmitter(TestCase):
def setUp(self):
self.queue_name = 'test_queue'
self.host... |
import pyvisa
from pyvisa.constants import Parity,StopBits
import numpy as np
import matplotlib.pyplot as plt
import re
import math
from scipy.signal import find_peaks
import inspect
import vxi11
import time
#===========================================================================
# Oscilloscope - Rigol DS1000E seri... |
from http.client import BadStatusLine
import speech_recognition as sr
class STT:
def __init__(self):
self.r = sr.Recognizer()
print(sr.Microphone.list_microphone_names())
def run(self, lang="zh-TW"):
is_first = True
while True:
with sr.Microphone(device_index=10) ... |
"""
When the implementation of fib in Figure 4.7 is used to compute fib(5),
how many times does it compute the value o fib(2) on the way to computing
fib(5)?
"""
"""
Computes it 4 times
fib(5) = fib(4) = fib(3) = fib(2) = fib(n - 1) + fib(n - 2)
fib(n) = fib(n - 1) + fib(n -2)
n - 2 is naively recomputed for each fib... |
import logging
import os
from typing import Optional, Union
from ruamel import yaml
logger = logging.getLogger(__name__)
class FS:
@staticmethod
def load_yaml(path: str) -> Optional[Union[list, dict]]:
if not os.path.exists(path):
raise OSError('File does not exist: {}'.format(path))
... |
#
# Copyright (c) 2021. Los Alamos National Laboratory (LANL).
# Written by: Bhanuka Mahanama (bhanuka@lanl.gov)
# Research and Prototyping Team, SRO-RL,
# Los Alamos National Laboratory
#
# Correspondence: Lyudmila Balakireva, PhD (ludab@lanl.gov)
# Resear... |
# coding=utf-8
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework.views import APIView
from account.models import WechatI... |
import unittest
from apal_cxx import pytest_biharmonic_matrix
from apal_cxx import pytest_laplacian_matrix3D
from apal_cxx import pytest_add_same_element
from apal_cxx import pytest_add_mixed_element
from scipy.ndimage.filters import laplace
from scipy.linalg import toeplitz
import numpy as np
class TestBuildMatrices(... |
##############################################################################
#
# Copyright (c) 2008-2012 NaN Projectes de Programari Lliure, S.L.
# http://www.NaN-tic.com
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of... |
"""
This script creates all the index.html etc. for all the projects, orgs etc.
e.g.
/metrics
/metrics/twitter
/metrics/twitter/twemoji
"""
from glob import glob
import json
import os
PATH_TO_METRICS_POSTS = "_posts"
PATH_TO_METADATA = "_metadata"
PATH_TO_GRAPHS = "graphs"
ALL_ORGS = filter(os.path.isdir, glob(PATH... |
from subprocess import Popen, PIPE
from .assert_repository import assert_repository
GIT_STATUS_ARGS = ["git", "status", "-s"]
AWK_ARGS = ["awk", "{print $NF}"]
def staged_files():
assert_repository()
p1 = Popen(GIT_STATUS_ARGS, stdout=PIPE)
p2 = Popen(AWK_ARGS, stdin=p1.stdout, stdout=PIPE, stderr=PIPE)... |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <headingcell level=1>
# Testing Glider DAC access in Python
# <codecell>
import numpy as np
import matplotlib.pyplot as plt
import netCDF4
import numpy.ma as ma
import seawater
%matplotlib inline
# <markdowncell>
# This is a url from Kerfooot's TDS server, usin... |
#Copyright Anirban Kar (anirbankar21@gmail.com)
#
# 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 appl... |
'''
Created on Nov 19, 2021
@author: mballance
'''
from fusesoc.config import Config
from fusesoc.coremanager import CoreManager
from fusesoc.librarymanager import Library
from fusesoc.vlnv import Vlnv
from mkdv import get_packages_dir
import os
import logging
import yaml
import sys
import jinja2
class _ConfigFile(o... |
# """ 104: Crie um programa que tenha a função leiaInt(), que vai funcionar de forma
# semelhante 'a função input() do Python, só que fazendo a validação para aceitar apenas um valor numérico.
# Ex: n = leiaInt('Digite um n: ')"""
#
#
# def leia_int(num):
# n = str(input(num))
# while True:
# if not n.i... |
#!/usr/bin/env python
import os
import re
from setuptools import setup
INSTALL_REQUIRES = ["docopt"]
TEST_REQUIRES = ["pytest"]
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, "README.rst")) as f:
long_description = f.read()
with open(os.path.join(here, "picklecat.py")) as f:
... |
import numpy as np
from sklearn.kernel_approximation import Nystroem
from sklearn.linear_model import Ridge
from bolero.representation.ul_policies \
import UpperLevelPolicy, BoundedScalingPolicy
from bolero.utils.validation import check_random_state
from bayesian_optimization import GaussianProcessModel
class ... |
from django.shortcuts import render, redirect, reverse, HttpResponseRedirect
from django.contrib.auth import login, authenticate, logout
from twitteruser.forms import CreateUserForm, LoginForm
# Create your views here.
def register_view(request):
form = CreateUserForm()
if request.method == 'POST':
f... |
# Uses python3
# this is almost offensively simple
def main(n):
r = n // 10
n %= 10
return r + n // 5 + n % 5
if __name__ == '__main__':
print(main(int(input())))
|
from datetime import timedelta
from typing import Any, Dict, List, Mapping, Optional, Tuple, Type
import pytest
from blacksmith.domain.exceptions import HTTPError
from blacksmith.domain.model import HTTPRequest, HTTPResponse, HTTPTimeout
from blacksmith.domain.model.middleware.zipkin import AbstractTraceContext
from ... |
#!/usr/bin/env python
# Copyright (c) 2013-2015, Rethink Robotics
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# ... |
from distutils.core import setup
setup(name='fib',
version='1.0',
packages=['fib',],
) |
# @file
#
# Copyright 2020, Verizon Media
# SPDX-License-Identifier: Apache-2.0
#
'''
Basic smoke tests.
'''
Test.Summary = '''
Some test for the with directive.
'''
tr = Test.TxnBoxTestAndRun("With testing", "with.replay.yaml", config_path='Auto', config_key="meta.txn_box.global"
)
ts = tr.Variables.T... |
from django.db import models
from forge.models import TimestampModel, UUIDModel
class Team(TimestampModel, UUIDModel):
name = models.CharField(max_length=255)
members = models.ManyToManyField(
"users.User", related_name="teams", through="TeamMembership"
)
class Meta:
ordering = ("nam... |
"""network configuration"""
# system provided modules
import os, string, time, socket
# PlanetLab system modules
import sioc, plnet
# local modules
import plnode.bwlimit as bwlimit
import logger, iptables, tools
# we can't do anything without a network
priority=1
dev_default = tools.get_default_if()
def start():... |
from common.ciphers.stream import StreamCipher
class RC4(StreamCipher):
def __init__(self, key):
StreamCipher.__init__(self)
self._init_state_from(key)
def _capped_sum(self, a, b):
return (a + b) % 256
def _swap_S(self, i, j):
self.S[i], self.S[j] = self.... |
import logging
import time
from urllib.parse import urlparse
import html_telegraph_poster
import newspaper
import nltk
import telegram
from html_telegraph_poster.upload_images import upload_image
from sqlalchemy import and_
from rssbot import Database, News
nltk.download("punkt")
logger = logging.getLogger(__nam... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from celery.contrib.testing.app import setup_default_app
from celery.contrib.testing import worker
@pytest.fixture(scope="package")
def config():
from app.extensions.flask.config import Config
config = Config()
try:
config.from_toml("ap... |
from enum import Enum, unique
@unique
class ViewMode(Enum):
GREYSCALE = 'Greyscale'
RGB = 'RGB'
|
from django import forms
from django.contrib.auth.forms import UserCreationForm
from fornecedor.models import Fornecedor
class FornecedorForm(forms.ModelForm):
class Meta:
model = Fornecedor
fields = ('nome','img','telefone','cidade')
|
import os
import random
import sys
import uuid
import warnings
from typing import Any, Dict, Optional, Sequence
__windows__ = sys.platform == 'win32'
__resources_path__ = os.path.join(
os.path.dirname(
sys.modules.get('docarray').__file__ if 'docarray' in sys.modules else __file__
),
'resources',
... |
import gzip
import logging
import nibabel as nib
import os
from tempfile import TemporaryDirectory
import shutil
def log_subprocess_output(pipe, err=False, silence=[]):
"""Util function to log information throughout this package
using a common logger.
Parameters
----------
pipe: a stream to read ... |
import os
import signal
import subprocess
#def run_process(executable, params = None, cwd='.'):
# return Process.run(executable, params, cwd)
def chmod_x(executable_path):
return run_process("chmod", ['+x', executable_path])
class Process:
@staticmethod
def run(executable, params = None, cwd='.', **... |
import akshare as ak
import pandas as pd
import matplotlib.pyplot as plt
etf_fund_daily = ak.fund_em_etf_fund_daily()
code=[]
for i in etf_fund_daily.iterrows():
if '指数型' in i[1]['类型']:
code.append(i[1]['基金代码'])
for i in code[0:1]:
fund_em_etf_fund_info_df = ak.fund_em_etf_fund_info(fund='510050')
... |
"""Python specific tests."""
from tests.data import standard, specific
def get_tests():
tests = {}
tests.update(standard.get_tests())
tests.update(specific.get_tests())
# structures
tests.update({
'brackets': {
'a': {'[': ']', '{': '}', '(': ')', '<': '>'},
'b': {'... |
# https://www.geeksforgeeks.org/python-program-for-quicksort/
# GeekforGeeks allows copy-paste of their code as long as proper attribution is given to them.
# To be clear, this entire file was written by members/contributors of the geeksforgeeks team and this repo holds no ownership of this code.
# Python program for ... |
"""Main module."""
import io
import spdx.writers.tagvalue
from python_sbom import private
def generate(toplevel_package_name):
"""Given the toplevel package name, return a string containing a
SPDX software bill of materials."""
module_info = private.get_module_info(toplevel_package_name)
if not mo... |
import os
import sys
from jinja2 import Environment, FileSystemLoader, meta
def render(sense, action):
env = Environment(loader=FileSystemLoader('/src/templates/sense'))
template_source = env.loader.get_source(env, sense+'.py')[0]
parsed_content = env.parse(template_source)
vars = meta.find_undeclared... |
# Basic syntax
#T# Table of contents
#C# Blocks of code
#C# Variables, constants, literals
#C# - Type hints
#C# Escape sequences and escaped chars
#C# Expressions
#C# Function calls
#C# Statements
#C# Multiline statements
#C# Multistatement lines
#C# Metadata
#T# Beginning of content
# |-------------------------... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import decimal
import unittest
import datetime
from sane_finances.sources.base import ParseError
from sane_finances.sources.cbr.v2016.meta import CurrencyInfo, CurrencyRateValue
from sane_finances.sources.cbr.v2016.parsers import CbrCurrencyHistoryXmlParser, CbrCurrencyI... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-06-22 12:08
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Crea... |
'''Finds the rigid registrations between blocks neiboring BFIs.
Registers using low res (default) B/W photos, then saves the
transformations in "photo_rigid_transformations_#.pkl"
'''
import PyCA.Core as ca
import matplotlib.pyplot as plt
plt.ion() # tell it to use interactive mode -- see results immediately
import... |
from os.path import dirname
from pytezos.jupyter import InlineDocstring, get_attr_docstring, get_class_docstring
from pytezos.rpc.docs import rpc_docs
from pytezos.rpc.node import RpcNode
def format_docstring(class_type, query_path):
res = ['']
methods = {
'GET': '()',
'POST': '.post()',
... |
class BoxedValue(object):
"""
An updatable boxed value
"""
def __init__(self, value):
"""
Initialize the box with ``value``
:param value: value for box to hold
"""
self._value = value
def get(self):
"""
Return the box's current value
... |
import math
f = open('packet_pipeline_regfile.v', 'w')
# name type mask/ro_value default
REGS = [
('vendor', 'ro', "64'h2222222222222223"),
('clock', 'ro', ''),
('mac_0', 'rw', 0xffffffffffff, "48'h315f32445754"),
('mac_1', 'rw', 0xffffffffffff, "48'h325f32445754"),
('mac_2', 'rw', 0xff... |
from .regexanalyzer import RegexAnalyzer
class PhoneNumberAnalyzer(RegexAnalyzer):
"""Analyzer to match Phone Numbers"""
def __init__(self, action):
"""Analyzer to match international phone numbers"""
regex = r"^(\+[0-9]+\s*)?(\([0-9]+\))?[\s0-9\-]+[0-9]+$"
super().__init__(action, re... |
from .synapse import SynapseAdapter
|
from flask import render_template, jsonify, Blueprint
from flask_login import current_user
ajax_bp = Blueprint('ajax', __name__) |
"""
Node in the directed acyclic graph.
Implemented on observer-observable pattern.
Plugins should subclass Node and override alert, revoke, reset, report.
"""
import logging
from snewpdag.values import History
class Node:
def __init__(self, name, **kwargs):
"""
Initialize the node.
OVERRIDE this meth... |
# -*- coding: utf-8 -*-
# ————————————————————————–
# Copyright Commvault 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
#
# ... |
from purequant.config import config
from purequant.exchange.huobi.websocket import subscribe, handle_ws_data
from purequant.exchange.okex.websocket import subscribe_without_login
from purequant.exceptions import *
import asyncio, uuid
def markets_update():
print("行情服务器已启动,数据正获取并保存至MongoDB数据库中!")
if config.mark... |
import numpy as np
from sgp4.api import jday, SatrecArray
from datetime import datetime, timedelta
from sgp4.conveniences import jday_datetime
async def update_sat_pos(sat_arr: SatrecArray, t):
# t = datetime.utcnow()
jd, fr = map(np.atleast_1d, jday(t.year, t.month, t.day, t.hour, t.minute, t.second + t.micro... |
from django.apps import AppConfig
class HauzConfig(AppConfig):
name = 'Hauz'
|
import urllib.parse
import webbrowser
import json
from xml.etree import ElementTree
import sublime
import SublimeHaskell.sublime_haskell_common as Common
import SublimeHaskell.internals.logging as Logging
import SublimeHaskell.internals.utils as Utils
import SublimeHaskell.internals.unicode_opers as UnicodeOpers
imp... |
import re
randstr = '''
Keep the Blues flag
flying high,
Team India..
'''
print (randstr)
regex = re.compile('\n')
randstr = regex.sub(" ",randstr)
print (randstr)
print ("*****************************************")
regex1 = re.compile('\b')
randstr1 = regex1.sub(" ",randstr)
print (randstr1)
print ("**... |
import copy
from unittest.mock import patch, MagicMock
import pytest
import os
import random
import tempfile
from UM.Trust import TrustBasics, Trust
from scripts.signfile import signFile
from scripts.signfolder import signFolder
_folder_names = ["a", "b"]
_subfolder_names = ["sub", "."]
_file_names = ["x.txt", "y.tx... |
import time
from django.urls import re_path
from django.shortcuts import render
from django.utils.timezone import now
def test_view(request):
return render(request, 'test.txt', {
'date': now(),
'number': time.time(),
'locale': request.locale,
})
urlpatterns = [
re_path('^$', tes... |
brd = {
'name': ('Raspberry Pi B+/2'),
'port': {
'rpigpio': {
'gpio' : {
# BCM/Functional RPi pin names.
'bcm2_sda' : '3',
'bcm3_scl' : '5',
'bcm4_gpclk0': '7',
'bcm17' : '11',
... |
from ebs_snapshots.s3_backup_config import S3BackupConfig
import unittest
import yaml
import boto
from moto import mock_s3
class TestS3BackupConfig(unittest.TestCase):
@mock_s3
def test_can_initialize(self):
# if key doesn't exist, initialization should still succeed in case key
# is written a... |
from migen import *
class Bft(Module):
def __init__(self, clk, rst, platform):
self.clk = clk
self.rst = rst
self.dout_leaf_0 = Signal(49, name="dout_leaf_0")
self.dout_leaf_1 = Signal(49, name="dout_leaf_1")
self.dout_leaf_2 = Signal(49, name="dout_leaf_2")
self.do... |
# Generated by Django 3.0.2 on 2020-01-31 21:47
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('profiles', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='profile',
options={'ordering': ['-pk']},
... |
import numpy as np
from scipy.stats import special_ortho_group
from scipy.linalg import hadamard, subspace_angles, orth
from scipy.special import binom
def _find_theta(subspaces):
K = len(subspaces)
sum_thetas = 0
for i in range(K):
for j in range(i):
a = subspace_angles(s... |
# snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.]
# snippet-sourcedescription:[retrieve_inventory_results.py demonstrates how to retrieve the results of an Amazon S3 Glacier inventory-retrieval job.]
# snippet-service:[glacier]
# snippet-keyword:[Amazon S3 Glacier]
# snippet-keywo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.