content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
# TemperatureConverter Tests import unittest from TemperatureConverter import TemperatureConverter from TemperatureErrors import * class KnownValues(unittest.TestCase): knownValues = ( (0, 32), (100, 212) ) temp_converter = TemperatureConverter() # test value conversions def testCtoF(self): ""...
nilq/baby-python
python
# Reads float and prints BRL money conversion to JPY # In 2020/11/01 JP¥ 1.00 = R$ 0.060 :) brl = float(input('Por favor, digite quanto dinheiro você tem na carteira: R$ ')) jpy = brl / 0.060 print('Com R$ {:.2f} você pode comprar ¥ {:.2f}.'.format(brl, jpy))
nilq/baby-python
python
def print_error(message): print("An error occured: " + message) def remove_white_chars(line): line = line.replace('\t', '') line = line.replace(' ', '') line = line.replace('\n', '') line = line.replace('\r', '') return line def remove_comments_and_empty_lines(text): new_text = '' fi...
nilq/baby-python
python
import os import logging from dp4py_config.section import Section from dp4py_config.utils import bool_env from dp4py_sanic.config import CONFIG as SANIC_CONFIG from dp_conceptual_search.config.utils import read_git_sha def get_log_level(variable: str, default: str="INFO"): """ Returns the configured log le...
nilq/baby-python
python
from federatedscope.tabular.model.quadratic import QuadraticModel __all__ = ['QuadraticModel']
nilq/baby-python
python
string = """0: "HOW ResidentSleeper LONG ResidentSleeper CAN ResidentSleeper THIS ResidentSleeper GO ResidentSleeper ON ResidentSleeper" 1: "REPPIN LONDON ONTARIO 519 GANG" 2: "my eyes" 3: "CLULG" 4: "ResidentSleeper" 5: "mvp ward" 6: "4Head EU WATCHING NA 4Head STILL AWAKE 4Head NO JOB 4Head NO RESPONSIBILITIES 4Head ...
nilq/baby-python
python
# Copyright 2015 Tesora Inc. # 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 a...
nilq/baby-python
python
from reading import Maze, MazeReader class Node(object): """Nodes for evolving in graph.""" def __init__(self, maze, x, y, parent=None): """Initialize node. Keep maze, parent, and position.""" self.maze = maze self.x = x self.y = y self.parent = parent self.up = ...
nilq/baby-python
python
import pyps from sys import argv if len(argv) == 1: # this source include a main() with a call to foo() ; but foo() isn't defined ! w=pyps.workspace("broker01.c") # We give a method to resolve missing module (here foo()) w.props.preprocessor_missing_file_handling="external_resolver" w.props.pre...
nilq/baby-python
python
from typing import Any, Dict, Tuple from dateutil.parser import parse from great_expectations.execution_engine import PandasExecutionEngine from great_expectations.execution_engine.execution_engine import ( MetricDomainTypes, MetricPartialFunctionTypes, ) from great_expectations.expectations.metrics.map_metri...
nilq/baby-python
python
from authlib.common.urls import quote, unquote def escape(s): return quote(s, safe=b'~') def unescape(s): return unquote(s)
nilq/baby-python
python
import json from typing import Optional import pyrebase from .database import Database class FirebaseDatabase(Database): def __init__(self, serialised_config: str): super().__init__() self.config = json.loads(serialised_config) def add_document(self, doc_id: str, doc: dict) -> None: ...
nilq/baby-python
python
from .s3 import *
nilq/baby-python
python
#!/usr/bin/env python3 """ Get jobs from aCT. Returns: 1: No proxy found. 2: One of the elements in job list is not a range. 3: One of the elements in job list is not a valid ID. 5: tmp directory not configured. """ import argparse import sys import shutil import os import logging import act.client...
nilq/baby-python
python
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="Turkish Topic Model", version="0.0.1", author="Ali ÇİMEN, Sevinç GÜLSEÇEN", author_email="cimenwd@gmailcom, gulsecen@istanbul.edu.tr", description="Türkçe metin ön işleme ve konu analizi k...
nilq/baby-python
python
import pandas from sklearn.model_selection import train_test_split def add_series(X, y, name): """Converts list (y) to pd.Series with name (name) then adds it to a dataframe (X)""" X = X.copy() series = pandas.Series(data=y, name=name) X[name] = series return X def data_split(X): """Spl...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models import re class ResCompany(models.Model): _inherit = 'res.company' org_number = fields.Char(compute='_compute_org_number') @api.depends('vat') def _compute_org_num...
nilq/baby-python
python
import numpy as np from ..functions import B_nu, dB_nu_dT from ..integrate import integrate_loglog from ..constants import sigma, k, c def test_b_nu(): nu = np.logspace(-20, 20., 10000) for T in [10, 100, 1000, 10000]: # Compute planck function b = B_nu(nu, T) # Check that the int...
nilq/baby-python
python
"""Myia Pytorch frontend.""" from .pytorch import *
nilq/baby-python
python
""" Dictionary Embedder Class """ import spacy from .base import BaseEmbedder class DictionaryEmbedder(BaseEmbedder): """Base Embedder class extended for implementing text embedders""" def __init__(self, spacy_pkg='en_vectors_web_lg', embedding_length=None): super(DictionaryEmbedder, self).__init__...
nilq/baby-python
python
# -*- coding: utf-8 -*- """Tests for Terminal methods that account for sequences in strings""" # std imports import os import sys import struct import platform import itertools # 3rd party import six import pytest # local from .accessories import TestTerminal, as_subprocess from .conftest import IS_WINDOWS if platf...
nilq/baby-python
python
def get_token(fi='dont.mess.with.me'): with open(fi, 'r') as f: return f.readline().strip() t = get_token()
nilq/baby-python
python
import re from address_extractor import ( unit_type, zipcode, street_direction, street_type, cities, ) class InvalidAddressError(Exception): pass class Address(object): def __init__(self, tokens): self.tokens = tuple(self._clean_tokens(tokens[:11])) self.street_number_ind...
nilq/baby-python
python
import os.path from newsplease.pipeline.pipelines.elements.extracted_information_storage import ExtractedInformationStorage class HtmlFileStorage(ExtractedInformationStorage): """ Handles storage of the file on the local system """ # Save the html and filename to the local storage folder def pro...
nilq/baby-python
python
import json from decimal import Decimal import jwt from django.core import mail from mock import patch from nose.tools import eq_, ok_ from amo import CONTRIB_PENDING, CONTRIB_PURCHASE from amo.tests import TestCase from amo.urlresolvers import reverse from constants.payments import PROVIDER_BANGO from market.models...
nilq/baby-python
python
from matplotlib import pyplot as plt from matplotlib import cm from matplotlib import animation from optimisation import FireflyOptimizer import numpy as np from optimisation import Ackley f_alg = FireflyOptimizer(population_size=10, problem_dim=2, generations=100) func = Ackley(2) N = 100 x = np.linspace(-5, 5, N) ...
nilq/baby-python
python
import socket import pickle import pandas as pd import matplotlib.pyplot as plt def graph_setting(): plt.ion() fig, ax = plt.subplots() return ax def data_get(df, conn, i): data = conn.recv(1024) data = float(pickle.loads(data)) df_temp = pd.DataFrame([[data]], columns=['data'...
nilq/baby-python
python
import re from csv import DictReader, DictWriter from .utils import get_headers class Dataset(object): def __init__(self, key=None, headers=None, data=None): self.headers = headers self.data = data self.key = key def write(self, fd, delim='\t'): writer = DictWriter(fd, self.he...
nilq/baby-python
python
from telnetlib import Telnet from uuid import uuid4 from time import sleep from hashlib import md5 from os import chmod from re import compile as compile_regex from sys import version_info from .abstractremoteshell import AbstractRemoteShell from .shellresult import ShellResult from .streamreader import PrefixedStream...
nilq/baby-python
python
""" 二分探索 <最悪実行時間に関する漸化式> T(n) = | Θ(1) if n = 1 | T(n/2) + c if n > 1 ループの度に検査範囲が半減するので、Θ(lgn)となる。 """ def binary_search(A, v): left = 0 right = len(A) - 1 while left <= right: i = (left + right) // 2 if v < A[i]: right = i - 1 ...
nilq/baby-python
python
# # RawIO # Copyright (c) 2021 Yusuf Olokoba. # from cv2 import findTransformECC, MOTION_TRANSLATION, TERM_CRITERIA_COUNT, TERM_CRITERIA_EPS from numpy import asarray, eye, float32 from PIL import Image from sklearn.feature_extraction.image import extract_patches_2d from typing import Callable def markov_similar...
nilq/baby-python
python
import numpy as np from glob import glob import os from sklearn.model_selection import train_test_split base_path = "/media/ml/data_ml/EEG/deepsleepnet/data_npy" files = glob(os.path.join(base_path, "*.npz")) train_val, test = train_test_split(files, test_size=0.15, random_state=1337) train, val = train_test_split(t...
nilq/baby-python
python
from ..game import Actor def test_id(): actor1 = Actor() actor2 = Actor() assert actor1.id assert actor2.id assert actor1.id != actor2.id def test_add_food(): actor = Actor() assert actor.food == 0 actor.add_food(10) assert actor.food == 10 actor.add_food(5) assert act...
nilq/baby-python
python
import deepmerge import functools import importlib import logging import yaml from inspect import getmembers, isfunction from urllib import parse, request from wcmatch import fnmatch from . import macros, middleware log = logging.getLogger("netbox_rbac") # Collect all public functions from macros. functions = [ ...
nilq/baby-python
python
from django.core.paginator import Paginator from django.shortcuts import redirect, render, get_object_or_404 from comps.models.comp import Comp from comps.models.heat import Heat from comps.models.heatlist_error import Heatlist_Error def delete_heatlist_error(request, error_id): heatlist_error = get_object_or_404...
nilq/baby-python
python
# Generated by Django 3.0.6 on 2020-06-12 16:27 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('My_Account', '0017_auto_20200612_1522'), ] operations = [ migrations.RenameField( model_name='sharing_image', old_name='Like...
nilq/baby-python
python
import pygame from pygame.locals import * from GUI.Colours import Colours from GUI.Measures import Measures from GUI.Point import Point from GUI.BarPoint import BarPoint from GUI.BearoffPoint import BearoffPoint from GUI.Checker import Checker class GUIBoard: def __init__(self): pass de...
nilq/baby-python
python
from cloud_scanner_azure.config.azure_credential_config import ( AzureCredentialConfig) class AzureResourceServiceConfig: """Configuration required for usage of AzureResourceService.""" def __init__(self, subscription_id, creds: AzureCredentialConfig): self.credentials = creds self.subscr...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Imports import sys,re,os import glob import numpy as n # Script information __author__ = "Sergi Rodà Llordés" __version__ ="1.0" __maintainer__="Sergi Rodà Llordés" __email__="sergi.rodallordes@bsc.es" class pKa: def __init__(self,PDB,Ser_residue): self.__PDB = PDB sel...
nilq/baby-python
python
from rest_framework import serializers from products.models import Product, Category class CategorySerializer(serializers.ModelSerializer): id = serializers.IntegerField() class Meta: model = Category fields = ("id", "name") class ProductSerializer(serializers.ModelSerializer): class M...
nilq/baby-python
python
import datetime import json import discord from discord.ext import commands import requests ''' スプラトゥーン2絡みのコマンド ''' class Splatoon2(commands.Cog, name='スプラトゥーン2'): def __init__(self, bot): self.bot = bot @commands.command(name='バイトシフト') async def say_salmon_schedule(self, ctx):...
nilq/baby-python
python
from django.db import models # Create your models here. from django_countries.fields import CountryField from django.contrib.gis.db import models from django.db.models import Manager as GeoManager class Site(models.Model): id = models.AutoField(primary_key=True) site = models.CharField('Site name', max_lengt...
nilq/baby-python
python
#!/usr/bin/env python # Pull out yearly precipitation # Daryl Herzmann 26 Jul 2004 import pg, dbflib, mx.DateTime, shutil, shapelib from pyIEM import wellknowntext mydb = pg.connect('wepp','iemdb') sts = mx.DateTime.DateTime(2005,3,1) ets = mx.DateTime.DateTime(2005,11,1) interval = mx.DateTime.RelativeDateTime(days=...
nilq/baby-python
python
#!/usr/bin/env python # # Simple websocket server to perform signaling. # import asyncio import binascii import os import websockets clients = {} async def echo(websocket, path): client_id = binascii.hexlify(os.urandom(8)) clients[client_id] = websocket try: async for message in websocket: ...
nilq/baby-python
python
import sys import traceback import logging from glass import http from . import highlight ERROR_TEMPLATE = ''' <title>{code} {title}</title> <h1>{title}</h1> <p>{description}</p> ''' logger = logging.getLogger('glass.app') class HTTPError(Exception): code = 500 description = "Internal Server Error" def ...
nilq/baby-python
python
""" An evolving population of genotypes(Ideally for optimizing network hyperparameters). See genotype constraint docs in spikey/meta/series. Examples -------- .. code-block:: python metagame = EvolveNetwork(GenericLoop(network, game, **params), **metagame_config,) population = Population(metagame, **pop_conf...
nilq/baby-python
python
#!/usr/bin/env python from setuptools import setup, find_packages packages = ['eda.' + p for p in find_packages('eda', exclude=['test', 'test*', '*.t'])] packages.append('eda') #packages=['eda', 'eda.components', 'eda.components.ST', 'eda.circuits'], setup( name='EDA', version='1.0.1', author='Pawe...
nilq/baby-python
python
import gym import retro import os import numpy as np from PIL import Image from gym import spaces from collections import deque import cv2 SCRIPT_DIR = os.getcwd() #os.path.dirname(os.path.abspath(__file__)) # Taken from: https://gitlab.cs.duke.edu/mark-nemecek/vel/-/blob/cfa17ddd8c328331076b3992449665ccd2471bd3/vel...
nilq/baby-python
python
import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap fig, axes = plt.subplots(2, 1) axes[0].set_title("Hammer projection") map = Basemap(projection='hammer', lon_0 = 10, lat_0 = 50, ax=axes[0]) map.drawmapboundary(fill_color='aqua') map.fillcontinents(color='coral',lake_color='aqua') map.drawcoas...
nilq/baby-python
python
""" Forward-ports of types from Python 2 for use with Python 3: - ``basestring``: equivalent to ``(str, bytes)`` in ``isinstance`` checks - ``dict``: with list-producing .keys() etc. methods - ``str``: bytes-like, but iterating over them doesn't product integers - ``long``: alias of Py3 int with ``L`` suffix in the ``...
nilq/baby-python
python
from pycocotools.coco import COCO import matplotlib.pyplot as plt import cv2 import os import numpy as np import random import torch import torchvision.transforms as transforms from torch.utils.data import DataLoader,Dataset from skimage import io,transform import matplotlib.pyplot as plt import os import torch from ...
nilq/baby-python
python
import LAMMPyS as lp steps = lp.Steps('test.dump') step = steps[-1] atoms = step.atoms
nilq/baby-python
python
def do_training(train, train_labels, test, test_labels, num_classes): #set TensorFlow logging level to INFO tf.logging.set_verbosity(tf.logging.INFO) # Build 2 hidden layer DNN with 10, 10 units respectively. classifier = tf.estimator.DNNClassifier( # Compute feature_columns from dataframe keys...
nilq/baby-python
python
from __future__ import absolute_import import abc class Writer(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def text(self, text): pass @abc.abstractmethod def start(self, name, attributes=None): pass @abc.abstractmethod def end(self, name): p...
nilq/baby-python
python
import utime import machine from machine import Timer, Pin, RTC import time import ntptime import micropython import config import control import mqtt_reporting def set_ntp_time(timer): ntptime.host = "tempus1.gum.gov.pl" for i in range(1,10): try: t = ntptime.time() tm = utime....
nilq/baby-python
python
import pytest from pathlib import Path from yalul.lex.scanners.grouping import GroupingScanner from yalul.lex.token_type import TokenType @pytest.fixture(scope='function') def open_file(request): return open(str(Path.cwd()) + "/tests/lex_examples/" + request.param) class TestShouldLex: def test_when_is_left...
nilq/baby-python
python
{"filter":false,"title":"bot.py","tooltip":"/bot.py","undoManager":{"mark":53,"position":53,"stack":[[{"start":{"row":163,"column":18},"end":{"row":163,"column":35},"action":"remove","lines":["BOT_USERNAME_HERE"],"id":2},{"start":{"row":163,"column":18},"end":{"row":163,"column":19},"action":"insert","lines":["k"]}],[{...
nilq/baby-python
python
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz 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 limitation the rights to use, copy, modify, merg...
nilq/baby-python
python
class Solution: def minDeletionSize(self, A: List[str]) -> int: return sum(list(column) != sorted(column) for column in zip(*A))
nilq/baby-python
python
import sys import os import os.path import re import shutil from setuptools import setup from setuptools.command.install_lib import install_lib from setuptools.command.install import install import setuptools.command.bdist_egg import distutils.spawn import subprocess import sys import glob exclude_directories = lambda...
nilq/baby-python
python
from dataclasses import dataclass from bindings.csw.graph_style_type import GraphStyleType __NAMESPACE__ = "http://www.opengis.net/gml" @dataclass class GraphStyle1(GraphStyleType): """The style descriptor for a graph consisting of a number of features. Describes graph-specific style attributes. """ ...
nilq/baby-python
python
##################################################### ## librealsense streams test ## ##################################################### # This assumes .so file is found on the same directory import pyrealsense2 as rs # Prettier prints for reverse-engineering from pprint import pprint # Get r...
nilq/baby-python
python
# ██████ ██▓ ▄▄▄ ██▒ █▓ ██▓ ▄████▄ ██▓███ ██▓▒██ ██▒▓█████ ██▓ # ▒██ ▒ ▓██▒ ▒████▄ ▓██░ █▒▓██▒▒██▀ ▀█ ▓██░ ██▒▓██▒▒▒ █ █ ▒░▓█ ▀ ▓██▒ # ░ ▓██▄ ▒██░ ▒██ ▀█▄▓██ █▒░▒██▒▒▓█ ▄ ▓██░ ██▓▒▒██▒░░ █ ░▒███ ▒██░ # ▒ ██▒▒██░ ░██▄▄▄▄██▒██ █░░░██░▒▓▓▄ ▄██▒ ▒██▄█▓...
nilq/baby-python
python
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: tensorflow/core/protobuf/worker_service.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.prot...
nilq/baby-python
python
def validate_cell(cell: tuple) -> tuple: x, y = cell if x == 6: x = 0 elif x == -1: x = 5 if y == 6: y = 0 elif y == -1: y = 5 return x, y def get_cell(cell: tuple, field: list) -> str: row, col = cell return field[row][col] def set_cell(cell: tuple, f...
nilq/baby-python
python
# nukedatastore tests import pytest import datetime from nukedatastore import NukeDataStore, NukeDataStoreError def test_datastore_crud(datastore): datastore['project_data'] = {'id': 1234, 'name': 'project name'} assert len(datastore.list()) == 1 assert datastore.list()[0] == 'project_data' assert da...
nilq/baby-python
python
# Copyright (c) 2020 Graphcore Ltd. # Copyright 2018 Google LLC # # 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...
nilq/baby-python
python
import torch import warprnnt_pytorch as warp_rnnt from torch.autograd import Function from torch.nn import Module from .warp_rnnt import * __all__ = ['rnnt_loss', 'RNNTLoss'] class _RNNT(Function): @staticmethod def forward(ctx, acts, labels, act_lens, label_lens, blank, reduction): """ acts:...
nilq/baby-python
python
from utils import color from browser import help import random def get(cmds, typ, add_attr=None): ''' USE: error.get(cmds, type, [optional:add_attr]) where add_attr must be < 3 Description: Returns a correctly colored message according to declared "typ" ''' #---------------------------------------------------...
nilq/baby-python
python
from brownie import accounts, PassiveStrategy from brownie.network.gas.strategies import ExponentialScalingStrategy import os STRATEGIES = [ # "0x40C36799490042b31Efc4D3A7F8BDe5D3cB03526", # V0 ETH/USDT # "0xA6803E6164EE978d8C511AfB23BA49AE0ae0C1C3", # old V1 ETH/USDC # "0x5503bB32a0E37A1F0B8F8F...
nilq/baby-python
python
from typing import Any import pandas as pd from anubis.models import Submission, Assignment from anubis.utils.cache import cache def get_submissions(course_id: str) -> pd.DataFrame: """ Get all submissions from visible assignments, and put them in a dataframe :return: """ # Get the submission s...
nilq/baby-python
python
# jsb/socklib/partyline.py # # """ provide partyline functionality .. manage dcc sockets. """ __copyright__ = 'this file is in the public domain' __author__ = 'Aim' ## jsb imports from jsb.lib.fleet import getfleet from jsb.utils.exception import handle_exception from jsb.lib.threads import start_new_thread from j...
nilq/baby-python
python
from __future__ import unicode_literals from builtins import str import six @six.python_2_unicode_compatible class TokenSet: """ A token set is used to store the unique list of all tokens within an index. Token sets are also used to represent an incoming query to the index, this query token set and ...
nilq/baby-python
python
################################################################################# # The Institute for the Design of Advanced Energy Systems Integrated Platform # Framework (IDAES IP) was produced under the DOE Institute for the # Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021 # by the softwar...
nilq/baby-python
python
# coding: utf-8 import numpy as np import matplotlib.pyplot as plt import random def busqueda_local(solucion_inicial, evaluacion, obtener_vecinos, T_max, T_min, reduccion): """ Simulated Annealing. """ from random import random solucion_mejor = solucion_actual = soluc...
nilq/baby-python
python
#!/usr/bin/python3 #-*-coding:utf-8-*- from threading import Thread import pymysql from Sqlcore import Sqlcore ''' 入口功能 ''' '''vmode打印显示模式full/standard/simple''' #生产环境的photo相册 conn = {"hostname":"xxxxxx.mysql.rds.aliyuncs.com","username":"forpython","password":"Ffu398fh_GFUPY","database":"dbuser","hostport":3708...
nilq/baby-python
python
#!/usr/bin/env python import sys import os import shutil def cleanup_dump(dumpstr): cardfrags = dumpstr.split('\n\n') if len(cardfrags) < 4: return '' else: return '\n\n'.join(cardfrags[2:-1]) + '\n\n' def identify_checkpoints(basedir, ident): cp_infos = [] for path in os.listdir(b...
nilq/baby-python
python
a, b = map(int, input()) if a <= 9 and b <= 9: ans = a * b else: ans = -1 print(ans)
nilq/baby-python
python
# Test the frozen module defined in frozen.c. from test.test_support import TestFailed import sys, os try: import __hello__ except ImportError, x: raise TestFailed, "import __hello__ failed:" + str(x) try: import __phello__ except ImportError, x: raise TestFailed, "import __phello__ fail...
nilq/baby-python
python
# Generated by Django 3.2.6 on 2021-08-21 12:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('education', '0021_alter_materialblocks_icon'), ] operations = [ migrations.AlterField( model_name='materialblocks', ...
nilq/baby-python
python
from __future__ import annotations from typing import TYPE_CHECKING from openhab_creator import _ from openhab_creator.models.common import MapTransformation from openhab_creator.models.configuration.equipment.types.sensor import ( Sensor, SensorType) from openhab_creator.models.items import (DateTime, Group, Gro...
nilq/baby-python
python
# -*- coding: utf-8 -*- """Library to easily manage Host Health""" from __future__ import division import logging import psutil import threading import time COLOR_GREEN = '#4caf50' COLOR_ORANGE = '#ff5722' COLOR_RED = '#f44336' CPU_THRESHOLD_WARNING = 70 CPU_THRESHOLD_DANGER = 85 duplex_map = { psutil.NIC_DUPL...
nilq/baby-python
python
__author__ = 'Rob Edwards' import sys from matrices import blosum62 def score(a, b): """score dna as match/mismatch""" if a == b: return 1 return -1 def dna_score_alignment(seq1, seq2, gap_open=11, gap_extend=1): """ Generate a score for an alignment between two sequences. This does not ...
nilq/baby-python
python
from libs.matrix_client.matrix_client.client import MatrixClient from libs.matrix_client.matrix_client.api import MatrixRequestError from libs.matrix_client.matrix_client.user import User from requests.exceptions import MissingSchema from helpers import setup_logger logger = setup_logger(__name__, 'info') class Clie...
nilq/baby-python
python
import unittest import uuid from unittest.mock import patch from microsetta_private_api.model.interested_user import InterestedUser from microsetta_private_api.repo.interested_user_repo import InterestedUserRepo from microsetta_private_api.repo.transaction import Transaction from psycopg2.errors import ForeignKeyViola...
nilq/baby-python
python
import binascii import socket import struct from twampy.utils import generate_zero_bytes, now from twampy.constants import TIMEOFFSET, TWAMP_PORT_DEFAULT, TOS_DEFAULT, TIMEOUT_DEFAULT import logging logger = logging.getLogger("twampy") class ControlClient: def __init__(self, server, port=TWAMP_PORT_DEFAUL...
nilq/baby-python
python
from helpers import test_tools from graph import GraphRoutingProblem from dungeon import DungeonProblem
nilq/baby-python
python
from __future__ import absolute_import from django.core.urlresolvers import reverse from sentry.models import AuthIdentity, AuthProvider from sentry.testutils import APITestCase class DeleteUserIdentityTest(APITestCase): def test_simple(self): user = self.create_user(email="a@example.com") org =...
nilq/baby-python
python
# # build the vocab/dictionary from outside to all related lexicons from __future__ import print_function import os import sys import argparse sys.path.append(".") sys.path.append("..") sys.path.append("../..") from neuronlp2 import utils from neuronlp2.io import get_logger, conllx_stacked_data # # Only use for ...
nilq/baby-python
python
# Copyright 2021 Universität Tübingen, DKFZ and EMBL # for the German Human Genome-Phenome Archive (GHGA) # # 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/license...
nilq/baby-python
python
def ones(l): #return l + [x + '_1' for x in l] #return sorted(l + [x + '_1' for x in l]) ret = [] for x in l: ret.append(x) ret.append(x + '_1') return ret # The complete primitive sets ffprims_fall = ones( [ 'FD', 'FDC', 'FDCE', 'FDE', '...
nilq/baby-python
python
import os from setuptools import setup, find_packages README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name = 'django-pimp-my-filter', version = '0.1.1', ...
nilq/baby-python
python
#!/usr/bin/env python # Python imports import matplotlib as plt import numpy as np import time import argparse # Other imports import srl_example_setup from simple_rl.tasks import GridWorldMDP from simple_rl.planning.ValueIterationClass import ValueIteration # INSTRUCTIONS FOR USE: # 1. When you run the program [eit...
nilq/baby-python
python
import socket import time HOST='data.pr4e.org' PORT=80 mysock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) mysock.connect((HOST,PORT)) mysock.sendall(b'GET http://data.pr4e.org/cover3.jpg HTTP/1.0\r\n\r\n') count=0 picture=b"" while True: data=mysock.recv(5120) if(len(data)<1): break time.slee...
nilq/baby-python
python
#!/usr/bin/env python """ Tropical Cyclone Risk Model (TCRM) - Version 1.0 (beta release) Copyright (C) 2011 Commonwealth of Australia (Geoscience Australia) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the...
nilq/baby-python
python
import pandas as pd import numpy as np from os import listdir import config def read(bound_file_path, compounds_file_path, adducts_file_path): ''' Read in excel files as pd.DataFrame objects ''' bound_df = pd.read_excel(bound_file_path) compounds_df = pd.read_excel(compounds_file_path) adduc...
nilq/baby-python
python
#! /usr/bin/env python import onnx.backend import argparse import caffe2.python.workspace as c2_workspace import glob import json import numpy as np import onnx import caffe2.python.onnx.frontend import caffe2.python.onnx.backend import os import shutil import tarfile import tempfile import boto3 from six.moves.url...
nilq/baby-python
python
# Copyright (c) 2018 Graphcore Ltd. All rights reserved. # This script is run by the release agent to create a release of PopTorch def install_release(release_utils, release_id, snapshot_id, version_str): # Tag must contain the string 'poptorch' to keep it unique. tag = "{}-poptorch".format(version_str) ...
nilq/baby-python
python
import json import pytest from ermaket.api.database import DBConn from ermaket.api.scripts import ScriptManager from ermaket.api.system.hierarchy import Activation, Trigger, Triggers CHAIN_ID = 1 TEAPOT_ID = 2 ADD_ID = 3 ADD2_ID = 4 def login(client, user): return client.post( '/auth/login', data={ ...
nilq/baby-python
python
from django.conf.urls import url from django.views.generic.base import RedirectView from tests.views import foo, foo_api urlpatterns = [ url(r"^api/foo/$", foo_api), url(r"^foo/$", foo), url(r"^bar/$", RedirectView.as_view(url="/foo/", permanent=False)), ]
nilq/baby-python
python