text stringlengths 38 1.54M |
|---|
from ..util.rabbitmq import (
connect_to,
)
def open_mq_connection(ip, port=None):
return MQbase(ip, port)
class MQbase(object):
def __init__(self, ip, port=None):
self.ip = ip
self.port = port
self.conn = None
def __enter__(self):
if not self.port:
self.co... |
import argparse
from pathlib import Path
from paramiko import SSHClient, AutoAddPolicy
class ExacloudConnection:
"""Resource manager for exacloud commands.
Helpful exacloud commands:
- View jobs in queue by user:
$ squeue -u <user>
- View all jobs by user (default is jobs since midnight, ad... |
import numpy as np
import cv2
__DB_DELIMITER__ = ':'
class Object:
"""
Reference object.
Contains information about filepath to image on disk, center point of the tag, corner
points and tag ID.
"""
def __init__(self, filename, tid, tcenter, corners, center=None, im=None):
"""
Create a new object.
:para... |
import re
import sys
import argparse
from srcs.Node import Node
from termcolor import colored
def __get_arg():
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file", help="Enter the propositionnal file", type=str)
args = parser.parse_args()
return args
def __clean_file(file: str) ->... |
#coding:utf-8
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
from django.db import models
# Create your models here.
@python_2_unicode_compatible
class Publisher(models.Model):
name = models.CharField(u'发布名称', max_length=255)
url = models.URLField(u'目标地址... |
"""
Узнав, что ДНК не является случайной строкой, только что поступившие
в Институт биоинформатики студенты группы информатиков предложили
использовать алгоритм сжатия, который сжимает повторяющиеся
символы в строке.
Кодирование осуществляется следующим образом:
s = 'aaaabbсaa' преобразуется в 'a4b2с1a2',
то ест... |
# Copyright 2013, Nachi Ueno, NTT I3, Inc.
# All Rights Reserved.
#
# 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
from alipay.aop.api.domain.AdUserQualification import AdUserQualification
class AlipayCommerceTransportAdAduserqualificationBatchqueryResponse(AlipayResponse):
def __init__(self):
... |
from django.apps.config import AppConfig
class GamesConfig(AppConfig):
name = 'games'
verbose_name = 'Games'
def ready(self):
import games.signals
default_app_config = 'games.GamesConfig'
|
from selenium.common.exceptions import NoSuchElementException
from re import search
from .utils import random_user_delay
class Messenger:
def __init__(self, driver):
self.driver = driver
def send_message(self, name, message):
"""Send a message to a friend or a group conversation
:pa... |
from django import test
from localground.apps.site import models
from django.contrib.gis.geos import Point
point = { "type": "Point", "coordinates": [12.49, 41.89] }
point2 = { "type": "Point", "coordinates": [1.24, 4.19] }
point3 = { "type": "Point", "coordinates": [124.00, 54.19] }
line = { "type": "LineString",... |
import pickle
import sys
import os
import numpy as np
import string
import re
from nltk.tokenize import TweetTokenizer
import sklearn
from sklearn.metrics import classification_report, confusion_matrix
import keras
import keras.backend as K
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequ... |
#!/usr/bin/env python
import sys
import spot_gpio
import rospy
import time
import pins
from xhab_spot.msg import *
import identity
import initializer
PUB_DELAY = 15
class PumpController(object):
def __init__(self):
print "PumpController init"
rospy.init_node("PumpController")
subtopic = "... |
from selenium import webdriver
import os
import time
from selenium.webdriver.common.keys import Keys
container = []
driver = webdriver.Firefox()
driver.get("https://www.instagram.com/")
time.sleep(5)
username = driver.find_element_by_xpath("//*[@id='react-root']/section/main/article/div[2]/div[1]/div/form/div[2]/d... |
from collections import defaultdict
class Solution:
def verticalTraversal(self, root: 'TreeNode') -> 'List[List[int]]':
if not root:
return []
seen = defaultdict(list)
cur = [(root, 0, 0)]
while cur:
nxt = []
for (node, x, y) in cur:
... |
# -*- coding: utf8 -*-
import datetime
import random
import db
from telegram.ext import Filters
from telegram.ext import MessageHandler, CommandHandler, CallbackQueryHandler, ConversationHandler
from telegram.ext import Updater
from telegram import InlineKeyboardMarkup, InlineKeyboardButton
from telegram impo... |
def auth(type_name):
from core import admin, student, teacher
def inner(func):
def wrapper(*args, **kwargs):
if type_name == 'admin':
if admin.user['obj']:
return func(*args, **kwargs)
else:
admin.login()
if ... |
# -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
... |
import itertools, threading, sys, time
class Animate:
def __init__(self):
self.run = False
self.t = None
def start(self, message):
self.run = True
self.t = threading.Thread(target = self.animate, args = [message])
self.t.start()
def animate(self, message):
for c in itertools.cycle(['|', '/', '-', '\\'... |
import numpy as np
import scipy
import scipy.ndimage
import imageio
import matplotlib.pyplot as plt
import matplotlib.patches as pat
import skimage.measure
import skimage
import glob
import smallestenclosingcircle
from sklearn.cluster import KMeans
def crofton_perimeter(I):
""" Computation of crofton perimete... |
import numpy as np
import sys
sys.path.append('../code')
from helpers import visualize,util
import matplotlib.pyplot as plt
from PIL import Image
import os
os.environ['GLOG_minloglevel'] = '3'
import caffe
import cPickle as pkl
import glob
import scipy.special
import multiprocessing
def save_im((attention_weight,atte... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index),
path('add-student', views.add_student),
path('add-college', views.add_college),
] |
#!python
# log/urls.py
from django.conf.urls import url
from . import views
# We are adding a URL called /home
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^createcontact/$', views.createcontact, name='createcontact'),
url(r'^update/(?P<pk>\d+)/$', views.update, name='update'),
url(r'^del... |
from selenium import webdriver
class youtube():
def __init__(self):
self.driver = webdriver.Chrome(
executable_path='C:/Users/laksh/Downloads/chromedriver.exe')
def playVideo(self, query):
self.query = query
self.driver.get(
url='https://www.youtube.com/results... |
from enum import Enum
class Assay(Enum):
def __new__(cls, key: str, fastq_count: int):
obj = object.__new__(cls)
obj._value_ = key
obj.fastq_count = fastq_count
return obj
def __str__(self):
return self.value
SNARESEQ = "snareseq", 3
SCISEQ = "sciseq", 2
S... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 17 17:10:59 2020
@author: K.Bjerkelund
"""
import folium
import pandas as pd
from folium import plugins
from datetime import timedelta, date
import numpy as np
def daterange(start_date, end_date):
for n in range(int((end_date - start_date).days)):
yield star... |
"""
Created 07:25:34 14/04/2021
Dasturlash asoslari
Muallif: Xatamjonov Ulugbek
#19-dars: FUNKSIYADAN QIYMAT QAYTARISH
Amaliyot https://python.sariq.dev web sahifasi asosida.
"""
#1
# Foydanaluvchidan ismi, familiyasi, tug'ilgan yili, tug'ilgan joyi,
# email manzili va telefon raqamini qabul qilib, lug'at ko... |
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
# 画曲线图
x = np.linspace(0, 5, 50)
y_cos = np.cos(x)
y_sin = np.sin(x)
plt.figure()
plt.plot(x, y_cos) # x—aixs, y-axis
plt.plot(x, y_sin)
plt.xlabel('x')
plt.ylabel('y')
plt.title('title')
plt.show()
print(list(mpl.rcParams['a... |
# coding: utf-8
"""
DataDomain Rest API Documentation
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolu... |
from .utils import get_tensor
def down_force(t):
return ExternalForce.DOWN
def vert_impulse(t):
if t < 0.1:
return ExternalForce.DOWN
else:
return ExternalForce.ZEROS
def hor_impulse(t):
if t < 0.1:
return ExternalForce.RIGHT
else:
return ExternalForce.ZEROS
d... |
import numpy as np
from graphics import GraphWin
from lab6 import plrpd_draw_lagrange, dimetric, draw_background
# Параметри паралелепіпеда ------------------------------------
xw = 600
yw = 600
st = 130
TetaG1 = 120
TetaG2 = 10
# Розташування координат у строках:
# дальній чотирикутник - A B I M, ближній чотирикутни... |
x_coef = float(input("What is the coeficent for x? "))
y_coef = float(input("What is the coeficent for y? "))
operator = input("What is the operator? ")
equality = float(input("What is " + str(x_coef) + "x" + operator + str(y_coef) + "y = ? " ))
x_value = float(input("What is the value of x? "))
y_value = float(input("... |
#!/usr/bin/env python
import feedparser
import sys
from time import mktime
from datetime import datetime
import smtplib
class Mailer( object ):
def __init__(self, email_sender, email_to, relay, logger=None):
self.email_sender = email_sender
self.email_to = email_to
self.relay = relay... |
# -*- coding: utf-8 -*-
#Ver 0.3.1 edited at 2013-07-23-23:56
#Changes: animation, goto func
#Changes: data updates
#Changes: initialize
#need to change: error sended in showstatus func
#replay widget
from Ui_2DReplayScene import *
class Ui_2DReplayWidget(Ui_2DReplayView):
def __init__(self, scene, parent = No... |
# Checks user input (either full word or first letter of word)
def string_checker(question, to_check):
valid = False
while not valid:
# ask user question and change response to lowercase
response = input(question).lower()
if response == "xxx":
return response
# check response is in list OR that it's the ... |
from django.db import models
from django.contrib.flatpages.models import FlatPage
class Navigation(models.Model):
name = models.CharField(max_length=30)
flatpage = models.ForeignKey(FlatPage, blank=True)
static_url = models.CharField(max_length=255,
help_text="Example: '/... |
from django.shortcuts import render, reverse, redirect
from .models import Comment
from django.views.decorators.http import require_http_methods
from django.template.defaultfilters import escape
import bleach
from bleach.sanitizer import ALLOWED_ATTRIBUTES, ALLOWED_TAGS
def index(request):
context = {
'co... |
from django.test import TestCase
from accounts.forms import *
from accounts.models import *
from appointment.forms import *
class PatientRegisterFormTest(TestCase):
def setUp(self):
hospital = Hospital.objects.create(name="Hospital", address="Address")
hospital.save()
user = User.objects.c... |
import numpy as np
from simpleRotate.numpy import euler2RM, RM2euler
R = euler2RM([0.5, 0, 0])
p1 = np.array([1, 0, 0])
p2 = np.array([0, 1, 0])
p3 = np.array([0, 0, 1])
p1_ = np.dot(R, p1)
p2_ = np.dot(R, p2)
p3_ = np.dot(R, p3)
P = np.stack([p1, p2, p3], axis=1)
P_ = np.stack([p1_, p2_, p3_], axis=1)
print(P)
pr... |
import sys
import queue
def bfs(map, visit):
q = queue.Queue()
count = 0
for i in range(n):
for j in range(n):
if visit[i][j] == False:
visit[i][j] = True
check_color = map[i][j]
q.put([j, i])
while q.qsize() != 0:
... |
class Character:
def __init__(self, name, current_room, health, focus, gold, atk, defense, description):
self.name = name
self.current_room = current_room
self.health = health
self.focus = focus
self.gold = gold
self.inventory = []
self.atk = atk
self.... |
from tabulate import tabulate
import sys
sys.path.append("/workspace/Financial_Statement/src/common")
import UrlGenerator
import RequestFactors as rf
import UrlToInfo
import DcInfoBrowse
# 유저입력 012221
def check_recapitalization():
list_of_essential_cds = [rf.corp_code, rf.bsns_year, rf.reprt_code]
condition_... |
from flask import Flask
from flask import request
import numpy as np
from copy import copy
import json as json
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def hello():
class Vector2(object):
x = None
y = None
def __init__(self, x, y):
self.x = x
self.y = y
def getJson(... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from user.models import User
# Register your models here.
"""
class UserAdmin(admin.ModelAdmin):
list_display = ('username','name', 'lastName', 'range', 'rate',)
list_filter = ('username','name', 'lastName', 'range', 'rate',... |
# -*- utf-8 -*-
#@Time :2019/6/3016:29
#@Author :无邪
#@File :__init__.py.py
#@Software:PyCharm |
# Convert:
# http://www.conwaylife.com/wiki/Run_Length_Encoded
# To:
# http://www.conwaylife.com/wiki/Apgsearch_format
import sys
encoding = "0123456789abcdefghijklmnopqrstuv"
def parse_rle(s):
# Note that, when parsing numbers, they can be more than one character long
worldlines = [[]]
maxlen... |
import random
import numpy as np
import re
program = """import sqlite3
dataset_path = 'prutor-deepfix-09-12-2017.db'
with sqlite3.connect(dataset_path) as conn:
cur = conn.cursor()
query = "SELECT user_id, tokenized_code FROM Code;"
code = []
coder = ()
for row in cur.execute(query):
user_id, toke... |
import Box2D
#########################################################################
######### This class is for calculating game physics using Box2D ########
#########################################################################
# iteration constants for use in game loop
timeStep = 1.0 / 60
vel_iters, pos_iters ... |
from sqlalchemy import Column, String, Integer, ForeignKey
from sqlalchemy.ext.declarative import declarative_base, ConcreteBase
from sqlalchemy.orm import relationship
from geoalchemy2 import Geometry
Base = declarative_base()
class CommonCelestial(object):
id = Column(Integer, primary_key=True)
name = C... |
import logging
import unittest
from Orange.data import Table
from orangecontrib.imageanalytics.image_grid import ImageGrid
class ImageGridTest(unittest.TestCase):
def setUp(self):
logging.disable(logging.CRITICAL)
self.grid = ImageGrid(Table("wine"))
def tearDown(self):
logging.disa... |
#!/usr/bin/env python3
import sys
print(sys.version)
old, new = 0, 1
for i in range(10):
print(f"{i=}, {old=}, {new=}")
old = new
new = old + new
|
import typing as typ
from pprint import pprint
import requests
from io import BytesIO
import attr
from hashlib import sha1
from libsvc.endpoint import Endpoint, Serializable, UID
from libsvc.rest_agent import RestAgent, RTy
from diana.dicom import DLv
from diana.dixel import Dixel
def dlvl_to_orthanc_resource(dlvl: D... |
from django.shortcuts import get_object_or_404
from product.models import Product
from decimal import Decimal
def get_cart_items_and_total(cart):
cart_total = 0
cart_items = []
for key in cart:
product = get_object_or_404(Product, pk=key)
quantity = cart[key]
cart_ite... |
import rps.robotarium as robotarium
import rps.utilities.graph as graph
from rps.utilities.transformations import *
from rps.utilities.barrier_certificates import *
from rps.utilities.misc import *
from rps.utilities.controllers import *
import numpy as np
import time
import traj_utils
from PriorityQueue import Priori... |
import requests #библиотека для работы с http запросами
from bs4 import BeautifulSoup #для работы с html страницами
import csv #модуль для работы с CSV
URL = 'https://kazandigital.ru/catalogue_category-category_id-47.html' #url сайта
URL1 = 'https://www.skynet-kazan.com/root/map'
HEADERS = {'user-agent': 'Mozilla/5.0 ... |
import pytest
from dotenv import find_dotenv, load_dotenv
from unittest.mock import patch, Mock
import os
import todo_app.app as app
@pytest.fixture
def client():
# Use our test integration config instead of the 'real' version
file_path = find_dotenv('.env.test')
load_dotenv(file_path, override=True)
#... |
try:
a = int(input('Numerador: '))
b = int(input('Denominador: '))
r = a / b
#except: -> dá para criar vários 'except', definindo seus erros, e criando um bloco pra cada um
# print('Infelizmente tivemos um problema :(')
#except Exception as erro:
# print(f'Problema encontrado foi: {erro.__class__}'... |
#so vi khuan = so vi khuan ban dau x 2 mu (so lan phan chia)
# ** la luy thua trong python
bacteriass = int(input("nhap so vi khuan vao: "))
timess = int(input("so phut: "))
k = bacteriass * 2** timess
print("sau",timess,"phut, chung ta co",k,"con vi khuan!!!")
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2018-04-23 10:46
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ui', '0022_auto_20180420_0931'),
]
operations = [
... |
# -*- coding: utf-8 -*-
"""
Modulo per la gestione del comando per dar pugni.
"""
#= IMPORT ======================================================================
from src.gamescript import check_trigger
from src.log import log
#= FUNZIONI ======================================================... |
n, k = map(int, input().split())
l, r = [], []
mod = 998244353
for i in range(k):
tmp = tuple(map(int, input().split()))
l.append(tmp[0]), r.append(tmp[1])
dp = [0 for i in range(n)]
dp[0] = 1
for i in range(0, n - 1):
dp[i] = dp[i - 1]
for j in range(k):
if r[j] >= 0:
dp[i] += dp... |
import unittest
from django.core.urlresolvers import reverse
from django.test import Client
from .models import Sesion, Castigo
from django.contrib.auth.models import User
from django.contrib.auth.models import Group
from django.contrib.contenttypes.models import ContentType
def create_django_contrib_auth_models_user... |
import os.path
import numpy.random
from amuse.units import nbody_system, units
from amuse.io import write_set_to_file
from amuse.ic.kingmodel import new_king_model
from amuse.ic.flatimf import new_flat_mass_distribution
from amuse.couple.collision_handler import CollisionHandler
from amuse.couple.parallel_stellar_ev... |
from plone.app.contentrules import handlers
from unittest import TestCase
from zope.lifecycleevent import ObjectAddedEvent
from zope.lifecycleevent import ObjectRemovedEvent
class TestModifyAction(TestCase):
def setUp(self):
self.called = False
def register_call(testcase):
def inner_r... |
from typing import List
class contests2020q4.leetcode20201017.Solution:
def getNoZeroIntegers(self, n: int) -> List[int]:
def haszeros(n):
mystr = str(n)
for char in mystr:
if char == '0':
return(True)
return(False)
a... |
#Author: tripp
#Desc: takes in a bunch of hashes and will attempt to decrypt them
import sys, getopt, hashlib,time
def main(argv):
print
charset = ""
encryption = ""
hashFile = ""
outputFile = ""
minLength = 0
maxLength = 0
variedChars = 0
userCharset = False
verbrose = False
u... |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------------
# Shapfile AddEditInfo & rename
# "for" loop
# ListDatasets.py
# Append.py
# Created on: 2021-04-14 18:09:12.00000
# (generated by ArcGIS/ModelBuilder)
# Description:
# -------------------------------------... |
import math
import pygame
import logging
import game_button
import constants as _c
from image_grid_cell import ImageCell
class ScrollGrid:
def __init__(self, n_cols, width, height, img_list,
disp, x_pos, y_pos, x_pad=2, y_pad=2, scroll_width=10,
log=logging.getLogger(), bg_color=_c.BUTTO... |
#!/bin/env python
#
# Example 3: Two-Body problem
#
# Arnau Miro, 2018
# Last rev: 2020
from __future__ import print_function
import numpy as np
import pyRKIntegrator as rk
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
plt.style.use('ggplot')
# Parameters
G = 6.674e-11*1.... |
from flask import Flask, request
from rockset import Client, Q
import json
app = Flask(__name__, static_url_path='')
rs = Client()
@app.route("/")
def index():
return app.send_static_file('explore.html')
@app.route("/rs/collections")
def rs_collections():
return json.dumps(rs.list())
@app.route("/rs/collect... |
"""mystore URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based... |
#!/usr/bin/python
import sqlite3
import time
StartTime=time.time()
DBTable = 'AvailablePacakges'
DBFolder = 'Cache'
DBPath = DBFolder+'/Master.sqlite'
db = sqlite3.connect(DBPath)
c = db.cursor()
Tags=['Package', 'Name', 'Section', 'Description', 'Publisher', 'Status',
'Contact', 'Source', 'Tag', 'Depends', 'H... |
"""
前処理その4
・履歴テーブルの情報を SK_ID_CURR をキー、50件の np.ndarray を値として保有するdictionaryに変換する
・50件に満たない場合はすべて0の行を追加して50件とする
ニューラルネットワーク(エンベディング層あり)の処理高速化のため
"""
import argparse
import joblib
from multiprocessing import Pool
import pandas as pd
from tqdm import tqdm
from util import read_all, SORT_KEYS, expand, dump
from model impor... |
from abc import ABC, abstractmethod
import pandas as pd
from src.settings import chart
from src.utils import Features
class Food(ABC):
g: int
# raw features for 100g
__features__: Features
# features scaled on g
features: Features
@property
@abstractmethod
def name(self) -> str:
... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 15 14:38:21 2017
@author: tugg
"""
import sys
import pandas as pa
from pyDatalog import pyDatalog
# ---------------------------------------------------------------------------
# Social graph analysis:
# work through this code from top to bottom (in... |
import urllib.request
try:
urllib.request.urlopen('https://www.google.com')
except: # -no-cov-
HAS_INTERNET = False
else:
HAS_INTERNET = True
|
from django.db import models
import re
class UserManager(models.Manager):
def basic_validator(self, data):
errors={}
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
if len(data['first_name'])<1:
errors['first_name']="Please enter your first name!"
... |
#test_app.py
#coding:utf-8
#third party imports
from flask_testing import TestCase
import unittest
import json
#local import
from app import create_app, db
class TestBase(TestCase):
""" common class"""
def create_app(self):
config_name = 'testing'
self.app = create_app(config_name)
... |
# 'val' is a group that is 'list' defined python
#about Entering number set off a clause by a comma
val = [int(a) for a in input("Enter Numbers set off a clause by a comma : ").split(',')]
print (val) # printing list
print (tuple(val)) # printing tuple
|
import contextlib
import time
from socket import socket
from unittest import TestCase
from octoprint_discordremote.genericforeversocket import GenericForeverSocket
class TestDiscordLink(TestCase):
def test_start_stop_rapid(self):
gfs = GenericForeverSocket(address='127.0.0.1', port=34567, read_fn=(), wr... |
#!/usr/bin/python
#Write a Python program to accept a filename from the user and print the extension of that
filename = raw_input("Input the Filename: ")
if "." not in filename:
print ("Plese entrer correct extention of the file")
else:
extn=filename.split(".")
print ("The extension of the file is : %s " % ... |
import warnings
from typing import List
import matplotlib.pyplot as plt
import numpy as np
from numpy import linalg as LA
from numpy import random
from numpy.linalg import inv
from pomegranate import (
DiscreteDistribution,
GammaDistribution,
GeneralMixtureModel,
IndependentComponentsDistribution,
... |
import socket
ENCODING = "utf-8"
SOCKET_ADDRESS = "/tmp/bottisota.sock"
class Error(Exception):
pass
class NoMessageError(Error):
pass
class SyscallError(Error):
def __init__(self, err):
self.err = err
def __str__(self):
return "Syscall error %d" % self.err
def connect_socket(add... |
from setuptools import setup
setup(
name='aiosteam',
version='1.0',
py_modules=['aiosteam'],
install_requires=[
'aiohttp',
'beautifulsoup4'
]
) |
from django.conf.urls import patterns, include, url
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import login
from django.contrib.auth import views as auth_views
from trademap import views
from trademap.views import *
urlpatterns = [
url(r'^login/$', ... |
from django.contrib.admin import AdminSite as DefaultAdminSite
from django.utils.translation import gettext_lazy
class AdminSite(DefaultAdminSite):
'''
https://github.com/django/django/blob/master/django/contrib/admin/sites.py#L30
'''
title = 'Monday Night Lights'
site_title = gettext_lazy(title)
... |
#!/usr/bin/python
"""
====================================================================================
Author: Tao Li (taoli@ucsd.edu)
Date: Jun 21, 2015
Question: 029-Divide-Two-Integers
Link: https://leetcode.com/problems/divide-two-integers/
=============================================================... |
from stdnet.utils import test, populate, zip, iteritems, to_string
from examples.models import Dictionary
from .struct import MultiFieldMixin
keys = populate('string', 200)
values = populate('string', 200, min_len=20, max_len=300)
class TestMultiField(test.CleanTestCase):
multipledb = 'redis'
model... |
import socket
import tokens
import connection
import io
import os
import threading
from PIL import Image
from message.literalMessage import LiteralMessage
from baseApplication import BaseApplication
import asynclib
class MinionApplication(BaseApplication):
def __init__(self, host, port): ... |
#!/usr/local/bin/python
import sys
sys.path.append('/Users/sanchaysaria/work/financial_analysis/src/pybase/pylib/')
sys.path.append('/Users/sanchaysaria/work/financial_analysis/src/pybase/abstractDB/')
import common
import logging
import sqlite3
import abstractDB
logging.basicConfig(level=logging.DEBUG)
def main() ... |
from dataclasses import dataclass, field
# Type hinting
from typing import Iterable, Optional, Union, Any, Dict
BatchSizeType = Optional[Union[int, float]]
@dataclass
class AugmenterConfig:
"""Base class for defining the augmenter configurations."""
pass
@dataclass
class FullAugmentKind(AugmenterConfig):
... |
# 집합 (set)
# 중복 안됨, 순서 없음
my_set = {1,2,3,3,3}
print(my_set)
# java = {"유재석", "김태호", "양세형"}
# python = set(["유재석", "박명수"])
# # 교집합
# print(java & python)
# print(java.intersection(python))
# # 합집합 (java나 python 할 수 있는 개발자 )
# print(java | python)
# print(java.union(python))
# # 차집합 (java는 할 줄 알지만 python을 할 줄 모르는 개... |
# -*- coding: utf-8 -*-
from argparse import ArgumentParser
from mock import patch
from os import getcwd
from photorenamer import main, parse_args
from photorenamer.exceptions import InvalidPathError
from unittest import TestCase
class MainTestCase(TestCase):
def test_main_should_raise_invalid_path_error_when_pa... |
class Node:
"""
Simple class definition for a Node, in case of trees where nodes may have more
than two children, a `children` list could be used to contain these references instead.
The important thing to note about this representation is that the attributes
`left` and `right` will become referenc... |
from django.conf import settings
# Site protocol (http:// or https://)
SITE_PROTOCOL = getattr(settings, 'SITE_PROTOCOL', 'http://')
# Request url
IPAYMU_REQUEST_URL = getattr(settings, 'IPAYMU_REQUEST_URL', 'https://my.ipaymu.com/payment.htm')
# iPaymu API KEY
IPAYMU_APIKEY = getattr(settings, 'IPAYMU_APIKEY', None... |
"""CLI commands for ML operations."""
#!/usr/bin/env python
import click
import requests
import model
from utils import load_file
@click.group()
@click.version_option("0.1")
def cli():
"""Machine Learning Utility Belt"""
@cli.command("retrain")
def retrain():
"""Retrain Model
Retrain the model with the... |
#!/usr/bin/env python
# -*- coding:utf8 -*-
"""
Brief: 将各种编码类型的内容转换为unicode编码
Author: tianxin(15626487296@163.com)
Date: 2017/01/08 20:23:45
"""
def decode(webpage):
"""decode webpage with different encoding to unicode
Args:
webpage: content of webpage which encoding might be
... |
#detect faces from video stream using face_recognition cnn
from imutils.video import VideoStream
import numpy as np
import imutils
import cv2
import face_recognition
vs = VideoStream(src=0).start()
while True:
frame = vs.read()
frame= cv2.flip(frame,1)
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
boxes = face_rec... |
# -*- encoding: utf-8 -*-
###########################################################################
# Module Writen to OpenERP, Open Source Management Solution
# Copyright (C) OpenERP Venezuela (<http://openerp.com.ve>).
# All Rights Reserved
# Credits######################################################
# ... |
import nltk
import json
import os
from analysis.nltk_ibm import *
from models.ibm_model import *
def app_check():
print("Checking for dataset ...")
print("Searching for en_fr.json")
for f in os.listdir("./data"):
if str(f).find("data1.json") or str(f).find("data2.json"):
print("Dataset... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.