content stringlengths 5 1.05M |
|---|
import unittest
from gifts._cosine_similarity import cosine_similarity
class TestCosine(unittest.TestCase):
def test(self):
# https://www.learndatasci.com/glossary/cosine-similarity/
d1 = [0, 0, 0, 1, 1, 1, 1, 1, 2, 1, 2, 0, 1, 0]
d2 = [0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1]
d3... |
from html import escape
from datetime import datetime
from atlassian import Confluence
from jinja2 import Environment, PackageLoader, select_autoescape
from .html_coverage import HTMLData
from .models import Module
def make_table(rows):
# TODO: use templating
table = "<table><tbody><tr><th>Name</th><th>Stat... |
# -*- coding: utf-8 -*-
# @Time : 2021/1/12 下午2:49
# @Author : zhongyuan
# @Email : zhongyuandt@gmail.com
# @File : train.py
# @Software: PyCharm
from model import Model
from datasets.wineDataset import WineDataset
import torch.utils.data.dataloader as Dataloader
import torch.optim as optim
import os
from tor... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 16 19:47:50 2017
@author: lfoul, Antonin ROSA-MARTIN (aka MrWormsy) and IGIRANEZA Beda
"""
import http.client
from urllib.parse import urlparse
import socket
class Sensor:
"""
A Sensor is represented as a URL, a label and a list of threshold
"""
def... |
#============================ adjust path =====================================
import sys
import os
if __name__ == "__main__":
here = sys.path[0]
sys.path.insert(0, os.path.join(here, '..'))
#============================ imports =========================================
from SmartMeshSDK import ApiExcepti... |
"""
Command-line interface for valar-dagger.
"""
from __future__ import annotations
import logging
from pathlib import Path
import typer
from valardagger.watcher import Watcher
logger = logging.getLogger(__package__)
cli = typer.Typer()
@cli.command()
def start(path: Path) -> None:
"""
Starts the schedu... |
__author__ = 'jbs'
import ship_data
def test():
print ship_data.boat_heading
ship_data.boat_heading = 7
print ship_data.boat_heading
test() |
#! /usr/bin/python
# by edward silher for collecting gps data in conjuction with AIS data
# edwardsihler@ursusonline.net
import serial
import subprocess
import os
from gps import *
from time import *
import time
import threading
gpsd = None #seting the global variable
os.system('clear') #clear the terminal (option... |
from django import forms
from django.contrib.auth import get_user_model
class UserForm(forms.ModelForm):
class Meta:
model = get_user_model()
fields = ['first_name', 'last_name', 'email', 'is_superuser', 'username', 'password', 'groups']
widgets = {
'password': forms.PasswordIn... |
from .validator import validate_params, Param, GET, FORM, PATH, JSON, HEADER
from .rules import (
AbstractRule,
CompositeRule,
Enum,
IsDatetimeIsoFormat,
IsEmail,
MaxLength,
MinLength,
Max,
Min,
NotEmpty,
Pattern,
)
|
# -*- coding: utf-8 -*-
import query
import unittest
class TestAlgorithms(unittest.TestCase):
def setUp(self):
# Generate some BS coordinates that are in the range of all
# elevation services.
self.latlons = [
(40.03488860164351, -105.27230724626),
(40.03498860164351, -105.27230724626),
... |
"""
# Step 1 - Create the App
# Step 2 - Create the Game
# Step 3 - Build the Game
# Step 4 - Run the App
"""
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty
from kivy.vector import Vector
from kivy.clock import C... |
# send incrementing packets containing numbers to given host
# start up a server by using ncat
# the static 5.59BETA1 version would work
# http://nmap.org/dist/ncat-portable-5.59BETA1.zip
# the server should be started with CRLF as EOF
# eg: ncat -u -l -C localhost 9111
import subprocess
import argparse
from time impor... |
# %%
from collections import defaultdict
# %%
with open('input.txt', 'r') as f:
data = f.read()
data = data.split('\n')
# %%
with open('test_input.txt', 'r') as f:
test_data = f.read()
test_data = test_data.split('\n')
# %%
def to_sequence(data):
sequences = []
for x in data:
singal_pattern, dig... |
import backbone.support.configurations_variables as confv
import backbone.support.data_loading as dl
import backbone.support.data_analysis as da
import backbone.support.data_cleaning as dc
import backbone.support.configuration_classes as confc
import backbone.support.saving_loading as sl
import backbone.support.plots_a... |
from . import ops
from . import bbox
from . import mask
from . import backbone
from . import neck
from . import head
from . import loss
from . import architecture
from . import post_process
from . import layers
from . import utils
from .ops import *
from .bbox import *
from .mask import *
from .backbone import *
from ... |
# -*- encoding: utf-8 -*-
from hypernets.tests.tabular.tb_dask import is_dask_installed, if_dask_ready, setup_dask
from .var_len_categorical_test import TestVarLenCategoricalFeature
if is_dask_installed:
import dask.dataframe as dd
@if_dask_ready
class TestVarLenCategoricalFeatureByDask(TestVarLenCategoricalFeat... |
from hiro_graph_client import PasswordAuthTokenApiHandler, HiroGraph, SSLConfig, GraphConnectionHandler
from .testconfig import CONFIG
class TestClient:
connection_handler = GraphConnectionHandler(
root_url=CONFIG.get('URL'),
ssl_config=SSLConfig(verify=False)
)
hiro_api_handler = Passwor... |
"""Interface tests for Treants.
"""
import datreant as dtr
from datreant import Treant
import pytest
import mock
import os
import py
from . import test_collections
from .test_trees import TestTree
class TestTreant(TestTree):
"""Test generic Treant features"""
treantname = 'testtreant'
@pytest.fixture
... |
from django.apps import AppConfig
class HomeShortyConfig(AppConfig):
name = 'home_shorty'
|
import urllib2
from jsonrpc import JSONRPCService
from urllib import urlencode
from utils.cmd import keep_trying
def reviews_pastehtml_upload(source, input_type="html"):
"""
Uploads 'source' as an 'input_type' type to pastehtml.com.
source ....... source of the webpage/text
input_type ... txt or htm... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2018-03-10 12:27
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 = [
('config', '0002_auto_201803... |
# __init__.py
# Version of the visual-automata package
__version__ = "1.1.1"
|
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 28 15:37:10 2020
@author: harinder
"""
import yaml
def convert_to_jmx():
filename = "result/jmeter.jmx"
stream = open("result/jmeter.yml","r")
my_dicts = yaml.load_all(stream)
try:
with open(filename,"w") as xmlfile:
... |
from dlapp import create_from_yaml_file
from dlapp import create_from_yaml_data
from dlapp import create_from_json_file
from dlapp import create_from_json_data
from dlapp import create_from_csv_file
from dlapp import create_from_csv_data
from os import path
test_path = path.dirname(__file__)
class TestDynamicDict:
... |
"""
Constants and functions pertaining to NFC bounding interval annotator datasets.
"""
import math
from tensorflow.data import Dataset, TFRecordDataset
from tensorflow.io import FixedLenFeature
import numpy as np
import tensorflow as tf
import vesper.util.signal_utils as signal_utils
import vesper.util.time_freque... |
"""
A random distribution is a set of random numbers
that follow a certain propability density function.
Probability Density Function:
A function that describes a continuous probability.
i.e. probability of all values in an array.
The probability is set by a number between 0 and 1,
where 0 means that the v... |
from behave import given, when, then, step
import sys
import pexpect
import time
import os
@when("we open the command line interface")
def step_impl(context):
os.chdir(context.basedir)
context.config_prompt = 'brewer@localhost#'
context.normal_prompt = 'brewer@localhost>'
context.cli = pexpect.spawn('... |
from setuptools import setup, find_packages
with open('README.md', 'r') as fh:
long_description = fh.read()
setup(
name='exercisecoachtools',
version='0.1.2',
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
python_requires='>=3.7, <4',
url='https://github.com/chandojo/ExerciseCoa... |
from typing import Dict, Iterable, Iterator, List, Sequence, Optional, Tuple
from word_ladder.types import WordDict
from word_ladder.rung import Rung
def get_word_with_letter_missing(word: str, position: int) -> str:
"""
>>> get_word_with_letter_missing('dog', 0)
'?og'
>>> get_word_with_letter_missing... |
from ignite.engine import Events, Engine
from protozoo.tiktorch_config_keys import ModelZooEntry
def get_trainer(model_zoo_entry: ModelZooEntry) -> Engine:
def training_step(trainer: Engine, batch) -> float:
print("STEP")
ipt, tgt = batch
trainer.state.optimizer.zero_grad()
pred =... |
#!/usr/bin/env python3
import argparse
import datetime
import json
import re
from copy import deepcopy
from gocddash.analysis import data_access, go_client, domain
from gocddash.util import app_config
from gocddash.console_parsers.junit_report_parser import JunitConsoleParser
from gocddash.console_parsers.determine_p... |
from __future__ import annotations
import typing as ty
import aurflux
import discord
import itertools as itt
import collections as clc
import asyncio as aio
if ty.TYPE_CHECKING:
import datetime
def message2embed(message: discord.Message, embed_color: discord.Color = None):
embeds = []
# for image in messag... |
import numpy as np
from numpy.random import RandomState
from qgomoku.core.board import Board
from qgomoku.learner import pexp_mind
minds = []
SIZE = 9
def run():
mind = pexp_mind.PExpMind(size=SIZE, init=False, channels=4)
mind.load_net('../models/9_4_4')
rs = RandomState(42)
for i in range(50):
... |
#!/usr/bin/env python
# Copyright 2012 James McCauley
#
# 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 la... |
import numpy as np
import cv2
import pyopengv
import networkx as nx
import logging
from opensfm import context
from opensfm import multiview
from opensfm.unionfind import UnionFind
logger = logging.getLogger(__name__)
# pairwise matches
def match_lowe(index, f2, config):
search_params = dict(checks=config.get(... |
import warnings as test_warnings
from unittest.mock import patch
import pytest
from rotkehlchen.assets.asset import Asset
from rotkehlchen.assets.converters import UNSUPPORTED_POLONIEX_ASSETS, asset_from_poloniex
from rotkehlchen.constants.assets import A_BTC, A_ETH
from rotkehlchen.errors import DeserializationError... |
'''
This file is part of GFLIB toolbox
First Version Sept. 2018
Cite this project as:
Mezher M., Abbod M. (2011) Genetic Folding: A New Class of Evolutionary Algorithms.
In: Bramer M., Petridis M., Hopgood A. (eds) Research and Development in Intelligent Systems XXVII.
SGAI 2010. Springer, Lon... |
#Skill : Ceil, list
#MS Excel column titles have the following pattern: A, B, C, ..., Z, AA, AB, ..., AZ, BA, BB, ..., ZZ, AAA, AAB, ... etc. In other words, column 1 is named "A", column 2 is "B", column 26 is "Z", column 27 is "AA" and so forth. Given a positive integer, find its corresponding column name.
#Examples:... |
import logging
from unittest.mock import patch
from rich.logging import RichHandler
import app
@patch("app.LOG_LEVEL", "DEBUG")
def test_logging(capsys):
assert app.LOG_LEVEL == "DEBUG"
assert isinstance(app.logging.root.handlers[0], RichHandler)
app.logging.root.setLevel(logging.DEBUG)
assert app.... |
# demo temperatuur sensor DHT22
# Configuration:
# - temperature/humidity sensor DHT22 on GPIO12
# - lED op GPIO14
# 2017-1003 PePo OLED output, Huzzah
import machine,time
import dht
import ssd1306
# create DHT22 sensor object
sensor = dht.DHT22(machine.Pin(12))
# create LED object on pin GPIO14
led = machine.Pin(14... |
import sqlite3
import pandas as pd
def save_dataframe_to_sql(data_frame, table_name):
"""
Save dataframe specified as SQL table (name provided as tableNmae) in Starbucks.db
INPUT:
data_frame: DataFrame
table_name: String
OUTPUT:
None
"""
sql_connect = sqlite3.connect('starbucks.db... |
"""
Subspace Product API
# Introduction The Subspace API is based on REST, has resource-oriented URLs, returns JSON-encoded responses, and returns standard HTTP response codes. The base URL for the API is: `https://api.subspace.com/` # Naming Convention * Version name currently in use is: *v1* * Example... |
import pytest
from app.calculation import add , sub, mul, div, BankAccount, InsufficientFund
## Creating a Fixture for our Bank account class
@pytest.fixture
def zero_bank_account():
return BankAccount()
@pytest.fixture
def bank_account():
return BankAccount(50)
@pytest.mark.parametrize(
"num1, num2, r... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-04-12 18:04
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('pfb_analysis', '0014_auto_20170412_1611'),
('pfb_analysis', '0015_add_neighborhood_geoms'),
... |
"""
Tool to generate prices from all sources
"""
import json
import logging
import multiprocessing
import pathlib
from typing import Any, Dict, List, Tuple, Union
import mtgjson4
from mtgjson4.provider import cardhoader, tcgplayer
LOGGER = logging.getLogger(__name__)
def build_price_data(card: Dict[str, Any]) -> Tu... |
import os
from msg_resolver import RESOLVER
from storage_engine import STORAGE_ENGINE
from cache import CACHE
from .util.config import Config
from .util.logging import logging_config
def setup_config():
config_path = os.getenv('config_path') or "./cfg/server.yml"
config = Config(config_path=config_path)
... |
from abc import ABCMeta, abstractmethod
import numpy as np
from scipy.constants import e, m_p
def gaussian_generator(eps_geo, phase_space_tuple=('x', 'xp'), alpha=0, beta=1):
sigma = np.sqrt(eps_geo)
def generate(bunch):
n_macroparticles = bunch.n_macroparticles
x = np.random.normal(scale=s... |
# -------------------------------------------------------------------------
# Copyright (c) 2020 Supun Nakandala. All Rights Reserved.
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------... |
import unittest
import json
from app import app
class TestAPI(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
self.app.testing = True
def test_cypher_request(self):
url = \
'/api/?url=https://en.wikipedia.org/' + \
'wiki/ROT13&q=To%20get%20to... |
# Copyright (c) 2021-2022 Dai HBG
"""
该代码定义的类用于计算一个信号的平均IC等统计值
日志
2021-08-30
- 定义:计算平均IC,信号自相关系数,IC_IR,IC为正的频率
2021-09-08
- 新增:统计信号排名最高的1个,5个,10个股票的平均收益,以评估信号的纯多头表现
2021-10-09
- 更新:统计平均收益应该也包含超额收益
2021-10-10
- 更新:stats应该存下top前50的所有超额收益率序列,因此可以后期选择需要的排位的股票
2021-10-15
- 更新:对于周频测试,可以使用字段fix_weekday指定计算周几的平均IC
2022-01-10... |
from __future__ import print_function
from __future__ import absolute_import
import datetime
import io
import csv
import json
from sqlalchemy import Column, Integer, String, DateTime, Float, Text, func
from .db import Base
from .psiturk_config import PsiturkConfig
from itertools import groupby
config = PsiturkConfi... |
# 类似于VGG的卷积神经网络
import numpy as np
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras.optimizers import SGD
# Generate dummy data
x_train = np.random.random((100, 100, 100, 3))
y_train = keras.utils.to_categorical(np.random.randint(10, siz... |
# LINK FOR PROBLEM: http://codeforces.com/problemset/problem/742/A
n = int(raw_input())
if n == 0:
print '1'
else:
factor = n % 4
if factor == 1:
print '8'
elif factor == 2:
print '4'
elif factor == 3:
print '2'
else:
print '6'
|
# -*- coding: utf-8 -*-
"""
http://www.astroml.org/sklearn_tutorial/dimensionality_reduction.html
"""
print (__doc__)
import numpy as np
import copy
import cPickle as pickle
import matplotlib
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
from matplotlib import gridspec
import nslkdd.preprocessing as... |
#!/usr/local/bin/python
import socket
import time
import exceptions as e
from config import *
def change_nick(irc)
irc.send("NICK " + cfg['botnick'] + "\r\n")
x = "_"
while("Nickname is already in use" in irc.recv(4096)):
irc.send("NICK " + nick + x + "\r\n")
x += "_"
time.sleep(1... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 14 13:40:02 2021
@author: default
"""
import torch
from torch import nn, einsum
from einops import rearrange
def pair(x):
return (x, x) if not isinstance(x, tuple) else x
def expand_dim(t, dim, k):
t = t.unsqueeze(dim = dim)
expand_shape = [-1... |
from django.contrib.gis.geos import GEOSGeometry
from rest_framework import serializers as rest_serializers
from geotrek.feedback import models as feedback_models
class ReportSerializer(rest_serializers.ModelSerializer):
class Meta:
model = feedback_models.Report
geo_field = 'geom'
id_fie... |
TEST_ORDER_DATA = 100
class WithDoNothing:
def __enter__(self):
pass
def __exit__(self, type, value, traceback):
pass
|
#! /usr/bin/env python
import cv2 as cv
import numpy as np
import math
import rospy
from yaml_parser import Parser
from iros_vision.msg import ObjectCoords
MAIN_WINDOW_NAME = 'camera'
DEBUG = 'debug'
class Color_object:
def __init__(self, config):
self.debug = None
self.config = config
sel... |
from cobald.controller.linear import LinearController
from cobald.controller.relative_supply import RelativeSupplyController
from cobald.interfaces import Pool
from usim import time
class SimulatedLinearController(LinearController):
def __init__(
self, target: Pool, low_utilisation=0.5, high_allocation=0.... |
import pandas as pd
import numpy
import datetime
print 'Stats for events'
df_events = pd.read_csv('data_v2/events.csv', parse_dates=['start', 'end', 'event_created'], date_parser=pd.core.tools.datetimes.to_datetime)
print 'Num events: %s' % len(df_events.index)
num_test = numpy.asscalar(df_events[df_event... |
import cv2
cap = cv2.VideoCapture(0) # pode ser -1
print(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
print(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
cap.set(3, 3000)
cap.set(4, 3000)
print(cap.get(3))
print(cap.get(4))
while (cap.isOpened()):
ret, frame = cap.read()
if ret == True:
gray = cv2.cvtColor(frame, cv2... |
#!/usr/bin/env python
# http://www.pythonchallenge.com/pc/return/5808.html
import Image,ImageEnhance, urllib2, StringIO
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm='inflate', uri='http://www.pythonchallenge.com/pc/return/', user='huge', passwd='file')
opener = urllib2.build_opener(a... |
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
import numpy as np
import tensorflow as tf
import argparse
import os
def ... |
import sublime, sublime_plugin, subprocess, threading, time
class Bdo(sublime_plugin.TextCommand):
def run(self, cmd):
sublime.active_window().show_input_panel("bdo ", "update", self.execute, None, None)
def execute(self, cmd):
output = subprocess.Popen(
"echo " + cmd + " | nc -w 10... |
from typing import Tuple
from typing import List
from typing import Union
from .sprite import Sprite, Texture
from arcade.text import Text
from arcade.color import BLACK
import PIL
from PIL import ImageFilter
RGB = Union[Tuple[int, int, int], List[int]]
RGBA = Union[Tuple[int, int, int, int], List[int]]
Color = Union[... |
#
# PySNMP MIB module AVICI-FABRIC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AVICI-FABRIC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:16:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
"""
Abstract Object Encoder/Decoder
Object schema is specified in JSON Abstract Data Notation (JADN) format.
Codec currently supports three JSON concrete message formats (verbose,
concise, and minified) but can be extended to support XML or binary formats.
Copyright 2016, 2021 David Kemp
Licensed under the Apache Li... |
import logging
from datetime import datetime, timedelta
from typing import Optional, Sequence, Tuple
from snuba import util
from snuba.clickhouse.native import ClickhousePool
logger = logging.getLogger("snuba.cleanup")
def run_cleanup(
clickhouse: ClickhousePool, database: str, table: str, dry_run: bool = True... |
# #####################################################################################################################
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# ... |
import os
import uuid
from cloudinitd.cb_iaas import IaaSTestInstance
from cloudinitd.exceptions import APIUsageException
from cloudinitd.pollables import InstanceHostnamePollable
from cloudinitd.user_api import CloudInitD
import unittest
class ServiceUnitTests(unittest.TestCase):
def test_baddir_name(self):
... |
from .config import Config, ConfigDict, DictAction
from .path import check_file_exist, mkdir_or_exist
from .logging import get_logger, print_log
from .misc import is_seq_of, is_str, is_list_of
__all__ = ['Config', 'ConfigDict', 'DictAction', 'check_file_exist',
'mkdir_or_exist', 'get_logger', 'print_log', '... |
import abc
import logging
import traceback
import servicemanager
import win32event, win32service, win32api
from win32serviceutil import ServiceFramework
log = logging.getLogger(__name__)
class WindowsService(object, ServiceFramework):
"""
Base windows service class that provides all the nice things that a p... |
# Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... |
from .basedata import *
"""
作用:布局
"""
class MainFrameGUI(wx.Frame, BaseData):
def __init__(self, parent = None):
BaseData.__init__(self)
wx.Frame.__init__(self, parent, -1, title = CON_JDJANGO_TITLE, pos = wx.DefaultPosition, size = wx.Size(1000, 580), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TR... |
import collections.abc as abc
import typing as typ
import aiohttp
from .chunked_stream import ChunkedBytesStream, JsonStream
from .contextlib import AsyncContextManager
StreamType = typ.TypeVar('StreamType', ChunkedBytesStream, JsonStream)
class StreamableResponse(typ.Generic[StreamType], abc.Awaitable,
... |
'''
Classifier : Logistic Regression
DataSet : TitanicDataset.csv
Features : Passenger id, Gender, Age, Fare, Class etc
Labels : -
Author : Prasad Dangare
Function Name : Titanic_Logistic
'''
# ===================
# Imports
# ===================
import numpy as np ... |
from . import forms, models
from django.shortcuts import render
from django.contrib.auth import decorators
from django.http import HttpResponse
from pyexcelerate import Workbook, Style, Font
import requests
# cache key format <model name in uppercase>-<start-date>-<end-date>
def payments_list(request):
return ... |
"""
How to use Asyncio with InfluxDB client.
"""
import asyncio
from datetime import datetime
from influxdb_client import Point
from influxdb_client.client.influxdb_client_async import InfluxDBClientAsync
async def main():
async with InfluxDBClientAsync(url="http://localhost:8086", token="my-token", org="my-org"... |
class JobMetricConsumer(object):
"""
Class to consume the 'stage_log_middleware' channel.
Passes the metric and value to a Redis list based on job_id
Arguments:
redis {redis.Redis} -- A Redis connection object
"""
def __init__(self, redis):
self._redis = redis
def call(s... |
from rest_framework import status
from rest_framework.response import Response
from django_pds.core.pds.generic import data_read, basic_data_read, data_insert, data_update, data_delete
from django_pds.core.rest.decorators import required
from django_pds.core.rest.response import error_response, success_response
from d... |
# import necessary libraries
import torch
import numpy as np
import ujson as json
import torch.nn as nn
import argparse
from pathlib import Path
from tokenizers import BertWordPieceTokenizer
from transformers import BertForSequenceClassification, BertConfig
from tqdm import tqdm
import numpy as np
import arguments.rank... |
import os.path
from collections import defaultdict
from graph import djikstra
def _parse_orbits(lines):
orbits = {}
for line in lines:
a, b = line.strip().split(')')
if b in orbits:
raise ValueError(f'object {b} orbits around more than one object')
orbits[b] = a
return... |
import unittest
from .util import TrelloElementMock
from trello_collection import TrelloCollection
class TrelloCollectionTests(unittest.TestCase):
def setUp(self):
self.collection = TrelloElementMock.collection()
self.trello_collection = TrelloCollection(self.collection)
def test_it_filters_t... |
"""The ASGI config for the project. """
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'conf.docker')
application = get_asgi_application()
|
"""Vendor-specific extensions of the `dicomweb_client` package."""
|
from models.user import AppUserModel
from resources.mixin import ActivateMixin, ListMixin, ResourceMixin
class User(ResourceMixin):
model = AppUserModel
parsed_model = model.parse_model()
class ActivateUser(ActivateMixin):
model = AppUserModel
class Users(ListMixin):
model = AppUserModel
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.CheckResultList import CheckResultList
class KoubeiQualityTestShieldResultSyncModel(object):
def __init__(self):
self._batch_no = None
self._check_result_list... |
#!/usr/bin/env python2
import cv2 as cv
import numpy as np
import glob, os
from sys import argv
kx = 0.1
kx2 = 1 - kx
def boundingRect_sel (rect, img_shape):
x, y, sw, sh = rect
h, w = img_shape
if ((kx * w < x) and (kx * h < y) and
(kx2 * w > (x + sw)) and ((y + sh) < kx2 * h)):
return Tr... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 5 20:51:41 2022
@author: ywjin0707
"""
sc.pp.normalize_total(mydata, target_sum = 1e4)
sc.pp.log1p(mydata)
sc.pp.highly_variable_genes(mydata)
mydata = mydata[:, mydata.var.highly_variable]
def simulate_bulk(datasets: list, n: int = 10000, c: int = 500, sf: int = 100):... |
import inspect
import io
import friendly_traceback.core
import rich.console
import rich.traceback
import markdown
from contextlib import redirect_stderr, redirect_stdout
from io import StringIO
import os
import sys
try:
import hebrew_python
except ImportError:
hebrew_python = None
console = rich.console.Conso... |
# O mobile na sala da Maria e composto de tres hastes exatamente como na figura abaixo.
# Para que ele esteja completamente equilibrado, com todas as hastes na horizontal, os pesos das
# quatro bolas A, B, C e D tem que satisfazer todas as seguintes tres condicoes:
# A = B + C + D
# B + C = D
# B = C
Pa, Pb, P... |
# pass
def bubble_sort(collection):
length = len(collection)
for i in range (length - 1):
swapped = False
for j in range(length - i - 1):
if (collection[j] > collection[j + 1]):
collection[j], collection[j + 1] = collection[j + 1], collection[j]
swappe... |
class cuenta_bancaria:
def __init__(self, titular,fondos):
if isinstance(titular,str):
self.titular=titular
else:
self.titular="nombre"
if isinstance(fondos,float):
self.fondos=fondos
else:
self.fondos=0
def imprimir(self):
... |
import json
import os.path as path
import sys
import getopt
class Param(object):
"""class to set up the default parameters value of the model
the default parameters are stored in a json file along with
their definition
launch the code with the -h to get the help on all the model
par... |
from .. import SNG
from .. xls import get_xlwt
from .. xls import main
from unittest import mock
import builtins
import pytest
import xlrd
import xlwt
def test_xls__get_xlwt__1():
"""It returns the `xlwt` module."""
assert get_xlwt() == xlwt
def test_xls__get_xlwt__2(capfd):
"""It exits with an error me... |
import os, sys, inspect
THISDIR = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
# Add ../lib to the import path
sys.path.insert(0, os.path.dirname(THISDIR) + "/lib")
sys.path.insert(0, os.path.dirname(THISDIR) + "/RecipeBuilder")
# Generate coverage data with py.test test\test_recipeBuild... |
BLACK = "\033[0m"
RED = "\033[1;31m"
GREEN = "\033[1;32m"
YELLOW = "\033[1;33m"
BLUE = "\033[1;34m"
PURPLE = "\033[1;35m"
AQUA = "\033[1;36m"
red=lambda x:RED+str(x)+BLACK
green=lambda x:GREEN+str(x)+BLACK
yellow=lambda x:YELLOW+str(x)+BLACK
blue=lambda x:BLUE+str(x)+BLACK
purple=lambda x:PURPLE+str(x)+BLACK
aqua=l... |
#!/usr/bin/env python
#encoding:utf-8
#-------------------------------------------------------------------------------
# Name: Syndication feed class for subsribtion
# Purpose:
#
# Author: Mike
#
# Created: 29/01/2009
# Copyright: (c) CNPROG.COM 2009
# Licence: GPL V2
#----------------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.