content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
"""
Playground for downloading GenBank files, wrapping in bowtie2, sCLIP/SOR prep
"""
from Bio import Entrez
import csv
import re
import requests
import subprocess
import os
from Bio import SeqIO
import shutil
from urllib.error import HTTPError
import time
import inv_config as config
# TODO Remove .gbk files at the e... | nilq/baby-python | python |
from __future__ import division
import os
import math
import scipy.misc
import numpy as np
import argparse
from glob import glob
from pose_evaluation_utils import mat2euler, dump_pose_seq_TUM
parser = argparse.ArgumentParser()
parser.add_argument("--dataset_dir", type=str, help="path to kitti odometry dataset")
parser... | nilq/baby-python | python |
import numpy as np
import matplotlib.pyplot as plt
with open('timings.txt','r') as inp:
inp.readline()
times = np.loadtxt(inp, delimiter=',')
print(times.shape)
selected = list([0,1,3,8,13,18])
# plt.plot((2+np.array(range(19))),times[:,0],'r^-',label="Best first search algorithm")
# plt.plot((2+np.array(range(1... | nilq/baby-python | python |
from pessoa import Pessoa
class Aluno(Pessoa):
def __init__(self, rm, turma_id, rg, nome):
super().__init__(rg, nome)
self._rm = rm
self._turma_id = turma_id
self._notas = []
def media(self):
if len(self._notas) > 0:
return sum(self._notas)/len(self._notas)
... | nilq/baby-python | python |
import numpy as np
import torch
class FeaturesLinear(torch.nn.Module):
def __init__(self, field_dims, output_dim=1):
super().__init__()
self.fc = torch.nn.Embedding(sum(field_dims), output_dim)
self.bias = torch.nn.Parameter(torch.zeros((output_dim,)))
self.offsets = np.array((0, ... | nilq/baby-python | python |
# Copyright 2013 - Red Hat, Inc.
#
# 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 writi... | nilq/baby-python | python |
import fileReader
import inputHandler
import fileHandler
import os
inputStuff = inputHandler.inputHandler()
fileStuff = fileHandler.FileHandler()
def getMode():
mode = inputStuff.determineAutoOrManual()
if mode == 'man':
getFileInfo()
loadAudioFile()
elif mode =='auto':
fileProcesser = fileReader.FileReader()... | nilq/baby-python | python |
from pybullet_utils import bullet_client
import math
class QuadrupedPoseInterpolator(object):
def __init__(self):
pass
def ComputeLinVel(self,posStart, posEnd, deltaTime):
vel = [(posEnd[0]-posStart[0])/deltaTime,(posEnd[1]-posStart[1])/deltaTime,(posEnd[2]-posStart[2])/deltaTime]
return vel... | nilq/baby-python | python |
from typing import List
from extraction.event_schema import EventSchema
from extraction.predict_parser.predict_parser import Metric
from extraction.predict_parser.tree_predict_parser import TreePredictParser
decoding_format_dict = {
'tree': TreePredictParser,
'treespan': TreePredictParser,
}
def get_predict... | nilq/baby-python | python |
import os
filename = os.path.dirname(__file__) + "\\input"
with open(filename) as file:
x = []
start = 0
for line in file:
text = list(line.rstrip())
if start == 0:
x = [0] * len(text)
i = 0
for t in text:
if t == '1':
x[i] += 1
... | nilq/baby-python | python |
def solve(input):
ans = 0
for g in input.split("\n\n"):
b = 0
for c in g:
if c.isalpha():
b |= 1 << (ord(c) - ord("a"))
ans += bin(b).count("1")
return ans
| nilq/baby-python | python |
# https://www.hackerrank.com/challenges/three-month-preparation-kit-jack-goes-to-rapture/problem
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'getCost' function below.
#
# The function accepts WEIGHTED_INTEGER_GRAPH g as parameter.
#
#
# For the weighted graph, <name>:
#
... | nilq/baby-python | python |
from typing import List, Callable, Optional, Dict, Set
from tqdm import tqdm
from src.data.objects.frame import Frame
from src.data.objects.stack import Stack
from src.data.readers.annotation_reader import AnnotationLoader
class LineModifiedClassifier:
def __init__(self, user_ids: Set[int], annotation_loader: A... | nilq/baby-python | python |
from scrapy import cmdline
name = 'douban_movie_top250'
cmd = 'scrapy crawl {}'.format(name)
cmdline.execute(cmd.split())
| nilq/baby-python | python |
#you += hash(pubkey || index) to both the private scalar and public point
#<tacotime> [02:35:38] so to get priv_i and pub_i
#<tacotime> [02:36:06] priv_i = (priv + hash) mod N
#<tacotime> [02:37:17] pub_i = (pub + scalarbasemult(hash))
import MiniNero
import PaperWallet
sk, vk, pk, pvk, addr, wl, cks = PaperWallet.key... | nilq/baby-python | python |
class OperationFailed(Exception):
pass
class ValidationFailed(Exception):
pass
| nilq/baby-python | python |
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython
"""
def suma(a: float, b: float) -> float:
return a + b
def resta(a: float, b: float) -> float:
return a - b
def multiplicacion(a: float, b: float) -> float:
return a * b
def division(a: float, b: float) -> float:
if b <= 0:
ra... | nilq/baby-python | python |
class ArtistCollection():
"""
Matplotlib collections can't handle Text.
This is a barebones collection for text objects
that supports removing and making (in)visible
"""
def __init__(self, artistlist):
"""
Pass in a list of matplotlib.text.Text objects
(or possibly any ... | nilq/baby-python | python |
from qemuvolume import QEMUVolume
from ..tools import log_check_call
class VirtualHardDisk(QEMUVolume):
extension = 'vhd'
qemu_format = 'vpc'
ovf_uri = 'http://go.microsoft.com/fwlink/?LinkId=137171'
# Azure requires the image size to be a multiple of 1 MiB.
# VHDs are dynamic by default, so we add the option
... | nilq/baby-python | python |
import pytest
import numpy
import os
import spacy
from spacy.matcher import Matcher
from spacy.attrs import ORTH, LOWER, ENT_IOB, ENT_TYPE
from spacy.attrs import ORTH, TAG, LOWER, IS_ALPHA, FLAG63
from spacy.symbols import DATE, LOC
def test_overlap_issue118(EN):
'''Test a bug that arose from having overlapping... | nilq/baby-python | python |
# 3rd party imports
import stellar_base.utils
from stellar_base.exceptions import *
from stellar_base.keypair import Keypair
from stellar_base.address import Address
STELLAR_MEMO_TEXT_MAX_BYTES = 28
def is_address_valid(address):
"""
Checks if a given Stellar address is valid. It does not check if it exists ... | nilq/baby-python | python |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... | nilq/baby-python | python |
"""Converts ECMWF levels into heights"""
import numpy as np
def readLevels(file_name='supra/Supracenter/level_conversion_ECMWF_37.txt', header=2):
""" Gets the conversion of heights from a .txt file, for use with convLevels().
Arguments:
file_name: [string] name of conversion file, .txt
heade... | nilq/baby-python | python |
#
# Copyright 2018 herd-mdl contributors
#
# 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 ... | nilq/baby-python | python |
import torch.optim
import torch.nn as nn
class AgentControl:
def __init__(self, hyperparameters):
self.gamma = hyperparameters['gamma']
self.device = 'cpu'# 'cuda' if torch.cuda.is_available() else 'cpu'
self.loss = nn.MSELoss()
#Return accumulated discounted estimated reward ... | nilq/baby-python | python |
"""Support for TPLink HS100/HS110/HS200 smart switch."""
import logging
import time
from homeassistant.components.switch import (
ATTR_CURRENT_POWER_W, ATTR_TODAY_ENERGY_KWH, SwitchDevice)
from homeassistant.const import ATTR_VOLTAGE
import homeassistant.helpers.device_registry as dr
from . import CONF_SWITCH, DO... | nilq/baby-python | python |
from .Util import *
| nilq/baby-python | python |
'''This file defines user interfaces to sDNA tools and how to convert inputs to config'''
##This file (and this file only) is released under the MIT license
##
##The MIT License (MIT)
##
##Copyright (c) 2015 Cardiff University
##
##Permission is hereby granted, free of charge, to any person obtaining a copy
#... | nilq/baby-python | python |
"""
This module contains helpers for the XGBoost python wrapper: https://xgboost.readthedocs.io/en/latest/python/index.html
The largest part of the module are helper classes which make
using a validation set to select the number of trees transparent.
"""
import logging
logger = logging.getLogger(__name__)
import jobl... | nilq/baby-python | python |
#! /usr/bin/python3.5
# -*- coding: utf-8 -*-
import random
import numpy as np
import matplotlib.pyplot as plt
def subdivied(Liste, Size):
"""
On divise la liste Liste, en :
sum from i = 1 to N - Size [x_i,x_i+1,...x_i+Size]
"""
res = []
# pour chaque éléments de la liste
for index, e... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 2 16:22:45 2019
@author: Soumitra
"""
import math
import numpy as np
import numpy.fft as f
import matplotlib.pyplot as plt
n = np.arange(12);
x = ((-1)**n)*(n+1)
plt.xlabel('n');
plt.ylabel('x[n]');
plt.title(r'Plot of DT signal x[n]');
plt.stem(n, x);... | nilq/baby-python | python |
"""Iterative Compression Module."""
from experiments import RESULTS_DIR, TABLES_DIR
from pathlib import Path
# Paths
IC_DIR = Path(__file__).parent
SELF_COMPARISON_DATA_PATH = RESULTS_DIR / 'ic_preprocessing_level.csv'
IC_TABLE_FORMAT_STR = 'timeout_{}.tex'
IC_TABLES_DIR = TABLES_DIR / 'ic'
IC_TABLES_DIR.mkdir(exist... | nilq/baby-python | python |
"""Examples showing how one might use the Result portion of this library."""
import typing as t
import requests
from safetywrap import Result, Ok, Err
# ######################################################################
# One: Validation Pipeline
# ##############################################################... | nilq/baby-python | python |
from django.shortcuts import render, redirect, render_to_response
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.forms.util import ErrorList
from django.contrib import auth, messages
from django.con... | nilq/baby-python | python |
# <auto-generated>
# This code was generated by the UnitCodeGenerator tool
#
# Changes to this file will be lost if the code is regenerated
# </auto-generated>
def to_u_s_miles_per_gallon(value):
return value * 2.35215
def to_miles_per_gallon(value):
return value * 2.82481
def to_litres_per100_kilometres(value):
... | nilq/baby-python | python |
"""
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
"""
from pyramid.compat import itervalues_
from everest.entities.utils import get_root_aggregate
from everest.querying.specifications import eq
from everest... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import logging
import logging.config
import os
import sys
import yaml
from datetime import datetime
from importlib import import_module
from pkgutil import iter_modules
from plastron import commands, version
from plastron.exceptions import FailureException... | nilq/baby-python | python |
alphabet = 'qw2rty534plkjhgfds1zxcvbnm'
alpha_dict = {'q':0,'w':1,'2':2,'r':3,'t':4,'y':5,'5':6,'3':7,'4':8,'p':9,'l':10,'k':11,'j':12,'h':13,'g':14,'f':15,'d':16,'s':17,'1':18,'z':19,'x':20,'c':21,'v':22,'b':23,'n':24,'m':25}
list_out = open("full_pass_list","w")
def reduction(my_letter):
while my_letter >= 0:
my_... | nilq/baby-python | python |
class Node(object):
"""
Represents a node in the query plan structure. Provides a `parse` function to
parse JSON into a heirarchy of nodes. Executors take a plan consisting of
nodes and use it to apply the Transformations to the source.
"""
@classmethod
def parse(cls, _dict):
raise NotImplemented
d... | nilq/baby-python | python |
from abc import ABCMeta, abstractmethod
from dataclasses import dataclass, field, asdict
from datetime import datetime
from typing import List
@dataclass(frozen=True)
class SalaryPayment:
basic_payment: int = field(default_factory=int, metadata={"jp": "基本給"})
overtime_fee: int = field(default_factory=int, met... | nilq/baby-python | python |
import os
def get_ip_name():
return "base_ip"
class base_ip:
ID = "base"
def __init__(self, io_hash):
return
def matched_id(in_key):
return in_key is self.ID
def get_rst_case_text(self):
return ''
def get_dft_case_text(self):
return ''
def get_pinmux_setting(self):
return ""
def ge... | nilq/baby-python | python |
import requests
import conf
import urllib2
import xml.etree.ElementTree as ET
import io
def get_min_temp_phrase_from_values(min_observed, min_forecast):
if abs(min_forecast) != 1:
degrees_text = "degrees"
else:
degrees_text = "degree"
s = "The temperature tonight will be %s %s, " % (min_fo... | nilq/baby-python | python |
from flask import Flask
from flask import render_template,redirect,request
import pandas as pd
import sys
import numpy as np
import pickle
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
#from sklearn.metrics import mean_squared_log_error
from sklearn.linear_model ... | nilq/baby-python | python |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 ... | nilq/baby-python | python |
import os
import platform
import textwrap
from collections import OrderedDict
from jinja2 import Template
from conans.errors import ConanException
from conans.util.files import normalize
sh_activate = textwrap.dedent("""\
#!/usr/bin/env sh
{%- for it in modified_vars %}
export CONAN_OLD_{{it}}="${{it}}"... | nilq/baby-python | python |
import logging
from copy import copy
from inspect import isfunction
import ibutsu_server.tasks
from flask_testing import TestCase
from ibutsu_server import get_app
from ibutsu_server.tasks import create_celery_app
from ibutsu_server.util import merge_dicts
def mock_task(*args, **kwargs):
if args and isfunction(a... | nilq/baby-python | python |
#!/usr/bin/env python
from kivy.app import App
from kivy.clock import Clock
from kivy.config import Config
from kivy.core.window import Window
from kivy.properties import (ListProperty,
NumericProperty,
ObjectProperty,
ReferenceList... | nilq/baby-python | python |
# -selenium webdriver-
from logging import fatal
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.... | nilq/baby-python | python |
import argparse
import os
import numpy as np
import scipy.io as sio
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from tqdm import tqdm
from net.models import LeNet_5 as LeNet
import util
os.makedirs('saves', exist_ok=True)... | nilq/baby-python | python |
import random
import numpy as np
import tensorflow as tf
import tqdm
from pipeline import SEED
from pipeline.dataset.gc import get_client
random.seed(SEED)
TRAIN = tf.estimator.ModeKeys.TRAIN
EVAL = tf.estimator.ModeKeys.EVAL
PREDICT = tf.estimator.ModeKeys.PREDICT
class MNISTDataset:
"""MNIST dataset."""
... | nilq/baby-python | python |
"""\
Demo app for the ARDrone.
This simple application allows to control the drone and see the drone's video
stream.
Copyright (c) 2011 Bastian Venthur
The license and distribution terms for this file may be
found in the file LICENSE in this distribution.
"""
import pygame
from pydrone import libardrone
if __na... | nilq/baby-python | python |
from Parameter import Parameter, registerParameterType
from ParameterTree import ParameterTree
from ParameterItem import ParameterItem
import parameterTypes as types | nilq/baby-python | python |
# encoding: utf-8
import uuid
import os
import random
import json
from collections import Counter
from flask import request, abort, jsonify, g, url_for, current_app, session
from flask_restful import Resource, reqparse
from flask_socketio import (
emit,
disconnect
)
from app.ansibles.ansible_task import INVENT... | nilq/baby-python | python |
import unittest
from random import uniform
from pysim import epcstd
class TestDataTypes(unittest.TestCase):
def test_divide_ratio_encoding(self):
self.assertEqual(epcstd.DivideRatio.DR_8.code, "0")
self.assertEqual(epcstd.DivideRatio.DR_643.code, "1")
def test_divide_ratio_str(self):
... | nilq/baby-python | python |
from __future__ import print_function
from builtins import str
import argparse
import os
import sys
import re
from .version import VERSION
from .utils import get_local_ip, DelimiterArgParser
import atexit
def add_parser_args(parser, config_type):
# General arguments
parser.add_argument(
'--trace_gre... | nilq/baby-python | python |
"""add column source_file_dir
Revision ID: 3880a3a819d5
Revises: 2579e237c51a
Create Date: 2019-11-12 16:49:05.040791
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '3880a3a819d5'
down_revision = '2579e237c51a'
branch_labels = None
depends_on = None
def upgr... | nilq/baby-python | python |
from collections import OrderedDict
from django.db.models import Count
from django.db.models.functions import TruncYear
from .models import Reading
def annual_reading_counts(kind="all"):
"""
Returns a list of dicts, one per year of reading. In year order.
Each dict is like this (if kind is 'all'):
... | nilq/baby-python | python |
import os
from CPAC.pipeline import nipype_pipeline_engine as pe
import nipype.algorithms.rapidart as ra
import nipype.interfaces.fsl as fsl
import nipype.interfaces.io as nio
import nipype.interfaces.utility as util
from .utils import *
from CPAC.vmhc import *
from nipype.interfaces.afni import preprocess
from CPAC.re... | nilq/baby-python | python |
##MIT License
##
##Copyright (c) 2019 Jacob Nudel
##Copyright (c) 2019 Yashu Seth
##
##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 righ... | nilq/baby-python | python |
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as f
from torch.autograd import Variable
import os
import numpy as np
from tqdm import tqdm
class ONE_HOT_MLP(nn.Module):
def __init__(self, hidden):
super(ONE_HOT_MLP, self).__init__()
self.cnn ... | nilq/baby-python | python |
import os
import string
from tqdm import tqdm
#from google.colab import drive
#conda install -c huggingface transformers
import matplotlib.pyplot as plt
#% matplotlib inline
import pandas as pd
import seaborn as sns
import numpy as np
import random
import torch
from torch.utils.data import Dataset, Data... | nilq/baby-python | python |
import json
import unittest
from mock import Mock, patch
import delighted
get_headers = {
'Accept': 'application/json',
'Authorization': 'Basic YWJjMTIz',
'User-Agent': "Delighted Python %s" % delighted.__version__
}
post_headers = get_headers.copy()
post_headers.update({'Content-Type': 'application/jso... | nilq/baby-python | python |
#!/usr/bin/env python3
from typing import Any, List
import configargparse
import paleomix
SUPPRESS = configargparse.SUPPRESS
class ArgumentDefaultsHelpFormatter(configargparse.ArgumentDefaultsHelpFormatter):
"""Modified ArgumentDefaultsHelpFormatter that excludes several constants (True,
False, None) and us... | nilq/baby-python | python |
#!/usr/bin/env nix-shell
#!nix-shell -i python -p python3 -I nixpkgs=../../pkgs
# SPDX-FileCopyrightText: 2020 Daniel Fullmer and robotnix contributors
# SPDX-License-Identifier: MIT
import json
import os
import urllib.request
def save(filename, data):
open(filename, 'w').write(json.dumps(data, sort_keys=True, in... | nilq/baby-python | python |
from .transformer import TransformerXL | nilq/baby-python | python |
# encoding: utf-8
from hoopa import const
from hoopa.middlewares.stats import StatsMiddleware
NAME = "hoopa"
# 最大协程数
WORKER_NUMBERS = 1
# 请求间隔, 可以是两个int组成的list,间隔随机取两个数之间的随机浮点数
DOWNLOAD_DELAY = 3
# pending超时时间,超过这个时间,放回waiting
PENDING_THRESHOLD = 100
# 任务完成不停止
RUN_FOREVER = False
# 队列
# 调度器队列,默认redis, memory, mq
QUE... | nilq/baby-python | python |
from pathlib import Path
SRC = Path(__file__).parent
BLD = SRC.parent.joinpath("bld")
| nilq/baby-python | python |
from collections import Counter
class Square(Counter):
"""Creates a special purpose counter than can store only one value, and wipes itself when zero."""
def __init__(self):
"""Object should be initialized empty."""
pass
def __setitem__(self, key, cnt):
"""Update the count."""
... | nilq/baby-python | python |
from django.http import JsonResponse
from django.shortcuts import render
from django.views.generic import View
# model
from timepredictor.models import PrediccionTiempos, UltimosGps
# Create your views here.
class MapHandler(View):
'''This class manages the map where the bus and stops are shown'''
def __init... | nilq/baby-python | python |
"""
CLI Module.
Handles CLI for the Repository Updater
"""
from os import environ
from sys import argv
import click
import crayons
from . import APP_FULL_NAME, APP_VERSION
from .github import GitHub
from .repository import Repository
@click.command()
@click.option(
"--token",
hide_input=True,
prompt="G... | nilq/baby-python | python |
'''Functions to calculate seismic noise in suspended optics.
'''
from __future__ import division
import numpy as np
from scipy.interpolate import PchipInterpolator as interp1d
def seismic_suspension_fitered(sus, in_trans):
"""Seismic displacement noise for single suspended test mass.
:sus: gwinc suspension ... | nilq/baby-python | python |
def func(num):
return x*3
x = 2
func(x)
| nilq/baby-python | python |
CHECKPOINT = 'model/checkpoint.bin'
MODEL_PATH = 'model/model.bin'
input_path = 'input/train.csv'
LR = 0.01
scheduler_threshold = 0.001
scheduler_patience = 2
scheduler_decay_factor = 0.5
embed_dims = 128
hidden_dims = 128
num_layers = 1
bidirectional = False
dropout = 0.2
out_dims = 128
Batch_Size = 64
Epochs = 100... | nilq/baby-python | python |
import pygame
# game
from cgame import CGame
def main():
try:
CGame().run()
except Exception as e:
print(e)
if __name__ == '__main__':
pygame.init()
main()
| nilq/baby-python | python |
from flask import Flask, Request, jsonify, request
from src.driver import FirestoreDriverImpl
from src.interactor import SolverInteractor
from src.repository import RoomRepositoryImpl
from src.rest import BaseException, ClientException, SolverResource
solver_resource = SolverResource(
solver_usecase=SolverInteract... | nilq/baby-python | python |
import netifaces
import time
from collections import namedtuple
from aplus import Promise
from openmtc_server.exc import InterfaceNotFoundException
from openmtc_server.transportdomain.NetworkManager import NetworkManager
Interface = namedtuple("Interface", ("name", "addresses", "hwaddress"))
Address = namedtuple("Add... | nilq/baby-python | python |
import elasticsearch
import json
import click
from toolz import iterate, curry, take
from csv import DictReader
from elasticsearch.helpers import streaming_bulk
nuforc_report_index_name = 'nuforc'
nuforc_report_index_body = {
"mappings": {
"properties": {
"text": {
"type": "text"... | nilq/baby-python | python |
import numpy as np
import sys
class RobotData:
"""
Stores sensor data at a particular frame
Attributes
----------
position : tuple
(x,y) tuple of the robot position
rotation : float
angle of robot heading clockwise relative to up (north)
forward_dir : tuple
(x,y) unit vector indicating the forward direct... | nilq/baby-python | python |
from makeit.utilities.fastfilter_utilities import Highway_self, pos_ct, true_pos, real_pos, set_keras_backend
from makeit.utilities.fingerprinting import create_rxn_Morgan2FP_separately
from rdkit import Chem
from rdkit.Chem import AllChem, DataStructs
from makeit.interfaces.scorer import Scorer
import numpy as np
impo... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#from distutils.core import setup
import glob
from setuptools import setup
readme = open('README.md').read()
setup(
name='ReMoTE',
version='0.1',
description='Registration of Mobyle Tools in Elixir',
long_description=readme,
author='Hervé Ménager',
... | nilq/baby-python | python |
class StateMachine:
"""A simple state machine"""
def __init__(self):
self.__states = {} #:dict[string] -> [(check, event, next)]
self.actions = {} #:dict[string] -> action
self.currentState = "start" #:string
self.addState("start")
def addState(self, name):
"""reg... | nilq/baby-python | python |
import numpy as np
def meshTensor(value):
"""**meshTensor** takes a list of numbers and tuples
that have the form::
mT = [ float, (cellSize, numCell), (cellSize, numCell, factor) ]
For example, a time domain mesh code needs
many time steps at one time::
[(1e-5, 30), (1e-4, 30), 1e-3... | nilq/baby-python | python |
import numpy
C_3 = numpy.array([1, 2]) / 3
a_3 = numpy.array([[3, -1], [1, 1]]) / 2
sigma_3 = numpy.array([[[1, 0], [-2, 1]], [[1, 0], [-2, 1]]])
C_5 = numpy.array([1, 6, 3]) / 10
a_5 = numpy.array([[11, -7, 2], [2, 5, -1], [-1, 5, 2]]) / 6
sigma_5 = numpy.array([[[40, 0, 0],
[-124, 100, 0],
... | nilq/baby-python | python |
from bs4 import BeautifulSoup
import urllib, requests, re
import json
import datetime
from datetime import date
def cnt1():
year=datetime.datetime.now().year
month=datetime.datetime.now().month
month=str(month)
day=datetime.datetime.now().day
if len(str(month)) == 1 :
month="0"+str(month)... | nilq/baby-python | python |
"""Time
Calculate the time of a code to run.
Code example: product of the first 100.000 numbers.
"""
import time
def product():
p = 1
for i in range(1, 100000):
p = p * i
return p
start = time.time()
prod = product()
end = time.time()
print('The result is %s digits long.' % len(str(prod)))
print(... | nilq/baby-python | python |
from roboclaw import Roboclaw
from time import sleep
rc = Roboclaw("/dev/ttyACM0",115200)
rc.Open()
address=0x80
#rc.ForwardM1(address, 50)
# sleep (5)
rc.ForwardM1(address, 0) | nilq/baby-python | python |
from pathlib import Path
from typing import Optional
import config # type: ignore
import hvac
from aiohttp_micro import AppConfig as BaseConfig # type: ignore
from config.abc import Field
from passport.client import PassportConfig
class StorageConfig(config.PostgresConfig):
host = config.StrField(default="loca... | nilq/baby-python | python |
import uuid
from operator import attrgetter
from typing import List
from confluent_kafka import Consumer, TopicPartition
from confluent_kafka.admin import AdminClient, TopicMetadata
from kaskade.config import Config
from kaskade.kafka import TIMEOUT
from kaskade.kafka.group_service import GroupService
from kaskade.ka... | nilq/baby-python | python |
#!/usr/bin/env python
from __future__ import print_function, division
import os
import sys
sys.path.append(os.path.dirname(sys.path[0]))
try:
import cPickle as pickle # python 2
except ImportError:
import pickle # python 3
import socket
import argparse
from random import randint
from numpy import unravel_in... | nilq/baby-python | python |
from highton.models import Party
from highton.highton_constants import HightonConstants
class AssociatedParty(
Party,
):
"""
:ivar id: fields.IntegerField(name=HightonConstants.ID)
:ivar author_id: fields.IntegerField(name=HightonConstants.AUTHOR_ID)
:ivar background: fields.StringField(name=High... | nilq/baby-python | python |
import unittest
from column import *
class ColumnTest(unittest.TestCase):
def test_polar2coord(self):
# test55
self.assertEqual(polar2coord( (46, 2.808) ), (1.9506007042488642, -2.019906159350932) )
self.assertEqual(polar2coord( (196, 1.194) ), (-1.1477464649503528, 0.32911100284549705) )
... | nilq/baby-python | python |
from helpers import *
import shutil
league_info_file = 'league_info.json'
ros_URL = 'https://5ahmbwl5qg.execute-api.us-east-1.amazonaws.com/dev/rankings'
def_expert = 'subvertadown'
kick_expert = 'subvertadown'
weekly_method = 'borischen'
yaml_config_temp = '_config_template.yml'
output_file = 'summary.txt'
yaml_con... | nilq/baby-python | python |
import re
from typing import List
import pytest
from ja_timex.pattern.place import Pattern
from ja_timex.tag import TIMEX
from ja_timex.tagger import BaseTagger
from ja_timex.timex import TimexParser
@pytest.fixture(scope="module")
def p():
# Custom Taggerで必要となる要素と、TimexParserの指定
def parse_kouki(re_match: ... | nilq/baby-python | python |
from patternpieces import PatternPieces
from piece import Piece
from piecesbank import PiecesBank
from ui import UI
from board import Board
from arbiter import Arbiter
from ai import Ai
import json
import random
def main():
pb = PiecesBank()
app = UI()
### DO NOT FUCKING REMOVE THIS. I DARE YOU. ###
a... | nilq/baby-python | python |
import re
import wrapt
from .bash import CommandBlock
class ConfigurationError(Exception):
pass
def add_comment(action):
@wrapt.decorator
def wrapper(wrapped, instance, args, kwargs):
def _execute(*args, **kwargs):
return CommandBlock() + '' + 'echo "{} {}"'.format(action, instance.d... | nilq/baby-python | python |
import logging
from .registry import Registry
from .parsers import RegistryPDFParser
from .securityhandler import security_handler_factory
from .types import IndirectObject, Stream, Array, Dictionary, IndirectReference, obj_factory
from .utils import cached_property, from_pdf_datetime
class PDFDocument(object):
... | nilq/baby-python | python |
from __future__ import print_function
import logging
import re
from datetime import datetime
from collections import Counter
from itertools import chain
import json
import boto3
import spacy
import textacy
from lxml import etree
from fuzzywuzzy import process
from django.utils.functional import cached_property
from d... | nilq/baby-python | python |
#!/usr/bin/env python
import time
import datetime
from web3.exceptions import TransactionNotFound, BlockNotFound
from web3.middleware import construct_sign_and_send_raw_middleware
from config import (
CONFIRMATIONS,
TARGET,
TARGET_TIME,
ACCOUNT,
BASE_PRICE,
web3,
INSTANCE,
)
def get_transa... | nilq/baby-python | python |
from pirate_sources.models import VideoSource, URLSource, IMGSource
from django.contrib import admin
admin.site.register(VideoSource)
admin.site.register(URLSource)
admin.site.register(IMGSource)
| nilq/baby-python | python |
import os
import sys
import numpy as np
import cv2
import ailia
from logging import getLogger
logger = getLogger(__name__)
def preprocessing_img(img):
if len(img.shape) < 3:
img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGRA)
elif img.shape[2] == 3:
img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
e... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.