text stringlengths 38 1.54M |
|---|
import glob
import pandas as pd
import numpy as np
from functools import partial
from sklearn.metrics import roc_auc_score
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from xgboost import XGBClassifier
def run_training(pred_df, fold):
#pdf = pred_df.copy(deep... |
# -*- coding: utf-8 -*-
"""
Profile: http://hl7.org/fhir/StructureDefinition/MedicinalProductPackaged
Release: R4
Version: 4.0.1
Build ID: 9346c8cc45
Last updated: 2019-11-01T09:29:23.356+11:00
"""
from pydantic.validators import bytes_validator # noqa: F401
from .. import fhirtypes # noqa: F401
from .. import medic... |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
import os
from setuptools import setup, find_packages
# pylint: disable=redefined-builtin
here = os.path.abspath(os.path.dirname(__file__)) # pylint: disable=invalid-name
wit... |
import numpy as np
import pandas as pd
from sklearn import datasets
boston = datasets.load_boston()
print(boston.data)
x = boston.data
t = boston.target
print(x.shape)
print(t.shape)
#データセットを分割する関数
from sklearn.model_selection import train_test_split
x_train,x_test,t_train,t_test = train_test_split(x,t,test_size=0.... |
#!/usr/bin/python3
#from collections import Counter
#import re
#import os
import time
from collections import defaultdict
#from collections import deque
''' ####### '''
date = 10
dev = 0 # extra prints
part = 1 # 1,2, or 3 for both
samp = 1 # 0 or 1
''' ####### '''
def day(te):
d = defaultdict(... |
import pandas as pd
import joblib
from fastapi import FastAPI
import uvicorn
import json
## PRELOADED COMPONENTS
# ------------------------------------------------------------------------------
# Instantiating the Flask application
application = FastAPI(title = 'Red Wine FastAPI Model',
descrip... |
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
packs = []
need_update = 0
incident = demisto.incidents()[0]
accountName = incident.get('account')
accountName = f"acc_{accountName}/" if accountName != "" else ""
config_json = demisto.executeCommand("demisto-api-get",
... |
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
import ipaddress
import re
class ShouldBe(Exception):
def __init__(self, what):
self.what = what
class Email:
def __call__(self, value):
try:
validate_email(value)
except ... |
import pandas as pd
from grammarbot import GrammarBotClient
import time
import language_check
import proselint
PUNCTUATION = [',', '.', '?', '!', '\'', '\"', '(', ':', ';']
COLUMNS = ['essay_id', 'essay_set', 'num_errors', 'essay_length', 'num_words','avg_word_len', 'num_punc', 'actual']
from spellchecker import Spell... |
#importing packages
import glob,os
import pandas as pd
import re
import csv
#setting working directory
os.chdir("C:/Users/Jill/OneDrive - UC Davis/Documents/collaboration/dairy sequencing/Metagenomics/PyTest")
#saving new header to be used later in rewriting file
new_header = ("target_name ResfamID query_name E-value s... |
#----------- 1 RegEx -----------
# a)
# [csm]at[\s,."?!)]
# \b[csm]at\b
# b)
# (\b[\w]+\b)\s\1\b
# c)
# [\d]+[\d,\.]+(\s(kr|DKK))?
#----------- 2. Tokenization -----------
new_regex = r'[\w\-]+(\'\w+)*|[.?,;:!]'
# 1) Improving tokenization
# Q: The tokenizer clearly misses out parts of the text. Which?
# A: pa... |
somme_multiple_3 = 0
for i in range(1000):
if i % 3 == 0:
somme_multiple_3 += i
print(f"somme_multiple_3 < 1000 = {somme_multiple_3}")
somme_multiple_5 = 0
for i in range(1000):
if i % 5 == 0:
somme_multiple_5 += i
print(f"somme_multiple_5 < 1000 = {somme_multiple_5}")
|
from typing import Optional, Tuple, List, Deque, Mapping, Any
import civ
import terrain
import sprite
import collections
class Spot():
def __init__(self, tile: Tuple[int, int], steps: int, prev: Optional['Spot']) -> None:
self.tile = tile
self.steps = steps
self.prev = prev
self.enemy = False
class Targeter(... |
from commons import rake
# EXAMPLE ONE - SIMPLE
stoppath = "../../rake/SmartStoplist.txt"
# 1. initialize RAKE by providing a path to a stopwords file
rake_object = rake.Rake(stoppath)
# 2. run on RAKE on a given text
text = """Two things might be happening.
IE is masking an HTTP error response with its friendly er... |
##### 解けた #####
A=input()
B=input()
if len(A)>len(B): # もしAの方が長い場合
print(A)
else: # もしBの方が長い場合
print(B) |
class Solution:
def repeatedNTimes(self, A: List[int]) -> int:
for i in range(len(A)):
if A[i] in A[i+1:]:
return A[i]
return None
|
from django.conf.urls import url
from django.views.generic import TemplateView
from .import views
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
url(r'^api/cpu/main$', views.main),
url(r'^$', TemplateView.as_view(template_name = 'monitoring_system/main.html')),
]
urlpatterns = f... |
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello worl!!#@@d !! ") |
"""
sk_linr_learn_predict.py
This script should learn from features in feat.csv and calculate predictions.
Demo:
python sk_linr_learn_predict.py
"""
import os
import pdb
import pandas as pd
import numpy as np
from sklearn import linear_model
# I should prep for a new csv file
fn_s = 'sk_linr_predictions.csv'
os.sy... |
# Generated by Django 2.2.2 on 2020-05-12 00:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('inventory', '0008_auto_20200508_0119'),
]
operations = [
migrations.AddField(
model_name='resource',
name='od_releas... |
#!/usr/bin/env python
# import libraries
import pandas as pd
from irisreader import iris_data_cube, sji_cube, raster_cube
def get_lines( file_object ):
"""
Returns the available lines in a raster or SJI file. Both filenames and
open iris_data_cube objects are accepted.
Parameters
----------
... |
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms.
#
# ## ### ##... |
#G2G
# get package names from parsethml.py return value or glob vars
import os
BASE_FTP = 'https://www.gnupg.org'
LOCAL_DIR = './downloads'
REQD_FTP_ROUTES = None
def get_rec_files(base=BASE_FTP, localdir=LOCAL_DIR, recs=REQD_FTP_ROUTES):
if not recs:
print 'Must specify url of files to download'
... |
# -*- coding: utf-8 -*-
'''
@author: Adrian Mora Perela
@author: Sergio Grande Murillo
'''
import csv
import codecs
from pylab import pcolor, show, colorbar, xticks, yticks
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn import ... |
import random
class Race(object):
registry = {}
@classmethod
def register(cls, new):
cls.registry[new.__name__.lower()] = new
@classmethod
def random_race(cls):
return random.choice(cls.registry.keys())
@property
def name(self):
return self.__class__.__name__.lower()
allowed_professions = set()
def _... |
# Generated by Django 3.0.6 on 2020-06-16 06:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('to_do_app', '0002_to_do_usr_id'),
]
operations = [
migrations.AlterField(
model_name='to_do',
name='usr_id',
... |
#!/usr/bin/env python
# coding=utf-8
'''
@author marlon
implementation of serialized/deserialized by the API
'''
from rest_framework import serializers
from .models import BookingStatus
class ApiSerializer(serializers.ModelSerializer):
class Meta:
model = BookingStatus
fields = ('MASTERNO', 'JOBNU... |
#!/usr/bin/env python
# encoding:UTF-8
# @Author : SUN FEIFEI
import time
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from app.student.login.object_page.home_page import HomePage
from app.stude... |
from scipy.sparse import csc_matrix
from scipy.sparse.linalg import svds
from surprise.prediction_algorithms import knns
from surprise.similarities import cosine, msd, pearson
from surprise import accuracy
from sklearn.model_selection import train_test_split
from surprise import Reader, Dataset
from surprise.model_sele... |
#! C:/python27
# To change this template, choose Tools | Templates
# and open the template in the editor.
__author__="kluitel"
__date__ ="$Sep 23, 2013 10:30:14 PM$"
if __name__ == "__main__":
print "Hello World";
'''
function vs method
funtion -> standalone fnction
method -> inside a class
oop has a design pa... |
import google.cloud.logging
import app.config.app as app_config
import logging
level = logging.INFO
def setup_logging():
if app_config.is_prod:
client = google.cloud.logging.Client()
client.get_default_handler()
client.setup_logging(log_level=level)
else:
logging.root.setLevel... |
# [ ] review and run example
cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City", "São Paulo", "Hyderabad"]
for city in cities:
print(city)
# [ ] review and run example
sales = [6, 8, 9, 11, 12, 17, 19, 20, 22]
total = 0
for sale in sales:
total += sale
print("total sales:", total... |
from openapi_core.schema.exceptions import OpenAPIMappingError
class OpenAPIOperationError(OpenAPIMappingError):
pass
class InvalidOperation(OpenAPIOperationError):
pass
|
import random
def setmultiply(sets,iteration):
if iteration==0:
return sets[0]
else:
for item in range(0,len(sets[0])):
sets[0][item]=sets[0][item]*sets[iteration][item]
setmultiply(sets,iteration-1)
return sets[0]
def setadd(sets):
pass
def setsubtract(self):
... |
#!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License");... |
class Dog:
def __init__(self, name, breed, energy):
self.name = name
self.breed = breed
self.energy = energy
my_dog = Dog("Chewbarka", "NewBreed", 3)
print(my_dog.name) |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 06 13:05:39 2018
@author: Ledicia Diaz
"""
import numpy as np
a = 0.; b = np.pi/2.
n = 1 # Número de subintervalos
h = (b-a) # Ancho de cada subintervalo
# Funcion a integrar
def f(x):
y=(x**2+3*x+1-x)*np.cos(x)
return y
x=np.linspac... |
import csv
import re
import traceback
year = 2006
month = 1
for year in range(2006,2013):
for month in range(1,13):
with open("./headlines_csv/headline" + str(year) + str(month) + ".csv", "wb") as csv_art, open("HistoricalPrices.csv", "rb") as djia:
values = list(csv.reader(djia, delimiter=',', quotechar='|'))
... |
# put the email password here and then place this file in your .gitignore file
EMAIL_PASSWORD = ''
|
"""
wrapper to perform a two condition DE testing of RNA-seq data using
the DSS package. requires in_file to be a table of counts and conds to
be a vector describing which condition each column of counts refers to
"""
import rpy2.robjects as robjects
import rpy2.robjects.vectors as vectors
from bcbio.utils import safe_... |
from typing import cast
from pynng import Req0
from labby.server import ServerRequest, TNonOptionalResponse
from labby.server.requests.device_info import DeviceInfoRequest, DeviceInfoResponse
from labby.server.requests.experiment_status import (
ExperimentStatusRequest,
ExperimentStatusResponse,
)
from labby.... |
from pymongo import MongoClient
client = MongoClient('mongodb://qaninja:qaninja123@ds035664.mlab.com:35664/spotdb?retryWrites=true&w=majority')
db = client['spotdb']
def remove_spot_by_company(company):
spots = db['spots']
spots.delete_many({'company': company})
|
from django.db import models
from django.contrib.auth.models import User
import datetime
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post_owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_owner', null=True, blank=True)
image = models.ImageF... |
"""Solution to task 6 from lesson 4."""
import sys
import datetime
import shutil
import os
def main():
"""Script entry point."""
file_name = sys.argv[1] if len(sys.argv) > 1 else ''
if file_name:
# copy file
copy = file_name + "~"
shutil.move(file_name, copy)
destination =... |
# 计算0~100之间所有偶数的累加和的结果
# 开发步骤:
# 1.编写循环 确认 要计算的数字
# 2.添加 结果 变量,在循环体内部,处理计算结果
result = 0
i = 0
while i <= 100:
# 1.判断偶数 i % 2 == 0:
# 判断奇数 i % 2 != 0:
if i % 2 == 0:
# print(i)
# 2.当i是偶数时,才进行累加
result += i
# 3.计数器累加,和while是配套使用的
i += 1
print("0~100之间的偶数和为:%d" % result) #--->25... |
'''定时器触发多线程'''
import schedule
import time
import threading
def job():
print('this is job')
time.sleep(2)
print('the job is done')
def job1():
print('this is job1')
time.sleep(1)
print('the job1 is done')
def run_threading(func):
t=threading.Thread(target=func,)
t.start()... |
def countOddNums(data):
count = 0 # total number of odd numbers
# iter thru strings
for num in data:
# converting current string value to int value
num = int(num)
# checking int value is odd
if num %2!=0:
count += 1.0
return count;
Def PercentOdd(numOfOdds, totalCount):
# find the percent... |
"""
将所有预测的路径变为查询语句,获取预测的答案
得到的文件格式
q【问题id】:【问题】
【预测分数1】---【预测路径1】---【问题id】---【问题】---【答案1】
【预测分数2】---【预测路径2】---【问题id】---【问题】---【答案2】
例子
q2:"光武中兴"说的是哪位皇帝?
0.9999997---<建武中兴>|||<皇帝>|||?x---2---"光武中兴"说的是哪位皇帝?---'<后醍醐天皇>'
"""
from py2neo import Graph
import numpy as np
def get_answer(predict_result_path, ans_path, gr... |
# 给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
#
# candidates 中的每个数字在每个组合中只能使用一次。
#
# 说明:
#
# 所有数字(包括目标数)都是正整数。
# 解集不能包含重复的组合。
# 示例 1:
#
# 输入: candidates = [10,1,2,7,6,1,5], target = 8,
# 所求解集为:
# [
# [1, 7],
# [1, 2, 5],
# [2, 6],
# [1, 1, 6]
# ]
# 示例 2:
#
# 输入: ca... |
"""
As substantial work has been placed—a few months of development—to make this fully featured music bot free for public use, please refrain from discrediting author or falsely claiming this open source work.
BSD 3-Clause License
Copyright (c) 2021, taku#3343 (Discord)
All rights reserved.
Redistribution and use in... |
import grpc
from functools import wraps
class WalletEncryptedError(Exception):
def __init__(self, message=None):
message = message or 'Wallet is encrypted. Please unlock or set ' \
'password if this is the first time starting lnd. '
super().__init__(message)
def han... |
# Generated by Django 2.0.5 on 2018-05-16 04:53
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('JuHPLC', '0015_auto_20180516_0443'),
('JuHPLC', '0015_auto_20180509_0740'),
]
operations = [
]
|
from django.db import models
# Create your models here.
class Location(models.Model):
name = models.CharField(max_length=50)
order = models.DecimalField(default=1000, max_digits=8, decimal_places=3,
null=False, blank=False)
def natural_key(self):
return (self.name)
... |
# encoding: utf-8
from __future__ import absolute_import, unicode_literals
import cv2
import torch
import numpy as np
import torch.backends.cudnn as cudnn
from torchvision import transforms
from .base import Base
class FaceAlignment(Base):
def __init__(self, *args, **kwargs):
super().__init__(*args, **... |
'''
Using the API from the API section, write a program that makes a request to
get all of the users and all of their tasks.
Create tables in a new local database to model this data.
Think about what tables are required to model this data. Do you need two tables? Three?
Persist the data returned from the API to your... |
import unittest
from answer.increasing_order_search_tree import Solution, TreeNode
class TestSolution(unittest.TestCase):
def setUp(self):
self.node = [
TreeNode(5, TreeNode(3, TreeNode(2, TreeNode(1), None), TreeNode(4)), TreeNode(6, None, TreeNode(8, TreeNode(7), TreeNode(9)))),
... |
## <--------------- Ans (6) ------------------------>
# def subsetSum(A, n, k):
# if k == 0:
# return True
# if n < 0 or k < 0:
# return False
# include = subsetSum(A, n - 1, k - A[n])
# exclude = subsetSum(A, n - 1, k)
# return include or exclude
# def Equ... |
import os
class Environment:
'''this class is used to initilize variable which will be required to run the test for specific env'''
# global new_user
# new_user = 'new_vagrant'
def __init__(self):
self.maintainer_name = 'sdp.uturn@gmail.com'
self.project_name = 'blackbird'
... |
# Pysäytyskohta
# use some random numbers to observe in debugger
from random import *
# declare couple of int variables
# observe the number2 in debugger to see what number is assigned to it
number1 = 10
number2 = randint(0, 100)
# print the values of our variables
print("value of number1 is ", number1)
print("value... |
# Copyright 2020 Xilinx Inc.
#
# 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 applicable law or agreed to in writin... |
# -*- coding: utf-8 -*-
from django import forms
class AddThemeForm(forms.Form):
title = forms.CharField(max_length=250)
description = forms.CharField(max_length=500)
|
"""6-1
使用一个字典存储一个人的姓、名、年龄、居住城市,最后都打印出来。
"""
person_information = {
"First_name": "Lock",
"Last_name": "Bro",
"age": "20",
"livingCity": "Tianjin",
}
print(person_information["First_name"])
print(person_information["Last_name"])
print(person_information["age"])
print(person_information["livingCity"])
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from builtins import range
import unittest
from datetime import time as datetime_time
from mock import patch, Mock
from bpolicy import MINUTE, HOUR
from bpolicy import FakeStore, PolicyError, ClockPolicy
from bpolicy import GenerationedPolicyFactory, Rat... |
import json
from oandapyV20 import API
import oandapyV20.endpoints.trades as trades
api = API(access_token="f7e9e4ce6d3053fd67480df1fb51e665-a52e75b6119ff67521f77ebfde0aafe0")
accountID = "101-004-9226142-001"
tradeID = "119"
cfg = {"units": -1}
r = trades.TradeClose(accountID, tradeID=tradeID)
# show the endpoint as ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 18 00:16:46 2018
@author: maximoskaliakatsos-papakostas
"""
import numpy as np
import copy
import computeDIC as dic
import os
cwd = os.getcwd()
import sys
sys.path.insert(0, cwd + '/CM_auxiliary')
import CM_Misc_Aux_functions as maf
... |
#!/usr/bin/env python3
# distance to each city from A = infinity
# (distance to A = 0)
# iterate through cities, if distance < previous smallest distance thereto replace it
# repeat for city with shortest distance from there
# get distance by adding current distance to distance from current city to next
# once checked... |
# chardet's setup.py
from distutils.core import setup
import setuptools
setup(
name = "inpho",
packages = ["inpho", "inpho.model"],
version = "0.1",
description = "Indiana Philosophy Ontology Project data processing tools",
author = "The Indiana Philosophy Ontology (InPhO) Project",
author_email... |
#PS5 Question 2a code
import random
import matplotlib.pyplot as plt
import csv
def parse():
fo = open("app_c.csv", 'r')
list_of_names = []
for line in fo:
list_of_names.append(line.strip().split(',')[0])
fo.close()
return list_of_names
def pickHalf(list_of_names):
half_list = len(list_of_names)//2
# print(l... |
from . import generic
arch = 'MIPS32'
class R_MIPS_32(generic.GenericAbsoluteAddendReloc):
pass
class R_MIPS_REL32(generic.GenericRelativeReloc):
pass
class R_MIPS_JUMP_SLOT(generic.GenericAbsoluteReloc):
pass
class R_MIPS_GLOB_DAT(generic.GenericAbsoluteReloc):
pass
class R_MIPS_TLS_DTPMOD32(gene... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 08 22:40:45 2018
@author: Wu Jingwei
"""
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
if len(nums) == 1:
return num... |
import unittest
from gedcom_parser import parse
class kids5onsameday(unittest.TestCase):
def test_fail_greater5kids(self):
people, families, errors, lists = parse('6kidsonsameday.ged')
self.assertEqual(len(errors), 6)
if __name__ == '__main__':
unittest.main()
|
""" Example of a library to be used in the Jupyter Notebook """
from fmpy import *
def simulate_heater(TAmb=293.15, stop_time=100):
""" Helper function with a fixed set of parameters """
result = simulate_fmu('Heater.fmu', stop_time=stop_time, start_values={'TAmb': TAmb})
plot_result(result)
|
import unittest
import awspice
class ModuleFinderTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
print("\nStarting unit tests of base service module")
def test_get_client_vars(self):
aws = awspice.connect('eu-west-2', profile='test')
client_vars = aws.service.ec2.get... |
class Smiles:
def __init__(self):
self.add= "➕"
self.change = "✏"
self.delete = "🚫"
self.back = "⬅"
self.next = "➡"
self.done = "✔"
self.kvartirant = "👥"
self.swap = "🔁"
self.copy = "📄"
self.notification = "⏰"
self.money = "... |
import bpy
from bpy.types import NodeTree, Node, NodeSocket
import nodeitems_utils
from nodeitems_utils import NodeCategory, NodeItem
from bpy.props import EnumProperty, BoolProperty, StringProperty, FloatProperty
import custom_sockets
from . import building_NODETREE
from .building_NODETREE import *
from utils impo... |
"""
This is just a simple game of a coin flip. I want the program to generate a coin flip and ask the player to make a call for heads or tails. Then the program will let the player know if they were right or not.
"""
import random
def coinflip():
"""
Get a coinflip by choosing randomly between 0 and 1 and re... |
from django.urls import path
from . import views
urlpatterns = [
#/mysearch/
path('', views.index, name='index'),
#/mysearch/search_result
path('search_result/', views.search_result, name='search_result'),
path('search_result/page_selection/', views.page_selection, name='page_selection'),
path('s... |
__version__ = '0.3.0'
__author__ = 'czh&xcb'
from .downtool import down
from .api import DtServerApi
|
import numpy as np
import pickle
import pandas as pd
import seaborn as sns
from scipy.stats import pearsonr
import matplotlib.pyplot as plt
import json
def init_plotting():
sns.set_style("darkgrid", {"axes.facecolor": "0.9"})
# plt.rcParams['figure.figsize'] = (15, 8)
plt.rcParams['figure.figsize'] = (7.25, 4)
... |
import os
from ..openapi import tator_openapi
def get_api(host='https://www.tatorapp.com', token=os.getenv('TATOR_TOKEN')):
""" Retrieves a :class:`tator.api` instance using the given host and token.
:param host: URL of host. Default is https://www.tatorapp.com.
:param token: API token.
:returns: :cla... |
#!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "Li... |
# -*-coding:utf-8-*-
from train_cnn import create_model
from data_help import VegDB
import pandas as pd
from tensorflow import keras
vocab_path = 'model/vocab'
vegdb = VegDB(vocab_path)
maxlen = 500
vocab_size = vegdb.vocab_size
df = pd.read_csv('article/sample.csv', sep='\t')
datas = [i[:500] for i in vegdb.get_pred... |
from unittest import TestCase
from LaTeXTools.latextools_utils.selectors import (
AstNode as Node, AstLeaf as Leaf, build_ast
)
class BuildAstTest(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_empty(self):
selector = ""
ast = Leaf("")
se... |
#!/usr/bin/env python
# Author: pabloheralm@gmail.com
# @pablololo12
import sys
import getopt
import numpy as np
import cv2
threshold = 140.0
average = 0
kmeans = 0
def add(colors, color):
global threshold
global average
added = 0
if colors is None:
colors = []
colors.append(color)
return colors
... |
import numpy as np
import gurobipy as gp
from gurobipy import GRB
from verification.interval_number import IntervalNumber, interval_max, inf, sup
epsilon_Q = 0.01
epsilon_G = 0.001
# review 这个可以直接拿来用,用来判断第一个条件
def milp_output_area(x_min, x_max, W, b):
ok = 0
weight_size = len(W)
input_size = len(W[0])
... |
import os
import unittest
from cris.config import TestConfig
from cris import create_app
from cris.extensions import db
#database objects currently being tested:
from cris.courses.model import Course
from cris.reviews.model import Review
from cris.users.model import User
from cris.posts.model import Post
from cris.ins... |
#
# MLDB-1361_join_on_subselect.py
# Francois Maillet, 2016-02-04
# This file is part of MLDB. Copyright 2016 mldb.ai inc. All rights reserved.
#
import unittest
import json
from mldb import mldb, MldbUnitTest, ResponseException
class SampleTest(MldbUnitTest):
@classmethod
def setUpClass(self):
# cr... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 29 00:27:01 2020
@author: Lenovo
"""
import cv2
import numpy as np
import sklearn
import os
import skimage
from sklearn.decomposition import PCA
def sobel(gray_image):
def gradNorm(grad):
return (grad - np.min(grad)) / (np.max(grad) - np.mi... |
#! /usr/bin/python
import sys
import math
class IcfUtil(object):
""" This class maintains the global state
information and provides some helpful
functions
"""
def __init__(self, no_procs):
self.no_procs = no_procs
self.header_row = []
def local_to_global_index(self, proc_id... |
import json
import pytest
import requests
import datahub.metadata.schema_classes as models
from datahub.emitter.mcp import MetadataChangeProposalWrapper
from datahub.emitter.rest_emitter import DatahubRestEmitter
MOCK_GMS_ENDPOINT = "http://fakegmshost:8080"
basicAuditStamp = models.AuditStampClass(
time=161898... |
import sublime, sublime_plugin
def expand(txt, open, close, indent=0):
output, chars_parsed = [], 0
while 1:
open_index = txt.find(open, chars_parsed)
close_index = txt.find(close, chars_parsed)
if open_index >= 0 and open_index < close_index:
# increase indent
output.append(txt[chars_parsed:ope... |
import sys, os
import numpy as np
import argparse
import tensorflow as tf
from PIL import Image
from tqdm import tqdm
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value... |
from flask_restplus import fields
from api.restplus import api
'''json format data frame'''
json_data = api.model('json args', {
'user_addr':fields.String(required=True, default="shenzhen", description='user address'),
'user_sex':fields.String(required=True, default="male", description='user sex')
})
|
# Generated by Django 3.2.5 on 2021-07-28 07:08
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('common', '0003_alter_comment_nail'),
]
operations = [
migrations.RenameField(
model_name='comment',
old_name='nail',
... |
def checkValid(str):
freq = {}
for x in str:
if x in freq:
freq[x] += 1
else:
freq[x] = 1
valtotal = sum(freq.values())
keytotal = len(freq.keys())
numtocheck = valtotal % keytotal
if numtocheck > 1:
return False
else:
if max(freq.valu... |
import math
import numpy as np
from gym_derk import ObservationKeys
class Network:
def __init__(self, weights=None, biases=None):
self.network_outputs = 13
if weights is None:
weights_shape = (self.network_outputs, len(ObservationKeys))
self.weights = np.random.normal(size=... |
from collections import defaultdict
import csv
from datetime import datetime, timedelta, time
import logging
import cStringIO
import pytz
from scipy import signal
import numpy as np
from scipy import stats
from sqlalchemy.orm import relationship
import rpy2.robjects as ro
from rpy2.robjects import numpy2ri
from webapp... |
# Bill Gosper's pure-period p1100 double MWSS gun, circa 1984.
import golly as g
from glife import *
g.new("P1100 gun")
g.setalgo("HashLife")
g.setrule("B3/S23")
# update status bar now so we don't see different colors when
# g.show is called
g.update()
glider = pattern("bo$bbo$3o!")
block = pattern("oo$oo!")
eater... |
import logging
from pathlib import Path
import numpy as np
import pandas as pd
from scipy.spatial.distance import cosine
from embedding.scorers.abstract_scorer import AbstractScorer
class CosineScorer(AbstractScorer):
def __init__(self):
CosineScorer.__name__ = "CosineScorer"
@staticmethod
def ... |
import re
from collections import defaultdict as ddict
def get_nodes_only(p):
x = {}
for sub in p:
for key, val in sub.items():
if key != "root":
x[key] = val
return x
def tagged(sentence, sup=False):
if sup:
parse = sentence["input_tags"]
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.