content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
#!/usr/bin/env python # encoding: utf-8 class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ r = 0 hd...
nilq/baby-python
python
import atexit from pathlib import Path from typing import Dict, Union from .template import BaseTemplate from .exceptions import NotFoundError class MemoryEngine(object): _data: Dict _path: Path _template: BaseTemplate def __init__(self, path: Union[Path, str], template: BaseTemplate, auto_load=True...
nilq/baby-python
python
#!/usr/bin/python #Libraries import RPi.GPIO as GPIO import time #GPIO Mode (BOARD / BCM) GPIO.setmode(GPIO.BCM) #set GPIO Pins GPIO_TRIGGER = 18 GPIO_ECHO = 24 GPIO_IR = 6 #set GPIO direction (IN / OUT) GPIO.setup(GPIO_TRIGGER, GPIO.OUT) GPIO.setup(GPIO_ECHO, GPIO.IN) GPIO.setup(GPIO_IR, GPIO.IN, pull_up_down=GPI...
nilq/baby-python
python
# -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ from projects.tokens import token_generator from rest_framework import permissions class HasAPIAccess(permissions.BasePermission): """ """ message = _('Invalid or missing API Key.') def has_permission(self, request, view): ...
nilq/baby-python
python
# Copyright 2019-2020 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" fil...
nilq/baby-python
python
#!/usr/bin/env python import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # A script to test the mask filter. # replaces a circle with a color # Image pipeline reader = vtk.vtkPNMReader() reader.ReleaseDataFlagOff() reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/earth.ppm") reade...
nilq/baby-python
python
""" Testing area package """ from shapes.square.area import area_square from shapes.square.perimeter import perimeter_square import pytest def test_square_area(): """ testing function area_square """ length = 2 A = area_square(length) assert pytest.approx(A) == 4.0 def test_square_perimeter...
nilq/baby-python
python
from dataset import FontData, make_tfrecodes gspath='gs://your-bucket-name/' def make1(): d = FontData() make_tfrecodes(d, gspath, 512, 64, 8, train=True) make_tfrecodes(d, gspath, 512, 64, 8, train=False) if __name__ == "__main__": make1()
nilq/baby-python
python
import zipfile import pytest from git_taxbreak.modules.writer import Writer @pytest.fixture def patch_zip_file(monkeypatch): class ZipFileMock(zipfile.ZipFile): def __init__(self, *args, **kwargs): self.output = args[0] self.content = [] def __enter__(self): r...
nilq/baby-python
python
import sys import shutil from pathlib import Path import logging from pcv import DEFAULTS_PATH, CALLER_PATH, SOURCE, STATIC, DIST """ Initializes a pcv project in the current folder. Run from command line: python -m pcv.start This will create the following directory tree in the current folder: ....
nilq/baby-python
python
import numpy as np import PatternToNumber def computing_frequencies(text, k): m = 4**k frequency_array = np.zeros(shape = (1, m), dtype = int) for i in range(len(text) - k + 1): pattern = text[i:i+k] j = PatternToNumber.pattern_to_number(pattern) frequency_array[0 , j] = frequency_array[0, j] + 1 return...
nilq/baby-python
python
# Copyright(C) Facebook, Inc. and its affiliates. All Rights Reserved. from typing import Dict, List import numpy as np import xarray as xr from .base_jags_impl import BaseJagsImplementation class RobustRegression(BaseJagsImplementation): def __init__(self, **attrs: Dict) -> None: self.attrs = attrs ...
nilq/baby-python
python
import discord import os from keep_alive import keep_alive client = discord.Client() @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.event async def on_message(message): if message.author == client.user: return if str(message.author) in ["robbb...
nilq/baby-python
python
""" Command line utility for repository """ import fire from repo_utils import get_repository_path import os import importlib # This will make available all definitions found under the same package that this file is found. # This allows making a command line out of any package with the repo_utils template by putting s...
nilq/baby-python
python
from random import choice from typing import Union from datetime import datetime from discord import User, Member, Embed from discord.ext import commands from bot.main import NewCommand class Hug(commands.Cog): def __init__(self, client): self.client = client def randomise(self, users:list): ...
nilq/baby-python
python
from django.core.urlresolvers import reverse from django.test import TestCase from django.utils import timezone from transductor.models import EnergyTransductor, TransductorModel class EnergyTransductorViewsTestCase(TestCase): def setUp(self): t_model = TransductorModel() t_model.name = "TR 4020" ...
nilq/baby-python
python
''' Created on March 30, 2018 @author: Alejandro Molina ''' import numpy as np from spn.algorithms.StructureLearning import get_next_operation, learn_structure from spn.algorithms.Validity import is_valid from spn.algorithms.splitting.Clustering import get_split_rows_KMeans, get_split_rows_TSNE from spn.algorithms.s...
nilq/baby-python
python
__version__ = "0.0.1" from ._widget import LiveIDS from .video_ui import initui
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('eventlog', '0037_auto_20180911_1252'), ] operations = [ migrations.RemoveField( model_name='celerytaskprogress',...
nilq/baby-python
python
import pytest from kaneda.backends import BaseBackend class DummyBackend(BaseBackend): reported_data = {} def report(self, name, metric, value, tags, id_=None): payload = self._get_payload(name, value, tags) payload['metric'] = metric self.reported_data[name] = payload @pytest.fixt...
nilq/baby-python
python
#!/usr/bin/env python """ Copy one netCDF file to another with compression and sensible chunking Adapted from nc3tonc4 https://github.com/Unidata/netcdf4-python/blob/master/utils/nc3tonc4 """ from netCDF4 import Dataset import numpy as np import numpy.ma as ma import os import sys import math import op...
nilq/baby-python
python
#!/usr/bin/python3 __author__ = 'yangdd' ''' example 034 ''' def hello_world(): print('Hello World') def three_hello(): for i in range(3): hello_world() if __name__ == '__main__': three_hello()
nilq/baby-python
python
from xml.etree import ElementTree import csocha from . import board, moves class GameState: def __init__(self, c: str, t: int, b: board.Board, undep: list): self.color = c self.opponent = "BLUE" if c == "RED" else "RED" self.turn = t self.board = b self.undeployed = undep ...
nilq/baby-python
python
from fastapi import FastAPI TAREFAS = [ {"id": 1, "titulo": "Cristiano"}, {"id": 2, "titulo": "Araujo"} ] app = FastAPI() @app.get('/tarefas') def listar(): return TAREFAS
nilq/baby-python
python
import string from model_mommy import mommy from datetime import datetime from django_rq import job from django.contrib.auth.models import User from django.utils import timezone from dateutil.parser import parse as extract_date from django.conf import settings from survey.models import * from survey.utils.decorators im...
nilq/baby-python
python
from scraper.web_scraper import WebScraper from loguru import logger uri = 'https://www.investing.com/technical/technical-summary' class SummaryTableScraper(WebScraper): def __init__(self, uri, class_name): super(SummaryTableScraper, self).__init__() self.goto(uri) self.n_table_pairs = ...
nilq/baby-python
python
import Bdecode as BD import pprint class Torrent: def __init__(self, filename): decoder = BD.Bdecode(filename) self.torrentData = decoder.decode() # self.meta_info = bencoding.Decoder(meta_info).decode() def __str__(self): whatever = pprint.pprint(self.torrentDa...
nilq/baby-python
python
import collections from collections import OrderedDict class ValidationError(Exception): def __init__(self, errors): self.errors = ValidationError.normalise(errors) @staticmethod def normalise(errors): if isinstance(errors, dict): new_errors = OrderedDict() for k,...
nilq/baby-python
python
from school.models.class_model import Class from account.models.instructor_model import InstructorProfile from country.models.country_model import Country from country.models.city_model import City from school.models.school_model import School from django.urls.base import reverse from rest_framework.test import APITest...
nilq/baby-python
python
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Persistent identifier minters.""" from __future__ import absolute_import, print_f...
nilq/baby-python
python
from threading import local from django.test import TestCase from django.test import override_settings from cid.locals import generate_new_cid from cid.locals import get_cid from cid.locals import set_cid _thread_locals = local() class TestCidStorage(TestCase): def setUp(self): self.clear_cid() ...
nilq/baby-python
python
'''Tools for interaction with IDF build system''' def build_name(name): name_parts = name.split('/') return '__'.join(name_parts)
nilq/baby-python
python
from torch.utils.data import Dataset, DataLoader from albumentations import (ShiftScaleRotate, Compose, CoarseDropout, RandomCrop, HorizontalFlip, OneOf, ElasticTransform, OpticalDistortion, RandomGamma, Resize, GaussNoise, VerticalFlip, RandomBrightnessContrast) import cv2 import os i...
nilq/baby-python
python
#!/usr/bin/env python from subprocess import check_call import sys import os import traceback def safe_remove(f): try: if os.path.exists(f): os.remove(f) except: traceback.print_exc() pass def tsprint(msg): sys.stderr.write(msg) sys.stderr.write("\n") if __name...
nilq/baby-python
python
from .__init__ import * def gen_func(maxRadius=100, format='string'): r = random.randint(1, maxRadius) ans = round((2 * math.pi / 3) * r**3, 3) if format == 'string': problem = f"Volume of hemisphere with radius {r} m = " solution = f"{ans} m^3" return problem, solution ...
nilq/baby-python
python
# -*- coding:utf8 -*- ''' export data ''' import logging import xlwt from LMDI import Lmdi from SinglePeriodAAM import Spaam from MultiPeriodAAM import Mpaam class WriteLmdiData(object): ''' write data using with surrounding ''' def __init__(self, xls_file_name, *lmdis): ''' constructio...
nilq/baby-python
python
from pathlib import PurePath def part1(l: list[int]) -> int: l = l.copy() i = 0 while i < len(l): match l[i]: case 1: l[l[i + 3]] = l[l[i + 1]] + l[l[i + 2]] i += 3 case 2: l[l[i + 3]] = l[l[i + 1]] * l[l[i + 2]] ...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-06 21:11 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('marketgrab', '0008_remove_data_v'), ] operations = [ migrations.AddField( ...
nilq/baby-python
python
from django.contrib import admin from . import models def push_to_influxdb(modeladmin, request, queryset): for row in queryset: row.push_to_influxdb() @admin.register(models.Instance) class InstanceAdmin(admin.ModelAdmin): list_display = [ 'name', 'url', 'users', 's...
nilq/baby-python
python
"""https://open.kattis.com/problems/provincesandgold""" from collections import OrderedDict vic, tres = OrderedDict(), OrderedDict() vic = {"Province": 8, "Duchy": 5, "Estate": 2} tres = {"Gold": 6, "Silver": 3, "Copper": 0} inp = list(map(int, input().split())) money = inp[0] * 3 + inp[1] * 2 + inp[2] options = [] ...
nilq/baby-python
python
#This script is hijacked from targetscan_parsecontextscores.py. It asks which miRNAs #are enriched for having sites in a particular sequence set. Actually, more precisely, #it just gives the density of sites for each miRNA. Number of sites for a miRNA / total sequence #search space. import os import gffutils impor...
nilq/baby-python
python
from cansfr import * class can11xx (object): ''' can11xx hierarchy ----------------- canm0 {sfr / updrpl - ams ~ ~ {i2c / ...
nilq/baby-python
python
from __future__ import print_function import argparse import pickle import os import time import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np from torchvision import datasets, transforms class Net(nn.Module): def __init__(self): super(Net, self)...
nilq/baby-python
python
# coding: utf-8 """ Cisco Intersight Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environmen...
nilq/baby-python
python
# -*- coding: utf-8 -*- # # michael a.g. aïvázis # orthologue # (c) 1998-2020 all rights reserved # """ This package provides the implementation of a simple evaluation network. There are three fundamental abstractions: variables, operators, and literals. Variables hold the values computed by the evaluation network, ...
nilq/baby-python
python
#!/usr/bin/env python3 # coding: utf-8 import os import glob import sfml as sf class Animation: """ An animated texture. """ def __init__(self, frames, interval=0): """ :param frames: Iterable of sf.Texture objects :param interval: Time between two frames (default: 0.0s) """ self.frames = frames s...
nilq/baby-python
python
import os import sys sys.path.append(os.path.dirname(os.path.dirname(__file__))) from utils import get_args, get, print_args, get_seed, extract_seed_from_ckpt from logger import set_logger from vilmedic.executors import Trainor, Validator def main(): # Get args and create seed config, override = get_args() ...
nilq/baby-python
python
import h5py import os from ._core import hfile from .. import utils from .. import h5tree def test_h5tree(hfile): assert hfile is not None assert os.path.exists(hfile) assert not utils.isHdf5FileObject(hfile) str_list = [ b"Q=1", b"Q=0.1", b"Q=0.01", b"Q=0.001", ...
nilq/baby-python
python
from uuid import uuid1 POSTGRES_MAX_TABLE_NAME_LEN_CHARS = 63 NULL_CHARACTER = "\\N" def generate_table_name(source_table_name: str) -> str: table_name_template = "loading_{source_table_name}_" + uuid1().hex # postgres has a max table name length of 63 characters, so it's possible # the staging table nam...
nilq/baby-python
python
''' black_scholes.py Created on Oct 11, 2018 @author: William Quintano ''' from scipy.stats import norm import math ''' Calculates the price of a stock option using the black scholes model :param s strike price :param t remaining lifespan of option in years :param u price of underlying stock (To get call...
nilq/baby-python
python
#!/usr/bin/env python from argparse import ArgumentParser from distutils.util import get_platform from setuptools import find_packages, setup parser = ArgumentParser() parser.add_argument("--plat-name", type=str, default=get_platform()) args, unknown_args = parser.parse_known_args() if args.plat_name == "win32": ...
nilq/baby-python
python
# Generated by Django 3.2.3 on 2021-06-06 17:24 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('asset', '0001_initial'), ('category', '0001_initial'), ] operations = [ migrati...
nilq/baby-python
python
#!/usr/bin/env dls-python2.7 """Write coordinated magnet moves to different outputs. A PvWriter and a Simulation writer are available to take magnet_jogs.Moves and apply them to their respective interfaces. """ from cothread.catools import caput from controls import PvReferences, PvMonitors, Arrays import magnet_jo...
nilq/baby-python
python
"""Test BrownianExcursion.""" import pytest from stochastic.processes.continuous import BrownianExcursion def test_brownian_excursion_str_repr(t): instance = BrownianExcursion(t) assert isinstance(repr(instance), str) assert isinstance(str(instance), str) def test_brownian_excursion_sample(t, n, thresh...
nilq/baby-python
python
import random class RandomFlip(object): """Flips node positions along a given axis randomly with a given probability. Args: axis (int): The axis along the position of nodes being flipped. p (float, optional): Probability that node positions will be flipped. (default: :obj:`0.5...
nilq/baby-python
python
def is_lock_ness_monster(s): return any(phrase in s for phrase in ["tree fiddy", "three fifty", "3.50"])
nilq/baby-python
python
import json import pandas as pd import time ################################# # #with open('logs.json', 'r') as data: # data = data.read() # #logs = json.loads(data) # ######################## def get_data(file): with open(file, 'r') as data: data = data.read() logs = json.loads(data) #s = Sender('Test', '192...
nilq/baby-python
python
# coding: utf-8 import datetime import random from http import HTTPStatus from unittest.mock import Mock from django.test.client import RequestFactory import pytest from src.infrastructure.api.views.exchange_rate import ( CurrencyViewSet, CurrencyExchangeRateViewSet) from tests.fixtures import currency, exchang...
nilq/baby-python
python
import mysql.connector # Multicraft Cred mydb = mysql.connector.connect( host="", user="", password="", database="" ) mycursor = mydb.cursor() # WHMCS Cred mydb_whmcs = mysql.connector.connect( host="", user="", password="", database="" ) mycursor_whmcs = mydb_whmcs.cursor()
nilq/baby-python
python
import argparse import sys import analyse import calibration from logginghelpers import configure_logging ALL_CMD = 'all' MUNICIPALITY_CMD = 'municipality' def parse_settings(settings) -> dict: result = {} if settings is not None: for setting in settings: k, v = setting.split('=') ...
nilq/baby-python
python
import sys import time import pygame from pygame.locals import * from classes.disk import Disk from classes.robot import Robot from classes.exit import Exit """ This class is used for the simulation It loops 60 times a second so it can draw and update the simulation """ class Window: def __init__(self): ...
nilq/baby-python
python
from os import name from django.urls import path, include from .views import * urlpatterns = [ path('latest-products/', LatestProductsList.as_view(), name="latest-products"), path('checkout/', checkout, name="checkout"), path('orders/', OrdersList.as_view(), name="orders"), path('products/search/', sea...
nilq/baby-python
python
from Cartas import Baraja, Carta import os Line = '---------------------------' def clear(): if os.name == "nt": os.system("cls") else: os.system("clear") class Jugador: def __init__(self, nombre: str, mazo: Baraja): self.nombre = nombre self.cardSum = 0 self.aca...
nilq/baby-python
python
import time import random import itertools as it from pathlib import Path from collections import namedtuple import numpy as np import torch.nn.functional as F from vizdoom import DoomGame, ScreenResolution, \ ScreenFormat, GameVariable, Mode, Button from utils.helpers import get_logger logger = get_logger(__fil...
nilq/baby-python
python
import dash import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as dbc import pandas as pd import plotly.graph_objs as go dataset_train = pd.read_csv('sg_train.csv') dataset_train_copy = dataset_train.copy() dataset_train_copy = dataset_train_copy.sort_value...
nilq/baby-python
python
import unittest import xmlconfigparse import xml.etree.ElementTree as ET import xml.etree.ElementPath as EP class XmlToDictTest(unittest.TestCase): """ """ @classmethod def setUpClass(cls): """Creates new xml file to test""" # Creates xml file to be modified by test root = ET...
nilq/baby-python
python
from typing import Literal foo: Literal[""] = "" bar: Literal[''] = ''
nilq/baby-python
python
time_travel = int(input()) speed_travel = int(input()) liters = (speed_travel * time_travel) / 12 print('{:.3f}'.format(liters))
nilq/baby-python
python
import os import re import ssl from operator import itemgetter import requests import urllib3 from bs4 import BeautifulSoup from smart_open import open ssl._create_default_https_context = ssl._create_unverified_context urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) MAIN_PAGE = "https://tff.org/d...
nilq/baby-python
python
# Copyright 2020 Dylan Baker # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, sof...
nilq/baby-python
python
# FinSim # # Copyright 2019 Carnegie Mellon University. All Rights Reserved. # # NO WARRANTY. THIS CARNEGIE MELLON UNIVERSITY AND SOFTWARE ENGINEERING INSTITUTE MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. CARNEGIE MELLON UNIVERSITY MAKES NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, AS TO ANY MATTER INCLUDING,...
nilq/baby-python
python
#Follow up for "Unique Paths": # #Now consider if some obstacles are added to the grids. How many unique paths would there be? # #An obstacle and empty space is marked as 1 and 0 respectively in the grid. # #For example, #There is one obstacle in the middle of a 3x3 grid as illustrated below. # #[ # [0,0,0], # [0,1,0],...
nilq/baby-python
python
# 给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。 # # 示例 : # 给定二叉树 # # 1 # / \ # 2 3 # / \ # 4 5 # 返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。 # # 注意:两结点之间的路径长度是以它们之间边的数目表示。 # # 来源:力扣(LeetCode) # 链接:https://leetcode-cn.com/problems/diameter-of-binary-tree # 著作权归领扣网络所有。商...
nilq/baby-python
python
#!/usr/bin/env python """ Creates MRI axial pictures for custom T-shirt. Usage: mripicture.py [options] <study> mripicture.py [options] <study> [-s <subject>]... mripicture.py [options] <study> [-s <subject>]... [-t <tag>] Arguments: <study> Nickname of the study to process Options: -...
nilq/baby-python
python
#!/usr/bin/env python3 from calendar import monthrange year = int( input() ) ( startDay, endDay ) = monthrange( year-543, 2 ) print( endDay )
nilq/baby-python
python
#!/usr/bin/python3 import os import time from datetime import datetime as dt import logging #from .database.database import * from threading import Thread class BloquearSites: def __init__(self): logging.basicConfig(filename="C:\\ConectaIT\\modules" + '\\logs\\logBloquearSites.log') #s...
nilq/baby-python
python
#numeric integration using the 2-point trapezoidal rule from math import * EPSILON = .0001 #base length of trapezoids def evaluate_function(func, a): func_at_a = eval(func.replace('x', str(a))) return func_at_a #doesnt yet take into account ability of domain a,b to have b<a def integrate(func, domain): ...
nilq/baby-python
python
__author__ = 'Jay Hennessy <tjay.hennessy@gmail.com>' __license__ = 'MIT' import os __version__ = '0.0.1' # fantraxpy version VERSION = '17.0.0' # fantrax version URL = 'https://www.fantrax.com/fxpa/req' FANTRAX_TOKEN = os.environ.get('FANTRAX_TOKEN', None)
nilq/baby-python
python
""" This module contains tests for the utility functions in the test_mapping module. """ import pytest from sqlalchemy import ( Column, Index, Integer, UniqueConstraint, ) from sqlalchemy.orm import registry from galaxy.model import _HasTable from . import ( collection_consists_of_objects, has_...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by Django 1.11.9 on 2018-03-22 14:40 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( ...
nilq/baby-python
python
# Mod01.py from MyCalc01 import Calc01 from MyCalc01.Calc01 import * x= 100; y= 200 print(Calc01.__name__) Calc01.Sum(x, y) Mul(x,y)
nilq/baby-python
python
class ValidationException(Exception): pass class DataApiException(Exception): "For errors raised when reading from data api"
nilq/baby-python
python
# Copyright (c) 2019-2020 SAP SE or an SAP affiliate company. All rights reserved. This file is # licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the L...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Class for a multi-panel structure """ __version__ = '1.0' __author__ = 'Noemie Fedon' import sys import numpy as np sys.path.append(r'C:\BELLA') from src.BELLA.parameters import Parameters from src.BELLA.constraints import Constraints from src.BELLA.panels import Panel from s...
nilq/baby-python
python
import warnings import dateutil.parser from requests import Session from time import sleep from .config import ( # noqa __version__, API_ROOT, DEFAULT_USER_AGENT, API_KEY_ENV_VAR, ENVIRON_API_KEY, ) session = Session() session.headers.update({"Accept": "application/json"}) session.headers.update(...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # Distributed under the terms of the MIT License. """ Script to append window and cage COM's to a CIF. Author: Andrew Tarzia Date Created: 19 Feb 2019 """ import sys from ase.io import read import pywindow as pw import logging import os import atools def main(): i...
nilq/baby-python
python
# Copyright (C) 2013 by Brian Neal. # This file is part of m209, the M-209 simulation. # m209 is released under the MIT License (see LICENSE.txt). """test_converter.py - Unit tests for the M209 class for the M-209 simulation.""" import unittest from .. import M209Error from ..converter import M209 # Data taken fro...
nilq/baby-python
python
from os import listdir import json from pymongo import MongoClient prediction_output = '../data/prediction_output/' # Edit def connect_db(mode, db_name): client = MongoClient('localhost', 27017) db = client[db_name] collection = db['train'] if mode == 'train' else db['val'] return collection if __nam...
nilq/baby-python
python
from wsgiref.util import FileWrapper from django.conf import settings from django.http import Http404, HttpResponse, StreamingHttpResponse from django.shortcuts import get_object_or_404, redirect from django.template.response import TemplateResponse from django.urls import reverse from wagtail.core import hooks from ...
nilq/baby-python
python
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. # This product includes software developed at Datadog (https://www.datadoghq.com/). # Copyright 2019-Present Datadog, Inc. from datadog_api_client.v1.model_utils import ( ModelNormal, cached_property, ...
nilq/baby-python
python
import demistomock as demisto from CommonServerPython import * # noqa: E402 lgtm [py/polluting-import] from CommonServerUserPython import * # noqa: E402 lgtm [py/polluting-import] # IMPORTS from typing import Tuple, Optional import traceback import dateparser import httplib2 import urllib.parse from oauth2client imp...
nilq/baby-python
python
from django.shortcuts import render, redirect from django import forms from django.contrib import messages from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth import authenticate, login, update_session_auth_hash from django.contrib.auth.models import User from django.contrib.auth.decorator...
nilq/baby-python
python
import math, itertools from functools import lru_cache def distance_squared(p1, p2): x1, y1 = p1 x2, y2 = p2 dx, dy = x1 - x2, y2 - y1 return dx * dx + dy * dy def points_up_tile_size_px(size): return math.floor(size * math.sqrt(3)), size * 2 def flats_up_tile_size_px(size): return size * ...
nilq/baby-python
python
class Board: ROW_COL_BASE = 1 def __init__(self, board, N): """ Builds a Board from a list of blocks and the size of the board. The list must hold N^2 blocks. :param board: the list with the blocks. :param N: the size of the board (length = width = N) :return: a new B...
nilq/baby-python
python
#!/usr/bin/env python3 """ Clean up (making tar) a single simulation directory after successful cybershake submissions """ import os import glob import shutil import tarfile import argparse from qcore import utils SUBMISSION_DIR_NAME = "submission_temp" SUBMISSION_TAR = "submission.tar" SUBMISSION_FILES = [ "fli...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Spyder Editor APRI和FIB4推测肝纤维化或肝硬化情况 This is a temporary script file. """ import math #APRI缩写:AST to Platelet Ratio Index #AST单位iu/l #PRI单位10**9/L #如果APRI>2,可能有肝硬化 def APRI(AST,upper_AST,PRI): apri=((AST*1.0/upper_AST)*100)/PRI return apri #FIB-4缩写Fibrosis-4 #age单位:年 #AST和ALT单...
nilq/baby-python
python
""" :class:`Registrable` is a "mixin" for endowing any base class with a named registry for its subclasses and a decorator for registering them. """ import importlib import logging from collections import defaultdict from typing import ( Callable, ClassVar, DefaultDict, Dict, List, Optional, ...
nilq/baby-python
python
import functools import os import pickle # decorator for pickle-caching the result of a function def pickle_cache(cache_filename, compare_filename_time=None, overwrite=False): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): exists = os.path.exists(cache_filena...
nilq/baby-python
python
# Generated by Django 3.0.4 on 2021-04-13 19:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('website', '0004_uploader_image_l'), ] operations = [ migrations.AlterField( model_name='uploader', name='id', ...
nilq/baby-python
python
# "THE BEER-WARE LICENSE" (Revision 42): # <flal@melix.net> wrote this file. As long as you retain this notice you can do whatever you want with this stuff. If we meet some day, and you think this stuff is worth it, you can buy me a beer in return # read a json describing people do the magic to pick two different peop...
nilq/baby-python
python