content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
#!/usr/bin/python3
from flask import request
from modules import simple_jwt
from modules.database import get_db_conn
# ----------------------------------------
# Check Auth Token before execute request
# ----------------------------------------
from server_error import server_error
def logged_before_request():
t... | nilq/baby-python | python |
import os
import tempfile
import re
import shutil
import requests
import io
import urllib
from mitmproxy.net import tcp
from mitmproxy.test import tutils
from pathod import language
from pathod import pathoc
from pathod import pathod
from pathod import test
from pathod.pathod import CA_CERT_NAME
def treader(bytes)... | nilq/baby-python | python |
import zipfile
import pandas as pd
from datanator_query_python.util import mongo_util
from datanator_query_python.config import config as q_conf
import os
class proteinHalfLives(mongo_util.MongoUtil):
def __init__(self, MongoDB, db, collection, username, password,
path):
super().__init__... | nilq/baby-python | python |
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
h = int(readline())
cnt = 0
if h == 1:
print(1)
elif h == 2:
print(3)
else:
for i in range(h):
if h < 2 ** i:
print(cnt)
exit()
... | nilq/baby-python | python |
_SCRIPT_VERSION = "Script version: Nuthouse01 - 6/10/2021 - v6.00"
# This code is free to use and re-distribute, but I cannot be held responsible for damages that it may or may not cause.
#####################
try:
# these imports work if running from GUI
from . import nuthouse01_core as core
from . import nuthou... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name="sio2puppetMaster",
version="0.3",
packages=find_packages(),
install_requires=[],
scripts=['scripts/sio2pm-spawndocker'],
license="MIT",
author="Mateusz Żółtak",
author_email="zozlak@zozlak.org"
)
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import re, os
if not hasattr(__builtins__, 'cmp'):
def cmp(a, b):
return (a > b) - (a < b)
from collections import OrderedDict, namedtuple as NamedTuple
from functools import wraps
from pkg_resources import parse_version as p... | nilq/baby-python | python |
#!/usr/bin/env python
##
# omnibus - deadbits
# fullcontact.com
##
from http import get
from common import get_apikey
class Plugin(object):
def __init__(self, artifact):
self.artifact = artifact
self.artifact['data']['fullcontact'] = None
self.api_key = get_apikey('fullcontact')
s... | nilq/baby-python | python |
NAME='console_broadcast'
GCC_LIST=['broadcast']
| nilq/baby-python | python |
from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql import SparkSession
from pyspark.sql import Row
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from pyspark.ml.fpm import FPGrowth
if __name__ == "__main__":
sc = SparkContext('local', 'arules')
s... | nilq/baby-python | python |
#coding:utf-8
#KDD99数据集预处理
#共使用39个特征,去除了原数据集中20、21号特征
import numpy as np
import pandas as pd
import csv
from datetime import datetime
from sklearn import preprocessing # 数据标准化处理
#定义KDD99字符型特征转数值型特征函数
def char2num(sourceFile, handledFile):
print('START: 字符型特征转数值型特征函数中')
data_file=open(handle... | nilq/baby-python | python |
import matplotlib.pyplot as plt
import os
from pathlib import Path
from typing import Union
import bilby
import redback.get_data
from redback.likelihoods import GaussianLikelihood, PoissonLikelihood
from redback.model_library import all_models_dict
from redback.result import RedbackResult
from redback.utils import lo... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads_v4/proto/errors/conversion_action_error.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobu... | nilq/baby-python | python |
#!/usr/bin/env python3
import sys
import os
import time
import docker
def error(msg):
print(msg, file=sys.stderr)
exit(1)
def main():
if len(sys.argv) != 2:
error(f"{sys.argv[0]} <container_name>")
container_name = sys.argv[1]
client = docker.from_env()
try:
container = c... | nilq/baby-python | python |
# -------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# ----------------------------------------------------------------------... | nilq/baby-python | python |
import json
from carla.driving_benchmark.results_printer import print_summary
with open('../_benchmarks_results/outputs-27/metrics.json') as json_file:
metrics_summary = json.load(json_file)
train_weathers = [1, 3, 6, 8]
test_weathers = [4, 14]
print("Printing Data\n")
print_summary(metrics_summa... | nilq/baby-python | python |
import json
import os.path as osp
from glob import glob
import numpy as np
from nms_cpu import nms_cpu as nms
'''
load annotation from BDD format json files
'''
def load_annos_bdd(path, folder=True, json_name='*/*_final.json'):
print("Loading GT file {} ...".format(path))
if folder:
jsonlist = sorted... | nilq/baby-python | python |
import context
import sys
import pytest
from dice import dice
from score import scoreCalculate
from game.Player import Player
from game.score_bracket import score_bracket
@pytest.fixture(scope='session')
def load_normal_player():
one = score_bracket(250,350,4)
two = score_bracket(400,500,3)
three = score_b... | nilq/baby-python | python |
import os
import random
import re
import sys
DAMPING = 0.85
SAMPLES = 10000
def main():
if len(sys.argv) != 2:
sys.exit("Usage: python pagerank.py corpus")
corpus = crawl(sys.argv[1])
ranks = sample_pagerank(corpus, DAMPING, SAMPLES)
print(f"PageRank Results from Sampling (n = {SAMPLES})")
... | nilq/baby-python | python |
import logging
import pandas as pd
import numpy as np
import glob_utils.file.utils
logger = logging.getLogger(__name__)
################################################################################
# Save/Load csv files
################################################################################
def sa... | nilq/baby-python | python |
# Generated by Django 3.1.4 on 2021-05-07 01:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('TFS', '0002_auto_20210507_0656'),
]
operations = [
migrations.AlterField(
model_name='customerdetail',
name='email',... | nilq/baby-python | python |
#-*-coding:utf-8-*-
import sys
import time
from flask import Flask,jsonify
app = Flask(__name__)
appJSON={
"controller":{
"title":"Speed Dial Squared Up",
"rightButton":{
"title":"请求",
"click":"${()=>{$dispatch('fetchData')}}"
}
},
"lifeCircle":{
"vi... | nilq/baby-python | python |
import tensorflow as tf
import numpy as np
interpreter = tf.lite.Interpreter('models/mobilefacenet.tflite')
interpreter.allocate_tensors()
def set_input_tensor_face(input):
input_details = interpreter.get_input_details()[0]
tensor_index = input_details['index']
input_tensor = interpreter.tensor(tensor_ind... | nilq/baby-python | python |
from typing import Sequence
from torch import nn
class Model(nn.Module):
def __init__(
self,
n_features: int,
n_classes: int,
units: Sequence[int] = [512],
dropout: float = 0.5,
):
super().__init__()
sizes = [n_features] + list(units)
self.hidd... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2019-02-12 23:07
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
def forwards_func(apps, schema_editor):
Menu = apps.get_model("das", "Menu")
db_alias = schema_editor.connectio... | nilq/baby-python | python |
"""Unit tests for the `cf_predict` package."""
| nilq/baby-python | python |
import torch
import argparse
from Transformer import Transformer
parser = argparse.ArgumentParser(description='Test transformer')
parser.add_argument('--src_len', '-s', type=int, default=5, help='the source sequence length')
parser.add_argument('--batch_size', '-bs', type=int, default=2, help='batch size')
parser.add... | nilq/baby-python | python |
import FWCore.ParameterSet.Config as cms
#
#
#------------------
#Preshower clustering:
#------------------
from RecoEcal.EgammaClusterProducers.multi5x5SuperClustersWithPreshower_cfi import *
# producer for endcap SuperClusters including preshower energy
from RecoEcal.EgammaClusterProducers.correctedMulti5x5SuperClus... | nilq/baby-python | python |
# Process PET from worldclim temperature
# Peter Uhe
# 25/3/2019
#
# This script uses python3, set up using conda environment gdal_env2
import os,sys,glob
import gdal
import numpy as np
import datetime,calendar
import netCDF4
sys.path.append('/home/pu17449/gitsrc/PyETo')
import pyeto
inpath = '/home/pu17449/data2/wo... | nilq/baby-python | python |
"""
Created on Wed Nov 7 13:06:08 2018
@author: david
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import PolynomialFeatures
import pandas as pd
#from astropy.convolution import Gaussian2DKernel... | nilq/baby-python | python |
import autodisc as ad
from autodisc.gui.gui import DictTableGUI, BaseFrame
import collections
try:
import tkinter as tk
except:
import Tkinter as tk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
class StatisticTableGUI(DictTableGUI):
@staticmethod
def... | nilq/baby-python | python |
from gf.models.account import Account
from time import time
from uuid import uuid4
import multiprocessing as mp
import gf.lib.db.db_utils as db
#db.get_row_by_id("users", uuid4())
#db.get_row_by_id("shit", uuid4())
Account(id=uuid4(), username= "hello", name="John", email="shit").commit()
quit()
init_id = uuid4()
acc ... | nilq/baby-python | python |
from collections import deque
import json
from kafka import KafkaProducer, KafkaConsumer
from anonymizer import Anonymizer
consumer = KafkaConsumer(bootstrap_servers="localhost:9092", value_deserializer=json.loads)
consumer.subscribe(["unanon"])
producer = KafkaProducer(bootstrap_servers="localhost:9092")
def anony... | nilq/baby-python | python |
import click
import pprint
@click.command()
@click.argument('type', default='all')
@click.option('--check/--no-check', help="Just check (no changes)", default=False)
@click.option('--update/--no-update', help="Update if exists", default=False)
@click.option('--push/--no-push', help="Push update (when specifed wit... | nilq/baby-python | python |
import pytest
import yaml
from utils import utils
class TestConvertReiwaToYear:
@pytest.fixture(scope="function")
def data_fixture(self):
return ((1, 2019), (2, 2020), (3, 2021))
def test_convert(self, data_fixture):
for reiwa, actual in data_fixture:
assert utils.convert_re... | nilq/baby-python | python |
"""
FactSet ESG API
FactSet ESG (powered by FactSet Truvalue Labs) applies machine learning to uncover risks and opportunities from companies' Environmental, Social and Governance (ESG) behavior, which are aggregated and categorized into continuously updated, material ESG scores. The service focuses on company... | nilq/baby-python | python |
#SPDX-License-Identifier: MIT
from augur.application import Application
from augur.augurplugin import AugurPlugin
from augur import logger
class FacadePlugin(AugurPlugin):
"""
This plugin serves as an example as to how to load plugins into Augur
"""
def __init__(self, augur):
self.__f... | nilq/baby-python | python |
from .currencies import Currencies
from .rates import Rates
| nilq/baby-python | python |
import pandas as pd
import numpy as np
import datetime
import time
import requests
from splinter import Browser
from bs4 import BeautifulSoup as bs
from selenium import webdriver
from flask import Flask, render_template
import pymongo
def Scraper():
executable_path = {'executable_path': 'chromedriver.exe'}
... | nilq/baby-python | python |
import os, matplotlib
class FileSaver:
def save_figure(self, selected_month, plt, charttype):
DIR = (selected_month)
CHECK_FOLDER = os.path.isdir(f"output/{DIR}")
# If folder doesn't exist, then create it.
if not CHECK_FOLDER:
os.makedirs(f"output/{DIR}")
plt.s... | nilq/baby-python | python |
from django.apps import AppConfig
class books_repoConfig(AppConfig):
name = 'books_repo'
| nilq/baby-python | python |
import discord
from discord.ext import commands, tasks
import os
import pickle
import config
import asyncio
import typing
import re
import traceback
from enum import Enum
from collections import OrderedDict
import datetime
import pytz
from apiclient import discovery
from google.oauth2 import service_account
class G... | nilq/baby-python | python |
'''
Created on 16 de nov de 2020
@author: klaus
'''
import jsonlines
from folders import DATA_DIR, SUBMISSIONS_DIR
import os
from os import path
import pandas as pd
import numpy as np
import igraph as ig
from input.read_input import read_item_data, get_mappings, NUM_DOMS
from nn import domain_string_identifier
from n... | nilq/baby-python | python |
import sys
import torchvision
import torch
from torch.utils.data import Dataset
from .episodic_dataset import EpisodicDataset, FewShotSampler
import json
import os
import numpy as np
import numpy
import cv2
import pickle as pkl
# Inherit order is important, FewShotDataset constructor is prioritary
class EpisodicTiered... | nilq/baby-python | python |
# Test the difference in computation time between a set of functions that calculate all prime numbers in a given range
import time
import math
import matplotlib.pyplot as plt
# Methods for finding all prime numbers up to max value 'n'
# Slow method using a basic check
def slow_method(n: int) -> list[int]:
results... | nilq/baby-python | python |
from typing import List, Optional
from fastapi.datastructures import UploadFile
from pydantic.main import BaseModel
from enum import Enum
class TextSpan(BaseModel):
text: str
start: int
end: int
class NamedEntity(TextSpan):
label: str # The (predicted) label of the text span
definition: Optiona... | nilq/baby-python | python |
import numpy as np
from sklearn.metrics import confusion_matrix
def test_data_index(true_label,pred_label,class_num):
M = 0
C = np.zeros((class_num+1,class_num+1))
c1 = confusion_matrix(true_label, pred_label)
C[0:class_num,0:class_num] = c1
C[0:class_num,class_num] = np.sum(c1,axis=1)
C[class_num,0:class_num] ... | nilq/baby-python | python |
l=input()
n=len(l)
f=0
prev=0
found=0
for i in range(n-1):
if l[i:i+2]=='AB':
if f==0:
prev=i+1
f=1
else:
continue
elif l[i:i+2]=='BA':
if f==1:
if i!=prev:
found=1
else:
continue
prev=0
f=0
for ... | nilq/baby-python | python |
"""
A Python library for generating Atom feeds for podcasts.
Uses the specification described at
http://www.atomenabled.org/developers/syndication/
"""
from xml.etree import ElementTree as ET
from xml.dom import minidom
import copy
from datetime import datetime, timedelta
from uuid import UUID
def parse_datetime(dt)... | nilq/baby-python | python |
from datetime import timedelta
import json
import sys
import click
from humanize import naturaldelta
from . import __version__
from .click_timedelta import TIME_DELTA
from .watson_overtime import watson_overtime
def _build_work_diff_msg(diff: timedelta) -> str:
msg = f"You are {naturaldelta(diff)} "
if diff... | nilq/baby-python | python |
def dump_locals(lcls):
print('|' + ('='*78) + '|')
print("|Locals:".ljust(79) + '|')
print('|' + ('- -'*(79//3)) + '|')
for (k, v) in lcls.items():
print("| {} => {}".format(k, v).ljust(79) + '|')
print('|' + ('='*78) + '|')
def dump_obj(name, obj):
print('|' + ('='*78) + '|')
pri... | nilq/baby-python | python |
"""
Settings file
You can set the database settings in here at DATABASES['default']
You can also set the supported languages with SUPPORTED_LANGUAGES
Before you launch the site, you should probably set DATABASE password and the SECRET_KEY to something that
is not in a public git repository...
"""
from random i... | nilq/baby-python | python |
# From any external file our program counts the number of lines
# thanks to Stackoverflow
# @program 3
# @author unobatbayar
# @date 03-10-2018
num_lines = sum(1 for line in open('out.txt'))
print(num_lines)
| nilq/baby-python | python |
#!/usr/bin/env python
import requests
import traceback
import sys
from bs4 import BeautifulSoup
import csv
## getHTML
def getHTML():
url = "http://mcc-mnc.com/"
html = ""
try :
r = requests.get(url)
html = r.text.encode("utf-8")
except:
traceback.print_exc()
return htm... | nilq/baby-python | python |
from user import User
from db import Base, Session
from sqlalchemy import *
from sqlalchemy.orm import relation, sessionmaker
from datetime import datetime, date
from attendee import Attendee
from werkzeug.security import generate_password_hash, check_password_hash
from flask import json
from sqlalchemy import exc
from... | nilq/baby-python | python |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.
import random
import time
# Using the Python Device SDK for IoT Hub:
# https://github.com/Azure/azure-iot-sdk-python
# The sample connects to a device-specific MQTT en... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, www.privaz.io Valletech AB
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class ModuleDocFragment(object):
# OpenNebula common documentation
DOCUMENTATION = r'''
options:
api_url:
description:
... | nilq/baby-python | python |
#!/usr/bin/env python3
import os
from electroncash.util import json_decode
from tkinter import filedialog
from tkinter import *
Tk().withdraw()
wallet = filedialog.askopenfilename(initialdir = "~/.electron-cash/wallets",title = "Select wallet")
coins = os.popen("electron-cash -w "+wallet+" listunspent").read()
coin... | nilq/baby-python | python |
from unittest import mock
from django.conf import settings
from django.contrib.auth.models import User
from django.test import Client, TestCase
from .models import Lamp
from .views import LampControlForm
class LoginTests(TestCase):
def setUp(self):
self.client = Client()
def test_login_view(self):... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright © 2018 by IBPort. All rights reserved.
# @Author: Neal Wong
# @Email: ibprnd@gmail.com
from setuptools import setup
setup(
name='scrapy_autoproxy',
version='1.0.0',
description='Machine learning proxy picker',
long_description=open('README.rst').read(),... | nilq/baby-python | python |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | nilq/baby-python | python |
def bin_count(x):
return bin(x).count('1')
def logic(n, m, y):
print(2)
print(n, 1)
if n == 0:
print(1)
print(1)
for i in range(m):
print(-1.0, end=' ')
print(-1.0)
return
for idx in range(n):
for binary in range(m):
if idx ... | nilq/baby-python | python |
import remi.gui as gui
import remi.server
import collections
class DraggableItem(gui.EventSource):
def __init__(self, container, **kwargs):
gui.EventSource.__init__(self)
self.container = container
self.refWidget = None
self.parent = None
self.active = False
self.ori... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'EA.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
... | nilq/baby-python | python |
from flask_appbuilder.security.sqla.apis.permission import PermissionApi # noqa: F401
from flask_appbuilder.security.sqla.apis.permission_view_menu import ( # noqa: F401
PermissionViewMenuApi,
)
from flask_appbuilder.security.sqla.apis.role import RoleApi # noqa: F401
from flask_appbuilder.security.sqla.apis.use... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2013-2016 DNAnexus, Inc.
#
# This file is part of dx-toolkit (DNAnexus platform client libraries).
#
# 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 c... | nilq/baby-python | python |
#
# The XBUILD builder.
#
# (c) 2012 The XTK Developers <dev@goXTK.com>
#
import datetime
import os
import stat
import sys
import subprocess
import config
from _cdash import CDash
from _colors import Colors
from _jsfilefinder import JSFileFinder
from _licenser import Licenser
#
#
#
class Builder( object ):
'''
'... | nilq/baby-python | python |
import logging
from src.backup.datastore.backup_finder import BackupFinder
from src.restore.list.backup_list_restore_service import \
BackupListRestoreRequest, BackupItem, BackupListRestoreService
from src.restore.status.restoration_job_status_service import \
RestorationJobStatusService
class TableRestoreSe... | nilq/baby-python | python |
class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
# 初始化dp[i][j] 当成二维的01背包问题
dp=[[0]*(n+1) for _ in range(m+1)]
for str in strs:
zeroNum = 0
oneNum = 0
#获得每个str下有几个0 和几个1 相当于物品价值
for i in str:
if i ==... | nilq/baby-python | python |
import sys
assert sys.version_info >= (3,9), "This script requires at least Python 3.9"
world = {
"uuid": "1A507EF7-87D8-4EBA-865E-C5D36673C916",
"name": "YELLOWSTONE",
"creator": "Twine",
"creatorVersion": "2.3.14",
"schemaName": "Harlowe 3 to JSON",
"schemaVersion": "0.0.6",
"createdAtMs": 163121052117... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org)
# See: https://docs.python.org/2/library/string.html#format-specification-mini-language
import math
def main():
# "{field_name:format_spec}".format(...)
#
# format_spec ::= [[fill]align][sign][#][0... | nilq/baby-python | python |
import uuid
from yandex_checkout.domain.common.http_verb import HttpVerb
from yandex_checkout.client import ApiClient
from yandex_checkout.domain.request.webhook_request import WebhookRequest
from yandex_checkout.domain.response.webhook_response import WebhookResponse, WebhookList
class Webhook:
base_path = '/w... | nilq/baby-python | python |
from .cache import LRUCache | nilq/baby-python | python |
from kasa_device_manager import KasaDeviceManager
if __name__ == "__main__":
kasa_device_manager = KasaDeviceManager()
# Print all the discovered devices out to the console
devices = kasa_device_manager.get_all_devices()
print(devices)
# Toggle a devices power state
# kasa_device_manager.tog... | nilq/baby-python | python |
import pytest
from dynaconf import LazySettings
from dynaconf.loaders.yaml_loader import load, clean
settings = LazySettings(
NAMESPACE_FOR_DYNACONF='EXAMPLE',
)
YAML = """
# the bellow is just to ensure `,` will not break string YAML
a: "a,b"
example:
password: 99999
host: server.com
port: 8080
service:... | nilq/baby-python | python |
# cls=20, base yolo5
import torch
import torch.nn as nn
import common as C
from torchsummary import summary
class YOLOV4(nn.Module):
def __init__(self):
super(YOLOV4, self).__init__()
self.input = nn.Sequential(
C.Conv(3, 32, 3, 1, mish_act=True),
)
self.group0 = nn.... | nilq/baby-python | python |
import onnxruntime as ort
import numpy as np
from onnxruntime_extensions import get_library_path
# python implementation for results check
def compare(x, y):
"""Comparison helper function for multithresholding.
Gets two values and returns 1.0 if x>=y otherwise 0.0."""
if x >= y:
return 1.0
els... | nilq/baby-python | python |
from itertools import permutations
from pytest import raises
import math
import networkx as nx
from networkx.algorithms.matching import matching_dict_to_set
from networkx.utils import edges_equal
class TestMaxWeightMatching:
"""Unit tests for the
:func:`~networkx.algorithms.matching.max_weight_matching` func... | nilq/baby-python | python |
from unittest import TestCase
from src import utils
class TestGetLoggerName(TestCase):
def test_get_logger_name(self):
logger_name = utils.get_logger_name(self.__class__)
self.assertEqual("TesGetLogNam", logger_name)
class TestGetProxyPort(TestCase):
def test_get_proxy_port(self):
... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2015-08-24 12:46:36
# @Author : LiangJ
import base64
import json
from time import time
import tornado.gen
import tornado.web
from BeautifulSoup import BeautifulSoup
from sqlalchemy.orm.exc import NoResultFound
from tornado.httpclient import HTTP... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 20 11:27:20 2018
@author: DrLC
"""
import pandas
import math
import nltk
import re
import gzip, pickle
import matplotlib.pyplot as plt
def load_csv(path="test.csv"):
return pandas.read_csv(path, header=None)
def load_class(path="classes.t... | nilq/baby-python | python |
import time
import struct
import sys
import os
import re
import threading
from functools import partial
import wx
import wx.lib.newevent as NE
from spidriver import SPIDriver
PingEvent, EVT_PING = NE.NewEvent()
def ping_thr(win):
while True:
wx.PostEvent(win, PingEvent())
time.sleep(1)
class He... | nilq/baby-python | python |
#!/usr/bin/python
"""
To add users and see their passwords
"""
import sqlite3
from passlib.hash import pbkdf2_sha256
conn = sqlite3.connect('DB.db', check_same_thread=False)
c = conn.cursor()
c.execute('''CREATE table if not exists LOGIN(unix real, username TEXT, password TEXT, hash TEXT)''')
print "Opened database... | nilq/baby-python | python |
import datetime
class BaseQuery(object):
supports_rolling = False
supports_isolated_rolling = False
def __init__(self, query_name, client, vars, log):
self.log = log
self.query_name = query_name
self.client = client
self.vars = vars
self.result = None
self.... | nilq/baby-python | python |
import tensorflow as tf
hello = tf.constant('Hello, TF!')
mylist = tf.Variable([3.142,3.201,4.019],tf.float16)
mylist_rank = tf.rank(mylist)
myzeros = tf.zeros([2,2,3])
with tf.compat.v1.Session() as sess:
sess.run(tf.compat.v1.global_variables_initializer())
print(sess.run(myzeros))
print(sess.run(mylist)... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
.. module:: NamedOpetope
:synopsis: Implementation of the named approach for opetopes
.. moduleauthor:: Cédric HT
"""
from copy import deepcopy
from typing import ClassVar, Dict, List, Optional, Set, Tuple, Union
from opetopy.common import *
class Variable:
"""
A variable is... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from flask import Flask # 引入 flask
from flask import redirect
from flask import render_template
from flask import url_for
from flask_cors import CORS
from config import GlobalVar
app = Flask(__name__, template_folder=GlobalVar.BASE_DIR + '/templates') # 实例化一个flask 对象
CORS(app)
... | nilq/baby-python | python |
# Copyright 2013 Red Hat, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
import re
import os
from urllib.parse import urljoin
from datetime import datetime
from bs4 import BeautifulSoup
from ferenda import util
from ferenda import Do... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright 2018 IBM.
#
# 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 agre... | nilq/baby-python | python |
# Generated by Django 3.0.5 on 2020-04-19 04:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('spectroscopy', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='spectrophotometer',
name='produc... | nilq/baby-python | python |
order = [
'artellapipe.tools.outliner.widgets.buttons',
'artellapipe.tools.outliner.widgets.items'
]
| nilq/baby-python | python |
#!/usr/bin/env python
# Copyright 2020 T-Mobile, USA, 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 applicabl... | nilq/baby-python | python |
import re
from urllib.parse import urlsplit
from bs4 import BeautifulSoup
from .base_fetcher import BaseFetcher
def clean_text(tag):
text = tag.find("pre").prettify()[5:-6].replace("<br/>", "\n").replace(u'\xa0', ' ')
# print('text', repr(text), repr(tag.find("pre").get_text()))
return text
... | nilq/baby-python | python |
from mltoolkit.mldp import Pipeline
from mltoolkit.mldp.steps.formatters import PyTorchFormatter
class PyTorchPipeline(Pipeline):
"""
Addresses the issue associated with processes that put PyTorch tensors to a
Queue object must be alive when the main processes gets/requests them from
the Queue. Format... | nilq/baby-python | python |
import os
import sys
sys.path.append('../../')
from dquant.markets._binance_spot_rest import Binance
from dquant.markets._bitfinex_spot_rest import TradingV1
# from dquant.markets._huobi_spot_rest import HuobiRest
from dquant.markets._okex_spot_rest import OkexSpotRest
from dquant.markets.market import Market
from dqua... | nilq/baby-python | python |
# Face.py - module for reading and parsing Scintilla.iface file
# Implemented 2000 by Neil Hodgson neilh@scintilla.org
# Released to the public domain.
# Requires Python 2.5 or later
def sanitiseLine(line):
if line[-1:] == '\n': line = line[:-1]
if line.find("##") != -1:
line = line[:line.find("##")]
line = line.... | nilq/baby-python | python |
from setuptools import setup
from setuptools_rust import RustExtension, Binding
def read(f):
return open(f, encoding='utf-8').read()
setup(
name="PyValico",
version="0.0.2",
author='Simon Knibbs',
license='MIT',
url='https://github.com/s-knibbs/pyvalico',
author_email='simon.knibbs@gmail... | nilq/baby-python | python |
import matplotlib.pyplot as plt
import numpy as np
import csv
markers = {
'heuristic': { 'timestamps': [], 'repl': [], 'repl_err': [], 'cost': [], 'cost_err': [], 'migr': [], 'migr_err': [], 'drop': [], 'drop_err': [], 'effc': [], 'effc_err': [] },
'optimal': { 'timestamps': [], 'repl': [], 'repl_err': [], 'co... | nilq/baby-python | python |
# coding: utf-8
'''
===============================================================================
Sitegen
Author: Karlisson M. Bezerra
E-mail: contact@hacktoon.com
URL: https://github.com/hacktoon/sitegen
License: WTFPL - http://sam.zoy.org/wtfpl/COPYING
=============================================================... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.