text stringlengths 8 6.05M |
|---|
from elasticsearchModel import elastic
from collections import defaultdict
from clustering import cluster
from PCA import pca_model
from PIL import Image
import numpy
import os
def extract_X(uuid):
response = elastic.fetch_all_images(uuid)
img_names = []
for res in response['hits']['hits']:
for fi... |
###########################
# To run the interactive data explorer
# Check if streamlit is installed in conda env
# Or run $ conda install -c conda-forge streamlit
# Run $ streamlit run data_explorer.py
###########################
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import ... |
import unittest
import chainer
from chainer import testing
import numpy as np
from tests.helper import ONNXModelTest
@testing.parameterize(
{'in_shape': (3, 5), 'name': 'softmax_cross_entropy'},
)
@unittest.skipUnless(
int(chainer.__version__.split('.')[0]) >= 6,
"SoftmaxCrossEntropy is supported from C... |
# This is the weirdest LCA implementation you will probably ever see (due to Python append array)
N, Q = map(int, input().split())
adj = [[] for _ in range(N)]
for i in range(N-1):
a, b = map(int, input().split())
adj[a-1].append(b-1)
adj[b-1].append(a-1)
MAX_LCA = 18
lcaArr = [[] for _ in r... |
import fnmatch
import importlib
import inspect
import sys
from dataclasses import dataclass
from enum import Enum
from functools import partial
from inspect import signature
from types import ModuleType
from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Set, Type, TypeVar, Union
from torch impo... |
# coding: utf-8
import time
import os
def bytes2human(n):
symbols = ('K','M','G','T','P','E','Z','Y')
prefix = {} ... |
import numbers
import random
import datetime
from faker import Faker
from PBD.data import *
fake = Faker()
allClients = list()
allConferences = list()
allConferenceDays = list()
allWorkshops = list()
allConferenceReservations = list()
allConferenceDayReservations = list()
allThresholds = list()
allParticipants = li... |
import util
import os
import fnmatch
def getCsvsFiles():
pattern = "*.csv"
holds = []
path = util.getPath('toscrub')
listOfFiles = os.listdir(path)
for entry in listOfFiles:
if fnmatch.fnmatch(entry, pattern):
holds.append("{}/{}".format(path,entry))
return holds
def c... |
import uuid
from gridfs import GridFS
from pymongo import MongoClient
from datetime import datetime
from bson import Binary
from io import BytesIO
import os
class NoFileException(Exception):
pass
class WrongTypeException(Exception):
pass
class FileManager:
mongoclient = MongoClient(host='172.17.0.1', po... |
from dash_bootstrap_components import __version__
def test_version():
assert __version__ == "1.5.0-dev"
|
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
if rank == 0:
data = {'key1' : [7, 2.72, 2+3j],
'key2' : ( 'abc', 'xyz')}
else:
data = None
data = comm.bcast(data, root=0)
|
import sys
import logging
import traceback
import warnings
from importlib import import_module
logger = logging.getLogger(__name__)
EXTRAS = ["h5py", "z5py", "pyn5", "PIL", "imageio"]
__all__ = ["NoSuchModule"] + EXTRAS
class NoSuchModule(object):
def __init__(self, name):
# logger.warning('Module {} ... |
from PyQt5.QtWidgets import QWidget, QApplication, QPushButton, QLabel
from PyQt5.QtGui import QPainter, QFont, QImage
from PyQt5.QtCore import Qt, QCoreApplication
from modules import gamefield as g, bomb as b
import sys
import time
from os.path import *
class Menu(QWidget):
def __init__(self, pare... |
# Necessary Imports
from django.db import models
from datetime import date
from django.urls import reverse # Used to generate URLs by reversing the URL patterns
from django.contrib.auth.models import User # Blog author or commenter
from ckeditor.fields import RichTextField
# Create your models here.
class BlogAutho... |
person = {}
print(person)
print(person == {})
# person = {
# "name" : "le duc viet"
# }
# person = {
# "name" : "le duc viet",
# "age" : 16,
# }
# print(person)
# print(person == {})
# person = {
# "name" : "le duc viet",
# "age" : 16,
# }
# print(person)
# person["status"]= "... |
#!/usr/bin/env
# encoding: utf-8
"""
Created by John DiBaggio on 2018-07-28
Find the Reverse Complement of a String
In DNA strings, symbols 'A' and 'T' are complements of each other, as are 'C' and 'G'. Given a nucleotide p, we denote its complementary nucleotide as p. The reverse complement of a DNA string Pattern =... |
import coreir
import os
def test_genargs():
context = coreir.Context()
mod = context.load_from_file(os.path.join(os.path.dirname(os.path.realpath(__file__)), "genargs.json"))
for instance in mod.definition.instances:
assert instance.module.generator_args["width"].value == 4
if __name__ == "__mai... |
#!/usr/bin/env python
# Script by Steven Grove (@sigwo)
# www.sigwo.com
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTH... |
#!/usr/bin/env python3
from ipaddress import IPv6Address
import sys
def mcast_mac(address):
sixmcast = IPv6Address(address)
x = int(sixmcast) & 0xffffffff
mac = x + 0x333300000000
return ( "{}:{}:{}:{}:{}:{}".format(hex(mac)[2:][0:2],
hex(mac)[2:][2:4],
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 1 12:15:48 2017
@author: Elliott
"""
#!/usr/bin/env python
import sys
import json
from nltk.corpus import wordnet as wn
## GETTING INFO FROM TERMINAL (JSON)
## sys.argv is list where 1st item is path of this file, 2nd, 3rd,...,nth are passed in arguments
#for string i... |
# Generated by Django 3.1.4 on 2020-12-27 12:43
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('Game', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='player',
name='asd',
),
]
|
# -*- coding: utf-8 -*-
class Solution:
def missingNumber(self, nums):
return len(nums) * (len(nums) + 1) // 2 - sum(nums)
if __name__ == "__main__":
solution = Solution()
assert 2 == solution.missingNumber([3, 0, 1])
assert 8 == solution.missingNumber([9, 6, 4, 2, 3, 5, 7, 0, 1])
|
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sys
from tqdm import tqdm
from sklearn.svm ... |
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.core import serializers
# Create your views here.
from .models import... |
'''
Created on Oct 19, 2010
@author: Jason Huang
'''
import bson
import pymongo
import datetime
import tornado.web
import simplejson
import MongoEncoder.MongoEncoder
from Users.Message import MessageHandler
from BrowseTripHandler import BaseHandler
from Auth.AuthHandler import ajax_login_authentication
... |
import pandas as pd
import sqlite3
# --- LOAD THE SOURCE DATA SETS TO DATA FRAMES
# get list prices data from github
df_list_prices = pd.read_csv(
'https://raw.githubusercontent.com/gygergely/PythonPandas/master/00_src_files/list_prices.csv',
parse_dates=['valid_from', 'valid_to'],
dtype={'product_id': 's... |
from setuptools import setup, find_packages
with open('README.rst','r') as f:
long_desc = f.read()
setup(
name='wikitable',
version='0.0.6',
description='Converts Wikipedia tables to dataframes and CSVs',
py_modules=["wikitable"],
packages=find_packages(),
install_requires=[
'reques... |
#!/usr/bin/python
import sys
import eventlet
import shlex
import os
import traceback
import subprocess
ircbot = eventlet.import_patched('ircbot')
irclib = eventlet.import_patched('irclib')
from irclib import irc_lower, ServerConnectionError, ip_quad_to_numstr, ip_numstr_to_quad, nm_to_n, is_channel
import commands
... |
#!/usr/bin/env python
import subprocess
import re
def passwd():
ignore = ('nfsnobody')
infile = open("/etc/passwd", 'r')
lines = infile.readlines()
# declare empty dictionary
passwd = { }
for line in lines:
field=line.split(":")
user, userid, userdir = field[0], field[... |
from src.nlpTool.contentClean import cleanArticle
from src.nlpTool.paragraphSplit import splitTextIntoParagraphList
from src.nlpTool.sentenceSplit import splitTextIntoSentences
from src.nlpTool.wordSegment import splitSentenceIntoWords
from src.entity.article import Article
import time
if __name__ == '__main__':
ar... |
def band_name_generator(n):
return n.capitalize() + n[1:] if n[0]==n[-1] else 'The ' + n.capitalize()
'''
My friend wants a new band name for her band. She like bands that use the formula:
"The" + a noun with the first letter capitalized, for example:
"dolphin" -> "The Dolphin"
However, when a noun STARTS and EN... |
# coding: utf-8
import json
import watson_developer_cloud
# BEGIN of python-dotenv section
from os.path import join, dirname
from dotenv import load_dotenv
import os
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
# END of python-dotenv section
discovery = watson_developer_cloud.DiscoveryV1(
... |
import numpy as np
import pyaudio
import effects
def sinusoid(amp: float, freq: float, phs: float, fs: float, duration: float) -> list:
return amp*np.sin(2*np.pi*np.arange(fs*duration)*(freq/fs)+phs).astype(np.float32)
def play(xn: list, fs: float):
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paFlo... |
from mmvizutil.db.query import (
Query
)
def query_box(q):
query = Query()
query.parameters = q.parameters
query.value = """
select min(num_1) num_1_min,
PERCENTILE_DISC(0.25) WITHIN GROUP (ORDER BY num_1) num_1_25,
median(num_1) num_1_50,
PERCENTILE_DIS... |
def decor(say_happy):
def wrapper():
print("\n")
say_happy()
return wrapper
@decor
def say_happy():
print("I am happy")
say_happy()
|
import matplotlib.pyplot as plt
import numpy as np
x = np.random.randn(1000)
plt.title("histogram")
plt.xlabel("random data")
plt.ylabel("freqiency")
plt.hist(x,10)
plt.show()
|
from django.conf.urls import patterns,url
#from django.conf.urls import url
from app.views import *
urlpatterns = patterns('',
url(r'^login/',loginUsuario,name='loginUsuario',),
url(r'^fetch_data/', fetch_data, name='get_data'),
url(r'^home/(?P<anystring>.+)/', homeView,name='homeView',),
)
|
from enum import IntEnum
class KeyBind(IntEnum):
FileNew = 0
FileSave = 1
FileSaveAs = 2
FileOpen = 3
FileClose = 4
Undo = 5
Redo = 6
Delete = 9
Copy = 10
Paste = 11
IncGridSize = 12
DecGridSize = 13
Toggle2DGrid = 14
Toggle3DGrid = 15
ToggleGridSnap = 16... |
import os
import time
print("Howdy.")
time.sleep(2)
os.system('clear')
print("We have assumed control of your computer. Resistance is futile.")
time.sleep(3)
print(''' ```''')
time.sleep(.5)
print(''' (`/\\''')
time.sleep(.5)
print(''' `=\/\\''')
time.sleep(.5)
print(''' `=\/\\''')
time.sleep(.5)
print... |
'''
15. 3Sum
Given an array S of n integers, are there elements a, b, c in S such that
a + b + c = 0? Find all unique triplets in the array which gives the sum of
zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
... |
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
#辅助管理-读卡器配置
_chrome_path = 'C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe'
url = 'http://192.168.128.234/masi-medicare-settlement-web/web/medicare/settlement/common/homepage/index.html'
driver = webdriver.Ch... |
#!/usr/bin/python3
''' I/O module '''
def pascal_triangle(n):
''' Returns a list of lists of integers representing
the Pascal’s triangle of n.
'''
if n <= 0:
return []
p_tri = []
for row in range(n + 1):
row_list = []
for col in range(row):
if col == 0 ... |
#!/usr/bin/env python
""" Example for analyse URIs for detect a Jboss attack
A detail explation of the attack is under http://www.deependresearch.org/
"""
import sys
import os
import base64
import pyaiengine
def callback_uri(flow):
""" This callback is called on every http request to the server """
pr... |
"""
Tests of neo.io.hdf5io_new
"""
import unittest
import sys
import numpy as np
from numpy.testing import assert_array_equal
from quantities import kHz, mV, ms, second, nA
try:
import h5py
HAVE_H5PY = True
except ImportError:
HAVE_H5PY = False
from neo.io.hdf5io import NeoHdf5IO
from neo.test.iotest.co... |
#! /usr/bin/python
from flask import Flask, render_template, request, url_for, flash, redirect, jsonify
from pytrends.request import TrendReq
app = Flask(__name__)
app.secret_key = "whatever floats your boat"
# Connect to Google with pytrends
pytrend = TrendReq(hl='en-US', tz=360)
# Views
@app.route('/', methods = ... |
# -*- coding: utf-8 -*-
from rest_framework import serializers
from .models import Category, Item
class ItemSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Item
fields = ('id', 'name', 'categories', 'value_int', 'value_float')
class CategorySerializer(serializers.Hyperli... |
#!/usr/local/bin/python3
# -*- conding: utf-8 -*-
import base64
import hashlib
from config import Config
import smtplib
from email.utils import parseaddr, formataddr
from email.header import Header
from email.mime.text import MIMEText
from flask import request, jsonify
from flask_sqlalchemy import SQLAlchemy
from fl... |
from os import system
class Leitura:
def __init__(self):
self.__dados= open('dados.txt').readlines()
self.__db = {}
try:
self.__upload()
except ValueError:
raise ValueError('dados corompidos')
def __upload(self):
if self.__dados == []:
self.__db['palavras'] = 4
self.__db['ppm'] = 200
s... |
from dask.array import stats
import re
import argparse
from numba import njit, vectorize
from dklearn.pipeline import Pipeline
from dklearn.grid_search import GridSearchCV
import dask.bag as db
import dask.dataframe as dd
import dask.array as da
import dask
from os import path
from scipy.sparse import csr_matrix, triu
... |
from aiogram import types
test = types.ReplyKeyboardMarkup(
keyboard=[
[
types.KeyboardButton(text="/items"),
types.KeyboardButton(text="/herou"),
types.KeyboardButton(text="/guide"),
types.KeyboardButton(text="/help"),
types.KeyboardButton(te... |
# 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 u... |
from collections import defaultdict, deque, Counter
from heapq import heapify, heappop, heappush
import sys
import math
import random
import string
from copy import deepcopy
from itertools import combinations, permutations, product
from bisect import bisect_left, bisect_right
def input():
return sys.stdin.readline... |
def summation(x):
return sum(xrange(1, x + 1)) if isinstance(x, int) else 'Error 404'
|
import sqlite3
file_name = input()
con = sqlite3.connect(file_name)
cur = con.cursor()
result = cur.execute(f'''select title from films where title like "%Астерикс%"
and not title like "%Обеликс%"''')
for elem in result:
print(elem[0]) |
# -*- coding: utf-8 -*-
"""Parser for the API."""
from collections import OrderedDict
from json import loads
from django.conf import settings
from django.utils.six import text_type
from rest_framework.exceptions import ParseError
from rest_framework.parsers import JSONParser as BaseJSONParser
class JSONParser(BaseJS... |
import pandas as pd
import numpy as np
import csv
import os
import const
def run_benchmark_cnn():
import sys
sys.path.append("/content/drive/My Drive/capstone1/CAN/torch2trt") # https://github.com/NVIDIA-AI-IOT/torch2trt
from torch2trt import torch2trt
import model
import time
import torch
... |
#!/usr/bin/python3.6
import requests
import sys
import json
def make_turn(turn_payload, token, count) -> bool:
turn_payload['turn_x'] = 0
turn_payload['turn_y'] = count
turn_text = requests.post(f'{API_URL}/game/turn', json=turn_payload).text
turn = json.loads(turn_text)
print('My turn: ' + turn... |
import re
# функция принимает имя лога и событие, которое нужно отслеживать
def parsLog(log, event):
try:
# результирующий массив структур
arResult = []
# словарь, который будет заполняться и обнуляться при каждом новом появлении события
objStruct = {}
with open(l... |
from _collections import defaultdict
bands = {}
bands_time = defaultdict(int)
while True:
tokens = input()
if tokens == "start of concert":
break
tokens = tokens.split("; ")
command = tokens[0]
if command == "Add":
band_name, members = tokens[1], tokens[2]
members = member... |
#!/usr/bin/env python
# encoding: utf-8
"""
Created by 'bens3' on 2013-06-21.
Copyright (c) 2013 'bens3'. All rights reserved.
python tasks/artefact.py ArtefactDatasetAPITask --local-scheduler
"""
import luigi
from ke2mongo import config
from ke2mongo.tasks import DATASET_LICENCE, DATASET_AUTHOR, DATASET_TYPE
from k... |
""" script to display the different interaction channels from Julia's GENIE simulation in a bar chart:
The original GENIE root file of Julia is read with "read_GENIE_file.py" and the fractions of the interaction
channels for the different isotopes are saved in file "interaction_channels_qel_NC_201617evts.txt".... |
bino = int(input())
cino = int(input())
print('Bino' if ((bino + cino) % 2 == 0) else 'Cino')
|
# -*- coding: utf-8 -*-
import cloud
class RTCoreRequest(object):
"""A wrapper class that requests real-time cores to PiCloud.
Usage:
>>> from picrawler.rt_cores import RTCoreRequest
>>> with RTCoreRequest(core_type='s1', num_cores=10):
... pass
:param str core_type: The PiC... |
n=int(input())
for i in range(n+1):
for j in range(i):
print("*",end=" ")
print()
# added a new line
#added one more line |
import psycopg2
import numpy as np
try:
conn = psycopg2.connect(user = "postgres",
password = "123",
host = "127.0.0.1",
port = "5432",
database = "test")
for i in np.arange(1000):
my... |
# -*- coding: utf-8 -*-
class Solution:
def findDuplicates(self, nums):
result = []
for num in nums:
i = abs(num) - 1
if nums[i] > 0:
nums[i] = -nums[i]
else:
result.append(abs(num))
return result
if __name__ == "__mai... |
import os,nmap
import socket,thread,threading
import urllib2
import time
import download_dhaga
rurl='' #download link
fname='' #file to be saved as
ext='' #extension of file
myip='' #ip extension of my node
live_ips=[]
size=''
yescount=0
th=[]
def handleclient(connsocket,start,end,i):
global rurl
msg=rurl+' '+s... |
from constant import INT_SIZE, INT_REPR
class LogicClock:
def __init__(self, n_instance, instance_id, zero_fill=False):
self.n_instance = n_instance
self.instance_id = instance_id
self._clock = [-1] * n_instance
if zero_fill:
self._clock = [0] * n_instance
def __re... |
# num = int(input("구구단을 외자! 17 x 5 = "))
# if num == 17 * 5:
# print("정답! 똑똑해")
# else:
# print("실망이야...")
#elif를 배우고 해결해봅시다
# money = int(input("밥 뭐먹지? 돈 얼마있어? : "))
# if money >= 50000:
# print("소고기 먹으러 가자")
# if money >= 30000:
# print("돼지고기 먹자")
# if money >= 10000:
# print("쟈니로켓 먹... |
import numpy as np
import pandas as pd
import warnings
from sklearn.base import is_regressor, is_classifier
from scipy.stats import norm
from statsmodels.stats.multitest import multipletests
from abc import ABC, abstractmethod
from .double_ml_data import DoubleMLData, DoubleMLClusterData
from ._utils_resampling im... |
import numpy as np
import tensorflow as tf
from game import Game
from randomBot import RandomBot
class ReinforcementBot:
def __init__(self):
self.discountFactor = 0.9
self.buildNet()
self.observeGames(10000, 100)
def buildNet(self):
self.net = tf.keras.models.Sequential()
... |
# Import the random package to radomly select individuals
import random
# Import the numpy package for the circular list
import numpy as np
# Import the superclass (also called base class), which is an abstract class,
# to implement the subclass ThresholdSelection
from SelectionOperator import *
# Import the circula... |
import pymongo
from pymongo import MongoClient
from pymongo import IndexModel, ASCENDING, DESCENDING
import time
import hashlib
import sys
class MongoUrlManager:
def __init__(self, mongo_ip='localhost', mongo_port=27017,
client=None, database_name='Zaojv', table_name='zaojv_items')... |
#coding:gb2312
#写入文件
filename = 'write.txt'
with open(filename,'w') as f:
"""
'r'--读取模式
'w'--写入模式
'a'--附加模式
' r+'--读取和写入文件模式
"""
f.write("I love python!\n")
f.write("Python is very useful!")
|
def Rcalculator():
A_string=raw_input("Please Enter the area of the wall (in m2):\n ")
R_tot=0
U=0
n_layer_string=raw_input("Please Enter the total number of layers \n ")
n_parallel_string=raw_input("Please Enter the total number of parallel layers \n ")
n_layer=int(n_layer_string)
A=flo... |
import boto
localIP=boto.utils.get_instance_metadata()['local-ipv4'][1]
region=boto.utils.get_instance_metadata()['local-hostname'].split('.')[1]
hostname=boto.utils.get_instance_metadata()['local-hostname']
|
def test_helper_clear_groups(db):
cursor = db.connection.cursor()
cursor.execute("DELETE FROM group_list")
cursor.close()
def test_helper_clear_contacts(db):
cursor = db.connection.cursor()
cursor.execute("DELETE FROM addressbook")
cursor.close()
def test_helper_clear_relations(db):
curso... |
from collections import defaultdict, deque, Counter
from heapq import heapify, heappop, heappush
import math
from copy import deepcopy
from itertools import combinations, permutations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
import sys
def input():
return sys.stdin.readl... |
import os,sys,time
from subprocess import *
import datetime,time
import threading
### This script do auto testing before release code.
test_list = ["mnist_f", "mnist_q", "mbnet_f", "mbnet_q"]
def runcmd(cmd):
r=Popen(cmd,stdin=PIPE,stdout=PIPE,stderr=PIPE, shell=True)
a=[]
for line in r.stdout.readlines... |
import os; dirname = os.path.abspath(os.path.dirname(__file__))
import sys; sys.path.append(os.path.join(dirname, 'image-similarity-clustering'))
from flask import Flask, flash, redirect, render_template, request, send_from_directory, url_for
from werkzeug.utils import secure_filename
from features import extract_f... |
# In the section on Functions, we looked at 2 different ways to calculate the factorial
# of a number. We used an iterative approach, and also used a recursive function.
#
# This challenge is to use the timeit module to see which performs better.
#
# The two functions appear below.
#
# Hint: change the number o... |
# -*- coding: utf-8 -*-
"""
Practical core of application - configuration and student's choices.
"""
from datetime import datetime
from django.db import models
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from app.a... |
"""
CCT 建模优化代码
工具集
作者:赵润晓
日期:2021年6月7日
"""
import os
import sys
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
PathProject = os.path.split(rootPath)[0]
sys.path.append(rootPath)
sys.path.append(PathProject)
from cctpy import *
R = 0.95
bl = (
Beamline.set_start_point... |
from shapely.geometry import Polygon, Point
import numpy as np
from functions.plot_manager import save_discarded_homography
from objects.constants import Constants
from functions.rgb_histogram_matching import evaluete_homography
from objects.homography import Homography
class Ratio:
def __init__(self, Hom, rati... |
# -*- coding: utf-8 -*-
# @Time : 2020/5/23 18:45
# @Author : J
# @File : 图像入门.py
# @Software: PyCharm
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
# 读取图像
img = cv.imread("../image.jpg",0) # 1是彩色图像 0是灰度图 -1是原始图像
cv.imshow("image",img)
cv.waitKey(0)
cv.destroyAllWindows()
#... |
def foobar(li):
for item in li:
if item % 15 == 0:
print('foobar')
elif item % 5 == 0:
print('bar')
elif item % 3 == 0:
print('foo')
else:
print(item)
my_list = []
for i in range(1,35001):
my_list.append(i)
foobar... |
import ROOT
from array import array
import re
import json
import os
import subprocess
import argparse
from compare import scatter
def makeNtuple(file_in, file_out):
print "Input file: {0}".format(file_in)
print "Output file: {0}".format(file_out)
with open("barcode.json", 'r') as b:
barco... |
"""Search UniProt for GO codes."""
import logging
import requests
import pandas as pd
_LOGGER = logging.getLogger(__name__)
SEARCH_GO_URL = "https://www.uniprot.org/uniprot/?query=database:pdb+go:{go}&format=tab&columns=id,entry name,protein names"
SEARCH_ID_URL = "https://www.uniprot.org/uniprot/?query=database:pdb+... |
from django.conf.urls import url
from django.contrib import admin
from django.views.generic import TemplateView
from .views import (
IndexView,
)
app_name = 'api'
urlpatterns = [
url(r'^$', IndexView, name='index'),
]
|
import bisect
import random
def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
i = bisect.bisect(breakpoints, score)
return grades[i]
def insort():
my_list = []
for _ in range(10):
number = random.randrange(20)
bisect.insort(my_list, number)
return my_list
if __nam... |
"""
Copyright 1999 Illinois Institute of Technology
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publis... |
"""
Models for the MVC setup of the Azzaip applications. Defines the
means by which the application interfaces with the database.
"""
import datetime
from django.db import models
class Message(models.Model):
"""
A single Azzaip post with all relevant fields.
"""
author_uri = models.CharField(max_len... |
from binascii import hexlify, unhexlify
from datetime import datetime, timedelta
import ecdsa
b58_digits = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def encode58(b):
"""Encode bytes to a base58-encoded string"""
# Convert big-endian bytes to integer
n = int('0x0' + hexlify(b).decode('... |
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import dataclasses
import itertools
import os.path
from dataclasses import dataclass
from pathlib import PurePath
from textwrap import dedent
from typin... |
# 本脚本实现了 5.3.1 节的 *不使用数据增强的快速特征提取* 算法
from keras.applications import VGG16
import os
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from keras import models
from keras import layers
from keras import optimizers
import matplotlib.pyplot as plt
conv_base = VGG16(weights='imagenet',
... |
from selenium import webdriver
from time import sleep
# import xlrd
import random
import os
import time
import sys
sys.path.append("..")
# import email_imap as imap
# import json
import re
# from urllib import request, parse
from selenium.webdriver.support.ui import Select
# import base64
import Chrome_driver
import em... |
#-*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
class Autor(models.Model):
usuario = models.OneToOneField(User, verbose_name = 'Usuário')
class Meta:
verbose_name_plural = 'Autores'
db_table = 'blog_autor'
def __unicode__(self):
ret... |
from heapq import *
def solution(operations):
answer = []
heapify(answer)
check = 0
for i in operations:
if i[0] == 'D' and check == 0:
continue
else:
if i[0] == 'I':
heappush(answer, int(i[2:]))
check += 1
elif i[0] =... |
#!/usr/bin/env python3
import time
import mpd
def connect_client():
"""Connect to MPD Client"""
client = mpd.MPDClient()
client.connect("localhost", 6600)
return client
def get_pl_tuples(client):
pl_tuples = []
for song in client.playlistinfo():
mytuple = (song["id"], song["album"])
... |
from GameLogic.Character import *
from GameLogic.MapHelpers import getAroundingTiles
def getUnitPrice(unitType, character):
from GameLogic.Unit import Soldier, Robot, Tank, Boat
if unitType is Soldier:
if type(character) is IceCharacter:
return 120
else:
return 150
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.