content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from sqlalchemy import Integer, String, Column, Float
from api.db.base_class import BaseLayerTable
from geoalchemy2 import Geometry
class CommunityLocations(BaseLayerTable):
"""
https://catalogue.data.gov.bc.ca/dataset/first-nation-community-locations
"""
__tablename__ = 'fn_community_locations'
... | nilq/baby-python | python |
import csv
def find_labels(xmap, contig_start_label, contig_end_label, contig_orientation):
"""
this does not account for split mapped molecules
i.e., assumes one molecule ID per line in XMAP
fix later
"""
# swap if -:
#print(contig_start_label, contig_end_label)
if contig_orientation == "-":
conti... | nilq/baby-python | python |
####################
# Gui V3 16 Sept. 2017 Malacophonous
#####################
'''
API for Gui v3
guiAPP
guiWIN
guiWID
'''
from buildingblocks import guiRectangle,guiLines
import random as r
class Widget():
def __init__(self,_x,_y,_w,_h):
self.x = _x
self.y = _y
... | nilq/baby-python | python |
# coding: utf-8
# ======================================================================
# DZI-IIIF
# DeepZoom(dzi)形式のファイルをIIIF Image APIでアクセスできるようにする
# ======================================================================
# 2020-05-21 Ver.0.1: Initial Version, No info.json handling.
# 2020-05-22 Ver.0.2: Add info.js... | nilq/baby-python | python |
# Returns the upper triangular part of a matrix (2-D tensor)
# torch.triu(input, diagonal=0, *, out=None) → Tensor
# The argument 'diagonal' controls which diagonal to consider.
import torch
source_tensor = torch.ones((10, 10))
# print(source_tensor)
tensor = (torch.triu(source_tensor) == 1).transpose(0, 1)
print(te... | nilq/baby-python | python |
import cant_utils as cu
import numpy as np
import matplotlib.pyplot as plt
import glob
import bead_util as bu
import tkinter
import tkinter.filedialog
import os, sys
from scipy.optimize import curve_fit
import bead_util as bu
from scipy.optimize import minimize_scalar as minimize
import pickle as pickle
import time
#... | nilq/baby-python | python |
import logging
import time
import cv2 as cv
import numpy as np
from scipy.sparse import lil_matrix
from scipy.optimize import least_squares
def project(points, camera_params, K, dist=np.array([])):
"""
Project 2D points using given camera parameters (R matrix and t vector), intrinsic matrix,
... | nilq/baby-python | python |
# Copyright (c) 2010-2019 openpyxl
import pytest
from openpyxl.xml.functions import fromstring, tostring
from openpyxl.tests.helper import compare_xml
@pytest.fixture
def Marker():
from ..marker import Marker
return Marker
class TestMarker:
def test_ctor(self, Marker):
marker = Marker(symbol=N... | nilq/baby-python | python |
from telegram import InlineKeyboardButton
def generate_buttons(labels):
buttons = [[InlineKeyboardButton(labels[0], callback_data=labels[0]),
InlineKeyboardButton(labels[1], callback_data=labels[1])],
[InlineKeyboardButton(labels[2], callback_data=labels[2]),
Inline... | nilq/baby-python | python |
import base64
from authlib.common.encoding import to_bytes, to_unicode
import fence.utils
def create_basic_header(username, password):
"""
Create an authorization header from the username and password according to
RFC 2617 (https://tools.ietf.org/html/rfc2617).
Use this to send client credentials i... | nilq/baby-python | python |
# ywo queue to stack
import queue
class ArrayQueue(object):
def __init__(self):
self.queue1 = queue.Queue(5)
self.help = queue.Queue(5)
def push(self, data):
"""模仿压栈"""
if self.queue1.full() == True:
raise RuntimeError('the stack is full')
self.queue1.put(... | nilq/baby-python | python |
'''
Written by Jinsung Yoon
Date: Jul 9th 2018 (Revised Oct 19th 2018)
Generative Adversarial Imputation Networks (GAIN) Implementation on MNIST
Reference: J. Yoon, J. Jordon, M. van der Schaar, "GAIN: Missing Data Imputation using Generative Adversarial Nets," ICML, 2018.
Paper Link: http://medianetlab.ee.ucla.edu/pap... | nilq/baby-python | python |
import datetime
import names
from django.contrib.auth import get_user_model
from usersetting.models import UserSetting
User = get_user_model()
def initialize_usersetting(email):
while(True):
try:
nickname = names.get_first_name()
UserSetting.objects.get(nickname=nickname)
e... | nilq/baby-python | python |
import numpy as np
import pandas as pd
def create_rolling_ts(
input_data,
lookback=5,
return_target=True,
apply_datefeatures=True,
return_np_array=False
):
"""
Make flat data by using pd.concat instead, pd.concat([df1, df2]).
Slow function.
Save data as preprocessed?
"""
... | nilq/baby-python | python |
import time
def merge(data, low, high, middle, drawData, timetick):
color=[]
for i in range (len(data)):
color.append('sky blue')
left = data[low:middle+1]
right = data[middle+1:high+1]
i = 0
j = 0
for k in range(low, high+1):
if i< len(left) and j<len(right):
... | nilq/baby-python | python |
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
from pyrogram import Client, emoji
from datetime import datetime, timedelta
from shamil.voicechat import mp
@Client.on_callback_query()
async def cb_handler(client: Client, query: CallbackQuery):
if query.data == "replay":
... | nilq/baby-python | python |
#!/usr/bin/env python
import yaml
import json
def main():
my_list = range(8)
my_list.append('0 through 7 are cool numbers')
my_list.append({})
my_list[-1]['subnet_mask'] = '255.255.255.0'
my_list[-1]['gateway'] = '192.168.1.1'
with open("first_yaml_file.yml", "w") as f:
f.write(yaml.... | nilq/baby-python | python |
import os
import glob
import sys
class CAPSProfile:
def __init__(self):
self.streams = [] # List of strings, e.g. XY.ABCD.*.*
self.stations = [] # List of network, station tuples, e.g. (XY,ABCD)
self.oldStates = [] # Content of old state file
'''
Plugin handler for the CAPS plugin.
'''
... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import time
import xlrd
from public import saveScreenshot
from core import LoginPage
from test import support
from public.log import logger
from public.pyse import Pyse
class LoginTest(unittest.TestCase):
def setUp(self):
self.driver = Pyse("ch... | nilq/baby-python | python |
import os
import pprint
import random
import collections
from ai_list_common import (
ListInterface,
ListBase,
ListTypeNgram,
TestRunnerCheckNgram,
)
class NgramList(ListTypeNgram, ListBase, ListInterface):
def check_num_of_gram(self, num_of_gram):
if super().check_num_of_gram(num_of_gram)... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import six
from aiida import orm
from aiida.common.lang import classproperty
from aiida.plugins import factories
from aiida_quantumespresso.calculations import BasePwCpInputGenerator
class PwCalculation(BasePwCpInputGenerator):
"""`CalcJob... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from com.pnfsoftware.jeb.client.api import IClientContext
from com.pnfsoftware.jeb.core import IRuntimeProject
from com.pnfsoftware.jeb.core.units import IUnit
from com.pnfsoftware.jeb.core.units.code import IDecompilerUnit, DecompilationOptions, DecompilationContext
from com.pnfsoftware.jeb.cor... | nilq/baby-python | python |
#!/usr/bin/env python
#
# ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University of Chicago
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://ge... | nilq/baby-python | python |
# coding=utf-8
import sys
from enum import Enum
from typing import List
class VarType(Enum):
INVALID = -1
EXIT = 0
OPERATION = 1
CONDITION = 2
SUBROUTINE = 3
START = 4
END = 5
SELECTED = 6 # 包含选择的条件语句 即yes分支或者no分支
class ConnectType(Enum):
NONE = 0,
NORMAL = 1,
YSE = 2,
... | nilq/baby-python | python |
def lcm(*values):
values = set([abs(int(v)) for v in values])
if values and 0 not in values:
n = n0 = max(values)
values.remove(n)
while any( n % m for m in values ):
n += n0
return n
return 0
lcm(-6, 14)
42
lcm(2, 0)
0
lcm(12, 18)
36
lcm(12, 18, 22)
396
| nilq/baby-python | python |
from GTDLambda import *
from TileCoder import *
import numpy
class DirectStepsToLeftDemon(GTDLambda):
def __init__(self, featureVectorLength, alpha):
GTDLambda.__init__(self, featureVectorLength, alpha)
def gamma(self, state, observation):
encoder = observation['encoder']
if (encoder ... | nilq/baby-python | python |
import os
import numpy as np
from tqdm import tqdm
from PIL import Image
from imagededup.methods import PHash
def run(root: str):
phasher = PHash()
img = Image.open("/home/huakun/datasets/meinv/anime/IMG_0903.PNG")
size = np.asarray(img.size)
scale = 0.1
new_size = (size * scale).astype(int)
i... | nilq/baby-python | python |
#!python
"""
Keras implementation of CapsNet in Hinton's paper Dynamic Routing Between Capsules.
The current version maybe only works for TensorFlow backend. Actually it will be straightforward to re-write to TF code.
Adopting to other backends should be easy, but I have not tested this.
Usage:
python capsulen... | nilq/baby-python | python |
# Copyright 2016 The TensorFlow Authors. 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 applica... | nilq/baby-python | python |
import configparser
import collections
import os
import json
import copy
from .utils import parse_timedelta
from .scrape import get_all_scrapers
import argparse
# Configuration handling
class AltJobOptions(collections.UserDict):
"""
Wrap argparse and configparser objects into one configuration dict object
... | nilq/baby-python | python |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from multi_var_gradient_decent import LinearRegressionUsingGD
from mpl_toolkits.mplot3d import axes3d
from sklearn.metrics import mean_squared_error, r2_score
def create_mesh_grid(start, end):
theta_1 = np.linspace(start, end, 30)
th... | nilq/baby-python | python |
import mxnet as mx
import utils
from model_utils import validate_model
from gluon_zoo import save_mobilenet1_0
from from_tensorflow import tf_dump_model
from os import path
def test_tf_resnet50_v1():
sym_path = "./data/tf_resnet50_v1.json"
prm_path = "./data/tf_resnet50_v1.params"
# if not path.exists(sy... | nilq/baby-python | python |
import click
import reader
from reader._cli import setup_logging
def make_add_response_headers_middleware(wsgi_app, headers):
def wsgi_app_wrapper(environ, start_response):
def start_response_wrapper(status, response_headers, exc_info=None):
response_headers.extend(headers)
return... | nilq/baby-python | python |
from collections import defaultdict
"""
Block
"""
class Block:
def __init__(self, author, round, payload, qc, id, txn_id):
self.author = author
self.round = round
self.payload = payload
self.qc = qc
self.id = id
self.txn_id = txn_id
self.children = []
... | nilq/baby-python | python |
try:
from webdriver_manager.chrome import ChromeDriverManager
except: raise ImportError("'webdriver-manager' package not installed")
try:
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
except: raise ImportError("'selenium' package not installed")
from bs4 import BeautifulSoup... | nilq/baby-python | python |
import requests
user = 'alexey'
password = 'styagaylo'
base_url = 'http://httpbin.org/'
def test_my_first_api():
r = requests.post(base_url + 'post', data={'user': user, 'password': password})
assert r.status_code == 200, "Unexpected status code: {}".format(r.status_code)
assert r.json()['url'] == base_ur... | nilq/baby-python | python |
import plotly.graph_objects as go
import dash
import dash_core_components as dcc
import dash_html_components as html
from matplotlib import pylab
import matplotlib.pyplot as plt
import networkx as nx
# read results from the file
docs = eval(open('final_out_dupe_detect.txt', 'r').read())
final_docs = [[i[0], list(set(... | nilq/baby-python | python |
import re
import os
import math
import subprocess
from MadGraphControl.MadGraphUtils import *
nevents = 10000
mode = 0
mass=0.500000e+03
channel="mumu"
gsmuL=-1
gseL=-1
gbmuL=-1
gbeL=-1
JOname = runArgs.jobConfig[0]
matches = re.search("M([0-9]+).*\.py", JOname)
if matches is None:
raise RuntimeError("Cannot fi... | nilq/baby-python | python |
# coding: utf-8
import sys
import utils
# python .github/workflows/scripts/override_version.py example/tools/analyzer_plugin/pubspec.yaml 1.1.0
pubspec_yaml = sys.argv[1]
version = sys.argv[2]
utils.override_version(pubspec_yaml, version) | nilq/baby-python | python |
"""Define a version number for turboPy"""
VERSION = ('2020', '10', '14')
__version__ = '.'.join(map(str, VERSION))
| nilq/baby-python | python |
from django.db import models
# Create your models here.
class TimeStampedModel(models.Model):
created_at = models.DateTimeField(_(""), auto_now=False, auto_now_add=True)
updated_at = models.DateTimeField(_(""), auto_now=True, auto_now_add=False)
class Meta:
abstract = True
class Image(TimeStampe... | nilq/baby-python | python |
#
# Copyright 2018 Jaroslav Chmurny
#
#
# This file is part of Python Sudoku Sandbox.
#
# Python Sudoku Sandbox is free software developed for educational and
# experimental purposes. It is licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with the
# Licens... | nilq/baby-python | python |
# _ __
# | |/ /___ ___ _ __ ___ _ _ ®
# | ' </ -_) -_) '_ \/ -_) '_|
# |_|\_\___\___| .__/\___|_|
# |_|
#
# Keeper Commander
# Copyright 2022 Keeper Security Inc.
# Contact: ops@keepersecurity.com
#
import abc
import json
import logging
from typing import Optional, List, Set, Tuple
from google.protobu... | nilq/baby-python | python |
"""
Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.
Example:
Input:
[1,2,3]
Output:
3
Explanation:
Only three moves are needed (remember each move increments two elements):
[1,2,3] =>... | nilq/baby-python | python |
from __future__ import annotations
import os
import warnings
from datetime import datetime
from pathlib import Path
from typing import (
Any,
Dict,
List,
Optional,
Tuple,
Union,
Sequence,
Iterable,
)
import pydantic
from .managers import ManagerQueryBody, ComputeManager
from .metadata... | nilq/baby-python | python |
import sys
import jinja2
import tdclient
import tdclient.version
from .version import __version__
import logging
logger = logging.getLogger(__name__)
class Context(object):
'''High-level wrapper for tdclient.Client.'''
def __init__(self, module=None, config=None):
if config is None:
conf... | nilq/baby-python | python |
import agama
mass_unit = (1.0/4.3)*(10.0**(6.0))
agama.setUnits(mass=mass_unit, length=1, velocity=1)
pot = agama.Potential(type='Spheroid', gamma=1.0, beta=3.1, scaleRadius=2.5, outerCutoffRadius=15.0)
df = agama.DistributionFunction(type='QuasiSpherical',potential=pot)
model = agama.GalaxyModel(pot,df)
M = model.s... | nilq/baby-python | python |
# Developed for the LSST System Integration, Test and Commissioning Team.
# This product includes software developed by the LSST Project
# (http://www.lsst.org).
# See the LICENSE file at the top-level directory of this distribution
# for details of code ownership.
#
# Use of this source code is governed by a 3-clause ... | nilq/baby-python | python |
# Import the toolkit specific version.
from pyface.toolkit import toolkit_object
TaskWindowBackend = toolkit_object(
'tasks.task_window_backend:TaskWindowBackend')
| nilq/baby-python | python |
# Based on
# https://www.paraview.org/Wiki/Python_Programmable_Filter#Generating_Data_.28Programmable_Source.29
#This script generates a helix curve.
#This is intended as the script of a 'Programmable Source'
def _helix(self, numPts):
import math
#numPts = 80 # Points along Helix
length = 8.0 # Length of Hel... | nilq/baby-python | python |
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth import authenticate, login, logout
from Propylaea.forms import LoginForm, SignUpForm
from django.template import loader
from django.contrib.auth.decorators import login_required
de... | nilq/baby-python | python |
#!/usr/bin/env python
import numpy as np
import h5py as h
import matplotlib
import matplotlib.pyplot as plt
import sys, os, re, shutil, subprocess, time
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-f", "--file", action="store", type="string", dest="inputFile", help="Input H5 file with... | nilq/baby-python | python |
import numpy as np
import math
# from mxnet import nd
from mxnet.gluon import nn
class Augmentation(nn.HybridBlock):
def __init__(self, angle_range, zoom_range, translation_range, target_shape, orig_shape, batch_size,
aspect_range = None, relative_angle = 0, relative_scale = (1, 1), relative_translation = 0):
sup... | nilq/baby-python | python |
from __future__ import absolute_import
import os
import sys
import pytest
from collections import defaultdict
myPath = os.path.abspath(os.getcwd())
sys.path.insert(0, myPath)
from salt.exceptions import ArgumentValueError
import hubblestack.extmods.fdg.process
class TestProcess():
"""
Class used to test th... | nilq/baby-python | python |
from pprint import pprint
def sort_with_index(arr):
arr_with_index = []
for i, item in enumerate(arr):
arr_with_index.append((i, item))
arr_with_index.sort(key=lambda it: -it[1])
return arr_with_index
def assign(jobs_with_index, n_not_fulfilled_jobs, n_machines):
assignment = {}
assi... | nilq/baby-python | python |
'''
Copyright 2022 Airbus SAS
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, sof... | nilq/baby-python | python |
#!python
"""
ANNOTATE FUNCTIONS WITH TIME AND SPACE COMPLEXITY!!!!!
"""
def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
return linear_search_iterative(array, item)
# return linear_search_recursive(array, item)
def linear_search_iterative(ar... | nilq/baby-python | python |
import json
import sys
import os
from time import sleep
import wxpy
class Greeting:
def __init__(self, name, puid, greeting='{name}新年快乐!狗年大吉!'):
self.name = name
self.puid = puid
self._greeting = greeting
def toJSON(self):
# return str(self.__dict__)
return json.d... | nilq/baby-python | python |
# ----------------------------------------------------------------------
# |
# | CentOsShell.py
# |
# | David Brownell <db@DavidBrownell.com>
# | 2019-08-30 19:25:23
# |
# ----------------------------------------------------------------------
# |
# | Copyright David Brownell 2019-22.
# | Distributed ... | nilq/baby-python | python |
class ReasonCode:
"""Default server reason codes."""
# General error
GENERAL_ERROR = 1
# General session error
SESSION_ERROR = 11
# The session resource is already registered
SESSION_REGISTRATION_ERROR = 12
# An authentication error occurred
SESSION_AUTHENTICATION_FAILED = 13
# ... | nilq/baby-python | python |
from django.db import models
from subscribers import mailchimp
class AbstractSubscriber(models.Model):
email = models.EmailField(blank=True, null=True)
created_on = models.DateField(auto_now_add=True)
objects = models.Manager()
class Meta:
abstract = True
def __str__(self):
retur... | nilq/baby-python | python |
from possum import *
spec = possum()
spec._generateParams(N=30000, fluxMin=0.1, noiseMax=0.2, pcomplex=0.5, seed=923743)
spec._simulateNspec(save=True, dir='data/train/V2/', timeit=True)
| nilq/baby-python | python |
from django.db import models
from djangae.tasks.deferred import defer
from djangae.test import TestCase, TaskFailedError
def test_task(*args, **kwargs):
pass
def assert_cache_wiped(instance):
field = DeferModelA._meta.get_field("b")
assert(field.get_cached_value(instance, None) is None)
class DeferMod... | nilq/baby-python | python |
# Copyright 2019 Google LLC. 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 applicable law or a... | nilq/baby-python | python |
"""
MSX SDK
MSX SDK client. # noqa: E501
The version of the OpenAPI document: 1.0.9
Generated by: https://openapi-generator.tech
"""
import unittest
import python_msx_sdk
from python_msx_sdk.api.workflow_events_api import WorkflowEventsApi # noqa: E501
class TestWorkflowEventsApi(unittest.TestC... | nilq/baby-python | python |
# coding: utf-8
__author__ = 'Paul Cunningham'
__email__ = 'pjcunningham@borsuk.co.uk'
__copyright = 'Copyright 2017, Paul Cunningham'
__license__ = 'MIT License'
__version__ = '0.1'
from .select2 import Select2
| nilq/baby-python | python |
import numpy as np
import pandas as pd
returns = prices.pct_change()
returns.dropna()
returns.std()
deviations = (returns - returns.mean())**2
squared_deviations = deviations ** 2
variance = squared_deviations.mean()
volatility = np.sqrt(variance)
me_m = pd.read_csv('./Data/Portfolios_Formed_on_ME_monthly_EW.csv',... | nilq/baby-python | python |
import logging
from django.contrib.auth.backends import (
RemoteUserBackend,
get_user_model,
)
from django.contrib.auth.models import (
Group,
)
from django.utils.translation import ugettext as _
from rest_framework import exceptions
from rest_framework_auth0.settings import (
auth0_api_settings,
)
fro... | nilq/baby-python | python |
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectUD import DistributedObjectUD
class AccountUD(DistributedObjectUD):
notify = DirectNotifyGlobal.directNotify.newCategory("AccountUD")
| nilq/baby-python | python |
from turtle import color
import matplotlib.pyplot as plt
from matplotlib import patches
import numpy as np
import math
th = np.linspace(0, 2*np.pi, 1000)
r=1
c=r*np.cos(th)
d=r*np.sin(th)
figure, axes = plt.subplots(1)
axes.plot(c,d)
axes.set_aspect(1)
plt.title("sensor position")
plt.plot(1,0,'o',color="blue",)
plt... | nilq/baby-python | python |
#!/usr/bin/python3
import itertools
import os
import re
_RE_INCLUDE = re.compile('#include ([<"])([^"<>]+)')
_LIB_BY_HEADER = {
'curl/curl.h': 'curl',
're2/re2.h': 're2',
'sqlite3.h': 'sqlite3',
}
def dfs(root, get_children):
todo = [root]
visited = {id(root)}
while todo:
item = todo.pop()
yiel... | nilq/baby-python | python |
from django.contrib import admin
from django.urls import path
from .views import IndexClassView, index
urlpatterns = [
path("", index, name="home"),
path(
"class", IndexClassView.as_view(template_name="index.html"), name="home_class"
),
path(
"class2",
IndexClassView.as_view(te... | nilq/baby-python | python |
# -*- coding:utf-8 -*-
from __future__ import print_function
import math
import numpy as np
import os
import sys
sys.path.insert(0, '../facealign')
sys.path.insert(0, '../util')
from caffe_extractor import CaffeExtractor
def model_centerface(do_mirror):
model_dir = './models/centerface/'
model_proto = mod... | nilq/baby-python | python |
from raytracer.tuple import (
tuple,
point,
vector,
magnitude,
normalize,
dot,
cross,
reflect,
Color,
)
from raytracer.rays import Ray
from raytracer.spheres import Sphere
from raytracer.intersections import Intersection, intersections, hit, prepare_computations
from raytracer.lights... | nilq/baby-python | python |
import os
import pathlib
import urllib
import bs4
from .subsearcher import HTMLSubSearcher, SubInfo
class SubHDSubSearcher(HTMLSubSearcher):
"""SubHD 字幕搜索器(https://subhd.tv)"""
SUPPORT_LANGUAGES = ['zh_chs', 'zh_cht', 'en', 'zh_en']
SUPPORT_EXTS = ['ass', 'srt']
API_URL = 'https://subhd.tv/search/'
... | nilq/baby-python | python |
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import pickle
class MyContainer(object):
def __init__(self, data):
self._data = data
def get_data(self):
return self._data
d1 = MyContainer([2, 5, 4, 3, [ 12, 3, 5 ], 32, { 'a': 12, 'b': 43}])
with open('/tmp/pickle_data.dat', "wb") as f:
... | nilq/baby-python | python |
import os
import urllib
import elasticsearch
import elasticsearch_dsl
import es2json.helperscripts as helperscripts
class ESGenerator:
"""
Main generator Object where other Generators inherit from
"""
def __init__(self, host='localhost',
port=9200,
es=None,
... | nilq/baby-python | python |
from copy import deepcopy
from sqlalchemy import (
Table,
Column,
Integer,
String,
DateTime,
UniqueConstraint,
DECIMAL,
LargeBinary,
Boolean,
ForeignKey,
PrimaryKeyConstraint,
)
from wt.common import Currency
from wt.entities.deliverables import DeliverableStatus
from wt.id... | nilq/baby-python | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2019 ckitagawa <ckitagawa@edu.uwaterloo.ca>
#
# Distributed under terms of the MIT license.
import logging
import threading
import serial
import serial.tools.list_ports
import fiber_reading
from collections import deque
def select_devic... | nilq/baby-python | python |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from typing import Dict, List, Optional, Tuple
from django.conf import settings
from rest_framework import serializers
from backend.components import bk_repo
from backend.helm.helm.models.chart import Chart, ChartVersion, ChartVersionSnapshot
def get_chart_version(
project_name: str, rep... | nilq/baby-python | python |
import os
from collections import OrderedDict
from coverage_checker.utils import get_all_path_combinations
def test_get_all_path_combinations():
facets = OrderedDict([('a', ['1', '2']), ('b', ['3', '4']), ('c', ['5', '6'])])
all_paths = get_all_path_combinations(facets)
expected_result = ['1/3/5', '... | nilq/baby-python | python |
import re
from math import sqrt, atan2
if __name__ == "__main__":
"""
This script file demonstrates how to transform raw CSI out from the ESP32 into CSI-amplitude and CSI-phase.
"""
FILE_NAME = "./example_csi.csv"
f = open(FILE_NAME)
for j, l in enumerate(f.readlines()):
imaginary = ... | nilq/baby-python | python |
# Recording video to a file
# https://picamera.readthedocs.io/en/release-1.13/recipes1.html#recording-video-to-a-file
import picamera
camera = picamera.PiCamera()
camera.resolution = (640, 480)
camera.start_recording('output/07_video.h264')
camera.wait_recording(5)
camera.stop_recording() | nilq/baby-python | python |
# Copyright 2015 Google 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 applicable law or ... | nilq/baby-python | python |
# -----------------------------------------------------------------------------
# Copyright (c) 2013-2022, NeXpy Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING, distributed with this software.
# -------------------------------------------------... | nilq/baby-python | python |
import os
import sys
from PIL import Image
import glob
import numpy as np
import h5py
import csv
import time
import zipfile
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
try:
from urllib.request import urlretrieve
except ImportError:
from urllib import urlretrieve
def reporth... | nilq/baby-python | python |
import sys
# Expose the public API.
from ehrpreper.api import *
# Check major python version
if sys.version_info[0] < 3:
raise Exception("Ehrpreper does not support Python 2. Please upgrade to Python 3.")
# Check minor python version
elif sys.version_info[1] < 6:
raise Exception(
"Ehrpreper only suppo... | nilq/baby-python | python |
__author__ ='Jacques Saraydaryan'
class ColorRange():
min_H=0
max_H=0
label=''
def getColor(self,minH,maxH,label):
self.min_H=minH
self.max_H=maxH
self.label=label
| nilq/baby-python | python |
#! /usr/bin/env python
import rospy, std_msgs.msg
from sensor_msgs.msg import Temperature
pub = rospy.Publisher('henri/temp_average', Temperature, queue_size=10)
average = 0
variance = 0
def callback(data):
global average, variance, pub
rospy.loginfo('Temperature Received: %f', data.temperature)
average =... | nilq/baby-python | python |
from flask import Flask
from config import config_options
from flask_sqlalchemy import SQLAlchemy
from flask_uploads import UploadSet,configure_uploads,IMAGES
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_bootstrap import Bootstrap
from flask_simplemde import SimpleMDE
from flask_mail ... | nilq/baby-python | python |
# import numpy as np
# import matplotlib.pyplot as plt
# import cv2
# img = cv2.imread('8.jpeg',0)
# dft = cv2.dft(np.float32(img),flags = cv2.DFT_COMPLEX_OUTPUT)
# dft_shift = np.fft.fftshift(dft)
# magnitude_spectrum = 20*np.log(cv2.magnitude(dft_shift[:,:,0],dft_shift[:,:,1]))
# plt.subplot(121),plt.imshow... | nilq/baby-python | python |
from flask import json, render_template, g, abort
from flask_login import current_user, login_required
import urllib, json
from thanados import app
from thanados.models.entity import Data
@app.route('/vocabulary/')
def vocabulary():
hierarchytypes = app.config["HIERARCHY_TYPES"]
systemtypes = app.config["SY... | nilq/baby-python | python |
# TensorFlow and tf.keras
import tensorflow as tf
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
# Display the image, labeled with the predicted label (blue if accurate to true label, red if not)
def plot_image(i, predictions_array, true_label, img):
true_label, img = true_label[i], img[i]
... | nilq/baby-python | python |
import os
import os.path as osp
import torch
from torch.utils.data import Dataset
from torch.utils.data.dataloader import default_collate
from torchvision.transforms import functional as F
import numpy as np
import numpy.linalg as LA
import cv2
import json
import csv
import matplotlib.pyplot as plt
from pylsd import ... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: mcxiaoke
# @Date: 2015-07-10 14:13:05
import os
import sys
from os import path
import re
import tempfile
import shutil
import time
'''
clean idea project files
param: max_depth -> max depth for recursively, default=3
param: permanently -> move to ... | nilq/baby-python | python |
import os
from .handler import QuickOpenHandler
from ._version import get_versions
from notebook.utils import url_path_join
__version__ = get_versions()['version']
del get_versions
def _jupyter_server_extension_paths():
"""Defines the entrypoint for the Jupyter server extension."""
return [{
"modul... | nilq/baby-python | python |
from abc import ABC
from typing import Type
from bokeh.models.glyph import Glyph
from bokeh.models.renderers import GlyphRenderer
from xbokeh.common.assertions import assert_type
class Renderer(ABC):
def __init__(self, type_: Type, renderer: GlyphRenderer) -> None:
"""
:renderer: instance of Gly... | nilq/baby-python | python |
from math import log
from utils import iter_primes
__author__ = 'rafa'
def algorithm(limit):
n = 1
for p in iter_primes():
if p > limit:
return n
exponent = int(log(limit, p))
n *= p**exponent
def solver():
"""
2520 is the smallest number that can be divided by e... | nilq/baby-python | python |
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
def plot_time_series(x: np.ndarray, title=None) -> None:
sns.set(font_scale=1.5)
sns.set_style("white")
t = np.arange(start=0, stop=x.shape[0])
plt.plot(t, x, linestyle='-', marker='o')
plt.title(title)
plt.xlabel(r'$t$')... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.