text stringlengths 38 1.54M |
|---|
#encoding=utf-8
#!/usr/bin/python
import gensim, logging
import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# Set features
dirnamecsvFile='test.txt'
model_name='Pixnet2016'
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
class MySentences(object):
def __in... |
# Generated by Django 3.1.7 on 2021-03-08 22:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0002_auto_20210307_2322'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='address',
... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#pylint: disable=locally-disabled,line-too-long,attribute-defined-outside-init
#pylint: disable=locally-disabled,too-many-public-methods
#
# Copyright 2015-2023 BigML
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in c... |
# Copyright (c) Optiver I.P. B.V. 2019
import logging
from datetime import datetime
from typing import Dict, Any, Optional
import itertools
from collections import defaultdict, deque
from .base_client import Client
from .common_types import TradeTick, Instrument, InstrumentType, OptionKind
from .type_checking import v... |
class BankAccount:
def __init__(self, owner):
self.owner = owner
self.balance = 0.0
def getBalance(self):
return self.balance
def deposit(self, amount):
self.balance += amount
return self.balance
def withdraw(self, amount):
self.balance ... |
from PIL import ImageGrab, Image
import numpy as np
import cv2
import time
import os
def is_different(imageA, imageB):
err = np.sum((imageA.astype("float") - imageB.astype("float")) ** 2)
err /= float(imageA.shape[0] * imageA.shape[1])
print(err)
return err > 1000
def save_into_pdf():
frames_pat... |
from data_access.canton_data_access import CantonDataAccess
class MunicipalityService:
@staticmethod
def get_municipalities(canton):
return CantonDataAccess.get_municipalities(canton)
@staticmethod
def get_municipality(canton, bfs_nr):
return CantonDataAccess.get_municipality(canton, ... |
import sys, os
sys.path.append(os.path.realpath(".."))
import tsfresh.feature_extraction.feature_calculators as tsf
from sacred.observers import MongoObserver
from sacred import SETTINGS
SETTINGS["CONFIG"]["READ_ONLY_CONFIG"] = False #weird issue where GridSearchCV alters one of the config values
import pickle as pkl
f... |
# coding: utf-8
# ## Interpolate a list of .edi files onto the same period range
import os
import mtpy.core.mt as mt
import numpy as np
edi_path = r"c:\Users\jpeacock\Documents\SaudiArabia\EDI_Files\Rotated_W34N"
edi_list = [os.path.join(edi_path, edi_fn) for edi_fn in os.listdir(edi_path)
if edi_fn.e... |
#!/usr/bin/python
import os
import time
import sqlite3 as mydb
import sys
import datetime
def logTime():
con = mydb.connect('testTime.db') #connect to DataBase
with con: #open and close connection once done
now = datetime.datetime.now() #give vari now the date and time
timeString = now.strftime("%H-%M-%S") #form... |
try:
import maya.cmds as cmds
except ImportError:
print('WARNING (%s): failed to load maya.cmds module.' % __file__)
from .. core import ALT, NOALT, CTRL, NOCTRL, PRESS, RELEASE
from .. import util
def getVimlineParts (state):
if state["right"]:
return (state["left"], state["right"][0], state["r... |
from plotutils import *
#samples
samples=[Sample('t#bar{t}',ROOT.kRed+1,'ttbar_test.root',''),Sample('t#bar{t}H',ROOT.kBlue,'tth_test.root','') ]
listOfhistoLists=createHistoLists_fromHistoFile(samples)
writeListOfhistoLists(listOfhistoLists,samples,'plots')
|
import unittest
from glovo_api_python import __version__
class VersionTest(unittest.TestCase):
def test_version(self):
assert __version__ == '0.1.1'
|
"""Crazy8s Constants
Constants used for playing crazy eights in Telegram chat.
param:
Author: Deborah Djon
Date: .06.2021
Version:0.1
license: free
"""
from enum import Enum
from telegram import Bot
"""Contains all constants"""
# Game constants
MoveOutcome = Enum(
"MoveOutcom... |
import pygame
from math import *
SCREEN_SIZE = (1280, 720)
LINE_COLOR = (255, 0, 0)
POINT_COLOR = (0, 255, 0)
class Function(object):
def __init__(self):
pygame.display.init()
self.screen = pygame.display.set_mode(SCREEN_SIZE)
self.rect = self.screen.get_rect()
self.ratio = 10
... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
#LIVE:
#database identifier?
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "vendors.settings")
#TEST: (uses static files form heroku server still )
#os.environ.setdefault("DJANGO_SETTINGS_MODULE", "vendors.TESTsettings")
from django.core.m... |
Last login: Thu Sep 15 12:55:14 on ttys001
stephaniebreunig@slb [~]
% cd git/bootcamp
stephaniebreunig@slb [~/git/bootcamp]
% ipython
Python 3.5.2 |Anaconda custom (x86_64)| (default, Jul 2 2016, 17:52:12)
Type "copyright", "credits" or "license" for more information.
IPython 5.1.0 -- An enhanced Interactive Python.
... |
stateMachineName="totem_finder"
finalOutcomes=['success','fail']
states=[
# {'name':'name',
# 'mymessage':'Something to say at the start',
# 'transitions':[
# ('pathName','toStateName','Relevant output message')
# ]},
{'name':'waitForStart',
'mymessage':'Waiting for start...',
'transitions... |
import sys
import pytest
import oommfc as oc
import micromagneticmodel.tests as mmt
def check_script(script, contains):
assert script.count('\n') == 9
assert script[0] == '#'
assert script[-1] == '\n'
for content in contains:
assert content in script
class TestDMI(mmt.TestDMI):
... |
#!usr/bin/env/ python
import subprocess
import optparse
import re
def get_arguments():
parser = optparse.OptionParser()
parser.add_option("-i", "--interface", dest="interface", help="Interface to change MAC adress for.")
parser.add_option("-m", "--mac", dest="new_mac", help="Enter the new mac for interfa... |
import pyttsx3
import PyPDF4
filename = 'api.pdf'
ratePatial = -60
startPage = 0
def parsePdf():
pdfreader = PyPDF4.pdf.PdfFileReader(filename)
print(pdfreader.isEncrypted)
pages = pdfreader.numPages
print(pages)
for num in range(startPage, pages -1 ):
page = pdfreader.getPage(num)
... |
from flask import Flask, request, redirect, render_template
app = Flask(__name__)
app.config['DEBUG'] = True
@app.route("/", methods=['POST', 'GET'])
def index():
if request.method == 'GET':
username = ''
email = ''
password = ''
verify = ''
if request.method ... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
IoT Penetration testing toolset
application Asset testing set
By sarunasil
"""
import pytest
import random
import os
from iotpentool.threatmodel import ThreatModel
from iotpentool.asset import Asset
from iotpentool.technology import Technology
from iotpentool.utils im... |
import abc
import functools
import thread
import os
import socket
import getpass
import sys
import traceback
import host
import time
import re
import nxos_XML_errors
import xml.etree.ElementTree as ET
# For later multi-thread support
import threading
import paramiko
import logging
#from nxos_XM... |
# -*- coding: utf-8 -*-
import scrapy
import json
import pickle
import urllib.parse
import requests
from selenium import webdriver
from jsonpath import jsonpath
from jd.items import Product
from scrapy_redis.spiders import RedisSpider
class JdProductSpider(RedisSpider):
name = 'jd_product'
allowed_domains = ... |
import argparse
from luigi import build
from .task import Aggregation, DetectorTraining
def main():
parser = argparse.ArgumentParser()
parser.add_argument("raw_path", help="input directory", type=str, default="data/asian")
parser.add_argument('dst_path', help="output directory", type=str, default="data/... |
from functools import wraps
from keras import backend as K
from keras.layers import Conv2D, Add, ZeroPadding2D, UpSampling2D, Concatenate, MaxPooling2D, Layer, Lambda
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.normalization import BatchNormalization
from keras.regularizers import l2
... |
import os
from dffml import AsyncTestCase
from shouldi.python.bandit import run_bandit
class TestRunBanditOp(AsyncTestCase):
async def test_run(self):
results = await run_bandit.test(pkg=os.getcwd())
self.assertEqual(
type(results["result"]["CONFIDENCE.HIGH_AND_SEVERITY.HIGH"]), int
... |
import numpy as np
import pandas as pd
from sklearn import model_selection, preprocessing
import xgboost as xgb
import datetime
train_df = pd.read_csv('../input/train.csv')
test_df = pd.read_csv('../input/test.csv')
# brings error down a lot by removing extreme price per sqm
train_full_sq_mean = 54.21
test_fill_sq_m... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-01-07 12:09
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('admina', '0005_auto_20171215_1504'),
]
operations = [
migrations.AddField(
... |
import mime, threading, datetime
from ebooklib import epub
from lib.logger import getLogger
from lib.constants import *
L = getLogger("epub")
class Book:
def __init__(self, meta: dict[str], book_id, title, chapter_cnt):
self.book = epub.EpubBook()
self.book.set_identifier(meta['identifier'])
self.book.... |
from selenium import webdriver
from selenium.common.exceptions \
import NoSuchElementException, ElementNotVisibleException
import time
import os
# from selenium.webdriver.common.by import By
# from selenium.webdriver.common.keys import Keys
# from selenium.webdriver.support.ui import WebDriverWait
# from selenium.w... |
a=int(input("Digite um valor:"))
b=a+1
c=a-1
print("No número {0} tem como seu antecessor {1} e como sucessor {2}.".format(a,c,b)) |
# Generated by Django 3.1.2 on 2020-10-18 22:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('desafio', '0002_auto_20201018_1715'),
]
operations = [
migrations.AlterField(
model_name='modelformarquivo',
name='a... |
import datetime
import os
import pyperclip
import sys
from . import print_error
class FileOperation:
REPORTER = os.environ['REPORTER']
today = datetime.date.today()
def __init__(self):
self.__dir_path = self.__build_dir_path()
self.__file_path = self.__build_file_path()
self.__che... |
def print_header():
print("CASH RECEIPT\n"
"------------------------------")
def print_body():
print("Charged to____________________\n"
"Received by___________________")
def print_footer():
print("------------------------------\n"
"\u00A9 SoftUni")
def print_receipt():
... |
import csv
import datetime
import logging
import luigi
import numpy as np
import pandas as pd
import sys
import src.etl.luigi.uade_lib as lib
class Fetch(luigi.Task):
logger = logging.getLogger('luigi-interface')
def run(self):
# Doesn't work on mac
# connection = lib.NeptunoDB.connection()
... |
# patch-255
decimal_accuracy = 7
def dtbconverter(num):
whole = []
fractional = ["."]
decimal = round(num % 1, decimal_accuracy)
w_num = int(num)
i = 0
while decimal != 1 and i < decimal_accuracy:
decimal = decimal * 2
fractional.append(int(decimal // 1))
... |
import numpy as np
import cv2
import pickle
face_cascades=cv2.CascadeClassifier("cascades/data/haarcascade_frontalface_alt2.xml")
recognizer=cv2.face.LBPHFaceRecognizer_create()
recognizer.read("my_traning.yml")
lable={}
with open("my_lable.pkl","rb") as obj:
new_lable=pickle.load(obj)
lable={v:k for k,v in new_la... |
# BOJ 11403
import sys
import collections
size = int(sys.stdin.readline())
graph = {}
for i in range(size):
graph[i] = []
for i in range(size):
line = map(int, sys.stdin.readline().split())
for idx, j in enumerate(line):
if j == 1:
graph[i].append(idx)
result = []
for i in range(size... |
# Jason Hurtado
# UCID: jh465 Section: 003
import sys, time
from socket import*
argv = sys.argv
serverhost = argv[1]
serverport = argv[2]
datalength = argv[3]
serverport = int(serverport)
datalength = int(datalength)
data = 'J'* datalength
s = socket(AF_INET, SOCK_DGRAM)
s.settimeout(1)
x=0
while x < 3:
try:
p... |
import addressable
import network
import artnet
import time
aled = addressable.controller(addressable.ALED_CONTROLLER, protocol = 0)
fix = addressable.fixture(495, protocol = 0)
aled.add_fixture(fix)
aled.recompute_chain()
aled.start()
stat = addressable.controller(addressable.STAT_CONTROLLER)
stat_fix = stat.fixture... |
import os
import json
import subprocess
class Asset:
def __init__(self, abs_path):
self.path = abs_path
self.name = os.path.basename(self.path)
@property
def entry(self):
package_json = os.path.join(self.path, 'package.json')
try:
with open(package_json) as f:
... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 13 09:16:52 2016
@author: jmtaysom
"""
import sys
with open('reversewords.txt', 'r') as f:
for line in f:
sample = line.split()
print(' '.join(sample[::-1]))
sys.exit() |
import numpy as np
import datetime
from flask import Flask, request, jsonify, json
class FreebaseEmbeddingServer:
dir_path: str
entity_to_id: dict # entity mid -> entity id
relation_to_id: dict
entity_vec: np.memmap
relation_vec: np.memmap
dim: int # embedding dimension for each entity or re... |
import csv
import sys
class Tweet_Counter:
def __init__(self):
pass
def count_tweets_file(self, infile, data={}):
print("analyzing " + infile + "...")
with open(infile, 'rb') as in_csv:
reader = csv.reader(in_csv)
for tweet in reader:
user_id = t... |
# Bubble sort
'''
Which bubble will come up first - bigger bubble / small bubble
bigger bubble because --> Terminal Velocity =~ Radius^2
Stokes Law - main intuition behind Bubble Sort
Comparisons - n+(n-1)+..... ->Time Complexity O(n^2)
Space Complexity - only 1 list O(1)
Swaps - O(n^2)
Stability (Relative Ordering of... |
# Escribe tus funciones abajo de esta línea
def main():
# Escribe tu código abajo de esta línea
pass
print("1. pies a cm, 2. pulgadas a cm, 3. yardas a cm")
res = int(input('Introduce una opcion: '))
if res == 1:
res = int(input("Introduce la cantidad: "))
pies_cm = res * 30.48
... |
# This file contains utilities for running benchmarks and collections of
# benchmarks (called benchmark suites).
#
# We view a benchmark as a function `f(input) -> output` that takes in some
# inputs and spits out some ouputs. For example, a prime factorization
# benchmark might take in a number `x` and output the time... |
# Programação Orientada a Objetos
# AC01 ADS-EaD - Números especiais
#
# Email Impacta: otavio.goncalves@aluno.faculdadeimpacta.com.br
def eh_primo(n):
"""Função que verifica se um número é primo
Recebe um número natural n, com n >= 2, e retorna verdadeiro se
n é um número primo e falso caso contrário.
... |
class MainMisc:
def __init__(self, app):
self.db = app.db
self.config = app.config
self.app = app
|
"""
snot = 0
while snot < 10:
#print "i will never sleep in class again"
print snot
snot = snot + 1
"""
guesses =0
while guesses < 5:
usersName = raw_input("hello, whats your favourite movie")
guesses = guesses + 1
if usersName == "LUCY":
print "Welcome to the favourite movie e... |
#coding:gbk
import time
import os
import utils
def check_file_exist(file_name):
return os.path.exists(file_name)
def handle_timeout(func, timeout, *args, **kwargs):
interval = 1
ret = None
while timeout > 0:
begin_time = time.time()
ret = func(*args, **kwargs)
if ret:
... |
from django.conf.urls import url
from . import views
urlpatterns=[
url(r'^add/$', views.add),
url(r'^adding/$', views.adding),
url(r'^destination/(?P<name>\d+)/', views.destination),
url(r'^join/(?P<name>\d+)/', views.join),
url(r'^$', views.dashboard),
] |
#!/usr/bin/env python
import sys, os, networkx as nx, numpy
from itertools import product, combinations
from collections import defaultdict
from .run import run_helper, get_deltas_hotnet2
from .constants import *
from .heat import filter_heat, filter_heat_to_network_genes
from .permutations import permute_heat
def co... |
# (C) British Crown Copyright 2011 - 2017, Met Office
#
# This file is part of cartopy.
#
# cartopy is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option)... |
# 链表
class Node(object):
def __init__(self, elem):
# _item存放数据元素
self.elem = elem
# _next是下一个节点的标识
self.next = None
class SingleLinkList(object):
def __init__(self, node=None):
self._head = None
def is_empty(self):
return self._head == None
def length... |
import os
from .core import Comtrade
from .util import (
DATA_DIR, KEY_ENV_NAME, KEY_FILE_NAME, DEFAULT_API_URL, get_partner_areas,
get_reporter_areas, get_trade_regimes, get_classification
)
__version__ = "0.0.1"
if not os.path.isdir(DATA_DIR):
os.makedirs(DATA_DIR)
|
#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# @DATETIME:2021/11/110:09
# @NAME:flask/__init__
import os
from flask import Flask
# 定义应用工厂函数
def create_app():
# __name__等于python模块名
# instance_relative_config告诉应用配置文件存在于实例文件夹的相对路径
app = Flask(__name__, instance_relative_config=True)
# E:\python\fl... |
import tornado.web
import tornado.template
class UploadHandler(tornado.web.RequestHandler):
def post(self):
file_body = self.request.files['spreadsheet'][0]['body']
response = { hash: 'xyz' }
self.set_header('Content-Type', 'application/json')
self.finish(response)
|
from django.shortcuts import render
from django.views import generic
from django.http.response import HttpResponse, HttpResponseRedirect
from django.contrib.auth.forms import UserCreationForm,UserChangeForm,PasswordChangeForm
from django.contrib.auth import authenticate, login,logout,update_session_auth_hash
from djang... |
from models import *
localbase = LOCALBASE
print('creation tables')
localbase.create_table(User)
localbase.close()
|
import datetime
@classmethod
def days_to_election(cls, days_passed, post='mayor'):
"""Days left to election.
Takes into account day of the week when elections run.
Arguments:
days_passed (int): Days passed since election.
post: 'mayor', 'governor' or 'president'.
Returns:
... |
from django.apps import AppConfig
class StarcraftAppConfig(AppConfig):
name = 'starcraft_app'
|
from django.db import models
from customer.models import Customer
from address.models import CustomerAddress
from product.models import Product
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.utils import timezone
# Create your mod... |
import copy
import time
import random
from deep_space_trader.items import ItemCollection
def random_planet_number():
return random.randrange(2, 399)
def random_planet_letter():
return chr(random.randrange(97, 108))
class Planet(object):
parts = [
[
'ho', 'ce', 'cu', 'he', 'hu', 'sa... |
"""口座情報をユーザに通知する"""
import re # 正規表現を使用するため
import sqlite3
import time
import requests
from app.module.exchangess import bitbank
# DBの初期設定(接続開始)
DBPATH = 'config/sample_db.sqlite'
CONNECTION = sqlite3.connect(DBPATH)
CURSOR = CONNECTION.cursor()
CURSOR.execute("SELECT API_KYE FROM lline")
GET_TOKEN = CURSOR.fetchone(... |
########################################################################################
# SaxParser class definition
########################################################################################
import xml.parsers.expat
from legalexception import *
class SaxParser:
"SaxParser class"
def __init__(s... |
# def soma(a, b): # cria método soma: que recebe a e b
# return a + b # e retorna a + b
#
# def subtracao(a, b): # cria método subtracao: que recebe a e b
# return a - b # e retorna a - b
#
# def multipicacao(a, b): # cria método multipicacao: que recebe... |
# copy list and swap items at indexes
def swap(arr, indexA, indexB):
c = list(arr)
c[indexA], c[indexB] = c[indexB], c[indexA]
return c
# output dictionary to file
def outputFile(dic, fileName='output.txt', accessMethod='a'):
with open(fileName, accessMethod) as f:
for key, value in dic.items():
f.write('{}: ... |
from __future__ import division, print_function, absolute_import
import operator
from numpy import (arange, array, asarray, atleast_1d, intc, integer,
isscalar, issubdtype, take, unique, where)
from numpy.fft.helper import fftshift, ifftshift, fftfreq
from bisect import bisect_left
__all__ = ['ffts... |
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
__author__ = "Diego Cadogan"
__copyright__ = "2018"
__version__ = "0.1"
__license__ = "LGPL"
import sys, os, platform, time, requests, traceback
import msvcrt as m
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from subpro... |
from .context import lux
import pytest
import pandas as pd
import time
def test_q1_performance_census():
df = pd.read_csv("lux/data/census.csv")
tic = time.perf_counter()
df.set_intent(["education","age"])
df._repr_html_()
toc = time.perf_counter()
delta = toc - tic
print(f"Overall Performance: {delta:0.4f} seco... |
from django.contrib import admin
from guardian.admin import GuardedModelAdmin
from utils.admin import PermissionsAdminMixin
from .models import Rating
class RatingAdmin(PermissionsAdminMixin, GuardedModelAdmin):
pass
admin.site.register(Rating, RatingAdmin)
|
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'Quest'
db.delete_table('canopy_quest')
# Removing M2M table for field users on ... |
▼ 入力させた値が、while の条件に合致する限りループし続ける(有効範囲内の値ではない、殻のスペース ではない)
-------------------------------------------------
position = 0
available_range = [1,2,3,4,5,6,7,8,9]
while position not in available_range or not is_empty_space(board, position):
try:
position = int(input('Player %s, choose you... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-11-28 09:34
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Crea... |
from flask import Flask, request, session, g, redirect, flash, render_template, Blueprint
from models import *
from sqlalchemy.exc import IntegrityError, InvalidRequestError
from flask_mail import Message, Mail
auth = Blueprint('auth', __name__)
app = Flask(__name__)
app.config.from_object('config')
mail = Mail(app)
... |
#!/usr/bin/env python
import random
import argparse
import cv2
import torch
import gym
import gym.spaces
import numpy as np
import GAN
BATCH_SIZE = 16
IMAGE_SIZE = 64 # dimension input image will be rescaled
REPORT_EVERY_ITER = 100
SAVE_IMAGE_EVERY_ITER = 1000
log = gym.logger
log.set_level(gym.logger.INFO)
class I... |
# -*- coding: utf-8 -*-
from openerp.osv import fields, osv
import openerp.addons.decimal_precision as dp
from datetime import datetime
import locale
import pytz
from openerp.tools.translate import _
import time
from itertools import ifilter
class debitcredit(osv.Model):
_order = 'date desc'
_name = 'debit.credit'
... |
import numpy
import random
from keras import models
from keras import layers
from keras.utils import to_categorical
import matplotlib.pyplot as plt
features_num = 18
dataset = numpy.loadtxt('AF_features_features_18.csv', delimiter=",", skiprows=1)
random.shuffle(dataset)
length = len(dataset)
idx = in... |
# -*- coding: utf-8 -*-
# author: ronniecao
# time: 2017/12/09
# description: environment of flappy bird
from itertools import cycle
import random
import time
import os
import cv2
import numpy
import pygame
class Environment:
def __init__(self, is_show=True, is_save=False):
self.is_show = is_show
... |
import numpy as np
from abc import ABC, abstractmethod
from desc.backend import use_jax, put, TextColors
if use_jax:
import jax
class Jacobian(ABC):
"""Jacobian is an abstract base class for jacobian matrix calculations
"""
@abstractmethod
def __init__(self, fun:callable, argnum:int=0, **kwargs... |
from django.shortcuts import render
from .models import Order, Products
from django.core.paginator import Paginator
# Create your views here.
def index(request):
product_objects = Products.objects.all()
# **********Search code
item_name = request.GET.get("item_name")
if item_name != '' and item_name ... |
# -*- coding:utf-8 -*-
class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(set(s))!=len(set(t)): #如果拥有的元素就不一样的话
return False #直接返回
length=len(s)
di={} #建立一个dict,其中s[i]为键,t[i]为值
... |
# -*- encoding: utf-8 -*-
"""
@File : demo.py
@Time : 2021/*/* 00:00
@Author : xuanRui
"""
# 前台管理的模型
from exts import db # 数据库连接
import shortuuid # 前台用户id加密
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash # 导入密码加密,解密方法的库
import enum # 导入枚举
... |
import xmltodict
from pprint import pprint
with open('show_security_zones.xml') as file:
xmldata = file.read().strip()
my_xml = xmltodict.parse(xmldata)
pprint(my_xml)
pprint(type(my_xml))
|
# -*- coding=utf-8 -*-
from sys import argv
script, operation = argv # main.py, read, write
prompt = '> '
def read():
print "程序将读取您以往的日记"
diary = open('diary.txt','r')
# if 是否为空,
# print "您的日记还没有内容。"
# else:
print diary.read()
def write():
print "您可以开始写日记了"
diary = open('diary.txt','a')
line = raw_inpu... |
import numpy as np
import quat
from state import State
class Sigma_pts:
def __init__(self):
self.n = 6
# Maybe change this to start with current state * eye
self.Y = []
self.X = []
self.Z = []
self.Y_raw = []
self.Y_qmean = quat.Quaternion([1, 0, 0, 0])
... |
# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from itsoho.core.auth.models import Xuser, BaseInfo, EduInfo
from itsoho.core.auth.forms import BaseInfoForm, EduInfoForm
def manage_home(request):
return render(request, 'manage/manage_home.ht... |
#!/usr/bin/env python3
import sys
import irank
import optparse
if __name__ == '__main__':
p = optparse.OptionParser()
p.add_option('-f', help='force', action='store_true', dest='force')
for k in irank.KEYS:
p.add_option('--' + k, default=None, type='int', dest='rating_' + k, help='set ' + k)
opts, files = p.pars... |
from blog.common.db import use_orm
from blog.models.blogs import Blog
from blog.models.categories import Category
from sqlalchemy import asc
class BlogController:
@classmethod
@use_orm(name='ro')
def info(cls, blog_id, *, session):
blog = session.query(Blog).filter_by(id=blog_id).first()
c... |
# routines to calculate a gaussian distribution (from debris) in a circular planet.
import numpy as np
import meancov
import statsPython
import lonlatChecks
import serialKernel as SK
import safetyMetrics as SMF
def getCorrelation2InRotatedFrame(beta,vals):
# lon0, lat0 : main vehicle lat and lon used as initia... |
import os
import sys
import shutil
import math
#import simplekml
import UTM as con
def run(src,dest):
# src=a[0]
# dest=a[1]
files=os.listdir(src)
print src
print dest
print files
dest_files=os.listdir(dest)
print dest_files
for dest_file in dest_files:
full_dest=os.... |
from urllib.parse import urlencode
import requests # todo: make this a service so we can substitute it ?
from bonobo.config import Configurable, Option
from bonobo.context import ContextProcessor, contextual
from bonobo.util.compat import deprecated
from bonobo.util.objects import ValueHolder
def path_str(path):
... |
import maya.cmds as cmds
import math
class HUDClass:
def __init__(self):
self.functions = []
if cmds.headsUpDisplay('SnapButton', exists = True):
cmds.headsUpDisplay('SnapButton', rem = True)
cmds.hudButton('SnapButton', s=7, b=5, vis = False, l='Snap I... |
#!/usr/bin/python
#
# Demonstration of getting the temperature reading from the LPS25H
#
from datetime import datetime
from time import sleep
from altimu.altimu import AltIMU
imu = AltIMU()
imu.enable_temperature()
print(" Temperature in Celsius: \t" + str(imu.getTemperatureCelsius()))
print(" Temperature in Fahre... |
#
#
# perBRENDAExtract.py
#
# Date: 9/28/20
#
# PER BRENDA: Parse and Extract tool for Machine Learning applications using the BRENDA Database
#
# Gian Marco Visani1,&, Thomas McNulty1,&, and Soha Hassoun1,2,*
#
# 1 Department of Computer Science, Tufts University, 161 Colle... |
# TODO: Quite flaky
# TODO: buffs, effects
# TODO: zerg morhps, cocoons are bypassed now
from pathlib import Path
import toml
import json
from sc2.bot_ai import BotAI
from sc2.data import Race
from sc2.main import run_game
from sc2.player import Bot
from sc2 import maps
from sc2.ids.upgrade_id import UpgradeId
from... |
def sum(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
return a / b
def selector(a, b, c):
if c == 1:
return sum(a, b)
elif c == 2:
return subtract(a, b)
elif c == 3:
return multiply(a, b)
elif c == ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.