text stringlengths 38 1.54M |
|---|
import numpy as np
import rnn_utils
def lstm_cell_forward(xt, a_prev, c_prev, parameters):
"""
根据图4实现一个LSTM单元的前向传播。
参数:
xt -- 在时间步“t”输入的数据,维度为(n_x, m)
a_prev -- 上一个时间步“t-1”的隐藏状态,维度为(n_a, m)
c_prev -- 上一个时间步“t-1”的记忆状态,维度为(n_a, m)
parameters -- 字典类型的变量,包含了:
... |
#!/usr/bin/env python3
import rospy
import numpy as np
import copy
import tf
import tf2_ros
import yaml
import datetime
import gc
from tools import *
from pprint import pprint
from pyquaternion import Quaternion
from gpd.msg import GraspConfigList
from moveit_python import *
from moveit_msgs.msg import Grasp, PlaceLoca... |
import cv2 as cv
import numpy as np
src = cv.imread("E:\\gannimei\\PycharmProjects\\opencv_python\\images\\github.jpg")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)
print(type(src))
print(src.shape)
# 克隆图像
m1 = np.copy(src)
# 赋值
m2 = src
src[0:100, 0:100, :] = 255
cv.imshow("m2"... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import redis
import urllib2
import time
import os
# 1、每天获取总的ip数(过滤24小时内提取过的),端口设定80 8080 8118 8123 808等
# 目前最大数量450左右
# 2、间隔十分钟左右检查所有ip是否有效,检查6次,查看6次全通的占比,5次全通的占比,以次所有占比情况
# 3、第二天再次操作步骤2,检查ip第二天的有效情况
# 4、第二天再操作步骤1和2
# 问题:当请求数变多时,会出现请求失败的问题
# =>request ip number: 1
# --... |
""" Handles repository layout scheme and package URLs."""
import os
import urlparse
from RepSys import Error, config
from RepSys.svn import SVN
__all__ = ["package_url", "checkout_url", "repository_url", "get_url_revision"]
def layout_dirs():
devel_branch = config.get("global", "trunk-dir", "cooker/")
devel... |
from keys import *
import webbrowser
import pyautogui
import requests
import argparse
import tweepy
import time
def fetch_urls_from_tweet(api, status_id):
status = api.get_status(status_id, tweet_mode="extended")
try:
content = status.retweeted_status.full_text
except AttributeError:
cont... |
"""
zbx.exceptions
~~~~~~~~~~~~~~
"""
class ValidationError(ValueError):
pass
class RPCException(Exception):
def __init__(self, message, code, data=None):
message = '%s(%d): %s' % (message, code, data)
super(RPCException, self).__init__(message)
self.code = code
self.... |
'''Utils.
Author:
P. Polakovic
'''
def ffs(num):
'''Returns first signed bit.'''
if num == 0:
return None
i = 0
while num % 2 == 0:
i += 1
num = num >> 1
return i
def qalign(num):
'''Aligns `n` on 8 bytes boundary.'''
return (num & ~0x7) + 0x8 if num % 0x08 ... |
import pymongo
from bson.json_util import dumps
import json
def get_top_10_by_points(event, context):
working_collection = get_working_collection()
found_subreddits = get_find_subreddits(event, working_collection)
result = found_subreddits.sort("punctuation", pymongo.DESCENDING).limit(10)
return curso... |
"""
Innlevering 1 | Oppgave 5
Kjør programmet ved kommandoen:
python oppg_5.py
Kastet er vertikalt, dvs at ballen kun vil bevege seg langs vertikalaksen(y-aksen).
Setter positiv retning oppover.
Ser bort fra luftmotstand, da er den eneste kraften som virker på ballen i luften vekten, W = mg.
Summen av kreftene ... |
#!/usr/bin/env python
import numpy as np
#!/usr/bin/env python
import sip
API_NAMES = ["QDate", "QDateTime", "QString", "QTextStream", "QTime", "QUrl", "QVariant"]
API_VERSION = 2
for name in API_NAMES:
sip.setapi(name, API_VERSION)
from PyQt4 import QtCore, QtGui, uic
# from source.dxf2shape import *
import iter... |
# conversion pa / mbar / atm / psi
def multi_cnv_pression(val,unit):
if(unit == "pa"):
start_txt = "The convertion of " + str(val) + " pa in mbar/atm/psi = "
pa_txt = ""
mbar_txt = ", " + str(val/100) + " mbar"
atm_txt = ", " + str(val/101325) + " atm"
psi_txt = ", " ... |
class Node:
def __init__(self, value=None):
self.value = value
self.prev = None
self.next = None
class DoublyList:
def __init__(self):
self.head = None
self.tail = None
def __iter__(self):
tempNode = self.head
while tempNode:
yield tem... |
class Pattern(object):
def __init__(self):
super(Pattern, self).__init__()
def do_something(self):
print('I\'m a pattern!')
|
#!/usr/bin/env python
#plt.ion()
'''
QT (Quality Codes):
0=missing data
1=highest
2=standard
3=lower
4=questionable
5=bad
ST (Source Codes):
0 = No Sensor, No Data
1 = Real Time (Telemetered Mode) *
2 = Derived from Real Time *
3 = Temporally Interpolated from Real Time
4 = Source Code Inactive at Present
5 = Recove... |
import paramiko
import sys
def ssh_command(ip, user, passwd, command):
client = paramiko.SSHClient()
#client.load_host_keys('/home/user/.ssh/known_hosts')
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(ip, username=user, password=passwd)
ssh_session = client.get_transport().op... |
from django.shortcuts import render
import requests
from sklearn.externals import joblib
from .forms import PredictForm
from sklearn.externals import joblib
df = joblib.load('df.pkl')
def home(request):
if request.method == 'POST':
form = PredictForm(request.POST)
if form.is_valid():
m... |
# python shallownet_animals.py --dataset ../datasets/animals/
import sys
sys.path.append("..")
from pyimagesearch.preprocessing import ImageToArrayPreprocessor
from pyimagesearch.preprocessing import SimplePreprocessor
from pyimagesearch.datasets import SimpleDatasetLoader
from pyimagesearch.nn.conv import ShallowNet... |
#!/usr/bin/env python
import os
import re
import sys
from pipe import * # http://pypi.python.org/pypi/pipe/1.3
from subprocess import Popen, PIPE
if len(sys.argv) > 1 and sys.argv[1] == '-h':
print "stats: Calcule des status sur quelqu'un"
print "N'a besoin que d'une partie de son nom pour le retrouver (perl... |
# FIXME : Complete the program. No need for defining new functions
# setup variables for counters among other things
num_count = 0
sum_count = 0
avg_count = 0
max_num = 0
min_num = 0
print('Simple Statistics')
numbs = str(input('Please enter numbers, separated by a space:\n'))
my_numbs = [float(numb) for numb in numb... |
import time
import functools
def log(text=None):
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
result = '{} {} {}'.format(text, f(*args, **kwargs), text)
return result
return wrapper
return decorator
def time_elapse(text=None):
def de... |
from setuptools import setup, find_packages
setup(
name='Group_6_predict',
version='0.1',
packages=find_packages(exclude=['tests*']),
license='MIT',
description='This package extract tweets',
#long_description=open('README.md').read(),
install_requires=['numpy'],
url='https://github.com... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import random
import os
def getPid(server):
pid_nu = os.popen('pidof %s'%(server)).read().strip()
return pid_nu
def getMem(nu):
with open('/proc/%s/status'%(nu)) as f:
for line in f.readlines():
if line.startswith('VmRSS'):
... |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.10.2
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
... |
from numpy import array
from keras.models import Sequential
from keras.layers import Dense, LSTM
# 데이터
x = array([[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10], [9, 10, 11], [10, 11, 12], [20000, 30000, 40000], [30000, 40000, 50000], [40000, 50000, 60000], [100, 200, 300]])
y... |
'''
Descripttion: 小型矩阵向量化未必比naive快,但大型矩阵向量化远超naive
Version: 1.0
Author: ZhangHongYu
Date: 2021-03-08 17:26:11
LastEditors: ZhangHongYu
LastEditTime: 2021-05-30 16:30:09
'''
import numpy as np
import time
eps = 1e-6
n = 6 #迭代次数
#向量化实现
def Jocobi(A, b):
assert(A.shape[0] == A.shape[1] == b.shape[0])
x = np.zeros(... |
from ..security import passwd, passwd_check
def test_passwd_structure():
p = passwd('passphrase')
algorithm, hashed = p.split(':')
assert algorithm == 'argon2'
assert hashed.startswith('$argon2id$')
def test_roundtrip():
p = passwd('passphrase')
assert passwd_check(p, 'passphrase') == True
de... |
# Generated by Django 2.1.3 on 2018-12-26 20:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('maincv', '0014_testimonial_image'),
]
operations = [
migrations.CreateModel(
name='SiteConfiguration',
fields=[
... |
def get_max_divis(in_list):
in_list.sort()
for index in range(len(in_list)):
divisor = in_list[index]
for ref in range(index+1, len(in_list)):
if in_list[ref]%divisor == 0:
return int(in_list[ref]/divisor)
return 0
def get_sum_chart(in_chart):
total_sum = 0
... |
import zlib
def compress(s):
'''
This function takes a string and converts it into a Python-compatible
string to be used in a print statement. This may come handy for
very long strings with many repetitions.
Example:
converts
"aaaa bbbb ccc\n"
to
"a"*4 + " "*4 +... |
from os.path import join, dirname
from nmigen import Fragment, Signal
from cores.jtag.jtag_peripheral_connector import JTAGPeripheralConnector
from soc.peripherals_aggregator import PeripheralsAggregator
from soc.memorymap import Address
from soc.soc_platform import SocPlatform
class JTAGSocPlatform(SocPlatform):
... |
# imports of both spynnaker and external device plugin.
import spynnaker.pyNN as Frontend
import spynnaker_external_devices_plugin.pyNN as ExternalDevices
#######################
# import to allow prefix type for the prefix eieio protocol
######################
from spynnaker_external_devices_plugin.pyNN.connections\
... |
##############################################################################
#
# Copyright (c) 2009 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... |
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
odds = 0
cnt_s = collections.Counter(s)
for _, val in cnt_s.items():
odds = odds + ( val & 1)
return len(s) - odds + int(odds > 0)
... |
#!/usr/bin/env python3
from typing import List, Dict
import json
import os
import subprocess
import sys
def ls(wd: str) -> List[str]:
"""Returns a list of directories under ``wd`` that match the johnny.decimal
pattern. The directories returned will be related to the passed working directory."""
pattern = "[12... |
from datetime import date
def edad(fn):
hoy = date.today()
dn, mn, an = fn.split('-')
dn = int(dn)
mn = int(mn)
an = int(an)
dh = hoy.day
mh = hoy.month
ah = hoy.year
e = ah - an
if (mn > mh) or (mn == mh and dn > dh):
e -= 1
return e
def separeNameFormalName(full... |
__author__ = 'Netšajev'
class BinarySearchTree:
def __init__(self):
self.root = None
def __iter__(self):
return self.root.__iter__()
def max_depth(self):
temp_depth = 0
for node in self.root.__iter__():
temp_depth = max(node.get_depth(), temp_depth)
r... |
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
import argparse
import io
import logging
import sys
from abc import ABC, abstractmethod
from typing import Any, Iterable, List, Mapping
from airbyte_cdk.connector import Connector
from airbyte_cdk.exception_handler import init_uncaught_exception_handler
fro... |
from django.shortcuts import get_object_or_404
from rest_framework import serializers
from care.facility.models import MedibaseMedicine, MedicineAdministration, Prescription
from care.users.api.serializers.user import UserBaseMinimumSerializer
class MedibaseMedicineSerializer(serializers.ModelSerializer):
id = s... |
import os
import docker
import time
def handle_container(file_name):
client = docker.from_env()
#create container and detach
container = client.containers.run('broncode_r', detach = True)
#wait until the container is running
while "created" in container.status:
container.reload()
#TODO: get docker-py to d... |
def i_am_this_old(age):
print('I am '+ str(age) + ' old')
my_age = 24
i_am_this_old(my_age)
if (my_age) > 23:
print("not real")
elif my_age == 24:
print("that's not real")
else:
print("you are fake news")
print("done")
a_list = []
for nubmer in range(10):
a_list.append('a')
|
# lets draw some stuff with ciaro!
from math import pi
import cairo
def to_cairo(pos, num_strings=6):
width, height = 300, 400
w, h = 0.6, 0.8*height/width
surface = cairo.ImageSurface(cairo.Format.ARGB32, width, height)
cr = cairo.Context(surface)
cr.translate(width/2, height/2)
cr.scale(wid... |
from functools import reduce
from math import inf as Infinity
import pprint
pp = pprint.PrettyPrinter(indent=1)
def prim(graph):
## MST: list of vertices currently in MST (uses None for index(0) for consistency)
## MSTedges: list of edges currently in MST
## MSTfilled: boolean ind... |
number = int(input())
count = 0
for i in range(1, number):
if number % i == 0:
count += 1
if count > 2:
print("False")
else:
print("True") |
ALGORITHMS = {
"firesaber": {"path": "firesaber", "is_kem": True},
"frodokem1344aes": {"path": "frodokem1344aes", "is_kem": True},
"frodokem1344shake": {"path": "frodokem1344shake", "is_kem": True},
"frodokem640aes": {"path": "frodokem640aes", "is_kem": True},
"frodokem640shake": {"path": "frodokem6... |
from PIL import Image
import numpy as np
#reading image
img = Image.open('500.png').convert('L')#monocrome
img.save('result21.png')
image_array = np.array(img)
#since image is 255.0 bit, in order to normalize them we have to divide image_array with 255 bit
image_array = image_array / 255.0
print (ima... |
# draw lines on a canvas
import numpy as np
import cv2
canvas = np.zeros((300, 400, 3), dtype = "uint8")
green = (0, 255, 0)
red = (0, 0, 255)
cv2.line(canvas, (0, 10), (200, 290), green) # (x1,y1), (x2,y2)
cv2.line(canvas, (190, 290), (390, 10), red, 3)
cv2.imshow("My Art", canvas) # create a single ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# author: Jan Hybs
from flowrunner.db.mongo import MongoDB
from flowrunner.utils import io, lists
from flowrunner.utils.logger import Logger
from flowrunner.utils.timer import Timer
logger = Logger(__name__)
timer = Timer()
class Experiments(object):
def __init__(self... |
import os
import pandas as pd
import warnings
warnings.filterwarnings('ignore')
from discord.ext import commands
import difflib
from recommendationKNN import predict_score
import json
knn_recommendations=json.load(open('KNN_recommendation.json'))
movies = pd.read_csv('movie recommendations/processedfinalfile.csv')
... |
from app import db
class News(db.Model):
"""The basic data for news items"""
__tablename__ = "News"
NewsID = db.Column(db.Integer, primary_key=True)
Title = db.Column(db.String(255), nullable=False)
Contents = db.Column(db.Text, nullable=False)
Author = db.Column(db.String(255), nulla... |
# create pydantic model
# Pydantic also uses the term "model" to refer to something different,
# the data validation, conversion, and documentation classes and instances
# Pydantic models (schemas) that will be used when reading data, when returning it from the API.
from typing import List,Optional
# BaseModel , py... |
"""
Demo by G. Brammer
"""
import numpy as np
from voronoi import bin2d
import matplotlib.pyplot as plt
# Noisy gaussian
yp, xp = np.indices((100,100))
R = np.sqrt((xp-50)**2+(yp-50)**2)
sigma = 10
g = 10*np.exp(-R**2/2/sigma**2)
s = 1
noise = np.random.normal(size=R.shape)*s
pix_bin, bin_x, bin_y, bin_sn, bin_npix, ... |
import matplotlib.pyplot as plt
from matplotlib import pyplot
import matplotlib as mpl
import numpy as np
import pandas as pd
import colormaps as cmaps
plt.register_cmap(name='viridis', cmap=cmaps.viridis)
plt.set_cmap(cmaps.viridis)
# Make a figure and axes with dimensions as desired.
fig, ax = plt.subplots(figsiz... |
# Generated by Django 2.2.4 on 2019-08-23 03:00
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Carousel'... |
#!/usr/bin/python
import re
def readNext(file):
tmp = file.readline()
if not tmp:
return ""
tmp = tmp.strip()
while (len(tmp)==0):
tmp = file.readline()
if not tmp:
return ""
else:
tmp = tmp.strip()
return tmp
def readNextWithTag(file, ta... |
# -*- coding: utf-8 -*-
# Copyright (C) 2016-2023 PyThaiNLP Project
#
# 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 a... |
import numpy as np
import datetime
import pandas as pd
from tqdm import tqdm
import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
import model_opt
import algo_GD
import helper
import noise
if __name__ == "__main__":
args = sys.argv
t = int(args[1])
w_init = np.array([3, 3])
_t... |
import sys
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from sklearn.metrics import confusion_matrix
from utils import set_random_seed, get_minibatches_idx, get_weighted_minibatches_idx
from models import ResNet18, VGG
from data import save_train... |
#Heapsort
#15.7.20
#chuanlu
import math
def right(i):
return 2*(i+1)
def left(i):
return 2*i+1
def parent(i):
return math.floor(i/2)
def heapsize(A):
return len(A) - 1 #我们认为堆A的有效元素个数和数组A的长度相等
def max_heapify(A ,i, x):
l = left(i)
r = right(i)
A_heapsize = x
largest = 0
if l < A_heapsize and A[l] > A[i]:
... |
from sqlalchemy import Column, Integer, String
from . import Base
class Instrument(Base):
"""
Map class for table instrument.
- **instrument_id**: Integer, primary_key.
- **instrument_type**: String(50), not null.
Note:
https://rszalski.github.io/magicmethods/
"""
... |
from . import db
from werkzeug.security import generate_password_hash,check_password_hash
from . import login_manager
from flask_login import login_required
from flask_login import UserMixin
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from flask import current_app
'''#保护路由只让认证用户访问
@app.rout... |
"""server file for she owns"""
import os
from flask import Flask, render_template, redirect, request, jsonify
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
from flask_debugtoolbar import DebugToolbarExtension
from jinja2 import StrictUndefined
from model import Business, Category, connect_to_db
... |
from datetime import timedelta
import djcelery
djcelery.setup_loader()
BROKER_BACKEND = "redis"
BROKER_URL = 'redis://119.3.4.159:6379/1'
CELERY_RESULT_BACKEND = 'redis://119.3.4.159:6379/2'
# 设置任务队列,区分不同的任务类型
CELERY_QUEUES = {
"beat_tasks": {
"exchange": "beat_tasks",
"exchange_type": "direct",
... |
import requests,pexpect,random,smtplib,telnetlib,sys,os
from ftplib import FTP
import paramiko
from paramiko import SSHClient, AutoAddPolicy
import mysql.connector as mconn
from payloads import *
def access(u,timeout=10,bypass=False,proxy=None):
'''
this function isused to check if the given link is returning 200 o... |
# Brian Hamrick
# 10/16/08
# Ellipse detection
import sys
import copy
import time
import curses
from math import *
from pgm import pgm
from ppm import ppm
starttime=time.time()
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
maxy, maxx = stdscr.getmaxyx()
bary, barx = maxy/2+1, (maxx-(52)... |
import unittest
from Deque_Generator import get_deque
from Stack import Stack
from Queue import Queue
class DSQTester(unittest.TestCase):
def setUp(self):
self.__deque = get_deque()
self.__stack = Stack()
self.__queue = Queue()
# Deque Tests
# Empty List Test
def test_empty_deque(self):
s... |
from uuid import UUID
from flask import request
from flask_restplus import Namespace, Resource, fields
import config
from mappers.event_mappers import EventResponseSchema, TotalByTypeResponseSchema
from repository.event_repo import EventRepo
from shared import response_object as res
from shared.enum.order_enum import... |
import socket
s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print('I am connecting the server!')
for xx in ['aBch','f服务d','h7Tq','.']:
s.sendto(xx,('192.168.3.13',8088))
str1,addr=s.recvfrom(1024)
str2=str(str1,encoding='utf-8')
print(s.recv(1024).decode('utf-8'))
s.close()
|
import tkinter as tk
root = tk.Tk()
frame1 = tk.Frame(root, text = "Frame 1")
frame1.pack()
frame2 = tk.Frame(root, text = "Frame 2")
frame2.pack()
root.mainloop() |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#Select from accident data the rows with those street names that are in traffic data
import pandas as pd
import numpy as np
df_accidents = pd.read_csv('data/5_accidents.csv')
df_road_usages = pd.read_csv('data/4_road_usages.csv')
roads = list(df_road_usages.nimi.uniqu... |
def resample_particles(particle_poses, particle_weights, num_particles):
# particle_poses = particle poses
# particle_weights = particle weights
# num_particles = number of particles
# keep count of total number of particles
count_num_particles = 0
# iterate through all particles
... |
# Copyright 2012-2013 OpenStack Foundation
#
# 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 la... |
def solution(arr, cmds):
answer = []
for i1, i2, i in cmds:
answer.append(sorted(arr[i1-1:i2])[i-1])
return answer
print(solution([1, 5, 2, 6, 3, 7, 4], [[2, 5, 3], [4, 4, 1], [1, 7, 3]]))
|
"""
Subset Tool eopy.dataIO.Product.Product for Sentinel-3 data, subclass of AbstractProcessingTool
"""
'''___Built-In Modules___'''
import sys
from os.path import dirname, basename
from os.path import join as pjoin
'''___Third-Party Modules___'''
'''___NPL Modules___'''
dataProcessing_directory = dirnam... |
__author__ = 'subin'
class Palindrome():
def Check_palindrome(self, IntegerValue):
IntegerValue = str(IntegerValue)
LenOfInteger = len(IntegerValue)
Half_length = LenOfInteger/2
if LenOfInteger < 2:
return 0
elif LenOfInteger%2 == 0:
for i in range(0, ... |
import cv2
import re
import os
import time
URL = "http://vrl-shrimp.cv:5000/video_feed"
video = cv2.VideoCapture(URL)
# 保存先フォルダ内の既存の画像枚数をカウントし,開始番号を決定
save_folder = "/Users/kubo/ex/python/shrimp_pool/JPEGImages/"
dir = os.chdir(save_folder)
files = os.listdir(dir)
cnt = 0
for file in files:
index = re.search('.jp... |
from md_statistics import *
from md_unit_converter import *
from math import pi
class MDGeometry:
def __init__(self, md):
self.md = md
self.unit_converter = MDUnitConverter(md)
self.md_statistics = MDStatistics(md, self.unit_converter)
def create_spheres(self, num_spheres, r_min, r_max, x_max, y_max, z_max):... |
from flask_restful import Resource,reqparse
from flask import Flask,abort,request
import config
import helpers
class CheckHealth(Resource):
def get(self):
return {"status":"Hey Geek, Im Up and running "}
class SearchBooks(Resource):
def get(self):
args = request.args
Url = "%s%s"%(conf... |
from datetime import *
class Term:
__instantiated = False
def __init__(self, term_start, term_end, holidays_start, holidays_end, day_offs=None):
if not self.instantiated():
self.instantiate()
self.term_start = term_start
self.term_end = term_end
self... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 1 18:41:42 2020
@author: abhishekhegde
"""
from itertools import combinations
from scipy import sparse
import numpy as np
import random
from random import randint
import copy
import binpacking
import pandas as pd
### Bin packing problem parameter... |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def conv2d(x, W):
return ... |
import os
import glob
import shutil
import time
import datetime
# create folder with the current date/time as the name (eg. '25 sep 1400'), to copy the files daily
today = datetime.datetime.today()
date = today.strftime('%d')
month = today.strftime('%b').lower()
t = today.strftime('%H')
folder_name = f'{date} {month} ... |
# https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof/
# 剑指 Offer 50. 第一个只出现一次的字符
from collections import Counter
# 用哈续表存储频数
class Solution:
def firstUniqChar(self, s: str) -> str:
d = {}
for i in s:
d[i] = 2 if i in d else 1
for i in s:
if ... |
#!/usr/bin/env python
# !-*- coding:utf-8 -*-
import json
Code_ERROR = "0" # 错误
Code_OK = "1" # 成功
class ResartInfo(object):
def __init__(self):
self.code = Code_OK
self.msg = "ok"
self.failList = []
def json(self):
"""JSON format data."""
json = {
'cod... |
import csv
from django.contrib.auth.models import User
header = ('id', 'username', 'email', 'date_joined')
users = User.objects.all().values_list(*header)
with open('io/csv/users.csv', 'w') as csvfile:
user_writer = csv.writer(csvfile)
user_writer.writerow(header)
for user in users:
user_writer.wri... |
import django
django.setup()
from sefaria.model import *
import re
from sources.functions import getGematria, post_text, post_index, post_link
import requests
from linking_utilities.dibur_hamatchil_matcher import match_ref
from sefaria.utils.talmud import section_to_daf
#SERVER = 'http://localhost:9000'
SERVER = 'http... |
import time
from contextlib import contextmanager
import gc
gc.collect()
@contextmanager
def timer(name):
t0 = time.time()
yield
print("\n\n" + name + ' done in ' + str(round(time.time() - t0)) + 's \n')
print("\n\nStarting\n\n")
with timer("Importing and setting up libraries"):
import os
import ... |
#!/usr/bin/python
# coding=utf-8
import sys
import re
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import ticker
from matplotlib.backends.backend_pdf import PdfPages
from datetime import datetime
def delta_eps_plot(plot_name, filename):
data = np.genfromtxt(filename, delimiter=',')
... |
import socket
import argparse
import time
import datetime
from net_structure import Packet, decode
def packets_prepare(packet_size, file_name):
f = open(file_name, 'r')
source = f.read()
source_len = len(source)
packets = []
source_pointer = 0
packet_id = 0
while source_pointer < source_le... |
import pygame
from pygame.math import Vector2
import sys
import random
pygame.init()
# Game display surface
cell_size = 40
cell_count = 20
game_screen = pygame.display.set_mode((cell_size * cell_count,
cell_size * cell_count))
pygame.display.set_caption('Snake Game')
# To restric... |
#!/usr/bin/env python
from abc import ABC, abstractmethod
import argparse
import gc
import os
import warnings
from pathlib import Path
from typing import Union, Generator, Tuple
import ffmpeg
import h5py
import imageio
import numpy as np
import utils
from carla_constants import *
from utils import save_data, stitch_i... |
class Car:
"""Базовый класс автомобиля"""
def __init__(self, marka, speed):
""" инициализирует атрибуты марки и скорости автомобиля"""
self.marka = marka
self.speed = speed
self.odometr_reading = 0
def car_ride(self):
return "машинка " + self.marka+" едет со скоростью... |
from math import exp
from math import log
import numpy as np
import linsepexamples
def sigmoid(arg):
return 1 / ( 1 + exp(-arg))
def log_create(name_datafile):
open(name_datafile, 'w').close()
def log_set(name_datafile, name_set, examples_set):
with open(name_datafile, 'a') as log_set:
log_set.wr... |
#!/usr/local/bin/python
from Crypto.Util.number import getStrongPrime, bytes_to_long, long_to_bytes
f = open("flag.txt").read()
m = bytes_to_long(f.encode())
p = getStrongPrime(512)
q = getStrongPrime(512)
n = p*q
e = 65537
c = pow(m,e,n)
print("n =",n)
print("e =",e)
print("c =",c)
d = pow(e, -1, (p-1)*(q-1))
c = i... |
"""This module contains functions related to Mantra Python filtering."""
# =============================================================================
# IMPORTS
# =============================================================================
# Standard Library Imports
import logging
import os
_logger = logging.getL... |
'''
Created on Mar 31, 2014
@author: tony
'''
import os
class Deleter():
'''
classdocs
'''
def fileDeleter(self,fileName):
os.remove(fileName)
print fileName + " has been removed!"
|
import asyncio
from alarme import Action
from alarme.extras.common import SingleRFDevice
class RfTransmitterAction(Action):
def __init__(self, app, id_, gpio, code, code_extra=0, run_count=1, run_interval=0.02):
super().__init__(app, id_)
self.gpio = gpio
self.code = code
self.co... |
# Generated by Django 3.0.5 on 2020-04-25 23:26
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('alunos', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='aluno',
old_name='schooL',
new_na... |
import MySQLdb
class SQL:
def __init__(self):
self.db=None
description = "This is a class"
author = "Raaj"
def connectToSQLServer(self):
self.db=MySQLdb.connect(host="",
user="",
passwd="",
db="")
def runQuery(self,query):
print query
a... |
#!/usr/bin/env python
#
# Copyright 2015-2020 Blizzard Entertainment. Subject to the MIT license.
# See the included LICENSE file for more information.
#
import os
import re
import imp
import sys
def _import_protocol(base_path, protocol_module_name):
"""
Import a module from a base path, used to import proto... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.