text stringlengths 8 6.05M |
|---|
#Purpose: To utilized closed-form solutions to determine the accuracy of the CalculiX solution for T3D2 elements.
#Date: July 9th, 2018
#Programmer: Garrett M. Kelley
#Define the variables
L = 100 #Beam length
h = 10 #Beam height
w = 5 #Beam width
P = 500
E = 29e6 #Young's Modulus
I = h**3*w/12
#Calculate the displac... |
from keras.models import Model, Input
from keras.layers import Dense, Dropout, BatchNormalization
from keras.utils import to_categorical
from sklearn.datasets import load_breast_cancer
import numpy as np
cancer = load_breast_cancer()
x = cancer.data
y = cancer.target
# y = to_categorical(y)
# print(y)
# print(... |
# Import libraries
import numpy
import os, json, datetime, sys
from operator import attrgetter
from azureml.core import Workspace
from azureml.core.model import Model
from azureml.core.image import Image
from azureml.core.webservice import Webservice
from azureml.core.authentication import AzureCliAuthentication
# Get... |
#!/usr/bin/env python
# encoding: utf-8
"""
Created by 'bens3' on 2013-06-21.
Copyright (c) 2013 'bens3'. All rights reserved.
"""
import re
import luigi
from collections import OrderedDict
from pymongo import MongoClient
from ke2mongo import config
def mongo_client_db(database=config.get('mongo', 'database'), host=... |
import unittest
class TestMethods(unittest.TestCase):
def test_string_to_list(self):
self.assertEqual(list('abcd'), ['a', 'b', 'c', 'd'])
def test_string_to_int(self):
self.assertEqual(int('5'), 5)
with self.assertRaises(ValueError):
int('a')
if __name__ == '__main__':
... |
# Mini-project #6 - Blackjack
import simplegui
import random
# load card sprite - 949x392 - source: jfitz.com
CARD_SIZE = (73, 98)
CARD_CENTER = (36.5, 49)
card_images = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/cards.jfitz.png")
CARD_BACK_SIZE = (71, 96)
CARD_BACK_CENTER = (3... |
#!/usr/bin/env python
from __future__ import print_function
import fastjet as fj
import fjcontrib
import fjext
import tqdm
import argparse
import os
from heppy.pythiautils import configuration as pyconf
import pythia8
import pythiafjext
import pythiaext
import ROOT as r
import array
import random
from pyjetty.mpu... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 15 16:08:08 2019
@author: Dell
"""
import torch
from torch.autograd import Variable
import torchvision
import torchvision.transforms as transforms
import os
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import matplotlib.pyplot as plt
... |
from flask import Flask
app = Flask(__name__)
# import json
from model import (
session as db_session,
User,
Book,
Location,
)
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
@app.route("/pins", methods=['POST'])
def create_pin():
'''
This function adds a pin ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 16/4/23 下午2:50
# @Author : ZHZ
# @Description : 根据num_days去划分数据集,默认值是14
import pandas as pd
import numpy as np
import datetime
global sum_flag
num_days = 7
sum_flag_temp = 0
days_20141009 = datetime.datetime(2014, 10, 9)
item_id_dict = {}
all_item_sum = []
... |
import flask
from flask_restful import Resource
from flask import request, jsonify, redirect, Response
from models.models import *
class ChatbotAPI(Resource):
def get(self):
if "id" in request.args:
model = TrainedModel.query.filter_by(id=request.args["id"]).first()
model_schema = ... |
n = int(input())
paises = dict()
for i in range(n):
linha = input().split()
if paises.__contains__(linha[0]):
paises[linha[0]] += 1
else:
paises[linha[0]] = 1
dic = dict(sorted(paises.items()))
for k in dic:
print(k, dic[k])
|
import numpy as np
from .._common import jitted
@jitted
def normc(ee, nmat):
"""Normalize Haskell or Dunkin vectors."""
t1 = 0.0
for i in range(nmat):
t1 = max(t1, np.abs(ee[i]))
if t1 < 1.0e-40:
t1 = 1.0
for i in range(nmat):
ee[i] /= t1
ex = np.log(t1)
return ... |
list = ['abcd', 786, 2.23, 'runoob', 70.2]
tinylist = [123, 'runoob']
print(list) # 输出完整列表
print(list[0]) # 输出列表第一个元素
print(list[1:3]) # 从第二个开始输出到第三个元素
print(list[2:]) # 输出从第三个元素开始的所有元素
print(tinylist * 2) # 输出两次列表
print(list + tinylist) # 连接列表\
print("\n********************************\n")
#列表中的元素是可以改变的
a = [... |
import serial
import time
import datetime
import MySQLdb
ser = serial.Serial(
port='COM3',\
baudrate=9600,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout=0)
print("connected to: " + ser.portstr)
conn = MySQLdb.connect(host= "localhost",
... |
print('Display text')
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from logging import getLogger
__author__ = 'golden'
__create_date__ = '2018/5/26 22:23'
class Request(object):
def __init__(self, url, callback):
self.url = url
self.callback = callback
self.logger = None
def set_logger(self):
self... |
#!/usr/bin/env python3
import cgi
from mysql_utils import get_connection
try:
# Gets ID from URL
fields = cgi.FieldStorage()
combatant_id = fields.getvalue("id")
sql = "SELECT combatant.name, species.name," \
"(combatant.plus_atk + species.base_atk)," \
"(combatant.plus_dfn + speci... |
from flask import Flask, request
from twilio.rest import Client
from github import Github, GithubException
app = Flask(__name__)
# contents = repo.get_commits_traffic(per="week")
sid = "AC3de35d6b4b5246a899bade4f33c1fe8b"
token = "816d65fc8f364d4b1acdb0f4fec59765"
client = Client(sid, token)
fromWhatsApp ... |
print "Is it true that 3 + 2 < 5 - 7 ?"
print 3 + 2 < 5 - 7
print 1.0/3
print 5%3.0 |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 3 13:08:19 2020
@author: vernika
"""
from __future__ import print_function
import cv2
import argparse
def show_img(img):
cv2.imshow("canvas",img)
cv2.waitKey(0)
return
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", requi... |
from selenium import webdriver
import time
driver=webdriver.Chrome()
driver.get('https://mail.163.com/')
time.sleep(3)
'''#先于iframe找到父元素,且点击不可触及的页面
driver.find_element_by_xpath("//*[@id='lbNormal']").click()
#找到所有的iframe
m=driver.find_elements_by_tag_name("iframe")
#跳转到iframe的列表中多个的某一个,用序号
driver.switch_to_frame(m[0])'... |
# -*- coding: utf-8 -*-
from openerp import api, fields, models, _
# Product template
class product_template(models.Model):
_inherit = 'product.template'
@api.model
def default_get(self, fields):
rec = super(product_template, self).default_get(fields)
rec['type'] = 'product'
r... |
import pygame
import sys
from pygame.locals import *
import time
from lib.player import Player
from lib.fallingShit import FallingShit
WINDOW_WIDTH = 1280
WINDOW_HEIGHT = 736
white = (255, 255, 255)
black = (0, 0, 0)
blue = (0, 0, 128)
class App:
def main(self):
pygame.init()
self.DISPLAYSURF ... |
import requests
url = 'https://restcountries.eu/rest/v2/regionalbloc/asean'
myobj = {'name':'Myanmar'}
x = requests.post(url, data = myobj)
#print the response text (the content of the requested file):
print(x.text) |
class MarketState(object):
"""
This class models the state of an instrument in the market
Attributes:
bid: bid price
ask: bid price
"""
def __init__(self,bid,ask):
self.bid=bid
self.ask=ask
def update_bid_ask(self,new_bid,new_ask):
self.bid=new_bid
... |
import cv2
input = cv2.imread("./Desktop/OpenCV/Basics/hand.jpg",0)
cv2.imshow("Grayscale image",input)
cv2.waitKey()
cv2.destroyAllWindows()
|
a = 1
b = 2
c = 3
my_sum = a + b
another_sum = 5 + 10
maths_operators = 1 + 3 * 4 / 2 - 2
print(maths_operators)
float_division = 12 / 3
print(float_division)
integer_division = 12 // 3 # drops anything after the decimal (no rounding!)
print(integer_division)
division_with_reminder = 12 // 5 # should be 2.4
prin... |
#-*- coding: utf-8 -*-
from django.contrib import admin
from models import Assinante
class AssinanteAdmin(admin.ModelAdmin):
list_display = ('email', 'data_assinatura', )
search_fields = ('email', 'data_assinatura', )
admin.site.register(Assinante, AssinanteAdmin)
|
# -*- coding: utf-8 -*-
"""
smartwall.base
~~~~~~~~~~~~~~
This module contains building blocks for the REST api such as:
* Error classes
* Base class for views
* Decorators
:author: Felipe Blassioli <felipe.blassioli@vtxbrasil.com.br>
"""
from functools import wraps
from flask import requ... |
import analysis
import master
FOLDER_ROOT_LOCATION = "/Users/wxp/Downloads/PHASE ONE CODED"
if __name__ == '__main__':
# Merge to a file
output_path, records_count = master.merge_excel_sheet(FOLDER_ROOT_LOCATION)
# Create analysis sheet
analysis.create_analysis_sheet(output_path, records_count)
|
import json
from simple_slack_bot.slack_request import SlackRequest
def get_thread_ts(data: SlackRequest, target):
json_data: dict = json.loads(str(data))
if target in json_data:
return json_data[target]
|
'''
Created on 28 jan. 2014
@author: Pieter
'''
from PIL import Image
class Card():
'''Objectholder for the cards in Dunqeun Petz'''
standards = {"red":"anger","green":"food","purple":"magic","yellow":"play"} #standard needs for a color
def __init__(self,color,need):
'''Card(string color [,string... |
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2021/4/8 19:07
# @Author :'liuyu'
# @Version:V 0.1
# @File :
# @desc :
import os
import tensorflow as tf
# tf2 --> tf1
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from .data_load import get_batch
from .model import Transformer
from .hparams imp... |
from tg import tmpl_context
import moksha.api.widgets
from tw2.jqplugins.ui import set_ui_theme_name
import decorator
def with_moksha_socket(f, *args, **kw):
tmpl_context.moksha_socket = moksha.api.widgets.moksha_socket
return f(*args, **kw)
def with_ui_theme(f, *args, **kw):
set_ui_theme_name('hot-sneak... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
mi_cadena = "Hola Mundo"
def adios():
print "Chao"
|
#!/usr/bin/env python
#! -*- coding:utf-8 -*-
#!@Author: faple
#!@Time: 2019/4/2 9:04
import configparser
import os
config = configparser.ConfigParser()
# 初始化
def init():
config.read(os.path.join(os.path.dirname((os.path.dirname(__file__))), 'conf/config.ini'))
# 获取值
def getValue(type, key):
init()
retu... |
# creating Employee class
class Employee:
count_emp = 0 # count of Employees
total_emp_salary = 0 # total salary of employees
# Creating a constructor to initialize name, family, salary, department
def __init__(self, name, family, salary, department):
... |
def next_avaible_drone_in(position, drones):
return min(drones, key=lambda d: d.ends_in_target(position))
def closest_warehouse_that_fulfills_needs(order, warehouses):
def distance(warehouse):
return warehouse.distance(order)
sorted_warehouses = sorted(warehouses, key=distance)
for warehouse... |
# -*- test-case-name: mimic.test.test_util -*-
#
"""
Helper methods
:var fmt: strftime format for datetimes used in JSON.
"""
from __future__ import absolute_import, division, unicode_literals
import binascii
import os
import string
import calendar
from datetime import datetime, timedelta
import json
from random imp... |
import sys
import re
from bot_feature import *
if __name__ == '__main__':
print(miaow(sys.argv[1]))
|
from rubicon_ml.viz.dashboard import Dashboard
from rubicon_ml.viz.dataframe_plot import DataframePlot
from rubicon_ml.viz.experiments_table import ExperimentsTable
from rubicon_ml.viz.metric_correlation_plot import MetricCorrelationPlot
from rubicon_ml.viz.metric_lists_comparison import MetricListsComparison
__all__ ... |
#Aim :- To understanding the gradients and various operators to detect edges
#Reference - Udacity introduction to computer vision lesson 2A-L5
try:
import cv2
import numpy as np
from matplotlib import pyplot as plt
except :
print ("please install the dependencies \n using command pip3 install requireme... |
#Lists
'''
1. Stored collection of different data types
2. We can modify
3. Mutable
4. Addressing(Indexing) in order manner
5. Random access possible
6. Duplicate possible
---------------------
MyList=[45,67.89, 4+9j,"Data",True,None]
print(MyList)
print("\nList access using possitive index")
print(MyList[0])
print... |
import re
import logging
import atomacos
import pyautogui
import atomacos.errors
from utils.FileUtils import FileUtils
from AutoTradingService.AutoRefresh import AutoRefresh
class AutoOrder(FileUtils):
def __init__(self):
super().__init__()
logging.info('@ Start Auto Order Service ... ')
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
delete_language_element_permanent_query = "DELETE FROM public.language AS lng WHERE lng.id = $1 RETURNING *;"
delete_language_element_query = """
UPDATE public.language AS lng SET deleted = TRUE,
active = FALSE WHERE lng.id = $1 RETURNING *;
"""
|
# Copyright 2017 The Forseti Security Authors. All rights reserved.
#
# 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 ap... |
import sys
import pytest
import shutil
try:
import pycuda.driver as drv
drv.init()
cuda_present = True
except Exception:
cuda_present = False
try:
import pyopencl
opencl_present = True
if 'namespace' in str(sys.modules['pyopencl']):
opencl_present = False
if len(pyopencl.get_p... |
import json
from datetime import datetime, timedelta
from django.db import transaction,DatabaseError
from quicklook.models import UserQuickLook
from leaderboard.models import Score
def _get_lst(lst,i,default = None):
""" get method for list similar to dictionary's get method """
try:
return lst[i];
except Inde... |
class Pokemon(object):
def __init__(self, data):
self.id = data['id']
self.cp = data['cp']
self.pokemon_id = data['pokemon_id']
self.data = data
def release(self, api):
return api.release_pokemon(pokemon_id=self.id)
|
# -*- coding: utf-8 -*-
from math import sqrt, acos, pi
import math
from decimal import Decimal, getcontext
import numpy
from decimal import Decimal
class Vector(object):
"""
This class gives simple functionalities related to a Vector
params:
coordinates: tuple of vector values
dimensi... |
from django.db import models
from analytics_project import settings
# РПД
class WorkProgramInFolder(models.Model):
RATING_CHOICES = [
(0, 0),
(1, 1),
(2, 2),
(3, 3),
(4, 4),
(5, 5),
]
folder = models.ForeignKey('Folder', verbose_name='Папка', on_delete=mode... |
from . import db
#db.create_all()
#from werkzeug.security import generate_password_hash
class Properties(db.Model):
# You can use this to change the table name. The default convention is to use
# the class name. In this case a class name of UserProfile would create a
# user_profile (singular) table, but if... |
from django.urls import path
from .views import *
urlpatterns = [
#api
path('synchronize/',Synchronize.as_view()),
path('set_price/',SetPrice.as_view()),
path('set_stock/',SetStock.as_view()),
path('rest/',Rest.as_view()),
path('start/',Start.as_view()),
] |
#!/usr/bin/python3.4
# -*-coding:Utf-8 -*
year = input("Which year you want to check ...")
answer = False
int(year)
if year % 4 != 0 :
answer = False
elif year % 100 == 0 :
if year % 400 == 0 :
answer = True
else :
answer = False
else :
answer = True
if answer == True :
print("Yes it is a bissextile year ... |
import os
import chainer
import chainer.functions as F
import chainer.links as L
import numpy as np
import onnx
import pytest
from onnx_chainer import export_testcase
@pytest.fixture(scope='function')
def model():
return chainer.Sequential(
L.Convolution2D(None, 16, 5, 1, 2),
F.relu,
L.C... |
import cv2
import numpy as np
video = cv2.VideoCapture(0)
while True:
ret, frame = video.read()
cv2.imshow(frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video.release()
cv2.destroyAllWindows() |
from __future__ import absolute_import
import json
from pyes.query import MatchAllQuery
def dump_docs(fp, conn, index_name, doc_type, scroll='5m', encoding='utf8'):
q = MatchAllQuery()
for result in conn.search(q, indices=[index_name], doc_types=[doc_type],
scan=True, scroll=scro... |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import unittest
fro... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# File: w2v_to_numpy.py
# Convert binary W2V file to
import sys, struct, os
import cPickle, gzip
import numpy as np
class HiddenLoader:
def __init__(self, fname):
f = open(fname, 'rb')
header = f.readline().decode('utf-8').strip()
self.rows, self.co... |
import gobject
gobject.threads_init()
import pygst
pygst.require("0.10")
import gst
from httplib import HTTP
from urlparse import urlparse
class BlankAudioSrc (gst.Bin):
def __init__ (self, wave = 4):
gst.Bin.__init__(self)
audiotestsrc = gst.element_factory_make("audiotestsrc")
audiotestsrc.set_property("wave"... |
# program to resize all train images
import os
import glob
from PIL import Image
from joblib import Parallel, delayed
in_dir = '../train_images/'
out_dir = 'train512/'
IMAGE_SIZE = 512
JPG_FILES = glob.glob(in_dir + '*.jpg')
def convert(img_file):
im = Image.open(img_file)
im.resize((IMAGE_SIZE, IMAGE_SIZE... |
def iterative_fibonacci(position):
"""Find a position in the Fibonacci sequence iteratively.
Time complexity: O(n)
Space complexity: O(1)
"""
if (position <= 1):
return position
first = 0
second = 1
next = first + second
for i in range(2, position):
first = second
... |
from flask import Flask , render_template , request
from flask import jsonify
import pafy
import vlc
app = Flask(__name__)
Instance = vlc.Instance('--no-video')
player = Instance.media_player_new()
url = ''
@app.route('/')
def index():
return render_template('index.html')
@app.route('/song', methods=['GET'])
def... |
from django.conf.urls import url, include
from django.urls import path
from .import views
urlpatterns = [
path('', views.index, name='index'),
path('inicioSesion', views.inicioSesion, name='inicioSesion'),
path('perfil', views.perfil, name='perfil'),
url(r'^signup', views.signup, name='signup'),
... |
import tkinter as tk
from tkinter import messagebox
def insertpoint():
var = e.get()
t.insert('insert', var)
def insertend():
var = e.get()
t.insert("end", var)
root = tk.Tk()
root.geometry("400x400+400+400")
root.title("无架构的GUI程序")
btn01 = tk.Button(text='insert point', command=insertpoint)
btnq... |
n1 = int(input('Digite o primeiro termo da PA: '))
r = int(input('Digite a razão da PA: '))
n = n1
for c in range(1, 11):
n = n1 + r*(c-1)
print(n, end=' -> ')
print('fim')
|
import json
import csv
import boto3
import json
import dateutil.parser
import datetime
import time
import os
import math
import random
import logging
import create_instance
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
def close(session_attributes, fulfillment_state, message):
response = {
... |
# Generated by Django 2.1.2 on 2018-11-26 04:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('prediksi', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='prediksi',
name='temp_jumlah_mahasiswa... |
from selenium import webdriver
'''
URL = 'https://www.miraeassetdaewoo.com/hki/hki3028/r01.do'
driver = webdriver.Chrome(executable_path='chromedriver')
driver.get(url=URL)
driver.implicitly_wait(time_to_wait=5)
'''
driver = webdriver.Chrome('H:\chromedriver.exe')
driver.get('https:/... |
# -*- coding:utf-8 -*-
# http://www.math.pku.edu.cn/teachers/lidf/docs/textrick/index.htm
import urllib2
import re
import os
import csv
'''
csvfile = file('sample.csv', 'rb')
reader = csv.reader(csvfile)
code_list=[]
line_num=0
for line in reader:
line_num=line_num+1
if line_num>150 and line_num<301:
... |
import os
import sys
import unittest
import mockings
path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../core'))
sys.path.insert(1, path)
from now import Now
import chords
class TestShouldRun(unittest.TestCase):
def testModuleWithoutShouldRunMethod(self):
now = Now(tweak = "2015-01-01 12:00:00")
... |
# Let S be a list of permutations of 0, 1, 2, ..., 9 which are sorted in
# ascending order.
# Find S[10^6]
# Define permu(n, D) = S[n] which is the n-th permutation in S where D is
# the set of possible digits.
#
# Let M = |D|
# permu(n, D) = 'i' + permu(n - (M! - (M + 1)!), D\{i})
# for k <= i in S wher... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the sockMerchant function below.
def sockMerchant(n, ar):
x = 0
banco = []
for s in ar:
if s in banco:
continue
else:
x += int(ar.count(s) / 2)
banco.append(s)
return ... |
'''
Created on Sep 6, 2015
@author: hugosenari
'''
from circuits import Component
from circuits import task
def show_window_gtk():
from gi.overrides.Gtk import Gtk
class MyWindow(Gtk.Window):
def __init__(self):
super().__init__(title="Hello World Gtk")
self.button =... |
from model.database import *
from model.simulator import Simulator
from model.crops.storage import Storage
from model.crops.itemsprocessor import ItemsProcessorManager
import pandas as pd
import matplotlib.pylab as plt
if __name__ == '__main__':
simulator = Simulator()
database = Database()
database.ini... |
import re
from django import forms
from django.forms import ModelForm
from .models import Mascota, Busqueda, Persona, Adopcion
# Formulario de inicio de sesion.
class IniciarSesionForm(forms.Form):
username = forms.CharField(
widget=forms.TextInput(), label="Nombre de Usuario")
password = fo... |
def knapsack(value, weight, capacity):
#index list with size of number of values
ind = list(range(len(value)))
#ratio list containing ratio's of value & weight
ratio = [v/w for v, w in zip(value, weight)]
#sorting the index list based on the ratio's in non-decreasing order
ind.sort(key=... |
# import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2
import numpy as np
from cv2 import aruco
def aruco_detection():
# start video capture for distance
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
... |
#!/usr/bin/env python
# -*- encoding=utf-8 -*-
"""
Sync from server to local machine on both Win & Linux
Add config in sync.cfg to config the sync parameters
and make sure you add your pub key to authorized_keys on remote
server.
"""
import os
import sys
import ConfigParser
class Syncer():
def __init__(self):
... |
import unittest
from katas.kyu_6.multi_tap_keypad_text_entry import presses
class PressesTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(presses('LOL'), 9)
def test_equals_2(self):
self.assertEqual(presses('HOW R U'), 13)
def test_equals_3(self):
self.assert... |
from _typeshed import Incomplete
def hnm_harary_graph(n, m, create_using: Incomplete | None = None): ...
def hkn_harary_graph(k, n, create_using: Incomplete | None = None): ...
|
"""
corpkit: Interrogate a parsed corpus
"""
#!/usr/bin/python
from __future__ import print_function
from corpkit.constants import STRINGTYPE, PYTHON_VERSION, INPUTFUNC
def interrogator(corpus,
search,
query='any',
show='w',
exclude=False,
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 16 14:42:34 2019
Lsplane.py Least square regression plane
INPUT
X array [X Y Z] where x = vector of x coordinates, y = y coords, z = z coords
output
x0 =centroid of the data = point on the best fit plane
dim 3x1
a = direction cosines of the normal to the best-fit plan... |
import itertools
import pandas as pd
class FPNode(object):
def __init__(self, name, value, children, parent):
self.name = name
self.value = value
self.children = children
self.parent = parent
self.next = None
def __repr__(self):
return "{}: {}".format(self.name,... |
import tensorflow as tf
from tensorflow.keras import Model
from constants import anchor_size, feature_size
class RoiPooling(Model):
def call(self, features_map, boxes):
output = []
for box in boxes:
x1 = box[0]
y1 = box[1]
x2 = box[2]
y2 = box[3]
... |
from datetime import timedelta
a = timedelta(days=2, hours=6)
b = timedelta(hours=4.5)
c = a + b
print c.days
print c.seconds
print c.seconds / 3600
print c.total_seconds() / 3600
from datetime import datetime
a = datetime(2012, 9, 23)
print a + timedelta(days=10)
b = datetime(2012, 12, 21)
d = b - a
print d.days... |
def testData():
otest = open('test.txt', 'r')
test = otest.readlines()
oanswer = open('answer.txt', 'r')
answer = oanswer.readline()
status = False
print("Runs test data")
result = runCode(test)
if result == int(answer): #not always int
status = True
print("Correct... |
# Generated by Django 2.2.13 on 2020-07-09 17:37
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('shop', '0027_auto_20200709_2246'),
]
operations = [
migrations.DeleteModel(
name='About1',
),
migrations.DeleteModel(
... |
# -*- coding: utf-8 -*-
"""
**************************************************************************
* IMAGE PROCESSING (e-Yantra 2016)
* ================================
* This software is intended to teach image processing concepts
*
* MODULE: Task1C
* Filename: task1-main.py
* ... |
# python2 kmlwriter.py --agency_id 'BART' --style_csv_path './route_styles/Current_15.csv' sample_feeds/BA_gtfs.zip move_bay_area_bus_maps/bart_current_15_map.kml
# python2 kmlwriter.py --agency_id 'Muni' --style_csv_path './route_styles/Current_15.csv' sample_feeds/SF_gtfs.zip move_bay_area_bus_maps/muni_current_15_ma... |
'''
Introduction to Secant Methods in Python -- Regula Falsi
Name: Kevin Trinh
Goal: Find the root of log(3x/2)
'''
import math
import scipy as sp
def func(x):
'''The function that we are finding the root of.'''
return sp.log(1.5 * x)
def regulaFalsi(a, b, tol=1e-15, maxiter=1000):
'''Per... |
from epidemioptim.environments.models.prague_ode_seirah_model import PragueOdeSeirahModel
list_models = ['prague_seirah']
def get_model(model_id, params={}):
"""
Get the epidemiological model.
Parameters
----------
model_id: str
Model identifier.
params: dict
Dictionary of expe... |
import sqlite3
from sqlite3 import Error
import numpy as np
import pandas as pd
from datetime import datetime, time
def create_connection(db_file):
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return conn
def fetch_slots(conn):
... |
from sublime import Region
from .str_utils import get_quote, get_prefix
from .settings_utils import get_root_prefix, get_scope_prefix
from .paths import get_cur_proj, get_scopes, is_valid_root, is_valid_scope
import re
def get_module_specifier(strs):
ret = re.findall(r'(import|export|require)', strs)
if not ... |
# Generated by Django 2.2.7 on 2020-01-14 13:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('statics', '0012_auto_20191231_1330'),
]
operations = [
migrations.AlterField(
model_name='review',
name='content',
... |
from utils.data import *
from config import *
def main():
preprogress(foreground_data)
if __name__ == '__main__':
main()
|
__author__ = "Narwhale"
# def get_formatted_name(first,last):
# '''合并姓名'''
# full_name = first + ' ' + last
# return full_name.title()
#
#------------------------------------------------------
def get_formatted_name(first,last,moddle=''):
'''合并姓名'''
if moddle:
full_name = first + ' ' ... |
#Li Xin
#Student number: 014696390
#xin.li@helsinki.fi
import sys
import socket
import random
import threading
import os
import listy
def send_mouse(mouse_port, mouse_node):
command = 'ssh xgli@' + mouse_node + \
' python3 /cs/home/xgli/Distributed_System_Exercise_2016/big_exercise_2/mouse.py ' + mouse_port
os.s... |
rt = 0
pt = 0
for _ in range(10):
cinout = list(map(int, input().split()))
pt += cinout[1] - cinout[0]
if pt > rt:
rt = pt
print(rt)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.