content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
game_logic = True winner = None curr_player = "X" board = [["-","-","-"], ["-","-","-"], ["-","-","-"]] def compTurn(): bestScore = -999 move = None for x in range(3): for y in range(3): if board[x][y] == "-": board[x][y] = "O" score = min...
nilq/baby-python
python
class task_status: """ Descriptive backend task processing codes, for readability. """ SCHEDULED = 0 PROCESSING = 1 FINISHED = 4 FAILED = -1 CANCELLED = 9 EXPIRED = 8 # only for ResultsPackage WAITING_FOR_INPUT = 2 # only for RunJob RETRYING = 11 # only for WorkflowRun ...
nilq/baby-python
python
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name = "taxon_parser", version = "0.2.3", author = "Augustin Roche", author_email = "aroche@photoherbarium.fr", description = "A library to parse taxon names into elementary compon...
nilq/baby-python
python
import logging from urllib.parse import urlparse import prometheus_client import requests import six from bs4 import BeautifulSoup as bs if six.PY3: from json import JSONDecodeError else: from simplejson import JSONDecodeError logger = logging.getLogger(__name__) class DataFetcher(object): def __ini...
nilq/baby-python
python
import json import requests from fabric.colors import red def publish_deploy_event(name, component, environment): url = environment.fab_settings_config.deploy_event_url if not url: return token = environment.get_secret("deploy_event_token") if not token: print(red(f"skipping {name} ev...
nilq/baby-python
python
class Data: def __init__(self, data_dir="data/FB15k-237/", reverse=False): self.train_data = self.load_data(data_dir, "train", reverse=reverse) self.valid_data = self.load_data(data_dir, "valid", reverse=reverse) self.test_data = self.load_data(data_dir, "test", reverse=reverse) ...
nilq/baby-python
python
import os import yaml from google.cloud import storage from google.oauth2 import service_account from .storage import Storage class GcsStorage(Storage): def __init__(self, bucket, path, project=None, json_path=None): if bucket is None: raise ValueError('Bucket must be supplied to GCS storage...
nilq/baby-python
python
from django.shortcuts import render from rest_framework.decorators import api_view from django.http import JsonResponse import json from .models import Wine from .serializers import WineSerializer from .constants import PAGE_SIZE # Create your views here. @api_view(["GET"]) def wines(request): pageParam = int(requ...
nilq/baby-python
python
# Copyright 2020 kubeflow.org. # # 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,...
nilq/baby-python
python
# Api view of grades from home.models import Grade # from Serializers.GradeSerializer import FlatGradeSerializer from api.services import handelFileSubmit, sendEmail, createTmpFile, getUserGrades from rest_framework import viewsets from rest_framework.response import Response from rest_framework.decorators impo...
nilq/baby-python
python
#!/usr/bin/env python3 import os import sys import time sys.path.append(os.getcwd()+'/CPDP') sys.path.append(os.getcwd()+'/JinEnv') sys.path.append(os.getcwd()+'/lib') import copy import time import json import numpy as np import transforms3d from dataclasses import dataclass, field from QuadPara import QuadPara from Q...
nilq/baby-python
python
""" https://adventofcode.com/2020/day/2 """ from collections import namedtuple import logging logger = logging.getLogger(__name__) Rule = namedtuple("Rule", ["letter", "f_pos", "s_pos"]) def check_password(rule, password): f_letter = password[rule.f_pos - 1] s_letter = password[rule.s_pos - 1] return ...
nilq/baby-python
python
# #!/usr/bin/env python ################################################################ ## contains code relevant to updating simulation ## e.g. physics, integration ################################################################ from local.particle import * # step particle simulation def simStep(particles, k, d...
nilq/baby-python
python
#!/usr/bin/env python # This script counts the number of PAM import regex as re import sys data_infile = sys.argv[1] # add 3 to account for PAM nt_overlap_threshold = int(sys.argv[2]) + 3 PAM_plus = re.compile(r'[ACTG]GG') PAM_minus = re.compile(r'CC[ACTG]') with open(data_infile, 'r') as infile: for line in in...
nilq/baby-python
python
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import argparse import json import itertools import sys parser = argparse.ArgumentParser(description='Check interop reports.') parser.add_argument('--required', type=str) parser.add_argument('--regressions') p...
nilq/baby-python
python
#! /usr/bin/env python """Give a string-oriented API to the generic "diff" module. The "diff" module is very powerful but practically useless on its own. The "search" and "empty_master" functions below resolve this problem.""" ################################################################################ __author_...
nilq/baby-python
python
from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.contrib import messages from django.contrib.auth.decorators import login_required from content.models import BlogPost, Category from .models import Profile, Contact def register(request): if request.method =...
nilq/baby-python
python
#!/usr/bin/env python3 import argparse import base64 import sys import time import requests def main(): print("Starting Pelion requests") # command line parser = argparse.ArgumentParser(description="Pelion device interactions") parser.add_argument("-a", "--apikey", type=str, help="User api key") ...
nilq/baby-python
python
from sklearn.cluster import KMeans, SpectralClustering, AffinityPropagation import numpy as np def clustering(X=None, model_name='KMeans', n_clusters=3, **param): if model_name == 'KMeans': # K均值 model = KMeans(n_clusters=n_clusters, **param) elif model_na...
nilq/baby-python
python
from typing import List, Optional, Union from lnbits.helpers import urlsafe_short_hash from . import db from .models import createLnurldevice, lnurldevicepayment, lnurldevices ###############lnurldeviceS########################## async def create_lnurldevice( data: createLnurldevice, ) -> lnurldevices: lnu...
nilq/baby-python
python
#!/usr/bin/python3 import bs4 import json import requests import http import re import pandas as pd from datetime import datetime import argparse import pathlib from enum import Enum MSG_LBL_BASE = '[PARSER]' MSG_LBL_INFO = f'{MSG_LBL_BASE}[INFO]' MSG_LBL_FAIL = f'{MSG_LBL_BASE}[FAIL]' def parse_args(): parser...
nilq/baby-python
python
import cv2 import numpy as np # 直方图均衡 def hisEqulColor(img): ycrcb = cv2.cvtColor(img, cv2.COLOR_BGR2YCR_CB) channels = cv2.split(ycrcb) # print len(channels) cv2.equalizeHist(channels[0], channels[0]) cv2.merge(channels, ycrcb) cv2.cvtColor(ycrcb, cv2.COLOR_YCR_CB2BGR, img) return img # ...
nilq/baby-python
python
#!/usr/bin/env python3 import argparse import subprocess import TEST_LOG import TEST_SETUP_IBOFOS import TEST def parse_arguments(args): parser = argparse.ArgumentParser(description='Test journal feature with SPO') parser.add_argument('-f', '--fabric_ip', default=TEST.traddr,\ help='Set target IP...
nilq/baby-python
python
""" Primitive operations for 3x3 orthonormal and 4x4 homogeneous matrices. Python implementation by: Luis Fernando Lara Tobar and Peter Corke. Based on original Robotics Toolbox for Matlab code by Peter Corke. Permission to use and copy is granted provided that acknowledgement of the authors is made. @author: Luis Fe...
nilq/baby-python
python
import matplotlib.pyplot as plt def plot(activity,lon,lat,lonsmooth,latsmooth) : fig = plt.figure(facecolor = '0.05') ax = plt.Axes(fig, [0., 0., 1., 1.], ) ax.set_aspect('equal') ax.set_axis_off() fig.add_axes(ax) #plt.plot(lonsmooth, latsmooth, '-', lon, lat, '.') #, xp, p(xp), '-') plt....
nilq/baby-python
python
import argparse from bothub_nlp_rasa_utils.train import train_update as train from bothub_nlp_rasa_utils.evaluate_crossval import evaluate_crossval_update as evaluate_crossval import os if __name__ == '__main__': PARSER = argparse.ArgumentParser() # Input Arguments PARSER.add_argument( '...
nilq/baby-python
python
from pathlib import Path import csv __all__ = ["text_writer", "str_file_read", "file_locate"] def str_file_read(file_path, encoding="utf-8"): """ Returns a file's contents as a string. Parameters ---------- file_path : str Path to GCA file to read encoding : str Encoding met...
nilq/baby-python
python
import pytest from seqeval.scheme import (BILOU, IOB1, IOB2, IOBES, IOE1, IOE2, Entities, Entity, Prefix, Token, Tokens, auto_detect) def test_entity_repr(): data = (0, 0, 0, 0) entity = Entity(*data) assert str(data) == str(entity) @pytest.mark.parametrize( 'data1, data...
nilq/baby-python
python
def model_snippet(): from pathlib import Path from multilevel_py.constraints import is_str_constraint, is_float_constraint, \ prop_constraint_ml_instance_of_th_order_functional from multilevel_py.core import create_clabject_prop, Clabject from multilevel_py.constraints import ReInitPropConstr ...
nilq/baby-python
python
''' Parser for the ConstantsDumper variables. ''' import re from typing import Optional, Text from ..parser import Context, ParserBase from ..cpp.types import parse_value class ConstantsParser(ParserBase): ''' Parses the constants outputted by the ConstantsDumper clang plugin. ''' VALUE_MATCHER = r...
nilq/baby-python
python
""" Author: Param Deshpande Date created: Fri Jul 10 23:48:41 IST 2020 Description: plots individual piecewise spline curves according to the timestamps in the splineCoeffs.txt License : ------------------------------------------------------------ "THE BEERWARE LICENSE" (Revision 42): Param Deshpande wrote t...
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
def configure(conf): conf.env.ARCHITECTURE = 'mips64el' conf.env.VALID_ARCHITECTURES = ['mips64el', 'mipsel64'] conf.env.ARCH_FAMILY = 'mips' conf.env.ARCH_LP64 = True conf.env.append_unique('DEFINES', ['_MIPS', '_MIPS64', '_MIPSEL', '_MIPSEL64', '_MIPS64EL', '_LP64'])
nilq/baby-python
python
# -*- python -*- # pymode:lint_ignore=E501 """Common settings and globals.""" from sys import path import os from django.contrib.messages import constants as message_constants from django.core.exceptions import ImproperlyConfigured from django.utils.translation import ugettext_lazy as _ from os.path import abspath, b...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Dynamic inventory script for ansible that works with ymir data. # See also: http://docs.ansible.com/ansible/intro_dynamic_inventory.html # import os from ymir import load_service_from_json YMIR_SERVICE_JSON = os.path.abspath( os.environ.get( 'YMIR_SERVICE_J...
nilq/baby-python
python
from collections import namedtuple import subprocess import os import sys from test_cases import Test from utils import pipe_read class RedundancyTest(Test): Config = namedtuple('Config', ['spatial_read_files', 'spatial_read_reds', 'spatial_write_files', 'spatial_write_reds', '...
nilq/baby-python
python
"""Module to preprocess detection data and robot poses to create usable input for ML model""" from copa_map.util import hist_grid, rate_grid, util import numpy as np from dataclasses import dataclass from termcolor import colored import os from matplotlib import pyplot as plt import pickle from matplotlib.widgets impo...
nilq/baby-python
python
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the NiBabel package for the # copyright and license terms. # ### ### ### #...
nilq/baby-python
python
import sys from PyQt5 import QtGui, QtCore, QtWidgets from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from time import sleep from view import Scene class Inventory(QWidget): def __init__(self, parent=None): super(Inventory, self).__init__(parent) self.setup_wind...
nilq/baby-python
python
# Copyright 2015 Yelp Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
nilq/baby-python
python
from django.urls import path from app.file_writer.views import FileWriterView urlpatterns = [ path('write/', FileWriterView) ]
nilq/baby-python
python
#!/usr/bin/python3 """ Functional Test: STABILITY Written by David McDougall, 2018 This verifies basic properties of the Stable Spatial Pooler. This generates a new artificial dataset every time. The dataset consists of randomly generated SDRs which are fed into the system as a timeseries. The dataset represents ob...
nilq/baby-python
python
import unittest from docx2md import DocxMedia class FakeDocxFile: def __init__(self, text): self.text = text def rels(self): return ( b'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships>' + self.text + b"</Relationships>" ...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Mon Jan 25 15:21:34 2021 @author: crtjur """ import tkinter as tk from PIL import Image, ImageTk root = tk.Tk() root.title("Title") root.geometry("280x350") root.configure(background="black") class Example(tk.Frame): def __init__(self, master, *pargs): tk.Frame.__i...
nilq/baby-python
python
""" WGAN-applicable Fully Convolutional Neural Network """ import tensorflow as tf from tensorflow.keras.layers import Input, Conv2D, Conv2DTranspose, AveragePooling2D, UpSampling2D, Concatenate, Dropout, LeakyReLU, BatchNormalization from architectures.activations import UV_activation from architectures.layers imp...
nilq/baby-python
python
from prometheus_client import start_http_server from prometheus_client.core import REGISTRY from collector import ElasticBeanstalkCollector import time import datetime def main(): port = 9552 print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3], "Starting exporter on :", port) try...
nilq/baby-python
python
import os import csv import datetime from flask import Flask, render_template, redirect, url_for app = Flask(__name__) file_data_list = [] def convert_to_timestamp(epoch_time='0'): return datetime.datetime.fromtimestamp(int(float(epoch_time))).strftime('%Y-%m-%dT%H:%M:%S') def cache_file_data(): global fil...
nilq/baby-python
python
"""Jenkins test report metric collector.""" from datetime import datetime from typing import Dict, Final, List, cast from dateutil.parser import parse from base_collectors import SourceCollector from collector_utilities.functions import days_ago from collector_utilities.type import URL from source_model import Entit...
nilq/baby-python
python
from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from __future__ import print_function from builtins import str as unicode from quark_runtime import * _lazyImport.plug("inheritance.pets") import quark.reflect class Pet(_QObject): def _init(self): ...
nilq/baby-python
python
#! /usr/bin/env python import numpy as np import random from time import sleep from curses import wrapper def two_dim(pos, width): ''' Return 2d co-ordinates represented as 1d array. pos: position in one dimension width: total width of 2d array(columns) ''' width += 1 return pos//width, p...
nilq/baby-python
python
""" UrlCanonicalizerMiddleware A spider middleware to canonicalize the urls of all requests generated from a spider. imported from http://snipplr.com/view/67007/url-canonicalizer-spider-middleware/ # Snippet imported from snippets.scrapy.org (which no longer works) # author: pablo # date : Sep 07, 2010 """ from sc...
nilq/baby-python
python
from .diophantine import diophantine, classify_diop, diop_solve __all__ = [ 'diophantine', 'classify_diop', 'diop_solve' ]
nilq/baby-python
python
# Generated by Django 3.1.7 on 2021-04-14 16:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0012_auto_20210414_1252'), ] operations = [ migrations.AlterField( model_name='post', name='additional_addre...
nilq/baby-python
python
""" DELL SDP P-Search API """ try: import xml.etree.cElementTree as ET except ImportError: import xml.etree.ElementTree as ET class SDPException(Exception): pass class SDPApi(object): """ SDP API Calls """ def __init__(self, sdpclient, logger, response_json=None): ...
nilq/baby-python
python
#!Venv/bin python3 # -*- coding: utf-8 -*- import sqlite3 from urllib.request import urlopen import numpy as np import pandas as pd from bs4 import BeautifulSoup html = urlopen('https://www.opap.org.cy/el/page/joker-results').read() html = html.decode('utf-8') soup = BeautifulSoup(html, features='html.parser') colu...
nilq/baby-python
python
import torch from torch import nn class RNN_LSTM(nn.Module): def __init__(self, input_dim, hidden_dim, n_lyrs = 1, do = .05, device = "cpu"): """Initialize the network architecture Args: input_dim ([int]): [Number of time steps in the past to look at for current prediction] ...
nilq/baby-python
python
# Copyright (C) 2020 Arm Limited or its affiliates. All rights reserved. # # SPDX-License-Identifier: Apache-2.0 # # 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 # # www.apache.org/licenses/LICE...
nilq/baby-python
python
import argparse import json import os import pickle import numpy as np from nasbench_analysis.search_spaces.search_space_1 import SearchSpace1 from nasbench_analysis.search_spaces.search_space_2 import SearchSpace2 from nasbench_analysis.search_spaces.search_space_3 import SearchSpace3 from nasbench_analysis.utils im...
nilq/baby-python
python
from pylab import * def imhist(img): rows, cols = img.shape h = np.zeros((256, 1), dtype=np.double) for k in range(255): h[k] = 0 for i in range(rows): for j in range(cols): if img[i,j] == k-1: h[k] = h[k]+1 return h def My...
nilq/baby-python
python
import tensorflow as tf import optotf.nabla import unittest class Nabla2d(tf.keras.layers.Layer): def __init__(self, hx=1, hy=1): super().__init__() self.op = lambda x: optotf.nabla.nabla_2d(x, hx=hx, hy=hy) def call(self, x): if x.dtype == tf.complex64 or x.dtype == tf.complex128: ...
nilq/baby-python
python
# -*- coding: utf-8 -*- """Top-level package for skipchunk.""" __author__ = """Max Irwin""" __email__ = 'max_irwin@yahoo.com' __version__ = '0.1.0'
nilq/baby-python
python
from django.contrib import admin from .models import User, EmailSender from django.core.mail import send_mass_mail import smtplib admin.site.register(User) class EmailSenderAdmin(admin.ModelAdmin): actions = ['send_email'] @admin.action(description='Send mass email') def send_email(self, request, query...
nilq/baby-python
python
from django.contrib import admin from bookings.models import Booking # Register your models here. admin.site.register(Booking)
nilq/baby-python
python
from .utils import cached_property from .utils.types import is_list, get_link, validate, is_nullable from .resource import Resource from .conf import settings from .expression import execute from .schemas import FieldSchema from .exceptions import TypeValidationError def is_resolved(x): if isinstance(x, Resource)...
nilq/baby-python
python
#!/usr/bin/env python3 # Copyright 2017 Johns Hopkins University (Shinji Watanabe) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) # This code is ported from the following implementation written in Torch. # https://github.com/chainer/chainer/blob/master/examples/ptb/train_ptb_custom_loop.py """Language m...
nilq/baby-python
python
# !/usr/bin/env python # -*- coding: utf-8 -*- # Copyright(c) 2019 Nippon Telegraph and Telephone Corporation # Filename: EmLoggingTool.py ''' Log tool for EM. ''' import logging.handlers import time import gzip import os import re import shutil import GlobalModule class Formatter(logging.Forma...
nilq/baby-python
python
import pytest from pipet.core.shop_conn.wc import * from pipet.core.transform.model_to_wc import * from pipet.core.transform.wc_to_model import * from pprint import pprint
nilq/baby-python
python
def maxMultiple(divisor, bound): return (bound // divisor) * divisor
nilq/baby-python
python
#Kyle Sizemore #2/7/2020 # pull historical data from the market for backtesting purposes and output to a # csv file on our mySQL database import warnings warnings.simplefilter(action='ignore', category=FutureWarning) import datetime import pandas as pd import pandas_datareader as web import csv import pymysql from sql...
nilq/baby-python
python
import pypro.core import os class CreateConfig(pypro.core.Recipe): def __init__(self, source, destination): self.source = source self.destination = destination def run(self, runner, arguments=None): # Read the template file content = '' with open(self.source, 'r') as ...
nilq/baby-python
python
import random import numpy as np import torch import torch.utils.data as data import data.util as util import os.path as osp class LQGT_dataset(data.Dataset): ''' Read LQ (Low Quality, here is LR) and GT image pairs. If only GT image is provided, generate LQ image on-the-fly. The pair is ensured by 'so...
nilq/baby-python
python
""" byceps.services.ticketing.dbmodels.archived_attendance ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2014-2022 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import datetime from ....database import db from ....typing import PartyID, UserID from...
nilq/baby-python
python
#!/usr/bin/env python3 """nargs=+""" import argparse parser = argparse.ArgumentParser( description='nargs=+', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('files', metavar='FILE', nargs='+', help='Some files') args = parser.parse_args() files = args.files print('number = {}'....
nilq/baby-python
python
""" @authors: Filip Maciejewski, Oskar Słowik, Tomek Rybotycki @contact: filip.b.maciejewski@gmail.com REFERENCES: [0] Filip B. Maciejewski, Zoltán Zimborás, Michał Oszmaniec, "Mitigation of readout noise in near-term quantum devices by classical post-processing based on detector tomography", Quantum 4, 257 (2020) [0...
nilq/baby-python
python
import numpy as np import modeling.geometric_model as gm import modeling.collision_model as cm import visualization.panda.world as wd import basis.robot_math as rm import math import pickle from scipy.spatial import cKDTree import vision.depth_camera.surface.gaussian_surface as gs import vision.depth_camera.surface.rbf...
nilq/baby-python
python
from django.http import Http404 from django.test import TestCase from model_bakery import baker from django.shortcuts import get_object_or_404 from paranoid_model.tests import models class TestGetObjectOr404(TestCase): def test_raise_when_object_does_not_exists(self): with self.assertRaises(Http404): ...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Sep 13 12:14:02 2018 @author: jguillaumes """ import os import sqlite3 import configparser import threading import calendar import pkg_resources from time import sleep from weatherLib.weatherUtil import WLogger,parseLine _SELECT_TSA = 'select maxt...
nilq/baby-python
python
# Princeton University licenses this file to You 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 writin...
nilq/baby-python
python
''' File name: GIN.py Discription: Learning Hidden Causal Representation with GIN condition Author: ZhiyiHuang@DMIRLab, RuichuCai@DMIRLab From DMIRLab: https://dmir.gdut.edu.cn/ ''' from collections import deque from itertools import combinations import numpy as np from causallearn.graph.GeneralGraph...
nilq/baby-python
python
#!/usr/bin/python2.5 # # Copyright 2010 Google 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 ...
nilq/baby-python
python
#!/bin/env python3.9 """ cyclic backup creating a tar file """ import datetime import getopt import logging import os import re import sqlite3 import stat import sys import tarfile import time import traceback from builtins import bool import jinja2 import yaml blocked = set() config = { 'db': 'cycbackup.db', ...
nilq/baby-python
python
# -*- coding: utf-8 -*- from os.path import dirname, abspath from math import sqrt import numpy as np from scipy.stats import spearmanr, pearsonr from scipy.spatial.distance import cosine import matplotlib matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab! Needed for calculations on server....
nilq/baby-python
python
from base import * import numpy as np from typing import List def numpy_heavy_create_dot(number, base): start = time.time() - base DIMS = 3000 a = np.random.rand(DIMS, DIMS) b = np.random.rand(DIMS, DIMS) np.dot(a, b) stop = time.time() - base return start, stop nums = range(1, 8) run_t...
nilq/baby-python
python
from ..encoding import wif_to_secret_exponent from ..convention import tx_fee from .Spendable import Spendable from .Tx import Tx from .TxOut import TxOut, standard_tx_out_script from .pay_to import build_hash160_lookup class SecretExponentMissing(Exception): pass class LazySecretExponentDB(object): """ ...
nilq/baby-python
python
from calendar import timegm from datetime import datetime import logging from django.contrib.sessions.middleware import SessionMiddleware from django.contrib.auth.middleware import AuthenticationMiddleware from django.core.urlresolvers import reverse from django.conf import settings from rest_framework import excepti...
nilq/baby-python
python
import json import uuid from moto.awslambda.exceptions import ( PreconditionFailedException, UnknownPolicyException, ) class Policy: def __init__(self, parent): self.revision = str(uuid.uuid4()) self.statements = [] self.parent = parent def wire_format(self): p = self...
nilq/baby-python
python
""" TensorFlow 基础概念 """ #%% 导入 TensorFlow import tensorflow as tf #%% 什么是Tensor # Tensor 是 TensorFlow 的基本对象 # 说白了就是多维向量 t0 = tf.constant(1) # 0阶 tensor t1 = tf.constant([1, 2]) # 1阶 tensor t2 = tf.constant([[1, 2], [3, 4]]) # 2阶 tensor t3 = tf.constant([[[1., 2., 3.]], [[7., 8., 9.]]]) # 3阶 tensor print(t0) print...
nilq/baby-python
python
import unittest import pytest from api.utils import encode from api.utils import decode class UtilsTest(unittest.TestCase): def test_base62_encode_zero(self): n = 0 encoded_digit = encode(n) assert "0" == encoded_digit def test_base62_encode_digit(self): n = 4 encode...
nilq/baby-python
python
#!/usr/bin/env python import subprocess import os import sys import glob import json import traceback import re import logging log = logging.getLogger('run-ci') import time import threading from benchmark import framework_test from benchmark.utils import gather_tests from benchmark.utils import header # Cross-platfor...
nilq/baby-python
python
from .dns_server import DnsServer, DnsServerNotRunningException from .dns_demo_server import DnsDemoServer
nilq/baby-python
python
import tempfile import unittest from pathlib import Path import numpy as np import pandas as pd from tests.fixtures.algorithms import DeviatingFromMean, DeviatingFromMedian from tests.fixtures.dataset_fixtures import CUSTOM_DATASET_PATH from timeeval import TimeEval, Algorithm, AlgorithmParameter, DatasetManager, Inp...
nilq/baby-python
python
"""Kata: Binary Addition - Return the opposite of the input number. #1 Best Practices Solution by arzyk and 7 others def add_binary(a,b): return bin(a+b)[2:] """ def add_binary(a, b): return bin(a + b)[2:]
nilq/baby-python
python
# -*- coding: utf-8 -*- import dataiku import pandas as pd, numpy as np from dataiku import pandasutils as pdu import requests import urllib import json import time from datetime import datetime from dataiku.customrecipe import * import dataiku_esri_utils import common from dataiku_esri_utils import recipe_config_get_s...
nilq/baby-python
python
""" This file is needed as 1.6 only finds tests in files labelled test_*, and ignores tests/__init__.py. """ from south.tests import *
nilq/baby-python
python
""" Copyright (c) 2018-2021 Intel 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 wri...
nilq/baby-python
python
""" The ``agar.json`` module contains classes to assist with creating json web service handlers. """ import datetime import logging from google.appengine.ext.db import BadRequestError, BadValueError from agar.config import Config from agar.models import ModelException from pytz.gae import pytz from restler.seriali...
nilq/baby-python
python
#!/usr/bin/python from math import floor def find_largest_factor(n): """ Return the largest prime factor of n: 1. Find i such that i is the smallest number that i * j = n 2. Therefore the largest prime factor of n is also the largest prime factor of j 3. Repeat until j is a prime number ...
nilq/baby-python
python
# Generated by Django 3.2.6 on 2021-09-04 16:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('telegrambot', '0011_telegramuserbot'), ] operations = [ migrations.AddField( model_name='telegramuserbot', name='ses...
nilq/baby-python
python
''' File name: utilities.py Author: Simonas Laurinavicius Email: simonas.laurinavicius@mif.stud.vu.lt Python Version: 3.7.6 Purpose: Utilities module defines various helper functions used by different modules ''' # Local modules import formats def return_shorter_str(str1, str2): if l...
nilq/baby-python
python
CLAUSE_LIST = [(1,), (0,)] N = 3 A = 65 class SAT: """ This class is an SAT solver. Create an instance by passing in a list of clauses and the number of variables Uses notation of 2N + 1 to input tuples of clauses Ex: (A+B)(~B+C) - > (0, 2)(3, 4) There are 3 variables so: A = 0 = 2*(0) ...
nilq/baby-python
python