text stringlengths 8 6.05M |
|---|
"""
Compute numerical derivatives on a non-uniform (but strictly increasing) grid,
using quadratic Lagrangian interpolation to generate the difference matrix.
"""
import numpy as np
from scipy.sparse import csr_matrix
def differenceMatrix(x):
"""Generates the difference matrix for a non-uniform (but strictly
... |
#!/usr/bin/env python
# Funtion:
# Filename:
import urllib.request
file = urllib.request.urlopen("http://www.baidu.com")
data = file.read()
dataline = file.readlines()
# print(dataline)
# print(data)
fhandle = open("baidu.html", "wb")
fhandle.write(data)
fhandle.close() |
# !/usr/bin/python
"""
-----------------------------------------------
Versions File in WIP Directory
Written By: Colton Fetters
Version: 1.4
First release: 12/2017
-----------------------------------------------
DEVELOPER NOTES: Queries the status of maya file and
determines whether o... |
#!/usr/bin/python
#\file lambda_local.py
#\brief test lambda with local variable.
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Feb.21, 2017
'''This code is written for understanding a strange behavior of lambda. See
https://stackoverflow.com/questions/42380951/python-using-lambda-as-thre... |
../rbtree.py |
import pygame
import random
import os
pygame.init()
window_size = (1600, 1000)
screen = pygame.display.set_mode(window_size)
bgmap = pygame.Surface((16000,16000))
parhFileNames = []
searchPath = ["/home/"]#検索したいpathを設定
def fileSearch():
esw=0
while len(searchPath)>0 and esw==0:
try:
ld = ... |
inorder = ["D", "B", "E", "A", "F", "C"]
preorder = ["A", "B", "D", "E", "C", "F"]
preorderIndex = 0
class Node:
def __init__(self, data):
self.key = data
self.left = None
self.right = None
def find_element(inorder, inorderStart, inorderEnd, key):
while inorderStart <= inorderEnd:
... |
#extract all cuisines
#create a matrix with restaurat id as rows and cuisines as cols
import pandas as pd
import numpy as np
import os
pd.set_option('display.mpl_style', 'default') # Make the graphs a bit prettier
def get_cuisine_info():
base_dir = os.path.dirname(os.path.realpath('__file__'))
business_file... |
# coding: utf8
# Ferran March Azañero
# 08/02/2018
mano_der="Movil"
mano_izq="Bocadillo"
mano_temp=mano_der
mano_der=mano_izq
mano_izq=mano_temp
print mano_izq
print mano_der
print mano_temp
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: wdf
# datetime: 9/28/2020 8:23 PM
# software: Windows 10 PyCharm
# file name: 暴力破解rar和zip密码.py
# description: 公众号【特里斯丹】
# usage:
# 安装所需三方库: pip install zipfile rarfile
class Passward():
def _... |
#If we list all the natural numbers below 10 that are multiples of 3 or 5,
# we get 3, 5, 6 and 9.
#The sum of these multiples is 23.
#
#Find the sum of all the multiples of 3 or 5 below 1000.
from Generators import get_number_from_user
from Generators import euler_one_generator
print(euler_one_generator(get_number_... |
import configparser as cp
from pyspark import SparkConf
class SparkConfiguration:
@staticmethod
def getSparkConf():
sparkConf = SparkConf()
conf = cp.ConfigParser()
conf.read(r"application.properties")
for key,value in conf.items("SPARK_APP_CONFIGS"):
sparkConf.set(ke... |
#import sys
#input = sys.stdin.readline
def main():
s = input()
k = int( input())
t = set()
for i in range(len(s)-k+1):
t.add(s[i:i+k])
print(len(t))
if __name__ == '__main__':
main()
|
# https://www.hackerrank.com/challenges/list-comprehensions/problem
if __name__ == '__main__':
x = int(input())
y = int(input())
z = int(input())
n = int(input())
result = []
for i in range(x+1):
for j in range(y+1):
for k in range(z+1):
if(i+j+k != n):
... |
import pandas as pd
import pickle
import streamlit as st
from PIL import Image
st.set_page_config(
# page_icon='NONE',
initial_sidebar_state='expanded'
)
st.title('r/wallstreetbets or r/SatoshiStreetBets? Predicting the Subreddit of a Post Using NLP')
st.write('**Disclaimer:** I am not a financial advisor. I am in ... |
'''
Methods that facilitate testing with mocks by enabling the usage of a failure message.
Created on 27.08.2018
@author: FM
'''
from collections import namedtuple
import types # get access to types such as function or method)
## TODO: create class MockAssertionError and implement a string method for bette... |
#!/usr/bin/python
import sys #don't know
import cPickle #file input and output
import collections #used for Counter
# def bracketSwitcher(i, hero): #Used to change the input file so all three brackets are tested sequentially
# baseStr = '[' + hero + '678]'
# baseStr = '[6.79... |
# -*- coding: utf-8 -*-
# This file as well as the whole tsfresh package are licenced under the MIT licence (see the LICENCE.txt)
# Maximilian Christ (maximilianchrist.com), Blue Yonder Gmbh, 2016
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from tsfresh import defaults
from tsfresh.fe... |
import requests
ID = 1
# RUN = True
class CaptchaService:
def __init__(self, key, sitekey, url):
self.id = ID
self.key= key
self.data = {
'key' : key,
'method' : 'userrecaptcha',
'googlekey' : sitekey,
'pageurl' : url,
'json' : '1'
}
def get(self):
s = requests.Session()
... |
Your input
2736
Output
7236
Expected
7236
Your input
9973
Output
9973
Expected
9973 |
from itertools import product
N = int( input())
ans = 0
for i in range(3,10):
for x in product("357", repeat = i):
z = ""
V = [0]*10
for l in x:
z += l
V[ int( l)] = 1
if int(z) <= N and sum(V) == 3:
ans += 1
print(ans)
|
# -*- coding: utf-8 -*-
import re, json
import MySQLdb
import sys, argparse
reload(sys)
sys.setdefaultencoding('utf-8')
def trunc_db(conn):
cur = conn.cursor()
cur.execute('SET NAMES utf8')
cur.execute("TRUNCATE TABLE ModelViews")
conn.commit()
cur.close()
def batch_insert(conn... |
from config import app
from routes import *
#Rodar Programa ao executar esse módulo
if __name__ == '__main__':
app.run(debug=True)
|
"""
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入:[3,2,3]
输出:3
示例 2:
输入:[2,2,1,1,1,2,2]
输出:2
进阶:
尝试设计时间复杂度为 O(n)、空间复杂度为 O(1) 的算法解决此问题。
Related Topics 位运算 01-数组 分治算法
"""
def majority_element(nums):
nums.sort()
return nums[len(nums) // 2]
majority_elemen... |
import plotly.graph_objects as go
import plotly.offline as po
from plotly.subplots import make_subplots
from datetime import datetime
import pandas as pd
import argparse
import pickle
import os
import warnings
import plotly.graph_objects as go
import plotly.offline as po
from plotly.subplots import make_subplots
warni... |
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('cr7.jpg')
color = ('b','g','r')
for i,col in enumerate(color):
hist = cv2.calcHist([img],[i],None,[256],[0,256])
plt.plot(hist,color = col)
plt.xlim([0,256])
plt.show() |
import numpy as np
import scipy.optimize as opt
# 矩阵权重随机初始化
# theta1(25, 101) theta2(3, 26)
def random_init(shape1, shape2):
theta1 = np.random.uniform(-0.12, 0.12, shape1)
theta2 = np.random.uniform(-0.12, 0.12, shape2)
return theta1, theta2
def sigmoid(z):
return 1. / (1. + np.exp(-z... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
PAD_WORD_ID = 0
UNK_WORD_ID = 1
END_WORD_ID = 2
PAD_CHAR = 261
BOW_CHAR = 259
EOW_CHAR = 260
ALM_MAX_VOCAB_SIZE = 20000
class bcolors:
HEADER = "\033[95m"
OKBLUE = "\033[94m"
OKGREEN = "\033[92m"
WARNING = "\033[93m"
FAIL ... |
# --------------------------------------------------------------------
import os
import functools
# --------------------------------------------------------------------
transposed = []
matrix = [[1, 2, 3, 4], [4, 5, 6, 8]]
for i in range (len (matrix[0])): # Loop over row length (outer loop)
transposed_row = []... |
#VBO/IBO/DSC Model Writing from Blender
import zipfile
import struct
import sys
import os
try:
import zlib
compression = zipfile.ZIP_DEFLATED
except:
compression = zipfile.ZIP_STORED
print("\n*** Welcome to Tiger/Line Zip Reader. ***\n")
print("Running in",sys.argv[0])
print(sys.versio... |
from setuptools import setup, find_packages
from openspending.ui import __version__
setup(
name='openspending',
version=__version__,
description='OpenSpending',
author='Open Knowledge Foundation',
author_email='okfn-help at lists okfn org',
url='http://github.com/okfn/openspending',
instal... |
# -*- coding: utf-8 -*-
# Copyright (c) 2014 Plivo Team. See LICENSE.txt for details.
import unittest
import ujson as json
from sharq_server import setup_server
class SharQServerTestCase(unittest.TestCase):
def setUp(self):
# get test client & redis connection
server = setup_server('./sharq.conf'... |
{
### Finance ###
"aidBill": {
W3Const.w3ElementType: W3Const.w3TypeApi,
W3Const.w3ApiName: "bill",
W3Const.w3ApiParams: [
{
W3Const.w3ApiDataType: W3Const.w3ApiDataTypeString,
W3Const.w3ApiDataValue: "from"
},
{
W3Const.w3... |
import pygame
class GameObject:
"""
An abstract class laying the foundation for all objects in the engine
"""
def __init__(self):
"""
GameObject Constructor
Returns a GameObject object.
TODO: set default values for position, dimension and velocity as optional parameter... |
from spidev import SpiDev
import RPi.GPIO as GPIO
import time
import logging
#############################################################################
# ADC 컨버터 함수 설정
class MCP3008:
def __init__(self, bus = 0, device = 0):
self.bus, self.device = bus, device
self.spi = SpiDev()
self.ope... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
# Reto:
"""
Reto #5 “Suma y multiplicación”
Instrucciones: añadiendo un extra al reto anterior ahora el usuario ingresará 3 números,
sumarás los 2 primeros y el resultado será multiplicado por el tercero.
Añade las consideraciones del punto decimal del reto anterior.
Eje... |
from typing import List
from pymongo.collection import Collection
from filemanager.dao.file import File
class FileListDao:
def get_all_files(self):
pass
def get_all_files_by_ids(self,file_ids:List[str]):
pass
class FileListMongoDBDao(FileListDao):
def __init__(self,collection:Collection... |
# Copyright 2018 Jae Yoo Park
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
def a() :
pass
def b() :
return '올라프'
def c(p) :
return p * 3
def d(p) :
if p == 1 :
return True
else :
return False
result1 = a()
result2 = b()
result3 = c('올라프')
result4 = c(10)
result5 = d(1)
result6 = d(2)
print(result1)
print(result2)
print(result3)
print(result4)
print(re... |
# -*- coding=utf-8 -*-
"""The plugin of the pytest.
The pytest plugin hooks do not need to be imported into any test code, it will
load automatically when running pytest.
References:
https://docs.pytest.org/en/2.7.3/plugins.html
"""
import pytest
from rayvision_utils.exception.exception import CGFileNotExistsE... |
string = 'string'
print(string[:4:2])
for letter in string:
print(letter + '\n')
print(len(string))
print(string.count('t'))
print(string.title())
print(string.capitalize())
string = '-'
sequence = ['a','b','c','d','e','f','g','h']
print(string.join(sequence));
string = 'a-b--d-g-h-r-hg-d-d-g-f-e-t-y-q-f'... |
activate_this = '/var/www/postmash/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
import sys
print sys.path
from postmash import app as application
|
# Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
# Copyright [2016-2023] EMBL-European Bioinformatics Institute
#
# 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 ... |
__author__ = 'Dell'
##
## init fav must be the first fav from src to dest
## reciprocated fav must be the first fav from dest to src
## reciprocated fav must have larger timestamp than init fav
##
import csv
from datetime import datetime
edgesreader = csv.reader(open("flickr-growth-sorted.txt", "r"), delimiter='\t... |
#!/usr/bin/env python3
import sys
import os
import argparse
SKOOLKIT_HOME = os.environ.get('SKOOLKIT_HOME')
if not SKOOLKIT_HOME:
sys.stderr.write('SKOOLKIT_HOME is not set; aborting\n')
sys.exit(1)
if not os.path.isdir(SKOOLKIT_HOME):
sys.stderr.write('SKOOLKIT_HOME={}; directory not found\n'.format(SKOOL... |
"""
Compute zodiacal light at a particular RA/Dec/Date
Get heliocentric lat/lon from lookup table
"""
import os
import numpy as np
import astropy.coordinates as co
import astropy.units as u
import pyfits
if hasattr(co, 'ICRS'):
icrs = co.ICRS
else:
icrs = co.ICRSCoordinates
def datapath():
return os.pat... |
import sys
print(sys.path)
import requests
|
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 4 10:47:15 2012
@author: leonard
"""
import numpy as np
import pylab
class BuscaHarmonica:
""" Algoritmo de otimização e busca baseado em perfomance musical.
Parâmetros:
-Funcao objetivo (fo)
-Número de variáveis de decisao (N)
""... |
# Generated by Django 2.0.7 on 2019-01-06 21:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('basedata', '0035_auto_20190106_2056'),
]
operations = [
migrations.AlterField(
model_name='feedback_report',
name='i... |
from .base import *
from .mnist import *
|
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list) # A
def addEdge(self, boy, girl):
self.graph[boy].append(girl) # B
def BFS(self, start):
visited = [False] * (len(self.graph)) # C
queue = []
queue.append... |
import random
from time import time
ms=9
class Terrain:
icon = ""
movement = 0
trees=0
miningquality=0
def __init__(self, icon, movement, trees,miningquality,foodDensity):
self.icon=icon
self.movement=movement
self.trees=trees
self.miningquality=miningquality
class... |
#!/usr/bin/env python3
import math
import collections
def half(length):
return math.sqrt(2 - math.sqrt(4-length*length))
def double(length):
return math.sqrt(length*length*(4-length*length))
def sum_(table, alpha, beta):
sup_alpha = math.sqrt(4-table[alpha]**2)
sup_beta = math.sqrt(4-table[beta]**2)
... |
from quickbats.config import CONFIG
from quickbats.config import AUTH
from quickbats.config import TOKENS
def test_config_sections():
assert "stripe" in CONFIG
def test_auth_keys():
assert isinstance(AUTH, dict)
assert "quickbooks_client_id" in AUTH
def test_tokens_keys():
assert "access_token" in TO... |
# Standard Deviation Skeleton
# This program should compute the standard deviation of a sequence of non-negative numbers, terminated by a -1.
# Standard deviation is: A measure of how spread-out data is.
# NOTE: You are not allowed to use a built-in standard deviation function from the libraries.
import math
list1... |
from components.fighter import Fighter
from components.ai import BasicMonster
from components.inventory import Inventory
from components.equipment import Equipment
from components.tome_factory import make_tome
import tcod
def component(name):
# TODO: Change this into a proper factory
component_map = {
... |
# count = 10
# def test():
# # pass
# # count = 5
# # print(count) # 全局变量不可被修改,相当于重新创建了一个count,可以
#
# # count +=1 # 报错 #全局变量被调用后,再修改报错 count +=1 相当于count = count +1
#
# # print(count)
# # count = 5 # 报错 # 全局变量被调用后,再修改报错
# 原因是,在局部变量中有count变量,但是在count被定义之前就使用了coun... |
from flask import request
from projectmanager.app import app
from projectmanager.mongodb import (
project_userlist_collection
)
from projectmanager.dao.project_userlist import (
ProjectUserListMongoDBDao, ProjectUser
)
from projectmanager.utils.handle_api import handle_response, verify_request
META_SUCCESS =... |
def find(A,x):
p = A[x]
if p == x:
return x
a = find(A,p)
A[x] = a
return a
def union(A, x, y):
# bx, by = sorted([find(A,x), find(A,y)]) # bx, by = find(A,x), find(A,y)だと無限ループ。
if find(A,x) > find(A,y):
bx, by = find(A,y), find(A,x)
else:
bx, by = find(A,x), fin... |
import transaction
from freezegun import freeze_time
from io import BytesIO
from onegov.gazette.models import GazetteNotice
from onegov.pdf.utils import extract_pdf_info
from openpyxl import load_workbook
from tests.onegov.gazette.common import login_admin
from tests.onegov.gazette.common import login_editor_1
from te... |
def uniquePaths(m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
memo = [ [0] * n for _ in xrange(m)]
def findPath(memo, index1, index2):
if memo[index1][index2] != 0:
return memo[index1][index2]
if index1 >= m-1:
return 1
if index2 >= ... |
#!/usr/bin/python
import gc
class TTest:
def __init__(self):
self.sub_func= None
print 'Created',self
def __del__(self):
self.sub_func= None
print 'Deleted',self
def Print(self):
print 'Print',self
def SubFunc1(t):
t.Print()
def DefineObj1():
t= TTest()
t.sub_func= lambda: SubFunc1(t)
... |
# -*- coding: utf-8 -*-
# flake8: noqa
# Generated by Django 1.11 on 2017-05-06 15:43
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
mi... |
import cv2
import sys
import numpy as np
class WeedDetection:
def __init__(self,img):
self.height = img.shape[0]
self.width = img.shape[1]
self.part_width = img.shape[1]//3
def preprocess(self, img):
'''
Blur da imagem e converte em HSV
'''
kernel_si... |
from PyQt5.QtWidgets import *
import sys
app = QApplication([])
widget = QWidget()
def showMsg():
QMessageBox.information(widget,'信息提示框','ok,弹出测试信息')
btn =QPushButton('测试点击按钮',widget)
btn.clicked.connect(showMsg)
widget.show()
sys.exit(app.exec()) |
import logging
from django.core.management import BaseCommand
from logging_sample.management.commands.utils.util_sample import logger_util
logger = logging.getLogger(__name__)
class Command(BaseCommand):
def handle(*args, **options):
# logging_sample.management.commands.command_sample
print(__... |
from django.db import models
#Modelo Grafica
class Grafica(models.Model):
#https://mc.ai/integrar-modelo-de-red-neuronal-convolucional-en-django/
# file will be uploaded to MEDIA_ROOT / uploads
imagen = models.ImageField(upload_to ='uploads/')
# or...
# file will be saved to MEDIA_ROOT / uploads... |
import os
import pandas as pd
def concatenate_all_games():
games = []
files = os.listdir('../data/merge/')
for file in files:
if '.csv' not in file:
continue
df = pd.read_csv('../data/merge/' + file)
games.append(df)
all_games = pd.concat(games)
all_games.to_c... |
from django.contrib import admin
from .models import *
from LandingPage.admin import *
from mailing.views import *
from django.contrib import messages
from django.contrib.auth.models import Group
class ExperienceInline(admin.StackedInline):
model = Experience
can_delete = False
verbose_name_plural = 'Exper... |
#!/usr/bin/env python
"""
File: reduce_features
Date: 12/7/18
Author: Robert Neff (rneff@stanford.edu)
"""
import os
import csv
import numpy as np
'''
Builds kaggle submission csv file for predictions dictionary
of the form: id:multi_hot_labels.
ex. "id1":[0, 5, 11]
'''
def build_kaggle_submission(predictions_dict,... |
#
"""
Created on Tue Dec 22 17:46:01 2020
@author: daniele
"""
import numpy as np
import matplotlib.pyplot as plt
#Sequential mi costruisce la rete nurale
from keras.models import Sequential
#dense è un metodo che mi permette di collegari i neuroni del livello precedente con i nodi del livello attuale
f... |
#!/bin/python
import sys
import math
map = []
infile = open(sys.argv[1], "r")
for line in infile:
map.append(list(line.rstrip()))
width = len(map[0])
height = len(map)
print (width)
print (height)
move = (3,1)
results = []
for move in [(1,1), (3,1), (5,1), (7,1), (1,2)]:
print (move)
xpos = 0
... |
#!/usr/bin/python3
def multiple_returns(sentence):
return (0, None) if not sentence else (len(sentence), sentence[0])
|
''' Tests for chronicler.decorators.audits '''
from mock import Mock
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from chronicler.models import AuditItem
from chronicler.decorators import audits
from chronicler.tests import TestCase
from chronicler.tests.mode... |
from django.shortcuts import render
from django import forms
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.edit import CreateView
from django.views.generic import ListView
from django.contrib.contenttypes.models import ContentType
from .models import Transaction, Pet, PetSupply... |
import os
path = os.path
from myhdl import *
from lift_step import lift_step
from signed2twoscomplement import signed2twoscomplement
from mux import mux_data
from ram import ram
from fifo import fifo
from rd_pc import pc_read
from PIL import Image
W0 = 9
im = Image.open("../../lena_256.png")
pix = im.lo... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("PairProducer")
process.load("FWCore.MessageService.MessageLogger_cfi")
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(100) )
process.source = cms.Source("PoolSource",
# replace 'myfile.root' with the source file you want to use... |
http://www.cnblogs.com/wupeiqi/articles/6229292.html #爬虫性能相关和Scrapy框架
性能相关
1.在编写爬虫时,性能的消耗主要在IO请求中,当单进程单线程模式下请求URL时必然会引起等待,从而使得请求整体变慢
1.1单线程单进程模式
实例1:#用时 ==> 19.061163187026978
import requests,time
time1 = time.time()
a = requests.get('http://www.cnblogs.com/wupeiqi/articles/6229292.html')
b = requests.get('... |
import operator
from functools import reduce
import os
import math
import pyautogui
from PIL import Image
from random import randint
import time
import fileinput
fileparent=["C:/Users/d0","C:/Users/d1","C:/Users/d2","C:/Users/d3"]
filelocation=['','','','']
while(True):
for i in range(0,4):
rand1=randint(0,... |
import time
import sys
import stomp
class MyListener(stomp.ConnectionListener):
def on_error(self, headers, message):
print('received an error "%s"' % message)
def on_message(self, headers, message):
print('received a message "%s"' % message)
def on_connected(self,headers,body):
pr... |
from chess.board import Board
import pytest
@pytest.fixture
def board():
arr = [
["br", "bn", "bb", "bq", "bk", "bb", "bn", "br"],
["bp", "bp", "bp", "bp", "bp", "bp", "bp", "bp"],
["--", "--", "--", "--", "--", "--", "--", "--"],
["--", "--", "--", "--", "--", "--", "--", "--"],
... |
## 1. Overview ##
f = open("movie_metadata.csv", "r")
rows = f.read().split("\n")
movie_data = []
for row in rows:
movie_data.append(row.split(','))
print(movie_data[0:5])
## 3. Writing Our Own Functions ##
def first_elts(movies):
movie_names = []
for movie in movies:
movie_names.append(movie[0... |
# class WaterHeater:
# "热水器:战胜寒冬的有利武器"
# def __init__(self):
# self.__observers = []
# self.__temperature = 25
# def getTemperature(self):
# return self.__temperature
# def setTemperature(self, temperature):
# self.__temperature = temperature
# print("current temp... |
"""
@File: thread_process.py
@CreateTime: 2020/1/11 上午9:59
@Desc: 多线程, 多进程
对于任务数量过多的,可以采用队列,一次取100条任务,执行结束后,再次取用, 在一个类中调用装饰器
"""
import time
import logging
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import ProcessPoolExecutor, wait, ALL_COMPLETED, FIRST_COMPLETED
logging.basicConfig(lev... |
import random
import sys
import os
#simply printing the message
print("hello world");
# writting single line comment
'''
multiline comments
'''
# in python u can store any type of variables
name="gokuljs"
print(name);
value1=10
value2=1.5
print(value1);
print(value2);
# numbers , lists ,tuples, dictionary ,Strin... |
from functools import cached_property
from onegov.ballot import Vote
from onegov.core.i18n import SiteLocale
from onegov.election_day import _
from onegov.election_day.layouts.default import DefaultLayout
class MailLayout(DefaultLayout):
""" A special layout for creating HTML E-Mails. """
@cached_property
... |
#!/usr/bin/env python
# ENCODE DCC fingerprint/JSD plot wrapper
# Author: Jin Lee (leepc12@gmail.com)
import sys
import os
import argparse
from encode_lib_common import (
log, ls_l, mkdir_p, rm_f, run_shell_cmd, strip_ext_bam)
from encode_lib_genomic import (
samtools_index)
from encode_lib_blacklist_filter ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 15 19:31:34 2017
@author: justjay
"""
#LIVE2 split images randomly
#Train: 17, Validation: 6, Test: 6
#Train: 23, Test: 6; train:test ~= 8:2
import numpy as np
import scipy.io as sio
names_mat = sio.loadmat('./refnames_all.mat')
dmos_mat = sio.loadmat('./dmos.mat')
d... |
from Paragraphs.AccordionParagraph import AccordionParagraph
import pytest
@pytest.allure.feature('Paragraphs')
@pytest.allure.story('Accordion paragraph')
@pytest.mark.usefixtures('init_solution_page')
class TestAccordionParagraph:
@pytest.allure.title('VDM-??? Accordion paragraph - creation')
def test_acco... |
from django.contrib import admin
from .models import DataSchema, DataSet, Field
@admin.register(DataSchema)
class DataSchemaAdmin(admin.ModelAdmin):
list_display = ('title', 'created', 'updated',)
@admin.register(DataSet)
class DataSetAdmin(admin.ModelAdmin):
list_display = ('file', 'schema', 'created', 'stat... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-05-21 22:27
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('userprofiles', '0001_initial'),
]
operations = [
migrations.AlterField(
... |
from stdmodandoption import *
import time
import multiprocessing as mp
runtodo='m12fmhdcvhr'
i=580
info=SSF.outdirname(runtodo, i)
rundir=info['rundir']
Nsnapstring=info['Nsnapstring']
havecr=info['havecr']
haveB=info['haveB']
cutcold=0
dx=dy=dz=1
commonpath='/home/tkc004/scratch/snipshot/philruns/'
#SSF.mkdir_p(commo... |
# program that prints all the even numbers from 2 to 100.
#author Angelina B
evenNum = 2
while evenNum < 10:
print (evenNum)
evenNum += 2
|
# @Title: 找到所有数组中消失的数字 (Find All Numbers Disappeared in an Array)
# @Author: 2464512446@qq.com
# @Date: 2020-03-05 18:32:37
# @Runtime: 660 ms
# @Memory: 20.5 MB
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
# 自己做的
# seen = set(nums)
# nums_all = set([i fo... |
from conans.model import Generator
from conans.paths import BUILD_INFO_VISUAL_STUDIO
class VisualStudioGenerator(Generator):
template = '''<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Label="PropertySheets" />
<Pr... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 30 16:39:36 2018
@author: Joshua Ip - Work
"""
antimonyString = ("""
J0: $AncDNA -> AncRNANuc ; a_rna * AncDNA
J1: $DimDNA -> DimRNANuc ; a_rna * DimDNA
# transcription
# units of (mRNA copies)/(sec)
J3: AncRNANuc -> AncRNACyt ; diffusion_rna * A... |
import sys, os
sys.path.insert(1, os.getcwd())
import json
from obi.db import *
from uuid import uuid4
patch_1 = {}
patch_1['items_to_create'] = [
{"op": "add", "path": "/test", "value": ["a new item, cool"]}
]
def create_records():
user = User.get()
bucket = DataBucket.get(id=1)
print(bucket, bucket... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import shutil
import nysol.mcmd as nm
import nysol.util as nu
import nysol.util.margs as margs
from nysol.util.mtemp import Mtemp
from nysol.util.mmkdir import mkDir
from nysol.util.mparallel import meach as meach
from nysol.util.mrecount import mrecount
class... |
# discord-components
from discord_components import DiscordComponents, Button, ButtonStyle, Select, SelectOption
import asyncio
import discord
async def timeout_button(msg):
await msg.edit(components=[
Button(style=4, label="Timed Out!", disabled=True, custom_id="timed_out"),
],
)
async def cl... |
import cv2
import os
IMAGE_SIZE = (200, 200)
def init_image(path):
detector = cv2.AKAZE_create()
image = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
image = cv2.resize(image, IMAGE_SIZE)
return detector.detectAndCompute(image, None)
def compare(des1, des2):
bf = cv2.BFMatcher(cv2.NORM_HAMMING)
m... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.