text stringlengths 38 1.54M |
|---|
from rest_framework.test import APITestCase
from rest_framework import status
from django.contrib.auth.models import User
from rest_framework_jwt.settings import api_settings
import json
JWT_DECODE_HANDLER = api_settings.JWT_DECODE_HANDLER
class AuthTests(APITestCase):
def tearDown(self):
User.object... |
num = input("Enter a number: ")
def validate_num(n):
rest = [int(i) for i in list(n)][::-1]
check = rest.pop(0)
for i in range(len(rest)):
if i %2 == 0:
rest[i] *= 2
for i in rest:
if i > 9:
rest[rest.index(i)] -= 9
return ((sum(rest) + int(check))%10 == ... |
# coding: utf-8
from flask import Flask
from flask import render_template
from flask import request,redirect,flash,get_flashed_messages,url_for,escape
from sqlalchemy import *
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
import datetime
app = Flask(_... |
# -*- coding: utf-8 -*-
import os
from flask import Flask, url_for, request, redirect, render_template, make_response, jsonify
from flask.views import View
from werkzeug.wrappers import Response
from flask_sqlalchemy import SQLAlchemy
import settings
from application import user
project_dir = os.path.dirname(os.pa... |
from django.contrib import admin
# Register your models here.
from .models import contact, advice
admin.site.register(contact)
admin.site.register(advice)
|
#!/usr/bin/python
__author__ = 'thovo'
import sys
def ibm1():
#Check for arguments
args_length = len(sys.argv)
print "The number of arguments: "+str(args_length)
i = 0
while i < args_length:
print "The argument number " + str(i) + " is " + str(sys.argv[i])
i += 1
ibm1() |
from PIL import Image
from matplotlib import pyplot as plt
histo = [0]*256
histo2 = [0]*256
histo3 = [0]*256
cdf = [0 for i in range(256)]
image = Image.open('lena.bmp')
dark_image = image.copy()
result = dark_image.copy()
(h , w) = image.size
for i in range(h):
for j in range(w):
dark_im... |
#===============================================================================
# 31564: Cancel adding a subject in new message/multimedia message
#
# Procedure:
# 1. Open Messaging/multimedia message app
# 2. Create a new message/multimedia message
# 3.Tap on the top-right icon to show the options menu (ER1)
# 4. Tap... |
import inputs_fixed_len
import tensorflow as tf
import argparse
import os
import model
import re
import time
import numpy as np
import utils
import matplotlib.pyplot as plt
import sklearn.ensemble
import sklearn.metrics
import pickle
import itertools
parser = argparse.ArgumentParser()
parser.add_argument('-model', ty... |
from resources import database
from .helpers import login, signup
async def resolve_login(_, info, **kwargs):
try:
username = kwargs.get('username')
password = kwargs.get('password')
token = login(username, password)
if token :
payload = {
"success": True... |
# coding=utf-8
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.ext.declarative import declarative_base
db = SQLAlchemy()
class names(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.UnicodeText)
epithet_id = db.Column(db.Integer)
class epithets(db.Model):
id = db.C... |
from dataProcessor import ImageFileHandler
from Classifiers.SVM.lsvc import LinearSupportVectorClassifier
import logging
logging.basicConfig(filename="svm.log",level=logging.INFO)
def logging_wrapper(func):
def inner(*args, **kwargs):
try:
func(*args, **kwargs)
except Exception as e:
... |
import math
from math import sqrt
import argparse
from pathlib import Path
# torch
import torch
from torch.optim import Adam
from torch.optim.lr_scheduler import ExponentialLR
# vision imports
from torchvision import transforms as T
from torch.utils.data import DataLoader
from torchvision.datasets import ImageFolde... |
import os
import csv
import multiprocessing
import pdf2image
# For some reason pytype doesn't like pdftotext
import pdftotext # type: ignore
from typing import Tuple, List
def _get_image_tag(image_filename: str) -> str:
return "<img src='" + image_filename + "'>"
class PDFToAnkiCardsConverter:
def __init_... |
import argparse
import copy
import json
import os
import pickle
import re
import sys
import traceback
from collections import Counter, defaultdict
import glob
import itertools
import shutil
import difflib
from nltk import word_tokenize, pos_tag, bigrams, ngrams
from canonical_relations import canonical_relations as ... |
"""NNPS utility functions to work with Zoltan lists"""
import numpy
from pyzoltan.core.zoltan import get_zoltan_id_type_max
from pysph.base.particle_array import ParticleArray
UINT_MAX = get_zoltan_id_type_max()
def invert_export_lists(comm, exportProcs, recv_count):
"""Invert a given set of export indices.
... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging
from odoo import fields, models, _
_logger = logging.getLogger(__name__)
class BusinessBorrower(models.Model):
'''BusinessBorrower class represent a business entity that applies for a loan,'''
... |
import operator
import json
from collections import Counter
import Tweet_processing_func as tp
from nltk.corpus import stopwords
import string
from collections import defaultdict
# com[x][y] contains the number of times the term x has been seen in the same tweet as the term y
com = defaultdict(lambda: default... |
#!/usr/bin/env python
# Author: oscar.kene@klarna.com
#
# Manages zones on fortigates in fortimanager
from ansible.module_utils.basic import AnsibleModule
import requests
import json
from Forti import FortiMgr
def main():
module = AnsibleModule(
argument_spec=dict(
username=dict(type='str', re... |
celsius = float(input('Write a temperature in ºC:'))
fahrenheit = (celsius * 9/5) + 32
print('This temperature ºC {} in Fahrenheit is ºF {}'.format(celsius,fahrenheit))
|
import distutils
import itertools
import os
import re
import shutil
import subprocess
import sys
from typing import Dict, List
from distutils.command.bdist import bdist as _bdist
from distutils.command.install_data import install_data as _install_data
from distutils import log
# requires setuptools >= 64.0.0
import se... |
from pydoc import describe
from numpy import empty
import pandas as pd
import numpy as np
import re
# import bs4
import json
import requests
import time
import sys,os
sys.path.append(os.path.abspath(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
sys.path.append(r"C:\Users\kaiyu\Desktop\miller")
from che... |
tobeSorted = "94848448"
a = [0] * 10
for i in tobeSorted:
b=int(i)
a[b] = a[b] + 1
i=0
while(i<len(a)):
if(a[i]==0):
i=i+1
continue;
else:
for j in range(0,a[i]):
print(i)
i=i+1
|
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
user_model = get_user_model()
class ContactForm(forms.Form):
name = forms.CharField(
label=' نام ',
widget=forms.TextInput(attrs={'class':'form-control', 'placeholde... |
import os
import base64
from flask import make_response
# from flask import send_file
class ResultService:
@classmethod
def get_result(cls, job_id):
path = 'FilesFolder/yaml_gen/%s.zip' % job_id
if os.path.exists(path):
with open(path, 'rb') as f:
content = f.read(... |
import os
import pytest
from impc_etl.transformations.experiment_transformations import _get_closest_weight
from impc_etl.jobs.clean.experiment_cleaner import *
from impc_etl.jobs.clean.specimen_cleaner import clean_specimens
from impc_etl.jobs.extract.impress_extractor import extract_impress
from impc_etl.jobs.extra... |
n,k=map(int,input().split(' '))
arr=[]
for i in range(n):
arr.append(int(input()))
i=len(arr)-1
count=0
while True:
if 0==k:
break
if k>=arr[i]:
count+= k//arr[i]
k%=arr[i]
i-=1
print(count) |
from __future__ import absolute_import
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from Qshop.celery import app
@app.task
def add():
x = 1
y = 2
return x+y
@app.task
def sendmail():
#第三方SMTP服务
from Qshop.settings import MAIL_PORT,MAIL_SENDER,MAIL_SERVER,MAI... |
# coding: utf-8
# In[2]:
import pandas as pd
import matplotlib.pyplot as plt, matplotlib.image as mpimg
from sklearn.model_selection import train_test_split
from sklearn import svm
get_ipython().run_line_magic('matplotlib', 'inline')
# In[3]:
labeled_images = pd.read_csv('/home/andrei/PycharmProjects/ds-ml/MNIS... |
#!/usr/bin/python
import re
urlForUserName = "https://www.youtube.com/user/JorgeLuisPeralta"
urlChannel = "https://www.youtube.com/channel/UC-q80GTFK2A0Y6I5ClT-8TQ"
exRegUser = r'https://www.youtube.com/user/(.*)'
exRegChannel = r'https://www.youtube.com/channel/(.*)'
matchUrlUser = re.match( exRegUser, urlForUserNa... |
from matplotlib import pyplot as plt
from PIL import Image
from pathlib import Path
if __name__ == '__main__':
csv_path = Path('train_result.csv')
with csv_path.open() as f:
x_times = 5
y_times = 5
fig = plt.figure()
for i in range(1, x_times * y_times + 1):
info ... |
from threading import *
import time
l = Lock()
def wish(name):
l.acquire()
for i in range(10):
print("[ Good Evening : ", end="")
time.sleep(1)
print(name, ']')
l.release()
t1 = Thread(target=wish, args=("Dhoni",))
t2 = Thread(target=wish, args=("Yuvraj",))
t3 =... |
import aiohttp
from collections import defaultdict, deque
from pathlib import Path
from functools import partial
import asyncio
from .constants import MatColors, GRAPH_TYPES, SAMPLING_FREQS
from .charts import CHARTS
import os
import streamlit as st
def add_custom_css():
st.markdown(
f"""
... |
#!/usr/bin/python
####################################
# Py joins on number ranges
# author: vladimir kulyukin
####################################
range1 = xrange(1, 6)
def join_number_range(separator, rng):
return separator.join([str(x) for x in rng])
def range_tests(r):
print join_number_range('*', r)
... |
def fak(n):
if n == 1:
return 1
return n * fak(n -1)
rest = fak(100)
answer = 0
while rest > 0:
answer += rest % 10
rest /=10
print answer
|
import math
import os
import random
import re
import sys
# Complete the hourglassSum function below.
def hourglassSum(arr):
i,j=0,0
maxnum=-1*9*9-1
for i in range(len(arr)):
if i == len(arr)-2:break
for j in range(len(arr[i])):
if j == len(arr[i])-2:break
a,b,c,d,e,f... |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
# Define 3D shape
block = np.array([
[[1, 1, 0],
[1, 0, 0],
[0, 1, 0]],
[[1, 1, 0],
[1, 1, 1],
[1, 0, 0]],
[[1, 1, 0],
[1, 1, 1],
[0, 1, 0]],
[[1, 0, 0],
[1, 1, ... |
from django.test import TestCase
from channels.models import Channel
from talks.models import Talk
# Create your tests here.
class SitemapTest(TestCase):
def setUp(self):
chanel_1 = Channel.objects.create(code='1', title='channel title 1')
Talk.objects.create(code='1', title='talk title 1', cha... |
import requests
from Get_All_Course import get_all_course
from Get_Exam_List import main as exams
def examlist(stuid):
courses = get_all_course(stuid)
openClassId = courses['openClassId']
courseOpenId = courses['courseOpenId']
exam_list = exams(openClassId, courseOpenId, stuid)
index = 1
for ... |
import os
import subprocess
goodPing = "1 received"
os.chdir("/home/vagrant/project/lingi2142")
#subprocess.call(["sudo","./create_network.sh","project_topo"])
t=subprocess.Popen("ls",stdout=subprocess.PIPE)
print(t.communicate())
locations = ["SH1C","HALL","PYTH","STEV","CARN","MICH"]
prefixA = "fd00:3:0f"
print(... |
#-*- coding:utf-8 -*-
#tornado web site
import os
import sys
import urllib
import math
import time
import string
import tornado.wsgi
import tornado.httpserver
import tornado.ioloop
import tornado.web
from tornado.httpclient import HTTPClient
from tornado.escape import json_encode, json_decode
import map_logic
from... |
import csv
#import pip._vendor.requests as requests
import requests
import logging
import os
import argparse
from requests import ReadTimeout, ConnectTimeout, HTTPError, Timeout, ConnectionError
class MergeCsvRecords(object):
def __init__(self, url='http://interview.wpengine.io/v1/accounts'):
self.url = ur... |
#import RPi.GPIO as GPIO
import time
import serial
port = serial.Serial("/dev/ttyAMA0", baudrate=115200, timeout=1.0)
#var count = 0
#GPIO.setmode(GPIO.BCM)
#GPIO.setup(25, GPIO.OUT)
while True:
#GPIO.output(25, False)
port.write("hello from Rpi\r\n");
time.sleep(1000) |
'''
Created on 20.11.2016
@author: simon
'''
from distutils.core import setup,Extension
from Cython.Build import cythonize
ext=Extension(name="filters",
sources=["filters.pyx"],
extra_compile_args=['-fopenmp'],
extra_link_args=['-lgomp','-fopenmp']
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 3 15:18:09 2020
@author: Justyn
"""
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.except... |
dInicial = int(input().split()[1])
h = input().split(':')
hi = int(h[0])
mi = int(h[1])
si = int(h[2])
dFinal = int(input().split()[1])
h = input().split(':')
hf = int(h[0])
mf = int(h[1])
sf = int(h[2])
days = dFinal - dInicial
hour = hf - hi
if hour < 0:
hour += 24
days -= 1
min = m... |
import sys
import listsearch
sys.path.append(r"C:\DevLcl\Sandbox\python-sandbox\think_python\chapter_10")
fin = open(r'C:\DevLcl\Sandbox\python-sandbox\think_python\words.txt')
def word_list():
thelist = []
for line in fin:
thelist.append(line.strip())
return thelist
def find_interlocks2(mylist,... |
'''
Created on Dec 30, 2020
@author: mballance
'''
import asyncio
import datetime
import multiprocessing
import os
import subprocess
import sys
from asyncio.subprocess import DEVNULL, STDOUT
from asyncio.tasks import FIRST_COMPLETED
from colorama import Fore
from colorama import Style
from typing import List
from mkd... |
import uuid
import src.models.users.constants as UserConstants
from src.common.database import Database
from src.common.utils import Utils
from src.models.notebooks.notebook import Notebook
from src.models.tags.tag import Tag
import src.models.users.errors as UserErrors
class User(object):
def __init__(self, user... |
import dash
from dash.dependencies import Input, Output
import dash_html_components as html
import dash_core_components as dcc
import dash_alternative_viz as dav
import plotly_express as px
import altair as alt
from bokeh.embed import json_item
import holoviews as hv
import matplotlib.pyplot as plt
import seaborn as sn... |
"""Run a Flask web server for symbol recognition."""
# Core Library modules
import base64
import io
from pathlib import Path
from typing import Any, Dict
# Third party modules
from flask import Flask, render_template, request
from PIL import Image
def create_app(model: Path, labels: Path) -> Flask:
app = Flask(... |
from django import forms
from .models import InputModel
# from .models import Location
#
# class LocationForm(forms.ModelForm):
# class Meta:
# model = Location
# fields = "__all__"
class InputFormModel(forms.ModelForm):
class Meta:
model = InputModel
fields = ('info', )
d... |
# Author: Matthew Shelbourn | Student ID: 001059665 | mshelbo@wgu.edu | December, 2020
# distance.py ingests data from "WGUPS Distance Table.csv", assigns them to objects for use in program
import csv
# Ingest distance data from 'wgups-distance-data.csv' and assign to list
# Space-time complexity O(N)
with open('./da... |
def employee(name, *manager):
print name
print manager
employee('Mohan')
employee('akash','jatin')
------------------------------------------------------------------------------------
def employee(name.**kwargs):
print name
print kwargs
employee('jatin')
employee('jatin', age=35, manager='rahul', lo... |
"""
.. moduleauthor:: Johan Comparat <johan.comparat__at__gmail.com>
.. contributor :: Sofia Meneses-Goytia <s.menesesgoytia__at__gmail.com>
.. contributor :: Violeta Gonzalez-Perez <violegp__at__gmail.com>
.. contributor :: Harry Hicks <iamhrh__at__hotmail.co.uk>
.. contributor :: Justus Neumann <jusneuma.astro__at__g... |
#Copyright (C) 2017 Interview Druid, Parineeth M. R.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
from __future__ import print_function
import sys
import random
MAX_NUM_ELEMENT... |
import csv
import io
import logging
import warnings
from urllib.parse import quote as urlquote
import dateutil.parser
import msgpack
log = logging.getLogger(__name__)
def create_url(tmpl, **values):
"""Create url with values
Args:
tmpl (str): url template
values (dict): values for url
"... |
from sklearn.metrics import accuracy_score, confusion_matrix, hamming_loss, hinge_loss, log_loss
from sklearn.model_selection import KFold, StratifiedKFold
from sklearn.preprocessing import normalize
from sklearn.multiclass import OneVsRestClassifier
import numpy as np
import matplotlib.pyplot as plt
import seaborn as... |
#!usr/bin/python
# _*_ coding:utf-8 _*_
import urllib2
import cookielib
import bs4
import re
import MySQLdb
import sys
reload(sys)
sys.setdefaultencoding('utf8')
def get_movie(url):
headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/600.8.9 (KHTML, like Gecko) Version/8.0.8 Safa... |
from collections import OrderedDict
from flask import Blueprint
from .. import __version__
from ._utils import CHANGELOG_URL, track
blueprint = Blueprint('root', __name__, url_prefix="/")
@blueprint.route("")
def index():
"""Track code coverage metrics."""
metadata = OrderedDict()
metadata['version'... |
@@ -0,0 +1,307 @@
import numpy as np
import json
import sys
import csv
class Parameters:
def __init__(self, parameter_dictionary):
self.max_adaptive_period = parameter_dictionary["MAXIMUM_ADAPTIVE_PERIOD"]
self.seed = parameter_dictionary["SEED"]
self.output_file = parameter_dictionary["OUT... |
# Search Twitter using Tweepy
# This program uses the module Tweepy to search Twitter for tweets with the two given tags.
import tweepy
import time
import xlsxwriter
import configparser
# Location of the config file
CONFIG_FILE = 'config.ini'
# Read config file
config = configparser.ConfigParser()
config.read(CONFIG... |
# Copyright 2013-2014 Nokia Solutions and Networks
#
# 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 appl... |
import pytest
from datetime import datetime
from src.inspetor.model.inspetor_item import InspetorItem
from src.inspetor.exception.model_exception.inspetor_item_exception import InspetorItemException
class TestInspetorItem:
def get_default_item(self):
item = InspetorItem()
item.id = "123"
... |
from triple_triple_etl.load.postgres.nbastats_postgres_etl import NBAStatsPostgresETL
from triple_triple_etl.constants import (
BASE_URL_PLAY,
BASE_URL_BOX_SCORE_TRADITIONAL,
BASE_URL_BOX_SCORE_PLAYER_TRACKING
)
if __name__ == '__main__':
game_id = '0021500568'
season = '2015-16'
params = ... |
import csv
from urllib.parse import urlparse, parse_qs
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from apps.articles.models import Section
from apps.utils.converters import perl_to_python_dict
class Command(BaseCommand):
help = 'Migrate partners channels f... |
import json
# j = json.loads('{"one" : "1", "two" : "2", "three" : "3"}')
# print j['two']
file_object = open(r"positive_examples_titles.json","r")
titles = file_object.read()
j = json.loads(titles)
# print j
# print j[0]['title']
l=[]
for i in j:
l.append(i['title'])
# uncomment to print the list
# for i in l:
# ... |
from Graph import *
import os
class TPGenerator:
"""生成测试点"""
def GenerateTP(self, path, file_name, exe_name, ty, count=10, node_num=100, edge_num=100, weight_limit=20):
self.file_path = path + "\\" + file_name
self.exe_path = path + "\\" + exe_name
if ty == 'DAG':
for i in range(1, count+1):
n = random... |
"""
tcp_client套接字编程 : 客户端流程
思路:逐步骤完成操作
重点代码
"""
from socket import * # 调用 套接字模块
# 创建套接字对象 tcp套接字
sockfd = socket() # tcp套接字参数默认值即为tcp套接字
# 链接服务端程序
server_addr = ("172.40.74.151", 8888) # 服务端IP地址,端口号
sockfd.connect(server_addr)
# 消息发送接收
while True:
data = input("Msg>>")
# 如果什么不输入,直接回车,退出
... |
from __future__ import with_statement
import numpy as np
import sys
from PySide import QtCore, QtGui
from equalibria import Ui_MainWindow
class DesignerMainWindow(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(DesignerMainWindow, self).__init__(parent)
self.setupUi(... |
#!/usr/bin/ipython
from ROOT import TH1F,TGraph
from dice import *
from numpy import mean,asarray
def counthits(pool,limit=None,edge=False):
nhits=0
for i in range(pool):
roll=die.roll1dX(6)
if roll>4:
nhits+=1
while roll==6 and edge:
roll=die.roll1dX(6)
... |
from flask import Flask
from config import my_config
from config import Config
from flask_oauthlib.client import OAuth
from . import my_constants
from celery import Celery
oauth = OAuth()
yammer_rank_oauth = oauth.remote_app(
'Yammer Rank',
consumer_key=my_constants.CLIENT_ID,
consumer_secret=my_constant... |
import numpy as np
import random
def shuffle(x):
x = list(x)
random.shuffle(x)
return x
class setClass:
def __init__(self,oldSet):
self.oldSet=oldSet
def print1(self):
return self.oldSet
def intersect(self,newSet):
intersectSet=[]
for x in self.oldSet:
if x in newSet:
intersectSet.a... |
#!/usr/bin/python
from unicodedata import normalize
import re
from sklearn.feature_extraction.text import CountVectorizer
from sklearn import svm
import nltk
import numpy
nltk.download('rslp')
_ARTICLES = ['a', 'as', 'o', 'os']
_PREPOSITIONS = ['a', 'ante', 'ate', 'apos', 'com', 'contra', 'para', 'per', 'por',\
... |
#!/usr/bin/env python3
import unittest
import pandas as pd
from pandas.util.testing import assert_series_equal
from unittest.mock import patch
from datetime import datetime, timedelta
import time
#from location_data_tests import getSiteNums, clean_up_sites, pullinfo, getDateInput
import os
from campsiteFinder impor... |
import AddressBook # noqa: F401
from PyObjCTools.TestSupport import TestCase, min_sdk_level
class TestABPersonPickerDelegate(TestCase):
@min_sdk_level("10.9")
def test_protocols(self):
self.assertProtocolExists("ABPersonPickerDelegate")
|
import matplotlib.pyplot as plt
from random_walk import RandomWalk
while True:
rw=RandomWalk()
rw.fill_walk()
point_numbers=list(range(rw.num_points))
plt.scatter(rw.x_values,rw.y_values,c=point_numbers,cmap=plt.cm.Blues,edgecolor='none',s=15)
plt.show()
keep_running=input("Make another walk?... |
import getopt
import os
import re
import sys
dupsFile = "dups.txt"
filepath = None
toRemoveDupFile = True
toDryRun = False
opts, args = getopt.getopt(sys.argv[1:], "p:rd")
for o, a in opts:
if o == "-p":
filepath = a
elif o == "-r":
toRemoveDupFile = False
elif o == "-d":
toDryRun = True
if filepath == No... |
#!/usr/bin/env python
import os
import shutil
import subprocess
import time
import click
from qgreenland.constants import (INPUT_DIR,
RELEASES_DIR,
TaskType,
WIP_DIR,
ZIP_TRIGGERFILE... |
'''
Created on Nov 14, 2012
@author: io
'''
import socket
import threading
import SocketServer
from SocketServer import ThreadingMixIn
from Queue import Queue
import threading, socket
class ThreadPoolMixIn(ThreadingMixIn):
'''
use a thread pool instead of a new thread on every request
code from : http://... |
from socket import *
import json
s = socket(AF_INET, SOCK_STREAM)
s.connect(('localhost', 8881))
while True:
msg = input('')
s.send(msg.encode()) |
from django.contrib import admin
from . import models
# class ELement():
# pass
# class Address():
# fk = Element()
class AddressInline(admin.TabularInline):
model = models.ElementAddress
class MenuInline(admin.TabularInline):
model = models.MenuCat
class FoodInline(admin.TabularInline):
... |
"""
Let us say your expense for every month are listed below,
January - 2200
February - 2350
March - 2600
April - 2130
May - 2190
Create a list to store these monthly expenses and using that find out,
"""
exp1=[2200,2350,2600,2130,2190]
print('Your list has\n',exp1)
#1. In Feb, how many dollars you spent extra compare... |
import datetime
import pickle
import sys
import os
import bs4 as bs
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import numpy
import requests
# from matplotlib import style
import plotly.graph_objs as go
# from matplotlib.finance import candlestick_ohlc
import plotly.plotly as py
import plotly.gra... |
import unittest
from cgi.member import Member
class PersonClassTest(unittest.TestCase):
def member_exist(self):
m = Member()
self.assertIsNotNone(m)
# TODO make test for add_to_member_table
# TODO make test for create_member
if __name__ == '__main__':
unittest.main() |
import pymongo
client = pymongo.MongoClient("localhost", 27017)
# db name - aminer
db = client.acm_aminer
# collection
db.shortened
print "DB name: ", db.name
print "DB collection: ", db.publications
print "[INFO] Processing papers"
file = open("../data/ACM_Aminer.txt")
lines = file.readlines()
file.close()
... |
import os
import sys
from stve.log import LOG as L
from stve.cmd import run
from stve.script import StveTestCase
from stve.exception import *
from nose.tools import with_setup, raises, ok_, eq_
try:
import configparser
except:
import ConfigParser as configparser
LIB_PATH = os.path.dirname(os.path.abspath(__fil... |
from itertools import chain, repeat
import pprint
from textwrap import dedent
import unittest
from clojure import requireClj
from py.clojure.lang.compiler import Compiler
from py.clojure.lang.fileseq import StringReader
from py.clojure.lang.globals import currentCompiler
from py.clojure.lang.lispreader import read
imp... |
from django import forms
from django.core.validators import validate_email, FileExtensionValidator
from .validators import validate_filesize, validate_phone_number
from django.conf import settings
class AuthenticationForm(forms.Form):
# This form is used in login.html page. Takes input username and password.
u... |
__all__ = ["logging", "set_global_seed", "typing"]
from move.core import logging, typing
from move.core.seed import set_global_seed
|
# -*- coding: utf-8 -*-
import StringIO
import json
import logging
import random
import urllib
import urllib2
# for sending images
from PIL import Image
import multipart
from google.appengine.api import urlfetch
from google.appengine.ext import ndb
import webapp2
import splitter
import sender
import dictionary
TOK... |
#!/home/jupyter/py-env/python2.7.13/bin/python2.7
import theano
import theano.tensor as T
from theano import pp
x = T.dmatrix('x') # declare variable
y = T.sum(1 / (1 + T.exp(-x)))
dy = T.grad(y,x)
f = theano.function([x], dy) # compile function
print f([[-1,0],[1,2]])
|
'''
Implementation of ZMP-based walking pattern generation.
However, the offset tracking error of ZMP in a long distance walking pattern is observed in this method.
For more details, refer to "Introduction to Humanoid Robotics" by Shuuji Kajita.
Background:
ZMP (Zero Moment Point) is a m... |
temp = input("请输入一个年份:")
while not temp.isdigit(): #isdigit() 判断输入是否为全数字,是返回ture,不是返回FALSE
temp = input("抱歉,您的输入有误,请重新输入:")
year = int(temp)
if year/400 == int(year/400):
print(temp + '是闰年!')
|
def read_file_return_list(name):
list = []
with open(name,'r') as f:
for line in f:
line = line.split('\n')
list.append(line[0])
if 'str' in line:
break
return list
def triangle_to_dict(triangle):
tri_dict = {}
row_count = 0
for i in triangle:
tri_dict.update({row_count: i.split(' ')})
row_co... |
import os,sys
import pandas as pd
import numpy as np
import tempfile
import re
from glob import glob
import mdtraj as md
import prody
import getopt
sys.path.append(os.path.dirname(os.path.dirname(sys.path[0])))
from util.createfolder import try_create_chain_parent_folder
from av4.av4_atomdict import atom_dictionary
... |
#Operaciones de inxacion
cad="No te preocupes por los fracasos, preocúpate con las posibilidades que pierdes cuando ni siquiera lo intentas"
msg="el valor del indice 38 es {}"
print(msg.format(cad[38]))
|
from enum import Enum
class ExpenseCategory(Enum):
GAS = "gas"
OTHER = "other"
HORMIGA = "hormiga"
Pharmacy = "pharmacy"
SUPERMARKET = "supermarket"
TRANSPORTATION = "transportation"
@classmethod
def of(cls, name):
if name:
name = name.lower()
for categ... |
import cv2
import numpy as np
image=cv2.imread("kelebek.jpg",0)
ret,thres1=cv2.threshold(image,127,255,cv2.THRESH_BINARY)#127nin altındaki pikseller sıfıra yuvaralanacak. diğerleri ise255 yuvarlanacak.
ret,thres2=cv2.threshold(image,127,255,cv2.THRESH_BINARY_INV)
ret,thres3=cv2.threshold(image,127,255,cv2.THRE... |
import numpy as np
a = np.array([1010,1000,990])
np.exp(a) / np.sum(np.exp(a))
c = np.max(a)
a - c
np.exp(a-c) / np.sum(np.exp(a-c))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.