text stringlengths 8 6.05M |
|---|
# Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
# Copyright [2016-2023] EMBL-European Bioinformatics Institute
#
# 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 ... |
import time
# use this program to test sending processes to the background
time.sleep(5)
print("done!")
|
import os
import matplotlib.pyplot as plt
import numpy as np
from MiscPyUtilities.pipeMAT import LoadMatFile2NumpyArray
from datetime import datetime
def PlotSaveHollowTri(CroSecFolder):
"""
plot cross section in a CroSecXX folder
@param CroSecFolder: str, path to a CroSecXX folder
@return:
"""
... |
#import sys
#input = sys.stdin.readline
def main():
N = int( input())
ans = 0
d = list( map( int, input().split()))
for i in range(N):
for j in range(N):
if i == j:
continue
ans += d[i]*d[j]
print(ans//2)
if __name__ == '__main__':
main()
|
from new2 import Father
class Son(Father):
pass
s1=Son()
s1.display()
|
import face_recognition
from cv2 import cv2
import numpy as np
import glob
import os
import sys
import time
contador_circulo_click = 0
color_circulo_click = ''
# Función que
ix,iy = -1,-1
def save_face_click(event,x,y,flags,param):
global ix,iy,contador_circulo_click,color_circulo_click, known_face_encodings, ... |
#stab at connect four
from os.path import realpath, join, dirname
import logging
import random
import itertools
log_file = realpath(join(dirname(__file__),"connect4.log"))
logging.basicConfig(filename=log_file, filemode="w+", level=logging.DEBUG)
log = logging.getLogger(__name__)
... |
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
hidden_dim = 32
act_dim = 3
model = keras.Sequential()
model.add(keras.Input(shape=(3,)))
model.add(layers.Dense(hidden_dim, activation="relu"))
model.add(layers.Dense(hidden_dim, activation="relu"))
model.add(layers.Dense(hidden_... |
# Machine Learning - Data Distribution
# Distribuição de dados
# No início deste tutorial trabalhamos com quantidades muito pequenas de dados em nossos exemplos,
# apenas para entender os diferentes conceitos.
# No mundo real, os conjuntos de dados são muito maiores,
# mas pode ser difícil coletar dados do mundo r... |
import csv
import sys
class Room:
def __init__(self, row):
self.data = self._trim(row)
def name(self):
return self.data[0]
def description(self):
return self.data[1]
def has_lock(self):
return '|' in self.data[2] and self.data[2].startswith('lock')
def has_item(... |
from rest_framework.routers import DefaultRouter
from .views import UserRegistrationView ,OrganisationUserLoginView
from django.urls import path
router = DefaultRouter(trailing_slash=False)
router.register(r'register', UserRegistrationView, basename='user_register')
router.register(r'login', OrganisationUserLoginView,... |
import datetime
MILISECODS = 1e3
# JavaScript has timestamp in miliseconds
# you have to divide by 1e3 = 1000
timestamp = 1331856000000
datetime.datetime.fromtimestamp(timestamp / MILISECODS)
# datetime.datetime(2012, 3, 16, 1, 0)
timestamp = 1331856000000
datetime.datetime.fromtimestamp(timestamp)
|
import u12
from time import sleep
from time import time
import datetime
import csv
import numpy as np
import sys
#path has to be adjusted unique to each machine
#change to make look in current directory?
sys.path.insert(0, '/home/albert/Documents/Albert Work/Scripts')
from thermocouple import temperature_read
from pres... |
#!/usr/bin/env python
from __future__ import with_statement
import sys
from setuptools import setup, find_packages
long_description = ""
setup(
name='ifilter',
version="0.2",
description='ifilter is a command line tool for interactive filtering of pipes.',
long_description=long_description,
autho... |
#!/usr/bin/env python3
"""
TODO:
+ Detectar que no existe en el path
+ Generar uno vacio
- Test default path on windows
- Test default path on mac
- Getting a missing profile
- Any attribute is null
"""
import os
from .namespace import namespace
from .consolemsg import error
# Kludge in order to use FileNotFoundErr... |
al1 = {'nome':'Isabela','nota':4}
al2 = {'nome':'Ricardo','nota':10}
al3 = {'nome':'Fernanda','nota':9.5}
lista = [al1, al2, al3]
for elemento in lista:
print(elemento['nome'],elemento['nota'])
|
#!/usr/local/bin/python3
class Board:
def __init__(self):
self.board = [[Space() for x in range(3)] for y in range(3)]
def get_space(self, x, y):
return self.board[x][y]
def fill_board(self, x ,y, player):
return self.board[x][y].set_space(player)
def print_board(self):
... |
#!/usr/bin/env python
"""
Pose server that uses a separate server to access journal data
that way journal data does not need to be reloaded every time server restarts
does make startup more complex:
separate tab:
cd /c/moments/moments
python journal_server.py /c/journal
python application-split.py
"""
from __future_... |
from .accent import Accent
class E(Accent):
REPLACEMENTS = {
r"[a-z]": "e",
}
|
import pickle
import os.path
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
from alexnet import AlexNet
import numpy as np
# Load traffic signs data.
with open('train.p', mode='rb') as f:
dataset = pickle.load(f)
nb_classes = len(np.unique(dataset['l... |
# Generated by Django 3.2.5 on 2021-08-30 05:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_order', '0009_auto_20210829_1825'),
]
operations = [
migrations.AddField(
model_name='orderstatus',
name='slug',... |
N = int( input())
F = [0]*(N+1)
Q = 10**9 + 7
for i in range(1,N+1):
n = i
for j in range(2, int( N**(1/2))+1):
while n%j == 0:
F[j] += 1
n //= j
if n != 1:
F[n] += 1
ans = 1
for i in range(N+1):
ans *= F[i]+1
ans %= Q
print(ans)
|
from pybrain.supervised.trainers import BackpropTrainer
from pybrain.datasets import SupervisedDataSet
from pybrain.structure import FeedForwardNetwork, LinearLayer, SigmoidLayer,FullConnection
import fitsio
import numpy as np
import time
import pickle
CACHED = False
# constants to change
MAX_EPOCHS = 100
NUM_DATA = ... |
def f1():
print(1)
def f1():
print(2)
f1() |
'''
Created on Jun 12, 2016
@author: Dayo
'''
import django_filters
from .models import ProcessedMessages
class ProcessedMessagesFilter(django_filters.FilterSet):
MSG_TYPE = (
('ADVANCED',' Advanced'),
('STANDARD',' Standard')
)
message_type = d... |
import copy
import os
import yaml
from autumn.projects.covid_19.mixing_optimisation.constants import OPTI_REGIONS
from autumn.projects.covid_19.mixing_optimisation.mixing_opti import (
DURATIONS,
MODES,
OBJECTIVES,
objective_function,
run_root_model,
)
from autumn.projects.covid_19.mixing_optimisa... |
from rest_framework import status
from rest_framework.response import Response
# Create your views here.
def HandleResponse(data,message,success = True,err = 'no err',resp_status = status.HTTP_200_OK):
"""
HandleResponse , makes easier to send Response
Equalent to Response({
'success':success,
... |
# This version outputs how many times the mouse was clicked
from turtle import Screen, Turtle
from random import randint
from tkinter import messagebox, Tk
window = Tk()
window.withdraw()
# Counter that increases
click_counter = 0
def chase_move(x_cor, y_cor): # _cor is where the mouse wants to go
global clic... |
import base64
import webapp2
from google.appengine.api import urlfetch
class FetchURL(webapp2.RequestHandler):
def get(self):
encoded_url = str(self.request.get('url'))
url = base64.urlsafe_b64decode(encoded_url)
validate = self.request.get('validate').lower() == 'true'
urlfetch.fetch(url, validate... |
# coding:utf-8
class Queue(object):
"""定义一个队列类"""
def __init__(self):
self.__queue = []
def len(self):
return len(self.__queue)
def add(self, item):
self.__queue.append(item)
def pop(self):
if not self.__queue:
return None
else:
retu... |
"""
smorest_sfs.modules.menus.schemas
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
菜单模块的Schemas
"""
from marshmallow import Schema, fields
from smorest_sfs.extensions import ma
from smorest_sfs.extensions.marshal import BaseMsgSchema, SQLAlchemyAutoSchema
from . import models
class MenuSchema(SQLAlchemyA... |
import os
import shutil
from shorthand.types import DirectoryPath, Subdir, InternalAbsoluteFilePath, InternalAbsolutePath
from shorthand.utils.paths import get_full_path
def _create_file(notes_directory: DirectoryPath,
file_path: InternalAbsoluteFilePath
) -> None:
'''Create a n... |
class Node:
def __init__(self, item, left, right):
self.item = item
self.left = left
self.right = right
def preorder(node): # 전위 순회
print(node.item, end='')
if node.left != '.':
preorder(tree[node.left])
if node.right != '.':
preorder(tree[node.righ... |
class DefaultList(list):
def __init__(self, fx):
self._fx = fx
def _fill(self, index):
while len(self) <= index:
self.append(self._fx())
def __setitem__(self, index, value):
self._fill(index)
list.__setitem__(self, index, value)
def __getitem_... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2018-01-24 06:51
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('nova', '0073_servicehistory_servicestep_servicetest'),
]
operations = [
migrations.... |
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import seaborn as sb
import numpy as np
def plot_correlation_matrix(data,data_type):
from sklearn.preprocessing import scale
import seaborn as sb
if data_type== "labels":
data_to_predict=scale(data,axis=0) #Rescale each columns
c... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 19 12:01:01 2020
@author: Chris Harris
To help you clean up your home directory
"""
import tkinter as tk
from tkinter import ttk
import os
import shutil
import tkinter.font as font
class Clean_Up(tk.Tk):
def __init__(self):
super().__... |
"""
Abstract Factory:
The Abstract Factory defines a Factory Method per product. Each Factory Method encapsulates the new operator
and the concrete, platform-specific, product classes. Each "platform" is then modeled with a Factory derived class.
Problem:
If an application is to be portable, it needs to encapsulate p... |
import qrcode
from io import BytesIO
import base64
def get_qr(data: str) -> str:
"""二维码
"""
if not data:
return None
img = qrcode.make(data)
output_buffer = BytesIO()
img.save(output_buffer, format="PNG")
byte_data = output_buffer.getvalue()
base64_str = base64.b64encode(byte_d... |
class AuthInfo(object):
def __init__(self, consumer_key = "20L3pj0XqJszENU5tVVFrKntT",
consumer_secret = "ptNul7KPR5gidrmfdbzc897f4oEESAebvOpViEU2ZBr8T15dmb",
access_token= "702690933679083520-ZPYrkYT0kfjfXGbO6xcwe6Bth6P9DIN",
access_token_secret = "miZ4ogEVCqokEL... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 04 16:16:26 2016
@author: Jordan
"""
|
from Pages.MediaPages.Media import Media
from selenium.webdriver.common.by import By
from magic_box.find_elements import find_element
from selenium.webdriver.support.ui import Select
from Pages.MediaBrowser import MediaBrowser
import pytest, time
class ContentPushMedia(Media):
def __init__(self, driver):
... |
# https://www.reddit.com/r/dailyprogrammer/comments/56tbds/20161010_challenge_287_easy_kaprekars_routine/
def largestDigit(digit):
numbers = list(map(int, str(digit)))
return max(numbers)
def descendingOrder(digit):
numbers = list(map(int, str(digit)))
numbers.sort(reverse=True)
s = [str(i) for ... |
print("This is for only dev branch") |
'''
.. todo::
cover the major cases and maybe a few more.
Leave rest in contrib
'''
|
def show_magicians(magicians_name):
for name in magicians_name:
print(name)
def make_great(magicians_name):
for i in range(len(magicians_name)):
magicians_name[i] = 'The Great ' + magicians_name[i]
magicians_name = ['aaa', 'bbb', 'ccc']
make_great(magicians_name)
show_magicians(magicians_name)... |
def count_zero_pairs(numbers):
count = 0
for i1 in range(0, len(numbers)):
for i2 in range(i1, len(numbers)):
if numbers[i1] + numbers[i2] == 0:
count += 1
return count
print(count_zero_pairs([0, 2, -2, 5, 10]))
|
#!/usr/bin/env python
import sys, array, re
from deflib import Field, Def, Def2CC
d2c = Def2CC([ 'record.h', 'recordtypes.h', 'buffer.h', '<boost/scoped_ptr.hpp>', '<boost/unordered_map.hpp>', '<memory>' ], [ 'coh' ])
d2c.before()
d2c.setfiles(sys.argv[1:])
fnhintcache = {}
print('namespace record {')
for fdef in ... |
import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv('Pattern_Recognised.csv')
fig = go.Figure(data=[go.Candlestick(x=df[df.columns[0]],
open=df[df.columns[1]], high=df[df.columns[2]],
low=df[df.columns[3]], close=df[df.columns[4]])
])
fig.update... |
import random
def random_weight_choice(L):
choice = None
total = 0
for item, p in L:
total += p
if random.random() * total < p:
choice = item
return choice
def test_random_weight_choice():
from collections import defaultdict
X = [('A', 1), ('B', 2), ('C', 3), ('... |
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
IP = '127.0.0.1'
PORT = 8080
ACCOUNT_PATH = os.path.join(BASE_DIR,'conf','accounts.cfg') |
#!env python3
# -*- coding: utf-8 -*-
from dataclasses import dataclass
@dataclass(order=True)
class Person:
name: str
age: int = 20
p1 = Person('Alice')
p2 = Person('Bob', 18)
print(p1, p2)
print(p1 < p2)
|
from __future__ import unicode_literals
from decimal import Decimal
from django.db import models
from people.models import BaseEntity
# Create your models here.
class Product(BaseEntity):
name = models.CharField(max_length=40)
company = models.CharField(max_length = 40,blank=True,null=True)
price = models.Decima... |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home_page(request):
return HttpResponse('<html> <title>To-Do lists</title> <body><p>foo</p></body></html>' )
|
#!/usr/bin/env python
import tensorflow as tf
from pandas_plink import read_plink
import pandas as pd
import numpy as np
import argparse as arg
def __main__(plink_file, tfrecords_file, tf_opts):
bim, fam, G = read_plink(plink_file)
G = np.array(G.T, dtype=np.int8)
G[np.isnan(G)] = 0
N = G.shape[0]
... |
import subprocess
import pandas as pd
import numpy as np
import os
import sys
import joblib
from ..utils.feature_process import feature_extraction, feature_transform, type_mapper
from .logistic_regression import extract_time
fm_train_data = "../data/fm_train.txt"
def preprocess(epoch, batch_size):
# 通过df的方式将流式数据... |
"""Tests for training the model for contradictory-claims."""
# -*- coding: utf-8 -*-
import os
import shutil
import unittest
import numpy as np
import tensorflow as tf
from contradictory_claims.models.train_model import build_model, load_model, regular_encode, save_model
from transformers import AutoModel, AutoToken... |
import smtplib, ssl
port = 465
password = input("Type your password and press enter: ")
context = ssl.create_default_context()
sender_email = "home.pharmacy.application@gmail.com"
receiver_email = "spodkowinska@gmail.com"
messageExpiryDate = """\
Subject: Some drugs are going to expire soon
Your drug {name} is going ... |
from flask import Flask, jsonify
app = Flask(__name__)
# pull in the config (i.e. vars from `services/web/project/config.py` on init)
# define your app/service routes here
@app.route("/")
def hello_world():
return jsonify(hello="world")
# Liveliness check--should at least have '/alive' and 'readiness' dummy rout... |
import numpy as np
def read_OFF(off_file):
'''Returns a list of vertices and a list of triangles (both represented as
numpy arrays)'''
vertexBuffer = []
indexBuffer = []
with open(off_file, "r") as modelfile:
first = modelfile.readline().strip()
if first != "OFF":
... |
__author__ = 'Tommaso Mazza'
import glob
from MatchVCF.comparator import Comparator
class Difference(Comparator):
__fold1 = None
__fold2 = None
def __init__(self, fold1, fold2):
self.__fold1 = fold1
self.__fold2 = fold2
def calc(self, genotype):
__dic1 = {}
__dic2 =... |
import matplotlib.pyplot as pl
import scipy.signal as s
import scipy.fft as f
import numpy as np
import random as r
def _show(fun, data, data_len, max_len, transformer, desired=False):
r.shuffle(data)
for i, x in enumerate(data):
if i >= max_len:
break
pl.figure(i)
pl.plot... |
import u12
import sys
import time
sys.path.insert(0, '/home/albert/Documents/Albert Work/Scripts')
from funcs import PID
from thermocouple import temperature_read
import matplotlib.pyplot as plt
import pylab as pylab
d=u12.U12()
i=0
max=100
frequency=1
temps=[]
sum=0
while i<max:
t=temperature_read(d)
temps.a... |
import glob
import math
import numpy as np
import argparse
import sys
import pickle
import time
import matplotlib.pyplot as plt
from copy import deepcopy
import logging
import scipy.optimize as opt
import os
from .screener import load_data_all, load_data_single
from .. import arguments
from sklearn.linear_model import ... |
a=input().split()
b=input()
print(a.index(b)+1)
|
# Generated by Django 2.1.4 on 2019-01-14 18:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('psychologues', '0016_auto_20190114_0032'),
]
operations = [
migrations.AddField(
model_name='competence',
name='char... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : login_token.py
@CopyRight : USTC SSE
@Modify Time : 2020/11/17 19:36
@Author : TJ
@Version : 1.0
@Description : 自定义登录验证类
"""
import jwt
import datetime
import logging as logger
from django.utils import timezone
from SharePlatf... |
import numpy
from load_data_ex1 import *
from normalize_features import *
from gradient_descent import *
from plot_data_function import *
from plot_boundary import *
import matplotlib.pyplot as plt
import os
figures_folder = os.path.join(os.getcwd(), 'figures')
if not os.path.exists(figures_folder):
os.makedirs(fi... |
# Copyright Alexander Wood 2016.
# Solutions for Coursera's Bioinformatics 1 Course.
'''
Minimum Skew Problem: Find a position in a genome where the skew diagram attains a minimum.
Input: A DNA string Genome.
Output: All integer(s) i minimizing Skewi (Genome) among all values of i (from 0 to |G... |
import os
import time
from appium import webdriver
from features.steps import login
from features.action.actions import *
from features.action.unhandled_event import *
from features.page.BotBar import BotBar
from features.page.HomePage import HomePage
from features.page.ItemPage import ItemPage
from features... |
# doc2vec
import numpy as np
import pandas as pd
import src.features.doc2vec as doc2vec
articles = ['A dog saw a cat. He was standing there', 'He says hi']
titles = ['A','B']
df = pd.DataFrame({'articles':articles,'titles':titles})
# def test_getEmbeddingsMeanUse():
# embDf = doc2vec.getEmbeddings(df,colName = ... |
"""
Time/Space complexity = O(log N)
"""
# Recursion
class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return TreeNode(val)
def dfs(node):
if not node:
return node
... |
import matplotlib.pyplot as plt
import numpy as np
import cv2
import argparse
import os.path
from PIL import Image
import os
import struct
width = 450
height = 350
def readDmp(file, depthShift):
# input: [string] file name
# output: list of {( [array of np.array(int)] 2D depth map , [array of np.array([int... |
# 1326. Minimum Number of Taps to Open to Water a Garden
'''
There is a one-dimensional garden on the x-axis. The garden starts at the point 0 and ends at the point n. (i.e The length of the garden is n).
There are n + 1 taps located at points [0, 1, ..., n] in the garden.
Given an integer n and an integer array ran... |
#!/user/bin/python
print("Welcome to Python Programmaing language")
print("Welcome to the python tutorials")
x=200
y=100
x+y
x-y
x/y
#print the Hello
print("Hello World Programmaing")
print(x+y)
print(x-y)
print(x/y)
print("\n"*20)
for x in 'AshishKumar'
print("Welcome to: ",x)
for x in "AshishKumar"
p... |
from dataviva import db
from dataviva.utils.auto_serialize import AutoSerialize
from dataviva.attrs.models import Bra, Isic, Cbo
from sqlalchemy import and_
############################################################
# ----------------------------------------------------------
# 2 variable tables
#
################... |
###########
## Notes ##
###########
'''
The replace() method returns a copy of the string where all occurrences of a substring is replaced with another substring.
The syntax of replace() is:
str.replace(old, new[, count])
replace() parameters
* old - old substring you want to replace
* new - new substring wh... |
import pandas as pd
import numpy as np
import pickle
df = pd.read_csv('Dataset.csv')
df = df.drop(columns = ['Id'])
X = np.array(df.iloc[:, 0:4])
y = np.array(df.iloc[:, 4:])
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
y = le.fit_transform(y.reshape(-1))
from sklearn.model_sel... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
import argparse
import cv2
import numpy as np
import dlib
import sys
import datetime
import os
import imutils
import math
from imutils import face_utils
# from scipy.spatial import distance as dist # for desktop
class FaceDLib:
def __init__(self, predictor_path):
... |
funcdict = {
"update": set.update,
"intersection_update": set.intersection_update,
"difference_update": set.difference_update,
"symmetric_difference_update": set.symmetric_difference_update,
}
_ = int(input())
set_a = set(list(map(int, input().strip().split())))
n = int(input())
for i in range(n):
... |
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.views import generic
from .forms import StoreInfoForm, StoreMenuForm
from .models import StoreInfo, StoreMenu
from django.utils.safestring import mark_safe
import json
# Create your views here.
class Hom... |
#!env python3
# -*- coding: utf-8 -*-
import argparse
# python3 argparse_module.py
# python3 argparse_module.py -h
# python3 argparse_module.py -a 1 -b 2 -c 3
def mul(a, b, c):
return a * b * c
if __name__ == "__main__":
parser = argparse.ArgumentParser("multiply three values")
parser.add_argument("-a", ... |
import logging
import contextlib
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything
@contextlib.contextmanager
def log_level(level, name):
logger = logging.getLogger(name)
old_level = logger.getEffectiveLevel()
logger.setLevel(level)
try:
... |
class Solution(object):
def generatePossibleNextMoves(self, s):
n, res = len(s), []
for i in range(n - 1):
if s[i:i+2] == '++':
res.append(s[:i] + '--' + s[i+2:])
return res |
#Created by WilliamOtieno
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get('https://lbry.tv/')
searchbox = driver.find_element_by_xpath('//*[@id="app"]/div/header/div/div[1]/div/div/input')
searchbox.send_keys('Arch Linux')
searchbox.send_keys(Keys... |
import unittest
def reverse(char_list):
size = len(char_list)
for i in range(0, size//2):
char_list[i], char_list[size-1-i] = char_list[size-1-i], char_list[i]
return char_list
# Tests
class Test(unittest.TestCase):
def test_empty_string(self):
list_of_chars = []... |
"""
this script demonstrates ggplot in python.
todo run script at clinux.
todo see if data must be long for ggplot.
"""
from ggplot import *
## graphs from website
# -----------------------------------------------------------------------------
## fun
ggplot(diamonds, aes(x='carat', y='price', color=... |
from selectable.base import ModelLookup
from selectable.registry import registry
from cities.models import City
class CityLookup(ModelLookup):
model = City
search_fields = ('name__icontains', )
# def get_item_label(self, item):
# # Display for choice listings
# return u"%s, %s" % (item.na... |
from datetime import datetime, timedelta
import os
import shutil
from zipfile import ZipFile, BadZipfile
class Archive:
def __init__(self, sourceDir, outputDir, stagingDir):
self.sourceDir = sourceDir
self.outputDir = outputDir
self.stagingDir = stagingDir
self.extension = ".zip"
... |
from behave import Given, When, Then, Step
@Given("I'm on the products list page")
def step_impl(context):
context.home_page.go_to_products_list()
@When("I choose price min to max from sort list")
def step_impl(context):
context.products_list_page.set_sort_products("low_to_high")
@Then("Products should be... |
#coding=utf-8
import requests
import json
url1={'mysql旧':'http://192.168.13.141:4042/sw/serviceApi/09f4fef9249c457ca67b4a7a45823730/interface/51aa655ec2734aa4a5f38bae78a7fc3a/customWrapper',
'sqlserver旧':'http://192.168.13.141:4042/sw/serviceApi/09f4fef9249c457ca67b4a7a45823730/interface/bd3f6e5debb34d94b63688d40... |
from __future__ import annotations
from pathlib import Path
from typing import Union
import tomlkit
class PathableConcept(object):
def __init__(self, path: Path):
self.path = path
# Assume the Workspace's name is the directory name
# TODO Enforce any name requirements (would they be pro... |
from adapters.contact_adapter import ContactAdapter
from adapters.generic.motion_sensor import MotionSensorAdapter
from adapters.generic.temp_hum_sensor import TemperatureHumiditySensorAdapter
from adapters.generic.water_leak_sensor import WaterLeakSensorAdapter
konke_adapters = {
'2AJZ4KPFT': TemperatureHumidity... |
#!/usr/bin/env python3
import sys
import Standardize
import estimation_n_grams
import n_gram
from collections import Counter
OUTPUT_FILE = "output.txt"
OUTPUT_FILE_PROPER = "output2.txt"
def main(args):
input = args[1]
#Standardize.standardize(input, "output.txt")
#
# lexicon = build_lexicon(OUTPUT... |
# -*- coding: utf-8 -*-
import tkinter as tk # 使用Tkinter前需要先導入
# 第1步,產生實體object,建立視窗window
window = tk.Tk()
# 第2步,給窗口的視覺化起名字
window.title('My Window')
# 第3步,設定窗口的大小(長 * 寬)
window.geometry('500x300') # 這裡的乘是小x
# 第4步,在圖形介面上創建一個標籤label用以顯示並放置
var1 = tk.StringVar() # 創建變數,用var1用來接收滑鼠點擊具體選項的內容
l = tk.Label(window, bg='g... |
import csv
import matplotlib.pyplot as plt
import math
import pandas as pd
from statistics import mean
import numpy as np
def fix():
fix_1, fix_2, fix_3, fix_4, fix_5, = [],[],[],[],[]
fix_6, fix_7, fix_8, fix_9 = [],[],[],[]
for i in range(1,10):
f = i/10
with open('data t '+str(f)+' and ... |
import asyncio
import cozmo
import cv2
import getopt
import logging
import numpy as np
import sys
import threading
import time
import PIL.Image
import PIL.ImageFont
import PIL.ImageTk
from scipy.interpolate import UnivariateSpline
import tkinter as tk
from cozmo.util import degrees, distance_mm, speed_mmps
from NH_I... |
from configuration import *
from bench_runner import *
import sys
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import json
import os
import socket
import math
# Find the newest subdirectory in a path (i.e. the one most recently modified)
def newest_subdir(path):
direc... |
from computeCost import computeCost
import numpy as np
def gradientDescent(X, y, theta, alpha, num_iters):
"""
Performs gradient descent to learn theta
theta = gradientDescent(x, y, theta, alpha, num_iters) updates theta by
taking num_iters gradient steps with learning rate alpha
"""
m ... |
print('test')
hi
print('feature') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.