text stringlengths 8 6.05M |
|---|
# 字符串操作测试
a = list()
b = list()
print(a is b)
print(a == b)
|
from __future__ import print_function
import numpy as np;
from keras.layers import Input, Dense, Lambda, Flatten, Reshape, Dropout
from keras.layers import Convolution2D, Conv2DTranspose
from keras.models import Model
from keras.optimizers import SGD, Adam, RMSprop, Adadelta
from keras.callbacks import Callback, ModelC... |
from pandas import DataFrame, read_csv
import pandas as pd
import matplotlib.pyplot as plt
import math
import re
import numpy as np
import random
file = 'train_test.csv'
file_evaluate = 'evaluate.csv'
Data = pd.read_csv(file)
poems = Data['text']
statuses = Data['label']
numberOfpoems = len(poems)
train_index = ... |
from itertools import chain, combinations
from aimacode.planning import Action
from aimacode.utils import expr
from layers import BaseActionLayer, BaseLiteralLayer, makeNoOp, make_node
class ActionLayer(BaseActionLayer):
def _inconsistent_effects(self, actionA, actionB):
""" Return True if an effect of ... |
import pandas as pd
x = {'one':[1,2,3], 'two':[4,5,6]}
df = pd.DataFrame(x)
df.set_index(['a','b','c'])
print(df)
|
def getTotal(costs, items, tax):
output = 0
for x in items:
output += costs.get(x, 0)
return round((output * tax) + output,2)
'''
How much will you spend?
Given a dictionary of items and their costs and a array specifying the items
bought, calculate the total cost of the items plus a given tax.
... |
from django.urls import path
from . import views
import django.conf.urls
from django.views.generic import TemplateView
urlpatterns=[
path('',views.home,name='doctor first page'),
path('signup/',views.signup,name="doctor signup"),
path('ajaxlogin/',views.ajaxlogin,name="ajaxlogin"),
path('signup/ajaxsignup/',views.... |
# image process
import os
import cv2
DEBUG = False
class Image:
scale_percent = 10 # percent of original size
def __init__(self, path, camera_i, time_i, ori_img=True):
self.ori_path = path
self.resize_path = None
self.camera_i = -1
self.time_i = -1
self.image_name = ... |
#!/usr/bin/env python
def fib(x):
''' assumes x is an int and >= 0
returns Fibonacci of x'''
assert type(x) == int and x >= 0
if x == 0 or x == 1:
return 1
else:
return fib(x-1) + fib(x-2)
print fib(7)
print fib(-2)
print fib(t)
|
from django.forms import ModelForm
from index.models import Moment
class MomentForm(ModelForm):
class Meta:
model = Moment
fields='__all__' |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
from web_backend.nvlserver.module import nvl_meta
from sqlalchemy import BigInteger, String, Column, Boolean, DateTime, Table, ForeignKey, func
from geoalchemy2.types import Geometry
from sqlalchemy import Numeric
from sqlalchemy.dialects.postgresql... |
import os
import webapp2
import jinja2
from new import Story
from google.appengine.ext import db
class ReviewHandler(webapp2.RequestHandler):
def post(self):
ratingValue = self.request.get('review.reviewRating.ratingValue')
reviewBody = self.request.get('review.reviewBody')
id = self.request.get('id')... |
import numpy as np
from copy import copy as copy
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from scipy.sparse import csr_matrix
from numpy.polynomial import Legendre
def normal_eqn_vects(X, Y, W, var):
overlap = np.einsum('bai,bi,bci->bac', X, W, X, optimize='greedy')
if np.any(np.lina... |
# test 1
# 输入的获取
# message = input("Please input some sent\n")
# message = int(message) #强制类型转换
# print(message+1)
'''
input()返回的输入的都被视作字符串,应该用相应的类型转换函数强制转换
'''
# test 2
# while循环
num = 0
sum = 0
while num < 5:
sum = sum + num
num = num + 1
print(sum)
# test 3
# 用户选择何时退出
print("===========================... |
import boto3
import random
import string
from typing import Dict, List
# prefix for objects created in test
ID_PREFIX = "fake-"
# us-east-1 is bleeding edge features
DEV_REGION = "us-east-1"
def id_generator(size=8, chars=string.ascii_lowercase + string.digits):
random_string = ''.join(random.choice(chars) for ... |
import pkg_resources
libsgutils2 = pkg_resources.resource_filename(__name__, 'libsgutils2-2.dll')
libc = 'msvcrt' |
from GUI import gaGUI
# 2*exp( - (x**2) - (y**2) ) + 5 * exp ( - (( x - 3 )**2) - (( y - 3)**2) ) max save all files widac dobrze tutaj!!!!
# (x ** 1/2 - 5 * y ) / (x ** 2 + y ** 2 - 2 * x + 10) - przykladowa Funkcja do testowania
# sin(x) + cos(y) min po wpisaniu idz do katalogu results + stworzony gif save all file... |
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class GimletUser(AbstractUser):
ROLE_OWNER = 'owner'
ROLE_MANAGER = 'manager'
ROLE_EMPLOYEE = 'employee'
ROLE_CHOICES = (
(ROLE_OWNER, 'Owner'),
(ROLE_MANAGER, 'Manager'),
... |
from psana import dgram
from psana.event import Event
from psana.psexp import PacketFooter, TransitionId, PrometheusManager
import numpy as np
import os
import time
import logging
logger = logging.getLogger(__name__)
s_bd_just_read = PrometheusManager.get_metric('psana_bd_just_read')
s_bd_gen_smd_batch = Promet... |
from django import forms
from .models import Contact
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field, Div, Submit
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
fields = ('name', 'number', 'email', 'message')
def clean(self):
c... |
import sys
from functools import wraps
import logging
import os
import random
import time
from contextlib import contextmanager
from typing import Union
from pathlib import Path
import numpy as np
import torch
from hydra.experimental import compose, initialize
from hydra._internal.hydra import Hydra as BaseHydra
def ... |
# Declares the variable "car" to equal 100
cars = 100
# Declares the variable "space_in_a_car" to equal 4
space_in_a_car = 4
# Declares the variable "driver" to equal 30
drivers = 30
# Declare the variable "passegers" to equal 90
passengers = 90
# Declares the variable "cars_not_driven" to equal the sum of cars minus d... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
# Create your views here.
def index(request):
return render(request, "store/index.html")
def checkout(request):
return render(request, "store/checkout.html")
def delete(request):
de... |
import xml.etree.ElementTree as ET
import csv
#import xml.dom.minidom as md
#
def main():
tree = ET.parse("D:\PPTV\Collins\DMC-31218-A-25-20-43-01000-941A-D_002-00_EN-US.XML")
root=tree.getroot()
#open a file for writing
Output_file=open('D:\PPTV\Collins\out.csv','w')
#create csv writer object
csvwr... |
import json
import time
import sys
from cleanser import df_header
from downloader import vinculo_str_d, month_list
def parser(month, year, file_list, df_struct):
json_data = json_encoder(month, year, file_list, df_struct)
print(json_data)
def json_encoder(month, year, file_list, employee_struct):
# Criaç... |
import hashlib
from time import time
class BlockChain:
"""
区块链结构体
chain:包含的区块列表 索引从1开始向后计数
current_transactions:存储每次需要打包的交易
transactions:存储所有交易记录
"""
def __init__(self):
self.chain = []
self.current_transactions = []
self.transactions = ... |
import re
# Memory Module
class Partition:
process = "A"
start_unit = 0
size = 2
def __init__(self, process, start, size):
self.process = process
self.start_unit = start
self.size = size
class Memory:
def allocate(self, process, size):
start = self.alloc_start
if self.type == "nf": # handle next fit
... |
import unittest
from katas.kyu_7.return_a_sorted_list_of_objects import sort_list
class SortListTestCase(unittest.TestCase):
def test_equals_1(self):
self.assertEqual(sort_list('x', []), [])
def test_equals_2(self):
self.assertEqual(sort_list(
'b', [{'a': 2, 'b': 2}, {'a': 3, 'b'... |
"""
13. Longest Palindromic Substring
Question:
Given a string S, find the longest palindromic substring in S. You may assume that the
maximum length of S is 1000, and there exists one unique longest palindromic substring.
Hint:
First, make sure you understand what a palindrome means. A palindrome is a string
which ... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class BeerAdvocateItem(scrapy.Item):
#ip_address = scrapy.Field()
pass
class RatingSummaryPageItem(scrapy.Item):
beer_name = scrapy.Field(... |
from itertools import cycle, islice
import tensorflow as tf
class FullyConnectedWTA:
"""Fully-connected winner-take-all autoencoder.
This model is deterministic.
"""
def __init__(self,
input_dim,
batch_size,
sparsity=0.05,
hidden_u... |
from django.db import models
from django.contrib.auth.models import User
class Project(models.Model):
STATUS_CHOICES = [
('LATE', 'Late'),
('ON TRACK', 'On Track'),
('NEAR COMPLETIONS', 'Near Completion'),
]
description = models.CharField(max_length=30)
status = models.CharField... |
import common
import random
def run(nick, message, cmd_prefix):
arg = common.get_plugin_argument(message, cmd_prefix, 'choose')
if arg is None:
return
if not arg:
return '{}: nothing to choose from'.format(nick)
result = random.choice(arg.strip().split(' | ')).strip()
return '{}: ... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import logging
from dataclasses import dataclass
from pathlib import PurePath
from typing import Any
from pants.backend.docker.target_types import AllD... |
# 给定一个仅包含大小写字母和空格 ' ' 的字符串 s,返回其最后一个单词的长度。如果字符串从左向右滚动显示,那么最后一个单词就是最后出现的单词。
#
# 如果不存在最后一个单词,请返回 0 。
#
# 说明:一个单词是指仅由字母组成、不包含任何空格字符的 最大子字符串。
#
#
#
# 示例:
#
# 输入: "Hello World"
# 输出: 5
#
# Related Topics 字符串
# 👍 226 👎 0
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def leng... |
#!/usr/bin/env python
# -*- Mode: Python; indent-tabs-mode: nil; tab-width: 4 -*-
# Date: 2017.07.03
# Author: Luis Cardoso
# Description: Create a list using the header information of all scripts and
# export to a CSV file.
# Modified by: Luis Cardoso
# Version: 0.1
import os
import sys
import... |
# -*- coding: utf8 -*-
import cx_Oracle
import requests
import json
import os
from backend import syn_sign,syn_student
#不加本句会出现中文编码问题!!!
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
def a(date):
host="xjtudlc_kq/it516kqdlc8tj@uc.xjtu.edu.cn/orcl.uc"
connection=cx_Oracle.connect(host)
cursor = ... |
#coding=utf8
#########################################################################
# Copyright (C) 2016 All rights reserved.
#
# 文件名称:RomeAnnotation.py
# 创 建 者:unicodeproject
# 创建日期:2016年11月29日
# 描 述:
#
# 备 注:将日语假名注音转成罗马音
# 用最短路径分词方法将假名系列作切分,如シャギ 可分成 シ、ャ、ギ 或者シャ、ギ
# 注意促音的处理
###################... |
from flask import Flask, render_template # Import Flask to allow us to create our app
app = Flask(__name__) # Create a new instance of the Flask class called "app"
@app.route('/') # The "@" decorator associates this route with the function immediately following
def index():
return "Hello World!"
@ap... |
distancia = float(input('Qual a distância percorrida em km: '))
dias = float(input('Qual a quantidade de dias que o carro foi alugado: '))
valordias = 60.00 * dias
valordistancia = 0.15 * distancia
total = valordias + valordistancia
print(f'R${total:.2f}')
|
import os
import re
import requests
# 设置要遍历的目录
dir_path = '../_posts/'
# 定义正则表达式匹配图片行和flickr图片url
md_img_pattern = re.compile(r'!\[.*?\]\((.*?)\)')
html_image_pattern = re.compile(r'<img.*?src="(.*?farm8\.staticflickr\.com.*?)".*?>')
flickr_pattern = re.compile(r'staticflickr\.com')
# file_type = '.html'
file_type ... |
from collections import defaultdict
import numpy as np
import networkx as nx
import sys
from attrdict import AttrDict
from logging import getLogger
from genice_svg import hooks, render_svg
from countrings import countrings_nx as cr
v1 = np.array([0.0, 0.0, 0.0])
r1 = 0.75
v2 = np.array([1.0, 1.0, 1.0])
r2 = 0.5
rb =... |
from tek import cli, Config
@cli(parse_cli=False)
def cli_test(data):
data.append(Config['sec1'].key1)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging as log
import yaml
import os
def get_settings_yml_file():
yml_file = None
config_file = "configs/settings.yaml"
try:
with open(config_file, 'r') as yml:
yml_file = yaml.load(yml, Loader=yaml.SafeLoader)
except KeyError:... |
"""
CCT 建模优化代码
作者:赵润晓
日期:2021年5月21日
"""
from cctpy import *
from hust_sc_gantry import HUST_SC_GANTRY
import time
import numpy as np
# 可变参数
# 动量分散
momentum_dispersions = [-0.05, -0.0167, 0.0167, 0.05]
# 每平面、每动量分散粒子数目
particle_number_per_plane_per_dp = 12
# 每个机架(束线)粒子数目
particle_number_per_gantry = len(
momentum_... |
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
#
# What is the 10 001st prime number?
primenum = 10001
i=0
testnum=2
while i < primenum:
checkprime = True
for j in range(2,testnum):
if testnum%j==0:
checkprime=False
if checkprime==True:
i+=1
current... |
def is_matched(expression):
stack = []
pair_lookup = {'{': '}', '(': ')', '[': ']'}
# loop through each character in the expression and push its closing counterpart
for ch in expression:
if ch in pair_lookup:
stack.append(pair_lookup[ch])
# when encounter a closing counterpa... |
numbers=[2,3,1,6,4,8,9]
numbers.insert(0,22) # bu insert methodi yordamida ko'rsatilgan indexdagi listning ichiga qo'shadi
print(numbers) |
#! /usr/bin/env python
import sys
import os
import argparse
from array import *
import numpy as np
import ROOT
import yaml
from pyjetty.alice_analysis.analysis.user.james import run_analysis_james_base
from pyjetty.alice_analysis.analysis.user.james import plotting_utils_subjet_z
# Prevent ROOT from stealing focus w... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.jvm.resolve.jvm_tool import JvmToolBase
from pants.option.option_types import SkipOption
class ScalafmtSubsystem(JvmToolBase):
options_scope = "scalafmt"
name = "scala... |
# -*- coding: UTF-8 -*-
li = ["a", "b", "mpilgrim", "z", "example"]
print li
print li[1]
li.append("new")
print li
li.insert(2, "new")
print li
li.extend(["two", "elements"])
print li
print li.index("example")
print "c" in li
print "example" in li
li.remove("a")
print li
li.remove("new") # 删除首次出现的一个值
print li
p... |
import unittest
from knowledge_graph.Mind import Mind
class TestLoadingOntology(unittest.TestCase):
def test_valid_ontology_source(self):
onto = Mind()
self.assertIsNotNone(onto.get_ontology()) |
import unittest
from look_and_say import *
# http://dojopuzzles.com/problemas/exibe/sequencia-look-and-say/
class LookAndSayTest(unittest.TestCase):
def test_menor_numero(self):
self.assertEquals(11, look_and_say(1))
def test_segundo_menor_numero(self):
self.assertEquals(12, look_and... |
#!/usr/bin/env python
import argparse
from braindecode.experiments.parse import (
create_experiment_yaml_strings_from_files, create_config_strings, create_config_objects,
create_templates_variants_from_config_objects,
process_parameters_by_templates, process_templates)
import numbers
def parse_command_lin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
get_user_hw_action_list_query = """
SELECT hwa.id AS id,
uhwa.user_id AS user_id,
uhwa.value as value,
hwa.name AS action_name,
hwa.hw_action_type_id AS hw_action_type_id,
... |
__author__ = "Narwhale"
animals = ['dog','lion','leopard']
for i in animals:
print(i)
#----------------------------------
for i in animals:
print('A %s will run'%i)
print('Any of hhese animals will run') |
"""
Serializers for consuming job submissions for running models and generating reports
"""
import json
from django.conf import settings
from rest_framework import serializers
from landscapesim.async.tasks import run_model
from landscapesim.models import Library, Project, Scenario, RunScenarioModel
from landscape... |
import matplotlib.pyplot as plt
import fast_cppn
import quad_tree
import queue
import random
def get_pattern(cppn, x1, y1, x2_range=[-1, 1], y2_range=[-1, 1],
step=0.05, threshold=None):
import numpy as np
output = []
i = 0
for y in np.arange(y2_range[0], y2_range[1], step):
ou... |
#-*- coding:utf-8 -*-
"""
if __name__ == '__main__':
tlist = []
head, mid, rear = 1, 0, 1
for i in range(input()):
tlist.append(head)
mid = int(head+rear)
head = rear
rear = mid
print tlist[i]
"""
tlist = []
head, mid, rear = 1, 2, 2
for i in range(1, input()):
... |
"""
Logic of the mongoDB interaction.
If you wish to use another databse, modify this file
and this file only.
"""
import pymongo
from pymongo.errors import PyMongoError
import config as cf
class DBError(PyMongoError):
""" Base class for Database errors, inheriting from
the base class for all pymongo e... |
ct = 1
mtx = []
lenMtx = int(input("Enter values to create a matrix : "))
for i in range(lenMtx) :
for x in range(1, lenMtx + 1) :
if x != ct :
mtx.append(0)
else :
mtx.append(1)
ct += 1
print(mtx) |
# I'm using horizontal bars as I think it's more space efficient than the vertical one
# It's also seem easier to draw vertical comparison between bars
import numpy as np
import matplotlib.pyplot as plt
import pandas
from textwrap import wrap
from matplotlib.ticker import FuncFormatter
import locale
locale.setlocale(lo... |
def longpal(s):
n = len(s)
maxpal = ''
for k in range(1,n+1):
for i in range(0,n+1-k):
j=0
while s[i+j] == s[i+k-1-j] and j < k/2:
j+=1
if j == k/2:
maxpal = s[i:i+k]
return maxpal
|
print"hello
print "aniket
|
# -*- coding: utf-8 -*-
from typing import Optional, Callable, Awaitable, Tuple, Union, List, TypeVar
from discord import Member, Embed
from commands.base.client import Ratelimit
from . import bot, Command, CommandError, authorise, Context
from . import get_alias, toggle_alias
from . import language
from . import to... |
"""This module contains pipeline definitions"""
import logging
import numpy as np
import sys
# set up a logger, at least for the ImportError
model_logr = logging.getLogger(__name__)
model_logr.setLevel(logging.DEBUG)
model_sh = logging.StreamHandler(stream=sys.stdout)
formatter = logging.Formatter('%(asctime)s : %(n... |
import string
def stringsplitter(string1):
arr2 = []
string1 = ''.join(c for c in string1 if c not in string.punctuation)
arr = string1.split(" " or "\n")
for i in range(len(arr)):
if not (type(arr[i]) != str or len(arr[i]) == 0):
arr2.append(arr[i])
print(arr2)
def zipfslaw1(arr):
d = {}
for i in range(... |
# Create SQLite table and populate it
import sqlite3
with sqlite3.connect("blog.db") as connection:
c = connection.cursor()
c.execute("""CREATE TABLE posts (title TEXT, post TEXT)""")
c.execute('INSERT INTO posts VALUES ("Well","I am well, thanks.")')
c.execute('INSERT INTO posts VALUES ("Good","I am good, than... |
# Generated by Django 2.1.2 on 2018-12-11 12:43
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('main', '0013_auto_20181128_1358'),
]
operations = [
migrations.CreateModel(
name='Cities',
... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
last mod 6/4/19
"""
import numpy as np
from scipy.optimize import linear_sum_assignment
import matplotlib.pyplot as plt
overlapres = 50
overlapbox = np.mgrid[:float(overlapres), :float(overlapres)]
overlapbox += .5
overlapbox *= 2./overlapres
overlapbox -= 1
overla... |
import maya.cmds as cmds
selection = cmds.ls(sl=True)
ws = cmds.workspace(q = True, fullName = True)
wsp = ws + "/" + "images"
cmds.sysFile(wsp, makeDir=True)
for i in range(0,50):
cmds.xform('Lamborginhi_Aventador', ws =True, relative=True, rotation=(45, 45, 45) )
cmds.saveImage( currentView=True )
i... |
# Generated by Django 3.0.5 on 2020-05-04 09:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('clients', '0004_clientprofile_branch'),
]
operations = [
migrations.AddField(
model_name='clientprofile',
name='cont... |
import re
class Verify:
def is_empty(self, items):
for item in items:
if bool(item) is False:
return True
return False
def is_whitespace(self, items):
for item in items:
if item.isspace() is True:
return True
... |
from django.urls import include, path
from . import views
urlpatterns = [
# return render templates
path('', views.index),
path('dogs', views.display_all_dogs),
path('dogs/new', views.new_dog),
path('dogs/<int:single_dog_id>', views.display_single_dog),
path('dogs/<int:single_dog_id>/edit', vi... |
import numpy as np
import random
from copy import deepcopy
from scipy.linalg import pinv2, cholesky, inv
from scipy import outer, dot, multiply, zeros, diag, mat, sum
def compute_ranks(x):
"""
Returns ranks in [0, len(x))]
which returns ranks in [1, len(x)].
(https://github.com/openai/evolution-strat... |
def my_parse_int(string):
try:
return int(string)
except ValueError:
return 'NaN'
'''
JavaScript provides a built-in parseInt method.
It can be used like this:
parseInt("10") returns 10
parseInt("10 apples") also returns 10
We would like it to return "NaN" (as a string) for the secon... |
import polars as pl
def test_horizontal_agg(fruits_cars: pl.DataFrame) -> None:
df = fruits_cars
out = df.select(pl.max([pl.col("A"), pl.col("B")])) # type: ignore
assert out[:, 0].to_list() == [5, 4, 3, 4, 5]
out = df.select(pl.min([pl.col("A"), pl.col("B")])) # type: ignore
assert out[:, 0].t... |
# Generated by Django 3.1.5 on 2021-01-22 19:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('data_aggregator', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='assignment',
name='excused',
... |
import os
from pprint import pprint
import cv2
import requests
imageName = "car"
imgType = ".jpg"
def handle_plate_identifier(croppedFrame, accessToken, objectID, score=0, regions=[]):
currentImageName = imageName + str(objectID) + imgType
cv2.imwrite(currentImageName, croppedFrame)
licenseNumber = str()... |
#!/usr/bin/env python
import roslib
roslib.load_manifest('baxter_rr_bridge')
import rospy
import baxter_interface
from sensor_msgs.msg import Image
from sensor_msgs.msg import CameraInfo
import time
import sys, argparse
import struct
import time
import RobotRaconteur as RR
import thread
import threading
import numpy
i... |
from assets import art
from resource import Resource
from cashier import Cashier
class Printer:
"""This class act like a printer which the users interact with
"""
print(art.logo)
print('Welcome to automated printer')
@classmethod
def printer_machine(cls):
resource = Resource()
... |
from tensorflow import keras
from tensorflow.keras import layers, utils
from sklearn.preprocessing import FunctionTransformer
from sklearn.pipeline import Pipeline
from original_approach import dataset
from sklearn.pipeline import Pipeline
from tensorflow.keras.wrappers.scikit_learn import KerasClassifier
from tensorfl... |
import boto3
import json
# Document
documentName = "7_screen.png"
documentName = "test2.png"
# Read document content
with open(documentName, 'rb') as document:
imageBytes = bytearray(document.read())
# Amazon Textract client
textract = boto3.client('textract')
# Call Amazon Textract
response = textract.detect_d... |
__author__ = "Vincent"
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def clean_df():
global df
df= pd.read_csv("DOHMH_New_York_City_Restaurant_Inspection_Results.csv")
df = df.dropna()
#Remove invalid grades (P & Z = grade pending)
mask = df.GRADE.isin(['P','Z','Not ... |
from django.urls import path
from django.urls.resolvers import URLPattern
from. import views
urlpatterns = [
path("", views.index)
] |
import utils
import time
def url_name(url):
# the web page opens up
chrome_driver.get(url)
# webdriver will wait for 4 sec before throwing a
# NoSuchElement exception so that the element
# is detected and not skipped.
time.sleep(4)
def first_picture():
# finds the first picture
pic ... |
import time
import sys
import ibmiotf.application
import ibmiotf.device
import random
import requests
#Provide your IBM Watson Device Credentials
organization = "985bj1"
deviceType = "ibmiot"
deviceId = "1001"
authMethod = "token"
authToken = "1234567890"
def myCommandCallback(cmd):
print("Command ... |
# ---------------------------------------------------------------------------
# extract_basin_nlcd_grid_count.py
# Created on: 2014-07-22 18:31:19.00000 (generated by ArcGIS/ModelBuilder)
# Description: extract NLCD gridded data using basin shapefiles and write
# a land cover count summary to csv file
# ----------... |
import cv2
import numpy as np
# Used everytime trackbar changes. (We don't want to do anything)
def emptyFunction(self):
pass
windowName = 'BGR color pallette'
cv2.namedWindow(windowName)
img1 = np.zeros((512, 512, 3), np.uint8)
cv2.createTrackbar('B', windowName, 0, 255, emptyFunction) # Name, lowerbound, upp... |
from collections import defaultdict
def pentagonal(n):
return int((3 * n ** 2 - n) / 2)
pentagon_numbers = defaultdict(bool)
pentagonal_list = []
# list for itterating over numbers, dict for checking existence
for i in range(1, 10000):
pentagonal_list.append(pentagonal(i))
for i in pentagonal_list:
pe... |
# -*- coding: utf-8 -*-
import random
class Baraja(object):
def __init__(self):
self.palos = ["Espadas", "Corazones", "Tréboles", "Diamantes"]
self.rangos = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "As"]
self.maso = []
for palo in self.palos:
... |
import math
# Qt
from PyQt5.QtCore import Qt
from PyQt5.QtCore import QLine
from PyQt5.QtCore import QPoint
from PyQt5.QtGui import QPolygon
class Arrow:
def __init__(self, points, color=Qt.black, fill=True, tipLength=5, orientation="right"):
"""
Creates an Arrow object
following given path (point list)
"""... |
from unittest import TestCase
from app import app
from models import User, db, Post, Tag, PostTag
# Perform tests on a Test database
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///blogly_test'
app.config['SQLALCHEMY_ECHO'] = False
# Real Errors
app.config['TESTING'] = True
db.drop_all()
db.create_all()
clas... |
__author__ = 'Justin'
import networkx as nx
from random import choice
from geopy.distance import vincenty as latlondist
def randomnodes(G,distancelimit,print_=False):
lons = nx.get_node_attributes(G,'lon')
lats = nx.get_node_attributes(G,'lat')
nodesdist = 0
connected = False
... |
print("*"*30,"捕鱼达人","*"*30)
username = input("输入参与者用户名:")
password = input("输入密码:")
print("%s 请充值才能加入游戏!" % username)
coins = int(input("您充值的金额为:"))
print("%s 元充值成功!当前游戏币是:%d" % (username,coins))
|
from classes.DBOperations import *
import unidecode
import requests
from collections import OrderedDict
postalcodedict = {}
class weather:
def __init__(self, dbOperations=None):
self.dbOperations = dbOperations
# simple function that returns a key for a given value from a dict
def get_key(self, ... |
import gc
gc.enable()
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
class FeatureSelection(object):
def __init__(self, feature_score_name):
self.feature_score_name = feature_score_name
pass
def load_data(self):
pass
def get_feature_score(self):
pass
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/12/3 下午7:13
# @Author : zs
# @Site :
# @File : test.py
# @Software: PyCharm
import os
import shutil
def main(list):
list.sort()
a = max(int(list[0]), int(list[1]))
b = min(int(list[0]), int(list[1]))
for i in range(2, len(list)):
i... |
# Generated by Django 2.1.2 on 2018-12-11 05:03
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ann', '0015_datasetdetailreview_masa_studi'),
]
operations = [
migrations.RenameField(
model_name='hiddenlayer',
old_name='n... |
#--*-- coding:utf-8 --*--
class Computer:
def __init__(self,name):
self.name=name
def __str__(self):
return self.name
def execute(self):
return 'execute a program'
class Synthesizer:
def __init__(self,name):
self.name=name
def __str__(self):
return self.na... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.