content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import click
import sys
from obs.libs import auth
from obs.cli.storage import bucket
from obs.cli.storage import gmt
from obs.libs import utils
from obs.libs import config
def warn_inexsit_config():
msg = (
f"Configuration file not available.\n"
f"Consider running 'obs --configure' to create one"... | python |
from .message import Message
from .notify import QueueNotify
from http.server import HTTPServer,BaseHTTPRequestHandler
from threading import Thread
from queue import Queue
from time import sleep
class cServerHandler(BaseHTTPRequestHandler, QueueNotify):
def rename_page(self):
res = """
<script... | python |
# We will need the following module to generate randomized lost packets
import random
from socket import *
# Create a UDP socket
# Notice the use of SOCK_DGRAM for UDP packets
serverSocket = socket(AF_INET, SOCK_DGRAM)
# Assign IP address and port number to socket
serverSocket.bind(('', 12000))
while True:
... | python |
""""""
# -*- coding: utf-8 -*-
# date: 2021
# author: AllChooseC
import os
import numpy as np
from tensorboardX import SummaryWriter
import torch
from tqdm import tqdm
from utils import EarlyStopping, class_penalty
class_distribution = [59.68, 8.68, 28.55, 3.08]
# 2017
class_distribution = [59.22, 8.65, 28.80, 3.3... | python |
from detoxify import Detoxify
detox_model = None
def generate_model():
global detox_model
detox_model = Detoxify('original')
def predict(inputmessage):
if detox_model is None:
generate_model()
results = detox_model.predict(inputmessage)
return results
if __name__ == '__main__':
... | python |
from ._base import Plugin, get_implementation # noqa
| python |
import numpy as np
import pytest
import treetensor.numpy as tnp
# noinspection DuplicatedCode
@pytest.mark.unittest
class TestNumpyFuncs:
_DEMO_1 = tnp.ndarray({
'a': np.array([[1, 2, 3], [5, 6, 7]]),
'b': np.array([1, 3, 5, 7]),
'x': {
'c': np.array([3, 5, 7]),
'd... | python |
# Lexical Addressing "X", because as of yet, we only do a very particular kind of addressing. Namely: we refer to a
# scope by "frames up", but we do not address within the scope (e.g.: memory-offset, or var-count-offset)
from utils import pmts
from dsn.form_analysis.free_variables import free_variables
from dsn.form... | python |
#You are given the following information, but you may prefer to do some research for yourself.
#1 Jan 1900 was a Monday.
#Thirty days has September,
#April, June and November.
#All the rest have thirty-one,
#Saving February alone,
#Which has twenty-eight, rain or shine.
#And on leap years, twenty-nine.
#A leap year oc... | python |
import urllib.parse
import socket
import re
from selectors import *
seen_urls = set('/')
urls_todo = set('/')
selector = DefaultSelector()
stopped = False
class Fetcher():
def __init__(self,url):
self.url = url
self.response = b''
self.sock = None
def fetch(self):
self.sock... | python |
# Copyright 2019,2020,2021 Sony Corporation.
#
# 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... | python |
import re
from routersploit import (
exploits,
print_success,
print_error,
print_table,
sanitize_url,
http_request,
mute,
)
class Exploit(exploits.Exploit):
"""
Exploit implementation for DSL-2750B Information Disclosure vulnerability.
If the target is vulnerable it allows to ... | python |
from django.db import models
# Create your models here.
class User(models.Model):
SEX = (
('M','男性'),
('F','女性'),
('S','保密'),
)
nickname = models.CharField(max_length=32,unique=True)
password = models.CharField(max_length=128)
age = models.IntegerField(default=18)
sex... | python |
for i in range(5):
with open('file.txt', 'a') as file:
file.write('input\n') | python |
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from core import views
from rest_framework_simplejwt import views as jwt_views
urlpatterns = [
path('teams/', views.TeamList.as_view()),
path('teams/<int:pk>/', views.TeamDetail.as_view()),
path('token/', jwt_views.T... | python |
import tensorflow as tf
# Define model as a policy network
class DynamicsModel():
def __init__(self):
def train(self):
| python |
import logging
import os
config_text = 'site_name: My Docs\n'
index_text = """
#LARGE(This is STATICGENNAN layout)
#MEDI(Created by Nandha, Ali, Abishekh)
#NORM(Aim to build a energy efficient website)
"""
log = logging.getLogger(__name__)
def new(output_dir):
docs_dir = os.path.join(output_dir, 'd... | python |
# coding: utf-8
"""
.. module:: fler_core.training_df.py
basic class for a training database
"""
__author__ = "Axel Marchand"
# standard
import asyncio
from typing import Union, List, Dict
import pandas as pd
import os
import numpy as np
import logzero
from sklearn.externals import joblib
# custom
from fler_utils.com... | python |
import os
import numpy as np
from flopy.utils.lgrutil import Lgr
def test_lgrutil():
nlayp = 5
nrowp = 5
ncolp = 5
delrp = 100.0
delcp = 100.0
topp = 100.0
botmp = [-100, -200, -300, -400, -500]
idomainp = np.ones((nlayp, nrowp, ncolp), dtype=int)
idomainp[0:2, 1:4, 1:4] = 0
nc... | python |
import sys
import logging
import traceback
import multiprocessing as mp
import atexit
class ExceptionWrapper(object):
r"""Wraps an exception plus traceback to communicate across threads"""
def __init__(self, exc_info):
self.exc_type = exc_info[0]
self.exc_msg = "".join(traceback.format_except... | python |
"""Auto-generated file, do not edit by hand. JM metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_JM = PhoneMetadata(id='JM', country_code=1, international_prefix='011',
general_desc=PhoneNumberDesc(national_number_pattern='(?:[58]\\d\\d|658|900)\\d{7}', possible_l... | python |
# https://stackoverflow.com/questions/34518656/how-to-interpret-loss-and-accuracy-for-a-machine-learning-model
from additional_models.data import read_csv_data, get_samples
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Flatten, Lambda
from keras.layers import ELU
from keras.layers.c... | python |
def headleft():
i01.setHeadSpeed(1.0,1.0)
i01.head.rothead.attach()
i01.head.rothead.moveTo(180)
sleep(1)
i01.head.rothead.detach()
| python |
#!/usr/bin/python
######################################################
# ****************************************
# Neural Network Color Classification \
# Using Yocto & Numpy /
# Running KnNN Network \
# /
# Alejandro Enedino Herna... | python |
"""
Creates a MobileNetV2 Model as defined in:
Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen. (2018).
MobileNetV2: Inverted Residuals and Linear Bottlenecks
arXiv preprint arXiv:1801.04381.
import from https://github.com/tonylins/pytorch-mobilenet-v2
"""
import torch.nn as nn
import ma... | python |
import csv, json, requests, datetime, sys
try:
import input
key = input.key
org_name = input.org_name
net_name = input.net_name
except ImportError:
print('Looks like there was an error inputting your variables. Please enter the correct information now: ')
key = str(raw_input('Enter your Meraki ... | python |
import logging
import sys
import time
import tkinter as tk
import traceback
from tkinter import PhotoImage, ttk
from multiprocessing import Queue
from modlunky2.constants import BASE_DIR, IS_EXE
from modlunky2.updater import self_update
from modlunky2.version import current_version, latest_version
from modlunky2.confi... | python |
# Import required libraries
import pygame
import os
from os.path import dirname, abspath
from Game import Game
imgs_path = dirname(dirname(abspath(__file__)))
GROUND_ASSET = pygame.transform.scale2x(pygame.image.load(os.path.join(imgs_path, "imgs", "ground.png"))) # Load in required images and double their size
# A... | python |
import pytest
import unittest
class MyTest(unittest.TestCase):
@pytest.fixture(autouse=True)
def initdir(self, tmpdir):
tmpdir.chdir() # change to pytest-provided temporary directory
tmpdir.join("samplefile.ini").write("# testdata")
def test_method(self):
with open("samplefile.ini") as f:
s = f.read()
... | python |
""" Cisco_IOS_XR_tunnel_nve_oper
This module contains a collection of YANG definitions
for Cisco IOS\-XR tunnel\-nve package operational data.
This module contains definitions
for the following management objects\:
nve\: NVE operational data
Copyright (c) 2013\-2016 by Cisco Systems, Inc.
All rights reserved.
""... | python |
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os.path as osp
import mmcv
import torch
from mmcv.runner import CheckpointLoader
def convert_stdc(ckpt, stdc_type):
new_state_dict = {}
if stdc_type == 'STDC1':
stage_lst = ['0', '1', '2.0', '2.1', '3.0', '3.1', '4.0', '4.1']
... | python |
class Test:
desc = "this is a test class"
def __init__(self, name):
self.name = name
def show(self):
print self.name
if (__name__ == "__main__"):
t = Test("test name")
print t
print t.desc
t.show()
| python |
# Copyright (c) 2016 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 applic... | python |
"""
Copyright (C) 2019-2020 Cisco Systems, Inc. and/or its affiliates. All rights reserved.
This module provides the base class for every Tool. A tool is anything that a Recipe
might depend on from the system environment.
The base class provides the logic for detecting tools.
There is work-in-progress logic to [opt... | python |
from .client import Client # noqa: F401
from . import log # noqa: F401
from . import broker # noqa: F401
from . import codec # noqa: F401
from . import protocol # noqa: F401
from . import throttle # noqa: F401
from . import sequence # noqa: F401
from . import correlater # noqa: F401
from . import ratelimiter ... | python |
from .asistplanningagents import *
from .preemptive import *
from .selectivetriage import *
from .mixedtimestrategy import *
from .mixedproxstrategy import *
| python |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# df.iloc[:,-8:]
def idx_to_case_xy(idx):
x=((idx/100).astype(int)/100*5).astype(int)
y=((idx-100*(idx/100).astype(int))/100*5).astype(int)
return x,y
# df['Answer.selected_idx']
# df['Input.ref_idx']
X=np.lo... | python |
import kopf
def test_nothing(invoke, real_run):
result = invoke(['run'])
assert result.exit_code == 0
registry = kopf.get_default_registry()
assert len(registry.resources) == 0
def test_one_file(invoke, real_run):
result = invoke(['run', 'handler1.py'])
assert result.exit_code == 0
reg... | python |
import re
class TxtParser(object):
"""
Class to apply Czech typography rules to input text.
Most of regular expressions are from Texy!
http://github.com/dg/texy/blob/master/Texy/modules/TexyTypographyModule.php
"""
text = ''
positions = {}
extracted = {}
def __init__(self, text... | python |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import math
from .blocks import ConvBnActivation3D, DecoderBlock3D, EncoderBlock3D, init_weights
class UNet(nn.Module):
def __init__(self, filters: list, in_channels: int = 1, n_classes: int = 13, residual: bool = True, bn: bool ... | python |
#UNION
n_english = int(input())
english_student = input().split()
n_french = int (input())
french_student = input().split()
set_english = set(english_student)
set_french = set(french_student)
one_sub = set_english.union(set_french)
output = len(one_sub)
print (output) | python |
import numpy as np
from scipy.interpolate import splprep, splev
import matplotlib.pyplot as plt
class paths:
def __init__(self,points = None):
self.spline = None
self.resolution = 100
if points != None:
self.set_points(points)
def set_points(self,points):
self.point_array = points
self.spline, u = spl... | python |
#!/usr/bin/env python
# Copyright (c) 2010 Rosen Diankov (rosen.diankov@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... | python |
#winVersion.py
#A part of NonVisual Desktop Access (NVDA)
#Copyright (C) 2006-2013 NV Access Limited
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
import sys
import winUser
winVersion=sys.getwindowsversion()
winVersionText="{v.major}.{v.minor}.{v.build}".fo... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 26 14:56:33 2019
@author: JoeCalverley
"""
import numpy as np
import math
import scipy.stats as sk
import matplotlib.pyplot as plt
def choose_b(J_est):
# Input is the array of current estimates of means
b = J_est.index(min(J_est))
#Fun... | python |
'''
Created on 8 de set de 2020
@author: michel
'''
from pymongo.mongo_client import MongoClient
from helpers import conf_reader
class mongo_con:
def connect_db(self):
c_reader = conf_reader.conf_reader('../configuration.cfg')
host = c_reader.getConf('general', 'host')
method = c_reader.... | python |
# Copyright (c) 2015 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 ... | python |
from telethon.errors import (UserIdInvalidError, UserAdminInvalidError,
ChatAdminRequiredError, BadRequestError)
from telethon.tl.functions.channels import EditBannedRequest
from ..help import add_help_item
from userbot import BOTLOG, BOTLOG_CHATID, is_mongo_alive, is_redis_alive
from user... | python |
# coding: utf-8
from enum import Enum
from six import string_types, iteritems
from bitmovin_api_sdk.common.poscheck import poscheck_model
from bitmovin_api_sdk.models.h264_per_title_configuration import H264PerTitleConfiguration
from bitmovin_api_sdk.models.h265_per_title_configuration import H265PerTitleConfiguration... | python |
"""
Common resource for bladder annotation terms.
"""
# convention: preferred name, preferred id, followed by any other ids and alternative names
bladder_terms = [
("urinary bladder", "FMA:15900", "UBERON:0001255"),
("neck of urinary bladder", "FMA:15912", "UBERON:0001258"),
("Dome of the Bladder", "ILX:07... | python |
import os
import subprocess
import unittest
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
class CodeStyleTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
if hasattr(cls, 'root_path'):
return
try:
root_path = os.p... | python |
from sanic import Sanic
from .views import SubscribeView
def init_routes(app: Sanic):
app.add_route(SubscribeView.as_view(), '/subscribe/<uid:uuid>', methods=['GET'])
| python |
import aiopubsub
from loguru import logger
import numpy as np
from tasty_alpha.broker import Broker
from tasty_alpha.exchange import Exchanges
from tasty_alpha.market import Markets
from tasty_alpha.order import LimitOrder, MarketOrder, OrderSide
from tasty_alpha.sampling.bar import Bar
from tasty_alpha.strategy import... | python |
import copy
from os import path, stat
import cocos
import cocos.actions
import cocos.sprite
import cocos.layer
import pyglet
from . import data, settings
from ..chart import Line, BaseNote, Drag, Flick, Hold, chart
__all__ = ['preview']
combo_label = None
score_label = None
def update_labels():
global combo_l... | python |
#!/usr/bin/env python3
# Copyright (c) 2021 The Finalcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Common utility functions
'''
import shutil
import sys
import os
from typing import List
def determine_w... | python |
import copy
import logging
import colorama
from math import floor
def colourize_string(string, colour):
return '{color_begin}{string}{color_end}'.format(
string=string,
color_begin=colour,
color_end=colorama.Style.RESET_ALL)
def initialize_logger_format(logger):
"""
Initialize the ... | python |
from .downloader import Downloader
from .lyrics import SongLyrics
from .search import Search, DownloadedSongs, yt_search
from .vocalremover import VocalRemover
__all__ = ['SongLyrics','Downloader','Search','DownloadedSongs','VocalRemover','yt_search'] | python |
"""
homeassistant.components.camera.foscam
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This component provides basic support for Foscam IP cameras.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/camera.foscam/
"""
import logging
from homeassistant.helpers imp... | python |
#!/usr/bin/env python
"""
Module for reading TXT files
This expects a segment from class derived in convert_text
"""
# do not delete - needed in time_aligned_text
from asrtoolkit.data_handlers.data_handlers_common import footer, header, separator
from asrtoolkit.data_structures.segment import segment
def format_seg... | python |
import shutil
import sys
import os, os.path
import imp
import blogofile.main
from blogofile import argparse
## These are commands that are installed into the blogofile
## command-line utility. You can turn these off entirely by removing
## the command_parser_setup parameter in the module __dist__ object.
def setup(p... | python |
"""
pinq.compat
~~~~~~~~~~~
"""
from collections import defaultdict, Iterable
from functools import reduce
from itertools import chain, dropwhile, groupby, islice, takewhile, tee
from operator import eq
try:
from functools import lru_cache
except ImportError:
def lru_cache(maxsize=128, typed=False):
"... | python |
from django.urls import reverse
from tests.base.main_test_case import MainTestCase
class UserRecipesViewTest(MainTestCase):
def test_userRecipes_whenNotLoggedIn_shouldRedirectToSignInWithNext(self):
self.create_recipe()
response = self.client.get(reverse('my-recipes'))
self.assertRedirect... | python |
"""
This module creates a rudimentary form entering system within an ipython
notebook and creates a food stack plot with the entered data.
"""
import ipywidgets as widgets
from IPython.display import clear_output
from stack_plotting import stack_plot, food_stack_plot
# a list of lists of values to be plotted in eac... | python |
"""
Main script for processing an image:
it preprocesses the image, detects the line, estimate line curve
and do the path planning
"""
from __future__ import print_function, with_statement, division, absolute_import
import argparse
import cv2
import numpy as np
from constants import REF_ANGLE, MAX_ANGLE, EXIT_KEYS, ... | python |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file
containing over five-thousand first names, begin by sorting it into
alphabetical order. Then working out the alphabetical value for each name,
multiply this value by its alphabetical position i... | python |
#!/usr/bin/python
#Import modules for CGI handling
import cgi, cgitb
import Cookie, os, time
import requests
# Instantiate a SimpleCookie object
cookie = Cookie.SimpleCookie()
cookie_string = os.environ.get('HTTP_COOKIE')
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
Use... | python |
import sys
import os
from os import listdir
from os.path import isfile, join
class DisparityAndImagesPath:
def __init__(self):
self.imageLeftFilename = None
self.imageRightFilename = None
self.disparityLeftFilename = None
self.disparityRightFilename = None
def isValid(self):
return (self.imageLeftFilename ... | python |
#!/usr/bin/env python
'''
Copyright (c) 2019, Robot Control and Pattern Recognition Group, Warsaw University of Technology
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions... | python |
import re
import hazm
import nltk
import pandas as pd
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer, WordNetLemmatizer
nltk.download("wordnet")
nltk.download("stopwords")
class Preprocess:
def fit(self, data, lang):
is_fa = data["lang"] == "fa"
fa_data = data[is_fa]
... | python |
import time
from pyferm.actions import action
class hold(action):
def __init__(self, name, parent, **kwargs):
super().__init__(name, parent, **kwargs)
def run(self):
self.value = self.params["value"]
self.low = self.params["controls"]["low"]
self.high = self.params["controls"]... | python |
from enos.core.constant.DeliveryTopicFormat import DeliveryTopicFormat
from enos.core.constant.MethodConstants import MethodConstants
from enos.core.message.BaseRequest import BaseRequest
from enos.core.message.BaseRequest import BaseBuilder
from enos.core.util.Deprecation import deprecated
from enos.message.upstream.o... | python |
import pytest
def test_arrange():
"""
Blank line in Arrange Block
"""
x = 3
y = 4
result = x ** 2 + y ** 2
assert result == 25
def test_act():
"""
Blank line in Act Block
"""
nothing = None
with pytest.raises(AttributeError):
nothing.get_something()
def... | python |
from typing import Dict, Iterable, List
from collections import defaultdict
import re
import networkx
TEST_INPUT = """Tile 2311:
..##.#..#.
##..#.....
#...##..#.
####.#...#
##.##.###.
##...#.###
.#.#.#..##
..#....#..
###...#.#.
..###..###
Tile 1951:
#.##...##.
#.####...#
.....#..##
#...######
.##.#....#
.###.#####
#... | python |
from collections import Counter
a = input()
b = Counter(input())
print(b.most_common()[-1][0])
| python |
"""This module contains functions for retrieving song data
from the Spotify dataset files.
MIT License
Copyright (c) 2021 Andrew Qiu
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 restr... | python |
import telebot
from os import environ
from extra import *
# Nuevo import para poder enviar cosas inline
# Declaración del bot
bot = telebot.TeleBot(environ['TELEGRAM_TOKEN'])
bot.delete_webhook()
# Declaración de los comandos
@bot.message_handler(commands=['start'])
def start_handler(m):
"Función que maneja los usu... | python |
addrById = {
1: '13:9a', # disi
2: '19:15', # disi
3: '11:0c', # disi
4: '12:8a', # disi
5: '11:a3', # disi
6: '10:9b', # disi
7: '18:33', # disi
8: '10:89', # disi
9: '11:4a', # disi
10: 'c8:0c', # disi
11: '18:32', # disi
12: '17:93', # disi
13: '02:d8',... | python |
""" Comparison Analysis FinBrain API """
__docformat__ = "numpy"
import argparse
from typing import List
import requests
from matplotlib import pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
from pandas.plotting import register_matplotlib_converters
import numpy as np
import seaborn as sns
from g... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Test the Census ETL schema package
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__),".."))
from schema import *
def test_range_funcs():
r1 = Range(1,1)
r2 = Range(1,1)
assert r1==r2
r3 = Range(2,2)
assert r1 < r3
def test... | python |
"""
Journald configuration
======================
Combiner for parsing of journald configuration. man journald.conf describes where various
journald config files can reside and how they take precedence one over another. The combiner
implements the logic and provides an interface for querying active settings.
The jour... | python |
from __future__ import annotations
from abc import ABC, abstractmethod
from nuplan.common.actor_state.state_representation import TimePoint
from nuplan.common.utils.split_state import SplitState
class InterpolatableState(ABC):
"""
Interface for producing interpolatable arrays from objects. Objects must have... | python |
from django.shortcuts import render
from applications.forms import ApplicationForm
from datetime import datetime
from django.views.generic import ListView
from django.views.generic.edit import FormView
from .models import ApplicationPeriod, ApplicationGroup
class ApplicationInfoView(ListView):
template_name = "app... | python |
from random import randrange as rd
# Target class
#
# Provides functions to randomly place the target in a valid location.
# Additionally, contains x and y coordinates, and color of the target
class Target:
def __init__(self, boardSize, board, robots):
self.board_size_ = boardSize
self.set_target(... | python |
from threading import Thread
import zmq
timeout = 0.1
class Subscriber(object):
def __init__(self, addrs, wsmanager):
self.addrs = addrs
self.wsmanager = wsmanager
self.kill = False
def run(self):
ctx = zmq.Context()
sockets = []
poller = zmq.Poller()
... | python |
import cProfile
import timeit
from hk1980 import LatLon
stmt = "LatLon(22.284034, 114.137814).to_hk80()"
time = timeit.timeit(stmt=stmt, globals=globals(), number=100)*1000
print(f"{time=} ms")
cProfile.run(stmt) | python |
#!/usr/bin/env pybricks-micropython
import struct, threading
from pybricks import ev3brick as brick
from pybricks.ev3devices import (
Motor,
TouchSensor,
ColorSensor,
InfraredSensor,
UltrasonicSensor,
GyroSensor,
)
from pybricks.parameters import (
Port,
Stop,
Direction,
Button... | python |
from pydantic import BaseSettings
class Settings(BaseSettings):
PROJECT_NAME: str = "AIOAuth FastAPI example"
PROJECT_HOST: str = "0.0.0.0"
PROJECT_PORT: int = 8001
DEBUG: bool = True
PSQL_DSN: str
JWT_PUBLIC_KEY: str
JWT_PRIVATE_KEY: str
ACCESS_TOKEN_EXP: int = 900 # 15 minutes
... | python |
"""
Django settings for arches_bchp project.
"""
import os
import arches
import inspect
from django.utils.translation import gettext_lazy as _
try:
from arches.settings import *
except ImportError:
pass
APP_NAME = 'arches_bchp'
APP_ROOT = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()... | python |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 4 11:01:16 2015
@author: hehu
"""
import matplotlib.pyplot as plt
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.svm import SVC, LinearSVC
from sklearn.linear_model ... | python |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import py... | python |
# SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the Rez Project
organisation_name = "nerdvegas"
application_name = "rez-gui"
| python |
from models.armedforces.formations.units.unitmixin import UnitMixin
from models.configurations import SIMULATOR_CONFIG as CONFIG
class TestUnitMixin():
def setup(self):
print("setup")
self.unit = UnitMixin()
def test_init(self):
print("test_init")
assert self.unit.recharge >=... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# map_setup.py
#
# Copyright (c) 2012-2013 PAL Robotics SL. All Rights Reserved
#
# Authors:
# * Enrique Fernández
import rospy
import rosparam
from std_msgs.msg import String
import os
class MapSetupException(Exception):
pass
class MapSetup:
def __init__(... | python |
#!/usr/bin/env python
from __future__ import print_function
from __future__ import unicode_literals
import sys
import roslib
import gencpp
import genmsg
from roslib import packages,msgs
import os
from io import StringIO
import argparse
NAME='create_boost_header'
def write_boost_includes(s, spec):
"""
... | python |
from logging import getLogger
from typing import Callable, Optional, Union, List, Set
from aiogram import Dispatcher, Bot
from state_manager import BaseStorage
from state_manager.event_processors.aiogram import AiogramEventProcessor
from state_manager.routes.base.state import BaseStateRouter, BaseMainStateRouter
from... | python |
from __future__ import annotations
from hypothesis import assume, event, example, given, infer, strategies as st
import json
import pytest
from sqlalchemy.future import create_engine
from typing import Dict, List, NamedTuple, Optional, Protocol, TypeVar
from jterritory.api import Endpoint, Invocation, Response
from jt... | python |
from . import monokai, darkly, github, tomorrow_night, tomorrow
| python |
import json
import requests
import time
import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
from datetime import date
class BayesianABTesting:
def __init__(self, likelihood_function: str, data: dict):
"""
A convenience wrapper class for commonly used Bay... | python |
# novalidate
# fmt: off
from collections import namedtuple
#: NetworkTables Entry Information
EntryInfo = namedtuple('EntryInfo', [
# Entry name
'name',
# Entry type
'type',
# Entry flags
'flags',
# Timestamp of last change to entry (type or value).
#'last_change',
])
#: NetworkTa... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.