content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
from typing import List from datetime import datetime from numpy import datetime64 from pandas import DataFrame from dolphindb import ( session, DBConnectionPool, PartitionedTableAppender, Table ) from vnpy.trader.constant import Exchange, Interval from vnpy.trader.object import BarData, TickData from...
nilq/baby-python
python
from __future__ import absolute_import __author__ = "akniazev" from collections import OrderedDict
nilq/baby-python
python
""" File: similarity.py Name: Po Kai Feng ---------------------------- This program compares short dna sequence, s2, with sub sequences of a long dna sequence, s1 The way of approaching this task is the same as what people are doing in the bio industry. """ def main(): """ User will types a long DNA sequence....
nilq/baby-python
python
# Generated by Django 3.2 on 2021-04-15 17:40 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Member', fields=[ ('id', models.BigAutoField(...
nilq/baby-python
python
import abjad import collections import importlib import itertools import os from abjad.tools import abctools from abjad.tools import indicatortools from abjad.tools import instrumenttools from abjad.tools import lilypondfiletools from abjad.tools import markuptools from abjad.tools import mathtools from abjad.tools imp...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # ----------------------------------------------------------------------------- # # P A G E B O T N A N O # # Copyright (c) 2020+ Buro Petr van Blokland + Claudia Mens # www.pagebot.io # Licensed under MIT conditions # # Supporting DrawBot, www.drawbot.com # ---...
nilq/baby-python
python
""" Streaming newline delimited JSON I/O. Calling `newlinejson.open()` returns a loaded instance of `NLJReader()`, or `NLJWriter()` that acts as a file-like object. See `help()` on each for more information. Example: import newlinejson as nlj with nlj.open('sample-data/dictionaries.json') as src, \\ ...
nilq/baby-python
python
''' 商品详情页面 ''' from common.base import Base good_url ='http://ecshop.itsoso.cn/goods.php?id=304' class Buy_Good(Base): '''页面点击立即购买''' # 商品名字 good_name_loc=('class name','goods_style_name') # 商品牌子 good_brand_loc=('css selector','a[href="brand.php?id=20"]') # 购买数量框 number_loc=('id','number'...
nilq/baby-python
python
import requests import re import threading from bs4 import BeautifulSoup as bs class Crawler(): def __init__(self, seed): self.seed = seed self.data_path = './data/' def make_filename(self,url): """ Extracts domain from a url. Prepend data_path and append '.html' :param url: string return <domain>....
nilq/baby-python
python
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # 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 applicab...
nilq/baby-python
python
import os import numpy as np import cv2 as cv # Set up path to OpenCV's Haar Cascades for face detection. cascade_path = "C:/Python372/Lib/site-packages/cv2/data/" face_detector = cv.CascadeClassifier(cascade_path + 'haarcascade_frontalface_default.xml') # Set up path to training i...
nilq/baby-python
python
from django.contrib.auth import get_user_model from django.test import TestCase #an extension of Python’s TestCase from django.urls import reverse, resolve from .models import ( PostJobModel, ApplicationModel ) from .views import ( createJobView, JobListView, JobsDetailView, SearchResultsList...
nilq/baby-python
python
import logging import time import celery from django.core.exceptions import ObjectDoesNotExist from django.db.models.query_utils import Q from genes.canonical_transcripts.canonical_transcript_manager import CanonicalTranscriptManager from genes.gene_matching import GeneSymbolMatcher from genes.models import GeneCover...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础计算平台 available. Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may o...
nilq/baby-python
python
from typing import Any import numpy from scipy.stats import poisson from .PropertyGenerator import PropertyGenerator class PoissonNumberGenerator(PropertyGenerator): def __init__(self, mu: float, return_int: bool = False): """ Init a NumberGenerator which will output number taken from a skewed n...
nilq/baby-python
python
#!/usr/bin/env python3 import sys import argparse import numpy as np from firedrake import * # recover stage3/: # ./solve.py -refine 0 -mz 8 -marginheight 0.0 # performance demo (1 min run time on my thelio) # tmpg -n 12 ./solve.py -s_snes_converged_reason -mx 4000 -refine 2 -s_snes_monitor -s_snes_atol 1.0e...
nilq/baby-python
python
# Copyright (c) 2015, Dataent Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import dataent def execute(): attach_fields = (dataent.db.sql("""select parent, fieldname from `tabDocField` where fieldtype in ('Attach', 'Attach Image')""") + dataent.db.sq...
nilq/baby-python
python
############################################################### # # ADIABATIC_FLAME - A freely-propagating, premixed flat flame # ############################################################### #import : from cantera import * from matplotlib.pylab import * import numpy #Functions : ####################...
nilq/baby-python
python
from mysqlhelper import DBConnection link_bd = DBConnection(user="dacrover_user", password="dacrover_pass", host="itsuki.e", port=3306, database= "dacrover") reminder_target = link_bd.select('reminders', where="`ReminderUser` = 'Тагир'", json=True) if (len(reminder_target) > 0): reminder_tar...
nilq/baby-python
python
# coding: utf-8 """ flyteidl/service/admin.proto No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: version not set Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import r...
nilq/baby-python
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from __future__ import absolute_import from django.contrib import admin from croisee import models class WordInline(admin.TabularInline): model = models.Word class DictionaryAdmin(admin.ModelAdmin): list_display = ('name','language','descriptio...
nilq/baby-python
python
############################################################################### # Caleydo - Visualization for Molecular Biology - http://caleydo.org # Copyright (c) The Caleydo Team. All rights reserved. # Licensed under the new BSD license, available at http://caleydo.org/license ######################################...
nilq/baby-python
python
import CIM2Matpower # from scipy.io import savemat cim_to_matpower_filename = 'CIM_to_Matpower_import' cimfiles = ['./UCTE10_20090319_modified_EQ.xml', './UCTE10_20090319_modified_TP.xml', './UCTE10_20090319_modified_SV.xml'] boundary_profiles = [] mpc = CIM2Matpower.cim_to_mpc(cimfiles, b...
nilq/baby-python
python
""" Parameterized models of the stellar mass - halo mass relation (SMHM). """ from __future__ import division, print_function from __future__ import absolute_import, unicode_literals import os import numpy as np from astropy.table import Table __all__ = ['behroozi10_ms_to_mh', 'behroozi10_evolution', '...
nilq/baby-python
python
__all__ = ["Dog", "test1", "name"] class Animal(object): pass class Dog(Animal): pass class Cat(Animal): pass def test1(): print("test1") def test2(): print("test2") def test3(): print("test3") name = "小明" age = "22"
nilq/baby-python
python
from flickr.flickr import search
nilq/baby-python
python
# Copyright 2016 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 a...
nilq/baby-python
python
from config import appconfig def uniqueName(base_name): return time.strftime('%Y%m%d%H%M%S', time.localtime()) + base_name def isImageByExtension(image_name): return '.' in image_name and image_name.rsplit('.', 1)[1].lower() in appconfig.IMAGE_EXTENSIONS
nilq/baby-python
python
import parse import logging import click from render import Render logging.basicConfig(level = logging.INFO) @click.command() @click.option('--default', '-d', help='Generate the default blog template') @click.option('--resume','-r', help='Generate a resume template') def build(default, resume): Renderer = Render...
nilq/baby-python
python
import asyncio import itertools from decimal import Decimal from typing import Tuple, Union from hq2redis.exceptions import SecurityNotFoundError from hq2redis.reader import get_security_price from motor.motor_asyncio import AsyncIOMotorDatabase from pydantic import ValidationError from pymongo import DeleteOne, Updat...
nilq/baby-python
python
import logging import inspect def logger(filename: str, name: str) -> logging.Logger: """configure task logger """ logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) fh = logging.FileHandler(filename) formatter = logging.Formatter( '%(asctime)s %(name)s %(levelname)s: %(me...
nilq/baby-python
python
from random import uniform import lepy from PySide2Wrapper.PySide2Wrapper.window import MainWindow from PySide2Wrapper.PySide2Wrapper.widget import OpenGLWidget from PySide2Wrapper.PySide2Wrapper.app import Application class SimpleScene: cells_num = [3, 2] def __init__(self): self.engine = None ...
nilq/baby-python
python
import unittest import socket import tcp from multiprocessing import Process from time import sleep import os import subprocess import signal ''' test_tcp.py can be run on command line by inputting the following sudo python3 tcp/test_tcp.py NOTE: THE TCP THREAD NEVER TERMINATES BECAUSE THE TCP THREAD IS IN A WHILE LO...
nilq/baby-python
python
""" The MIT License (MIT) Copyright (c) 2015 Zagaran, Inc. 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...
nilq/baby-python
python
from __future__ import print_function import os import random import sys import time import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from torch.nn.parameter import Parameter import numpy as np import matplotlib import matplotlib.pyplot as plt matplotlib.style.use('ggp...
nilq/baby-python
python
# coding: utf-8 """ Xero Payroll UK This is the Xero Payroll API for orgs in the UK region. # noqa: E501 OpenAPI spec version: 2.4.0 Contact: api@xero.com Generated by: https://openapi-generator.tech """ import re # noqa: F401 from xero_python.models import BaseModel class LeavePeriod(Base...
nilq/baby-python
python
import time import os import sys import getopt import pytz import re import time from datetime import datetime from dotenv import load_dotenv from monitoring import Monitoring from untils import toBytes load_dotenv() class DockerMonitoring(Monitoring): def __init__(self, database, settings): super().__in...
nilq/baby-python
python
# -*- coding: utf-8 -*- """Example 0 (no style, no lint, no documentation). First version of the example code (slide 10a), prior to applying any tool. """ def Calculate(A, B= {}, print = True): if A == None: if print: print('error: A is not valid') return elif A != None: ...
nilq/baby-python
python
import numpy as np cimport numpy as np cimport cython from .utils import fillna, to_ndarray from .c_utils cimport c_min, c_sum, c_sum_axis_0, c_sum_axis_1 cpdef ChiMerge(feature, target, n_bins = None, min_samples = None, min_threshold = None, nan = -1, balance = True): """Chi-Merge Args: feature (array-like): fe...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayCommerceTransportEtcInfoModifyModel(object): def __init__(self): self._biz_agreement_no = None self._card_no = None self._device_no = None self._order_id = N...
nilq/baby-python
python
# Copyright (c) Microsoft Corporation. # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
nilq/baby-python
python
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative wo...
nilq/baby-python
python
from pathlib import Path from typing import NamedTuple, List, Dict, Any from os import fsync, rename from .instrumentation_id import InstrumentationId from util.atomic_file import atomic_write def get_intrumentation_ids(config: Dict[str, Any]) -> List[InstrumentationId]: intrumentation_ids = [] if config["ins...
nilq/baby-python
python
''' Version: 2.0 Autor: CHEN JIE Date: 2020-10-12 15:29:23 LastEditors: CHEN JIE LastEditTime: 2020-10-17 15:54:29 language: Deep learning framework: ''' import torch import torch.nn as nn import torch.nn.functional as F from .node import NodeOp from .dag_layer import DAGLayer from .sep_conv import SeparableConv2d ...
nilq/baby-python
python
from django.http import HttpResponse, HttpResponseRedirect from django.conf import settings from django.contrib.auth import login from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes, force_text from django.utils.http import urlsafe_base64_encode, urlsafe_base64_deco...
nilq/baby-python
python
import numpy as np import scipy.sparse as ss import pandas as pd import anndata as ad def filter_genecounts_percent(adata, cell_fraction, median_count_above_zero): """ filter function for counts :param adata: anndata object to be filtered :param pheno: phenotype to filter on :param percent_ce...
nilq/baby-python
python
#! /data/sever/python/bin/python # -*- coding:utf-8 -*- """ @author: 'root' @date: '9/30/16' """ __author__ = 'root' import time import datetime from lib.utils import format_list from lib.mongo import MongoClient from lib.crawler import Crawler from lib.excel import Excel M = MongoClient() def f(): with open('/...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Fri Mar 25 18:54:45 2022 @author: balas """ import requests from bs4 import BeautifulSoup import pandas as pd def extract(location,tag, page): #Using User Agent,sometimes you will find that the webserver blocks certain user agents. #This is mostly because ...
nilq/baby-python
python
import pathlib from setuptools import setup from src.hyperfit import __version__ here = pathlib.Path(__file__).parent.resolve() # Get the long description from the README file long_description = (here / "README.md").read_text(encoding="utf-8") setup( name="hyperfit", version=__version__, description="Pro...
nilq/baby-python
python
from __future__ import absolute_import import pytest from DeploymentDirector.director import Context from DeploymentDirector.rules import Match # def pytest_generate_tests(metafunc): # if 'context' in metafunc.fixturenames: # metafunc.parametrize("context", envs.keys(), indirect=True) envs={ 'complete': { ...
nilq/baby-python
python
from django.db import models class ShortenedUrl(models.Model): id = models.BigIntegerField(primary_key=True) long_url = models.TextField(blank=False, null=False)
nilq/baby-python
python
#!/usr/bin/env python3 ''' Converted to Python 6/00 by Jason Petrone /* * Copyright (c) 1993-1997, Silicon Graphics, Inc. * ALL RIGHTS RESERVED * Permission to use, copy, modify, and distribute this software for * any purpose and without fee is hereby granted, provided that the above * copyright notice appear ...
nilq/baby-python
python
"""Support for GitHub.""" from datetime import timedelta import logging import github import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( ATTR_NAME, CONF_ACCESS_TOKEN, CONF_NAME, CONF_PATH, CONF_URL, ) import homeassistant.helpers....
nilq/baby-python
python
import os import numpy as np import gym import ray from ray.rllib.models import ModelCatalog from ray.tune.registry import register_env from rl4rs.env.slate import SlateRecEnv, SlateState from rl4rs.env.seqslate import SeqSlateRecEnv, SeqSlateState from rl4rs.utils.rllib_print import pretty_print from rl4rs.nets.rllib....
nilq/baby-python
python
"""Tasks module All tasks run via external message queue (via celery) are defined within. NB: a celery worker must be started for these to ever return. See `celery_worker.py` """ from datetime import datetime from functools import wraps import json from traceback import format_exc from celery.utils.log import get_...
nilq/baby-python
python
if x == 3: print("bye")
nilq/baby-python
python
from django.apps import AppConfig class SteveConfig(AppConfig): name = 'steve'
nilq/baby-python
python
name = input("What is the name of the gift giver?") present = input("What is the present they gave you?") print() age = input("How old were you on your birthday?") yourName = input("What is your name?") print("Dear " + name + ", ") print("") print("Thank you for the " + present + ". ") print("I really like it. I can't...
nilq/baby-python
python
from enum import Enum class IndType(Enum): CONFIRMED = 'Confirmed' DECEASED = 'Deceased' RECOVERED = 'Recovered'
nilq/baby-python
python
""" An exceptionally lousy site spider Ken Kinder <ken@kenkinder.com> This module gives an example of how the TaskClient interface to the IPython controller works. Before running this script start the IPython controller and some engines using something like:: ipcluster -n 4 """ from twisted.python.failure impor...
nilq/baby-python
python
# -*- coding: utf-8 -*- import sys from sqlalchemy import create_engine from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base import os SQLALCHEMY_DATABASE_URI = None if 'DATABASE_URI' in os.environ: SQLALCHEMY_DATABASE_URI = os.getenv("DATABASE_URI") else: SQ...
nilq/baby-python
python
""" Storage containers for durable queues and (planned) durable topics. """ import abc import logging import threading from coilmq.util.concurrency import synchronized __authors__ = ['"Hans Lellelid" <hans@xmpl.org>'] __copyright__ = "Copyright 2009 Hans Lellelid" __license__ = """Licensed under the Apache License, V...
nilq/baby-python
python
#!/usr/bin/env python3 # Copyright (C) 2015-2016 Ben Klein. All rights reserved. # # This application is licensed under the GNU GPLv3 License, included with # this application source. import sys global DEBUG DEBUG = True if DEBUG: print("Debugging enabled.") print("Called with system args: " + str(sys.ar...
nilq/baby-python
python
import pyqtgraph as pg from pyqtgraph import QtCore, QtGui from .. import definitions as defs from .. import functions class FinWindow(pg.GraphicsLayoutWidget): def __init__(self, title, **kwargs): self.title = title pg.mkQApp() super().__init__(**kwargs) self.setWindowTitle(title)...
nilq/baby-python
python
import os import re from setuptools import setup PWD = os.path.dirname(__file__) with open(os.path.join(PWD, 'sshtunnel_requests', '__init__.py')) as f: VERSION = (re.compile(r""".*__version__ = ["'](.*?)['"]""", re.S).match(f.read()).group(1)) def parse_requirements_file(filename): ...
nilq/baby-python
python
# Generated by Django 3.1.5 on 2021-03-28 18:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('challenge', '0004_match_log_file_token'), ] operations = [ migrations.AlterField( model_name='match', name='status',...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Copyright (c) 2006-2018, Alexis Royer, http://alexis.royer.free.fr/CLI # # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # # * Redistributions of source code m...
nilq/baby-python
python
# -*- coding: utf-8 -*- import os from jsonschema import ValidationError from app_factory.base import AppZero from gluon import current class Table(AppZero): _definition_path = os.path.join( current.request.folder, "static", "json", "model", "dal", "table.json" ) _schema_name = "table.schema.j...
nilq/baby-python
python
import os from codecs import open from setuptools import setup, find_packages try: # for pip >= 10 from pip._internal.req import parse_requirements except ImportError: from pip.req import parse_requirements here = os.path.abspath(os.path.dirname(__file__)) install_requirements = parse_requirements('requirement...
nilq/baby-python
python
import os import glob import re from setup_app import paths from setup_app.utils import base from setup_app.static import AppType, InstallOption from setup_app.config import Config from setup_app.utils.setup_utils import SetupUtils from setup_app.installers.base import BaseInstaller class JythonInstaller(BaseInstalle...
nilq/baby-python
python
# Copyright 2016-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" f...
nilq/baby-python
python
import socket, time, threading, sys, signal, errno from threading import Thread if (len(sys.argv) < 2): print "Server usage: python server.py PORT" sys.exit(0) MIN_THREADS = 2 # Minimum number of workers at start and at any point MAX_THREADS = 32 # Maximum number of workers TOLERANCE = 2 # Minimum difference ...
nilq/baby-python
python
import os import sys import json from PyQt5 import QtCore, QtWidgets from PyQt5.QtWidgets import * from PyQt5.QtGui import * class WindowObj6CornernetLiteModelParam(QtWidgets.QWidget): backward_6_cornernet_lite_valdata_param = QtCore.pyqtSignal(); forward_hyper_param = QtCore.pyqtSignal(); def __init__(...
nilq/baby-python
python
"""FreeBSD Ports Collection module. This module provides an interface to interact with the FreeBSD Ports Collection, and means of discovering ports therein. """ from os import environ from typing import Callable, ClassVar, List, Optional from pathlib import Path from .make import make, make_var from .port import Port,...
nilq/baby-python
python
from mock import patch from twisted.trial.unittest import TestCase from apns.errorresponse import ( ErrorResponse, ErrorResponseInvalidCodeError, ErrorResponseInvalidCommandError ) MODULE = 'apns.errorresponse.' class ErrorResponseTestCase(TestCase): CLASS = MODULE + 'ErrorResponse.' def test_...
nilq/baby-python
python
from typing import List def warmUp(nums: List[int], target: int) -> List[int]: numsDict = {} for index, item in enumerate(nums): diff = target - item if diff in numsDict: return numsDict[diff], index numsDict[item] = index
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from setuptools import setup except ImportError: from distutils.core import setup with open('README.rst') as readme_file: readme = readme_file.read() requirements = [ 'pika', 'twisted', 'checkoutmanager', # The 'collectors' branch of chint...
nilq/baby-python
python
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the Li...
nilq/baby-python
python
from fastapi import APIRouter from kairon.api.auth import Authentication from kairon.api.processor import AccountProcessor from kairon.api.models import Response, User from fastapi import Depends router = APIRouter() auth = Authentication() @router.get("/details", response_model=Response) async def get_users_detail...
nilq/baby-python
python
import time from slacker import Slacker from script.util.BaseFSM import BaseFSM from script.util.misc_util import error_trace class SlackBotFsm(BaseFSM): def __init__(self): super().__init__() self.add_state('pending', initial_state=True) self.add_state('on going') sel...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # rom.py # # Part of MARK II project. For informations about license, please # see file /LICENSE . # # author: Vladislav Mlejnecký # email: v.mlejnecky@seznam.cz from memitem import memitem import sys import mif class rom(memitem): def __init__(self, baseAddress, s...
nilq/baby-python
python
#! /usr/bin/env python # -*- coding:utf-8; mode:python -*- from ilcli import Command class FirstDemoCommand(Command): ignore_arguments = ['-b'] def _init_arguments(self): super()._init_arguments() self.add_argument('--foo') class SecondDemoCommand(FirstDemoCommand): ignore_arguments = ...
nilq/baby-python
python
r"""UTF-8 sanitizer. Python's UTF-8 parser is quite relaxed, this creates problems when talking with other software that uses stricter parsers. >>> _norm(safe_utf8_decode(b"foobar")) (True, ['f', 'o', 'o', 'b', 'a', 'r']) >>> _norm(safe_utf8_decode(b'X\0Z')) (False, ['X', 65533, 'Z']) >>> _norm(safe_utf8_decode(b'OK'...
nilq/baby-python
python
#! /usr/local/bin/python3 import operator import sys from collections import deque from math import prod pubKeys = [int(x) for x in sys.stdin.read().split("\n")[:2]] subject = [1 for i in pubKeys] print(pubKeys) handDivisor = 20201227 acc = [0 for i in pubKeys] for i, k in enumerate(pubKeys): while k != subje...
nilq/baby-python
python
import sys import os sys.path.append(os.path.join('..','utils')) import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from utilsRobust import * ###################### ### VARIOUS TESTS FOR UTILS ROBUST ###################### def test_mestimate(): mean = 0 std = 5 ...
nilq/baby-python
python
import numpy as np from scratch.abstract import AbstractModel class PCA(AbstractModel): def __init__(self): pass @staticmethod def normalizing(v): return (v - np.mean(v)) / np.std(v) def fit(self, X): # step 1: normalizing Xarray = X.to_numpy() self.Xscale = ...
nilq/baby-python
python
from django.db import models class Like(model.Models): uid = models.IntegerField() name = models.CharField() # Create your models here.
nilq/baby-python
python
import numpy as np import pytest import tensorflow as tf from tensorflow.keras.layers import Dense, Input, InputLayer from alibi_detect.cd.preprocess import UAE, HiddenOutput, pca n, n_features, n_classes, latent_dim, n_hidden = 100, 10, 5, 2, 7 shape = (n_features,) X = np.random.rand(n * n_features).reshape(n, n_fea...
nilq/baby-python
python
# Generated by Django 2.1.3 on 2019-02-27 15:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('queueapp', '0007_auto_20190220_1642'), ] operations = [ migrations.AddField( model_name='queue', name='pause_and_cle...
nilq/baby-python
python
import re import sys import unittest from line import * from canonicalLine import * from degenerateLine import * from lineClassifier import * import importlib pd.set_option('display.width', 1000) filename = "../testData/daylight_1_4.eaf" xmlDoc = etree.parse(filename) lineCount = len(xmlDoc.findall("TIER/ANNOTATION/A...
nilq/baby-python
python
# pylint:disable=missing-module-docstring,missing-class-docstring,missing-function-docstring from .base import compare_template, SimpleTestCase class CopyButtonTest(SimpleTestCase): maxDiff = None def test_rendered(self): template = """ {% load carbondesign %} {% CopyButton %} """ expected = "...
nilq/baby-python
python
# These should probably all live in separate files from ..tensorboard_writer import TensorboardWriter from allennlp.training.callbacks.events import Events from allennlp.training.callbacks.callback import Callback, handle_event from allennlp.common.params import Params import logging from typing import Set, Dict, TYPE_...
nilq/baby-python
python
from datetime import datetime from decimal import Decimal import calendar from enum import IntEnum import timex from sqlalchemy import event from sqlalchemy import and_, or_ from sqlalchemy import literal_column from sqlalchemy import Column, Table, ForeignKey, Index, UniqueConstraint from sqlalchemy import Float, Bo...
nilq/baby-python
python
from Step_5.A3C import A3Cagent from Step_5.Parameter import PARA from Step_5.A3C_NETWORK import A3C_shared_network class MainModel: def __init__(self): self.worker = [] shared_model = A3C_shared_network().model for i in range(0, 2): self.worker.append(A3Cagent(Remote_ip=PARA.Re...
nilq/baby-python
python
import profig from gogetmarvel.comic import Comic from gogetmarvel.engine import Engine cfg = profig.Config('gogetmarvel/config.cfg') cfg.sync() class Marvel(object): """ Main marvel object connects the engine to its children. """ def __init__(self, private_key=None, public_key=None): """ ...
nilq/baby-python
python
#!/usr/bin/env python #coding:utf-8 import requests import re #下面三行是编码转换的功能,大家现在不用关心。 import sys reload(sys) sys.setdefaultencoding("utf-8") #header是我们自己构造的一个字典,里面保存了user-agent header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36'} #部分网...
nilq/baby-python
python
import repetition menu_selex = 'y' while menu_selex == 'y': #This is so that HW Menu is generated print('\nHomework 3 Menu\n1-Factorial\n2-Sum odd numbers\n3-Exit') selex = int(input('Please select menu item 1, 2 or 3: ')) if selex == 1: #This is the factorial part of the assignment keep_...
nilq/baby-python
python
import os import re import sys import time import traceback import logging import hashlib from urllib.parse import urlsplit, urlunsplit from datetime import datetime from dateutil import tz from flask import ( Flask, render_template, request, redirect, url_for, send_from_directory, jsonify, ...
nilq/baby-python
python
# Assessing placement bias of the global river gauge network # Nature Sustainability # Authors: Corey A. Krabbenhoft, George H. Allen, Peirong Lin, Sarah E. Godsey, Daniel C. Allen, Ryan M. Burrows, Amanda G. DelVecchia, Ken M. Fritz, Margaret Shanafield # Amy J. Burgin, Margaret Zimmer, Thibault Datry, Walter K. Dodds...
nilq/baby-python
python
from __future__ import annotations import logging import random from collections import defaultdict from dataclasses import dataclass from typing import Callable, Dict, List, Optional, Tuple, Union from nuplan.common.actor_state.vehicle_parameters import VehicleParameters from nuplan.database.nuplan_db.lidar_pc impor...
nilq/baby-python
python