text stringlengths 8 6.05M |
|---|
import matplotlib.pyplot as plt
import numpy as np
radius, modulo, multiplier = 1, 360, 13
ax = plt.gcf().gca()
ax.set_aspect('equal')
ax.add_artist(plt.Circle((0, 0), radius, edgecolor='r', facecolor='w'))
plt.xlim(-radius-0.1, radius+0.1)
plt.ylim(-radius-0.1, radius+0.1)
x_points, y_points = [], []
for i in range(m... |
# O(n^3) solution.
class Solution(object):
def getMoneyAmount(self, n):
"""
:type n: int
:rtype: int
"""
# matrix[i][j] is the minimal amount of money to guarantee a win when
# the range of number to guess is [1, n]. Note that we has an extra row
# at the bott... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# this script serves to integrate classifier
# and cluster scripts
#
# @author Yuan JIN
# @contact chengdujin@gmail.com
# @since 2012.03.16
# @latest 2012.03.18
#
# reload the script encoding
import sys
reload(sys)
sys.setdefaultencoding('UTF-8')
# CONSTANTS
DB = '176.3... |
# -*- coding:utf-8 -*-
import re
import os
import subprocess
# os.system('svn diff -r 6830:6840 --summarize https://10.1.8.191/svn/shyycg_src/YSXT/trunk/ysxt')
def run(project_dir, date_from, date_to, search_key, file_name):
""" 处理log """
log_dic = {}
try:
os.chdir(project_dir) # 定位当前目录到项目路径
... |
# 오류 예외 처리 기법
"""
1 번째 방법
try:
...
except :
...
2 번째 방법
try:
...
except 발생 오류 :
...
3 번째 방법
try:
...
except 발생오류 as 오류 메시지 변수:
...
"""
print('에러 발생 : ')
try:
4/0
except ZeroDivisionError as e:
print(e)
print()
# try .. else
print('try .. else')
try:
f... |
import sys
sys.path.append("/home/nick/Github/Controls/RaspberryPi/")
sys.path.append("/home/nick/Github/DataLogger")
from RaspberryPi.rpy_pid_controller.Feb27test_pid_shell import pid_wrapper
from RaspberryPi.rpy_motorcontroller.MotorController_hat import MotorController
from RaspberryPi.rpy_pid_controller.devices.mpu... |
from .base import Base
from models import Student
from components import Methods
class StateAskAuthCorrectness(Base):
def __init__(self, state_controller):
super().__init__(state_controller)
self.response_phrases = {
"yes": [
"Да"
],
"no": [
... |
import pygame
import random
import panda
S = [['.....',
'......',
'..00..',
'.00...',
'.....'],
['.....',
'..0..',
'..00.',
'...0.',
'.....']]
Z = [['.....',
'.....',
'.00..',
'..00.',
'.....'],
['.....',
'..0... |
import torch
def gather_elementwise(tensor, idx_tensor):
'''
For `tensor.shape = tensor_shape + (K,)`
and `idx_tensor.shape = tensor_shape` with elements in {0,1,...,K-1}
'''
return tensor.gather(-1, idx_tensor[..., None])[..., 0]
|
from onegov.core.utils import normalize_for_url, is_uuid
from onegov.newsletter import Newsletter, Recipient
from onegov.newsletter.errors import AlreadyExistsError
from typing import Any, TYPE_CHECKING
if TYPE_CHECKING:
from datetime import datetime
from sqlalchemy.orm import Query, Session
from uuid imp... |
from datetime import datetime
from slacker import Slacker
from app import db, slackconnect
from datetime import timedelta
from app.model import message, slack_user, message_channel
from flask import Flask, Request
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import desc
import collections, sys
class Message... |
from requests import Session
from bs4 import BeautifulSoup
from torrents_parser.proxy import read_proxy
import pickle
from torrents_parser.exceptions import LoginError
from torrents_parser.login_data import *
def get_captcha(page):
soup = BeautifulSoup(page.content, 'lxml')
form = soup.find('table', {'class'... |
import yaml
file = open("familyinfo.yaml")
data = yaml.load(file)
print(data)
print(data["name"])
print(data["age"])
print(data["spouse"])
print(data["spouse"]["name"])
print(data["spouse"]["age"])
print(data["children"])
print(data["children"][0]["name"])
print(data["children"][0]["age"])
print(data["children"][... |
from django.urls import path
from rest_framework_simplejwt.views import TokenRefreshView, TokenObtainPairView
from .views import AllPosts, PostDetail, PostCreate, UpdatePost, SearchPost, PostDelete, AllUsers, UserProfile, \
UserDetail, UserDelete
app_name = 'apis'
urlpatterns = [
# token
path('api/token/'... |
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.core.validators import ValidationError
def validateEmail(email):
try:
User.objects.get(email=email)
except User.DoesNotExist:
raise ValidationError(" Invaid... |
from setuptools import setup
setup(name='pkgtest',
version='1.0.0',
description='A print test for PyPI',
author='winycg',
author_email='win@163.com',
url='https://www.python.org/',
license='MIT',
keywords='ga nn',
packages=['pkgtest'],
install_requires=['numpy>=1.1... |
import argparse
io_parser = argparse.ArgumentParser(add_help=False)
io_parser.add_argument(
"-i",
"--input-files-dir",
help="Path of the directory containing the files to be converted.",
type=str,
action="store",
dest="input_dir",
required=True,
)
io_parser.add_argument(
"-o",
"--ou... |
#encoding='utf-8'
import sys
from datetime import datetime
from django.shortcuts import render
from django.http import HttpResponse,Http404
from .models import Article
# Create your views here.
reload(sys)
sys.setdefaultencoding('utf-8')
def home(request):
post_list = Article.objects.all()
return render(reques... |
#!/usr/bin/python
"""
Starter code for the evaluation mini-project.
Start by copying your trained/tested POI identifier from
that which you built in the validation mini-project.
This is the second step toward building your POI identifier!
Start by loading/formatting the data...
"""
import pickl... |
import tensorflow as tf
import scipy.sparse as sp
import numpy as np
def normalized_adj(adj):
adj = sp.coo_matrix(adj)
rowsum = np.array(adj.sum(1))
d_inv_sqrt = np.power(rowsum, -0.5).flatten()
d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.
d_mat_inv_sqrt = sp.diags(d_inv_sqrt)
normalized_a... |
#!/usr/bin/python
#\file follow_q_traj1.py
#\brief Baxter: follow a joint angle trajectory
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Oct.08, 2015
'''
NOTE: run beforehand:
$ rosrun baxter_interface joint_trajectory_action_server.py
'''
import roslib
import rospy
import actionlib
imp... |
#!/usr/bin/python3
"""
Module with add_integer function
Function that adds two numbers
This module only has one function
"""
def add_integer(a, b=98):
"""
add_integer
"""
if type(a) is not int and type(a) is not float:
raise TypeError('a must be an integer')
if type(b) is not i... |
import math
import chainer
import chainer.functions as F
import numpy as np
from time_axis_rcnn.constants.enum_type import TwoStreamMode
from time_axis_rcnn.model.time_segment_network.faster_rcnn_train_chain import _fast_rcnn_loc_loss
class Wrapper(chainer.Chain):
def __init__(self, time_seg_train_chain, two_str... |
import sys
sys.path.append("/home/lixueting/Documents/caffe/python")
import caffe
|
import datetime
from datetime import timedelta
from ..models import AccountReminding
def update_reminder_emails(account, email):
""" Update reminder and in the loop emails.
@type account: accounts.models.Account
@type email: unicode
"""
account.reminder_email = email
account.in_the_loop_email... |
def main():
import math
a = float(input("digite seu primeiro x: "))
b = float(input("digite seu primeiro y: "))
c = float(input("digite seu segundo x: "))
d = float(input("digite seu segundo y: "))
def distancia(x1,y1,x2,y2):
dist = math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
return dist
distance = distancia... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
from crawler import run_crawler
stocks = ['$GOOG', '$WINS', '$GV', '$CC', '$KEM', '$CWEI', '$ZIONW', '$AMD', '$REN', '$STI.B', '$CRBP', '$EVI', '$EXEL', '$TWNKW', '$GST-B', '$LNTH', '$GST-A',
'$AKAO', '$TROX', '$VAL.P', '$OIB.C', '$TELL', '$NRP', '$A... |
# encoding: utf-8
"""
@desc: Chunk corpus into batches that source sentences inside one batch are similar to each other.
todo: use better vector-representation than tf-idf
"""
import argparse
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
import scipy
from tqdm import tqdm
from typin... |
def stupid_sort(data):
i, size = 1, len(data)
while i < size:
if data[i - 1] > data[i]:
data[i - 1], data[i] = data[i], data[i - 1]
i = 1
else:
i += 1
return data
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-08-16 10:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('nova', '0004_asset_configs'),
]
operations = [
migrations.CreateModel(
... |
import database as dbs
db = dbs.getDatabase()
def on():
s = dbs.Setting.select().where(dbs.Setting.key==dbs.Setting.RECORD_EVENTS).get()
s.value = "1"
return s.save()
def off():
s = dbs.Setting.select().where(dbs.Setting.key==dbs.Setting.RECORD_EVENTS).get()
s.value = "0"
return s.save()
... |
import sys
from PIL import Image
import ImageFilter
import numpy
import PIL.Image
from numpy import array
import copy
import scipy
import os
import mysql.connector
import cStringIO
import base64
WIDTH = 0
HEIGHT = 0
SIZE = 0
TOU = 0
path='C:/Users/Abhi/Desktop/cbirfinalproject/project/retrieved/'
ext='.jpg'
pi='C:/U... |
# Copyright (c) 2020 Matthew Rossi
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distr... |
import random
from PyQt4 import QtCore, QtGui
from src.gfx.grid import Grid
from src.actors.Human import Human
from src.actors.Tree import Tree
from src.actors.Block import Block
class World(QtGui.QFrame):
# Should we render the grid?
show_grid = True
# How dense is the world grid?
grid_density = 50
# How often s... |
from mitm import color
import requests
def get_ip(protocol):
return requests.get(
f"{protocol}://api.ipify.org?format=json",
proxies={"http": "127.0.0.1:8888", "https": "127.0.0.1:8888"},
verify=False,
).text
print(color.green("HTTP Reply:\n"), get_ip(protocol="http"), "\n")
print(co... |
import unittest
import Entity
import weapon
class TestsEntity(unittest.TestCase):
def setUp(self):
self.such_entity = Entity.Entity("test1", 123)
self.such_weapon = weapon.Weapon("Axe", 35, 0.2)
def test_equip_weapon(self):
self.such_entity.equip_weapon(self.such_weapon)
sel... |
# Compression algorithm
# http://www.cse.yorku.ca/~oz/hash.html
# https://marc-b-reynolds.github.io/math/2017/10/13/IntegerBijections.html
# https://stackoverflow.com/questions/4273466/reversible-hash-function
def u32(v:int): return 0xFFFFFFFF & v
def tochk(v:int): return bytearray(v.to_bytes(4, byteorder='big'))
de... |
from .contrast_image import _contrast_image
from .contrast_parameters import _contrast_parameters
from .contrast_psychopy import _contrast_psychopy
class Contrast:
"""
A class to generate the Simultaneous Contrast illusion.
Simultaneous contrast, identified by Michel Eugène Chevreul, refers to the
ma... |
# Generated by Django 3.0.5 on 2020-05-09 01:06
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('organizations', '0002_organization_abbreviation'),
('clinics', '0004_auto_20200508_1520'),
]
operations = [... |
import mwclient
import hashlib
class GamepediaClient:
mwc = None
'''
Login on creation
'''
def __init__(self, url='faeria.gamepedia.com', username=None, password=None):
self.mwc = mwclient.Site(url, path='/')
if username is not None and password is not None:
self.mwc.... |
from gene_register.models import Gene
from variant_register.models import Variant
from disease_register.models import Disease, GeneDisease, DiseaseType
import csv
import os
path = os.path.abspath(os.getcwd()) + "\data\\"
with open(path + 'Gene.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader... |
from django.urls import path
from .import views
urlpatterns = [
path('', views.index, name='blog.index'),
path('<slug>/', views.single, name='blog.single'),
path('comment/news/<int:post_id>', views.comment, name='blog.comment'),
path('tag/<tag_slug>', views.tags, name='blog.tags'),
] |
from sklearn.datasets import load_breast_cancer
from sklearn import tree
import sklearn.model_selection as ms
import sklearn.metrics as metrics
import graphviz
import matplotlib.pyplot as plt
cancer = load_breast_cancer( )
clf = tree.DecisionTreeClassifier(min_samples_leaf=50)
clf = clf.fit(cancer.data, cancer.target... |
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
n1 = len(s1)
n2 = len(s2)
n3 = len(s3)
if n1+n2!=n3:
return False
return self.isInterleaveHelper(s1,s2,s3)
def isInterleaveHelper(self,s1,s2,s3):
if len(s3)==0:
... |
from app import api
from flask import Flask, escape, request, render_template
app = Flask(__name__, static_folder = "app/static/", template_folder='app/templates/')
app.register_blueprint(api.flurfunk.bp, url_prefix='/api/flurfunk')
@app.route("/")
def hello():
name = request.args.get("name", "World")
return ... |
import smtplib
class SMTPlibexception(Exception): pass
def sendmail(from_addr, to_addr_list, subject, message, smtpserver='10.177.1.10'):
header = 'From: %s\n' % from_addr
header += 'To: %s\n' % ','.join(to_addr_list)
header += 'Subject: %s\n\n' % subject
message = header + message
try:
se... |
'''
Created on Aug 7, 2016
@author: Dayo
'''
import re
from django.conf import settings
from django.db import transaction
from django.core.exceptions import ObjectDoesNotExist
from core.exceptions import MissingSMSRateError, MissingCallRateError
from core.models import KITUBalance, FundsTransfer
from .m... |
import threading
class StoppableThread(threading.Thread):
"""A thread that can be stopped.
The target function will be called in a tight loop until the thread is stopped.
Note: Don't subclass this to override run(). That won't work. """
def __init__(self, group=None, target=None, name=None, post_target=Non... |
from pyspark.sql import SparkSession
schema = "`Id` INT, `First` STRING, `Last` STRING, `Url` STRING, `Published` STRING, `Hits` INT, `Campaigns` ARRAY<STRING>"
data = [[1, "Jules", "Damji", "https://tinyurl.1", "1/4/2016", 4535, ["twitter", "LinkedIn"]],
[2, "Brooke","Wenig","https://tinyurl.2", "5/5/2018", ... |
import os
import sys
import json
from flask.ext.script.commands import InvalidCommand, Command, Option
from flask_script import Manager
from ..models import User
from . import sso, api, models
from .config import config
DiscourseCommand = manager = Manager(usage='Manage Discourse integration.')
class CustomManager(M... |
import json
z = """{
"first_ name": "Jane",
"last_ name": "Smith",
"email": "jane .smith@wyng.com",
"gender": null,
"invitations": [
{
"from": "",
"code": null,
"test": false,
"home": true
}
],
"company": {
"name": "",
"industries": {"dd":""},
"industries1": {"dd":"1"}
},
"address"... |
from __future__ import division
import os
import sys
import time
import torch
import random
import pickle
from model import *
import torch.nn as nn
from torch import optim
from torch_util import *
from datetime import datetime
from datetime import timedelta
from collections import Counter
from torchtext.v... |
# CNN으로 구성
# 2차원을 4차원으로 늘여서 하시오.
import numpy as np
# 1. 데이터
from sklearn.datasets import load_diabetes
dataset = load_diabetes()
x = dataset.data
y = dataset.target
print(x.shape) # (442, 10)
print(y.shape) # (442,)
from sklearn.model_selection import train_test_split
x_train, x_test, y_tr... |
from unittest import TestCase
from unittest.mock import patch, Mock
from ..cli import (
argparser,
BATCLI,
NestedNameSpace,
Commands,
logging,
argparse,
)
SRC = 'bat.cli'
class TestArgparser(TestCase):
def test_argparser(t):
argparser()
class TestBATCLI(TestCase):
def se... |
#!/usr/bin/env python
import logging
from typing import (
Dict,
Optional
)
import ujson
from aiokafka import ConsumerRecord
from sqlalchemy.engine import RowProxy
from hummingbot.logger import HummingbotLogger
from hummingbot.core.event.events import TradeType
from hummingbot.core.data_type.order_book cimport... |
from datetime import date
from onegov.ballot import ElectionCompound
from onegov.ballot import ElectionCompoundCollection
def test_elections_by_date(session):
session.add(ElectionCompound(
title="first",
domain='federation',
date=date(2015, 6, 14)
))
session.add(ElectionCompound(
... |
#PreprocessingModule:
#Houses the parent class for any module which fits data into the common domain
#
#Objects:
# - DataModule:
# Discr:
# - DataModule is the format for any file parsing raw data into the common format for locationDict.
# - All modules which intend to accomplish this must u... |
# -*- coding: utf-8 -*-
"""Tests for the tex lexer."""
import nose.tools
from unittest import TestCase
from latexcodec.lexer import (
LatexLexer, UnicodeLatexLexer,
LatexIncrementalLexer,
LatexIncrementalDecoder, UnicodeLatexIncrementalDecoder,
LatexIncrementalEncoder, UnicodeLatexIncrementalEncoder,... |
from pysat.formula import IDPool
from itertools import combinations
from pysat.solvers import Solver
from sympy.logic import to_cnf
from sympy import symbols
from sympy.logic import SOPform, POSform
from sympy.logic.boolalg import And, Not, Or
ids = ['207668286', '316327238']
vpool = IDPool()
# possible directions for... |
#!/usr/bin/env python
import sys
import time
from subprocess import Popen, PIPE, STDOUT
try:
from subprocess import DEVNULL # py3k
except ImportError:
import os
DEVNULL = open(os.devnull, 'wb')
if (len(sys.argv) < 1):
print "No stream given."
streamname = sys.argv[1]
prefix = "http://twitch.tv/"
url =... |
"""Test file used in pytest to test the names module"""
import pytest
from names import Names
@pytest.fixture
def empty_names():
""" Returns a Names instance with initialising values of error_code_count = 0 and names = []"""
return Names()
@pytest.fixture
def filled_names():
""" Returns a Names instanc... |
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, Float, Boolean
from models import Base, JSONEncodedValue
from models.pricing import PricingEngine
from utils import utcnow
from utils.maps import distance_between
from copy import copy
PENDING = 0
WAITING_DELIVERY_ACCEPTANCE = 1
DELIVERY_ACCEPTED = ... |
import pandas as pd
import numpy as np
def topic_pred(lda_model, tf, vectorizer):
"""returns a dataframe with topic predictions."""
# Column names based on top three topics
# source: https://stackoverflow.com/questions/44208501/getting-topic-word-distribution-from-lda-in-scikit-learn
vocab = vectori... |
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------------
# testtool2.py
# Created on: 2017-04-21 11:16:02.00000
# (generated by ArcGIS/ModelBuilder)
# Description:
# ---------------------------------------------------------------------------
# Import arcpy module... |
# import socket
#
# # 서버의 주소입니다. hostname 또는 ip address를 사용할 수 있습니다.
# HOST = '192.168.0.103'
# # 서버에서 지정해 놓은 포트 번호입니다.
# PORT = 9999
#
# # 소켓 객체를 생성합니다.
# # 주소 체계(address family)로 IPv4, 소켓 타입으로 TCP 사용합니다.
# client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#
# # 지정한 HOST와 PORT를 사용하여 서버에 접속합니다.
# client... |
import math
import os
import struct
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.cluster import KMeans
from scipy.sparse import csc_matrix, csr_matrix
from collections import defaultdict, namedtuple
from heapq import heappush, heappop, heapify
from pathlib import P... |
def main(n, ps):
zeros = [0 for _ in range(n)]
count = 0
for i, p in enumerate(ps):
if i == 0:
zeros[i] = p
count += 1
continue
else:
zeros[i] = min(zeros[i - 1], p)
if p <= zeros[i-1]:
count += 1
print(c... |
from datetime import datetime
import json
import time
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
x = []
y = []
if __name__ == '__main__':
weight = {'like_num': 50000, 'comment_num': 3000, 'repost_num': 2500}
with open("ysxw.json", 'rb') as load_f:
load_dict = json.l... |
# Author : Xiang Xu
# -*- coding: utf-8 -*-
import sys
from filter import filter_users_with_checkintimes, filter_users_with_friends
def get_user_friends(uid):
with open('friends.txt') as f:
for line in f:
token = line.strip().split('\t')
if int(token[0]) == uid:
re... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 22 21:29:51 2017
@author: sahebsingh
"""
""" We are going to do Stock Market prediction """
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import train_tes... |
import math
from pygame.math import Vector2
from .UnitLayer import UnitLayer
class ItemLayer(UnitLayer):
def __init__(self, cell_size, texture, game_state):
super().__init__(cell_size, texture, game_state)
def render(self, surface):
for item in self.game_state.items:
tile_x = ma... |
__author__ = "Komal Atul Sorte"
"""
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root... |
from jnpr.junos import Device
from jnpr.junos import version
import sys
from getpass import getpass
from jnpr.junos.decorators import normalizeDecorator
from jnpr.junos.utils.sw import SW
from lxml import etree
import os
os.system('clc||clear')
def connect(manual=1, method=0, hostname=0, junos_username=0, junos_passwo... |
#!/usr/bin/python3
# -*- coding:utf8 -*-
# Author : Arthur Yan
# Date : 2019-03-05 20:52:09
# Description : 生成验证码
import random
def generate_code(code_len=4):
"""docstring for main"""
all_charts = '0123456789abcdefghipqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
last_pos = len(all_charts) - 1
c... |
"""
3. Rekursion 6 Pkt.
Schreiben Sie ein Python-Programm, das in einer rekursiven Funktion hoch mit den Parametern x
und i in dieser Reihenfolge den Wert xi berechnet. Das Hauptprogramm muss die Eingabe von x und
i vornehmen. Wenn der Parameter x beim Aufruf nicht angegeben wird, soll er mit 2 angenommen
werden.
Sorge... |
def testConditional():
name = 'Darmawan'
if (name == "Darmawan"):
print("ini abi")
elif (name == "imam"):
print("ini elif")
else:
print("else")
testConditional()
print("-------------------------")
def testLooping():
for x in range(0,5):
print("nilai x : ", x)
test... |
import pandas as pd
import numpy as np
import seaborn as sns
import itertools
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder, StandardScaler
import warnings
warnings.simplefilter('ignore')
from sklearn import model_selection
from sklearn import metrics
from sklearn.model_selection imp... |
"""
"""
class ControladorTemperatura:
histeris = 2
@staticmethod
def comparar_temperatura(temperatura_actual, temperatura_deseada):
temperatura = "normal"
limite_superior = temperatura_deseada + ControladorTemperatura.histeris
limite_inferior = temperatura_deseada - ControladorT... |
import SimpleITK as sitk
import skimage.io as io
from itkwidgets import view
import itk
from scipy import ndimage
import numpy as np
import os
from tqdm import tqdm
def distance_transform(path, transformed_path):
path_list = os.listdir(path)
for pa in tqdm(path_list):
img = sitk.ReadImage(path + pa)
... |
#!/usr/bin/python
import sys
f = open(sys.argv[1])
lines = f.readlines()
wordCount = 0;
print 'PROGMEM const unsigned int firmware[] = {'
for line in lines:
line = line[9:-4]
while line != '':
print '0x' + line[2:4] + line[0:2] + ',',
line = line[4:]
wordCount += 1
print ''
print '}... |
import pandas as pd
import pyodbc
server = 'localhost, port_no'
databse = 'test_db'
username = 'system_name'
password = 'password_name'
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL server}; SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+password)
print(cnxn)
cursor = cnxn.cursor()
... |
from flask import Flask, url_for
app = Flask(__name__)
from datetime import timedelta
from flask import make_response, request, current_app
from functools import update_wrapper
import json
import math
def crossdomain(origin=None, methods=None, headers=None,
max_age=21600, attach_to_all=True,
... |
#!/usr/bin/env python
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from networking.lib import * #@UnusedWildImport
from location.lib import * #@UnusedWildImport
from location.maps import SUNYNorth, DAVIS_HALL
n = Networking.load('../data.dat')
wifi_locations = []
threeg_locations = []
fo... |
import re
import os
import sys
import serial_manager
from PyQt5.QtWidgets import (
QMainWindow, QWidget, QPushButton, QVBoxLayout, QApplication, QLabel,
QLineEdit, QComboBox, QGridLayout, QGroupBox, QHBoxLayout,
QMessageBox, QAction, QActionGroup, QFileDialog, QDialog, QMenu,
QDesktopWidget, QTextEdit
)... |
import jetson.inference
import jetson.utils
import argparse
import sys
from segnet_utils import *
parser = argparse.ArgumentParser(description="Segment a live camera stream using an semantic segmentation DNN.",
formatter_class=argparse.RawTextHelpFormatter, epilog=jetson.in... |
import signal
import sys
import torch
import torch.nn as nn
import numpy as np
import csv
from sklearn.preprocessing import MinMaxScaler
""" Necessary args """
filename = r"appl.csv"
outfile_name = r"appl_pred.csv"
checkpoint_file_name = r"model.pt"
train_data_ratio = 0.1
epochs = 10000
train_window = 60
""" Optiona... |
from sqlalchemy import Column, String, Boolean, DateTime, ForeignKey
from models import db
class Task(db.Model):
__tablename__ = 'tasks'
id = Column(String(36), primary_key=True)
user = Column(String)
case_name = Column(String)
queued_at = Column(DateTime)
complete = Column(Boolean, default=... |
# Generated by Django 2.1.7 on 2019-03-03 19:48
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Account",
fields=[
... |
default_app_config = 'daf.apps.DjangoActionFrameworkConfig'
|
import os, re
from S32R_BitFields import Packages, ID_BitFields, MSCR_BitFields
# The path of repository
ksdk_path = "e:/C55SDK/s32_internal_tools/"
family = 'S32R'
endOfLine = '\n' # Unix standard
######################################################
def update_and_write_data_to_file(fFile, wdata, line_ending)... |
"""
Homework 02
Problem 09
Kevin Hsieh
11 February 2016
CS CM122 (1B)
"""
# --------------------------------------------------
# LEVEL 1 FUNCTIONS
# --------------------------------------------------
def overlap_indices(str1, str2, i):
"""
Finds the indices of the beginning and ending of the o... |
import math
import random
import matplotlib.pyplot as plt
from util import City, read_cities, write_cities_and_return_them, generate_cities, visualize_tsp, path_cost
class SimAnneal(object):
def __init__(self, cities, temperature=-1, alpha=-1, stopping_temperature=-1, stopping_iter=-1):
self.cities = citi... |
import requests
import json
import boto3
def find_machine(index):
'''
Finds value type using iterable position in a list of strings
Finds the machine type in description
'''
split_index = index.split()
for word in split_index:
if split_index.index( word ) == 2:
return word... |
from onegov.search import ORMSearchable, Searchable
from onegov.search import utils
from sqlalchemy import Column, Integer, Text
from sqlalchemy.ext.declarative import declarative_base
def test_get_searchable_sqlalchemy_models(postgres_dsn):
Foo = declarative_base()
Bar = declarative_base()
class A(Foo):... |
import cv2
import numpy as np
from math import sin, cos
from scipy.optimize import minimize
import torch
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib as mpl
import pandas as pd
from sklearn.linear_model import LinearRegression
def str2coords(s, names=['id', 'yaw', 'pitch', 'ro... |
# Rescale data (between 0 and 1)
from pandas import read_csv
from numpy import set_printoptions
from sklearn.preprocessing import MinMaxScaler
filename = 'pima-indians-diabetes.data.csv'
data = read_csv(filename)
array = data.values
# separate array into input and output components
X = array[:, 0:8]
Y = array[:, 8]
sc... |
import os, glob
import numpy as np
from pandas import DataFrame, read_csv, to_datetime, DateOffset, datetime
from faker import Factory
header = list(read_csv('tblCrmClientRecords.csv', encoding='utf-8').columns)
clientRecords = DataFrame(columns=header)
fake = Factory.create()
fake.seed(1234)
def fill(fake, cli... |
# Generated by Django 3.2.4 on 2021-07-09 12:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pay', '0013_auto_20210709_1222'),
]
operations = [
migrations.AddField(
model_name='forms',
name='id',
f... |
import datetime
from haystack import indexes
from .models import Article
class ArticleIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
title = indexes.CharField(model_attr='title')
body = indexes.CharField(model_attr='body')
def get_model(self):
return A... |
''' Make 2D plot of xsec with variied couplings
'''
# Standard imports
import ROOT
import os
import itertools
import ctypes
# TopEFT imports
from TopEFT.Generation.Configuration import Configuration
from TopEFT.Generation.Process import Process
from TopEFT.Tools.u_float import u_float
from TopEFT.Tools.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.