content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# -*- coding: utf-8 -*-
'''
Provides tools to help unit test projects using pop.
For now, provides mock Hub instances.
'''
# Import python libs
import inspect
import copy
from asyncio import iscoroutinefunction
from functools import partial
# Import third party libs
try:
from asynctest.mock import create_autospec
... | python |
import pwn
def gnu_hash(s):
h = 0
h = 5381
for c in s:
h = h * 33 + ord(c)
return h & 0xffffffff
class DynELF:
def __init__(self, path, leak, base = None):
if isinstance(path, pwn.ELF):
self.elf = path
else:
self.elf = pwn.elf.load(path)
self... | python |
import os
# kepaknaga@gmail.com
def cuci():
os.system('clear')
cuci()
while True:
print('====================')
print('=====GITKU v2.0=====')
print(' 0 = git pull')
print(' 1 = git add .')
print(' 2 = git commit -m')
print(' 3 = git push')
print(' 4 = git add & commit')
print(' 5 = git diff')
print(' 6 = gi... | python |
from typing import Tuple, List
import numpy as np
from GPy.core.parameterization.priors import Prior, Gaussian
from numpy.linalg import LinAlgError
from statsmodels.stats.correlation_tools import cov_nearest
from src.autoks.backend.kernel import get_priors
from src.autoks.core.active_set import ActiveSet
from src.aut... | python |
#
# PySNMP MIB module H3C-OBJECT-INFO-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/H3C-OBJECT-INFO-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:10:08 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | python |
# 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 writing, software
# distributed under th... | python |
__author__ = 'Devesh Bajpai'
'''
https://codeforces.com/problemset/problem/381/A
Solution: This is very similar to the DP card game problem. Since the numbers are distinct, it avoids
the complex case when both the ends are same and the player would pick the side which exposes the
smaller number for next round. That w... | python |
"""This script contains the main authentication and hash generation functions"""
import subprocess
from shadow_auth._internal.classes import ShadowHash
from shadow_auth._internal.enums import Algorithm
from shadow_auth._internal.validations import (
validate_system_requirements_first
)
from shadow_auth._internal.... | python |
"""
Some simple logging functionality, inspired by rllab's logging.
Logs to a tab-separated-values file (path/to/output_directory/progress.txt)
"""
import atexit
import json
import os
import os.path as osp
import shutil
import sys
import time
import warnings
from collections import defaultdict
from pathlib import Pa... | python |
# train.py
### command> python train.py --fold 0 --model decision_tree_gini
import argparse
import os
import joblib
import pandas as pd
from sklearn import metrics
import config
import dispatcher
def run(fold, model):
# read the training data with folds
df = pd.read_csv(config.TRAINING_FILE)
# traini... | python |
from base64 import b64encode
import jinja2
import json
import os
import yaml
import kubernetes.config
import kubernetes.client
from simpleflow.utils import json_dumps
class KubernetesJob(object):
def __init__(self, job_name, domain, response):
self.job_name = job_name
self.response = response
... | python |
# coding: utf-8
from bs4 import BeautifulSoup
import requests
from urllib.parse import urljoin
import json
def main():
'''
To crawl the base url of each city, and saved the results as a json file named baseurl.
'''
url_json = {}
url = "http://www.tianqihoubao.com/aqi/"
headers = {'user-agent': 'my-app/0.0.1'}
... | python |
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import unittest
from httpglob import httpglob, path_match
class PathMatchCase(unittest.TestCase):
def test_010_path_match(self):
self.assertTrue(path_match('/v1.1.1/image_1.1.1.zip', '/v1.1.1/image_1.1.1.zip'))
def test_020_path_match(self):
se... | python |
from django.utils.translation import ugettext_lazy as _
SERVICE_TYPES = (
("HKI_MY_DATA", _("HKI_MY_DATA")),
("BERTH", _("BERTH")),
("YOUTH_MEMBERSHIP", _("YOUTH_MEMBERSHIP")),
("GODCHILDREN_OF_CULTURE", _("GODCHILDREN_OF_CULTURE")),
)
| python |
# Betül İNCE - 180401020
with open("veriler.txt", "r+") as data:
cases = []
for line in data:
cases.append(int(line))
size = len(cases)
sum_cases = sum(cases)
def first_order_polynomial():
n = len(cases)
sum_of_x = 0
sum_of_y = sum(cases)
sum_of_xiyi = 0
sum_of_xi_s... | python |
#NAME: mappingLoadTest.py
#AUTH: Ryan McCartney, EEE Undergraduate, Queen's University Belfast
#DESC: Loading Map from CSV file test
#COPY: Copyright 2019, All Rights Reserved, Ryan McCartney
import cv2 as cv
from mapping import Mapping
import time
#Initialise Mapping
map = Mapping(0.1,40,60)
print('INFO: Mappin... | python |
"""
.. module:: CClassifierLogistic
:synopsis: Logistic Regression (aka logit, MaxEnt) classifier
.. moduleauthor:: Battista Biggio <battista.biggio@unica.it>
.. moduleauthor:: Ambra Demontis <ambra.demontis@unica.it>
"""
from sklearn.linear_model import LogisticRegression
from secml.array import CArray
from secm... | python |
import csv
from io import StringIO, BytesIO
import pandas as pd
from des.models import DynamicEmailConfiguration
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.test import Client
from django.urls import reverse
from django_rq import job
from scripts.integration_test i... | python |
import os
import sys
rszdir = "/home/inopia/webapps/mlfw_media/f/rsz/"
#nqdir = thumbsdir + "png/"
l = os.listdir(rszdir)
l.sort()
for imagefile in l:
part = imagefile.lstrip("mlfw").partition(".")
ext = part[2].lower()
if part[0] in ("save", "png"):
continue
try:
iid = int(part[0].pa... | python |
import os
from d3m import utils
D3M_API_VERSION = 'v2020.1.9'
VERSION = "1.0.0"
TAG_NAME = "{git_commit}".format(git_commit=utils.current_git_commit(os.path.dirname(__file__)), )
REPOSITORY = "https://github.com/brekelma/dsbox_graphs"
PACKAGE_NAME_GRAPHS = "dsbox-graphs"
D3M_PERFORMER_TEAM = 'ISI'
if TAG_NAME:
... | python |
#!/usr/bin/python3
import pickle
import sys
import numpy as np
from scipy.stats import ks_2samp
if __name__ == "__main__":
if len(sys.argv) < 3:
print("Usage: %s [max min diff dat] [stdev dat]" % (sys.argv[0]))
exit()
def plot(dataPerExperiment):
smallestDiffMaxMin = None
smallestDiffMaxMinOperator = None
fo... | python |
# Generated by Django 3.0.1 on 2020-06-14 03:19
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('arti... | python |
# coding=utf-8
from sii.resource import SII, SIIDeregister
from sii.models.invoices_record import CRE_FACTURAS_EMITIDAS
from sii.utils import unidecode_str, VAT
from expects import *
from datetime import datetime
from spec.testing_data import DataGenerator, Tax, InvoiceLine, InvoiceTax
from mamba import *
import os
... | python |
from typing import Union
import spacy
regex = [r"\bsofa\b"]
method_regex = (
r"sofa.*?((?P<max>max\w*)|(?P<vqheures>24h\w*)|"
r"(?P<admission>admission\w*))(?P<after_value>(.|\n)*)"
)
value_regex = r".*?.[\n\W]*?(\d+)[^h\d]"
score_normalization_str = "score_normalization.sofa"
@spacy.registry.misc(score_... | python |
import cloudmesh
user = cloudmesh.load()
print user.cloudnames()
| python |
import sqlite3
con = sqlite3.connect(":memory:")
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute("select 'John' as name, 42 as age")
for row in cur:
assert row[0] == row["name"]
assert row["name"] == row["nAmE"]
assert row[1] == row["age"]
assert row[1] == row["AgE"]
con.close()
| python |
# Blog (c) by yanjl
#
# Blog is licensed under a
# Creative Commons Attribution 3.0 Unported License.
#
# You should have received a copy of the license along with this
# work. If not, see <http://creativecommons.org/licenses/by/3.0/>.
from django.contrib.auth.models import User
from django.db import models
from djan... | python |
import tablib
from collections import OrderedDict
from inspect import isclass
from sqlalchemy import create_engine,text
def _reduce_datetimes(row):
"""Receives a row, converts datetimes to strings."""
row = list(row)
for i in range(len(row)):
if hasattr(row[i], 'isoformat'):
row[i] =... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/7/26 0026 下午 5:54
# @Author : Exchris Tsai
# @Site :
# @File : imagedemo.py
# @Software: PyCharm
__author__ = 'Exchris Tsai'
import requests
import os
import urllib
import urllib.request
from bs4 import BeautifulSoup as BS
path = 'd:/images' #
t... | python |
# coding: utf-8
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department
# Distributed under the terms of "New BSD License", see the LICENSE file.
"""
The `state` module holds (almost!) all the code for defining the global state of a pyiron instance.
Such "global" beh... | python |
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "Hello, World with Flask"
@app.route('/user/<name>')
def user(name):
#example: access http://127.0.0.1:5000/user/dave
return '<h1> Hello, %s </h1>' % name
def main():
app.run(port=5000, debug=False, host='0.0.0.0')
i... | python |
# -*- coding: utf-8 -*-
import os
import re
from subprocess import PIPE, Popen
from pip.download import PipSession
from pip.req import parse_requirements
setup_py_template = """
from setuptools import setup
setup(**{0})
"""
def get_git_repo_dir():
"""
Get the directory of the current git project
Retur... | python |
# Decompiled by HTR-TECH | TAHMID RAYAT
# Github : https://github.com/htr-tech
#---------------------------------------
# Auto Dis Parser 2.2.0
# Source File : patched.pyc
# Bytecode Version : 2.7
# Time : Sun Jan 31 17:36:23 2021
#---------------------------------------
import os, sys, zlib, base64, marshal, binascii... | python |
from django.core.management.base import BaseCommand
from tracking.harvest import harvest_tracking_email
class Command(BaseCommand):
help = "Runs harvest_tracking_email to harvest points from emails"
def add_arguments(self, parser):
parser.add_argument(
'--device-type', action='store', des... | python |
# -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# 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 appl... | python |
import time
class Logging:
def logStateString(self, logStateString):
self._dt = time.strftime("%d %b %Y", time.localtime(time.time()))
self._logname = '/home/pi/PyIOT/logs/json/' + self._dt +'_log.txt'
self._stateLogFile = open(self._logname, 'a')
self._stateLogFile.write(logStateS... | python |
from testtools import TestCase
import requests_mock
from padre import channel as c
from padre import handler
from padre.handlers import tell_joke
from padre.tests import common
class TellJokeHandlerTest(TestCase):
def test_expected_handled(self):
bot = common.make_bot()
m = common.make_message(... | python |
import requests
import time
riot_token = ""
if(not riot_token):
riot_token = input("Please enter your Riot API token here, or replace variable riot_token with your token and rerun the program: \n")
summonerName = input ("Enter summoner's name: ")
url = "https://na1.api.riotgames.com/lol/summoner/v4/summ... | python |
import subprocess
import threading
import logging
import queue
import sys
if sys.version_info < (3, 0):
sys.stdout.write("Sorry, requires Python 3.x, not Python 2.x\n")
sys.exit(1)
def ps(hosts, grep_filter):
output = []
q = queue.Queue(len(hosts))
def work(host, grep_filter):
cmd = ['/bi... | python |
from datetime import datetime, timedelta
from src.utils.generation import (
create_appointment,
create_appointment_patient_doctor_relation,
create_patient,
)
def populate(is_print=False):
patient = create_patient(is_print=is_print)
base_datetime = datetime.today()
datetimes_of_appointments = ... | python |
"""
This file contains methods to attempt to parse horrible Specchio data into some coherent format.
This is only used in the case that reflectance and transmittance measurements have to be
loaded in separate files in separate folders one by one from specchio.ch web interface. The code is
a mess but one should not hav... | python |
import json
from django.conf import settings
from django.contrib.auth.decorators import permission_required, login_required
from django.contrib import messages
from django.urls import reverse
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_protect
from django.shortcuts... | python |
#!/usr/bin/env python3
from ev3dev2.motor import MoveTank, OUTPUT_A, OUTPUT_D
from ev3dev2.button import Button
from ev3dev2.sensor.lego import ColorSensor
from ev3dev2.display import Display
from time import sleep
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(levelna... | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 28 12:25:51 2019
@author: Asier
"""
# Fourth: Production-style FizzBuzz. The horror.
# While I won't be adding __init__.py to this doodles folder, pretend it's there so this would be importable
# Finished in 30:24.49
"""
fizzbuzz takes a starting and stopping integer a... | python |
from code.classes.aminoacid import AminoAcid
from code.classes.protein import Protein
import random
import copy
class Random():
'''
Algorithm that folds the amino acids in the protein at random.
'''
def __init__(self):
self.protein = None
self.best = [0, {}]
self.sol_dict = {}
... | python |
"""
Copyright [2009-2019] EMBL-European Bioinformatics Institute
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 a... | python |
###############################################################################
# Project: PLC Simulator
# Purpose: Class to encapsulate the IO manager functionality
# Author: Paul M. Breen
# Date: 2018-07-17
###############################################################################
import logging
import thre... | python |
from django.urls import path
from api import view as local_view
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('top-movie/', local_view.top_movie),
path('detail-movie/<int:id>', local_view.detail_movie),
] +static(settings.STATIC_URL, document_root=settings.... | python |
import os
import time
import random
import tkinter
import threading
import subprocess
import glob
from ascii_art import *
from widgets import *
import platform
platform = platform.system()
# thanks to everyone on https://www.asciiart.eu/
class FILE_HANDLER(object):
""" File opening and closing yes"""
def __init__... | python |
#!/usr/bin/env python
# coding: utf-8
import os
import numpy as np
import pandas as pd
import matplotlib.pylab as pylab
import matplotlib.pyplot as plt
import matplotlib.artist as martist
from matplotlib.offsetbox import AnchoredText
import pylab as plt
os.chdir('/Users/pauline/Documents/Python')
df = pd.read_csv("Tab... | python |
import sys
import os
from subprocess import (Popen, PIPE, STDOUT)
APP = os.path.abspath(os.path.join(os.path.dirname(__file__), 'run.py'))
"""The Python script to run."""
def spawn():
"""
Start the Quantitaive Imaging Profile REST server.
:return: the completed process return code
"""
# The ... | python |
#! /usr/bin/env python
import logging
import os
import sys
gitpath=os.path.expanduser("~/git/cafa4")
sys.path.append(gitpath)
from fastcafa.fastcafa import *
gitpath=os.path.expanduser("~/git/pyEGAD")
sys.path.append(gitpath)
from egad.egad import *
#SALMON_NET=os.path.expanduser('~/data/cococonet/atlanticsalmon_p... | python |
'''
Created on Feb 7, 2011
@author: patnaik
'''
import sys
import time
from collections import defaultdict
from parallel_episode_mine import load_episodes
from itertools import izip
from numpy import diff
from math import sqrt
class S(object):
def __init__(self, alpha, event):
self.alpha = alpha
... | python |
#!/usr/bin/env python
"""
Copyright (C) 2018 Intel 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 ag... | python |
import hashlib
from pyxbincodec import CodecUtils
from pyxbincodec import PixBlockDecoder
class PixBinDecoder:
"""docstring for """
def __init__(self):
self.MAGIC_NUMBER = "PIXPIPE_PIXBIN"
self._verifyChecksum = False
self._input = None
self._output = None
... | python |
from xsbs.events import registerServerEventHandler
from xsbs.players import player
import logging
event_handlers = (
('player_connect', lambda x: logging.info(
'connect: %s (%i)' % (player(x).name(), x))
),
('player_disconnect', lambda x: logging.info(
'disconnect: %s (%i)' % (player(x).name(), x))
),
('pl... | python |
import setuptools
with open('README.md') as readme_file:
long_description = readme_file.read()
setuptools.setup(
name='aioevproc',
version='0.1.0',
author='Anton Bryzgalov',
author_email='tony.bryzgaloff@gmail.com',
description='Minimal async/sync event processing framework on pure Python',
... | python |
from flask import Flask, request
import os
import json
import socket
app = Flask(__name__)
@app.route('/dostep/<time>&<inputnames>&<inputvalues>&<outputnames>')
def step(time, inputnames, inputvalues, outputnames):
data = _parse_url(time, inputnames, inputvalues, outputnames)
outputs = [data['input1'] * data[... | python |
import pygame
import sys
import random
from ..env_var.env_var import *
from pygame.locals import *
from ..geometry import vector
class Ball (object):
def __init__(self):
random.seed()
self.text = chr(random.randrange(ord('A'), ord('Z')))
pygame.init()
self.color = ball_color
... | python |
import pandas as pd
import re
import os
def _export(data_dir):
file = "State Exports by NAICS Commodities.csv"
t = pd.read_csv(os.path.join(data_dir, file), skiprows=3, engine="c")
t.dropna(how="all", axis=1, inplace=True)
# rename in order to aid in joining with import data later
t.rename(colum... | python |
# -*- coding: utf-8 -*-
# vispy: testskip (KNOWNFAIL)
# Copyright (c) 2015, Felix Schill.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
"""
Simple demonstration of mouse drawing and editing of a line plot.
This demo extends the Line visual from scene adding mouse events that allow
modificat... | python |
#!/usr/bin/env python
f = open('new.txt')
lines = f.readlines()
for line in lines:
print(line.split()[8])
| python |
import NsgaII
import random
# Non-dominated Ranking Genetic Algorithm (NRGA)
class Ngra(NsgaII.NsgaII):
# Initializes genetic algorithm
def __init__(self, configuration, numberOfCrossoverPoints=2, mutationSize=2, crossoverProbability=80,
mutationProbability=3):
NsgaII.NsgaII.__init__(... | python |
import torch
from torch import nn
from allennlp.modules.span_extractors import SelfAttentiveSpanExtractor
class SpanClassifierModule(nn.Module):
def _make_span_extractor(self):
return SelfAttentiveSpanExtractor(self.proj_dim)
def _make_cnn_layer(self, d_inp):
"""
Make a CNN layer as a... | python |
# run some simple select tests
import psycopg2 as psy
import simplejson as json
import argparse
import setup_db
def find_all_studies(cursor,config_obj):
STUDYTABLE = config_obj.get('database_tables','studytable')
sqlstring = "SELECT id FROM {t};".format(t=STUDYTABLE)
cursor.execute(sqlstring)
print "re... | python |
#!/usr/bin/env python3
try:
from flask import Flask
except ImportError:
print ("\n[X] Please install Flask:")
print (" $ pip install flask\n")
exit()
from wordpot import app, pm, parse_options, check_options
from wordpot.logger import *
import os
check_options()
if __name__ == '__main__':
par... | python |
import pyglet
from pyglet.gl import *
class Camera:
def __init__(self, width: float, height: float, position: list, zoom: float):
self.width = float(width)
self.height = float(height)
self.position = list(position)
self.zoom = float(zoom)
def left(self):
return self.pos... | python |
from nnf import Var
from lib204 import Encoding
import geopy
import geopy.distance
from geopy.geocoders import Nominatim
import pyproj
#factors that might affect the trips
virus = Var('virus') # 🦠
documents = Var('documents') # document
international = Var('international') # crossing the border
toll_money = Var('mon... | python |
"""
.. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de>
"""
import numpy as np
import pytest
from .. import PolarGrid, SphericalGrid
from ..boundaries.local import NeumannBC
@pytest.mark.parametrize("grid_class", [PolarGrid, SphericalGrid])
def test_spherical_base_bcs(grid_class):
""" test setting boundary ... | python |
# Copyright (c) 2008-2012 by Enthought, Inc.
# All rights reserved.
import sys
from setuptools import setup
setup_data = {}
execfile('setup_data.py', setup_data)
INFO = setup_data['INFO']
if 'develop' in sys.argv:
INFO['install_requires'] = []
# The actual setup call.
setup(
name = 'ets',
version = INF... | python |
def dobro(n):
d = n * 2
return d
def metade(n):
d = n / 2
return d
def aumento(n):
d = n + n * 10 / 100
return d
def reduzir(n):
d = n - (n * 13 / 100)
return d
| python |
# -*- coding: utf-8 -*-
import unittest
import numpy as np
import turret
import turret.layers as L
from util import execute_inference
class BasicMathTest(unittest.TestCase):
def test_sum_ternary(self):
N, C, H, W = 3, 5, 7, 11
input0 = np.random.rand(N, C, H, W).astype(np.float32)
input... | python |
from fastatomography.util import *
from scipy.io import loadmat, savemat
# %%
path = '/home/philipp/projects2/tomo/2019-03-18_Pd_loop/'
# path = '/home/philipp/projects2/tomo/2018-07-03-Pdcoating_few_proj/sample synthesis date 20180615-Pd coating/'
# path = '/home/philipp/projects2/tomo/2019-04-17-Pd_helix/philipp/'
fn... | python |
# Copyright 2021 University of Manchester
#
# 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 t... | python |
__all__ = ["Process", "ProcessError"]
import os
import sys
import shlex
import queue
import select
import logging
import subprocess
import collections
import threading
from itertools import chain
from dataclasses import dataclass
from typing import Sequence, Mapping
def poll(fd: int, stop_event: threading.Event,
... | python |
# Copyright 2017 The TensorFlow 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 applica... | python |
from pymongo import MongoClient
from pymongo.database import Database
import json
import os
from asset_manager.models.models import Asset, License
def connect_db(connection_string: str, database_name: str) -> Database:
client = MongoClient(connection_string)
return client.get_database(database_name)
def ini... | python |
from __future__ import annotations
import csv
import gzip
import json
import os
import shutil
import time
from typing import Iterator
from decouple import config
from light_controller.const import MODE_BRIGHTNESS, MODE_COLOR_TEMP, MODE_HS
from light_controller.controller import LightController
from light_controller.h... | python |
#!/usr/bin/python
"""
Euclid covariance matrices, taken from arXiv:1206.1225
"""
import numpy as np
def covmat_for_fom(sig_x, sig_y, fom, sgn=1.):
"""
Return covariance matrix, given sigma_x, sigma_y, and a FOM. Diagonal
elements are unique up to a sign (which must be input manually).
(N.B. In fi... | python |
from spotcli.configuration.configuration import load
__all__ = ["load"]
| python |
from mathutils import Vector, Matrix, Euler, Quaternion
from typing import List
def convert_source_rotation(rot: List[float]):
qrot = Quaternion([rot[0], rot[1], -rot[3], rot[2]])
# qrot.rotate(Euler([0, 0, 90]))
return qrot
def convert_source_position(pos: List[float]):
pos = Vector([pos[0], pos[2]... | python |
# from vocab import Vocab
# from tr_embed import TREmbed | python |
def hidden_layer_backpropagate(layer, prev_outputs, outputs, next_weights_totlin, rate):
tot_lin = []
weights = []
i = 0
for (n, o) in zip(layer, outputs):
op_lin = n.activation_d(o)
total_op = 0
for w, tl in zip(next_weights_totlin["w"], next_weights_totlin["tl"]):
... | python |
#!/usr/bin/python
# code from https://www.raspberrypi.org/forums/viewtopic.php?t=220247#p1352169
# pip3 install pigpio
# git clone https://github.com/stripcode/pigpio-stepper-motor
'''
# connection to adafruit TB6612
# motor: SY28STH32-0674A
Vcmotor --> 12V 5A power supply
VM --> floating
Vcc --> 3V3 Pin 17
GND --> G... | python |
import unittest
from linkml.generators.markdowngen import MarkdownGenerator
from linkml.utils.schemaloader import SchemaLoader
from linkml.utils.yamlutils import as_yaml
from tests.utils.test_environment import TestEnvironmentTestCase
from tests.test_issues.environment import env
class Issue63TestCase(TestEnvironmen... | python |
# import gevent.monkey;gevent.monkey.patch_all()
import time
from funboost import boost, BrokerEnum,run_consumer_with_multi_process,ConcurrentModeEnum
import nb_log
logger = nb_log.get_logger('sdsda',is_add_stream_handler=False,log_filename='xxx.log')
@boost('20000', broker_kind=BrokerEnum.REDIS, concurrent_num=2, ... | python |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | python |
__all__ = ['MASKED', 'NOMASK']
MASKED = object()
NOMASK = object()
| python |
from torchreid import metrics
from torchreid.utils import re_ranking
import numpy as np
import torch
from torch.nn import functional as F
if __name__ == '__main__':
ff = torch.load('train_avg_feature.pt')
f_pids = np.load('train_pids.npy')
f_camids = np.load('train_camids.npy')
# eval_index = 5... | python |
# General imports
import os, json, logging, yaml, sys
import click
from luna.common.custom_logger import init_logger
init_logger()
logger = logging.getLogger('generate_tiles')
from luna.common.utils import cli_runner
_params_ = [('input_slide_image', str), ('output_dir', str), ('tile_size', int), ('batch_size', i... | python |
"""
sudoku.py -- scrape common web sources for Sudokus
"""
import json
from datetime import datetime
from dataclasses import dataclass
import requests
from bs4 import BeautifulSoup
sudokuexchange_head = "https://sudokuexchange.com/play/?s="
@dataclass
class Puzzle:
name: str
source_url: str
sudokuexcha... | python |
from .BaseWriter import TensorboardWriter
from .visual import * | python |
from .chat import Chat
from .livestream import Livestream
from .message import Message
from .tiny_models import *
from .user import User | python |
import click
import maldnsbl
from collections import Counter
import json
import sys
# Utlity Functions
def iterate_report(report,sep=': '):
"""Converts an iterable into a string for output
Will take a list or dicitonary and convert it to a string where
each item in the iterable is joined by linebreaks (\... | python |
from rest_framework.reverse import reverse_lazy
def get_detail_url(obj, url_name, request):
url_kwargs = {
'pk': obj.id,
}
return reverse_lazy(url_name, kwargs=url_kwargs, request=request)
# def get_base_fields():
# return [
# 'unique_id',
# 'integration_code'
# ]
# def... | python |
from datetime import date
from email import message
from vigilancia.order_screenshot import Orders
from django.db.models.fields import DateField
from django.http import Http404
from django.http import HttpResponse
from django.template import loader
from django.shortcuts import get_object_or_404, render
from .models imp... | python |
import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from .utils import *
from .addons import *
import qcdb
_ref_h2o_pk_rhf = -76.02696997325441
_ref_ch2_pk_uhf = -38.925088643363665
_ref_ch2_pk_rohf = -38.91973113928147
@using_psi4
def test_tu1_rhf_a():
"""tu1-h2o-energy/input.dat
glob... | python |
from .naive_bayes import NaiveBayes
| python |
import os
import codecs
import sqlite3
import re
from flask import Flask, render_template, abort, request, Response, g, jsonify, redirect, url_for
app = Flask(__name__)
if os.getenv('FLASK_ENV', 'production') == 'production':
debug = False
else:
debug = True
app.config.update(
DATADIR='pages',
IMGDIR=... | python |
import matplotlib.pyplot as plt
plt.plot()
plt.show() | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.