content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import rospy
import message_filters
#from std_msgs.msg import String ## we need it stamped or we cant use TimeSynchronizer
from ros_example_torch_classifier.msg import StringStamped
from ros_example_torch_classifier.utils import check_remap
from std_srvs.srv import Trigg... |
from __future__ import unicode_literals
import logging
#: not set object
NOT_SET = object()
class BaseTableModel(object):
"""Base model for table
"""
#: the table object
TABLE = None
def __init__(self, factory, logger=None):
self.logger = logger or logging.getLogger(__name__)
... |
from django.contrib.auth.models import Group
from dalme_api.serializers import (AgentSerializer, ContentClassSerializer, ContentTypeSerializer,
CountryReferenceSerializer, GroupSerializer, LanguageReferenceSerializer,
LocaleReferenceSerializer, Plac... |
from pretalx.event.models import Organiser, Team
def create_organiser_with_user(*, name, slug, user):
organiser = Organiser.objects.create(name=name, slug=slug)
team = Team.objects.create(
organiser=organiser,
name=f'Team {name}',
can_create_events=True,
can_change_teams=True,... |
# TODO: handle file mode?
import io
import sys
from ..interface import Contract, ContractNotRespected
from ..syntax import (add_contract, add_keyword, Keyword, W)
inPy2 = sys.version_info[0] == 2
if inPy2:
file_type = (file, io.IOBase)
else:
file_type = io.IOBase
class File(Contract):
def __init__(self... |
import pyshark
import py
import os
CONFIG_PATH = os.path.join(os.path.dirname(pyshark.__file__), 'config.ini')
def get_config():
return py.iniconfig.IniConfig(CONFIG_PATH) |
from pathlib import Path
from magnus.integration import BaseIntegration
class LocalContainerComputeS3Catalog(BaseIntegration):
"""
Integration pattern between Local container and S3 catalog
"""
mode_type = 'local-container'
service_type = 'catalog' # One of secret, catalog, datastore
servic... |
"""
Created on @Time:2019/7/9 15:34
@Author:sliderSun
@FileName: generate_char.py
"""
from qaPairsRelationClassification.utils.preprocess import MyVocabularyProcessor
import numpy as np
def generate(x2_text, x1_text, max_document_length):
print("Building vocabulary")
vocab_processor = MyVocabularyProcessor(max... |
# -*- coding: utf-8 -*-
import sys
import gc
import time
try:
import msvcrt
def kbhit():
return msvcrt.kbhit()
def getch():
return msvcrt.getwch()
except ImportError:
print("Assuming on ESP")
import uselect
def kbhit():
spoll=uselect.poll()
spoll.register(sy... |
# -*- coding: utf-8 -*-
from setuptools import setup
from pyHMI import __version__
with open('requirements.txt') as f:
required = f.read().splitlines()
setup(
name='pyHMI',
python_requires='>=3.2',
version=__version__,
description='A set of class for easy build tkinter HMI with Python',
long_... |
from ctypes import cast, c_uint, c_uint32, c_float, CDLL, POINTER
c_uint32p = POINTER(c_uint32)
c_floatp = POINTER(c_float)
import sys
import torch
from data import examples
so = CDLL('cuda/libmodel.so')
init = so.init
init.restype = None
init.argtypes = []
model = so.model
model.restype = None
model.argtypes = [
... |
import itertools
import math
def read_input():
file = open('input/2015/day2-input.txt', 'r')
return [[int(side) for side in line.split('x')] for line in file.readlines()]
def wrapping(lengths):
"""
>>> wrapping([2, 3, 4])
58
>>> wrapping([1, 1, 10])
43
"""
sides = [(x * y) for x... |
"""Tests replicating
Written by Peter Duerr
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
import unittest
import numpy as np
import logging
import io
import multiprocessing
import functools
if True: # Ugly, but... |
class Board():
def __init__(self):
self.size = 8 |
import functools
import importlib
from threading import Lock
from .di import Di
class MapLoader:
def __init__(self, di: Di, map_: dict = None):
self._di = di
self._map = {}
self._loaded = {}
self._stack = []
self._lock = Lock()
if map_:
self.append(ma... |
# -*- coding: utf-8 -*-
__author__ = 'idbord'
from cmm.lexer import Lexer
def lexer(path):
result = []
try:
stream = open(path, 'r')
token_list = Lexer.lexer_analysis(stream)
stream.close()
for i in token_list:
result.append(i.to_string_with_line())
return ... |
from flask_script import Manager, Server
from app import app
manager = Manager(app)
manager.add_command("run", Server(host='0.0.0.0', port=5000, use_debugger=True))
if __name__ == '__main__':
manager.run()
|
#!/usr/bin/env python3
import canvas_grab_gui
if __name__ == '__main__':
canvas_grab_gui.Main().main()
|
from django.contrib import admin
from .models import Api, Service, Parameter, ParameterGroup, TagSignature
class ParameterGroupTabularInline(admin.TabularInline):
model = ParameterGroup
@admin.register(Service)
class ServiceAdmin(admin.ModelAdmin):
inlines = [ParameterGroupTabularInline]
list_display = (... |
from flask import Flask, abort, request, jsonify
from redis import Redis, RedisError
from message_pb2 import Request, Response
import os
import socket
import logging
import json
redis = Redis(host="redis", port=6379, db=0, socket_connect_timeout=2, socket_timeout=2)
app = Flask(__name__)
def play_station(station):
... |
import pytest
from .utils import reset_config
from fastapi_jwt_auth import AuthJWT
from fastapi import FastAPI, Depends
from fastapi.testclient import TestClient
from datetime import timedelta
@pytest.fixture(scope='function')
def client():
app = FastAPI()
@app.get('/protected')
def protected(Authorize: A... |
import re
NUMBER_REGEX = r"\d+(\.\d+)?"
def _create_regex(name, specifier, number_regex=NUMBER_REGEX):
return r"(?P<{name}>{number}){specifier}".format(
name=name, specifier=specifier, number=number_regex
)
TIME_PERIOD_REGEX = (
r"^"
r"({days})?"
r"({hours})?"
r"({minutes})?"
r"... |
#!/Library/Frameworks/Python.framework/Versions/Current/bin/python
# ===============================================================================
# Copyright 2012 Jake Ross
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may... |
import tensorflow as tf
from idas.models.hyperbolic import hyp_ops
import numpy as np
from tensorflow.python.ops import tensor_array_ops, control_flow_ops
# def hyp_pixel_embedding(incoming, radius=1.0):
#
# def _embed_pixel_by_pixel(x_in, chs_in):
#
# if len(x_in.get_shape()) > 1:
# # in tf.m... |
#!/usr/bin/env python
""" Run a few tests using the King James Bible plain text version as
available from:
http://www.gutenberg.org/etext/10
"""
import re, time
from mx import TextTools, Tools
# Location of the text file
KJB = '/tmp/kjv10.txt'
# Iterations to use for benchmarking
COUNT = 100
def search_b... |
import random
fin = open("D:/Users/tsyac/Documents/GitHub/personal/6883-SOD/data/combined/fin.txt", 'rb')
f_train = open("D:/Users/tsyac/Documents/GitHub/personal/6883-SOD/data/combined/f_train.txt", 'wb')
f_test = open("D:/Users/tsyac/Documents/GitHub/personal/6883-SOD/data/combined/f_test.txt", 'wb')
f_val = open("... |
def merge(arr,l,mid,r):
n1 = mid-l+r
n2 = r-mid
temp1 = []
temp2 = []
for i in range(n1):
temp1.append(arr[l+i])
for i in range(n2):
temp2.append(arr[mid+1+i])
i = 0
j = 0
k = l
while(l<n1 and r<n2):
if(temp1[i] < temp2[j]):
arr[k] = temp1[... |
from setuptools import find_packages, setup
setup(
name="auto_argparse",
version="0.0.7",
url="https://github.com/neighthan/auto-argparse",
author="Nathan Hunt",
author_email="neighthan.hunt@gmail.com",
description="Automatically create argparse parsers.",
license="MIT",
packages=find_p... |
"""Scan text and check if it contains a keyword
"""
from prowl.utility.file import read_file_by_line
def contains_keywords(text: str, keywords: list) -> bool:
"""Check if text contains a keyword from a list of keyword
:param text: text to analyze
:param keywords: list of keywords to match
:return: tr... |
from django.test import TestCase
from .models import Article, Website
class ArticleTestCase(TestCase):
def setUp(self):
self.website_ = "https:://reuters.com"
self.website = Website.objects.create(url=self.website_)
self.article = Article.objects.create(
title="Testing",
... |
import argparse
import sys
def contains_crlf(filename):
with open(filename, mode='rb') as file_checked:
for line in file_checked.readlines():
if line.endswith(b'\r\n'):
return True
return False
def removes_crlf_in_file(filename):
with open(filename, mode='rb') as file... |
import pickle
from collections import deque
import pytest
from validx import exc
NoneType = type(None)
def test_lazyref(module):
v = module.Dict(
{"x": module.Int(), "y": module.LazyRef("foo", maxdepth=2)},
alias="foo",
optional=["x", "y"],
)
data = {"x": 1}
assert v(data)... |
from gym import Wrapper
from mujoco_py import MjViewer, MjRenderContextOffscreen
class RenderEnv(Wrapper):
def __init__(self, env,
cam_id=None, cam_pos=None, cam_angle=None, cameras=None,
view="left", zoom=1.0,
width=84, height=None, ):
super().__init__(e... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 3 22:37:10 2019
@author: Ghayasuddin Adam
"""
# -*- coding: utf-8 -*-
"""
Created on Fri May 3 07:41:43 2019
@author: Ghayasuddin Adam
"""
import re
import tweepy
from tweepy import Stream
from tweepy.streaming import StreamListener
from tweepy import... |
import os
from typing import List, Optional
from urllib.request import urlopen, Request
from datetime import date
from time import sleep
from pathlib import Path
import json
from bs4 import BeautifulSoup
def wait_for_input(day: Optional[int] = None, year: Optional[int] = None) -> None:
today = date.today()
i... |
#!/usr/bin/env python
########################
# author:terry #
# 27/11/15 #
########################
import time
import os
import getopt
import sys
filename = ''
name = '' #author name
hasdes = False #whether has description
cusdate = '' #custom date
def usage():
... |
"""
Classes
-------
Additional Classes used in different places around the code.
Mostly to help to get data around.
"""
import numpy as np
from plofeld.utils.constants import RealNumber
class Vector(np.ndarray):
"""Class to collect coordinates.
Basically a named-numpy array of size 2 or 3.
Numpy subclas... |
from __future__ import absolute_import
import pytest
from django.conf import settings
from django.test import RequestFactory
from django.dispatch import receiver
from importlib import import_module
from django_cas_ng.models import SessionTicket
from django_cas_ng.backends import CASBackend
from django_cas_ng.signals ... |
import os
import tempfile
from mock import patch
import dusty.constants
from dusty.systems.known_hosts import ensure_known_hosts
from ....testcases import DustyTestCase
@patch('dusty.systems.known_hosts._get_known_hosts_path')
@patch('dusty.systems.known_hosts.check_output')
class TestKnownHostsSystem(DustyTestCase)... |
__version__ = '0.1dev'
from ..config import __NTHREADS__
from ..config import __USE_NUMEXPR__
if __USE_NUMEXPR__:
import numexpr
numexpr.set_num_threads(__NTHREADS__)
else:
#import numpy ufunc (c-coded for speed-up)
from numpy import subtract, divide, power, add
import numpy
from numpy import log, exp... |
#!/usr/bin/env python3
# so that script can be run from Brickman
import termios, tty, sys
from ev3dev.ev3 import *
# attach large motors to ports B and C, medium motor to port A
motor_left = LargeMotor('outC')
motor_right = LargeMotor('outD')
motor_a = MediumMotor('outA')
motor_b = MediumMotor('outB')
def getch():
... |
import crosscat.tests.component_model_extensions.ContinuousComponentModel as ccmext
import random
import math
import numpy
import six
import unittest
def main():
unittest.main()
class TestContinuousComponentModelExtensions_Constructors(unittest.TestCase):
def setUp(self):
N = 10
self.N = N
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 23 20:02:25 2022
@author: dv516
"""
import numpy as np
import math
from scipy.optimize import minimize
from typing import List, Tuple
from Functions.test_functions import f_d2, f_d3
def optimizer_dummy(f, N_x: int, bounds: List[Tuple[float]], N: int = 100) -> (float, ... |
#
# PySNMP MIB module ITOUCH-EVENT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ITOUCH-EVENT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:57:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
#
# PySNMP MIB module ASCEND-MIBATMATOM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBATMATOM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:10:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
#!/usr//bin/env python3
# T. Vuillaume, 12/09/2019
# merge and copy DL1 data after production
# Modifications by E. Garcia, 21/01/2020
# 1. check job_logs
# 2. check that all files have been created in DL1 based on training and testing lists
# 3. move DL1 files in final place
# 4. merge DL1 files
# 5. move running_d... |
#!/usr/bin/env python
import os
from setuptools import setup
from hyperledger import version
ROOT_DIR = os.path.dirname(__file__)
SOURCE_DIR = os.path.join(ROOT_DIR)
requirements = [
'requests >= 2.5.0',
'six >= 1.4.0',
# 'websocket-client >= 0.32.0',
]
exec(open('hyperledger/version.py').read())
with o... |
# @copyright@
# Copyright (c) 2006 - 2019 Teradata
# All rights reserved. Stacki(r) v5.x stacki.com
# https://github.com/Teradata/stacki/blob/master/LICENSE.txt
# @copyright@
import stack.commands
import json
from stack.exception import CommandError
class __Plugin(stack.commands.Plugin, stack.commands.Command):
def ... |
# A part of NonVisual Desktop Access (NVDA)
# Copyright (C) 2006-2022 NVDA Contributors <http://www.nvda-project.org/>
# This file is covered by the GNU General Public License.
# See the file COPYING for more details.
"""global variables module
@var foregroundObject: holds the current foreground object. The object for... |
print("----------------------------------------------")
print(" Even/Odd Number Identifier")
print("----------------------------------------------")
play_again = 'Y'
while play_again == 'Y':
user_num = input("Enter any whole number: ")
user_int = int(user_num)
if user_int % 2 == 0:
print("... |
from fifo_animal_shelter import __version__
from fifo_animal_shelter.fifo_animal_shelter import AnimalShelter,Cat,Dog
def test_version():
assert __version__ == '0.1.0'
def test_adding_to_shelter():
'''
testing enqueue is working fine
'''
shelter=AnimalShelter()
cat1=Cat('jojo')
assert she... |
class When(object):
state = None
used = False
callableObject = None
def __init__(self, obj):
self.obj = obj
def of(self, item):
self.state = self.obj == item
if not self.state:
try:
self.state = isinstance(self.obj, item)
except Exc... |
"""
Parsing mnemonics of a LAS file
===============================
Often, a mnemonic aliasing process looks like the following:
#. List all the mnemonics in the file
#. Group synonymous mnemonics under a single label
#. Make dictionaries with mnemonics and labels
#. Feed dictionaries into welly
The class... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2014, Blue Box Group, Inc.
# Copyright 2014, Craig Tracey <craigtracey@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
#
# ... |
# version 1.0
# 07/21/2018
# swtich to new database structure
# stream name: attribute name
# key: attribute value
# value: enitre record
# version 0.3
# 06/26/2018
# use fixed query to benchmark
# added graphic chart
# version 0.2.1
# 06/25/2018
# added validation function
# version 0.2
# 06/21/2018
# implematation... |
# Copyright 2015 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
"""Provides info about registered luci services."""
import logging
from google.appengine.ext import ndb
from components import config
from comp... |
import argparse
import logging
from pathlib import Path
import pandas as pd
logger = logging.getLogger(__name__)
def ensemble(models_dir: Path):
df_parts = []
for model_dir in [d for d in models_dir.iterdir() if d.is_dir()]:
predictions_file = model_dir / 'test_predictions.csv'
logger.info(... |
from app import db, models
pairs = [('https://adamska426.wordpress.com/','Katelyn'),('https://computerscience183923392.wordpress.com','Jessie'),
('https://youngdublog.wordpress.com/','Dustin'),('https://waughblogs.wordpress.com','Chandler'),
('https://basantfoss.wordpress.com','Basanta'),('https://myso... |
import unittest
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
import numpy as np
from sklearn.utils.estimator_checks import check_estimator
from ITMO_FS.filters.unsupervised import *
from ITMO_FS.filters.univariate import *
np.random.seed(42)
class T... |
import indieweb_utils
from bs4 import Comment
import datetime
import logging
import mf2py
import json
def add_to_database(full_url, published_on, doc_title, meta_description, heading_info, page,
pages_indexed, page_content, outgoing_links, crawl_budget, nofollow_all, main_page_content,
original_h_card, hash, thin_... |
#!/usr/bin/python
#coding:utf-8
import scrapy
from tutorial.items import TutorialItem
from scrapy.http import Request
from scrapy.spiders import CrawlSpider
from scrapy.selector import Selector
import json
import time
import random
import redis
from scrapy.conf import settings
#zhipin 爬虫
class ScriptSlug(scrapy.Sp... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shopping', '0027_product_items_in_stock'),
]
operations = [
migrations.AddField(
model_name='customorder',
... |
"""
The collision engine of the game.
"""
import pygame as pg
from pygame.math import Vector2
from xcape.common.loader import SFX_RESOURCES
from xcape.common.object import GameObject
from xcape.components.audio import AudioComponent
class CollisionEngine(GameObject):
"""
A specialised (non-scalable) collisio... |
from core.advbase import *
def module():
return Templar_Hope
class Templar_Hope(Adv):
conf = {}
conf['slots.a'] = [
'The_Shining_Overlord',
'Flash_of_Genius',
'Felyne_Hospitality',
'Sisters_of_the_Anvil',
'His_Clever_Brother'
]
conf['slots.poison.a'] = [
'The_Shining_Overlo... |
import BF_v2
import search_filter
import pickle
from bitarray import bitarray
import os
import matplotlib.pyplot as plt
import seaborn as sns
from collections import Counter
from Bio import SeqIO, SeqRecord, Seq
import csv
import Classifier
from OXA_Table import OXATable
#from Bio.Seq import Seq
# Help-Script to gener... |
__author__ = 'ipetrash'
|
import logging
import os
import subprocess
import sys
from .cd import current_directory
from .filesystem import TempDir
from .utility import Style
def __log_check_output(cmd, verbosity, **kwargs):
shell = not isinstance(cmd, list)
with open(os.devnull, 'w') as devnull:
logging.log(verbosity, __format... |
from flask_login import login_required,current_user
from flask import render_template,request,redirect,url_for,abort
from ..models import User,Blog,Category,Comment,Subcription
from .forms import UpdateProfile,BlogForm,CategoryForm,CommentForm
from ..import db,photos
from . import main
from ..requests import get_quote... |
from bs4 import BeautifulSoup
from checklib import *
import secrets
import requests
PORT = 5000
class CheckMachine:
@property
def url(self):
return f'http://{self.host}:{self.port}'
def __init__(self, host, port):
self.host = host
self.port = port
def register_in_servi... |
import pytest
from app import ic
from app.auth import Group, UserMod
from app.tests.auth_test import VERIFIED_EMAIL_DEMO
@pytest.mark.fixtures
@pytest.mark.skip
def test_fixtures(loop, client, passwd):
async def group_count():
return await Group.all().count()
async def get_user():
retur... |
"""
flatlanddb.py - Loads the existing flatland database
"""
import sys
import logging
import logging.config
from pathlib import Path
from sqlalchemy import create_engine, MetaData
from sqlalchemy import event
from sqlalchemy.engine import Engine
from sqlite3 import Connection as SQLite3Connection
@event.listens_for(... |
# Importing 3-rd party modules:
import requests
from bs4 import BeautifulSoup
import pandas as pd
# Importing base web objects:
from base_objects import BaseWebPageResponse, BaseWebPageIngestionEngine
class EDGARResultsPageResponse(BaseWebPageResponse):
"""
This is a class that inherits from the BaseWebPageRe... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-20 05:40
from __future__ import unicode_literals
import books.models
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('books', '0008_auto_20170420_0531'),
]
operations = [
mi... |
import copy
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import pickle
import seaborn as sns
from sklearn.metrics import r2_score
import torch
from tqdm import tqdm
from behavenet import get_user_dir
from behavenet import make_dir_if_not_exists
from behavenet.fitting.utils import ex... |
import datetime
import dateutil.parser
from django.utils import timezone
from . import models
from . import signals
from . import util
from . import fixed_data
from tatl.models import TatlVerb
def _format_tuple(x):
if hasattr(x, "process_kind"):
return (x.kind, str(x.id), "")
elif hasattr(x, "group_... |
import argparse
import pymongo
import config
from twitter_streamer import TwitterStreamer
LOCAL_DB = config.LOCAL_CLIENT.tweets
ATLAS_DB = config.ATLAS_CLIENT.tweets
class Load_DB:
def __init__(self, batch_size, limit):
self.batch_size = batch_size
self.buffer = []
self.limit = limit
... |
import logging
log_level = logging.getLogger().level
import gym
logging.getLogger().setLevel(log_level)
from rllab.envs.base import Env, Step
from rllab.spaces.box import Box
from rllab.core.serializable import Serializable
from conopt.experiments.A7_particle_imitation_two import Experiment
import numpy as np
from sand... |
import unittest
import json
from pyanalysis.mysql import Conn
from pyanalysis.moment import moment as m
from pyghostbt.strategy import Strategy
from pyghostbt.tool.order import *
from pyghostbt.tool.runtime import Runtime
from pyghostbt.const import *
from dateutil import tz
strategy_1st_config = {
"mode": "backt... |
import numpy as np
import cv2
import copy
import math
import os
import time
def double_raster(imgTakein, startRow):
# take in binary image; startRow is the start row of the current image slice
img = normalize(imgTakein)
cur_label=2
coordinates = [None] * 50
eq=[]
for i in range(0,len(img)*len(i... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import compas_rhino
from compas_rv2.rhino import get_scene
from compas.utilities import flatten
from compas_rv2.rhino import rv2_undo
__commandname__ = "RV2pattern_move_vertices"
@rv2_undo
def RunCommand(is... |
import pytest
from dataclasses import dataclass
from gemma import (
Surveyor,
Course,
Attr,
Item,
Compass,
NonNavigableError,
Call,
SuppressedErrors,
PORT,
)
def test_surveyor_chart_raises_navigable():
compass = Compass(target_types=dict)
surveyor = Surveyor(compasses=[com... |
from setuptools import setup, find_packages
from os import remove
from pathlib import Path
from json import dump
from ravenml.utils.git import is_repo, git_sha, git_patch_tracked, git_patch_untracked
pkg_name = 'ravenml'
rml_dir = Path(__file__).resolve().parent
with open(rml_dir / 'README.md', encoding='utf-8') as f... |
import open3d as o3d
import numpy as np
from numba import jit
def dataset_intrinsics(dataset='tartanair'):
if dataset == 'kitti':
focalx, focaly, centerx, centery = 707.0912, 707.0912, 601.8873, 183.1104
elif dataset == 'euroc':
focalx, focaly, centerx, centery = 458.6539916992, 457.2959899902,... |
"""Caching for this package."""
from __future__ import annotations
import json
import os.path
from typing import cast
import pywikibot
from pywikibot_extensions.page import get_redirects
import nfcbot
def _get_cache_directory() -> str:
"""Return the cache directory."""
loc = os.environ.get("XDG_CACHE_HOME"... |
from datetime import datetime
from datetime import timezone
import pytest
from aioresponses import aioresponses
from freezegun import freeze_time
from senor_octopus.sources.whistle import whistle
mock_payload = {
"pets": [
{
"id": 123456,
"gender": "f",
"name": "Rex",
... |
# Copyright (c) 2020, NVIDIA CORPORATION. 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 of source code must retain the above copyright
# notice, this list of conditio... |
#!/usr/bin/env python
import sys
from fs.opener import opener
from fs.commands.runner import Command
from fs.utils import print_fs
class FSTree(Command):
usage = """fstree [OPTION]... [PATH]
Recursively display the contents of PATH in an ascii tree"""
def get_optparse(self):
optparse = supe... |
from fortunae.fortunae import * #get_stocks, get_fiis, br_stocks, br_fiis |
# -*- coding: utf-8 -*-
import uuid
import importlib
import logging
import time
import functools
from threading import local
try:
from celery import (
Celery,
signals,
)
except ImportError:
raise ImportError('To use queue module, you must install celery.')
try:
from sqlalchemy import ... |
"""
Dot product of two vectors implemented as parallel lists
"""
from operator import add, mul
from pyske.core.util import fun
__all__ = ['opt_dot_product', 'dot_product']
# ------------------- Dot Product Variant Example -------------
def dot_product(vector1, vector2):
"""
Compute the dot product of two ... |
import sys
sys.path.append('../')
sys.path.append('../../binary_classifier')
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import math
import itertools
from tqdm import tqdm
import pickle
from sklearn.cluster import KMeans
import tensorflow as tf
from tensorflow.keras import models
reward_ta... |
#Simple assignment
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
import re
import json
import time
import random
bvre = r"https:\/\/www\.bilibili\.com\/video\/(?P<bv>BV\w+)"
options = Options()
options.page_load_strategy = 'eager'
driver = Chrome('D:/zf-download/chromed... |
import numpy as np
import cv2 as cv
from modules.Node import Node
def calculate_perimiter(bbox_image):
perimiter = 0
for row in bbox_image:
for pix in row:
if pix == 1:
perimiter += 1
return perimiter
def calculate_area(segment):
return len(segment["cordinates"])
d... |
import random
from time import sleep
nome = str(input('Olá, qual é o seu nome? '))
print('Olá {}, seja bem vindo ao nosso canal de jogos!!'.format(nome))
jogo = str(input('{}, sorteamos um jogo legal para que você conheça um pouco sobre a nossa plataforma de games, o jogo do dado. Você gostaria de conhecer esse jogo? '... |
# Assume you have a method isSubstring which checks if one word is a substring of another. given two strings, s1 and s2,
# write code to check if s2 is a rotation of s1 using only one call to isSubstring(e.g. "waterbottle" is a rotation of "erbottlewat")
def isSubtring(original,substring):
return substring in or... |
import collections
import pathlib
import numpy as np
import torch
import yolov3
def load_network(
config_path: pathlib.Path,
weights_path: pathlib.Path = None,
device: str = "cuda",
) -> yolov3.Darknet:
model = yolov3.Darknet(config_path, device=device)
if weights_path is not None:
mode... |
from time import sleep
from robit.core.alert import Alert
from robit.core.clock import Clock
from robit.core.web_client import post_worker_data_to_monitor
from robit.job.group import Group
from robit.core.health import Health
from robit.core.id import Id
from robit.core.name import Name
from robit.core.status import S... |
from flask import Flask,render_template,request,redirect,session,url_for,flash
from flask_mysqldb import MySQL
from datetime import datetime,time,date
from flask_login import LoginManager
from flask_login import login_required
from flask_mail import Mail, Message
from dateutil import relativedelta
import uuid
i... |
from .view3d import view3d
from .chemspace import chemspace
from .landing import landing
pages = {
"3DView Page" : (view3d, False),
"Chemspace" : (chemspace, False),
"Landing" : (landing, True)
} |
"""Code here is only intended for use by developers"""
import time
import pandas as pd
import numpy as np
import copy
from scipy.stats import norm
import random
def parameter_recovery_sweep(sweep_θ_true, model, design_thing, target_param_name):
print("starting parameter recovery sweep")
rows, _ = sweep_θ_tru... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.