content stringlengths 5 1.05M |
|---|
import pytest
from .testutils import name
@pytest.fixture
def test_name(request):
return name(request.node.name)
|
import time
import board
import busio
import adafruit_ads1x15.ads1115 as ADS
from adafruit_ads1x15.analog_in import AnalogIn
# Create the I2C bus
i2c = busio.I2C(board.SCL, board.SDA)
# Create the ADC object using the I2C bus
ads = ADS.ADS1115(i2c)
# you can specify an I2C adress instead of the default 0x48
# ads = A... |
from darkPy.guild import Guild
from darkPy.message import Message
from darkPy.user import User
class ConnectionState:
def __init__(self, client, *, loop=None):
self.client = client
self.loop = loop
self.guilds = {}
self.channels = {}
self.clear()
def clear(self):
... |
from xpag.tools.utils import (
DataType,
reshape,
hstack,
maximum,
datatype_convert,
get_env_dimensions,
)
from xpag.tools.eval import single_rollout_eval
from xpag.tools.timing import timing
from xpag.tools.logging import eval_log
from xpag.tools.learn import learn
from xpag.tools.replay import... |
import pytest
import numpy as np
import lapsolver as lap
def test_small():
costs = np.array([[6, 9, 1],[10, 3, 2],[8, 7, 4.]], dtype=np.float32)
r = lap.solve_dense(costs)
expected = np.array([[0, 1, 2], [2, 1, 0]])
np.testing.assert_allclose(r, expected)
costs = np.array([[6, 9, 1],[10, 3, 2]... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2015 uralbash <root@uralbash.ru>
#
# Distributed under terms of the MIT license.
"""
Show pyramid_sacrud records as tree.
"""
from pyramid.events import ApplicationCreated
CONFIG_MODELS = 'ps_tree.models'
PS_TREE_GET_TREE = 'ps_tree_get_t... |
import time
import sys
import numpy as np
import matplotlib.pyplot as plt
import tqdm
import torch
from graphgrove.vec_scc import Cosine_SCC
from graphgrove.graph_builder import unit_norm
gt = time.time
np.random.seed(123)
cores = 80
num_rounds = 50
thresholds = np.geomspace(1.0, 0.001, num_rounds).astype(np.float... |
import json
from django.utils import timezone
from datetime import datetime
from django.templatetags.tz import localtime
from django.shortcuts import render, get_object_or_404, redirect
from django.utils.translation import ugettext_lazy as _
from django.http import Http404
from django.core.management import call_comma... |
import math
import shutil
def print_head(string):
print(f"[1;4;33m{string}[m")
def print_val(val, name):
print_head(name)
print(val)
def print_mem(array, name, val_width=8, label_all=False):
addrsize = math.ceil(math.log2(len(array))/4)
valsize = math.ceil(val_width/4)
t_columns, t_rows... |
nome = str(input("Digite seu nome completo: ")).upper().strip()
nomeDividido = nome.split() #dividindo o nome
contandoNomes = len(nomeDividido)#contando a quantidade de nomes.
print("Satisfação em conhecer você!")
print("O seu primeiro nome é {}.".format(nomeDividido[0]))#imprimindo o primeiro nome.
print("O seu sultim... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Philippe Dellaert <philippe@dellaert.org>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = r'''
---
mod... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
r"""
# .---. .-----------
# / \ __ / ------
# / / \( )/ ----- (`-') _ _(`-') <-. (`-')_
# ////// '\/ ` --- ( OO).-/( (OO ).-> .-> \( OO) ) .->
# //// / // : : --- (,------.... |
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
from urllib.parse import unquote
impor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2013 Deren Wu <deren.g@gmail.com> (author).
#
# 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 pytest
from poetry.packages import FileDependency
from poetry.utils._compat import Path
DIST_PATH = Path(__file__).parent.parent / "fixtures" / "distributions"
def test_file_dependency_wheel():
dependency = FileDependency(DIST_PATH / "demo-0.1.0-py2.py3-none-any.whl")
assert dependency.is_file()
... |
import pygame
from SpriteBase import SpriteBase
"""
所有战机的基类,这里将战机的共性集中在一起,提供给所有有战机使用
"""
class PlanceBase(SpriteBase):
def __init__(self, screen):
"""
在子类要调用这个初始化方法
:param screen:
"""
location = self.getLocation() # 获取子类重写的位置
paths = self.getImagePaths() # 获取子类... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# by Qige <qigezhao@gmail.com> since 2020-08-09
import json
import functools
class WechatMiniAppReponse(object):
@staticmethod
def serialize(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
data = func(*args, **kwargs)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import tests
from tests.tweets import tweet2
from twitter_rest_exporter import TwitterRestStatusTable
from datetime import datetime
class TestTwitterStatusTable(tests.TestCase):
def test_row(self):
table = TwitterRestSta... |
# -*- coding: utf-8 -*-
from requests import get
from bs4 import BeautifulSoup
def best_hashtags(tag, kind='popular'):
r = get(f'http://best-hashtags.com/hashtag/{tag}/')
if r.status_code == 200:
soup = BeautifulSoup(r.text, 'html.parser')
tag_boxs = soup.findAll("div", {"class": "tag-box"})
... |
#!/usr/bin/env python
# Licensed under a 3-clause BSD style license, see LICENSE.
"""
Tests for the skhep.dataset.defs module.
"""
# -----------------------------------------------------------------------------
# Import statements
# -----------------------------------------------------------------------------
import p... |
import asyncio
import pytest
from modmail.utils.general import await_nonblocking, nonblocking
@pytest.mark.asyncio
async def test_await_nonblocking() -> None:
"""Ensure that we can execute coroutines asynchronously from a sync task."""
a = 0
async def test(number: int) -> None:
nonlocal a
... |
import sys
from g_python.gextension import Extension
from g_python.hunitytools import UnityRoomUsers, UnityRoomFurni
extension_info = {
"title": "Room stuff",
"description": "g_python test",
"version": "1.2",
"author": "sirjonasxx & Hellsin6"
}
ext = Extension(extension_info, sys.argv)
ext.start()
d... |
import queue
import re
from threading import Thread
from curses import *
class SpigotOutputWindow:
"""Output window for Spigot.
Prints out the server's outpit from stdout and stderr.
A callback can be registered which executes when a setblock command is detected from Minecraft."""
set_block_ca... |
from django.views.generic import DetailView, ListView
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.contrib import messages
from django.core.urlresolvers import reverse
from med_social.views.base import... |
from django.db import models
from auditlog.registry import auditlog
from apps.core.models import (
TypePartner,
)
class Partner(models.Model):
MAN = 1
WOMAN = 2
SEX_CHOICES = (
(MAN, 'Male'),
(WOMAN, 'Female'),
)
first_name = models.CharField(max_length = 50, verbose_name = 'Fir... |
import gzip
import io as StringIO
import os
import numpy as np
import pandas as pd
def parse_header_of_csv(csv_str):
# Isolate the headline columns:
headline = csv_str[:csv_str.index('\n')]
columns = headline.split(',')
# The first column should be timestamp:
assert columns[0] == 't... |
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
(r"/yhl", tornado.web.RedirectHandler, {"url": "/yhl/index.html"}),
(r"/yhl/",... |
import time
import os
import pandas as pd
from collections import defaultdict
# Get list of events and ages
from swimnet import events, ages, metrics
from metrics import *
names_location = "data/test_names.csv"
# Path needs to have backslashes (chrome driver doesn't like forward slashes)
xlsx_location = os.path.absp... |
#!/usr/bin/env python
'''
Este módulo se encarga de buscar entre los archivos dentro de la carpeta /dataset.
Usa extensiones comunes para identificar imágenes cuyo nombre sea el que introdució
el usuario, para después sacar la codificación y poder dibujar los valores obtenidos.
DiracSpace
'''
img_heu... |
# https://leetcode.com/problems/scramble-string/
#
# algorithms
# Hard (31.83%)
# Total Accepted: 92,440
# Total Submissions: 290,420
class Solution(object):
def isScramble(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
length = len(s1)
... |
"""
Code that goes along with the Airflow located at:
http://airflow.readthedocs.org/en/latest/tutorial.html
"""
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
from datetime import datetime, timedelta
# Following are defaults which can be overridden later on
default_args = {
... |
#coding=utf-8
#无限循环P110 2017.4.17
active = True
t=1
while active:
t+=1
print(t)
|
from config import model_name
import pandas as pd
import swifter
import json
import math
from tqdm import tqdm
from os import path
from pathlib import Path
import random
from nltk.tokenize import word_tokenize
import numpy as np
import csv
import importlib
from transformers import RobertaTokenizer, RobertaModel
import ... |
# -*- coding: utf-8 -*-
from flask import jsonify
from entrenamiento.views.base import UserRequiredView
class DatabaseInformationView(UserRequiredView):
''' Se encarga de obtener toda la informacion del schema
de la base de datos, para que el javascript pueda hacer
su magia.
Ademas, levanta como con... |
from nose.tools import *
from lamson.routing import *
from lamson.mail import MailRequest
from lamson import queue, routing, encoding
from mock import *
def setup():
Router.clear_states()
Router.clear_routes()
def teardown():
setup()
def test_MemoryStorage():
store = MemoryStorage()
store.set(te... |
from django.conf.urls import url
from django.contrib import admin
from main import views
from django.urls import path
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.home, name='home'),
path('add_todo/', views.add_todo),
path('delete_todo/<int:todo_id>/', views.delete_todo),
]
|
"""Exceptions used throughout package"""
class WorldgenError(Exception):
"""Base worldgen Error"""
class CommandError(WorldgenError):
"""Raised when there is an error in command-line arguments"""
class BadCommand(WorldgenError):
"""Raised when a command is not found""" |
import json
import logging
from typing import Dict
from typing import List
import neo4j
from googleapiclient.discovery import HttpError
from googleapiclient.discovery import Resource
from cartography.util import run_cleanup_job
from cartography.util import timeit
logger = logging.getLogger(__name__)
@timeit
def ge... |
"""
Tellurium utilities for working with COMBINE archives.
Open Modeling EXchange format (OMEX) is the basis of the COMBINE Archive, a single file that supports
the exchange of all the information necessary for a modeling and simulation experiment in biology.
An OMEX file is a ZIP container that includes a manifest fi... |
from thx_bot.models import Model
from thx_bot.models import mongo_client
class User(Model):
collection = mongo_client.thx_tg_integration.users
|
from django.db.models import Sum, Q, Count, Value, F
from django.db.models.functions import Coalesce
from .models import Item, Unit, Inventory
def shelf_counter(inventory, created_by, shelf_id):
if any(var is None for var in [inventory, created_by, shelf_id]):
return 0
item_num = Item.object... |
from mycleaners.base import Cleaner, ManualTable, ManualText
class HzbankTable(ManualTable):
table_labels_config = {}
class HzbankText(ManualText):
labels_check_config = {}
labels_check_one_config = {}
class HzbankCleaner(Cleaner):
name = 'HzbankCleaner'
bank_name = '杭州银行'
... |
from entities.category import CategoryEntity
from entities.product import ProductEntity
|
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import pyvmax
# this obviously won't work... just testing
vmax_api = pyvmax.connect('url', 'user', 'pass')
|
import os, sys
import tensorflow as tf
from PIL import Image
import numpy as np
from .DATA_HDR import *
from .MODEL_HDR import *
from .FUNCTION import *
from .PREPROCESSING_HDR import *
print(current_time() + ', exp = %s, load_model path = %s' % (FLAGS['num_exp_HDR'], os.path.dirname(os.path.abspath(__file__))))
os.e... |
import unittest
from parameterized import parameterized
from src.menuClass import MenuClass
class MenuClass_chooseLanguage_MethodLevel(unittest.TestCase):# Poziom Method
def setUp(self):
self.tmp = MenuClass()
@parameterized.expand([
("EN", "EN"),
("EN", "EN"),
])
def test_choo... |
import json
import os
from dataclasses import dataclass
from haystack import Finder
from haystack.document_store.elasticsearch import ElasticsearchDocumentStore
from haystack.reader.farm import FARMReader
from haystack.retriever.dense import DensePassageRetriever
from haystack.retriever.sparse import ElasticsearchRetr... |
file = get_var('file')
sheet = int(get_var('sheet') or 1) - 1
ids = get_var('ids') or "0"
ids = [int(x) - 1 for x in ids.split(',')]
names = get_var('names') or "1"
names = [int(x) - 1 for x in names.split(',')]
direction = get_var('direction') or "row"
start = get_var('start')
if not start and direction == "row":
... |
"""
File: section3/cifar10_model.py
Author: Brandon McKinzie
Description: Builds the CIFAR-10 network.
"""
import tensorflow as tf
def l2_regularizer(wd):
def _l2_regularizer(var, name=None):
weight_decay = tf.multiply(tf.nn.l2_loss(var), wd, name=name)
tf.add_to_collection('losses', weight_decay... |
import logging
from distutils.version import LooseVersion
import pytest
from modernrpc.utils import logger_has_handlers, get_modernrpc_logger
def test_configured_logger():
# Logger has been configured in settings.py
# In such case, logging.getLogger() and get_modernrpc_logger() return
# the same object ... |
# Copyright 2019 Michael Kemna.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
import numpy as np
import pytest
from numba_celltree.algorithms import (
cohen_sutherland_line_box_clip,
cyrus_beck_line_polygon_clip,
liang_barsky_line_box_clip,
)
from numba_celltree.constants import Box, Point
def ab(a, b, c):
"""Flip the result around to compare (a, b) with (b, a)"""
return (... |
#! /user/bin/env python
# -*- coding:utf-8 -*-
from apscheduler.schedulers.background import BackgroundScheduler
import subprocess
import os
from datetime import datetime
import time
import logging
logging.basicConfig(level=logging.DEBUG)
def tick_list():
logging.debug('启动爬虫! The time is: %s' % datetime.now())
... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'H:\python_work\plotWav\0330_waveModule\waveModule.ui'
#
# Created: Tue Apr 02 14:18:35 2013
# by: pyside-uic 0.2.14 running on PySide 1.1.2
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
clas... |
"""Prioritize structural variants based on biological information.
Provides high level summaries of structural variants in regions of interest,
as defined by the input configuration. Tries to narrow structural variant calls
based on potential biological targets.
"""
import os
import pandas as pd
import toolz as tz
fr... |
# -*- coding: utf-8 -*-
import swig_ex4
import numpy as np
np_array = np.array([5, 4, 3, 2, 1])
print(np_array, "에서 Max값을 찾는다.")
print("결과:", swig_ex4.find_max(np_array))
np_array = swig_ex4.create_np_array(10)
print("\n입력받은 사이즈만큼의 numpy.array를 생성한다")
print("생성된 객체의 타입:", type(np_array))
print("결과:", np_array)
np_ar... |
from abc import abstractmethod
from artemis.general.should_be_builtins import memoize
import numpy as np
from six.moves import xrange
__author__ = 'peter'
def vector_length_to_tile_dims(vector_length, ):
"""
You have vector_length tiles to put in a 2-D grid. Find the size
of the grid that best matches... |
"""
step08.py: get R2 scores
"""
import argparse
import multiprocessing
import pandas
import scipy.stats
import step00
def r2_score(x, y):
"""
r2_score: get R2 score between x and y
"""
return scipy.stats.linregress(x, y)[2]
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parse... |
by = b'abcd\x65'
print(by)
print(type(by))
print(len(by))
print()
by += b'\xff'
print(by)
print(len(by))
print(by[0])
try:
by[0] = 100
except TypeError as err:
print(err)
print()
by = b'abcd\x65'
barr = bytearray(by)
print(barr)
print(len(barr))
barr[0] = 102
print(barr)
print()
by = b'd'
s = 'abcde'
try:
... |
import logging
from . import utils
logger = logging.getLogger(__name__)
def get_user_objs(load, *, ask_on_failure=True):
"""
Load the user's modules.
All objects from these modules will be imported e.g.
``from module import *`` and the objects will be returned.
Parameters
----------
lo... |
"""
TTWidgets - Tagged-Text Multi-Font Enhanced Tkinter Widgets
=========
Package **TTWidgets** improves the Button, Label, and Listbox widgets of the
Tkinter library, and provides a bonus ToolTip widget, all with support for
multiple fonts and visual schemes via *tagged-text* input.
The standard Tkinter Button and L... |
#!/usr/bin/env python3
import argparse
import flask
from http import server
import sys
app = flask.Flask(__name__, static_url_path='')
@app.route('/')
def index():
return flask.render_template('index.html')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Testing server launcher')
parse... |
#!/usr/bin/env python
import math
"""
// ARRI ALEXA IDT for ALEXA logC files
// with camera EI set to 800
// Written by v3_IDT_maker.py v0.06 on Thursday 01 March 2012 by alex
float
normalizedLogCToRelativeExposure(float x) {
if (x > 0.149659)
return (pow(10,(x - 0.385537) / 0.247189) - 0.052272) / 5.555556;
e... |
class YoutubeRPCException(Exception):
def __init__(self, message: str = None):
if message is None:
message = 'An error has occurred within Youtube RPC'
super().__init__(message)
class BrowserNotFound(YoutubeRPCException):
def __init__(self):
super().__init__('Could n... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import (
compat_urllib_parse,
)
from ..utils import (
remove_start,
)
class VideoMegaIE(InfoExtractor):
_VALID_URL = r'''(?x)https?://
(?:www\.)?videomega\.tv/
(?:iframe\.php)?\?ref=(?P... |
import _initpath
import os
import re
import collections
import pyradox
province_map = pyradox.worldmap.ProvinceMap(game = 'CK3')
colormap = {}
for water_province in province_map.water_provinces:
#colormap[water_province] = (51, 67, 85)
#rivers = (142, 232, 255)
#lakes = 51, 67, 8... |
"""
jumpserver.config
~~~~~~~~~~~~~~~~~
Jumpserver project setting file
:copyright: (c) 2014-2017 by Jumpserver Team
:license: GPL v2, see LICENSE for more details.
"""
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
class Config:
# Use it to encrypt or decrypt data
# SE... |
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import Dataset
class ECGRecord:
"""
class for parsing ecg in .csv format
with the following fields:
lead_system: ...
sampli... |
import sys
sys.path.append('./build')
sys.path.append('../lib')
from samcnet.probability import *
from samcnet.pydai import PyVar, PyVarSet, PyFactor, PyJTree
u = PyVar(0,2)
v = PyVar(1,2)
x = PyVarSet(u,v)
y = PyVarSet(u)
print len(x)
print len(y)
f1 = PyFactor(x)
f2 = PyFactor(u)
f1.set(0,0.01)
print f1
f1.norm... |
import threading
import os
# Cache that depend's on file modification time
__version__ = "1.0.0"
__author__ = 'weldpua2008@gmail.com'
# store cache data
__cache_store = {}
__lock = threading.Lock()
ttl = 86400
# # store file access time
# __cache_file_store = {}
# pylint: disable=logging-not-lazy
class NotFoundE... |
'''
Pulls data from xml and creates an array for each user consisting of PMID,
type, and annotation. Uses NLTK scoring metrics tools to determine
precision, recall, and f-score. By including PMID in the hash, this version
allows for examining user to user comparisons across multiple documents in the
... |
#!/usr/bin/env python
#
# Copyright 2013 Andy Gimma
#
# 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... |
import asyncio
import logging
import aiohttp
from rgparse import parse_info, parse_publications
program = 'researchgate_logger'
logger = logging.getLogger(program)
class Profile:
PROFILE_FORMAT = 'http://www.researchgate.net/profile/%s'
PUBLICATION_URL = '%s/publications' % PROFILE_FORMAT
INFO_URL = '... |
from dolfin import *
import numpy as np
import time
m =6
errL2u = np.zeros((m-1,1))
errL2p = np.zeros((m-1,1))
NN = np.zeros((m-1,1))
DoF = np.zeros((m-1,1))
Vdim = np.zeros((m-1,1))
Qdim = np.zeros((m-1,1))
Wdim = np.zeros((m-1,1))
l2uorder = np.zeros((m-1,1))
l2porder = np.zeros((m-1,1))
nonlinear = np.zeros((m-1,1)... |
import os
class AlreadyRegistered(Exception):
pass
class NotRegistered(Exception):
pass
class PreprocessorRegistry(object):
def __init__(self):
self._registry = {}
def process_path(self, source_url):
path_dir, ext = os.path.splitext(source_url)
new_url = source_url
... |
# Copyright (c) 2017-2022 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""
:mod:`dazl.client` package
==========================
The :mod:`dazl.client` module a high-level view of the Ledger API in a friendly way.
It provides:
* a callback-base... |
import json
from .base import NgenicBase
from ..const import API_PATH
class NodeStatus(NgenicBase):
def __init__(self, session, json, node):
self._parentNode = node
super(NodeStatus, self).__init__(session=session, json=json)
def battery_percentage(self):
if self["maxBattery"] == 0:
... |
import time
import serial
class Robot:
def __init__(self, port):
self.serial = serial.Serial(port, 115200)
# Wake up Grbl firmware
self.serial.write(b"\r\n\r\n")
time.sleep(2) # Wait for Grbl to initialize
self.serial.flushInput() # Flush startup text in serial input
... |
import botocore
import click
from newrelic_lambda_cli import utils
def list_functions(session, filter=None):
client = session.client("lambda")
all = filter == "all" or not filter
pager = client.get_paginator("list_functions")
for res in pager.paginate():
funcs = res.get("Functions", [])
... |
import sys
from collections import Counter
sys.stdin = open('input.txt')
d = {'B': 1, 'U': 10, 'S': 100, 'P': 1000,
'F': 10000, 'T': 100000, 'M': 1000000}
for _ in range(int(input())):
s = raw_input().strip()
total = 0
er = False
for k, v in Counter(s).items():
if v >= 10:
er =... |
# Copyright (C) 2020, 2021 Satoru SATOH <satoru.satoh@gmail.com>
# SPDX-License-Identifier: MIT
#
# pylint: disable=invalid-name,too-few-public-methods
"""Common utility test routines and classes.
"""
import os
import pathlib
import subprocess
import tempfile
import typing
import unittest.mock
import ansiblelint.confi... |
from operator import add
def tokenize(text):
return text.split()
words = text.flatMap(tokenize)
print words
|
import os
from flask import Flask, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_bcrypt import Bcrypt
from sqlalchemy.ext.automap import automap_base
# Set this to True for production!
production = True
app = Flask(__name__)
app.config.from_object('config')
... |
# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import time
import pygame
import uuid
def publish_message(client, message):
client.publish('testPepper', message)
direcction = {'forward':'fw','backward':'bw'}
head_position = {'up':'h_up','down':'h_dw','left':'h_lf','right':'h_rt','center':'h_ct'}
posit... |
#!/usr/bin/env python3
import time
import threading
from PIL import Image
import gi
gi.require_version('Gst', '1.0')
from gi.repository import Gst
gi.require_version('GstWebRTC', '1.0')
from gi.repository import GstWebRTC
gi.require_version('GstSdp', '1.0')
from gi.repository import GstSdp
Gst.init(None)
class Mix... |
# Generated by Django 3.1.5 on 2021-03-17 11:13
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('blogapp', '00... |
# Copyright (c) Facebook, Inc. and its affiliates.
import os, sys, shutil
import os.path as osp
from . import general_utils as gnu
def main():
root_dir = "/mnt/SSD/rongyu/data/3D/frank_mocap/dataset/expose"
in_dir = osp.join(root_dir, "image_crop/train")
out_dir = osp.join(root_dir, "image_dist/train")
... |
def isnotebook():
try:
shell = get_ipython().__class__.__name__
if shell == 'ZMQInteractiveShell':
return True # Jupyter notebook or qtconsole
elif shell == 'TerminalInteractiveShell':
return False # Terminal running IPython
else:
return False ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
try:
from setuptools import setup, find_packages
except ImportError:
import ez_setup
ez_setup.use_setuptools()
from setuptools import setup, find_packages
VERSION = '0.4'
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), ... |
import ctypes
import win32api
import time
import multiprocessing
from random import randrange
from multiprocessing.spawn import freeze_support
import overlay # text overlaying module
import modus1, modus2, modus3, modus4, modus5, modus6, modus7 # config files
# C struct redefinitions
PUL = ctypes.POINTER... |
toshl_parameters = {'username': '<Your_API_Key>',
'password': '',
'upload_url': 'https://api.toshl.com/'} |
'''
Created on Apr 2014
Edited on Oct 2020
@author: Jan Verhoeven
@author: Bassem Girgis
@copyright: MIT license, see http://opensource.org/licenses/MIT
'''
from threading import Thread
from typing import Optional, Tuple, Type
from ..command import ICommand
from ..receiver import SubSocket, SubSocketAddress
from... |
# -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the ... |
#: Operation ids
ops = [
"transfer",
"limit_order_create",
"limit_order_cancel",
"call_order_update",
"fill_order",
"account_create",
"account_update",
"account_whitelist",
"account_upgrade",
"account_transfer",
"asset_create",
"asset_update",
"asset_update_bitasset",... |
#******************************************************************************
# (C) 2018, Stefan Korner, Austria *
# *
# The Space Python Library is free software; you can redistribute it and/or *
... |
from setuptools import setup
import unittest
def readme():
try:
import pypandoc
return pypandoc.convert('README.md', 'rst')
except:
# Fall back to raw README
with open('README.md') as f:
return f.read()
# from https://stackoverflow.com/a/37033551
def my_test_suite()... |
from typing import Set
import collections
import os
import secrets
import time
import aiohttp
import pytest
from hailtop.config import get_deploy_config, get_user_config
from hailtop.auth import service_auth_headers
from hailtop.utils import retry_response_returning_functions, external_requests_client_session, sync_sl... |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
from vit_pytorch.longformer.longformer import LongformerSelfAttention |
"""
Utilities for tests only. These are not or should not be used normally -
functions here are crafted as we don't want to use ``vcs`` to verify tests.
"""
import os
import re
import sys
from subprocess import Popen
class VCSTestError(Exception):
pass
def run_command(cmd, args):
"""
Runs command on th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.