content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import os
import pandas as pd
import matplotlib.pyplot as plt
def get_speedup(precision: str, df1: pd.DataFrame, df2: pd.DataFrame, sys: str, dev: str) -> list:
speedup = [{} for x in range(2, 11)]
d1: pd.DataFrame = df1.copy()
d2: pd.DataFrame = df2.copy()
d1 = d1[d1['precision'] == precision]
d2... | nilq/baby-python | python |
from typing import TypedDict, Optional
class IMeasInfo(TypedDict):
file_tag: str
entity_tag: str
metric_name: str
time_offset_hrs_mins: str
address: str
aggregation_strategy: Optional[str]
equation: Optional[str]
| nilq/baby-python | python |
import re
import subprocess
import sys
import time
import traceback
import uuid
from collections import namedtuple
from PySide2.QtCore import (QObject, QRunnable, Qt, QThreadPool, QTimer,
Signal, Slot)
from PySide2.QtWidgets import (QApplication, QMainWindow, QPlainTextEdit,
... | nilq/baby-python | python |
import os
from flask import Flask
class Config:
def __init__(self, app: Flask = None) -> None:
self.app = None
if app:
self.init_app(app)
def init_app(self, app: Flask) -> None:
config = self.get_user_config()
app.config.update(config)
@staticmethod
def ... | nilq/baby-python | python |
"""
The sensors module contains the base definition for a generic
sensor call and the implementation of all the specific sensors
"""
from __future__ import print_function
from qds_sdk.qubole import Qubole
from qds_sdk.resource import Resource
from argparse import ArgumentParser
import logging
import json
log = loggi... | nilq/baby-python | python |
from types import SimpleNamespace
from typing import Any, cast
from unittest.mock import Mock
import pytest
from playbacker.track import Shared, SoundTrack, StreamBuilder
from playbacker.tracks.file import FileSounds, FileTrack
from tests.conftest import get_audiofile_mock, get_tempo
@pytest.fixture
def file_track(... | nilq/baby-python | python |
""" Pytest firewallreader
"""
import pickle
import pytest
from nftfw.rulesreader import RulesReader
from nftfw.ruleserr import RulesReaderError
from nftfw.firewallreader import FirewallReader
from .configsetup import config_init
@pytest.fixture
def cf(): # pylint: disable=invalid-name
""" Get config fro... | nilq/baby-python | python |
from django.urls import path
from errors import views
app_name = 'errors'
urlpatterns = [
path('403.html', views.view_403, name="403"),
path('405.html', views.view_405, name="405"),
path('404.html', views.view_404, name="404"),
] | nilq/baby-python | python |
"""Service module to store package loggers"""
import logging
import sys
def configure_logger():
logger = logging.getLogger(name='lexibot')
console_handler = logging.StreamHandler(stream=sys.stdout)
console_handler.setFormatter(
logging.Formatter('%(filename)s:%(lineno)d %(message)s'))
logger.a... | nilq/baby-python | python |
import argparse
import glob
import math
import ntpath
import os
import shutil
import pyedflib
import numpy as np
import pandas as pd
import mxnet as mx
from sleepstage import stage_dict
from logger import get_logger
# Have to manually define based on the dataset
ann2label = {
"Sleep stage W": 0,
"Sleep stage... | nilq/baby-python | python |
# Generated by Django 3.2.7 on 2021-09-28 13:56
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),
]
ope... | nilq/baby-python | python |
_base_ = [
'../_base_/datasets/dota.py',
'../_base_/schedules/schedule_1x.py',
'../../_base_/default_runtime.py'
]
model = dict(
type='OrientedRCNN',
backbone=dict(
type='SwinTransformer',
embed_dims=96,
depths=[2, 2, 6, 2],
num_heads=[3, 6, 12, 24],
windo... | nilq/baby-python | python |
import sys, math
nums = map(int, sys.stdin.readlines()[1:])
gauss = lambda x: (x/2.0)*(1+x)
total = gauss(len(nums)-1)
a = max(nums)
nums.remove(a)
b = max(nums)
nums.remove(b)
if a == b:
cnt = gauss(1 + nums.count(a))
else:
cnt = 1 + nums.count(b)
shit_fmt = lambda x: math.floor(x*100.0)/100.0 # b/c hacke... | nilq/baby-python | python |
downloadable_dataset_urls = {
"ag-raw-train": {
"filename": "train.csv",
"url": ("https://raw.githubusercontent.com/mhjabreel/CharCnn_Keras/master/"
"data/ag_news_csv/train.csv"),
"md5": "b1a00f826fdfbd249f79597b59e1dc12",
"untar": False,
"unzip": False,
}... | nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# this is a windows documentation stub, actual code lives in the .ps1
# file of the same name
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | nilq/baby-python | python |
from IComprehension import Comprehension
from service.preprocess import (
check_answers_and_get_answer_sentence_matches,
check_questions_and_get_question_tokens,
_removeStopWords
)
from service.qualifier import find_similarity,find_question_similarity
class wiki(Comprehension):
def __init__(self, para... | nilq/baby-python | python |
from random import randint
import numpy as np
from qiskit import execute, BasicAer
from qiskit.circuit.quantumcircuit import QuantumCircuit
cards = ["H", "H", "X", "X", "CX", "RX", "RX"]
def run(circuit: QuantumCircuit):
# use local simulator
backend = BasicAer.get_backend('qasm_simulator')
results = ex... | nilq/baby-python | python |
import unittest
import datetime
import pandas as pd
from simple_ranker import Ranker
class RankerTest(unittest.TestCase):
def setUp(self):
self.current_year = datetime.datetime.now().year
def test_rank_by_PE_returns_lowest_first(self):
pe_rank = {
'name': 'pe',
'asce... | nilq/baby-python | python |
from . import crop
from . import info
from . import inpaint
from . import pool
from . import unstack
| nilq/baby-python | python |
"""
interchange_regression_utilities
Utilities to help with running the interchange regression tests
"""
from setuptools import find_packages, setup
setup(
name="interchange_regression_utilities",
author="Open Force Field Consortium",
author_email="info@omsf.org",
license="MIT",
packages=find_packa... | nilq/baby-python | python |
from main.model import Font
from main.views import fetch_css
import requests
import datetime
import random
import string
SNAPSHOTTER_URL = "http://localhost:3000/"
def populate():
with open('urls.txt', 'r') as f:
urls = f.read().split('\n')[:10]
for url in urls:
print 'Processing', url, '...'
font_string = f... | nilq/baby-python | python |
import pandas as pd
TITLE_NAME = "Auto List"
SOURCE_NAME = "auto_list"
LABELS = ["Team",
"Match",
"Starting position",
"Plate Assignments",
"Total Success",
"Total Attempt and Success",
"Scale Success",
"Switch Success",
"First Time",
... | nilq/baby-python | python |
#!/usr/bin/env python
#!vim:fileencoding=UTF-8
import subprocess
jobid = (
("sf_0002", "A_onlyAICG"),
("sf_0004", "A_onlyAICG"),
("sf_0009", "I_ELE_HIS0_P1all"),
("sf_0010", "I_ELE_HIS0_P1all"),
("sf_0011", "G_ELE_HIS0_noP"),
("sf_0012", "G_ELE_HIS0_noP"),
("sf_0015", "J_ELE_HIS0_P2act"),
("sf_0016", "J_ELE_HIS0_P2ac... | nilq/baby-python | python |
"""aubergine: create REST APIs using API-first approach."""
from setuptools import setup, find_packages
CLASSIFIERS = [
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python ... | nilq/baby-python | python |
import json
import os
from datetime import datetime, timedelta
import pytz
import calculate_daily_payment_data
import calculate_market_data
import config
from manage_transactions import get_first_transaction_timestamp
from util import logging
STORE_FINAL_DATA_GENERAL = '/terra-data/v2/final/general'
log = logging.g... | nilq/baby-python | python |
import re
import requests
'''
爬取校花网视频基础版
'''
response = requests.get('http://www.xiaohuar.com/v/')
# print(response.status_code)
# print(response.content)
# print(response.text)
urls = re.findall(r'class="items".*?href="(.*?)"', response.text, re.S) #re.S 把文本信息转换成1行匹配
# print(urls)
url = urls[2]
result = requests.get... | nilq/baby-python | python |
# coding: utf-8
"""
Uptrends API v4
This document describes Uptrends API version 4. This Swagger environment also lets you execute API methods directly. Please note that this is not a sandbox environment: these API methods operate directly on your actual Uptrends account. For more information, please visit ... | nilq/baby-python | python |
"""Compose new Django User models that follow best-practices for international names and authenticate via email instead of username."""
# This file:
# 1. define directory as module
# 2. set default app config
# pylint: disable=invalid-name
__version__ = "2.0a1"
# https://docs.djangoproject.com/en/stable/ref/ap... | nilq/baby-python | python |
import utm as UTM
import math
import unittest
class UTMTestCase(unittest.TestCase):
def assert_utm_equal(self, a, b, precision=6):
self.assertAlmostEqual(a[0], b[0], precision)
self.assertAlmostEqual(a[1], b[1], precision)
self.assertEqual(a[2], b[2])
self.assertEqual(a[3].upper(),... | nilq/baby-python | python |
# Software License Agreement (Apache 2.0 License)
#
# Copyright (c) 2021, The Ohio State University
# Center for Design and Manufacturing Excellence (CDME)
# The Artificially Intelligent Manufacturing Systems Lab (AIMS)
# All rights reserved.
#
# Author: Adam Exley
from typing import Union
import numpy as np
from klam... | nilq/baby-python | python |
import os
from pwn import *
class tools():
def __init__(self, binary, crash):
self.binary = binary
self.crash = crash
self.core_list = filter(lambda x:"core" in x, os.listdir('.'))
self.core = self.core_list[0]
def gdb(self, command):
popen=os.popen('gdb '+self.binary+'... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 19 10:36:38 2021
@author: mahdi
"""
import numpy as np
from scipy.linalg import toeplitz
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib import rc
from matplotlib.pyplot import figure
import matplotlib.colors as mcolors
import matp... | nilq/baby-python | python |
import warnings
from sympy.testing.pytest import (
raises,
warns,
ignore_warnings,
warns_deprecated_sympy,
Failed,
)
from sympy.utilities.exceptions import SymPyDeprecationWarning
# Test callables
def test_expected_exception_is_silent_callable():
def f():
raise ValueError()
rai... | nilq/baby-python | python |
# Verhalten sich wie 'Mengen' aus der Mathematik
# Werte müssen einmalig sein
# Kann verwendet werden um Daten aus einer Liste mit doppelungen einmalig zu machen
# Wird oft für das Nachschlagen von Werten verwendet, da sets schneller arbeiten als Listen
# sets können bei bedarf wachsen und schrumpfen
# leere Instanz e... | nilq/baby-python | python |
# convert2.py
# A program to convert Celsius tempts to Fahrenheit
# This version issues heat and cold warnings.
def main():
celsius = float(input("What is the Celsius temperature?"))
fahrenheit = 9/5 * celsius + 32
print("The temperature is", fahrenheit, "degrees fahrenheit.")
# Print warnings for extreme temps
... | nilq/baby-python | python |
import pickle
import os
from pprint import pprint
with open('data.pk', 'rb') as f:
data = pickle.load(f)
data.reset_index(inplace=True, drop=True)
user_list = set(data['name'])
authors = data.groupby('name')
# pprint(authors.groups)
# print(type(authors.groups))
authors_list = {}
for user, index in authors.group... | nilq/baby-python | python |
#Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos dígitos separados.
'''num = str(input('Digite um número de 0 a 9999: '))
print(
'O número: {} está dividido entre as casas:\n'
'unidade: {}\n'
'dezena: {}\n'
'centena: {}\n'
'milhar: {}\n'.format(num, num[3], num[2], num[1... | nilq/baby-python | python |
from .vault import kubeconfig_context_entry
def test_kubeconfig_context_entry_minikube():
mock_context_entry = {
'name': 'minikube',
'context': {
'cluster': 'minikube-cluster',
'user': 'minikube-user',
}
}
assert kubeconfig_context_entry('minikube') == mock_context... | nilq/baby-python | python |
from dagster import repository
from simple_lakehouse.pipelines import simple_lakehouse_pipeline
@repository
def simple_lakehouse():
return [simple_lakehouse_pipeline]
| nilq/baby-python | python |
# -*- coding: UTF-8 -*-
__license__="""
Copyright 2004-2008 Henning von Bargen (henning.vonbargen arcor.de)
This software is dual-licenced under the Apache 2.0 and the
2-clauses BSD license. For details, see license.txt
"""
__version__=''' $Id: __init__.py,v 1.2 2004/05/31 22:22:12 hvbargen Exp $ '''... | nilq/baby-python | python |
from __future__ import absolute_import
from __future__ import print_function
from keras.datasets import stock_one
from keras.models import Sequential
from keras.layers.core import Dense, TimeDistributedDense, Dropout, Activation, Merge
from keras.regularizers import l2, l1
from keras.constraints import maxnorm
from ker... | nilq/baby-python | python |
import numpy as np
import math
from scipy.optimize import linear_sum_assignment
from contourMergeTrees_helpers import *
def branchMappingDistance(nodes1,topo1,rootID1,nodes2,topo2,rootID2,editCost,traceback=False):
memT = dict()
#===================================================================... | nilq/baby-python | python |
from django.contrib import admin
from .models import Customer, User
admin.site.register(Customer)
admin.site.register(User)
| nilq/baby-python | python |
import numpy as np
from models.robots.robot import MujocoRobot
from utils.mjcf_utils import xml_path_completion
class Sawyer(MujocoRobot):
"""
Sawyer is a witty single-arm robot designed by Rethink Robotics.
"""
def __init__(
self,
pos=[0, 0, 0.913],
rot=[0, 0, 0],
... | nilq/baby-python | python |
from tool.runners.python import SubmissionPy
from collections import defaultdict
import operator
class JulesSubmission(SubmissionPy):
def run(self, s):
def find_nearest(points, x, y):
min_distance = 1000
curr_nearest_point = -1
number_having_min_distance = 0
... | nilq/baby-python | python |
from django.contrib import messages
from django.shortcuts import render, get_object_or_404, redirect
from applications.filetracking.models import File, Tracking
from applications.ps1.models import IndentFile,StockEntry
from applications.globals.models import ExtraInfo, HoldsDesignation, Designation
from django.template... | nilq/baby-python | python |
from pygame.mixer import Channel
from pygame_menu import Menu
from pygame_menu.themes import Theme
from pygame_menu.baseimage import BaseImage
from pygame_menu.baseimage import IMAGE_MODE_SIMPLE
from pygame_menu.widgets import MENUBAR_STYLE_NONE
from pygame_menu.widgets.selection.none import NoneSelection
from pygame_m... | nilq/baby-python | python |
import logging
import tensorflow as tf
import ray
from replay.func import create_local_buffer
from algo.apex.actor import Monitor
logger = logging.getLogger(__name__)
def disable_info_logging(config,
display_var=False, save_code=False,
logger=False, writer=False):
config['display_var'] = displa... | nilq/baby-python | python |
import PIL
from PIL import Image
import os
#5:7 Aspect ratio that is larger than cardface pngs
CARD_SIZE = (260, 364)
#adds background to transparent card faces found in /card_faces
def add_background(path):
img = Image.open(path)
dimensions = img.size
background = Image.open('card_background.png')
b... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2020, Anima Istanbul
#
# This module is part of anima-tools and is released under the MIT
# License: http://www.opensource.org/licenses/MIT
import logging
import unittest
import sys
from anima.ui import IS_PYSIDE, IS_PYQT4, reference_editor
logger = logging.getLogger('an... | nilq/baby-python | python |
#!/usr/bin/python3
#
# Read multiple yaml files output one combined json file
#
# This source file is Copyright (c) 2021, FERMI NATIONAL
# ACCELERATOR LABORATORY. All rights reserved.
import os
import sys
import yaml
import json
prog = 'parseconfig.py'
def efatal(msg, e, code=1):
print(prog + ': ' + msg + ': ... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from __future__ import print_function
import os
import sys
from PIL import Image
if __name__ == "__main__":
infile = sys.argv[1]
outfile = os.path.splitext(infile)[0] + ".transpose.png"
if infile != outfile:
try:
with Image.open(infile) as ... | nilq/baby-python | python |
A_1101_10 = {0: {'A': 1.5, 'C': -1.0, 'E': -2.3, 'D': -2.3, 'G': 0.0, 'F': -2.4, 'I': 0.5, 'H': -1.5, 'K': -2.3, 'M': -1.4, 'L': -2.9, 'N': -2.0, 'Q': 0.6, 'P': -2.2, 'S': 1.5, 'R': -2.3, 'T': -1.8, 'W': -1.3, 'V': -2.2, 'Y': -1.9}, 1: {'A': 0.3, 'C': -1.2, 'E': -2.7, 'D': -2.6, 'G': -2.9, 'F': -2.0, 'I': 0.0, 'H': -1.... | nilq/baby-python | python |
# Generated by Django 1.11.3 on 2017-07-07 19:21
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration): # noqa
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Order',
fields=[
... | nilq/baby-python | python |
from django.http.response import HttpResponse
from django.shortcuts import render, redirect
from .models import Pet
from .forms import PetForm
from users.models import User
def All(request):
if not request.user.is_authenticated:
print("This is a not logged user bro:")
return redirect('/accounts/lo... | nilq/baby-python | python |
from controller.qt.controller import QtGameController | nilq/baby-python | python |
from django.test import TestCase
from django.contrib.auth import get_user_model
class ModelTest(TestCase):
def test_create_user_with_email(self):
""" test creating user with email address """
email = "tester@mail.com"
password = "testpassword"
user = get_user_model().objects.creat... | nilq/baby-python | python |
import copy
from typing import List
def selection_sort(x: List) -> List:
"""Selection sort repeatedly swaps the minimum element of a list with the left-most unsorted element, building up
a new list that's fully sorted. It has an average time complexity of Θ(n^2) due to the nesting of its two loops.
Time c... | nilq/baby-python | python |
from typing import Union, Callable, Any, Optional, Dict
import os
import logging
import hashlib
from pathlib import Path
import numpy as np
try:
import soundfile as sf
from espnet2.bin.tts_inference import Text2Speech as _Text2SpeechModel
except OSError as ose:
logging.exception(
"`libsndfile` no... | nilq/baby-python | python |
"""
iorodeo-potentiostat
---------------------
Python interface to LTU Electrocheminiluminescence(ECL)/Potentiometer Shield for the teensy 3.6 development
board. Based upon the IO Rodeostat potentiometer (Will Dickson, http://stuff.iorodeo.com/docs/potentiostat).
"""
from setuptools import setup, find_packages... | nilq/baby-python | python |
# TODO: Implement this script fpr
as5048aencoder = Runtime.start("as5048aencoder","As5048AEncoder")... | nilq/baby-python | python |
# Copyright 2022 The Bazel 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 applicable la... | nilq/baby-python | python |
from data_structures.queue.queue import Queue
# You have a group of people
# One person is holding a hot potato
# Each turn the person passes the potato to the person in the left
# Then the person gives the potato to his left and then leaves
def play_hot_potato_game(items, reps):
queue = Queue()
# O(n)
... | nilq/baby-python | python |
from gaia_sdk.graphql.request.type.BuildInEvaluation import BuildInEvaluation
from gaia_sdk.graphql.request.type.SkillEvaluation import SkillEvaluation
from typing import Callable, List
from gaia_sdk.api.VariableRegistry import VariableRegistry
from gaia_sdk.graphql.request.enumeration.Order import Order
from gaia_sd... | nilq/baby-python | python |
"""
Finds and stores the voting data for each candidate in every district
in the Russia 2018 Presidential election.
"""
import re
from os import stat
import time
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdri... | nilq/baby-python | python |
# coding:utf-8
# @Time : 2021/6/29
# @Author : fisher yu
# @File : file_hash.py
"""
file hash: v0.0.1
"""
import argparse
import hashlib
import os
chunkSize = 8 * 1024
def valid_file(file_path):
if os.path.exists(file_path) and os.path.isfile(file_path):
return True
return False
def fil... | nilq/baby-python | python |
{
'targets': [
{
'target_name': 'binding',
'sources': [ 'binding.cc' ],
'libraries': ['-lzmq'],
'cflags!': ['-fno-exceptions'],
'cflags_cc!': ['-fno-exceptions'],
'conditions': [
['OS=="mac"', {
'xcode_settings': {
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
def main():
s = input()
t = s[::-1]
n = len(s) // 2
count = 0
for i in range(n):
if s[i] != t[i]:
count += 1
print(count)
if __name__ == '__main__':
main()
| nilq/baby-python | python |
try:
import config_local as config
except:
import config
import requests
headers = {"User-Agent": "http-url-test"}
response = requests.get(config.url, headers=headers)
print('Response URL:', response.url)
print(response.text)
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-05-28 23:39
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import multiselectfield.db.fields
class Migration(migrations.Migration):
dependencies = [
... | nilq/baby-python | python |
from unyt._unit_lookup_table import *
| nilq/baby-python | python |
from datetime import datetime, timedelta
from msl.qt import QtCore, QtGui, QtWidgets, Button
from ...log import log
from ...constants import FONTSIZE
def chop_microseconds(delta):
return delta - timedelta(microseconds=delta.microseconds)
class WaitUntilTimeDisplay(QtWidgets.QDialog):
def __init__(self, l... | nilq/baby-python | python |
import os
import glob
import pandas as pd
import xml.etree.ElementTree as ET
def xml_to_csv(path):
xml_list = []
# 讀取標註檔案
for xml_file in glob.glob(path + '/*.xml'):
tree = ET.parse(xml_file)
root = tree.getroot()
for member in root.findall('object'):
value = (str(root.... | nilq/baby-python | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import ray
from ray.rllib.evaluation.postprocessing import compute_advantages, \
Postprocessing
from ray.rllib.policy.tf_policy_template import build_tf_policy
from ray.rllib.policy.sample_batch import Samp... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 8 14:37:57 2020
"""
from gensim import models
#import pymysql
import pandas as pd
#import MeCab
#from progressbar import ProgressBar
#import time
#from pandas import Series,DataFrame
#from gensim import corpora,matutils
#from gensim.models import word2ve... | nilq/baby-python | python |
import random
import string
from collections import namedtuple
from unittest.mock import patch
from uuid import uuid4
from django.test import TestCase
from django.utils import timezone
from requests.exceptions import ConnectionError
from corehq.apps.accounting.models import SoftwarePlanEdition
from corehq.apps.accou... | nilq/baby-python | python |
from performance_tests import generate_problem
from Drawing import draw_problem_configuration
import matplotlib.pyplot as plt
for name in ['barriers', 'hallway', 'narrow', 'split', 'maze']:
environment, robot, start, goal = generate_problem(name)
plt.close()
draw_problem_configuration(environment, robot, ... | nilq/baby-python | python |
'''input
6
red
red
blue
yellow
yellow
red
5
red
red
yellow
green
blue
1
1
voldemort
10
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
voldemort
0
3
apple
orange
apple
5
apple
apple
apple
apple
apple
1
6
red
red
blue
yellow
... | nilq/baby-python | python |
import urllib
import requests
import json
import datetime
import os
import argparse
import pandas as pd
if __name__ == '__main__':
from Code.cdi_class import CDI_Dataset
from Code.cdi_validator import CDI_Masterlist_QA, Extra_Data_Gov
from Code.tag_validator import Climate_Tag_Check, Export_Retag_Request
... | nilq/baby-python | python |
import maya.cmds as cmds
import re
import rsTools.utils.openMaya.dataUtils as dUtils
import maya.OpenMayaAnim as OpenMayaAnimOld
import maya.OpenMaya as OpenMayaOld
import maya.api.OpenMaya as om
import maya.api.OpenMayaAnim as oma
def isDeformer(deformer):
if not cmds.objExists(deformer):
return False
... | nilq/baby-python | python |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2018-present MagicStack Inc. and the EdgeDB authors.
#
# 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... | nilq/baby-python | python |
# flake8: noqa F401
from ask_cfpb.models.django import (
ENGLISH_PARENT_SLUG, SPANISH_PARENT_SLUG, Answer, Audience, Category,
NextStep, SubCategory, generate_short_slug
)
from ask_cfpb.models.pages import (
ABOUT_US_SNIPPET_TITLE, CONSUMER_TOOLS_PORTAL_PAGES,
ENGLISH_ANSWER_SLUG_BASE, ENGLISH_DISCLAIME... | nilq/baby-python | python |
"""
Test cases for customers Model
"""
import logging
import unittest
import os
from service.models import Customer, DataValidationError, db
from service import app
from service.models import Customer, DataValidationError, db
from werkzeug.exceptions import NotFound
DATABASE_URI = os.getenv(
"DATABASE_URI", "po... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Copyright [2009-2021] 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... | nilq/baby-python | python |
#--------------------------------------------
# calculate auc, tpr, tnr with n bootstrap
#-------------------------------------------
import os
import numpy as np
import pandas as pd
import glob
from sklearn.utils import resample
import scipy.stats as ss
from utils.mean_CI import mean_CI
from sklearn.metrics import ro... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2022 all rights reserved
#
# externals
import re
# the framework
import pyre
# my superclass
from .ProjectTemplate import ProjectTemplate
# declaration
class React(ProjectTemplate, family='pyre.smith.projects.react'):
"""
Encapsulation... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# TCP
import socket
# Client
# # create
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#
# # connect
# s.connect(('www.sina.com.cn', 80))
#
# # AF_INET IPV4
# # AF_INET6 IPV6
# # SOCK_STREAM 使用面向流的TCP协议
# # connect 参数是tuple 包含ip和port
#
# # send
# s.send(b'GET / ... | nilq/baby-python | python |
import random
from bos_consensus.common import Ballot, BallotVotingResult
from bos_consensus.consensus import get_fba_module
IsaacConsensus = get_fba_module('isaac').Consensus
class DivergentVotingConsensus(IsaacConsensus):
faulty_frequency = None
faulty_ballot_ids = None # store the ballot to be fault
... | nilq/baby-python | python |
'''
I was given this problem in an interview. How would you have answered?
Design a data structure that offers the following operations in O(1) time:
insert
remove
contains
get random element
Consider a data structure composed of a hashtable H and an array A. The hashtable keys are the elements in the data structur... | nilq/baby-python | python |
import time
import board
import busio
import adafruit_adxl34x
i2c = busio.I2C(board.SCL, board.SDA)
# For ADXL343
accelerometer = adafruit_adxl34x.ADXL343(i2c)
# For ADXL345
# accelerometer = adafruit_adxl34x.ADXL345(i2c)
accelerometer.enable_freefall_detection()
# alternatively you can specify attribut... | nilq/baby-python | python |
import abc
from .card import CardType, Icons
class Tableau(abc.ABC):
def __init__(self, player_name, cash=0, thugs=None, holdings=None, hand=None):
self.player_name = player_name
self._cash = cash
self.thugs = thugs if thugs else []
self.holdings = holdings if holdings else []
... | nilq/baby-python | python |
from Bio import SeqIO
import os
from utils import batch_iterator, create_dir
import csv
import collections
class DeepLocExperiment:
"""
Class to set up DeepLoc experiments:
1) convert fasta -> csv for Pytorch
2) split csv -> train and test
"""
def __init__(self, fasta_path, domains_path, output_path, label_na... | nilq/baby-python | python |
class DependenciesMatrixError(Exception):
def __init__(self, msg, desc=None):
super().__init__(self, msg)
self.msg = msg
self.desc = desc
def __str__(self):
return f"DependenciesMatrixError: {self.msg}\nDescription: {self.desc}"
class PropabilityMatrixError(Exception):
def... | nilq/baby-python | python |
import math
from functools import reduce
import aiger
import funcy as fn
from aigerbv import atom, UnsignedBVExpr
from aiger_coins import utils
def coin(prob, input_name=None):
# TODO: reimplement in terms of common_denominator_method.
prob = utils.to_frac(prob)
mux, is_valid = mutex_coins({'H': prob, '... | nilq/baby-python | python |
"""
MIT License
Copyright (c) 2022 VincentRPS
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, merge, publish, di... | nilq/baby-python | python |
# -------------------------------------------------------------------------------
#
# Copyright (C) 2017 Cisco Talos Security Intelligence and Research Group
#
# PyREBox: Python scriptable Reverse Engineering Sandbox
# Author: Xabier Ugarte-Pedrero
#
# This program is free software; you can redistribute it and/... | nilq/baby-python | python |
from unittest import TestCase
import numpy as np
import pandas as pd
from fireant.queries.pandas_workaround import df_subtract
class TestSubtract(TestCase):
def test_subtract_partially_aligned_multi_index_dataframes_with_nans(self):
df0 = pd.DataFrame(
data=[
[1, 2],
... | nilq/baby-python | python |
"""Keras Sequence for running Neural Network on graph edge prediction."""
from typing import List
import numpy as np
import tensorflow as tf
from ensmallen import Graph # pylint: disable=no-name-in-module
from keras_mixed_sequence import Sequence
from embiggen.utils.tensorflow_utils import tensorflow_version_is_highe... | nilq/baby-python | python |
from django.utils import timezone
from django.conf import settings
from rest_framework import serializers
from apps.todos.models import Todo
class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = Todo
fields = (
'pk', 'author', 'title', 'description',
'de... | nilq/baby-python | python |
import pygame
class Sprite(pygame.sprite.Sprite):
def __init__(self, image, spawn_x, spawn_y):
super().__init__()
self.image = pygame.image.load(image)
self.rect = self.image.get_rect()
self.rect.center = [spawn_x, spawn_y]
def update(self):
pass
def ... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.