content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
from wagtailmedia import __version__
import io
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
# Testing dependencies
testing_extras = [
# Required for running the tests
'mock>=1.0.0',
# For coverage and PEP8 linting
... |
import regex
from reactTypes import *
from parser.useRegex import useRegex, applyType
from typing import Tuple
REGEXP = {
"HTML": regex.compile(r'(<(?:[^)(]+|(?1))>)', regex.MULTILINE)
}
def sortFunctionTypes(functions: list) -> Tuple[list, list]:
"""
sortFunctionTypes(): separate classic functions from f... |
data_within_protected = geopandas.sjoin(data_utm, protected_areas_utm[['NAME_AP', 'geometry']],
op='within', how='inner') |
#
# Tests for the `osbuild.util.rmrf` module.
#
import os
import pathlib
import shutil
import subprocess
import tempfile
import unittest
from osbuild.util import rmrf
from .. import test
class TestUtilLinux(unittest.TestCase):
@unittest.skipUnless(test.TestBase.can_modify_immutable("/var/tmp"), "root-only")
... |
def test_repository_test_details(
client, default_login, default_testcase, default_repo, default_repo_access
):
resp = client.get(
"/api/repos/{}/tests/{}".format(
default_repo.get_full_name(), default_testcase.hash
)
)
assert resp.status_code == 200
data = resp.json()
... |
from procedure.generic import Generic
import api.api_docker as docker
import api.api_podman as podman
import api.api_lxd as lxc
import api.api_contingious as contingious
class DatabaseRead(Generic):
def __init__(self, size='xl'):
super().__init__()
if size not in ['xs', 'sm', 'md', 'lg', 'xl']:
... |
SECRET_KEY = 'super secret key' # change this
# Database settings
DB_USERNAME = 'username' # change this
DB_PASSWORD = 'password' # change this
DB_HOST = 'localhost' # change this
DB_NAME = 'qldf'
DB_PORT = 5432 # change this, usually 5432 or 5433
SQLALCHEMY_DATABASE_URI = 'postgresql://{}:{}@{}/{}'.format(DB_USE... |
import sys
sys.path.append("../")
from kaleidoscope import util
import os
if __name__ == '__main__':
print util.get_shell_output('/Users/wjielai/Workspace/QCloudAndroid/library/TencentAppCloud',
'./gradlew :foundation:properties | grep projectDir') |
"""
@author: David Lei
@since: 28/08/2016
@modified:
ReTRIEval tree = Trie
Tree data structure (reTRIEval tree)
- used to store collections of strings
- if 2 strings have a common prefix, will have a same ancestor in this tree
- idea for dictionaries, less space compared to hashtable
a.k.a digital tree, radix tree,... |
from unittest.util import _MAX_LENGTH
from rest_framework import serializers
from jquery.models import Username
class UsernameSerializer(serializers.ModelSerializer):
class Meta:
model = Username
fields = '__all__' |
import unittest
from length_of_longest_substring.solution import Solution
class LengthOfLongestSubstringTest(unittest.TestCase):
def test_length_of_longest_substring(self):
s = Solution()
string1 = 'bbbbba'
len = s.lengthOfLongestSubstring(string1)
self.assertEqual(2, len)
... |
"""
Abstract models to be included in other apps
"""
# Ignore pylint problems with Meta-classes
# pylint: disable=missing-docstring,too-few-public-methods
from datetime import datetime
from django.db import models
from django.conf import settings
from django.contrib.sites.models import Site
from image_cropping.fields i... |
from Spiders_.scrapy_me.core.spider import Spider
from Spiders_.scrapy_me.http.request import Request
import time
# 继承框架的爬虫基类
class BaiduSpider(Spider):
name = 'baidu'
start_urls = ['http://www.baidu.com']
total = 0
def parse(self, response):
self.total += 1
if self.total > 10:
... |
#!/usr/bin/env python
# LuMP_Pulsar_Cleanup.py
# clean up LuMP data header information
#_HIST DATE NAME PLACE INFO
# 2011 Sep 11 James M Anderson --MPIfR start
# 2012 Apr 20 JMA --update for modulal setup
# 2013 Jul 24 JMA ---- updates for LuMP v2.0
# 2013 Aug 12 JMA ---- file list file name change to _lis
# ... |
# can be imported from the labs directory
import numpy
def filter_banks(pow_frames, sample_rate, nfilt = 40, NFFT=512):
"""calculate filter banks.
Args:
pow_frames (np.array): frames of the power spectrum, one frame per row
sample_rate (numerical): sampling frequency
nfilt (numerical)... |
import re
import pytz
from django.db import transaction, IntegrityError
from django.utils import timezone
from django.core.exceptions import ValidationError
from django.conf import settings
from ledger.settings_base import TIME_ZONE
from preserialize.serialize import serialize
from ledger.accounts.models import EmailU... |
#!/usr/bin/env python
from raspyrfm import *
d = rfmbase.RfmBase.scan()
if len(d) == 0:
print("Unable to open SPI. Check if SPI is enabled!")
exit
for i in range(len(d)):
line = "Module #" + str(i + 1) + " on CS " + str(i) + ": "
if d[i] == None:
print(line + "No module found")
continue
elif d[i] == 0x24:
... |
import numpy as np
from danmaku import *
from moviepy.editor import *
class DanmakuClip(object):
def __init__(self, danmaku, timestamp):
self.danmaku = danmaku
self.speed = 0
self.comm_clip = None
self.tran_clip = None
self.timestamp = timestamp
self.duration = 0
self.w = 0
self.h = 0
self.pos_h = ... |
class session:
__instance = None
__user_code = None
__user_name = None
__user_type = None
@staticmethod
def get_instance():
if(session.__instance == None):
session()
return session.__instance
def __init__(self):
if(session.__instance != None):
raise Exception(... |
#!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK
import argparse
import configparser
import json
import logging
import argcomplete
from las import Client, Credentials
from las.credentials import MissingCredentials, read_from_file
from .util import NotProvided
from .parser import (
create_app_clients_parser,
cre... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from voxolab.sphinx import Sphinx
from voxolab import convert
def ctm_to_xml(ctm_file, recasing_path = "/home/vjousse/usr/fac/decodeur/majAuto", recase = False):
convert.recase_ctm(ctm_file, ctm_file_maj, recasing_path)
s.make_xml(latp5_dir, iv_seg_file, xml_fil... |
from time import sleep
from ControllerState import ControllerState
from AI import AI
from StateType import StateType
from PieceColor import PieceColor
class GUIAIState(ControllerState):
def __init__(self, StateManager, View, Model, Controller, MoveController, InputController,\
AI):
self.StateManag... |
import pandas as pd
import pytest
from toucan_data_sdk.utils.postprocess.text import (
capitalize,
center,
concat,
contains,
endswith,
find,
isupper,
length,
lower,
partition,
repeat,
replace_pattern,
split,
strip,
title,
)
@pytest.fixture
def df():
ret... |
import numpy as np
import tensorflow as tf
import keras.backend as K
from keras.layers.merge import concatenate
from keras.layers import Input, Reshape, Dense, Dropout
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.models import Model
from keras.optimizers import RMSprop
from keras.regularizers... |
# FinaleDB pipeline
__author__ = "Haizi Zheng"
__copyright__ = "Copyright 2021, Haizi Zheng"
__email__ = "haizi.zh@gmail.com"
__license__ = "MIT"
from os import path
import os
import sys
# smk file home location
smk_path = path.normpath(path.dirname(__file__))
sys.path = [smk_path] + sys.path
from os import path
f... |
# uncompyle6 version 3.2.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
# Embedded file name: direct.showbase.ExcelHandler
__all__ = [
'ExcelHandler']
from xml.sax import saxutils
class ExcelHandler(saxutils.DefaultHandler):
... |
# -*- coding: utf-8 -*-
"""
=====KAIST EE532 Brain IT Project=====
Using LSTM for making lung movement time-series
With Lung Movement Data(Composed of 3 axes input, x, y, z)
Using Raiman's theano_rnn library and referencing his tutorial.
[here](https://github.com/JonathanRaiman/theano_lstm)
@author: BK Yoo
@date: Ju... |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 4 21:44:06 2021
@author: lankuohsing
"""
from sklearn.datasets import load_digits
from sklearn.feature_selection import SelectKBest, chi2
import numpy as np
# In[]
# In[]
"""sklearn implementation"""
def select_k_best_sklearn(X,y,k):
k=min(20,X.shape[1])# select to... |
"""Tests for `pyramid_listing.pagination` Pagination class."""
import pytest
from . import DummyRequest
@pytest.mark.parametrize(
"data,key,default,expected",
[
({}, "x", 1, 1),
({"a": 2}, "x", 1, 1),
({"x": 2}, "x", 1, 2),
({"x": "123"}, "x", 1, 123),
({"x": None}, "... |
#!/usr/bin/env python3
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
"""
sbz poudriere runner
"""
import argparse
import configparser
import os
import shlex
import subprocess
import sys
from typing import Dict
import colored
from colored import stylize
LOCALBASE = "/usr/local"
PORTSDIR = "/usr/ports" or o... |
import galene as ga
input_files = ['1231022b.csv', ]
dataset_id = 'ices-ctd'
station_file = 'helcom_stations.csv'
for f in input_files:
ga.ices_reader.process_cvs_file(f, station_file, dataset_id)
|
"""
contains the provider class which is used to register a provider and parse the response.
"""
from typing import Callable
from aiohttp import ClientSession
from proxy_random.query import ProxyQuery
from proxy_random.utils import get_page
class Provider:
"""The proxy provider class"""
def __init__(self, ... |
import json
import pytest
from indy_common.authorize.auth_constraints import AuthConstraintForbidden
from indy_common.types import SetRsSchemaDataField
from indy_node.test.api.helper import sdk_write_rs_schema_and_check, build_rs_schema_request
from indy_node.test.rs_schema.templates import TEST_1
from plenum.common.e... |
import requests
import json
import os
from requests.exceptions import ConnectionError
# you'll need to have an API key for TMDB
# to run these examples,
# run export TMDB_API_KEY=<YourAPIKey>
tmdb_api_key = os.environ["TMDB_API_KEY"]
# Setup tmdb as its own session, caching requests
# (we only want to cache tmdb, not ... |
#
# University of Luxembourg
# Laboratory of Algorithmics, Cryptology and Security (LACS)
#
# FigureOfMerit (FOM)
#
# Copyright (C) 2015 University of Luxembourg
#
# Written in 2015 by Daniel Dinu <dumitru-daniel.dinu@uni.lu>
#
# This file is part of FigureOfMerit.
#
# This program is free software: you can redistribut... |
from setuptools import setup, find_packages
import sys
import os
import re
org = "ICB-DCM"
repo = "fiddy"
def read(fname):
"""Read a file."""
return open(fname).read()
def absolute_links(txt):
"""Replace relative links by absolute links, on GitHub."""
raw_base = f"(https://raw.githubusercontent.c... |
from hyp.schematics import Responder as SchematicsResponder
from fixtures import (
PostResponder,
PersonResponder,
PostSerializer,
)
from hyp.constants import JSONAPI_VERSION_DICT
class TestIncluded(object):
def test_single(self):
author = {'id': 1, 'name': 'John'}
comments = [
... |
import PySimpleGUI as sg
from Conectar import conexao
con, cursor = conexao()
def logar():
sg.theme('DarkBlue')
acesso = False
cursor.execute('select nome from login')
login = cursor.fetchall()
nomes = []
cont = 0
for c in login:
nomes.append(c[0])
layout = [
[sg.Image... |
import tensorflow as tf
import numpy as np
from net import resnet_v1
from net import resnet
from roi_rotate import rotate_np
from roi_rotate import roi_rotate_quad as roi_rotate_quad
from utils import quad_to_param, getboxes, bbox_inverse_transform, bbox_transform_from_anchor_list, generate_anchor_box
from intermediate... |
"""empty message
Revision ID: f3458b927eba
Revises: e3202524923f
Create Date: 2018-07-29 03:25:24.358278
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f3458b927eba'
down_revision = 'e3202524923f'
branch_labels = None
depends_on = None
def upgrade():
# ... |
# This file is part of VoltDB.
# Copyright (C) 2008-2020 VoltDB Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later ver... |
N_testes=int(input())
for i in range (0,N_testes):
Teste=input().split()
Mao1=int(Teste[0])
Mao2=int(Teste[1])
if Mao1 ==1 and Mao2 == 1:
print("coma")
else:
print("pense")
|
"""
StudentView viewsets Class.
Part of views.student module.
"""
__license__ = "MIT"
__version__ = "0.0.1"
__author__ = "Ariel Saavedra D"
__email__ = "ariel@gmail.com"
__copyright__ = "Copyright 2020"
from rest_framework import viewsets
from rest_framework import status
from rest_framework.response import Response... |
import argparse
import re
def convert_marble_vita(s):
'''
FMC1_LA_0_P -> FMC1_LA00_CC_P
'''
d = s.split('_')
if d[1] == 'LA':
index = int(d[2])
postfix = 'CC_' + d[3] if index in [0, 1, 17, 18] else d[3]
result = '{}_{}{:02d}_{}'.format(d[0], d[1], index, postfix)
elif... |
# FQDN for current machine
LIQUID_DOMAIN = "{{ liquid_domain }}"
# Network interface used for the DNS server.
# The machine must have a single IPv4 address on this interface.
# Set to None to omit using a DNS server
DNSMASQ_INTERFACE = None
# Flask debug
DEBUG = {% if devel %}True{% else %}False{% endif %}
|
# flake8: noqa
# import all models into this package
# if you have many models here with many references from one model to another this may
# raise a RecursionError
# to avoid this, import only the models that you directly need like:
# from from cosmotech_api.model.pet import Pet
# or import this package, but before d... |
# coding=utf-8
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from abc import ABCMeta, abstractmethod
import game
__author__ = 'Aijun Bai'
class Simulator(object):
__metaclass__ = ABCMeta
def __init__(self, g):
... |
#!/usr/bin/env python3
'''
bsub.py
This script checks a Snakemake job's properties (threads, resources) and chooses
an appropriate LSF queue that meets the requirements. It also automatically
chooses the queue that is least busy unless you already specified a queue.
Usage
-----
Add 'threads' and 'resources' to your ... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 CERN.
# Copyright (C) 2020 Northwestern University.
#
# Invenio-Drafts-Resources is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
"""Invenio Drafts Resources module to create REST APIs"""... |
# This is a script for the second dataset
import pandas as pd
import spacy
data = pd.read_csv("C:/Users/anast/Desktop/Thesis/Datasets/Searching/2/g28.txt", header=None, sep="\t")
nlp = spacy.load('en_core_web_lg')
# Save Dependency Parsing in svg for better visualization
# for i in range(0, data.__len__()):... |
class MyClass:
def __init__(self):
print("생성자가 호출 되었네요!")
def __del__(self):
print("소멸자가 호출 되었네요!")
o = MyClass()
del o |
"""
Helper classes to convert iTunes library XML file to SQLite database to use in Flask app
Usage:
db = SongDb('itunes/library/file.xml', echo=False)
db.create_db()
db.populate_db()
"""
import shutil
import sys
import xml.etree.cElementTree as ET
from peewee import DoesNotExist
from pyItunes import Library
from juk... |
from config import *
import os
import requests
import pprint
import getpass
import json
import cmd
import csv
dir_path = os.path.dirname(os.path.realpath(__file__))
directorystructureteam = []
directorystructureindividual = []
studentteamassignments = []
user = input("Username:")
passwd = getpass.getpass("Password fo... |
from pynput import mouse
from pynput import keyboard
import time
import json
import sys
n = len(sys.argv)
if n < 2:
exit("Takes a compulsory argument - name of recording, and optional argument - record-all")
if n > 3:
exit("Only takes two arguments - name of recording and (optional) record-all")
if n == 2:
... |
from unittest import TestCase
import numpy as np
import pandas as pd
from numpy.testing import assert_array_equal
from serenata_toolbox.chamber_of_deputies.reimbursements import Reimbursements
class TestReimbursements(TestCase):
def setUp(self):
self.dataset = pd.read_csv('tests/unit/receipts.csv',
... |
import pytest
from django.core.exceptions import ImproperlyConfigured
from rest_framework import serializers
from datahub.core.serializers import ConstantModelSerializer
from datahub.metadata.models import Sector, UKRegion
from datahub.metadata.registry import MetadataRegistry
# mark the whole module for db use
pytes... |
#Copyright MIT License, 2017 Armaghan Naik, Pieter Spealman
#PS - 08.07.18: updated syntax for print commands
import string
import numpy
import sys
import os
genome = []
cache = []
commands = open(sys.argv[1],'r')
for rline in commands:
line = rline.rstrip()
Line = string.split(line)
if '#' in Line[0]:
... |
"""
Understanding GIS: Assessment 2
@author [Qian Liu]
An Implementation Weighted Redistribution Algorithm (Huck et al.)
"""
from numpy import mean, zeros
from numpy.random import uniform
from math import hypot, pi, sqrt, ceil, floor
from geopandas import read_file
from shapely.geometry import Point
from... |
from datetime import date
anoAtual = date.today().year
n1 = int(input('Em que ano você nasceu: '))
while n1 < 0 or n1 > anoAtual:
n1 = int(input('Valor inválido, por favor digite outro: '))
idade = anoAtual - n1
if idade <= 9:
print('Você se enquadra na categoria \033[1;34mMIRIN\033[m de natação')
elif idade <=... |
# -*- coding: utf-8 -*-
import rosbag
from std_msgs.msg import String, Float64
bag = rosbag.Bag('./green.bag', 'w')
'''
/consumption/provenance/type: std_msgs/String: ‘Wind’,
/consumption/provenance/proof: std_msgs/String <link_to_tobalaba>
/consumption/quantity: std_msgs/Float64: 91639.00
/consumption/compensation... |
""" Python-mode async support. """
from ._compat import Queue
RESULTS = Queue()
|
class Graph(object):
def __init__(self):
self.__size = 0
self.__matrix = []
self.__verticies = []
@property
def verticies(self):
return self.__verticies
@property
def matrix(self):
return self.__matrix
@property
def size(self):
return self._... |
import typing
import dataclasses
if typing.TYPE_CHECKING:
from ...client import Client
from .channel import BaseChannel
from ..mixins import Hashable
from ...utils import Snowflake
@dataclasses.dataclass(repr=False)
class NewsChannel(BaseChannel,Hashable):
"""
This is the NewsChannel it used to repre... |
################################################################################
# Copyright (c) 2021 ContinualAI. #
# Copyrights licensed under the MIT License. #
# See the accompanying LICENSE file for terms. ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-23 12:57
from __future__ import unicode_literals
from django.db import migrations
from unicodecsv import DictReader
def load_banks(apps, schema_editor):
country_model = apps.get_model("core", "Country")
company_model = apps.get_model("core", "Co... |
# Generated by Django 3.0.3 on 2020-10-07 08:26
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('fyle', '0009_auto_20200929_0717'),
]
operations = [
migrations.AlterUniqueTogether(
name='expensegroup',
unique_together=set... |
import uuid
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Callable, Dict
import marshmallow
from marshmallow import (
ValidationError,
fields,
post_dump,
post_load,
pre_dump,
pre_load,
)
import prefect
from prefect.utilities.serialization import (
UUID,
Fun... |
import sys
import os
import platform
from setuptools import setup
from setuptools.extension import Extension
# Ensure Cython is installed before we even attempt to install linmdtw
try:
from Cython.Build import cythonize
from Cython.Distutils import build_ext
except:
print("You don't seem to have Cython in... |
from .base_page import BasePage
from .locators import ProductPageLocators
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
class ProductPage(BasePage):
def should_be_right_book_name(self):
btn = self.browser.find_element(*... |
from __future__ import print_function
from copy import deepcopy
from functools import partial
import time
import random
import sys
import yaml
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pydrake
from pydrake.math import (RollPitchYaw, RigidTransform)
import torch
import torch.distr... |
import numpy as np
from numpy.lib.stride_tricks import as_strided
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import check_is_fitted
from skits.feature_extraction import AutoregressiveTransformer
def expand_dim_if_needed(arr):
if arr.ndim == 1:
return np.expand_... |
# -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
#
# Copyright (c) 2011 Vauxoo - http://www.vauxoo.com/
# All Rights Reserved.
# info Vauxoo (info@vauxoo.com)
####################################... |
# Create a program that asks the user to enter their name and their age. Print out a message
# addressed to them that tells them the year that they will turn 100 years old.
Name = input("Enter your name: ")
Age = int(input("Enter your age: "))
print("Hello",Name,"You will turn 100 in",100-Age,"years") |
import shutil
from spec.health.microhealth.healthcheck import Healthcheck
from spec.health.microhealth.healthcheck_response import HealthcheckResponse
class LivelinessHealthcheck(Healthcheck):
def call(self):
return HealthcheckResponse.up('liveliness', None)
class DiskSpaceHealthcheck(Healthcheck):
... |
# -*- coding: utf-8 -*-
"""
comments
author: diqiuzhuanzhuan
email: diqiuzhuanzhuan@gmail.com
"""
import collections
class NumberAdapter(object):
_data = collections.OrderedDict({
"个": -1,
"零": 0,
"又": 0,
"0": 0,
"一": 1,
"1": 1,
"壹": 1,
"二": 2,
... |
from extract_json_data import download_json_file
from get_file_vanilla import read_file
from utils import MonthlyFile
def main():
"""
:return:
"""
download_json_file()
process = MonthlyFile()
read_file(process.data)
if __name__ == '__main__':
main()
|
import psutil
# CPU逻辑数量
print(psutil.cpu_count())
# CPU物理核心
print(psutil.cpu_count(logical=False))
print(psutil.cpu_times())
# for x in range(10):
# print(psutil.cpu_percent(interval=1, percpu=True))
print(psutil.virtual_memory())
print(psutil.swap_memory())
# 磁盘分区信息
print(psutil.disk_partitions())
# 磁盘使用情况... |
import os.path
from flask import Flask
from flask.ext.autoindex import AutoIndex
app = Flask(__name__)
AutoIndex(app, browse_root=os.path.curdir)
if __name__ == '__main__':
app.run(host="0.0.0.0")
|
import torch
from alphafold2_pytorch.alphafold2 import Alphafold2
def test_main():
model = Alphafold2(
dim = 256,
depth = 2,
heads = 8,
dim_head = 64
)
seq = torch.randint(0, 21, (2, 128))
msa = torch.randint(0, 21, (2, 5, 64))
mask = torch.ones_like(seq).bool()
... |
from kafka_cosumer_test import f
# i = 203
# f.push(i)
for i in range(200):
f.push(i)
|
#!/usr/bin/env python
""" Network visualisation from Python
Sara-Jayne Terp
2015
"""
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import operator
"""
Create NetworkX undirected or directed graph for processing
"""
def create_graph(edgelist, directed=False):
if directed:
G = n... |
# -*- coding: utf-8 -*-
import cgi
import datetime
from django import http
from django.http import HttpResponse
from django.template import Context, loader
from xhtml2pdf import pisa
import cStringIO as StringIO
from gestao.settings import PROJECT_ROOT_PATH
def render_to_pdf(template_src, context_dict):
data_a... |
#!/usr/bin/env python
# coding=utf-8
# code by kbdancer@92ez.com
from threading import Thread
from telnetlib import Telnet
import requests
import sqlite3
import Queue
import time
import json
import sys
import os
reload(sys)
sys.setdefaultencoding('utf8')
def ip2num(ip):
ip = [int(x) for x in ip.split('.')]
... |
from abc import ABCMeta, abstractmethod
class BaseCommand(metaclass=ABCMeta):
@abstractmethod
def parse_arguments(self, subparsers):
return
@abstractmethod
def handle_command(self, args):
return
|
from django.urls import path
from system.views import viewsSyspara
# 添加到urls.py
# path('syspara/',include("system.urlsSyspara")),
urlpatterns = [
# path('admin/', admin.site.urls),
path('index/', viewsSyspara.index),
path('ajaxSaveSyspara/', viewsSyspara.ajaxSaveSyspara),
path('ajaxDelSyspara/', view... |
# 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 t... |
import pandas as pd
from data_pipeline.food_material_price.columns import condition
from data_pipeline.main import DataPipeline
class PriceDataPipeline:
"""
prepare data from process data
return prepared data(one pd DataFrame) for FeatureExtraction
"""
def __init__(self):
self.ty... |
from telegram import ReplyKeyboardRemove, InlineKeyboardButton, InlineKeyboardMarkup, InlineQueryResultArticle, InputTextMessageContent, ParseMode
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, ConversationHandler, MessageHandler, Filters, InlineQueryHandler
from telegram.utils.helpers import e... |
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or ... |
import os
from typing import Any, List, Optional, TypeVar, Tuple
import numpy as np
from donkeycar.config import Config
from donkeycar.parts.tub_v2 import Tub
from donkeycar.utils import load_image, load_pil_image, normalize_image, train_test_split, process_image
from typing_extensions import TypedDict
X = TypeVar('X... |
import pytest
import simplejson
from flask import Flask
from sacredboard import bootstrap
from sacredboard.app.data import MetricsDAO, NotFoundError, DataStorage
from sacredboard.app.webapi import metrics
from sacredboard.tests.fixtures.metrics import m1, m2
app = None
test_client = None
class FakeMetricsDAO(Metric... |
from pyoogle.preprocessing.crawl.crawler import crawl_mathy
from pyoogle.preprocessing.web.nodestore import WebNodeStore
path, webnet = crawl_mathy()
if webnet is not None:
from pyoogle.preprocessing.ranking.ranker import BaseRanker
ranker = BaseRanker()
print("Starting ranking webnet with", ranker)
... |
# Generated by Django 2.2.10 on 2020-07-13 10:13
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("wagtailcore", "0054_initial_locale"),
]
operations = [
migrations.AddField(
model_name="page",... |
"""
This is the main script for controlling the experiment.
It contains the main control loop of experiment.
"""
import time
import datetime
import multiprocessing
from multiprocessing.queues import Queue
import threading
import numpy as np
# Serial ports and NI
import serial.tools.list_ports
# Local project scripts
... |
# 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 applicab... |
import requests
import json
headers = {'X-Auth-Token': '3b7bd33d925842878308aa20f4422129', 'X-Response-Control': 'minified'}
base_url = 'http://api.football-data.org/v1/'
epl_team_id = {'arsenal': 57, 'man-u': 66, 'liverpool': 64, 'man-city': 65, 'leicester': 338, 'birmingham': 332,
'southampton': 340... |
"""
使用多进程对复杂任务进行“分而治之”。
我们来完成1~100000000求和的计算密集型任务,这个问题本身非常简单,有点循环的知识就能解决,代码如下所示。
"""
from time import time
def main():
total = 0
number_list = [x for x in range(1, 100000001)]
start = time()
for number in number_list:
total += number
print(total)
end = time()
print('Execution ti... |
# Imports
import numpy as np
import time
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.svm import SVC
from Saved_Dataset import save_pickle
from LR_Regularization_Dropout_Adam import L_layer_model,predict
np.random.seed(0)
def load_numpy(dataset_path):
X_train = np.load(datase... |
class Token:
def __init__(self, amount, rt):
self.amount = amount
self.receivedtime = rt |
from kafka import KafkaConsumer
from kafka.admin import KafkaAdminClient, NewTopic
import json
class Chang_Consumer:
def __init__(self, broker: str, topic_name: str, auto_offset_reset='earliest', group_id="consumer-group-c"):
self.broker = broker
self.consumer =KafkaConsumer( topic_name, boot... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.