text stringlengths 8 6.05M |
|---|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from naoqi import ALProxy
def test(robot_IP,is_simulation):
#if not is_simulation:
#audioProxy = ALProxy("ALTextToSpeech",robot_IP,9559)
#audioProxy.post.say("I am Tanaka") # .post make a parallel call.
memProxy = ALProxy("ALMemory",robot_IP,9559)
memProxy.ins... |
from scipy.signal import iirdesign, lfiltic, lfilter
from au_defs import *
class Filter:
def __init__( self, band_start, band_stop ):
nyquist_frequency = float(SAMPLES_PER_SECOND) / 2.0
band_start /= nyquist_frequency
band_stop /= nyquist_frequency
assert( band_start >= 0 ... |
# %load ../standard_import.txt
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
import seaborn as sns
from sklearn.preprocessing import scale
import sklearn.linear_model as skl_lm
from sklearn.metrics import mean_squared_error, r2_score
import... |
'''
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
'''
# Definition for singl... |
# coding:utf-8
from django.db import models
from model_utils import FieldTracker
from commons.models import CommonModel
import constants
class MassEmailOnChangeMixin(object):
def save(self, *args, **kwargs):
if self.tracker.changed():
from suscription.tasks import send_mass_email
... |
import socket
s=socket.socket()
port = 12345
s.connect(('10.2.24.13',port))
print s.recv(1024)
s.close()
|
import numpy as np
def convert_to_child(parent, children):
while len(children[parent]) > 0:
parent = np.random.choice(children[parent])
return parent
def gen_ex(exposed_y, parents, children, noise_std = .1):
'''
Toy data generation function
'''
true_y = np.array([convert_to_child(i, c... |
q = int(input().strip())
hackerrank = 'hackerrank'
for inp in range(q):
j = 1
k = 0
result = False
s = input().strip()
for i in range(0, len(hackerrank)):
for j in range(k, len(s)):
if hackerrank[i] == s[j]:
result = True
break
else:
... |
# ==================================================================================================
# Copyright 2011 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... |
import random as rn
import math as mt
import numpy as np
import copy
class reseau():
def __init__(self):
self.fonction_dactivasion = []
self.pois_w = []
self.bier_b = []
self.inisialisation_premier = True
self.nerone_size = []
def add(self, nerone, fonction, couche_dantre = 0):
self.fonct... |
# -*- coding: utf-8 -*-
'''
1. GRU
2. CNN
3. GRU+CNN
4. Transformer
5. Star-Transformer
6. BT-Transformer
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class RNN(nn.Module):
'''
hyperparameters:
batch_size=32, init_lr=2.5e-2, weight_decay=1e-5, lr_decay=0.1: 83.50... |
# This is a test python file, which includes sensitive information from ROCKYOU password dataset, and some URLs. Add another password to test counter.
INTERNAL_URL = 'http://jira.agile.bns/'
POTENTIAL_PASSWORD_LIST = ['123456', 'shadow', 'monkey']
print("Internal URL is: "+INTERNAL_URL)
i = 1
for(item in POTENTIAL_P... |
from __future__ import division
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from composition import closure
from metrics import variation_distance
from skbio.stats import subsample_counts
from skbio.stats.composition import closure
from skbio.diversity.alpha import robbins, ... |
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
path('api/login', views.UserLoginAPIView.as_view(), name='login'),
path('api/logout', views.UserLogoutAPIView.as_view(), name='logout'),
path('api/employeebranchwi... |
'''
Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.
You may assume the array's length is at most 10,000.
找到中间值即可,问题的转换很重要
Runtime: 52 ms
Your runtime beats 54.45 ... |
import Data_importer
import model
import random
import feature_engineering2 as feature_engineering
from sklearn.model_selection import train_test_split
def main():
train = Data_importer.load_train_set()
train = feature_engineering.main(train)
train_set = train.copy()
book_trainset = train_set[train_... |
import numpy as np
import pandas as pd
import os
from matplotlib import pyplot as plt
from matplotlib.ticker import ScalarFormatter
from experiments.util import collect_exp_results
params = {'legend.fontsize': 9.5,}
plt.rcParams.update(params)
DIR = os.path.dirname(os.path.abspath(__file__))
lines = []
fig, axes = ... |
import os
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
from scipy.spatial import Delaunay
from sklearn import linear_model, datasets
from torchvision import models
import torchvision.transforms as T
from PIL import Image
import torch
from sklearn.cluster import DBSCAN
from sklearn.cluster im... |
from wiki.general.classes import Car
"""
Objectives:
PCPP-32-101 1.1 – Understand and explain the basic terms and
programming concepts used in the OOP paradigm
- essential terminology: class, instance, object, attribute, method, type,
instance and class variables, superclasses and subclasses
- reflexion: isinstance(... |
def fun():
print("hello yanlp")
|
import pysc2
from pysc2.env import sc2_env
from pysc2.lib import features
from absl import app
import time
import tensorflow as tf
import numpy as np
import threading
import os
import pickle
import parameters_default
import parameters_custom
from reinforcement_learning.networks import AC_Network
from reinforcement_lear... |
from flask import Flask, render_template, request, redirect, flash, session
app = Flask(__name__)
app.secret_key = 'Macbook'
# our index route will handle rendering our form
@app.route('/')
def index():
return render_template("index.html")
# this route will handle our form submission
# notice how we defined which HTT... |
Your input
4
Output
2
Expected
2
Your input
8
Output
2
Expected
2 |
"""
A simple Monte Carlo solver for Nim
http://en.wikipedia.org/wiki/Nim#The_21_game
"""
import random
try:
import codeskulptor
except ImportError:
import SimpleGUICS2Pygame.codeskulptor as codeskulptor
codeskulptor.set_timeout(20)
MAX_REMOVE = 3
TRIALS = 10000
def evaluate_position(num_items)... |
from PyQt5 import QtCore
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QPushButton, QLabel, QApplication, QLineEdit)
from PyQt5.QtGui import (QFont, QPixmap)
class EntryWindow(QWidget):
def __init__(self):
super().__init__()
self.init_gui()
def init_gui(self):
font = QFont()
... |
# --------------------------------------------------------------------
import os
import functools
# --------------------------------------------------------------------
# Lambda functions
def myfunc (n):
print ("n: ", n)
return lambda i: i * n # i is the parameter
doubler = myfunc (2) # Creates 2 functions (bas... |
from . import views
from django.urls import path
from django.contrib.auth import views as auth_views
app_name = 'clients'
urlpatterns = [
path('index', views.index, name='index'),
path('<int:id>/',views.details, name='details'),
path('e',views.empindex,name='e'),
path('e/<int:id>/',views.empdetail,name='empdeta... |
# -*- coding: utf-8 -*-
import math
import numpy as np
import chainer, os, collections, six, math, random, time, copy
from chainer import cuda, Variable, optimizers, serializers, function, optimizer, initializers
from chainer.utils import type_check
from chainer import functions as F
from chainer import links as L
from... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 28 16:37:59 2013
bpath1
This is a direct re-implementation of Des Higham's SDE scripts. First up
is the Brownian path simulation
@author: ih3
"""
import numpy as np
T = 1.0 # End time
N = 500 # Number of steps
dt = T / N
W = np.zeros(N)
dW = np.zeros(N)
t = np.linspa... |
#-*- coding:utf8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import re
import hashlib
import inspect
import copy
import time
import datetime
import json
import urllib
import urllib2
from django.conf import settings
from django.core.cache import cache
from shopapp.weixin.models import WeiXinAccount
from... |
#!/usr/bin/python3
"""Unittest for max_integer([..])
"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
"""Tests the function max_integer for correct output
"""
def test_max_at_the_end(self):
"""Tests all positive numbers
"""... |
# -*- coding: utf-8 -*-
from rest_framework import permissions, viewsets
from rest_framework.response import Response
from posts.models import Post
from posts.permissions import IsAuthorOfPost
from posts.serializers import PostSerializer
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.order_by('-... |
from pathlib import Path
class Bankomat:
def __init__(self, lokacija):
self.lokacija = lokacija
self.stanje = 1000
if Path(str(self.lokacija) + ".txt").exists():
with open(str(self.lokacija) + ".txt") as dat:
for vrstica in dat:
self.stanje =... |
import pandas as pd
ds1 = pd.read_csv("VaccineData.csv")
ds2 = pd.read_csv("VaccineData2.csv")
ds3 = pd.read_csv("VaccineData3.csv")
ds4 = pd.read_csv("VaccineData4.csv")
ds5 = pd.read_csv("VaccineData5.csv")
ds6 = pd.read_csv("VaccineData6.csv")
ds7 = pd.read_csv("VaccineData7.csv")
ds8 = pd.read_csv("VaccineData8.c... |
i = 5
print(i) |
def minion_game(string):
words = list(string)
vowels = ('A', 'E', 'I', 'O', 'U')
stuart = 0
kevin = 0
for i in range(len(words)):
if (words[i:i + 1][0] in vowels):
kevin = kevin + len(words) - i
else:
stuart = stuart + len(words) - i
if (stuart == kevin):
... |
d={}
with open('nyc_weather.csv','r') as f:
for line in f:
tokens=line.split(',')
day=tokens[0]
try:
temp=int(tokens[1])
d[day]=temp
except:
print('invalid temperature, ignore line')
print(f'the temperature in jan 9 was {d["Jan 9"]}')
print(f'the ... |
'''
Created on Nov 17, 2015
@author: Jonathan
'''
def bags(strength, food):
numBags = 0
for type in set(food):
if food.count(type) % strength == 0:
numBags += food.count(type) / strength
else:
numBags += food.count(type) / strength + 1
return numBags
if __name__ ==... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('member-directory/', views.directory_of_members, name='member-directory'),
path('current-sponsors/', views.current_sponsors, name='current-sponsors'),
path('resources/', views.resources_page... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function
from flask import request, g, make_response, jsonify
from . import Resource
from .. import schemas
import ast
class Timelots(Resource):
def get(self):
result = []
with open('dentists.txt', 'r') as f:
for line... |
# -*- coding: utf-8 -*-
'''
Created on 8 Jul 2015
@author: motasim
Script that loads the MNIST dataset as numpy arrays where the pixels are normalised to be between [0, 1].
If the data is not available it will attempt to download it.
There are 3 classes, all of which load the same data but returns them in different ... |
requests
qhue
plotly
pandas
dash
dash-bootstrap-components
selenium
forex-python
yfinance
forex_python |
"""
REST API Documentation for the NRS TFRS Credit Trading Application
The Transportation Fuels Reporting System is being designed to streamline
compliance reporting for transportation fuel suppliers in accordance with
the Renewable & Low Carbon Fuel Requirements Regulation.
OpenAPI spec version: ... |
import tweepy
from tweepy import OAuthHandler
consumer_key='wdIHUveP64KOhdJiGVEdjkp8B'
consumer_secret='6jyY1sA6Dz6aZlYPXJ2nE9GwwhU4KcmPqdLmCnPGqp8xuunX96'
access_token='567899563-1HmNAIgXYxX2FcVRpPB2Y6OhJ1zyjzOB4FjGRn33'
access_secret='bNAmEuMy1FWgARaHRkbZ893DdvYCxBW9W8C7pGiqIQBw5'
auth = OAuthHandler(consumer_k... |
from collections import namedtuple
def namedtuple_and_choices_from_kwargs(name, **kwargs):
return (
namedtuple(name, sorted(kwargs.keys()))(
**{k: k for k in kwargs.keys()}
),
list(kwargs.items()),
)
|
import requests
from bs4 import BeautifulSoup
import urllib
import re
import sys
sys.stdout = open('file.txt', 'w')
text_file = open("source.txt", "w")
def get_data(item_url):
f = urllib.request.urlopen(item_url)
text_file.write(str(f.read()))
get_data('http://www.ted.com/talks/susan_cain_the_power_of_introv... |
#-*-coding:utf-8 -*-
#@author:wendy
def talk_with_daddy(is_cheap3,buy_amount3):
if is_cheap3:
print'老妈对老爸说菜便宜买了,买了%d斤'%(buy_amount3)
else:
print'老妈对老爸说菜贵了没买'
def money_account(is_cheap4,buy_amount4):
if is_cheap4:
print'老妈记账在本子上,写下买了%d斤'%(buy_amount4)
else:
print'老妈没有记账因为没买东西'
def buybuybuy():
who='wendy的... |
#!/usr/bin/env python
""" Profiling functions in Python using '%run -p' to compare function speed """
__author__ = 'Saul Moore sm5911@imperial.ac.uk'
__version__ = '0.0.1'
def a_useless_function(x):
""" Exploring the speed of 'xrange' vs 'range' """
y = 0
for i in xrange(100000000): # Eight zeros!
y = y + 1
re... |
from fabric.context_managers import cd, prefix
from fabric.operations import sudo, run
from fabric.state import env
PROJECT_ROOT = ''
VENV_DIR = ''
UWSGI_APP_NAME = ''
def update():
env.host_string = ''
env.user = ''
env.password = ''
with cd(PROJECT_ROOT):
sudo('git pull origin master')
... |
import json
import os
import fnmatch
from parser import *
from preprocess_R import *
# debugging flags
line_print = 1
graph_print = 0
for_print = 0
if_print = 0
bracket_print = 0
write = 1
check = 0
# has the same name as functions and data types
invalid_models_type1 = []
invalid_graphs_type1 = []
# has op sign in ... |
import math
class ListNode:
def __init__(self, val):
self.next = None
self.val = val
class LinkedListOperations:
def createLinkedList(self, arr):
"""
Create Linked List with values in input array.
:type:
"""
return
def mergeTwoLists(self, l1, l2):
... |
from django.contrib import admin
from .models import Product,Item,Promotions,TimeDeal,ItemComment
# Register your models here.
admin.site.register((Product,Item,Promotions,TimeDeal,ItemComment)) |
# -*- coding:UTF-8 -*-
from rest_framework.routers import DefaultRouter
from . import views
router=DefaultRouter()
app_name='delivery'
router.register('orderCallback',views.OrderCallbackViewSets,base_name='orderCallback')
urlpatterns=router.urls |
# Script that takes code.bin as an input and
# decodes the emoji instruction in it to
# assembly like instructions and writes them
# to a output file
import sys
emojiToInsruction = {
b'\xf0\x9f\x92\xaa': "PUSH", #arm
b'\xF0\x9F\x93\x96': "READ", #book
b'\xe2\x9c\x8f\xef\xb8\x8f': "WRITE", #pen
b'\xf0\... |
import part1
import part2
from flask import Flask
from flask import request
from flask import render_template
import os
from werkzeug import secure_filename
app = Flask(__name__, template_folder='templates')
Upload_Folder = './Upload_Folder'
app.config['Upload_Folder'] = Upload_Folder
@app.route('/', methods=['GET'])... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Script that initializes 'cadaster' index in ElasticSearch so that
is also well supported by Kibana Visualization """
from src.utils.elasticsearch_utils import ElasticSearchUtils
if __name__ == "__main__":
ElasticSearchUtils.remove_index()
ElasticSearchUtils.c... |
import pandas as pd
student1 = pd. Series({'국어':100,"영어":80,'수학':90})
print(student1)
print()
print("# 학생의 과목별 점수를 200으로 나누기")
percentage = student1/200
print(percentage)
print(type(percentage))
student2 = pd.Series({'수학':80,'국어':90,'영어':80})
print('===================================')
print(student1)
print()
pri... |
# -*- coding: utf-8 -*-
"""
Geometry of an artery bifurcation
Olga Mula 2019
Modified by Changqing Fu
"""
from dolfin import * # FEM solver
# from mshr import * # mesh
import numpy as np
class Artery():
def __init__(self, diam_steno_vessel=0.1, diam_narrow=0.04, theta_steno=np.pi/6, diam_healthy... |
#Objective: Use sckitit learn module (and its least squares model, LInearRegression) to solve simple linear regression coefficients
#The data set is the same data set used for the normal equation / matrix multiplication in a different code set
#import modules
import pandas as pd
from sklearn.linear_model import Linear... |
import sys
input = sys.stdin.readline
from collections import deque
from copy import deepcopy
def main():
N, M, P = map( int, input().split())
E = []
rE = [[] for _ in range(N)]
for _ in range(M):
a, b, c = map( int, input().split())
a, b = a-1, b-1
E.append((a,b,c-P))
... |
import sys, os, cPickle, re, json, dircache, datetime, itertools, gzip
from multiprocessing import Pool
class AutoDict(dict):
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
class Logline(object... |
import math
class Circle(object):
def area(self,radius):
return math.pi*radius**2
def circumference(self,radius):
return 2* math.pi * radius
c = Circle()
c.area(3)
c.circumference(5)
|
nome = 'jessica'
message = "Alô " + nome.title() + ", voce gostaria de aprender um pouco de Python Hoje?"
famoso = 'Albert Einstein'
message2 = famoso
print (message)
nome = " Jessica "
x = nome.lstrip()
y = nome.rstrip()
z = nome.strip()
print(x + z + y)
print(nome.lower())
print(nome.upper())
print(... |
from libra.ledger_info import LedgerInfo
from libra.validator_verifier import VerifyError
from libra.hasher import *
from libra.proof import verify_transaction_list
from libra.proof.signed_transaction_with_proof import SignedTransactionWithProof
from libra.proof.account_state_with_proof import AccountStateWithProo... |
'''15. Write a Python program to filter a list of integers using Lambda. '''
nums = [1, 2, 3, 4, 5]
print(nums)
print("\nEven number:")
even = list(filter(lambda x: x%2 == 0, nums))
print(even)
print("\nOdd number:")
odd = list(filter(lambda x: x%2 != 0, nums))
print(odd)
|
#!/usr/bin/python
import datetime
import time
def onPageLoad(paramstr):
now = datetime.datetime.now()
return "Current Time: " + now.strftime("%c")
|
import os
from os.path import join
# To use the code you should change hard_coded_out_dir and hard_coded_code_dir
# to fit your system
def which_computer():
"""
Detect if we are working on Iain's laptop or on the cluster
"""
cwd = os.getcwd()
if 'iaincarmichael' in cwd:
return 'iain_lapto... |
import tmdb_api
from pprint import pprint
import os
import cv2
import scenedetect
from scenedetect.video_manager import VideoManager
from scenedetect.scene_manager import SceneManager
from scenedetect.frame_timecode import FrameTimecode
from scenedetect.stats_manager import StatsManager
from scenedetect.detectors impor... |
#!/usr/bin/env python
#start zap daemon
# encoding=utf8
# -*- coding: utf-8 -*-
import os
import subprocess
import time
from pprint import pprint
from zapv2 import ZAPv2
from shutil import copyfile
print 'Starting ZAP ...'
subprocess.Popen(['/Applications/OWASP ZAP.app/Contents/Java/zap.sh','-daemon'],stdout=open(os.... |
#1
#v 0.001
def _ERROR(Message,Function):
import sys,traceback
i=sys.exc_info();T=traceback.extract_tb(i[2])[0]
print '-----'
print 'Recall: '+Function
print
print 'File: '+T[0].split('\\')[-1]+', line '+str(T[1])
print "Code: '"+T[3]+"'"
print traceback.format_exception_only(i[0], i[1... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import bs4
import time
un="Redacted"
pw="Redacted"
# initialize browser, --incognito for cache/cookies
option = webdriver.ChromeOptions()
option.add_argument("— incognito")
# replace 'C:/bin/chromedriver.exe' to where chromedriver is inst... |
from zipfile import ZipFile
zip = ZipFile('ch6.zip', 'r');
print(zip.getinfo('90052.txt').comment);
pathPrefix = 'ch6/';
fileType = '.txt';
filename = "90052";
fileContents = open(pathPrefix + filename + fileType, "r").read();
filename = fileContents[fileContents.index('is') + 3:];
print(str(zip.getinfo(filename + f... |
# This is the file you'll use to submit most of Lab 0.
# Certain problems may ask you to modify other files to accomplish a certain
# task. There are also various other files that make the problem set work, and
# generally you will _not_ be expected to modify or even understand this code.
# Don't get bogged down with ... |
from django.conf.urls import include, url
#from . import chat.views
import views
urlpatterns = [
url(r'^$', views.about, name='about'),
url(r'^new/$', views.new_discussion, name='new_discussion'),
url(r'^(?P<label>[\w-]{,50})/$', views.discussion_forum, name='discussion_forum'),
]
|
'''
1 获取2019年4月之前的新闻链接
2 存入csv
'''
import time
import sys
import os
import pymysql
from pymysql import Error
import requests
from multiprocessing import Pool
from bs4 import BeautifulSoup
from pandas.core.frame import DataFrame
#获取滚动页面的url
def get_url(date):
url = 'http://www.chinanews.com/scroll-news/' + date +'/... |
# -*- coding: utf-8 -*-
"""MRI pulse-design-specific linear operators.
"""
import sigpy as sp
from sigpy import backend
def PtxSpatialExplicit(sens, coord, dt, img_shape, b0=None, ret_array=False):
"""Explicit spatial-domain pulse design linear operator.
Linear operator relates rf pulses to desired magnetizat... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.lista_personas, name='lista_personas'),
path('persona/nueva', views.persona_nueva, name='persona_nueva'),
path('tarjetas', views.lista_tarjetas, name='lista_tarjetas'),
path('tarjetas_con_plata', views.tarjetas_con_plata, n... |
import csv
num_list = []
for i in range(0, 49):
i += 1
num_list.append(i)
neue = []
for i in range(0, 49):
for j in range(0, 49):
for k in range(0, 49):
for x in range(0, 49):
for y in range(0, 49):
for z in range(0, 49):
... |
import logging
from furl import furl
from lxml import etree
from share.harvest import BaseHarvester
logger = logging.getLogger(__name__)
# TODO Could we use the OAI harvester instead, or is there something non-standard about NCAR?
class NCARHarvester(BaseHarvester):
VERSION = 1
namespaces = {
'OAI... |
"""
This module takes care of starting the API Server, Loading the DB and Adding the endpoints
"""
import os
from flask import Flask, request, jsonify, url_for
from werkzeug.wrappers import response
from flask_cors import CORS
from utils import APIException, generate_sitemap
from datastructures import FamilyStructure
i... |
from datetime import datetime
from dateutil.parser import isoparse
from functools import cached_property
from onegov.agency.collections import ExtendedPersonCollection
from onegov.agency.collections import PaginatedAgencyCollection
from onegov.agency.collections import PaginatedMembershipCollection
from onegov.api imp... |
from gevent.monkey import patch_all
patch_all()
|
class Solution(object):
def rob(self, root):
res = self.robSub(root)
return max(res[0], res[1])
def robSub(self, root):
if not root:
return [0, 0]
left = self.robSub(root.left)
right = self.robSub(root.right)
res = [0, 0]
res[0] = max(left[0],... |
from django import forms
from .models import Layer, Messagetiers, Projet
from django.forms import ModelForm, ModelChoiceField
from django.utils.translation import ugettext_lazy as _
class UploadFileForm(forms.Form):
name = forms.CharField(label='Nom du fichier', max_length=100)
file = forms.FileField()
class ... |
import pandas as pd
from sklearn import svm, metrics
house = pd.read_csv('Housing.csv', sep=',', header=0)
k = pd.get_dummies(house.iloc[:,[6,7,8,9,10,12]])
house = house.join(k.iloc[:,[0,2,4,6,8,10]])
data = house.iloc[:,[2,3,4,5,11,13,14,15,16,17,18]]
label = house.iloc[:,1]
clf = svm.SVC(gamma='auto')
clf.fit(data... |
import os
def path_split(path):
"""
This is a replacement for the combined use of os.path.split and
os.path.splitext to decompose a relative path into its components.
"""
path_and_file = path.rsplit(os.sep, 1)
if len(path_and_file) <= 1:
path = ""
else:
path = path_and_file... |
def checkio(number):
def get_min_k(ns):
maxs = "0"
for s in ns:
if ord(maxs) < ord(s):
maxs = s
if ord(maxs) < 60:
return ord(maxs) - 48 + 1
else:
return ord(maxs) - 55 + 1
def sum_number(number1,k1):
sumNumber = 0
... |
from urllib import request,parse
from http import cookiejar
import re
url='https://login.bit.edu.cn/cas/login'
req=request.Request(url)
req.add_header('Host','login.bit.edu.cn')
req.add_header('Origin','https://login.bit.edu.cn')
req.add_header('Referer','https://login.bit.edu.cn/cas/login?service=http%3A%2F... |
"""
Profile page app adming module.
"""
#from django.contrib import admin
# Register your models here.
|
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from locators import TestPageLocators as TPL
from base_page import BasePage
class TestPage(BasePage):
"""
A TestPage class ables to interact with the tested page
"""... |
# _*_ coding:utf-8 _*_
__anthor__=u'橘子来了'
import Scrapy
class ScrapySpider(scrapy.spiders.Spider):
name="xs84"
all
if __name__=="__main__": |
import sys
from PyQt5 import QtWidgets
from Designs import mainWindow
from Models import Data
# noinspection PyBroadException
class MainApp(QtWidgets.QMainWindow, mainWindow.Ui_MainWindow):
def __init__(self):
# inherit from parent class, setup UI
super(self.__class__, self).__init__()
sel... |
# class Hand:
# pass
# class Foot:
# pass
# class Trunk:
# pass
# class Head:
# pass
#
#
#
#
# class Person:
# def __init__(self,id_num,name):
# self.id_num = id_num
# self.name = name
# self.hand = Hand()
# self.foot = Foot()
# self.trunk = Trunk()
# ... |
import mysql.connector as mc
import FoodFilter as foodpy
from datetime import datetime
'''
password is hidden for privacy purposes
'''
Password = '****************'
Cure=[]
nutr = list()
problem = list()
TotalEnergy = dict()
FoodValues={}
DeficiencyToFoodMap={
"Water":"Water",
"Protein":"Protein",... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class RNNNaive(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(RNNNaive, self).__init__()
self.hidden_size = hidden_size
self.i2h = nn.Linear(input_size+hidden_size, hidden_size)
self.h2o ... |
# -*- coding: utf-8 -*-
# flake8: noqa
# Generated by Django 1.11 on 2017-05-27 09:05
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('catalog', '0005_productcategory_seo_block_imag... |
import os
import glob
from collections import defaultdict
import langid
from generate_multi import ParallelWriter
#from ilmulti.segment import Segmenter
#from ilmulti.sentencepiece import SentencePieceTokenizer
reqs = ['hi', 'ml', 'ta', 'ur', 'te','bn','mr', 'gu', 'or']
for lang in reqs:
mkb = defaultdict(list... |
import pytest
import transaction
from onegov.core.orm import Base, SessionManager
from onegov.core.orm.types import UUID
from onegov.pay.models import Payable, Payment, PaymentProvider, ManualPayment
from onegov.pay.collections import PaymentCollection
from sqlalchemy import Column
from sqlalchemy import Text
from sql... |
from utils import readTrainLabels,readTrainData
import classModel
import glob
def main():
directory=classModel.Directories()
files=glob.glob(directory.xmlPath)
para=classModel.Parameters()
modelPara=classModel.ModelParameters(len(files),para.lx,para.ly,7)
CNNModel=classModel.Model()
CNNModel.model.compile(loss=... |
from flask import jsonify
from werkzeug.http import HTTP_STATUS_CODES
def error_response(status_code, message=None):
scoreload = {}
if message:
scoreload["errors"] = message
else:
scoreload["errors"] = HTTP_STATUS_CODES.get(status_code, 'Unknown Error'),
#end if
response = scoreloa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.