text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python3
import getopt
import select
import socket
import ssl
import sys
def usage(f=sys.stdout):
f.write("""\
Usage: %s --tls-cert=FILENAME --tls-key=FILENAME HOST PORT
--disable-tls run without TLS
--tls-cert=FILENAME use this TLS certificate (required without --disable-tls)
--tls-k... |
# python
import sys
import os
import time
import importlib
import argparse
import random
import re
# numpy
import numpy as np
# torch
import torch
from torch import nn, optim
# ours
from data import MonoTextData
from modules import VAE
from modules import LSTMEncoder, LSTMDecoder
# constants
DIVIDER = '------------... |
#!/usr/bin/env python3
""" Basic Annotations """
def concat(str1: str, str2: str) -> str:
"""concat function w/ annotations"""
return "{}{}".format(str1, str2)
|
import IceRayPy
import camera
def make( P_object_cargo ):
engine = IceRayPy.core.render.Engine()
cargo_camera = camera.make()
engine.camera( cargo_camera['this'] )
cargo_object = P_object_cargo
engine.object( cargo_object['this'] )
return { 'this': engine, '0': cargo_camera,... |
# This files contains your custom actions which can be used to run
# custom Python code.
#
# See this guide on how to implement these action:
# https://rasa.com/docs/rasa/core/actions/#custom-actions/
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __fu... |
from sys import stdin
from itertools import repeat
def merge(decks):
d_l = 0
for deck in decks:
max_card = 0
for c in deck:
if c[0] > max_card:
max_card = c[0]
d_l += max_card
n_d = [None] * d_l
for deck in decks:
for card in deck:
... |
import os
from datetime import datetime, timedelta
from sys import version_info as info
from typing import Iterable, List, Optional
import pytest
import requests
from auth0.v3.authentication import GetToken
from auth0.v3.management import Auth0 as Auth0sdk
from fastapi.security.http import HTTPAuthorizationCredentials... |
# 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, software
# distributed under t... |
from django.core.management.base import BaseCommand
import layzer.startup
from layzer.layzerjobs import UpdateFeedsJob
class Command(BaseCommand):
args = ""
help = "Refresh all subscriptions"
def handle(self, *args, **kwds):
UpdateFeedsJob().run()
|
# -*- coding=UTF-8 -*-
# pyright: strict
from __future__ import annotations
import re
import os
import logging
_LOGGER = logging.getLogger(__name__)
_IMAGE_DIR = "_images"
_IMAGE_PATTERN = re.compile(r"_images/(.+\.(png|jpg))")
def iter_image_names():
for dirpath, dirnames, filenames in os.walk("."):
... |
#
# Shared methods and classes for testing
#
import pybamm
import numpy as np
class SpatialMethodForTesting(pybamm.SpatialMethod):
"""Identity operators, no boundary conditions."""
def __init__(self, mesh):
for dom in mesh.keys():
mesh[dom].npts_for_broadcast = mesh[dom].npts
sup... |
# coding=utf-8
from ..settler import HopfieldSettler
from ..utils import binary_array
from bases import HopfieldTestCase
from mocking import make_net_from_lecture_slides
class HopfieldSettlerTests(HopfieldTestCase):
def test_finding_deep_minimum(self):
net = make_net_from_lecture_slides()
net.s... |
## imports
import os, time
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as mplPath
from scipy.misc import imresize
import skimage.io as io
from . import utilities
def backgroundFalseNegErrors( coco_analyze, imgs_info, saveDir ):
loc_dir = saveDir + '/background_errors/false_negatives'
... |
##############################################################################
#
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
from lib.blockchain import Blockchain
from lib.network import Network
from lib.http_server import MasterServer
if __name__ == '__main__':
b = Blockchain('master')
master = Network.get_master()
server = MasterServer(master, b)
server.serve_forever()
|
class Vector:
__secretCount = 0 # private 私有变量
_protectedParm=100 #protected类型变量,允许本类和及其子类访问
publicCount = 1 # public 公开变量
def __init__(self,a,b):
"""
构造方法
:param a:
:param b:
"""
self.a=a
self.b=b
def __str__(self):
return 'Vector... |
from game import Game
import os
import sys
if len(sys.argv) < 2:
print("Usage: python3 run.py <filename> [play]")
sys.exit()
filename = sys.argv[1]
try:
game_object = Game(filename)
except FileNotFoundError as e:
print(e)
sys.exit()
except ValueError as e:
print(e)
sys.exit()
except TypeE... |
import asyncio
from abc import abstractmethod
class BaseConsumer:
def __init__(self, queue: asyncio.Queue):
self._queue = queue
@abstractmethod
async def consume(self, task: dict):
pass
|
import requests
api = 'https://ubcexplorer.io/'
allCourseData = {}
# methods for finding course pre-requisites ---------------------
# returns all course data
def courses():
url = api + 'getAllCourses/'
r = requests.get(url)
return r.json()
# returns all the courses for a subject
def courseInfo(code):
... |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def maxPathSum(root):
"""
:type root: TreeNode
:rtype: int
"""
max_sum = float('-inf')
def max_gain(node):
if node is None:
return 0
l = max... |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'step',
]
def GenSteps(api):
# We are going to have steps with the same name, so fix it automagically.
api.step.auto_resolve_conflicts = Tru... |
from django.shortcuts import render
from django.views.generic import TemplateView
def index(request):
return render(request, 'index-du.html')
class Paths(TemplateView):
template_name = 'front/tracks/paths/index.html'
class PathDetail(TemplateView):
template_name = 'front/tracks/path/detail/index.html'... |
from pages.models import Page
def list_pages(request):
pages = Page.objects.all().order_by('-title')
return {"pages": pages}
|
import redis
REDIS_HOST = "localhost"
REDIS_PORT = 6379
REDIS_PASSWORD = None
REDIS_KEY = "proxies"
class PoolEmptyError(Exception):
def __init__(self, error_info='IP代理池为空,无法提供有效代理'):
# super().__init__(self)
self.error_info = error_info
def __str__(self):
return self.error_info
cl... |
#
# Programming Assignment 2, CS640
#
# A Gomoku (Gobang) Game
#
# Adapted from CS111
# By Yiwen Gu
#
# You need to implement an AI Player for Gomoku
# A Random Player is provided for you
#
#
from pa2_gomoku import Player
import random
# numpy is used to accelerate matrix computing
import numpy as np
FIVE = 7
FOUR... |
from airflow.models import DAG
from airflow.operators.dummy import DummyOperator
from airflow.operators.python import BranchPythonOperator
from airflow.operators.python import ShortCircuitOperator
from airflow.utils.dates import days_ago
from datetime import datetime
from call_back.notify import succes_callback,failure... |
# Generated by Django 3.1.1 on 2020-09-21 12:17
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
replaces = [('projects', '0004_auto_20200920_1853'), ('projects', '0005_auto_20200921_1210'), ('projects', '0006_proje... |
import sys, os
sys.path.append(os.path.abspath(".."))
import spidev
import time
import audioop
import pyaudio
import numpy as np
from math import trunc
from matplotlib import pyplot as plt
from utils import getInputDeviceID, getMicDeviceID, getTimeValues
spi = spidev.SpiDev()
spi.open(0, 1)
spi.max_speed_hz = 7629
# ... |
import requests
from bs4 import BeautifulSoup
from random import choice
from Proxy import proxies
import xlsxwriter
from time import sleep
def get_html(url):
r = requests.get(url, headers=user, proxies=proxy)
r.encoding = 'utf8'
return r.text
def get_soup(url):
soup = BeautifulSoup(ur... |
import redis
import os
import sdk
r = redis.StrictRedis(host=sdk.config.state.host,
port=sdk.config.state.port, db=0)
def load(appname, state):
"""Loads app state from Jarvis into |state|.
Returns:
Flag indicating whether or not a saved state was found.
"""
msg_str = r.g... |
# OWASP-Why-Random-Matters demo
from MT19937 import Random
if __name__ == "__main__":
rnd = Random (100)
print rnd.get() |
def expand_attrs_dict(attrs_dict, *keys):
new_attrs_dict = attrs_dict.copy()
for key in keys:
try:
new_attrs_dict[key] = attrs_dict[key].__dict__
except AttributeError:
pass
return new_attrs_dict
def deepupdate_attrs(obj, attr_dict):
for attr in obj.__dict__:
... |
{
"description": """
Внезапно руки мишки превратились в длинные щупальца и ринулись в вашу сторону.
От страха все мысли улетучились из вашей головы и вы могли лишь стоять и смотреть в глаза приближающейся старухе с косой.
Склизкие щупальца обвили вас и потянули к себе.
В этот момент вы очнулись и стали вырыватьс... |
import json
import urllib
import stripe
import requests
from django.shortcuts import render
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.conf import settings
from django.views import View
from django.views.generic import ListView, DetailView
from django.http import JsonRespon... |
#!/usr/bin/env python
import argparse
import os
import subprocess
import sys
from lib.config import LIBCHROMIUMCONTENT_COMMIT, BASE_URL, PLATFORM, \
enable_verbose_mode, is_verbose_mode, get_target_arch
from lib.util import execute_stdout, scoped_cwd
SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(... |
from core.models import Todo
from core.forms import Todoform
from django.shortcuts import redirect, render
from core.forms import Todoform
def home(request):
form = Todoform()
todos = Todo.objects.all()
if request.method == 'POST':
form = Todoform(request.POST)
if form.is_valid():
... |
"""
Class representing transactions in Bank System.
"""
from mysql_engine import *
class Transactions:
transaction_type = None
date = None
amount = None
account_number = None
person = None
def create_transaction(self):
pass
def get_all_transactions(self):
mysql_obj=MySqlE... |
#!/usr/bin/python
#
# Ceph - scalable distributed file system
#
# Copyright (C) Inktank
#
# This is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License version 2.1, as published by the Free Software
# Foundation. See file COPYING.
#
"""
This is intended... |
from __future__ import print_function
import os, glob, shutil, re
import numpy as np
# Strings to replace in jdl template
EXEC = '__EXEC__'
INPUTS = '__INPUTS__'
ARGS = '__ARGS__'
MEM = '__MEM__'
# Input maNtuple campaign
indir = '../maNtuples'
#input_campaign = 'Era04Dec2020v1' # updated later with 2018A
input_campa... |
# User Preference Structure & Recommendation Effectiveness Analysis 3.5
import pathlib
import pandas as pd
import numpy as np
from scipy.stats import entropy
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_distances
import re
import matplotlib as mpl
import matpl... |
"""144. Binary Tree Preorder Traversal"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def preorderTraversal(self, root):
"""
... |
from shared_matrix import SharedMatrix
from custom_barrier import CustomBarrier
from threading import Thread, current_thread
from typing import Tuple, Union
from statistics import mean
class Worker(Thread):
def __init__(self, barrier: CustomBarrier, observer_barrier: Union[CustomBarrier, None], shared_matrix: Sha... |
# Generated by Django 2.2.7 on 2020-01-21 13:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0002_product_size'),
]
operations = [
migrations.AddField(
model_name='product',
name='type',
fi... |
#
# 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... |
from PyQt5 import QtCore, QtGui, QtWidgets
class Vehicle(object):
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
class InputWidget(QtGui.QWidget):
def __init__(self):
super(InputWidget, self).__init__()
self.setFixedSize(... |
from socket import *
import threading
from config import *
class Server:
def __init__(self, hostname, port):
self.hostname = hostname
self.port = port
self.clients = {}
self.threads = []
self.keep_alive = True
self.socket = socket(AF_INET... |
import numpy as np
import DateTimeTools as TT
def UTPlotLabel(fig,axis='x',seconds=False):
if hasattr(fig,'gca'):
ax=fig.gca()
else:
ax = fig
R = ax.axis()
mt=ax.xaxis.get_majorticklocs()
labels=np.zeros(mt.size,dtype='S8')
for i in range(0,mt.size):
tmod = mt[i] % 24.0
hh,mm,ss,ms=TT.DectoHHMM(tmod,Tr... |
import cv2
import numpy as np
img1 = np.zeros((250,500,3), np.uint8)
img1 = cv2.rectangle(img1,(200,0), (300,100),(255,255,255),-1)
img2 = cv2.imread("image.jpg")
img2 = cv2.resize(img2,(500,250))
#bitAnd = cv2.bitwise_and(img2,img1);
#bitOr = cv2.bitwise_or(img2,img1)
#bitXor = cv2.bitwise_xor(img1,img2);
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('library', '0022_auto_20190918_1425'),
]
operations = [
migrations.AlterField(
model_name='document',
... |
from lr.tests import *
class TestPublisherController(TestController):
def test_index(self):
response = self.app.get(url('publish'))
# Test response...
def test_index_as_xml(self):
response = self.app.get(url('formatted_publish', format='xml'))
def test_create(self):
respo... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def longestUnivaluePath(self, root: TreeNode) -> int:
answer = 0
def caller(node):
non... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 27 06:06:55 2018
@author: mromiario
"""
import operator #library untuk mengambil value tertinggi dictionary
#Dibuat oleh Ibu Ade Romadhony
#Dikembangkan/dilengkapi oleh Muhammad Romi Ario Utomo - 1301154311
def read_file_init_table(fname): #membaca... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 3 10:05:29 2019
@author: zoescrewvala
"""
import os
import cartopy
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import numpy as np
import pandas as pd
import xarray as xr
import pygemfxns_gcmbiasadj as gcmbiasadj
#%% X-Y PL... |
# example_publisher.py
import pika, os, logging
logging.basicConfig()
# Parse CLODUAMQP_URL (fallback to localhost)
url = os.environ.get('CLOUDAMQP_URL', 'amqp://oivaegml:LFBj9SGoVYhWqr14OJRrBY8KoI-NxXie@prawn.rmq.cloudamqp.com/oivaegml/%2f')
params = pika.URLParameters(url)
params.socket_timeout = 5
connect... |
width = int(input())
height = int(input())
symbol = input()
for i in range(height):
for j in range(width):
if i == 0 or i == height - 1:
print(symbol, end="")
elif j == 0 or j == width - 1:
print(symbol, end="")
else:
print(" ", end="")
print()
|
from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse, HttpResponseBadRequest, HttpResponse
from django.core import serializers
from .forms import IncidentForm, UpdateForm, DeveloperForm
from .models import Incident,Developers
# Create your views here.
def indexView(request):
... |
class Morphs:
def __init__(self, morphs):
(surface, attr) = morphs.split('\t', 1) # 行を最初の\tで区切る
attr = attr.split(',')
self.surface = surface # 表層形
self.base = attr[5] # 基本形
self.pos = attr[0] # 品詞
self.pos1 = attr[1] # 品詞細分類
class Chunk:
def __init__(... |
'''
Created on Dec 8, 2019
@author: slane
'''
inputFile = open("input.txt","r")
totalFuel = 0
for line in inputFile.readlines():
fuel = int(line)
fuel = int(fuel/3) - 2
fuelPlus = int(fuel/3) - 2
while (fuelPlus > 0):
totalFuel += fuelPlus
fuelPlus = int(fuelPlus/3) - 2
totalFuel +=... |
def flattenList(x):
""" Flatten a list using recursion """
flattened = []
for i in x:
if type(i) not in (list, tuple, set):
flattened.append(i)
else:
flattened += flattenList(i)
return flattened
if __name__ == "__main__":
for test_case in ([1, 2, 3], [1, [... |
"""
Use DMatrix api to train and test
Cross-validation hasn't support DMatrix yet, but will do soon.
"""
import os
import xlearn as xl
import pandas as pd
data_path = r"F:\for learn\Python\Repo_sources\xlearn\demo\regression\house_price"
train_file = os.path.join(data_path, "house_price_train.txt")
test_file = os.... |
class Solution:
def twoOutOfThree(self, nums1, nums2, nums3):
num_set1 = set()
for num in nums1:
num_set1.add(num)
num_set2 = set()
for num in nums2:
num_set2.add(num)
num_set3 = set()
for num in nums3:
num_set3.add(num)
set... |
import MetaTrader5 as mt5
# 显示有关MetaTrader 5程序包的数据
print("MetaTrader5 package author: ", mt5.__author__)
print("MetaTrader5 package version: ", mt5.__version__)
# 建立与MetaTrader 5程序端的连接
if not mt5.initialize():
print("initialize() failed, error code =", mt5.last_error())
quit()
# 获取所有交易品种
symbols = mt5.symbol... |
from mxnet import ndarray as nd
from mxnet import autograd as ag
import random
# 批量获取数据
def load_data_iter():
# 索引
idx = list(range(sample_num))
# 乱序
random.shuffle(idx)
for i in range(0, sample_num, batch_size):
j = nd.array(idx[i: min(i + batch_size, sample_num)])
yield nd.take(... |
# coding:utf-8
################
#练习3:数字与数学计算
################
# 题目:企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,
# 低于10万元的部分按10%提成,高于10万元的部分,可可提成7.5%;20万到40万之间时,高于20万元的部分,可提成
# 5%;40万到60万之间时高于40万元的部分,可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%,高
# 于100万元时,超过100万元的部分按1%提成,从键盘输入当月利润I,求应发放奖金总数?
# 程序分析:条件语句的运用,... |
import re
import math
from uuid import UUID
from .exceptions import Invalid
def str_validation(val, key=None, min_length=None, max_length=None, regex=None, choices=None, cast=None, *args, **kwargs):
if cast:
try:
val = str(val)
except (ValueError, TypeError):
raise Invali... |
num = int(input("Digite um número inteiro: "))
resp = num // 10
dezena = resp % 10
print("O dígito das dezenas é", dezena) |
# -*- coding: utf-8 -*-
import random
import hashlib
def get_chars(length=None, mode=2):
"""
:param length: 生成字符的长度,如果不指定则为返回长度为1-20
:param mode: 0,小写,1,大写,2,混合
:return:
"""
if not length:
length = random.randint(1,20)
lc = 'abcdefghijklmnopqrstuvwxyz'
if mode == 0:
cs ... |
from gtts import gTTS
from playsound import playsound
import requests
import random
import webbrowser
def noticias():
url = ('https://newsapi.org/v2/top-headlines?'
'country=br&'
'apiKey=05d5ce74721c41698d58009213297db9')
req = requests.get(url, timeout=3000)
json = req.json()
# PERCORREN... |
count=0
entry ='Y'
while entry !='N' and entry!= 'n':
print(count)
entry = input('please enter "Y" to continue or "N" to quit:')
if entry == 'Y' or entry == 'y':
count+= 1
elif entry !='N'and entry != 'n':
print('"'+ entry + '" is not valid choice')
|
from bs4 import BeautifulSoup
import requests
from Mail import sendMail
from writeAndRead import saveData, checkData
data = 0
source = requests.get('https://www.worldometers.info/coronavirus/').text
soup = BeautifulSoup(source, 'html.parser')
table = soup.find('tbody')
i = 3
for row in table.find_all_next(string=True)... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2017-01-30 23:31
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0011_content_position'),
]
operations = [
migrations.AlterField(
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "Zhangye"
# Date: 18-6-6
for i in range(7,0,-1):
print(i) |
from collections import Counter # importing the dict subclass Counter to count how many times
# each color appears and store the colors and their counts in a dictionary as keys and values
def matchingSocks(n, ar):
dictionary = Counter(ar) # using Counter which will store the colors as keys and their counts as ... |
# Generated by Django 3.2.4 on 2021-10-17 22:56
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0036_alter_guestlog_special_note'),
]
operations = [
migrations.AlterField(
model_name='guestlog',
... |
#!/usr/bin/env python
# coding=utf-8
import unittest
from epherousa.searchers.ExploitDB import ExploitDB
from epherousa.searchers.PacketStorm import PacketStorm
from epherousa.searchers.SecurityFocus import SecurityFocus
from epherousa.test.base_test import BaseTest
class TestSearcherCVE(BaseTest):
def setUp(se... |
class Employee(object):
def __init__(self, name, job_title, start_date):
self.name = name
self.job_title = job_title
self.start_date = start_date
def set_name(self, name):
self.name = name
def get_name(self):
return self.name
class Company(object):
"""This repr... |
#-*- coding: UTF-8 -*-
import re
from flask import render_template, request, redirect, url_for, json
from xichuangzhu import app, db
from xichuangzhu.models.work_model import Work, WorkImage, WorkReview
from xichuangzhu.models.author_model import Author
from xichuangzhu.models.dynasty_model import Dynasty
# pa... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Data Enlighten Technology (Beijing) Co.,Ltd
__author__ = 'ada'
import Lib.Logger.log4py as log
class Pinyin():
def __init__(self, data_path='./Mandarin.dat'):
self.dict = {}
for line in open(data_path):
k, v = line.s... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import math
import numpy
def distance(x1,y1,x2,y2) :
return math.sqrt((x1-x2)**2 + (y1-y2)**2)
def KNN(trainData, type, textData, K) :
s = []
T = {}
for i in range(len(trainData)):
s.append(distance(trainData[i][0],trainData[i][1],textData[0],textDa... |
#<ImportSpecificModules>
import ShareYourSystem as SYS
import numpy as np
import scipy.stats
from tables import *
import time
import operator
import os
#</ImportSpecificModules>
#<DefineLocals>
HookStr="Mul"
#</DefineLocals>
#<DefineClass>
class DistanceClass(SYS.ObjectsClass):
#<DefineHookMethods>
def initAfter(s... |
from django import forms
from geofr.constants import REGIONS, DEPARTMENTS
class RegionField(forms.ChoiceField):
"""Form field to select a single french region."""
def __init__(self, *args, **kwargs):
kwargs["choices"] = REGIONS
super().__init__(**kwargs)
class DepartmentField(forms.Choice... |
import torch
import time
from apex import amp
import os
import sys
import math
from utils import options, utils, criterions
from utils.ddp_trainer import DDPTrainer
from utils.meters import StopwatchMeter, TimeMeter
import data
from data import data_utils, load_dataset_splits
from models import build_model
import torch... |
from App.Mysql.MysqlTool import MysqlTool
class Error(MysqlTool):
"""
错误信息表
"""
_table = 'db_error'
|
class Node:
def __init__(self,dataval):
self.dataval=dataval
self.nextval=None
class Linkedlist:
def __init__(self):
self.headval=None
def printlist(self):
printval=self.headval
while printval!=None:
print(printval.dataval)
printval=printval.ne... |
from functions.microphone import listen_microphone
from kym import Kym
from sentence import Sentence
import pandas as pd
import sys
import os
training_data_path = "C:/Users/vitor/Documents/KYM/src/database/traindata.csv"
test_data_path = "C:/Users/vitor/Documents/KYM/src/test.txt"
kym = Kym(data_path=training_data_p... |
import sys
import math
#import mathutils
import random
import datetime
# Direction Map 1D
# =======
# 2 . 1
# =======
def nnX1D( i ):
if i == 1:
result = 1
elif i == 2:
result = -1
else:
result = 0
return result
# Direction Map 2D
# =======
# 2
# 3 . 1
# 4
# =======
def... |
from spikeextractors import RecordingExtractor
import numpy as np
from .basepreprocessorrecording import BasePreprocessorRecordingExtractor
from spikeextractors.extraction_tools import check_get_traces_args
class NormalizeByQuantileRecording(BasePreprocessorRecordingExtractor):
preprocessor_name = 'NormalizeByQua... |
# Copyright 2020-2021 Huawei Technologies Co., Ltd
#
# 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... |
import unittest
from dedupe import common
class TestConf(unittest.TestCase):
def test_not_null(self):
self.assertTrue(common.conf is not None)
if __name__ == '__main__':
unittest.main() |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import os
rep=os.walk('C:\\Users\\Sujji\\Assignment')
d1={}
for r,d,f in rep:
for file in f:
d1.setdefault(file,[]).append(r)
file_name=input('Enter the file name:')
for k,v in d1.items():
if file_name.lower() in k.lower():
for i in v:
... |
class Solution:
def validPalindrome(self, s):
left = 0
right = len(s) - 1
x = self.even(s, left, right)
y = self.odd(s, left, right)
return x or y
def even(self, s, left, right):
deleted = False
while left < right:
if s[left] != s[right]:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 29 12:22:31 2021
@author: xies
"""
import numpy as np
import pandas as pd
import matplotlib.pylab as plt
from skimage import io, util
from os import path
from tqdm import tqdm
import pickle as pkl
from measureSemiauto import measure_track_timese... |
import struct
PUMP_GPIO_NUM = 4
HEATER_GPIO_NUM = 4
SPIDEV = "/dev/spidev0.0"
def gpio_output_enable(number):
# Enable the GPIO for modification
# If GPIO is already exported, it will error out,
try:
f = open("/sys/class/gpio/export","w")
f.write(str(number))
f.close()
except IOError:
# GPIO alread... |
from setuptools import setup
setup(name='uluplot',
version='0.1.0',
description='Flexible map plot utility based on gmplot',
url='http://github.com/ulu5/uluplot',
author='ulu5',
author_email='ulu_5@yahoo.com',
license='MIT',
packages=['uluplot'],
install_requires=[
... |
import numpy as np
import pandas as pd
import pandas.util.testing as tm
import pytest
import ibis
from ibis.expr import datatypes as dt
from ibis.expr import schema as sch
pytestmark = pytest.mark.pandas
@pytest.mark.parametrize(
('column', 'expected_dtype'),
[
([True, False, False], dt.boolean),
... |
#!/usr/bin/python
import os
import sys
import time
# set django environment
from django.core.management import setup_environ
import settings
setup_environ(settings)
from django.template import Template, Context
from django.template.loader import *
def print_usage():
"""
display the help message to the user... |
import taichi as ti
import numpy as np
from matplotlib import cm
import os
cmap = cm.get_cmap('magma')
res = 256, 64, 64
#res = 1024, 256, 1
rho = ti.field(float, res)
vel = ti.Vector.field(3, float, res)
img = ti.field(float, (res[0], res[1]))
def load(frame):
path = f'/tmp/{frame:06d}.npz'
if not os.path... |
from typing import Iterable
from cimsparql.query_support import combine_statements, group_query
def _query_str(var_list: Iterable[str], rdf_type: str, connection: str) -> str:
select = "SELECT ?mrid " + " ".join([f"?{x}" for x in var_list])
where = [
f"?s rdf:type cim:{rdf_type}",
f"?s cim:{r... |
import sqlitedatastore as datastore
from annoutil import find_x_including_y, find_xs_in_y
if __name__ == '__main__':
datastore.connect()
anno_name = 'affiliation'
for doc_id in datastore.get_all_ids(limit=-1):
row = datastore.get(doc_id, fl=['content'])
text = row['content']
senten... |
#configuracion_module
from django.conf.urls import url
from django.contrib import admin
from django.views.generic import TemplateView
from django.contrib.auth.decorators import login_required
urlpatterns = [
url(r'^configuracion',
login_required(TemplateView.as_view(template_name="configuracion/configuracion... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.