content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import libsinan from libsinan import handler, output, jsax class VersionCheckTaskHandler(output.SimpleTaskHandler): def __init__(self): output.SimpleTaskHandler.__init__(self) self.version = None def object_end(self): """ We only get one object per right now so lets print it ...
nilq/baby-python
python
import urllib.request, json from .models import News_Update from .models import Article api_key = None base_url = None articles_url = None def configure_request(app): global api_key, base_url, articles_url api_key = app.config['NEWS_API_KEY'] base_url = app.config['NEWS_API_BASE_URL'] articles_url =...
nilq/baby-python
python
# -*- coding: UTF-8 -*- from django.shortcuts import render from rest_framework import authentication, viewsets from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated, AllowAny from rest_framework.response import Response from rest_framework import stat...
nilq/baby-python
python
""" Docstring for the app_test.py module. """ import pytest from app import app @pytest.fixture def client(): """ Method to yield a test client from app. """ app.config['TESTING'] = True client = app.test_client() yield client def test_ping(client): """ Function to test debug route....
nilq/baby-python
python
#!/usr/bin/python # An example vendordata server implementation for OpenStack Nova. With a giant # nod in the direction of Chad Lung for his very helpful blog post at # http://www.giantflyingsaucer.com/blog/?p=4701 import json import sys from webob import Response from webob.dec import wsgify from paste import https...
nilq/baby-python
python
#PYTHON 3.6 #coding : utf8 from tkinter import * class Aplication(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.msg = Label(self, text='Hello World') self.msg.pack() self.bye = Button(self, text="Bye", command=self.quit) self.bye.pack() self.pack() ...
nilq/baby-python
python
# %matplotlib notebook import os, re, sys, urllib, requests, base64, IPython, io, pickle, glob import itertools as itt import numpy as np import subprocess as sb import pandas as pd import matplotlib.pyplot as plt import matplotlib.image as mpimg import roadrunner from bs4 import BeautifulSoup as BS from IPython.displ...
nilq/baby-python
python
from datetime import datetime, timedelta from freezegun import freeze_time from pyobjdb import PyObjDB def test_basic(tmp_path): db = PyObjDB(str(tmp_path / 'test.db')) db.put('key_str', 'foo') assert db.get('key_str') == 'foo' assert db.get(b'key_str') == 'foo' db.put('key_str', 'bar') ass...
nilq/baby-python
python
""" This file contains tests for partition explainer. """ import tempfile import pytest import numpy as np import shap def test_serialization_partition(): """ This tests the serialization of partition explainers. """ AutoTokenizer = pytest.importorskip("transformers").AutoTokenizer AutoModelForSeq2SeqL...
nilq/baby-python
python
""" This module handles teams - collections of Characters """ from maelstrom.util.serialize import AbstractJsonSerialable import functools class Team(AbstractJsonSerialable): """ stores and manages Characters """ def __init__(self, **kwargs): """ Required kwargs: - name: s...
nilq/baby-python
python
# tifffile/__main__.py """Tifffile package command line script.""" import sys from .tifffile import main sys.exit(main())
nilq/baby-python
python
import pygame import sys import numpy as np pygame.init() WIDTH = 600 HEIGHT = 600 LINE_WIDTH = 15 WIN_LINE_WIDTH = 15 BOARD_ROWS = 3 BOARD_COLS = 3 SQUARE_SIZE = 200 CIRCLE_RADIUS = 60 CIRCLE_WIDTH = 15 CROSS_WIDTH = 25 SPACE = 55 BG_COLOR = (255,0,0) LINE_COLOR = (0,0,0) CIRCLE_COLOR = (239, 231...
nilq/baby-python
python
from nnrecsys.models.metrics import mean_reciprocal_rank import tensorflow as tf def model_fn(features, labels, mode, params): print(features) input_layer, sequence_length = tf.contrib.feature_column.sequence_input_layer(features, params['feature_columns']) with tf.name_scope('encoder'): def rnn_...
nilq/baby-python
python
import numpy as np import torch def default_collate_fn(batch): batch, targets = zip(*batch) batch = np.stack(batch, axis=0).astype(np.float32) batch = torch.from_numpy(batch).permute(0, 3, 1, 2).contiguous() for i, target in enumerate(targets): for k, v in target.items(): if isinst...
nilq/baby-python
python
from random import randint from django.contrib.auth.models import User from .models import Analytic, Group def get_client_ip(request): x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR") if x_forwarded_for: ip = x_forwarded_for.split(",")[0] else: ip = request.META.get("REMOTE_ADD...
nilq/baby-python
python
from __future__ import absolute_import, print_function, division import os import numpy import theano from theano.compat import PY3 from theano import config from theano.compile import DeepCopyOp from theano.misc.pkl_utils import CompatUnpickler from .config import test_ctx_name from .test_basic_ops import rand_gpua...
nilq/baby-python
python
import os import sys myfolder = os.path.dirname(os.path.abspath(__file__)) def rpienv_source(): import subprocess if not os.path.exists(str(myfolder) + '/.rpienv'): print("[ ENV ERROR ] " + str(myfolder) + "/.rpienv path not exits!") sys.exit(1) command = ['bash', '-c', 'source ' + str(myfo...
nilq/baby-python
python
# =============================================================================== # Copyright 2020 ross # # 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/LICE...
nilq/baby-python
python
from lib import action class ConsulParseNodesAction(action.ConsulBaseAction): def run(self, data): nodes = [] # Loop through the keys, and return the needful return nodes
nilq/baby-python
python
from fastapi import FastAPI import routes from middleware import auth_check from starlette.middleware.base import BaseHTTPMiddleware app = FastAPI() # TO RUN THE APP SPECIFY THIS INSTANCE OF THE FastApi class # uvicorn file_name:instance name --reload app.include_router(routes.router) app.add_middleware(BaseHTTPMidd...
nilq/baby-python
python
import os import os.path as op from ..externals.six.moves import cPickle as pickle import glob import warnings import numpy as np from numpy.testing import assert_array_equal, assert_array_almost_equal from nose.tools import assert_true, assert_raises from mne.datasets import sample from mne import (label_time_course...
nilq/baby-python
python
from django.contrib import admin from .models import MataKuliah, Tugas # Register your models here. admin.site.register(MataKuliah) admin.site.register(Tugas)
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2020-02-16 14:41 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('folio', '0007_auto_20200216_1720'), ] operations = [ migrations.AddField( ...
nilq/baby-python
python
@bot.command(brief="Kicks a server member", description="b!kick <member> [reason]") @commands.has_permissions(kick_members=True) async def kick(ctx, member: discord.Member, *, reason=None): try: await member.kick(reason=reason) await ctx.send(f'User {member} has been kicked.') except: await ct...
nilq/baby-python
python
#!/usr/bin/env python3 """ Python module to assist creating and maintaining docker openHab stacks.""" import crypt from enum import Enum from typing import NamedTuple import logging import os import sys import json as pyjson from hashlib import md5 from shutil import copy2 from subprocess import PIPE, run from time imp...
nilq/baby-python
python
import os from bs4 import BeautifulSoup bicycle = {'Price':'------','Brand':'------','Model':'------','Frame': '------', 'Color': '------', 'Size': '------', 'Fork': '------', 'Headset': '------', 'Stem': '------', 'Handlebar': '------', 'Grips': '------', 'Rear Derailleur': '------', 'Front Derailleur': '------', 'Sh...
nilq/baby-python
python
a=int(input("enter a number")) for i in range(a+1): if(i>1): for j in range(2,i): if(i%j==0): break else: print(i)
nilq/baby-python
python
from spinn_front_end_common.utilities.notification_protocol.\ notification_protocol import NotificationProtocol import logging logger = logging.getLogger(__name__) class FrontEndCommonNotificationProtocol(object): """ The notification protocol for external device interaction """ def __call__( ...
nilq/baby-python
python
#!/usr/bin/env python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import hashlib import optparse import os import urllib2 import sys import time # Print a dot every time this number of bytes is r...
nilq/baby-python
python
import RPi.GPIO as GPIO from queue import Queue EventClick = 'C' class ButtonWorker(object): def __init__(self, pin): self.gpio = GPIO self.gpio.setwarnings(False) self.queue = Queue() self.pin = pin self.gpio.setmode(GPIO.BCM) self.gpio.s...
nilq/baby-python
python
from pyrogram.types import InlineQueryResultArticle,InputTextMessageContent from uuid import uuid4 class InlineQueryResults(list): def __init__(self): self.results = list() super().__init__(self.results) def add(self,title,message_text,message_parse_mode = None,message_disable_web_page_previe...
nilq/baby-python
python
from .FSError import * class ProtectFlags: FIBF_DELETE = 1 FIBF_EXECUTE = 2 FIBF_WRITE = 4 FIBF_READ = 8 FIBF_ARCHIVE = 16 FIBF_PURE = 32 FIBF_SCRIPT = 64 flag_txt = "HSPArwed" flag_num = len(flag_txt) flag_none = 0xF # -------- empty_string = "-" * flag_num def __in...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ tipfyext.mako ~~~~~~~~~~~~~ Mako template support for Tipfy. Learn more about Mako at http://www.makotemplates.org/ :copyright: 2011 by tipfy.org. :license: BSD, see LICENSE.txt for more details. """ from __future__ import absolute_import from cStringIO import Stri...
nilq/baby-python
python
# coding=utf-8 import unittest import sys from helpers import xroad, auditchecker from main.maincontroller import MainController from tests.xroad_configure_service_222 import configure_service class XroadDeleteService(unittest.TestCase): """ SERVICE_15 Delete a Security Server Client's WSDL RIA URL: https...
nilq/baby-python
python
from typing import Callable, Tuple import numpy as np from fedot.core.data.data import InputData from fedot.core.validation.compose.metric_estimation import metric_evaluation from fedot.core.validation.split import ts_cv_generator def ts_metric_calculation(reference_data: InputData, cv_folds: int, ...
nilq/baby-python
python
# # PySNMP MIB module TRAPEZE-NETWORKS-BASIC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRAPEZE-NETWORKS-BASIC-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:27:11 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version ...
nilq/baby-python
python
#!/usr/bin/env python2.7 # Copyright 2016, Google Inc. # 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 must retain the above copyright # notice, this lis...
nilq/baby-python
python
"""Module with implementation of the Grid classes.""" from bubblebox.library.create import Dataset,Block,Data from bubblebox.library.utilities import Action import numpy import pymorton class GridBase(Dataset): """Base class for the Grid.""" type_ = 'base' def __init__(self, varlist, nx, ny, xmin, xmax,...
nilq/baby-python
python
COLUMNS = [ 'TIPO_REGISTRO', 'NRO_RV_ORIGINAL', 'NRO_CARTAO', 'NRO_PV_ORIGINAL', 'DT_TRANSACAO_CV', 'NRO_NSU', 'VL_TRANSACAO_ORIGINAL', 'NRO_AUTORIZACAO', 'TID', 'NRO_PEDIDO' ]
nilq/baby-python
python
"""Setup script""" try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup, find_packages from Cython.Build import cythonize import numpy as np my_modules = cythonize("pysparselp/*.pyx", annotate=True) libname = "pysparselp" setup( name=libna...
nilq/baby-python
python
import pandas as pd class HelperDataFrame(pd.DataFrame): """Inherits from a Pandas Data Frame and adds a couple methods.""" def __init__(self, df): super().__init__(data=df) # self.random_state = 42 def randomize(self): """Shuffles observations of a dataframe""" return self...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ app ~~~~~~~~~~~ The Flask application module. :author: Jeff Kereakoglow :date: 2014-11-14 :copyright: (c) 2014 by Alexis Digital :license: MIT, see LICENSE for more details """ import os from utils import prepare_json_response from flask imp...
nilq/baby-python
python
""" This falls into my "bad idea that I'm playing with" category. Withold judgement and ye lunches. Upgraded to plausible. """ from importlib import import_module class Singleton(type): instance_list = {} def __call__(klass, *args, **kwargs): if not klass in klass.instance_list: ...
nilq/baby-python
python
# -*- coding: utf-8 -*- # @FILE : consts.py # @AUTH : model_creater
nilq/baby-python
python
#!/usr/bin/env python import numpy as np import math from multi_link_common import * #height is probably 0 from multi_link_common.py #total mass and total length are also defined in multi_link_common.py num_links = 8.0 link_length = total_length/num_links link_mass = total_mass/num_links ee_location = np.matrix([0.,...
nilq/baby-python
python
import streamlit as st st.sidebar.subheader("About dspy") st.sidebar.info("A webapp that is running on python and teaching python!") st.sidebar.markdown(""" <img src="https://media.giphy.com/media/3o7527pa7qs9kCG78A/giphy.gif" width="200"> """, unsafe_allow_html=True) st.title("`dspy` - Data Science with Python") st....
nilq/baby-python
python
#! /usr/bin/env python3 import sys import os import cmd2 import logging import inspect # local modules import subcmd from subcmdfactory import SubCmdFactory from config import Config, Observer, Subject class QsmShell(cmd2.Cmd, Observer): intro = 'Type help or ? to list the command.\n' def emptyline(self)...
nilq/baby-python
python
import os import time import gpustat import numpy as np from redlock import Redlock GPU_LOCK_TIMEOUT = 5000 # ms class GPUManager(object): def __init__(self, verbose: bool=False): self.lock_manager = Redlock([{"host": "localhost", "port": 6379, "db": 0}, ]) self.verbose = verbose def get_f...
nilq/baby-python
python
from matplotlib import pyplot as plt from matplotlib import animation import random import numpy as np from boids.flock import Flock from boids.flight import Flight from argparse import ArgumentParser import yaml import os from nose.tools import assert_equal from nose.tools import assert_raises
nilq/baby-python
python
import orca import numpy as np from urbansim.utils import misc def register_skim_access_variable( column_name, variable_to_summarize, impedance_measure, distance, skims_table, agg=np.sum, log=False): """ Register skim-based accessibility variable with orca. Parameters ---------- co...
nilq/baby-python
python
import chainer from chainer.dataset import dataset_mixin from chainercv.chainer_experimental.datasets.sliceable import GetterDataset import chainercv from collections import defaultdict import glob import os import numpy as np import xml.etree.ElementTree as ET class DogDataset(dataset_mixin.DatasetMixin): def __...
nilq/baby-python
python
#! /usr/bin/env python import numpy as np import cv2 import glob import yaml class CameraCalib : def __init__(self,img_path='/tmp',CHESSX=8,CHESSY=6,extension=".jpg"): """ Initialize Camera Calibration Class @param: img_path = [path to get images], CHESSX = [chessboard corners in X directi...
nilq/baby-python
python
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from edward.util.tensorflow import get_control_variate_coef class test_get_control_variate_coef(tf.test.TestCase): def test_calculate_correct_coefficient(self): with self.test_...
nilq/baby-python
python
# Copyright 2020 Jiang Shenghu # SPDX-License-Identifier: Apache-2.0 from tvm import topi from ..poly import TensorTable, Statement, ScheduleTree from .conv import PlainConv2d, Conv2d def schedule(**kwargs): init_t = 'stmt_init[n, c, h, w]' calc_t = 'stmt_calc[n, c, h, w, i, j, k]' output_constraints = '...
nilq/baby-python
python
# ============================================================================= # SIMULATION-BASED ENGINEERING LAB (SBEL) - http://sbel.wisc.edu # University of Wisconsin-Madison # # Copyright (c) 2020 SBEL # All rights reserved. # # Use of this source code is governed by a BSD-style license that can be found # at http...
nilq/baby-python
python
""" Write a function with a list of ints as a paramter. / Return True if any two nums sum to 0. / >>> add_to_zero([]) / False / >>> add_to_zero([1]) / False / >>> add_to_zero([1, 2, 3]) / False / >>> add_to_zero([1, 2, 3, -2]) / True / """
nilq/baby-python
python
# encoding=utf-8 # A collection of regular expressions for parsing Tweet text. The regular expression # list is frozen at load time to ensure immutability. These reular expressions are # used throughout the Twitter classes. Special care has been taken to make # sure these reular expressions work with Tweets in all la...
nilq/baby-python
python
# !/usr/bin/env python # -*-coding:utf-8 -*- # PROJECT : algorithm_mad # Time :2020/12/22 11:06 # Warning :The Hard Way Is Easier import random """ 堆排序 """ '''堆化''' def heapify(array, length, i): largest = i left = 2 * i + 1 right = 2 * i + 2 if left < length and array[largest] < array[le...
nilq/baby-python
python
from concurrent.futures import Future from typing import Any, Callable, TypeVar from threading import Lock from amino import do, Do, IO, Map, Dat from amino.logging import module_log from ribosome.rpc.error import RpcReadError from ribosome.rpc.data.rpc import ActiveRpc A = TypeVar('A') log = module_log() PendingR...
nilq/baby-python
python
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from django.contrib.auth.models import User from uw_gws.utilities import fdao_gws_override from uw_pws.util import fdao_pws_override from uw_uwnetid.util import fdao_uwnetid_override def get_user(username): try: user = ...
nilq/baby-python
python
from Jumpscale import j import os # import copy # import sys import inspect import types class JSBase: def __init__(self, parent=None, topclass=True, **kwargs): """ :param parent: parent is object calling us :param topclass: if True means no-one inherits from us """ self._...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Protocol implementation for `Tokyo Tyrant <http://1978th.net/tokyotyrant/>`_. Let's assume some defaults for our sandbox:: >>> TEST_HOST = '127.0.0.1' >>> TEST_PORT = 1983 # default port is 1978 """ import math import socket import struct import exceptions # Pyrant constant...
nilq/baby-python
python
import h2o h2o.init() weather_hex = h2o.import_file("weather.csv") # To see a brief summary of the data, run the following command. weather_hex.describe()
nilq/baby-python
python
from Tkinter import Tk, Label, Button def update_label(): global n n += 1 l["text"] = "Number of clicks: %d" % n w = Tk() n = 0 l = Label(w, text="There have been no clicks yet") l.pack() Button(w, text="click me", command=update_label).pack() w.mainloop()
nilq/baby-python
python
# -*- coding: utf-8 -*- # cython: language_level=3 # Copyright (c) 2020 Nekokatt # Copyright (c) 2021-present davfsa # # 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, inc...
nilq/baby-python
python
import json import os import copy __author__ = 'nekmo' class Field(object): def __call__(self, value): return self.parse(value) def parse(self, value): raise NotImplementedError class IntegerField(Field): def parse(self, value): return int(value) class BooleanField(Field): ...
nilq/baby-python
python
import logging.config import os class Config(object): SERVER_NAME = '127.0.0.1:5000' LOGGING_CONFIG_FILE = 'logging-config.ini' @classmethod def init_app(cls, app): logging_config_path = os.path.normpath( os.path.join( os.path.dirname(__file__), cls.LOGGING_CONFIG_F...
nilq/baby-python
python
""" InputReader -------------------------------------------------- Input Reader that loads previous output files """ import yaml import json def load_previous_outputs_as_inputs(file_paths: list) -> dict: print("Start loading input files...") previous_records = {} for file_path in file_paths: prin...
nilq/baby-python
python
from robo_ai.resources.assistants import AssistantsResource from robo_ai.resources.client_resource import ClientResource from robo_ai.resources.oauth import OauthResource class BaseResource(ClientResource): def _register_resources(self): self._add_resource('assistants', AssistantsResource) self._a...
nilq/baby-python
python
# sdspy import configparser import datetime import json from performance_counters import PerformanceCounters as PC from sds_client import SdsClient from sds_stream import SdsStream from sds_type import SdsType from sds_type_code import SdsTypeCode from sds_type_data import SdsTypeData from sds_type_property import Sds...
nilq/baby-python
python
import matplotlib # Force matplotlib to not use any Xwindows backend. matplotlib.use('Agg') import pickle import operator from random import randint import matplotlib.pyplot as plt import matplotlib.cm as cm import numpy as np import data_io.settings as Settings from data_io.testdata import sliding_window f...
nilq/baby-python
python
class CircularQueue: """ Queue implementation using circularly linked list for storage """ #------------------------------------------------------------------------------------- #------------------------------------------------------------------------------------- class _Node: """ LightWwight, non public cl...
nilq/baby-python
python
# -*- coding: utf-8 from __future__ import unicode_literals, absolute_import import django DEBUG = True USE_TZ = True # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "uh-v-hc=h7=%4(5g&f13217*!ja%osm%l0oyb$^n2kk^ij#&zj" DATABASES = { "default": { "ENGINE": "django.db.backen...
nilq/baby-python
python
import os import pytest from helpers.cluster import ClickHouseCluster from helpers.network import PartitionManager from helpers.test_tools import assert_eq_with_retry CLICKHOUSE_DATABASE = 'test' def initialize_database(nodes, shard): for node in nodes: node.query(''' CREATE DATABASE {data...
nilq/baby-python
python
# Import the modules import sys import MinVel as mv import numpy as np # NOTES: May want to update temperature dependence of thermal expansivity using Holland and Powell's (2011) # new revised equations (see figure 1 in that article). This will necessitate recalculating the first # Gruneisen parameters...
nilq/baby-python
python
import os import sys import cv2 import numpy as np from PyQt5.QtCore import pyqtSlot, QThreadPool, QTimer from PyQt5.QtWidgets import * from PyQt5 import QtCore from PyQt5.QtGui import * from src.transformers.Transformer import Transformer, getTransformer from src.util.UserInterface.ControlBox import ControlBox from ...
nilq/baby-python
python
# coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
nilq/baby-python
python
"""Metrics to assess performance on sequence labeling task given prediction Functions named as ``*_score`` return a scalar value to maximize: the higher the better Reference: seqeval==0.0.19 """ from __future__ import absolute_import, division, print_function import warnings from collections import defaultdict impor...
nilq/baby-python
python
from det3d.core.utils.scatter import scatter_mean from torch.nn import functional as F from ..registry import READERS from torch import nn import numpy as np import torch def voxelization(points, pc_range, voxel_size): keep = (points[:, 0] >= pc_range[0]) & (points[:, 0] <= pc_range[3]) & \ (points[:,...
nilq/baby-python
python
from fjord.base.tests import eq_, TestCase from fjord.feedback.utils import clean_url, compute_grams class Testclean_url(TestCase): def test_basic(self): data = [ (None, None), ('', ''), ('http://example.com/', 'http://example.com/'), ('http://example.com/#f...
nilq/baby-python
python
from typing import Optional from cdm.enums import CdmObjectType from cdm.objectmodel import CdmAttributeReference, CdmCorpusContext from .cdm_object_ref_persistence import CdmObjectRefPersistence class AttributeReferencePersistence(CdmObjectRefPersistence): @staticmethod def from_data(ctx: CdmCorpusContext,...
nilq/baby-python
python
import pandas as pd IN_FILE = 'aus-domain-urls.txt' START_IDX = 0 BLOCK_SIZE = [10, 20, 50, 100, 1000, 100000, 1000000] OUT_FILE_PREFIX = 'aus-domain-urls' data = pd.read_csv(IN_FILE) data_length = len(data) for i in range(len(BLOCK_SIZE)): if i == 0: lower_bound = 0 else: lower_bound = upper_...
nilq/baby-python
python
# Generated by Django 3.2.6 on 2021-10-19 10:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dashboard', '0002_auto_20211019_1613'), ] operations = [ migrations.RemoveField( model_name='bookingrooms', name='ro...
nilq/baby-python
python
from typing import Protocol class SupportsStr(Protocol): def __str__(self) -> str: ...
nilq/baby-python
python
import os import tensorflow as tf from PIL import Image cwd = os.getcwd()+'/train/' for root, dirs, files in os.walk(cwd): print(dirs) # 当前路径下所有子目录 classes = dirs break print(cwd) writer = tf.python_io.TFRecordWriter("train.tfrecords") for index, name in enumerate(classes): class_path = cwd + name + ...
nilq/baby-python
python
# -*- coding: utf-8 -*- # (c) Copyright IBM Corp. 2010, 2021. All Rights Reserved. # pragma pylint: disable=unused-argument, no-self-use """ Incident poller for a ProofPoint TRAP server """ import logging from resilient_circuits import ResilientComponent, handler from fn_scheduler.components import SECTION_SCHEDULER f...
nilq/baby-python
python
import os import pandas as pd from bento.common import datautil, logger, util logging = logger.fancy_logger(__name__) def load_covid_raw_data(data_path, base, cases, deaths, nrows=None): read_args = {} if nrows: read_args["nrows"] = nrows idf = pd.read_csv(f"{data_path}/{base}/{cases}").drop(["La...
nilq/baby-python
python
from tests.unit.dataactcore.factories.staging import DetachedAwardFinancialAssistanceFactory from tests.unit.dataactvalidator.utils import number_of_errors, query_columns _FILE = 'fabs18_detached_award_financial_assistance' def test_column_headers(database): expected_subset = {'row_number', 'business_types', 'un...
nilq/baby-python
python
from rtm.api import validate def test_validate(rtm_path): validate(rtm_path)
nilq/baby-python
python
from sqlalchemy import create_engine from td.client import TDClient from datetime import datetime from td import exceptions from requests.exceptions import ConnectionError import datetime import pandas as pd import sqlite3 import time import credentials print("- Modules imported -") def make_sqlite_table(table_name)...
nilq/baby-python
python
import sys, os, subprocess, shutil, time BUILDDIR = os.path.abspath("build") NINJA_EXE = "ninja.exe" NINJA_BUILD_FILE = "build/build.ninja" CALL_PATH = os.getcwd() TOOL_PATH = sys.path[0] + "/" TOOLCHAIN_PATH = os.path.dirname(sys.path[0]) NO_EMOJI = False NO_COLOR = False SELECTION = None SECONDARY = None CMAKE_EX...
nilq/baby-python
python
#!/usr/bin/python """ This plugin implements identifying the modbusRTU protocol for serial2pcap. Modbus RTU Frame Format: Name Length (bits) Function Start 28 At least 3.5 (28 bits) character times of silence Address 8 Function 8 Data n*8 CRC 16 End 28 At Least 3.5 (28 bits) charact...
nilq/baby-python
python
import sys import DiveConstants as dc from rpy2.rinterface import NA from rpy2.robjects.vectors import IntVector, FloatVector, StrVector import rpy2.robjects.packages as rpackages import rpy2.robjects as robjects import numpy as np np.set_printoptions(suppress=True) utils = rpackages.importr('utils') scuba = rpackages....
nilq/baby-python
python
from collections import Counter from random import randint from django.http import JsonResponse from django.shortcuts import render from django.views.generic import View, TemplateView from .models import Article, portals, languages from utils.utils import parse_a_website BENCHMARK_URL = 'https://www.benchmark.pl/' B...
nilq/baby-python
python
'''utils and constants functions used by the selector and selectors class''' import re RE_ALPHA = re.compile(r'\w') SELECTOR_TYPE = {'XML': 'xml', 'TRXML': 'trxml'} TRXML_SELECTOR_TYPE = {'SINGLETON': 'singleton', 'MULTIPLE': 'multiple'} def valid_field_name(tag_name: str = '') -> bool: ''' simple validatio...
nilq/baby-python
python
import matplotlib.pyplot as plt import random import numpy as np import cv2 def visualize(img, det_boxes=None, gt_boxes=None, keypoints=None, is_show_label=True, show_cls_label = True, show_skeleton_labels=False, classes=None, thresh=0.5, name='detection', return_img=False): if is_show_label: if classes ==...
nilq/baby-python
python
import webbrowser class RomanNumeralCipher: def __init__(self): ''' This is a python implementation of Roman Numeral Cipher''' self.val = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ] self.syb = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"...
nilq/baby-python
python
import json import disnake as discord from disnake.ext import commands class Active_Check(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def activate(self, ctx, cog=None): with open('utils/json/active_check.json', 'r') as f: data = json.load(f...
nilq/baby-python
python
import sys sys.path.append("../common/tests") from test_utils import * import test_common sys.path.insert(0, '../../../../build/production/config/schema-transformer/') from vnc_api.vnc_api import * import uuid class STTestCase(test_common.TestCase): def setUp(self): super(STTestCase, self).setUp() ...
nilq/baby-python
python
from django.contrib import admin from unecorn.models import * admin.site.register(Discount) admin.site.register(Category) admin.site.register(Company)
nilq/baby-python
python