content stringlengths 5 1.05M |
|---|
# Autogenerated file. Do not edit.
from jacdac.bus import Bus, SensorClient
from .constants import *
from typing import Optional
class SoundLevelClient(SensorClient):
"""
A sound level detector sensor, gives a relative indication of the sound level.
Implements a client for the `Sound level <https://micros... |
from .basic import Node, LinkedList
|
from pathlib import Path
class PathHandler:
BASE_DIR = Path(__file__).parents[1]
RESOURCES = BASE_DIR / 'resources'
SRC = BASE_DIR / 'src'
|
# -*- coding:utf-8 -*-
"""封装Response对象"""
import json
import re
from lxml import etree
class Response(object):
"""框架内置Response对象"""
def __init__(self, url, status_code, headers, body): # , request
self.url = url
self.status_code = status_code
self.headers = headers
self.body = ... |
import os
import sys
import argparse
import pkg_resources
import importlib
import warnings
from scipy.stats import norm
from scipy.stats import multivariate_normal
from tensorflow.python.util import deprecation
deprecation._PRINT_DEPRECATION_WARNINGS = False
KEY_ORDER = ['observation', 'achieved_goal', 'desired_goal']
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import json
import os
import re
import shutil
from enum import Enum
from pathlib import Path
from mlflow.tracking import MlflowClient
from tensorflow.keras.models import load_model
DATA_PATH = Path(os.envir... |
#!/usr/bin/env python3
######################################################################
## Author: Carl Schaefer, Smithsonian Institution Archives
######################################################################
import uuid
import sys
import os
import hashlib
import re
import db_access as dba
import dm_de... |
import copy
import logging
import threading
from amplitude.constants import PluginType
from amplitude.exception import InvalidEventError
from amplitude.constants import LOGGER_NAME
class Timeline:
def __init__(self, configuration=None):
self.locks = {
PluginType.BEFORE: threading.Lock(),
... |
import os, sys, argparse, yaml, datetime, re, getpass, pexpect
from xxh_xxh import __version__
from shutil import which
from sys import exit
from argparse import RawTextHelpFormatter
from urllib.parse import urlparse
from base64 import b64encode
from signal import signal, SIGINT
from .shell import *
def sigint_handler... |
'''
Created by auto_sdk on 2021.04.01
'''
from dingtalk.api.base import RestApi
class OapiImChatScencegroupFileDownloadurlGetRequest(RestApi):
def __init__(self,url=None):
RestApi.__init__(self,url)
self.download_code = None
def getHttpMethod(self):
return 'POST'
def getapiname(self):
return 'dingtalk.oapi... |
# http://www.pythonchallenge.com/pc/def/0.html
def main():
return 2**38
if __name__ == "__main__":
print(main())
# http://www.pythonchallenge.com/pc/def/274877906944.html
|
# Copyright 2020 Alibaba Group Holding Limited. 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 ... |
# Generated by Django 3.2.8 on 2021-11-04 12:46
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('indexer', '0012_auto_20211021_2008'),
]
operations = [
migrations.AddField(
model_name='block',
name='transaction_co... |
"""Create messages from data that conform to device's specified protocol."""
# Copyright 2020 WolkAbout Technology s.r.o.
#
# 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
#
# htt... |
"""Test features of lightkurve that interact with the data archive at MAST.
Note: if you have the `pytest-remotedata` package installed, then tests flagged
with the `@pytest.mark.remote_data` decorator below will only run if the
`--remote-data` argument is passed to py.test. This allows tests to pass
if no internet c... |
#!/usr/bin/python3
from brownie import Token, accounts, config
def main():
acct = accounts.add(
config["wallets"]["from_key"],
)
return Token.deploy("Test Token", "TST", 18, 1e21, {"from": acct})
|
from solrcloudpy import *
from solrcloudpy.collection import schema
conn=SolrConnection(['dats.swordfishsecurity.ru:8983'])
print(conn.list())
test_data=["""
{
"id" : 587605975,
"content_t" : "I said this early, and I don’t know why it got lost.\r\nRather than adding more arguments, let’s just modify the job after... |
#!/usr/bin/env python3
# added the relationship graph to a arangoDB DB
from sys import exit
import base64
import requests
class ArangoConfig():
n_attr = 0
base = None
db_name = None
password = None
username = None
def __init__(self, **kawrs):
for k,v in kawrs.items():
self... |
"""Tic Tac Toe in Python."""
def player_marker(player1, player2):
"""Take both players input for the markers."""
# check if player1 is 'X' or 'O'
while player1 != "X" and player1 != "O":
try:
player1 = input("Please pick a marker ('X' or 'O'): ").upper()
except ValueError:
... |
"""design tools"""
# -*- coding:utf-8 -*-
from .singleton import SingletonDecorator, SingletonInstance
|
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
{
"targets": [
{
"target_name": "jack_connector",
"sources": [ "src/jack_connector.cc" ],
"libraries": [ "-ljack" ]
}
]
}
|
# 559. Maximum Depth of N-ary Tree
# https://leetcode.com/problems/maximum-depth-of-n-ary-tree
import unittest
# Definition for a Node.
class Node(object):
def __init__(self, val, children=[]):
self.val = val
self.children = children
class Solution(object):
def maxDepth(self, root):
... |
# coding=utf-8
#给你两个数a和b,计算出它们分别是哪两个数的最大公约数和最小公倍数。
#输出这两个数,小的在前,大的在后,以空格隔开。若有多组解,输出它们之和最小的那组。
import math
a,b = 12,36
if a > b:
a, b = b, a
p = b / a
for i in range(1, int(math.sqrt(p)) + 1):
if p % i == 0:
f1, f2 = i, p / i
print f1 * a, f2 * a |
n = int(input())
cobaias = {"C": 0, "R": 0, "S": 0}
for i in range(n):
valores = input().split()
a = int(valores[0])
b = valores[1]
cobaias[b] += a
total = sum(cobaias.values())
coelhos = cobaias["C"]
ratos = cobaias["R"]
sapos = cobaias["S"]
print("Total: {} cobaias".format(total))
print("Total de co... |
'''
Copyright 2012 Konrad Jopek
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 w... |
from pydantic import BaseModel
import time
class ConsoleLog(BaseModel):
command: str = ""
stdout: str = ""
time: float = time.time() |
import malada
"""
This example shows how MALADA can be used to run a simple pipeline for
creating atomic position / LDOS data for machine learning workflows.
The example system is a very limited system of Be atoms.
The example sets parameter in such a way that calculations will be performed
fast - not necessarily in... |
##### libraries #####
import pandas as pd
import numpy as np
from datetime import datetime
def store_relational_JH_data():
"""
Transformes the COVID data in a relational data set
"""
# Load raw data
data_path='https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_d... |
from django import forms
from django.forms import ModelMultipleChoiceField
from django.forms.widgets import SelectMultiple
from .models import Task, Hashtag
from django.core.exceptions import ValidationError
class TaskForm(forms.ModelForm):
_user : int
hashtags : ModelMultipleChoiceField
def __init__(... |
"""
1. Clarification
2. Possible solutions
- Dynamic programming v1
- Dynamic programming v2
3. Coding
4. Tests
"""
# T=O(n^2), S=O(1)
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
if numRows <= 0: return []
ans = [[0] * (i + 1) for i in range(numRows)]
for i... |
# Operators
print('Module', 10%3)
print('Exponential', 5**3)
print('Floor division', 9//2)
# Data types
print(type(5))
print(type("Luis"))
print(type(5.2))
# Condition
num1 = 5
num2 = 7
if num1 > num2:
print(num1, 'is bigger')
else:
print(num2, 'is bigger')
|
from utils.db import db
from sqlalchemy import ForeignKey
class Product(db.Model):
# __tablename__ = "product"
# __table_args__ = {"schema": "public"}
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(70))
product_img = db.Column(db.String(70))
price_p... |
import logging
SECRET_KEY = 'secret-for-dev'
LOGGING_LEVEL = logging.INFO |
from common import Tool
from entity.Server import Server, WindLevel, Mode
class AirCondition:
def __init__(self, default_temp: int, default_mode: int, default_highest_temp: int,
default_lowest_temp: int, default_wind_level: int, user=None):
"""
空调(房间)对象
:param use... |
# -*- coding: utf-8
import pandas as pd
import numpy as np
import csv
import plotly as py
import plotly.graph_objs as go
from datetime import datetime
py.plotly.sign_in('mtrpires', 'cd7lus33e2')
df = pd.read_csv('data/eventos_femininos.csv')
trace1 = go.Scatter(
x = df['Ano'],
y = df['Femininos'],
mode =... |
# Generated by Django 3.1.7 on 2021-03-25 09:37
from django.db import migrations, models
import django_countries.fields
import phonenumber_field.modelfields
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
... |
# Formatting configuration for locale ca
languages={'gu': 'gujarati', 'gd': u'escoc\xe8s', 'ga': u'irland\xe8s', 'gn': u'guaran\xed', 'gl': 'gallec', 'la': u'llat\xed', 'ln': 'lingala', 'lo': u'laosi\xe0', 'tt': u't\xe0tar', 'tr': 'turc', 'ts': 'tsonga', 'lv': u'let\xf3', 'to': 'tonga', 'lt': u'litu\xe0', 'tk': 'turcm... |
class _OnfleetError(Exception):
'''
Base exception class for all errors raised by the Onfleet API.
'''
def __init__(self, message, status=None, request=None, cause=None):
self.message = message
self.status = status
self.request = request
self.cause = cause
class Validat... |
from office365.graph.directory.user import User
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.runtime.client_query import DeleteEntityQuery, UpdateEntityQuery
from office365.runtime.client_runtime_context import ClientRuntimeContext
from office365.runtime.http.http_metho... |
"""
方法1: 位运算 (如果a^b == c, 则 a^c == b)
时间复杂度:O(n)
空间复杂度:O(n)
示例 1:
输入:encoded = [1,2,3], first = 1
输出:[1,0,2,1]
解释:若 arr = [1,0,2,1] ,那么 first = 1 且 encoded = [1 XOR 0, 0 XOR 2, 2 XOR 1] = [1,2,3]
示例 2:
输入:encoded = [6,2,7,3], first = 4
输出:[4,2,0,7,4]
"""
import sys
from typing import List
class Solution:
@st... |
# Letter variable names in this file match common mathematical notation.
# Local variables maintain more concise mathematical equations.
# pylint: disable=invalid-name,too-many-locals
import enum
import functools
import math
from spatial.vector3 import Vector3
# All of these functions convert quaternion representati... |
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn import datasets
count_df = pd.DataFrame(
np.array([
[1,0,1,0,0,0],
[0,1,0,1,0,0],
[1... |
import uuid
from .hub.base_hub_connection import BaseHubConnection
from .hub.auth_hub_connection import AuthHubConnection
from .transport.websockets.reconnection import \
IntervalReconnectionHandler, RawReconnectionHandler, ReconnectionType
from .helpers import Helpers
from .messages.invocation_message import Invoc... |
from random import randint
ns = (randint(0, 10), randint(0, 10), randint(0, 10), randint(0, 10), randint(0, 10))
print(f'Os valores sorteados foram : {ns}')
print(f'Maior: {max(ns)}\nMenor: {min(ns)}')
|
from django.urls import reverse
from .dojo_test_case import DojoTestCase
from dojo.models import JIRA_Instance, Product, JIRA_Project
from django.utils.http import urlencode
from unittest.mock import patch
import requests
# from unittest import skip
import logging
logger = logging.getLogger(__name__)
class JIRAConfi... |
import serial, time
from struct import pack
from mesh.generic.nodeParams import NodeParams
from mesh.generic.serialComm import SerialComm
from mesh.generic.radio import Radio
from mesh.generic.nodeCmdProcessor import NodeCmdProcessor
from mesh.generic.slipMsg import SLIPMsg
from test_SLIPMsg import truthSLIPMsg, testMs... |
# bibframe
from versa import I
# use BFZ namespace to scope MARC tags that don't match transformation recipes
BFZ = I('http://bibfra.me/vocab/marcext/')
BFLC = I('http://bibframe.org/vocab/')
#A way to register services to specialize bibframe.py processing
#Maps URL to callable
g_services = {}
BF_INIT_TASK = 'http:... |
# -*- coding: utf-8 -*-
###
# (C) Copyright (2012-2017) Hewlett Packard Enterprise Development LP
#
# 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 limi... |
import os
import argparse
from dataclasses import dataclass
import typing as tp
from numbers import Number
import locale
import numpy as np
import numpy.typing as npt
try:
import click
except ImportError:
click = None
from .math import *
__all__ = (
'TableParameters', 'TableResult', 'well_height_table',... |
import pandas as pd
__all__ = [
"FEATURE_NAMES",
"fires",
]
FEATURE_NAMES = [
"temp",
"RH",
"wind",
"rain",
]
fires = pd.read_csv("../fires.csv")
|
import numpy as np
from keras.applications.imagenet_utils import preprocess_input, decode_predictions
from keras.preprocessing import image
from seldon_core.proto import prediction_pb2
import tensorflow as tf
import logging
logger = logging.getLogger(__name__)
class ImageNetTransformer(object):
def __init__(self,... |
from unittest.mock import MagicMock, patch
import pytest
from belvo import resources
from belvo.enums import AccessMode
def test_links_create_sends_token_if_given(api_session):
link = resources.Links(api_session)
link.session.post = MagicMock()
link.create("fake-bank", "fake-user", "fake-password", tok... |
""" Summary
zip: 接受一系列可迭代对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。
"""
class Solution(object):
"""
Problem:
https://leetcode.com/problems/pascals-triangle-ii/
Example:
given k = 3,
Return [1,3,3,1].
"""
def __init__(self):
self.cache = {}
def ge... |
"""
PyAudio exmple: Record a few seconds of audio and save to a WAVE
file.
"""
import pyaudio
import wave
import sys
from dejavu import Dejavu
CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 1L
RATE = 48000
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "/sounds/output.wav"
if sys.platform == 'darwin':
CHANNELS = 1
... |
# below 802.15.4 wireless protocol code based on Digi International
# example code for network communication between nodes for end device
import xbee, time
# Utility functions to perform XBee3 802.15.4 operations
from machine import Pin
# pin function needed for sensor
def format_eui64(addr):
return ':'.join('%... |
# Date: 10/23/2017
# Author: Ethical-H4CK3R
# Description: Returns True if the file compiled & moved
import os
class FileState(object):
''' Returns True if the file compiled & moved OR if the file is not compiled '''
@staticmethod
def isCompiled(exe):
name = exe.split(os.path.sep)[-1]
return False... |
import argparse
from glob import glob
import pandas as pd
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("train_data_dir")
parser.add_argument("concatenated_csv")
args = parser.parse_args()
paths = glob(f'{args.train_data_dir.rstrip("/")}/*')
train_dfs = []
... |
# encoding: utf-8
"""
@author: fonttian
@contact: fonttian@gmail.com
@license: by-nc-sa
@file: RequestsTools.py
@time: 2020/12/2 下午5:34
"""
import requests
from Tools.Sqlite3Manager import metadata_select_url
def request_to_java(bigType, smallType, data, sensorId, strategy,
url="http://192.168.1.... |
# -*- coding: utf-8 -*-
# Copyright 2013 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from __future__ import with_statement
import __builtin__
import unittest
from splinter.exceptions import DriverNotFoundError
from fak... |
"""
Comb sort is a relatively simple sorting algorithm originally designed by Wlodzimierz Dobosiewicz in 1980.
Later it was rediscovered by Stephen Lacey and Richard Box in 1991. Comb sort improves on bubble sort.
This is pure python implementation of comb sort algorithm
For doctests run following command:
python -m d... |
#!/usr/bin/env python
# for tgi cluster:
#/gapp/x64linux/opt/pythonbrew/venvs/Python-2.7.6/gemini/bin/python
# for uva cluster:
import pysam
import sys
import argparse
from argparse import RawTextHelpFormatter
import string
from string import *
__author__ = "Ira Hall (ihall@genome.wustl.edu) and Colby Chiang (cc2qe@... |
"""
Empirical evaluation of Question 2 -- `Flips until two heads`
(solved analytically in the pdf file)
"""
from common import bernoulli
ZERO, ONE, TWO = 0, 1, 2
BACKWARD, FORWARD = 0, 1
def experiment(p: float) -> int:
state = ZERO
steps = 0
while state != TWO:
steps += 1
if state == ZER... |
import lexer
from iterutils import groupby
#Here we set up some keywords. Honestly, this is only written like this because constantly wrapping things in quotes is the road to madness.
RESERVED = 'RESERVED'
INT = 'INT'
KEY = 'KEY'
MODKEY = 'MODKEY'
STR = 'STR'
NEWLINE = 'NEWLINE'
TIME = 'TIME'
FLOAT = 'FLOAT... |
import cv2
import tensorflow.compat.v1 as tf
import numpy as np
import glob
import os
import time
import argparse
import configparser
from auto_pose.ae import factory, utils
tf.disable_eager_execution()
parser = argparse.ArgumentParser()
parser.add_argument("experiment_name")
parser.add_argument("-f", "--file_str", ... |
import os
import sys
import time
import pytest_check as check
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(base_dir)
import datasets
def test_tencent_ml_classes():
classes, synsets, hierarchy, subsets = datasets.tencent_ml.TencentML7M.get_classes(lang='ko')
assert le... |
"""Generic open method for wt5 files."""
# --- import -------------------------------------------------------------------------------------
import os
import tempfile
import weakref
import h5py
import numpy as np
from . import collection as wt_collection
from . import data as wt_data
from . import _group as wt_gro... |
import os, sys, pdb
import random
import math
import torch
import numpy as np
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(ar... |
"""
This component evaluates the performance of a currently deployed model, and
the evaluation is based on the result of batch prediction on Vertex AI from the previous component.
At the end, this component will output true or false to indicate if retraining is needed.
Reference: https://bit.ly/vertex-batch
"""
from ... |
import matplotlib.pyplot as plt
import numpy as np
from magcoilcalc.core import Task, CurrentLoop, Mesh
from matplotlib.pyplot import Rectangle
from magcoilcalc.calculations import find_gradient
from matplotlib.colors import LogNorm, Normalize
def draw_cell_boundary(ax, width, height, x_offset=0, y_offset=0):
r =... |
# ===========================================================================
# train.py ----------------------------------------------------------------
# ===========================================================================
# import ------------------------------------------------------------------
# -----... |
from __future__ import print_function
import matplotlib
matplotlib.use('Agg')
from orphics import maps,io,cosmology,mpi
from pixell import enmap
import numpy as np
import os,sys,shutil
from datetime import datetime
from actsims import noise as actnoise
from actsims.util import seed_tracker
from soapack import interface... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import numpy.linalg as la
### CLASS GEOMETRY 2D###
class Geometry2d():
def __init__(self, geom_file):
self.tol = 1e-15
self.parse(geom_file)
def parse(self, geom_file):
# open geometry.txt ... |
import numpy as np
from scipy.signal.windows import tukey
import gwmemory
from bilby.core.series import CoupledTimeAndFrequencySeries
from .utils import nfft
def td_mwm(times, mass_ratio, total_mass, luminosity_distance, inc, phase, **kwargs):
times -= times[-1]/2
mwm = gwmemory.waveforms.MWM(q=mass_ratio, ... |
#Classes Challenge 38: Pykemon Simulation App
import random
#Parent class
class Pykemon():
"""A model of a generic Pykemon character."""
def __init__(self, name, element, health, speed):
"""Initialize attributes."""
self.name = name.title()
self.element = element
#Current heal... |
"""
This module connects to, drops and then creates new tables in the sparkifydb as specified by the
queries imported from 'sql_queries.py'
"""
import configparser
import psycopg2
from sql_queries import create_table_queries, drop_table_queries
def drop_tables(cur, conn) -> None:
"""
Drop tables in the spar... |
import cv2
import utils
import numpy as np
from numba import njit
from functools import partial
# TODO: Not working exactly as cpp version
@njit(cache=True)
def get_constrained_zero_crossings(
img_log: np.ndarray, grad_mag_thresh: float, zero_cross_thresh: float
):
output = np.zeros_like(img_log, dtype='uint... |
from __future__ import division, print_function, absolute_import
import numpy as np
from ..actmodels import virialgamma
from .fitmulticomponent import fobj_vle, fobj_lle, fobj_vlleb
from scipy.optimize import minimize, minimize_scalar
def fobj_wilson(inc, mix, datavle, virialmodel='Tsonopoulos',
weigh... |
# This is Python!
print "Hello World"
|
import numpy as np
from mlprogram.metrics import Accuracy
class TestAccuracy(object):
def test_simple_case(self):
acc = Accuracy()
assert np.allclose(
1.0,
acc(expected="str", actual="str"))
assert np.allclose(
0.0,
acc(expected="int", actua... |
# Ignoring some linting rules in tests
# pylint: disable=redefined-outer-name
# pylint: disable=missing-docstring
import pytest
import numpy as np
from bingo.chromosomes.multiple_values import MultipleValueChromosome, \
MultipleValueChromosomeGenerator, SinglePointCrossover, SinglePointMutation
def mutation_onem... |
import time
class timing(object):
def __init__(self, func):
self.f = func
def __call__(self, *args, **kwargs):
start_time = time.time()
if len(args) == 0 and len(kwargs) == 0:
print("none")
self.f()
elif len(args) != 0 and len(kwargs) ... |
from supergsl.core.function import SuperGSLFunction, SuperGSLFunctionDeclaration
from supergsl.core.plugin import SuperGSLPlugin
from supergsl.core.function import SuperGSLFunction
from supergsl.core.ast import Assembly
from supergsl.core.types.builtin import NucleotideSequence
class ChopChopFunction(SuperGSLFunctio... |
from maltego_trx.maltego import MaltegoEntity, MaltegoTransform, Phrase
from maltego_trx.overlays import OverlayPosition, OverlayType
from graphsense.configuration import Configuration
import json
import re as regex
from graphsense.api import addresses_api, entities_api
from graphsense.api_client import ApiClient, ... |
import torch
from models.resnet_simclr import ResNetSimCLR
# from torch.utils.tensorboard import SummaryWriter
import torch.nn.functional as F
from loss.nt_xent import NTXentLoss
import os
import shutil
import sys
import time
import torch.nn as nn
from tqdm import tqdm
server_path=''
result = os.popen('echo "$USER"') ... |
import unittest
import zserio
from testutils import getZserioApi
def _convertRgbToCmyk(rgb):
# see https://www.rapidtables.com/convert/color/rgb-to-cmyk.html
rr = rgb[0] / 255. * 100
gg = rgb[1] / 255. * 100
bb = rgb[2] / 255. * 100
k = 100. - max(rr, gg, bb)
c = round((100. - rr - k) / (100... |
import os
import configparser
from wandb import util
from wandb.old import core
from wandb import env
class Settings:
"""Global W&B settings stored under $WANDB_CONFIG_DIR/settings."""
DEFAULT_SECTION = "default"
_UNSET = object()
def __init__(self, load_settings=True, root_dir=None):
sel... |
from models import User
from bcrypt import hashpw, gensalt
from dataclasses import dataclass
@dataclass
class userOutput:
id: int = None,
username: str = None,
email: str = None,
first_name: str = None,
last_name: str = None,
department: str = None,
default_pathway_id: int = None,
is_a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
: Project - RGANet
: Demo to test images
: Author - Xi Mo
: Institute - University of Kansas
: Date - 9/23/2021
"""
import time
import argparse
import numpy as np
import torch
import torch.nn as nn
from torchvision import transforms
from torchvision.utils import save... |
# pylint: disable=missing-docstring, line-too-long, protected-access, E1101, C0202, E0602, W0109
import unittest
from runner import Runner
class TestE2E(unittest.TestCase):
@classmethod
def setUpClass(self):
self.snippet = """
provider "aws" {
region = "eu-west-2"
... |
class VariableTable:
def __init__(self, parent=None):
self.parent = parent
self._variables = {}
def find_variable(self, id):
if self.parent is None:
return self._variables.get(id)
return self._variables.get(id, self.parent.find_variable(id))
def add_variable(self, id, var):
if id not i... |
# coding: utf-8
import json
import zmq
from bson import json_util
from parkkeeper.datatools.task import process_task_data
from parkkeeper.base import StoppableMixin
from parkkeeper.event import get_sub_socket, async_recv_event
from parkworker.const import TASK_EVENT
class TaskResultCollector(StoppableMixin):
def... |
from django.contrib import admin
from .models import SpeciesGarden
# Register your models here.
class SpeciesGardenAdmin(admin.ModelAdmin):
list_display = ("id", "species", "garden_name", "order", "garden_id")
search_fields = ("species", "garden_name", "garden_id")
list_per_page = 25
admin.site.registe... |
# part of the demo. Run with demoCH and multiple instances of demoCarCM
import CM
import time, socketserver, os
from common import consts,utils,cryptostuff,packers
from simplehttp import simpleServer
from threading import Thread
# The role of the OEM in the demo is to prepare a message and send it to the CH before ser... |
import subprocess
import re
hotkey = "<f6>"
if re.match('.*Chromium-browser', window.get_active_class()):
# click is done where the cursor is
subprocess.run(["xdotool","keydown","alt","click","1","keyup","alt"])
else:
keyboard.send_keys(hotkey)
|
import shutil
import sys
from pathlib import Path
import pytest
from atakama.packager import Packager, main
import atakama.packager
EXAMPLE_PATH = Path(__file__).parent.parent / "example"
EXAMPLE_RUNCMD_PATH = EXAMPLE_PATH / "runcmd"
@pytest.fixture(scope="module")
def self_signed_cert(tmp_path_factory):
tmp_p... |
from pntools import partialorder, partialorder_renderer
from pntools.algorithm import lpo_skeleton, lpo_transitive
lpos = partialorder.parse_lpo_file("abcabc.lpo")
lpo = lpos[0]
lpo_skeleton.skeleton(lpo)
lpo_transitive.transitive_closure(lpo)
image = partialorder_renderer.draw_lpo(lpo, skeleton=True, transitive=Tru... |
# -*- coding: utf-8 -*-
#
# Authors: Tomi Jylhä-Ollila, Finland 2014-2017
# Toni Ruottu, Finland 2014
#
# This file is part of Kunquat.
#
# CC0 1.0 Universal, http://creativecommons.org/publicdomain/zero/1.0/
#
# To the extent possible under law, Kunquat Affirmers have waived all
# copyright and related or ne... |
# -*- coding: utf-8 -*-
from __future__ import print_function
# stdlib
import unittest
# pyramid
from webob.cookies import SignedSerializer
# local
from ..util import _NullSerializer
from ..legacy import LegacyCookieSerializer
from ..legacy import GracefulCookieSerializer
# ========================================... |
#!/usr/bin/env python
""" Bluegiga BGAPI/BGLib demo: health thermometer collector
Changelog:
2014-10-15 - Add logfile output mode
2014-07-05 - Fix indication subscription to use 2-byte value
2013-06-07 - Fix "address_type" to support Random (e.g. iPhone as peripheral)
2013-05-15 - Added comments, scri... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.