text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python3
import argparse
import math
import random
import re
import sys
MIN_ENTROPY = 44
def choose(words, nb):
rng = random.SystemRandom()
return [rng.choice(words) for i in range(nb)]
class Wordlist():
def __init__(self, words):
self.words = list(words)
self._len = len... |
# ------------------------------------------------------------
#
# -----------------------
# -------- Tuple --------
# -----------------------
#
#
# [1] Tuple Items Are Enclosed in Parentheses
# [2] You Can Remove The Parentheses If You Want
# [3] Tuple Are Ordered, To Use Index To Access Item
# [4] Tuple Are Immutable... |
from rest_framework.permissions import BasePermission
class IsSuperAdminUser(BasePermission):
"""Allows access only to SuperAdmin users."""
def has_permission(self, request, view):
"""Check condition for the permission."""
return bool(request.user and request.user.is_superuser)
|
from __future__ import print_function
from um_fileheaders import *
import numpy as np
from six.moves import builtins
import types
class umfile_error(Exception):
pass
class packerr(Exception):
pass
class UMFile():
# Should this inherit from io.something?
""" Extended version of file class that uses 8 ... |
from termcolor import colored as clr
from collections import OrderedDict
from fuzzer.common.FuzzData import FuzzData
from fuzzer.strategies import baseline_strategies as base
def heuristic(max_depth: int, properties: dict, fuzz_data: FuzzData):
""" Makes a search plan based on a heuristic """
ospf_links = fuz... |
import os
import cv2
from PIL import (
Image,
ImageDraw,
ImageFont,
)
import argparse
import textwrap
import numpy as np
import pandas as pd
from tqdm import tqdm
from typing import Tuple, List
def logs_to_df(log_path: str, date_end_idx: int = 20) -> pd.DataFrame:
"""
Take an Overrustle .txt log a... |
from select import select
from socket import socket
from typing import IO, Callable
class IOWrapper:
def __init__(self, io_stream: IO, socket_: socket = None):
self.io_stream = io_stream
self.socket = socket_
self.next_timeout_cb = None
def set_next_timeout_cb(self, cb: Callable):
... |
'''
Os dicionários representam coleções de dados que contém na sua estrutura um
conjunto de pares chave/valor, nos quais cada chave individual tem um valor associado. Esse
objeto representa a ideia de um mapa, que entendemos como uma coleção associativa desordenada.
A associação nos dicionários é feita por meio de uma ... |
import FWCore.ParameterSet.Config as cms
# Set variables from the os environment
globalTag = 'MC_3XY_V26'
# Load Standard CMSSW process initial configurations
process = cms.Process("DHCand")
process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.load("Configuration.StandardSequences.Geometry_cff")
process.lo... |
import io
import base64
from repository.in_memory_data import in_memory_photos
def test_root_redirects(configured_app):
response = configured_app.get('/').status_code
assert response == 302
def test_root_unconfigured_redirects(unconfigured_app):
response = unconfigured_app.get('/').status_code
assert ... |
"""
Ресурс, предоставляющий доступ к данным о студенческих отказах о мероприятиях.
"""
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
import models.db_session as db_session
from models.all_models import student_declines, Student
parser = RequestParser()
parser.add_argument('conte... |
# -*- coding: utf-8 -*-
"""Convenience wrapper function to simplify the interface to launch a :class:`aiida_shell.ShellJob` job."""
from __future__ import annotations
import logging
import pathlib
import shlex
import tempfile
import typing as t
from aiida.common import exceptions, lang
from aiida.engine import Proces... |
# Script para dividir o arquivo 'fasta', de forma a igualar o proces-
# samento entre os nucleos (max de 20)
# Nome do arquivo a ser processado abaixo, associado a esta variavel
proteins_fasta = 'GCF_000347755.3_Ccap_2.1_protein'
new_file = open(proteins_fasta + '.txt', 'w')
# Numero de divisoes para a proteina s... |
import unittest
from functions.funtionLibrary import *
class testEditSQLString(unittest.TestCase):
def testEditSQLString(self):
"""This checks to see if the EDIT sQL string is built"""
val = editSQLStr("BookTitle","New Book Title",2)
self.assertEqual(val,"UPDATE bookStore SET BookTitl... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#foo abs
print(abs(-1))
#foo max
print(max(1, -2, 3))
#type change
int('123')
float('12.34')
str(1.23)
bool(1)
bool('')
#function name
a = abs
print(a(-1))
#hex
print(hex(255))
print(hex(1000))
|
from django.db import models
class ProductCategory(models.Model):
title = models.CharField(max_length=1000, verbose_name='عنوان')
description = models.TextField(null=True, blank=True, verbose_name='توضیحات')
def __str__(self):
return self.title
class Meta:
verbose_name = 'دستهی محصو... |
def merge(arr,l,mid,r):
L = arr[:mid]
R = arr[mid:]
i = j = k = 0
while(i<len(L) and j<len(R)):
if(L[i]<=R[j]):
arr[k] = L[i]
i = i+1
else:
arr[k] = R[j]
j=j+1
k = k+1
while(i<len(L)):
arr[k] = L[i]
i = i+1
... |
from __future__ import unicode_literals
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django_thumbs.db.models import ImageWithThumbsField
# Create your models here.
# class User(AbstractUser):
# avatar = Ima... |
import subprocess as sp
import mdlPil, mdlGFX, ThunderBorg
def PreFlight():
image = mdlPil.creatImage()
image = ControllerCheck(image)
image = TBCheck(image)
mdlGFX.gfxDisplay(image)
return image
def ControllerCheck(image):
stdoutdata = sp.getoutput("hcitool con")
if "00:06:F7:13:66:8... |
import json
import requests
# A simple class to store attributes of a single track.
class Track(object):
def __init__(self, name, track_id, artist):
# Name of the track (Can be used to display on the front end)
self.name = name
# ID of the track (Will be used to get the Lyrics)
sel... |
from res_util import *
from bird_co import *
# from other_util import *
# conda install pandas
# conda install librosa
# conda install pandas
# conda install pandas
# conda install pandas
import os
import sys
import gc
import time
import math
import shutil
import random
import warnings
import typing as tp
from path... |
import random
p = [4, 3, 4, 4, 5, 3, 5, 4, 4, 5, 4, 4, 3, 4, 5, 4, 3, 4]
b = ['b', 0, 'B']
f = [{i: [0, 0] for i in range(4)} for z in range(3)]
w = None
for r in range(3):
c = True
a = [0, 1, 2, 3]
m = None
while c:
t = [map(lambda x: random.randint(x-1, x+1), p) for i in range(4)]
s = ... |
# file_write.py
try:
fw = open("mynote.txt", 'w') #覆盖写
fw = open("mynote.txt", 'x') #如果原文件存在则报错
fw = open("mynote.txt", 'a') #追加
print("打开文件成功!")
fw.write("你好!")
print("写入文件成功能")
fw.write("ABC")
fw.writelines( ["这是第一个字符串", '这是第二个字符串'])
fw.write("1234\n")
fw.write("这是第二行!")... |
# task 2.3
name = "Eric"
message = f"Hello {name}, would you like to learn some Python today?"
print(message)
# task 2.4
print(name.upper())
print(name.lower())
print(name.title())
# task 2.5
message = 'Albert Einstein once said, "A person who never made a mistake never tried anything new."'
print(message)
# task 2.6
f... |
def divides(n, p):
return n % p == 0
def divides_list(n, l):
for p in l:
if divides(n, p):
return True
return False
def next_prime(l):
counter = max(l) + 1
while divides_list(counter, l):
counter += 1
return counter
prime_list = [2]
for i in range(1, 10002):
n... |
from django.urls import reverse
from django.test import TestCase
from django.test.client import RequestFactory
from django.test import Client
from tests.factories.gbe_factories import (
ActFactory,
BioFactory,
ConferenceFactory,
ProfileFactory,
)
from tests.functions.gbe_functions import (
grant_pri... |
import sys
import os
from call_back import *
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/../call_back")
os.path.abspath(os.path.join(os.getcwd(), os.pardir))
sys.path.append("/home/wittybrains/airflow_learning/call_back")
|
#!/usr/bin/env python3
import psycopg2
if_total = 0
of_total = 0
def main():
dbconn = psycopg2.connect(host='studsql.csc.uvic.ca', user='paraguay', password='9MM|QscGV4')
cursor = dbconn.cursor()
global if_total
global of_total
print("""Please select what would you like to do, press a numbe... |
from core.permissions import BasePermission
from.models import RolePermission
class CanAddEmployee(BasePermission):
permission_name = RolePermission.EMPLOYEE_CREATE
class CanEditEmployee(BasePermission):
permission_name = RolePermission.EMPLOYEE_EDIT
class CanViewEmployee(BasePermission):
permission_n... |
#!/usr/bin/python3
import os, subprocess, platform, argparse
# default paths to anaconda and data roots
ANACONDA_DIR = os.path.join("C:\\", "Apps", "Anaconda3") if platform.system() == "Windows" else os.path.join("~", "anaconda3")
DEFAULT_COUNT, DEFAULT_NAME, DEFAULT_CONFIG = 1, "DemoImpModel", "ConfigImp.yaml"
# pa... |
import matplotlib.pyplot as plt
import sys
a=1
x=[]
y=[]
f=open("read.txt","r")
x1=f.read()
x1=x1.split(" ")
for i in x1:
y.append(int(i))
x.append(a)
a+=1
f.close()
plt.plot(x,y)
plt.plot(x,y,"ro")
plt.xticks(x)
plt.yticks(y)
plt.xlabel('Number')
plt.ylabel('Square')
plt.grid()
plt.title("GCI-MakeFile-Demo(Square N... |
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA512
import requests
import datetime
import Crypto
import json
import threading
import balance
f = open('key.pem')
key = RSA.import_key(f.read())
f.close()
publicExponent = key.publickey().n
'''
res = requests.get('https://gw.kaist.ac.kr/broadcast/get?reverse=... |
"""
This is a script which trains the BalancedBagginClassifier on top of the best
word2vec model, on the train + validation dataset.
"""
from imblearn.ensemble import BalancedBaggingClassifier
from sklearn.externals import joblib
import pandas as pd
if __name__ == "__main__":
print("Loading data")
data = pd.co... |
import os
from numpy import *
from timeit import *
import random
def main():
#file = openF('graph.txt')
#graph = loadGraph(file)
graph = randomGraph(10)
tour = TSP(graph)
#print("TSP tour = ")
print()
print(tour)
a=tourLength(tour, graph)
print(a)
tourZgadn = Zgadn(graph)
#... |
#code for basic geocoding search
import requests
import sys
import json
url = "https://us1.locationiq.com/v1/search.php"
#change this to the input
query = sys.argv[1]
data = {
'key': '8d6879e1df3d64',
'q': query,
'format': 'json'
}
response = requests.get(url, params=data)
rjson = response.json()
#latit... |
xa=float(input("x de a:"))
ya=float(input("y de a:"))
xb=float(input("x de b:"))
yb=float(input("y de b:"))
xm=(xa+xb)/2
ym=(ya+yb)/2
print(float(round(xm,1)))
print(float(round(ym,1))) |
import audioop
import numpy as np
import pyaudio
import wave
CHUNK_SIZE = 1024
class Music:
def __init__(self, path = "./stereo.wav"):
self.path = path
self.wf = wave.open(path, 'rb')
self.width = self.wf.getsampwidth()
self.pa = pyaudio.PyAudio()
self.stream = self.pa.ope... |
from django.urls import path
from .views import *
app_name = 'blog'
urlpatterns = [
# Example: /
path('', PostLV.as_view(), name='index'),
# Example: /post/ (same as /)
path('post/', PostLV.as_view(), name='post_list'),
# Example: /post/django-example/
path('post/<slug:slug>/', PostDV.as_... |
"""
伪代码:
去除平均值
计算协方差矩阵
计算协方差矩阵的特征值和特征向量
将特征值从大到小排序
保留最上面的N个特征向量
将数据转换到上述N个特征向量构建的新空间中
"""
import numpy as np
def loadDataSet(filename, delim="\t"):
f = open(filename)
strArr = [line.strip().split(delim) for line in f.readlines()]
arr = [list(map(float, line)) for line in strArr]
... |
import sys
zeefile = open(sys.argv[1])
for x in zeefile:
holder = x.strip().split()
indienums = holder[0]
totalnums = []
for x in indienums:
x = int(x)
totalnums.append(x ** len(indienums))
if str(sum(totalnums)) == indienums:
print "True"
else:
print "False"
|
#Problem ID: COVIDLQ
#Problem Name: COVID Pandemic and Long Queue
for _ in range(int(input())):
n = int(input())
s = list(input().split())
z = 5
i = 0
r = True
while i < n:
if(s[i] == '1'):
if(z<5):
r = False
break
else:
... |
import logging
import pytest
from ocs_ci.framework.pytest_customization.marks import (
system_test,
ignore_leftovers,
polarion_id,
skipif_ocs_version,
)
from ocs_ci.framework.testlib import E2ETest
log = logging.getLogger(__name__)
@system_test
@ignore_leftovers
@polarion_id("OCS-2716")
@skipif_ocs_... |
# With list comprehension
vector = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
L = [number for list in vector for number in list]
print(L)
# Prints [1, 2, 3, 4, 5, 6, 7, 8, 9]
# equivalent to the following plain, old nested loop:
vector = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
L = []
for list in vector:
for number in list:
... |
from typing import List
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
"""
Brute Force
Time Complexity: O(n^3)
Space Complexity: O(n)
"""
count = 0
# Considering every possible subarray O(n^2)
for start in range(len(nums)):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Delete indicators and groups which have been created for the tests."""
import hashlib
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), ".")))
import validator
def _create_xid(type_, name):
# if given a file indicator, ... |
class UserModel:
def __init__(self,id,name,password):
self.id = id
self.user_name=name
self.password=password
|
# time O(logN)
# stack O(logN) call stack
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
self.min_idx , self.max_idx = -1, -1
def helper(left, right, nums, target):
if left<=right:
mid = (left+right)//2
if nums[mid] == ta... |
from tkinter import Toplevel, BOTH
from tkinter.ttk import *
class CustomDialog(Toplevel):
"""
Class to open dialogs which uses ttk instead of tkinter for style
consistency. This class is intended as a base class for custom dialogs
Parameters
----------
parent : `enrich2.gui.configurator.... |
import math
from kivy.uix.floatlayout import FloatLayout
from kivy.properties import StringProperty,NumericProperty,ListProperty,DictProperty
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.clock import Clock
from kivy.app import App
Builder.load_string('''
#:... |
#!/usr/bin/env python3
from sys import stderr, exit, argv
import re
import random
from TALinputs import TALinput
from multilanguage import Env, Lang, TALcolors
from increasing_subsequence_lib import *
# METADATA OF THIS TAL_SERVICE:
problem="increasing_subseq"
service="min_k_col"
args_list = [
('colo... |
import threading
from time import sleep
from model.experiment import Experiment
experiment = Experiment()
experiment.load_config('experiment.yml')
experiment.initialize()
t = threading.Thread(target=experiment.start_scan)
t.start()
while t.is_alive():
print(experiment.i)
sleep(1)
experiment.keep_running ... |
import unittest
from pylatexenc import _util
class TestLineNumbersCalculator(unittest.TestCase):
def test_simple(self):
s = """\
one
two
three
four
five
""".lstrip()
ln = _util.LineNumbersCalculator(s)
self.assertEqual( ln.pos_to_lineno_colno(0), (1,0) )
self.assertEqual( ... |
#!/usr/bin/env python2.7
import dicom, cv2, re
import os, fnmatch, sys
from keras.callbacks import *
from keras import backend as K
from keras.backend.tensorflow_backend import set_session
import tensorflow as tf
from itertools import zip_longest
from scipy.misc import imsave
from helpers import center_crop_3d, center... |
"""
A scaled down version of the Brunel model useful for testing (see OMV files: .test.*)
"""
from brunel08 import runBrunelNetwork
from pyNN.utility import get_script_args
simulator_name = get_script_args(1)[0]
simtime = 1000
order = 100
eta = 2.0 # rel rate of external input
g = 5.0
runBru... |
import numpy as np
def fft(samples: np.array, fft_size: int):
result = np.fft.fft(samples, fft_size)
result = np.fft.fftshift(result)
return result
def psd(samples, fft_size: int):
window = np.hamming(fft_size)
result = np.multiply(window, samples)
result = np.fft.fft(result, fft_size)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 9 09:33:40 2019
@author: amc
"""
# -------------------- script for A.I. -----------------------#
import numpy
import pandas
import re
import nltk
from nltk.corpus import stopwords
nltk.download('stopwords')
from sklearn.feature_extraction.text im... |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# 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 o... |
import cuisine as c
import subprocess
from fog_lib import FogRequester, shutdown
import logging
class SnapinRequester(FogRequester):
"""docstring for SnapinRequester"""
def _handler(self, text):
def process(x):
key = x[0].lower().replace('snapin', '')
value = x[1]
r... |
from .Cliente import Cliente
from .interfaces.IClienteService import IClienteService
from .interfaces.IClienteRepository import IClienteRepository
from .interfaces.IEmailService import IEmailService
class ClienteService(IClienteService):
def __init__(self, _emailService: IEmailService, _clienteRepository:IClienteR... |
'''
Author : Deepak Chauhan
GitHub : https://github.com/royaleagle73
Email : 2018PGCACA63@nitjsr.ac.in
'''
import os
class get_browsers:
'''
********* THIS SCRIPT RETURNS A LIST CONTAINING BROWSERS INSTALLED ON USER'S LINUX SYSTEM *********
CLASS get_browsers DOCINFO:
get_browsers HAVE TWO FUNCTIONS I.E.,
1) _... |
import pytest
from werkzeug.exceptions import HTTPException
from flaskapp.db import get_db
from flaskapp.reports import get_report_by_id
def test_index(client):
response = client.get("/")
assert b"Reports" in response.data
assert b"State" in response.data
@pytest.mark.parametrize("id", (25, 16))
def te... |
#!/usr/bin/env python3
# coding: utf-8
__author__ = "Robert Abel"
__copyright__ = "Copyright (c) 2018–2019"
__license__ = "MIT"
import certifi
import os
import sys
import argparse
import hmac
import json
import locale
import pycurl
import random
import re
import yaml
from base64 import b64encode
from datetime import ... |
__author__ = 'AlexLlamas'
from Tkinter import *
from samples import Samples
from CorrelationMesures import *
import matplotlib.pyplot as plt
import sympy as sym
from scipy.optimize import curve_fit
def colocar_scrollbar(listbox,scrollbar):
scrollbar.config(command=listbox.yview)
listbox.config(yscrollcommand=s... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:wiley
# datetime:2020/4/21 9:38 AM
"""
Definition for a Node.
"""
class Node:
def __init__(self, x, next=None, random=None):
self.val = int(x)
self.next = next
self.random = random
class Solution(object):
def __init__(self):
... |
"""This script creates object structure to store the extracted data
and provides methods to set and retrieve the attributes"""
import enum
class Contents:
"""This class creates content_list which is list of extracted contents"""
def __init__(self):
self.content_list = list()
self.content... |
#
# 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 core.evaluation.labels import Label
from core.source.opinion import Opinion
from core.source.vectors import OpinionVector
from core.source.news import News
from words import NewsWords
class TextPosition:
"""
Represents an article sample by given newsID,
and [left, right] entities positions
"""
... |
import json
import requests
import sys
import argparse
def highestID():
return requests.get("https://0ym0hvjsll.execute-api.us-east-2.amazonaws.com/default/chat/highestid").json()
def newMessage(msgID = None):
i = highestID()
if msgID == None:
message_id = i
else:
message_id = str(msgID)
r = requests... |
from functools import partial
import numpy as np
def macd(values, alpha=0.8, period1=26, period2=12):
x = np.array(exponential_moving_average(values, alpha=alpha, period=period1))
y = np.array(exponential_moving_average(values, alpha=alpha, period=period2))
return x-y
def rsi(values, alpha=0.5... |
'''
This module should contain a class that automates gromacs tool gmx msd
'''
import os
import MDAnalysis as mda
import numpy as np
from MDAnalysis.analysis.lineardensity import LinearDensity
from MDAnalysis.analysis.waterdynamics import MeanSquareDisplacement as MSD
from . import neighbors
from .neighbors impor... |
#!/usr/bin/env python
'''
Features to do a "make" double-pump.
This feature rely on the "prepare" step to have run. It produces "build" and "install" steps.
'''
from waflib.TaskGen import feature
import waflib.Logs as msg
from orch.wafutil import exec_command
import orch.features
orch.features.register_defaults(
... |
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5)
tup3 = "a", "b", "c", "d"
tup4 = ()
tup5 = (25, 45, 65, 85, 45, 35)
print("Max =", max(tup5))
print("Min =", min(tup5))
print("Length =", len(tup5))
|
"""
Example to demonstrate simple transpiling and evaluating.
"""
from flexx.pyscript import js, py2js, evaljs, evalpy
def foo(a, b=1, *args):
print(a)
return b
# Create jscode object
jscode = js(foo)
# Print some info that we have on the code
print(jscode.name)
print(jscode.pycode)
print(jscode.jscode)
# ... |
#Importing the Libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the Dataset
dataset = pd.read_csv('Academic_Data.csv')
#Create the matrix of features and Dependent Variables vector
X = dataset.iloc[:, :-1].values
#creating the dependent variable vector
y = dataset.iloc[:, 1... |
from book import Book
from user import User
from review import Review
from author import Author
import time
import psycopg2 as dbapi2
class Database:
def __init__(self, db_url):
self.db_url = db_url
def add_book(self, book):
with dbapi2.connect(self.db_url) as connection:
cursor =... |
# -*- coding: utf-8 -*-
# Module: addon
# Author: Mike Knight
# Created on: 12.09.2019
# License MIT
import sys
import json
from urllib import urlencode
from urlparse import parse_qsl
import xbmcaddon
import xbmcgui
import xbmcplugin
_url = sys.argv[0]
_handle = int(sys.argv[1])
ADDON = xbmcaddon.Addon('plugin.radi... |
import WConio as W
import logging
log = logging.getLogger('term.windows')
#import our color constants per-platform
BLACK = 0
BLUE = 1
GREEN = 2
CYAN = 3
RED = 4
MAGENTA = 5
BROWN = 6
LIGHTGRAY = LIGHTGREY = 7
DARKGRAY = DARKGREY = 8
LIGHTBLUE = 9
LIGHTGREEN = 10
LIGHTCYAN = 11
LIGHTRED = 12
LIGHTMAGENTA = 13
YELLOW =... |
#!/usr/bin/env python3
# -*-encoding: utf-8-*-
# by David Zashkol
# 2 course, comp math
# Taras Shevchenko National University of Kyiv
# email: davendiy@gmail.com
"""
Компанія Giggle відкриває свій новий офіс у Судиславлі, і ви запрошені на співьесіду.
Ваша задача - розв'язати поставлену задачу.
Вам потрібно створит... |
'''
IC* graph for 3 categories
'''
import itertools
import networkx as nx
from sample_set import SampleSet
class HybridGraph(nx.Graph):
def add_directed_edge(self, out_node, in_node):
self.add_edge(out_node, in_node, out=out_node)
class IC_Graph():
def __init__(self, sampleSet, SIGNIFICANCE_LEVEL=0.... |
# 영상의 명암비 조절
# 히스토그램 스트레칭(Histogram stretching) - 영상의 특징을 분석해서 자동으로 기울기를 계산
# 영상의 히스토그램이 그레이스케일 전 구간에서 걸쳐 나타나도록 변경하는 선형 변환 기법
# 정규화 함수
# cv2.normalize(src, dst, alpha=None, beta=None, norm_type=None, dtype=None, mask=None) -> dst
# src : 입력 영상
# dst : 결과 영상 : python에서는 dst를 일반적으로 주지 않는다. None 주면 됨.
# alpha : (노름 정규화인... |
import json
import plotly
import pandas as pd
import numpy as np
import wordcloud
from flask import Flask
from flask import render_template, request, jsonify
from plotly.graph_objs import Bar, Heatmap, Layout, Figure, Scatter
import plotly.express as px
from sklearn.externals import joblib
from sqlalchemy import crea... |
import click
from colorama import Fore, Style
from constants import ProjInfo
def print_usage():
print("USAGE: $ veripypi [PKG_NAME] [GITHUB_AUTHOR_PKG]")
print("EX: $ veripypi shallow-backup alichtman/shallow-backup")
def print_version(splash=False):
"""
Format version differently for CLI and splash screen.
... |
# https://leetcode.com/problems/koko-eating-bananas/description/
"""
Koko loves to eat bananas. There are n piles of bananas, the ith pile has piles[i] bananas. The guards have gone and will come back in h hours.
Koko can decide her bananas-per-hour eating speed of k. Each hour, she chooses some pile of bananas and ea... |
from .squeeze1d import Squeeze1d
from .argmax_product import BinaryProductArgmaxSurjection
from .utils import integer_to_base, base_to_integer
|
import os
import gradio as gr
import torchaudio
import time
from datetime import datetime
from tortoise.api import TextToSpeech
from tortoise.utils.audio import load_audio, load_voice, load_voices
VOICE_OPTIONS = [
"random", # special option for random voice
"custom_voice", # special option for custom voice
... |
import datetime
import os
import random
import string
import warnings
import time
from math import sqrt
import numpy as np
from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage
PROJECT_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')
OUTPUT_DIR = os.path.join(PROJECT_DIR,"output"... |
import PyQt5.QtWidgets as qtw
import PyQt5.QtCore as qtc
import PyQt5.QtGui as qtg
import uuid
from mate.ui.views.map.layer.obstacleData_config_view \
import Ui_ObstacleDataConfig
from mate.ui.views.map.layer.layer_config import LayerConfig, LayerConfigMeta
import mate.net.utils as net_utils
import mate.ui.utils ... |
import urllib
import json
import pprint
import mysql.connector
#
#create table information ( id int, score int, author varchar(500), title varchar(500), venue varchar(500), volume varchar(500), pages int, year int, type varchar(255), site varchar(255))
cnx = mysql.connector.connect(user='root', host='127.0.... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymongo
class TianqiPipeline(object):
def process_item(self, item, spider):
return item
class MojiPipeli... |
# -*- coding:utf-8 -*-
# @Desc : 图片验证码与短信验证码
# @Author : Administrator
# @Date : 2019-09-20 20:05
# from iHome.tasks.task_sms import send_sms
from iHome.tasks.sms.tasks import send_sms
from . import api
from iHome.utils.captcha.captcha import captcha
from iHome import redis_store, constants
from flask import current_... |
"""Codewars test converted to pytest and expanded."""
import pytest
numbers_table = [
[-1, 1],
[0, 0],
[1, -1]
]
@pytest.mark.parametrize('input, output', numbers_table)
def test_opposite(input, output):
"""Test opposite kata function works."""
from opposite import opposite
assert opposite(i... |
"""给定一个整数数组,判断是否存在重复元素。
如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。
示例 1:
输入: [1,2,3,1]
输出: true
"""
class Solution:
def containsDuplicate(self, nums):
return not len(nums)==len(set(nums)) |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on 17-10-19 8:53 PM
@author: limengyan
"""
import os, time, pickle, random, time
from datetime import datetime
import numpy as np
from time import localtime, strftime
import logging, scipy
import tensorflow as tf
import tensorlayer as tl
from model import *
f... |
from datetime import datetime
from random import randint
from time import sleep
import boto3
dynamodb = boto3.resource('dynamodb')
batchnumber = 2000
table = dynamodb.Table('ddbstream2')
acc =0
while True:
with table.batch_writer() as batch:
for i in range(batchnumber):
batch.put_item(
... |
import heapq # 它可以用来实现优先队列
import random
list = random.sample([i for i in range(100)], 10)
print(list)
heapq.heapify(list) # 构建堆的过程(默认小根堆)
for i in range(len(list)):
# 每次弹出最小的数
print(heapq.heappop(list), end=",") |
from django.contrib import admin
from accounts.models import Follow
# Register your models here.
admin.site.register(Follow) |
##############################################################################
#
# Copyright (c) 2007 Agendaless Consulting and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the BSD-like license at
# http://www.repoze.org/LICENSE.txt. A copy of the license should accompany
# th... |
from __future__ import division
import six
import struct
import zlib
from erlastic.compat import *
from erlastic.constants import *
from erlastic.types import *
__all__ = ["ErlangTermEncoder", "ErlangTermDecoder", "EncodingError"]
class EncodingError(Exception):
pass
class ErlangTermDecoder(object):
def _... |
#!/usr/bin/env python3
#Se pide al usuario un numero
num = eval(input("Ingresa un numero: "))
# Se valida si el residuo es 0 sera par
if num % 2 == 0:
print("El numero es par")
else :
print("El numero es impar")
|
import cv2
import matplotlib.pyplot as plt
#カメラ起動
cap = cv2.VideoCapture(0)
while True:
#画像として読み込み
_,frame = cap.read()
#グレイスケール化
frame = cv2.cvtColor(frame,cv2.COLOR_RGB2GRAY)
#ガウシアンフィルターで平滑化
frame = cv2.GaussianBlur(frame,(7,7),0)
#画像の2値化
frame = cv2.threshold(frame,120,240,cv2.THRE... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.