text stringlengths 38 1.54M |
|---|
import unittest
from city_functions import get_city_country
class CityCountryTestCase(unittest.TestCase):
"""Tests for get_city_country()"""
def test_get_city_country(self):
"""Do inputs like 'Lagos, Nigeria' work?"""
formatted_name = get_city_country('lagos', 'nigeria')
self.assertEqu... |
from django import template
from django.template import Library, Node
# Create your views here.
from django.core.context_processors import csrf
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.template import Library
from django.http import HttpResponseRedirect
from... |
#!/usr/bin/python
import os
import sys
import unittest
from BeautifulSoup import BeautifulSoup
sys.path.insert(1, os.path.join(sys.path[0], '../../'))
from pixnet.spiders.blog import BlogSpider
class BlogTest(unittest.TestCase):
def setUp(self):
self.spider = BlogSpider()
dirname = os.path.dirna... |
import recommendations
allSimilar = []
file = open("data.txt", 'a')
newline = '\n'
tab = '\t'
file.write(f'First User Chosen: {tab} 368{newline}')
file.write(f'Second User Chosen: {tab} 81 {newline}')
file.write(f'Third User Chosen: {tab} 135 {newline}{newline}')
pref = recommendations.loadMovieLens()
# Get sorted ... |
#!/usr/bin/env python
import ROOT
import array
class Jet(object):
def __init__(self, pt, eta, phi, mass):
self.pt = pt
self.eta = eta
self.phi = phi
self.mass = mass
class FSR(object):
def deltaR(self, jet1, jet2):
deltaPhi = ROOT.TVector2.Phi_mpi_pi(jet1.phi-jet2.... |
from app import db
class CustomerApplication(db.Model):
id=db.Column(db.Integer,primary_key=True)
firstName=db.Column(db.String(20))
lastName=db.Column(db.String(20))
dateOfBirth=db.Column(db.Date)
address=db.Column(db.String(30))
city=db.Column(db.String(30))
zipcode=db.Column(db.String(10... |
#!/usr/bin/env python
#coding=utf-8
import math
import rospy
from goap_2021.srv import *
from precondition_little import *
from setting_little_goap import *
from goap_little_server import *
def GOAP_script(req):
global penalty_mission
global counter
global action
global position
global cup
glob... |
import glob
import json
#open the json files
def combined_function():
with open('data/cities.json', "r") as infile:
cities = json.load(infile)
with open('data/libraries.json', "r") as infile:
libraries = json.load(infile)
#create combined dict and combine them
combined = {}
for i ... |
#%%
import os
import sys
import random
import numpy as np
import pickle as pkl
import shelve
import itertools as it
import networkx as nx
import scipy.sparse as sp
from utils import loadWord2Vec, clean_str
from math import log
from sklearn import svm
from nltk.corpus import wordnet as wn
from sklearn.feature_extraction... |
import os
import boto3
import datetime
if __name__ == '__main__':
sim_day = str(datetime.date.today())
client = boto3.resource('s3')
bucket = client.Bucket('active-matter-simulations')
for obj in bucket.objects.filter(Prefix = f'ANFDM/{sim_day}'):
print(obj.key)
if not os.path.exists(os... |
# this file contains the class for the DenseNet neural network
# reference : pytorch - DenseNet
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(0)
from collections import OrderedDict
from torch import Tensor
from typing import Any
class _Transition(nn.Sequential):
"... |
# from mpl_toolkits import mplot3d
#
# import numpy as np
# import matplotlib.pyplot as plt
#
# fig = plt.figure()
# ax = plt.axes(projection="3d")
#
# z_line = np.linspace(0, 15, 1000)
# x_line = np.cos(z_line)
# y_line = np.sin(z_line)
# ax.plot3D(x_line, y_line, z_line, 'gray')
#
# z_points = 15 * np.random.random(1... |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.utils.module_loading import import_string
TEMPLATE_EMAIL_SENDER = getattr(settings, 'SKY_TEMPLATE_EMAIL_SENDER', 'sky_visitor.template_email_senders.DjangoTemplateSender')
TEMPLATE_EMAIL_SENDER_CLASS = import_string(TEMPLATE_EMAIL_SENDER)
SEND_USER... |
from src.api import API as API
class Example:
def static_init() -> None:
return API.static_init()
def download_wp_media() -> None:
return API.download_all_media()
Example.static_init()
Example.download_wp_media() |
# coding=utf-8
import tensorflow as tf
from bert import tokenization, modeling
import os
from bert.run_classifier import convert_single_example_simple
os.environ["CUDA_VISIBLE_DEVICES"] = '1'
def get_inputdata(query):
token = tokenization.CharTokenizer(vocab_file=bert_vocab_file)
split_tokens = token.tokeni... |
# -*- coding: utf-8 -*-
'''
用于调整一张图片的透明度的,如果不是png格式会先转化成png的RGBA格式然后调整透明度
run: python transparentHelper.py pictureName transparency
'''
import sys
import os
from PIL import Image
import shutil
def main(filename, transparency):
if not os.path.isfile(filename):
print 'No such picture file...'
return... |
n = int(input())
for i in range(2,n+1):
c=0;
for j in range(1,i+1):
if i % j == 0:
c = c + 1
if(c==2):
print(i)
|
from enum import Enum
class ParserTypes(Enum):
group = 'group'
jisho = 'jisho'
mine = 'mine'
readings_after = 'after'
ruby = 'ruby'
|
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# Card search
# ----------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ------------------------------------------------------------------... |
import numpy as np
import matplotlib.pylab as plt
# sigmoid function used broadcast for numpy array.
def sigmoid(x):
return 1 / (1 + np.exp(-x))
a = np.array([-1.0, 1.0, 2.0])
print(sigmoid(a))
# 이와 같은 시그모이드 함수를 그래프로 나타내 그 변화를 살펴보자.
x = np.arange(-5.0, 5.0, 0.1)
y = sigmoid(x)
plt.plot(x, y)
plt.ylim(-0.1, 1.1... |
import pygame,sys
import random
from pygame.locals import *
import math
pygame.init()
DIMENSIONS=[485,375]
screen=pygame.display.set_mode(DIMENSIONS,RESIZABLE)
pygame.display.set_caption('Guess The Word')
BG_COLOR=[50,50,50]
#BG_COLOR=[233,249,242]
screen.fill(BG_COLOR)
pygame.display.flip()
dictionary={"QUALIFI... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 12 11:07:01 2021
@author: nate_mac
"""
"""
Write a script to plot the period of a plane pendulum as a function of
amplitude from 0 to π. Include a line showing the approximate solution for
comparison. At what amplitude does the exact solution di... |
# Default Imports
import pandas as pd
import numpy as np
dataframe_1 = pd.read_csv('data/house_prices_multivariate.csv')
dataframe_2 = pd.read_csv('data/house_prices_copy.csv')
# Return the correlation value between the SalePrice column for the two loaded datasets
# Your code here
def correlation():
sp_1=datafram... |
'''
Created on 21/03/2014
@author: Beto
'''
'''
yourAge = int(raw_input('How old are you: '))
if (yourAge > 0) and (yourAge < 120):
if (yourAge == 35):
print "Same as me"
elif (yourAge > 35):
print "Older than me"
else:
print "Younger than me"
else:
print "Don't lie about you... |
#dart_result = input()
dart_result = "1S2D*3T"
score = [1, 1, 1]
d_index = 0
for i in range(0, 3):
try:
num = int(dart_result[d_index:d_index+2])
d_index += 1
except Exception as e:
num = int(dart_result[d_index])
d_index += 1
if dart_result[d_index] == 'S':
... |
# Generated by Django 2.1.7 on 2019-03-18 06:22
from django.db import migrations
from django.core.management import call_command
def load_initial_palika_codes(apps, schema_editor):
call_command('loaddata', 'initial_palika.json', app_label='geo')
class Migration(migrations.Migration):
dependencies = [
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 11 11:06:46 2013
@author: pathos
"""
from __future__ import division
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D, proj3d
import pylab
from scipy.interpolate import griddata
import numpy as np
import matplotlib.pyplot as plt
def gen_sinusoidal(N):
... |
from tkinter import ttk
from tkinter import *
import gui
from tkvideoplayer import tkvideo
# console output :
verbose = 0
# predefined values
minimumPoints = 20
RadiusLimit = 0
requestedpoints = 500
new_width = 600
kernel_list = ['laplace4', 'laplace2', 'X sobel', 'Y sobel']
order = 20 # AANTAL CIRKELS: order = div... |
import multiprocessing
import importlib
def create(module_name):
def pipe_process(pipe):
lib = importlib.import_module(module_name)
func = getattr(lib, module_name)
pipe.send('Okay :-)')
while 1:
data = pipe.recv()
try:
poem = func(data)
... |
numbers = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
style_param = {
"weights": [0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.2],
"descriptions": ["very poor", "poor", "little", "mild", "normal", "strong", "very strong"]
} |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import List
from .base_api_resource import BaseAPIResource
from .data_models import EligibilityRequirement
... |
import serial
import datetime
import os
import sys
import stat
import json
import time
import pmDatabase
import pmWiFi
from threading import Thread
#========================================
#Permissions
#Change the serial port access permission
#os.chmod('/dev/serial0', stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH | stat... |
import random
def main():
play = "y"
cScore = 0
uScore = 0
while play == "y":
computer = random.randint(0,2)
userChoice = "spock"
computerChoice = "spock2"
print("Choose [R]ock, [P]aper, or [S]cissors: ", end="")
user = "t"
while user.lower() == "t":
... |
#sort array of 0's ,1's and 2's
#Method 1
#use sorting algorith to sort the given array
#T.C=O(NlogN)(merge sort)
#Method 2
#use counting sort
#Method 3
#using Dutch National Flag Algorihtm
#T.c =
def sort(arr):
if(len(arr)<=1):
return arr
lp=mp=0
hp=len(arr)-1
while(mp<=hp):
... |
def palindrome(n):
result = True
for i in range(0, len(n) // 2):
if n[i] != n[-i - 1]:
result = False
break
return result
if __name__ == "__main__":#https://stackoverflow.com/questions/419163/what-does-if-name-main-do
#how to use __name__ == "__main__
input_str = input("... |
import json
import os, sys
CONFIG_FILE = '.sryapi-cli.json'
class SRYClientPlugin(object):
"""
Abstract base class for plugins providing their own commands. Each subclass
must implement `register` methods.
"""
def __init__(self, runner):
self.runner = runner
def _before_register(self... |
import sqlite3
class SQLighter:
def __init__(self, db_name):
self._connection = sqlite3.connect(db_name)
self._db_field = {"IntField": "INTEGER", "StringField": "TEXT"}
self.cursor = self._connection.cursor()
def __enter__(self):
return self
def __exit__(self, exc_type, e... |
import nfc
import threading
import binascii
def decode(device):
return binascii.b2a_hex(device).decode("utf-8")
def on_startup(targets):
print("Esperando un dispositivo (nfc)...")
return targets
def on_connect(tag):
print("New contactless device detected, ID #",decode(tag.identifier))
def scan():
... |
#!/usr/bin/env python3
"""Parse timestamps from log file to convert it to ISO.
Usage:
sgf-parse-log.py [--tz TIMEZONE] [--time-format=TIME_FORMAT]...
[<logfile>]...
sgf-parse-log.py (-h | --help)
sgf-parse-log.py --version
Argiments:
<logfile> Log file to read [default: stdin].
Optio... |
import time
# This sleep delays initializing things until after the pi finishes booting (this script is run at boot time using cron).
time.sleep(15)
import datetime
import threading
import subprocess
import sys
import os
import json
import queue
import RPi.GPIO as GPIO
from ringmybell.ringbell_reply import ringbell_re... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import collections, os, random
from StringIO import StringIO
import muz
import muz.assets
import muz.vfs as vfs
from muz.beatmap import log, formats
class NoteError(E... |
# Generated by Django 3.2.8 on 2021-10-21 06:43
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('store', '0004_rename_payment_order_payment_status'),
]
operations = [
migrations.AlterModelOptions(
... |
#!/usr/bin/python
#coding=UTF-8
import threading
class t_runner:
'''
'''
def __init__(self):
'''
'''
self.cmds=[]
return
class worker(threading.Thread):
'''
'''
def __init__(self,name):
'''
'''
threading.Thread.__init__(self)
self.name=name
self.cmds=[]
self.emsg=None
return
... |
import sublime
from SublimeGHCi.completions.CompletorFactory import *
def default_completor_factory(ghci_factory):
return CompletorFactory(sublime, ghci_factory) |
import taichi as ti
import numpy as np
import math as m
# ti.init(debug=True, arch=ti.cpu)
ti.init(arch=ti.gpu)
# Equi-Angular Sampling
# Implementation of equi-angular sampling for raymarching through homogenous media
# https://www.shadertoy.com/view/Xdf3zB
GUI_TITLE = "Equi-Angular Sampling"
w, h = wh = (640, 360)
... |
import tkinter as tk
from tkinter import messagebox
from tkinter.font import Font
from gerenciador_db import *
import os
import shutil
import cv2
import face_recognition
from datetime import datetime
fonte = "Helvetica 16 bold"
fonte_pequena = "Helvetica 12"
LOCAL_DIR = os.path.dirname(os.path.realpath(__f... |
# # you can write to stdout for debugging purposes, e.g.
# # print("this is a debug message")
# def solution(A, S):
# # write your code in Python 3.6
# aLen = len(A)
# listTracker = []
# # print(aLen)
# for i in range(aLen):
# # print("i = %s -" % (i))
# subStringL = 1
# me... |
#!/usr/bin/env python
# coding: utf-8
# # Important Python Packages imported.
# In[1]:
from pylab import plot,show
from numpy import vstack,array
from numpy.random import rand
from scipy.cluster.vq import kmeans,vq
from sklearn import datasets
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.c... |
import pygame
from pygame.sprite import Sprite
from time import sleep
vec = pygame.math.Vector2
class Pow(Sprite):
def __init__(self, ai_settings, screen, map, Game):
super(Pow, self).__init__()
self.screen = screen
self.ai_settings = ai_settings
self.map = map
... |
# -*- coding: utf-8 -*-
# import Env
import os, sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../")
from env import Env
Env()
from pymongo import *
from datetime import datetime
from convert_datetime import dt_to_end_next05,dt_from_14digits_to_iso,shift_seconds
from get_coord import *
client = Mon... |
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Flatten
from keras.layers.convolutional import Conv3D, MaxPooling3D, ZeroPadding3D
from keras.optimizers import SGD
from keras.layers import Input
from keras.models import Model
def get_model():
""" Return the Keras model of the ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-05-02 07:30
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('customer', '0004_tokomodel_nama_user'),
]
operati... |
# A simple blog using flask with a database
#https://www.bogotobogo.com/python/Flask/Python_Flask_Blog_App_Tutorial_5.php
from flask import Flask, redirect, render_template, request, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import login_user, LoginManager, Use... |
x = input("enter any value between 1-10")
y = input("enter any value between 1-10")
z = x+y
c = z+30
print("result is",c)
|
#!/usr/bin/env python3
#
# Ryan Lamb
# CPSC 223P-03
#2020-9-16
#rclamb27@cus.fullerton.edu
"""Ouputs the sum of all multiples of 3 or 5 below 10000000"""
def main():
"""Takes the multiples of 3 and 5 and sums them"""
total_nums = input('Please input a range of numbers below 1000000: ')
print('You chose {}... |
import requests
import json
data = list()
response = requests.get('https://api.weibo.com/2/emotions.json?source=1362404091')
for i in response.json():
data.append({"alt":i["phrase"],"src":i["icon"]})
print(data) |
from functools import partial
from typing import Tuple
import haiku as hk
import jax
import jax.numpy as jnp
import numpy as np
import optax
from rljax.algorithm.base_class import QLearning
from rljax.network import DiscreteQFunction
from rljax.util import get_q_at_action, huber, optimize
class DQN(QLearning):
... |
name1=input("name")
name2=input("clg name")
name3=input("cgpa")
print("my name is",name1,"studying in",name2,"cgpa is",name3)
|
from flask import Flask
import pickle
import pandas as pd
import numpy as np
import re, string, nltk
from nltk.corpus import stopwords
app = Flask(__name__)
@app.route("/")
def hello():
return "Welcome to machine learning model APIs!"
if __name__ == '__main__':
app.run(debug=True) |
"""
Source: https://github.com/simonqbs/cayennelpp-python
"""
import struct
import math
LPP_DIGITAL_INPUT = 0 # 1 byte
LPP_DIGITAL_OUTPUT = 1 # 1 byte
LPP_ANALOG_INPUT = 2 # 2 bytes, 0.01 signed
LPP_ANALOG_OUTPUT = 3 # 2 bytes, 0.01 signed
LPP_LUMINOSITY = 101 # 2 bytes, 1 lux... |
from pyspark.sql import SparkSession
import time
import sys
spark = SparkSession.builder.appName("appName").getOrCreate()
sc = spark.sparkContext
start = int(round(time.time() * 1000))
records = sc.textFile(sys.argv[1])
rows = records.map(lambda line: line.split("\t"))
userToFavouriteProducts=rows.map(lambda x: (x[2... |
# -*- coding: utf-8 -*-
students = [
{'name': '张三', 'chinese': '84', 'math': '95', 'english': '65', 'total': 195},
{'name': '李四', 'chinese': '60', 'math': '68', 'english': '65', 'total': 195},
{'name': '王五', 'chinese': '75', 'math': '79', 'english': '65', 'total': 195},
{'name': '赵六', 'chinese': '99', ... |
__author__ = '@tomereyz'
import argparse
import os
DOCKERFILE_TEMPLATE = """
{architecture_dependant}
RUN apt-get update
WORKDIR /
RUN apt-get install -y openssh-server
RUN apt-get install -y sudo
RUN apt-get install -y python
RUN apt-get install -y gdb
RUN apt-get install -y git
RUN apt-get install -y vim
RUN apt... |
from django.apps import AppConfig
class AssineFacilTVAppConfig(AppConfig):
name = 'AssineFacilTV'
verbose_name = 'Assine Fácil TV'
|
import numpy as np
import matplotlib.pyplot as plt
def sample_function(x=None, nfuncs=10, ndata=100):
if x is None: x = np.sort(np.random.uniform(-10, 10, ndata)[:, None], 0)
xs = np.tile(x, (nfuncs, )).T
a = np.random.uniform(-10, 10, size=(nfuncs, 1))
b = np.random.uniform(-2, 2, size=(nfuncs, 1))
... |
import functools
import sys
import time
import warnings
__author__ = 's.rozhin'
trace_on = True
def trace(func):
@functools.wraps(func)
def inner(*args, **kwargs):
print(func.__name__, args, kwargs)
return func(*args, **kwargs)
return inner if trace_on else func
def timethis(func):
... |
#!/usr/bin/env python
import os
import sys
import itertools
import subprocess
from optparse import OptionParser
import boto.ec2.connection as ec2
def _get_instances():
connection = ec2.EC2Connection()
instances = map(lambda r: r.instances, connection.get_all_instances())
return list(itertools.chain.from... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 18/11/9 15:24
# @Author : lijian
# @Desc : https://leetcode.com/problems/maximum-depth-of-binary-tree/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.rig... |
from flask import Flask,render_template,url_for,request,redirect,make_response,url_for,make_response
import os,string
import sqlite3
import time
import entry,pay,sale_j,shopinfo
app=Flask(__name__)
@app.route('/input/',methods=['GET','POST'])
def input():
username=request.cookies.get('username')
password=request.... |
import os
import numpy as np
from genEM3.data.wkwdata import WkwData, DataSource
run_root = os.path.dirname(os.path.abspath(__file__))
datasources_json_path = os.path.join(run_root, '../../data/debris_clean_added_bboxes2_datasource.json')
datasources_json_path_out = os.path.join(run_root, '../../data/debris_clean_adde... |
import datetime
import logging
import sys
from typing import Any
__all__ = ["QuantrtLog"]
logger = logging.getLogger('quantrtlog')
formatter = logging.Formatter("[%(name)s] @ %(asctime)s from %(funcName)s with level %(levelname)s: %(message)s")
console_stream = logging.StreamHandler(stream = sys.stderr)
console_str... |
"""
This module is based on ideas from https://thetinkerpoint.com/2019/02/11/why-the-world-has-gone-crazy/ and code Alex Lamb shared with me: https://github.com/alexlamb/groupdecision via twitter dm.
I attempted to do this in a more functional style, as inspired by my recent watching of https://www.youtube.com/watch?... |
import time
from app.game.input import Input, Command
from app.game.field import Field
from app.game.field_outputter import FieldOutputter
from app.slack import slacker
class BomberFactory:
_bomber_store = {}
@classmethod
def create(cls, channel, users):
bomber = cls.instance(channel)
i... |
import os
from setuptools import setup
from setuptools import find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.md')) as f:
README = f.read()
requires = [
'flake8',
'flake8-print',
'mock',
'opbeat',
'opbeat_pyramid',
'pyramid',
'pyr... |
import functools
# Common function decorator
def eggs_decorator(function):
@functools.wraps(function)
def _eggs(*args, **kwargs):
return function(*args, **kwargs)
return _eggs
def spam():
"""
This is spam function
:return: string
"""
print("spam function called")
return "... |
from gym.envs.registration import register
from gym_algorithmic.copy_ import CopyEnv
from gym_algorithmic.duplicated_input import DuplicatedInputEnv
from gym_algorithmic.repeat_copy import RepeatCopyEnv
from gym_algorithmic.reverse import ReverseEnv
from gym_algorithmic.reversed_addition import ReversedAdditionEnv
re... |
import pygame
# поле
# поле: 20 в ширину на 40 в высоту, видимая на акране часть: около 15-19 на 10 - 12 (в зависимости от разрешения экрана)
#
# требуется в дальнейшем реализовать камеру (я думаю, песонаж должен быть чуть ниже центра)
board_width = 40
board_height = 25
cell_size = 40
fps = 60
# инициа... |
# A navbar with an optional focused element. Uses materializecss.
# All links are also used as mobile links with a slideout menu.
"""
Desktop:
________________________________________________________
| |
| Bidbyte Link1 Link 2 |
| ... |
'''
2. 还记得求回文字符串那道题吗?现在让你使用递归的方式来求解,亲还能骄傲的说我可以吗?
'''
def is_huiwen(str1):
length = len(str1)
if length <= 1:
return True
elif str1[0] == str1[- 1]:
return is_huiwen(str1[1 : - 1])
else:
return False
print(is_huiwen('上海自来水来自海上'))
print(is_huiwen('双手插口袋'))
|
#!/usr/bin/env python
import rospy
from std_msgs.msg import Float64
import std_msgs.msg
import geometry_msgs.msg
import nav_msgs.msg
import sensor_msgs.msg
odom = [0,0]
vel = [0,0]
THRUSTER_COB = 300 #Distance between thrusters and cob
def listener():
rospy.init_node("accel_to_pwm")
rospy.Subscriber("/odom", nav_ms... |
# coding = utf8
import flask,json
import pymysql
"""post 传参加MySQL处理"""
server=flask.Flask(__name__)#__name__代表当前的python文件。把当前的python文件当做一个服务启动
@server.route('/index',methods=['post'])#第一个参数就是路径,第二个参数支持的请求方式,不写的话默认是get
def index():
username=flask.request.values.get('username')
passwd=flask.request.values.g... |
# -- encoding:utf-8 --
from sklearn.preprocessing import LabelBinarizer
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn import datasets
from keras.layers.core import Dense
from keras.models import Sequential
from keras.optimizers import SGD
import nump... |
from django.db import models
# Create your models here.
from apps.sistema.models import EntidadBase
from utils.choices import TIPO_DOC_CHOICES
class Persona(EntidadBase):
FISICA = 'F'
JURIDICA = 'J'
TIPO_PERSONA_CHOICES = (
(FISICA, 'Física'),
(JURIDICA, 'Jurídica'),
)
nombres = m... |
# Outline Data Structures:
# Point
class Point(object):
def __init__(self, x, y):
self.X = x
self.Y = y
def __str__(self):
return "Point(%s,%s)"%(self.X, self.Y)
# Parcel
class Parcel:
def __init__(self, lowerleft: Point, upperright: Point, land_type):
self.lowerleft =... |
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from ..items import ZcoolspiderItem
class ZcoolSpider(CrawlSpider):
name = 'zcool'
allowed_domains = ['zcool.com.cn']
start_urls = ['https://www.zcool.com.cn/?p=1#tab_anchor']
rules = (
... |
'''
URL patterns includes for Figures devsite
'''
from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import TemplateView
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='homepage.html'), name='homepage'),
url(r'^admin/', include(admin.site.urls))... |
#!/usr/bin/python3
"""Module creates method add_item which adds all arguments to a\
Python list, and saves the list to a file"""
# import sys to handle command line args (sys.argv[])
import sys
# import json to handle json syntax in imported functions
import json
# save_to_json_file takes python object and dumps
# t... |
import tornado.ioloop
import tornado.web
import os, sys
import subprocess
import json
import time
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
'''
{'tiaozhuan': [b'2'],
'domain_name': [b'zhoutao990.51xidu.com'],
'page': [b'3'],
'site_id': [b'123'],
'comp': [b'\xe6\x9f\x90\xe6\x9f\x90\xe5\x85\xac\xe5\... |
# -*- coding: utf-8 -*-
from celery import current_app
from celery.bin import worker
from flask_script import Command
class CeleryWorker(Command):
"""Run the celery worker"""
def __call__(self, app=None, *args, **kwargs):
a = current_app._get_current_object()
w = worker.worker(app=a)
... |
###
# Tree
# Time Complexity: O(n)
# Space Complexity: O(n)
###
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findMode(self, root):
"""
:type root:... |
"""Statistics for the assessment of DA methods.
`Stats` is a data container for ([mostly] time series of) statistics.
It comes with a battery of methods to compute the default statistics.
`Avrgs` is a data container *for the same statistics*,
but after they have been averaged in time (after the assimilation has finis... |
# Copyright (c) 2016 Fabian Kochem
from libtree import Node, ReadWriteTransaction
from libtree.core.database import make_dsn_from_env
from libtree.core.query import get_node
from libtree.core.tree import insert_node
import os
import pytest
try:
from psycopg2cffi import compat
except ImportError:
pass
else:
... |
"""
Base API class including methods shared between all APIs
"""
from datetime import datetime, timedelta
from json.decoder import JSONDecodeError
from typing import Any, Dict, List, Optional
from json.decoder import JSONDecodeError
import requests
from visiology_py.authorization_token import AuthorizationToken
fro... |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: GuoCheng
#
# Created: 19/06/2015
# Copyright: (c) GuoCheng 2015
# Licence: <your licence>
#------------------------------------------------------------------------------... |
import numpy as np
from math import cos
from math import sin
from math import pi
import os
from dolfin import *
'''
This is a helper file. It contains routines
that are somewhat peripheral to the actual
math done in a run.
'''
# The following piece of codes makes sure we have the directory
# structure where we wan... |
# Generated by Django 2.2.7 on 2019-11-26 13:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0008_auto_20191126_1243'),
]
operations = [
migrations.AlterField(
model_name='doctor',
name='image',
... |
import socket #importa modulo socket
IP_destino = "192.168.0.13" #Endereço IP do servidor
PORTA_destino = 5005 #Numero de porta do servidor
#Criação de socket UDP
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
#sock.bind((IP_servidor, PORTA_destino))
while True:
MENSAGEM = input("enviar... |
"""controle_gastos URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/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')
Cla... |
import SOAPpy
url = 'http://soap.amazon.com/schemas3/AmazonWebServices.wsdl'
proxy = SOAPpy.WSDL.Proxy(url)
# show methods retrieved from WSDL
print '%d methods in WSDL:' % len(proxy.methods) + '\n'
for key in proxy.methods.keys():
print key
print
# search request
_query = 'spotted owl'
request = { 'keyword': _... |
"""This module contains classes to represent image resources."""
import os
from flask import request, current_app
from flask_restful import Resource
from werkzeug.utils import secure_filename
from werkzeug.datastructures import FileStorage
from marshmallow import ValidationError
from app.models import Image, Artist
f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.