content stringlengths 5 1.05M |
|---|
# Python3
import sys
import shutil
from pathlib import Path
# Get the root path to this repo
repo_dir = Path(__file__).parent
# Get the os dependant kits path
if sys.platform == "win32":
install_path = Path(r"~\AppData\Roaming\Luxology\Kits").expanduser()
elif sys.platform == "darwin":
install_path = Path("... |
from sqlalchemy.ext.asyncio import AsyncSession
from app.crud import dialogue_crud
from app.service import dialogue_exist
async def get_all_dialogues_for_user(db: AsyncSession, user_id: int):
"""
Get all dialogues for user
:param db: DB
:type db: AsyncSession
:param user_id: User ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_compartmentmodels
----------------------------------
Tests for `compartmentmodels` module.
The tests for the individual models are in separate files.
"""
import pytest
#import tempfile
import os
import numpy as np
from compartmentmodels.compartmentmodels imp... |
from typing import Optional
from typing import Union
import attr
@attr.s
class Attachment:
content_type = attr.ib(type=str)
id = attr.ib(type=str)
size = attr.ib(type=int)
stored_filename = attr.ib(type=str)
@attr.s
class Reaction:
emoji = attr.ib(type=str)
target_author = attr.ib(type=Unio... |
#!/usr/bin/python
# coding: utf-8
# Copyright 2018 AstroLab Software
# Author: Chris Arnault
#
# 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... |
from ast import literal_eval
from database.model_people import ModelPeople
from database.model_planet import ModelPlanet
from database import base
import logging
import sys
# Load logging configuration
log = logging.getLogger(__name__)
logging.basicConfig(
stream=sys.stdout,
level=logging.INFO,
format='%(a... |
import numpy.random as rd
import numpy as np
from display import *
from solver import *
def init_list(N):
balls = []
r = 10.
v = 10.
x = 400./float(N+1)
for i in range(N):
m = r*(1.-0.05*i)
vv = [-1.*v, 1.*v]
vx = [float(i+1)*x, float(i+1)*x]
balls.append(Ball(m, m, ... |
'''
source-directory /etc/network/interfaces.d
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet manual
allow-hotplug ppp0
iface ppp0 inet wvdial
post-up echo "cellular (ppp0) is online"
allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
allow-hotplug wlan1
iface w... |
import torch
from PIL import Image
import numpy as np
from torchvision import datasets, models, transforms
import os
import glob
from models import DoveNetG
transformsC = transforms.Compose([transforms.Resize((512, 512)), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
transformsG = tra... |
"""
Desafio 011
Problema: Faça um programa que leia a largura e a altura de uma
parede em metros, calcule a sua área e a quantidade de
tinta necessária para pintá-la, sabendo que cada litro
de tinta pinta uma área de 2 metros quadrados"""
l = float(input('Digite a largura: '))
a = float(i... |
import torch
import torch.nn as nn
class FactorizedReduce(nn.Module):
"""
Reduce feature map size by factorized pointwise(stride=2).
"""
def __init__(self, C_in, C_out, affine=True):
super().__init__()
self.relu = nn.ReLU()
self.conv1 = nn.Conv2d(C_in, C_out // 2, 1, stride=2, p... |
from typing import Union, List, Optional
from pyspark.sql.types import StructType, StructField, StringType, ArrayType, DataType
# This file is auto-generated by generate_schema so do not edit manually
# noinspection PyPep8Naming
class DetectedIssueSchema:
"""
Indicates an actual or potential clinical issue w... |
# simple no arg function
def simple_function():
print 'Hello, function!'
simple_function()
# simple function with argument
def fib(n):
a, b = 0, 1
while a < n:
print a,
a, b = b, a+b
fib(10)
print ''
# example of using documentation string (so-called docstring)
def other_function():
"""Simple gibbrish print... |
import pytest
from pytest import raises
from vyper import compiler
from vyper.exceptions import InvalidType, UnknownType
fail_list = [
"""
x: bat
""",
"""
x: HashMap[int, int128]
""",
"""
x: [bar, baz]
""",
"""
x: [bar(int128), baz(baffle)]
""",
"""
struct A:
b: B
struct B:
... |
import os, sys
import numpy as np
from env_handler import EnvHandler
from q_function import Q
from logger import Logger
from agent import Agent
from action_selectors.mbie_eb import MBIE_EB
from action_selectors.epsilon_greedy import EpsilonGreedy
from action_selectors.boltzmann import Boltzmann
from action_selectors.uc... |
#!/bin/python
import sys
import yaml
import datetime
if __name__ == '__main__':
filename = sys.argv[1] if len(sys.argv) > 1 else '/Volumes/Kea/devel/MOSSCO/code/external/fabm/code/util/standard_variables/variables.yaml'
if not filename: sys.exit(1)
with open(filename, 'r') as fid:
yml = yaml.... |
import pandas as pd
from scholarly import scholarly
import plotly.express as px
def search_author(name, return_list=False):
search_query = scholarly.search_author(name)
if not return_list:
return next(search_query)
else:
return list(search_query)
def search_author_id(id):
try:
... |
from Tkinter import *
from common import Codes
from ..controllers import AdminDataController
from ..handlers.data import Data
class Admin(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.elements = {}
title_frame = Frame(self)
tit... |
# Import library(toolkit) for deep learning
import numpy as np
import os
import torch
import torch.nn as nn
import torchvision.transforms as transforms
from torch.utils.data import DataLoader, Dataset
import pytorchtools as tools
import pandas as pd
import time
import myfunctions as my
# read data
workspace_dir = './o... |
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 5 04:53:01 2020
@author: Infraestructura 3D
"""
"""
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 limitatio... |
from django.core.cache import cache
from django.test import Client, TestCase
from django.urls import reverse
class MoviesTest(TestCase):
def setUp(self):
self.client = Client()
cache.clear()
def test_view_movies_correct_template(self):
"""check if the right template is called"""
... |
#!usr/env/bin python3
interface = input("enter your interface>>")
mac = input("enter new mac>>")
print (" ")
print ("--------------------------------------------------------------------------")
import subprocess
subprocess.call("ifconfig " + interface + " down",shell=True)
subprocess.call("ifconfig " + i... |
"""
Horizontal boxplot with observations
====================================
_thumb: .7, .45
"""
import numpy as np
import seaborn as sns
sns.set(style="ticks", palette="muted", color_codes=True)
# Load the example planets dataset
planets = sns.load_dataset("planets")
# Plot the orbital period with horizontal boxes... |
# Generated by Django 3.1 on 2020-08-26 08:48
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('mining', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='match_key',
name='MK_key_type',
),
... |
from flask import Blueprint
bp = Blueprint("StCourierServer", __name__, url_prefix="/master")
from . import view
|
#
# This file is part of the PyMeasure package.
#
# Copyright (c) 2013-2022 PyMeasure Developers
#
# 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 limit... |
"""protected field on Address
Revision ID: 427743e76984
Revises: f8c342997aab
Create Date: 2021-02-02 11:39:45.955233
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '427743e76984'
down_revision = 'f8c342997aab'
branch_labels = None
depends_on = None
def upgr... |
import binance
from config import BINANCE_API_KEY, BINANCE_API_SECRET
async def connect():
binance_client = binance.Client(BINANCE_API_KEY, BINANCE_API_SECRET)
await binance_client.load()
return binance_client
|
#!/usr/bin/python
import os
import pyopencl as cl
import numpy as np
# initialize OpenCL
def initCl():
PACKAGE_PATH = os.path.dirname( os.path.realpath( __file__ ) ); print(PACKAGE_PATH)
#CL_PATH = os.path.normpath( PACKAGE_PATH + '../../cl/' )
CL_PATH = os.path.normpath( PACKAGE_PATH + '/../cl' )
... |
# -*- coding: utf-8 -*-
import sfml as sf
WIDTH = 640
HEIGHT = 480
TITLE = "Python SFML Events"
window = sf.RenderWindow(sf.VideoMode(WIDTH, HEIGHT), TITLE)
while window.is_open:
for event in window.events:
if type(event) is sf.CloseEvent:
window.close()
if type(event) is sf.MouseMov... |
from flask import Flask, request
app = Flask(__name__)
def getAllPuppies():
return "Getting All the puppies!"
def makeANewPuppy():
return "Creating A New Puppy!"
def getPuppy(id):
return "Getting Puppy with id {}".format(id)
def updatePuppy(id):
return "Updating Puppy with id {}".format(i... |
import numpy as np
import matplotlib.pylab as pl
pl.rcParams['pdf.fonttype'] = 42
pl.rcParams['ps.fonttype'] = 42
fig = pl.figure(figsize=(12,4))
ax = fig.add_subplot(1,2,1)
def plot_perf(nlist, err, color, label, errbar=False, perc=20):
pl.loglog(nlist, err.mean(0), label=label, color=color)
if errbar:
... |
from __future__ import unicode_literals
__all__ = ['core','util']
import os
import warnings
import ruamel.yaml as yaml
__author__ = "Pymatgen Development Team"
__email__ ="pymatgen@googlegroups.com"
__maintainer__ = "Shyue Ping Ong"
__maintainer_email__ ="shyuep@gmail.com"
__version__ = "2017.8.16"
SETTINGS_FILE = ... |
import json
import requests
import xlrd
SOURCES = (
('awois_wrecks', 'http://wrecks.nauticalcharts.noaa.gov/downloads/AWOIS_Wrecks.xls'),
('enc_wrecks', 'http://wrecks.nauticalcharts.noaa.gov/downloads/ENC_Wrecks.xls'),
)
if __name__ == '__main__':
for source_item in SOURCES:
# Source and URL
... |
__author__ = 'arjun010'
from visObject import *
from chartDataFormatter import *
from dataFactGenerator import *
from itertools import combinations, permutations
def getPossibleVisualizations(attributeList, dataList, metadataMap):
possibleVisualizations = []
possibleDataFacts = []
itemAttribute = None # i... |
from __future__ import division
# X é o numero no qual queremos a raiz quadrada
# I quantidade de interações
def calc_raizq(x, chute, i):
if i < 1:
raise ValueError("É necessário pelo menos uma iteração")
if chute < 1:
chute = 1
if x < 0:
return complex(0, calc_raizq(-x, chute, i)... |
############################################################################
# Copyright ESIEE Paris (2019) #
# #
# Contributor(s) : Giovanni Chierchia, Benjamin Perret #
# ... |
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import pytorch_lightning as pl
class Net(pl.LightningModule):
def __init__(self):
super(Net, self).__init__()
self.layer1 = nn.Linear(28*28, 1024)
self.layer2 = nn.Linear(1024, 128)
se... |
def foo(x):
return x*x
y = [1,2,3,4,5]
z = list(map(foo,y))
for val in z:
print(val)
|
# -*- coding: utf-8 -*-
__author__ = "Michele Samorani"
import pandas as pd
import cplex
import time
import random
TIME_LIMIT_SECONDS = 60
def build_scenarios(show_probs, max_scenarios,seed):
"""
Builds the scenarios
:param show_probs:
:type show_probs: list[float]
:return: a list of (probability,... |
# This file is part of the Etsin service
#
# Copyright 2017-2018 Ministry of Education and Culture, Finland
#
# :author: CSC - IT Center for Science Ltd., Espoo Finland <servicedesk@csc.fi>
# :license: MIT
"""Language and translation utilities"""
from flask import request, session
from etsin_finder.auth.authenticatio... |
import pygame;
from .drawable import Drawable;
# --------------------------------------------------- *\
# [class] Image()
#
# * Image element *
#
# --------------------------------------------------- */
class Image(Drawable):
# --------------------------------------------------- *\
# [function] __init__():
#
# ... |
"""
This file contains all the sales related resources
"""
# Third party imports
from flask import request, json, abort
from flask_restplus import Resource
from flask_jwt_extended import jwt_required, get_jwt_identity
# Local application imports
from app.api.v1.models.sales import Sale
from app.api.v1.models.db imp... |
from flask import Flask, render_template,request, session , redirect , url_for , g,flash, jsonify, make_response, json,flash
from flask_mail import Mail,Message
from flask_cors import CORS
from pusher import pusher
from flask_wtf import FlaskForm
from wtforms import (StringField ,PasswordField,SubmitField)
from w... |
#!/usr/bin/env python3
# -----------------------------------------------------------------------
# VIZPAIRWISESEQ
# Copyright 2015, Stephen Gould <stephen.gould@anu.edu.au>
# -----------------------------------------------------------------------
# Script to visualize an integer sequence based on the visualization of
#... |
import sys
sys.path.append("../bundle_adjustment/ceres-solver/ceres-bin/lib/") # so
import PyCeres
import numpy as np
import scipy.io as sio
import cv2
from utils import geo_utils
def order_cam_param_for_c(Rs, ts, Ks):
"""
Orders a [m, 12] matrix for the ceres function as follows:
Ps_for_c[i, 0:3] 3 para... |
"""Turrets and torpedo mpunt data in a useable form"""
from schemas import TURRETS
class Turret:
"""Container for the data needed to draw a turret
Args:
caliber (int): caliber of the gun in inches (urgh)
pos (string): the letter of the turret, like "A", "X", etc...
positio... |
# Copyright (c) 2021, Carlos Millett
# All rights reserved.
# This software may be modified and distributed under the terms
# of the Simplified BSD License. See the LICENSE file for details.
import abc
from pathlib import Path
from .types import Types
class Media(abc.ABC):
def __init__(self, media_type: Type... |
class Solution(object):
def minDistance(self, w1, w2):
if w1 == "":
return len(w2)
if w2 == "":
return len(w1)
l1 = len(w1)
l2 = len(w2)
d=[]
for i in range(l1+1):
d.append([0] * (l2 + 1))
for i in range(0, l1 + 1):
... |
import math
import os
import time
import unicodedata
from pyrogram.errors import MessageNotModified
from help.progress import humanbytes, TimeFormatter
import requests
from config import Config
from tqdm.utils import CallbackIOWrapper
from pathlib import Path
from tqdm.contrib.telegram import tqdm
CHUNK_SI... |
import click
from flask.cli import with_appcontext
from goslinks.db.factory import get_model
@click.command()
@with_appcontext
def migrate():
"""Creates and migrates database tables."""
for model_name in ("user", "link"):
model = get_model(model_name)
click.echo(f"Creating table {model.Meta.t... |
from .nondet import Nondet
|
# test_file.py
import io
import pytest
import graspfile.torfile
test_file = "tests/test_data/tor_files/python-graspfile-example.tor"
"""TICRA Tools 10.0.1 GRASP .tor file"""
@pytest.fixture
def empty_tor_file():
"""Return an empty GraspTorFile instance."""
return graspfile.torfile.GraspTorFile()
@pytest... |
"""Choose python classifiers with a curses frontend."""
from __future__ import unicode_literals
import os
import curses
from collections import namedtuple
from .constants import VERSION
from .constants import CHECKMARK
class BoxSelector(object): # pragma: no cover
"""Originally designed for accman.py.
D... |
'''
Created on 20/01/2014
@author: MMPE
See documentation of HTCFile below
'''
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import zip
from builtins import int
from builtins import str
from future im... |
from apscheduler.schedulers.blocking import BlockingScheduler
from server.sync import sync_blocks, sync_tokens
background = BlockingScheduler()
background.add_job(sync_tokens, "interval", seconds=30)
background.add_job(sync_blocks, "interval", seconds=5)
background.start()
|
########################################################
# plot_norms.py #
# Matheus J. Castro #
# Version 1.2 #
# Last Modification: 11/11/2021 (month/day/year) #
# https://github.com/MatheusJCastro... |
from django.shortcuts import render
from django.http import JsonResponse
import os
import json
import time
from .api import GoogleAPI
from threpose.settings import BASE_DIR
from src.caching.caching_gmap import APICaching
from decouple import config
gapi = GoogleAPI()
api_caching = APICaching()
PLACE_IMG_PATH = os.p... |
import os
import math
import random
import argparse
def generate_entities(num_entities=100):
"""generate num_entities random entities for synthetic knowledge graph."""
i = 0
entity_list = []
hex_chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
l = ... |
# Simple script for drawing the chi-squared density
#
from rpy import *
def draw(df, start=0, end=10):
grid = r.seq(start, end, by=0.1)
l = [r.dchisq(x, df) for x in grid]
r.par(ann=0, yaxt='n')
r.plot(grid, l, type='lines')
if __name__ == '__main__':
print "<Enter> to quit."
while 1:
... |
"""
queue.py
location queue implementation for ducky25, decides next location to travel to
"""
class DestinationQueue:
def __init__(self):
self.queue = []
self.position = 0
def add_to_queue(self, location):
self.queue.append(location)
def pop_next_destination(self):
if len(self.queue) > self.position:
... |
from logging.config import dictConfig # type: ignore
import json
from config import CONFIG_DICT
done_setup = False
def setup_logging():
global done_setup
if not done_setup and CONFIG_DICT['LOGGING']:
try:
logging_config_file_path = CONFIG_DICT['LOGGING_CONFIG_FILE_PATH']
wi... |
"""
MIT License
Copyright(c) 2021 Andy Zhou
"""
from flask import render_template, request, abort
from flask.json import jsonify
from flask_wtf.csrf import CSRFError
from flask_babel import _
def api_err_response(err_code: int, short_message: str, long_message: str = None):
if (
request.accept... |
from tidyms import lcms
from tidyms import utils
import numpy as np
import pytest
from itertools import product
mz_list = [200, 250, 300, 420, 450]
@pytest.fixture
def simulated_experiment():
mz = np.array(mz_list)
rt = np.linspace(0, 100, 100)
# simulated features params
mz_params = np.array([mz_li... |
from flask_login import UserMixin
from datetime import datetime
from sqlalchemy import ForeignKey
from sqlalchemy.orm import backref
from app.extensions import db
ACCESS = {
'guest': 0,
'user': 1,
'admin': 2
}
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True, unique=Tru... |
# encoding: utf-8
"""
Enumerations related to tables in WordprocessingML files
"""
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
from docxx.enum.base import (
alias, Enumeration, EnumMember, XmlEnumeration, XmlMappedEnumMember
)
@alias('WD_ALIGN_VERTICAL')
class WD_... |
# Copyright 2011 OpenStack Foundation
# 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 requ... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
import nlm_pb2 as nlm__pb2
class NLMStub(object):
# missing associated documentation comment in .proto file
pass
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.StrReca... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, PibiCo and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
import datetime, time
from frappe.utils import cstr
from frappe import msgprint, _
from frappe.core.d... |
from __future__ import division
import json
import time
import serial as _serial
import platform
import sys
if sys.version_info >= (3, 0):
import queue
else:
import Queue as queue
from threading import Event, Thread
from serial.tools.list_ports import comports
from . import IOHandler
try:
JSONDecodeEr... |
#!/usr/bin/env python
from distutils.core import setup
setup(
name = 'elastico',
version = '0.6.3',
description = "Elasticsearch Companion - a commandline tool",
author = "Kay-Uwe (Kiwi) Lorenz",
author_email = "kiwi@franka.dyndns.org",
url = 'https://github.com/klo... |
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import Required,Email, EqualTo
from ..models import User
from wtforms import ValidationError
class RegisterationForm(FlaskForm):
email = StringField('Enter Your email Address', validato... |
import pytest
from nengo_os import SimpleProc, ConventScheduler
procs = [ # name id arrival1,+2, comp_t, needed_cores
SimpleProc("Cifar", 0, 0, 0, 10, 4038), # test single process
SimpleProc("SAR", 1, 0, 0, 100, 3038), #test two procs that can not run together
SimpleProc("SAR", 2, 0, ... |
from daq_server import DAQServer
import asyncio
server = DAQServer
event_loop = asyncio.get_event_loop()
# task = asyncio.ensure_future(heartbeat())
task_list = asyncio.Task.all_tasks()
async def heartbeat():
while True:
print('lub-dub')
await asyncio.sleep(10)
def shutdown(server):
print... |
import pathlib
import numpy as np
import simscale_eba.HourlyContinuous as hc
epw = hc.HourlyContinuous()
# Put any path here
path = r'E:\Current Cases\SimScale Objects\examples\epw_to_stat\USA_MA_Boston-Logan.Intl.AP.725090_TMYx.2004-2018.epw'
epw.import_epw(pathlib.Path(path))
weather_stats = hc.WeatherStatistics... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pygsheets
def boxplot(models_list,
d_exp,
xlabel='Models',
ylabel='Mise Surv 0',
option=0):
n = len(models_list)
if option == 0:
input = [d_exp[f'mise_0_{model_name}'] for model... |
#coding=UTF-8
import argparse, sys
from urllib.request import urlopen
parse = argparse.ArgumentParser(description="Check vaadin.com version lists")
parse.add_argument("version", help="Released Vaadin version number")
args = parse.parse_args()
if hasattr(args, "echo"):
print(args.echo)
sys.exit(1)
prerelease = Non... |
'''
Created on May 2, 2018
@author: hwase0ng
'''
import settings as S
import requests
from BeautifulSoup import BeautifulSoup
from utils.fileutils import getStockCode
from common import loadMap
WSJSTOCKSURL = 'https://quotes.wsj.com/company-list/country/malaysia'
def connectStocksListing(url):
... |
#!/usr/bin/python3
# coding=utf-8
# Copyright 2021 getcarrier.io
#
# 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 req... |
# -*- coding: utf-8 -*-
# (C) Copyright 2017 Hewlett Packard Enterprise Development LP
# 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
#
# Unl... |
casa = float(input('Qual valor da casa? R$'))
s = float(input('Qual valor do seu salário? R$'))
a = int(input('Em quantos anos deseja pagar a casa?'))
parcela = casa / (a * 12)
if parcela <= 0.3 * s:
print(f'Parabéns, você está apto para compra da casa, vamos fechar negócio! \nVocê pagará em {a*12} parcelas de {pa... |
# -*- coding: utf-8 -*-
# Copyright (c) 2010-2016, MIT Probabilistic Computing Project
#
# 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/LICENS... |
from req import Service
from service.base import BaseService
import requests
import json
import config
import datetime
class DatetimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(obj, da... |
from .case import *
from .valkyrie_utils import *
from .section_model import *
from .cbr_cycle import *
from .functions import *
from .storage_unit import *
from .valkyrie_ner import *
|
import io
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from pandas.plotting import register_matplotlib_converters
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.metri... |
#! /usr/bin/python2.4
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
"""
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GUI application for Forward modelling 2D potential field profiles.
Written by Brook Tozer, University of Oxford 2015-17. SIO 2018-19.
Includes ability to import seismic reflection, well, surface ... |
from typing import List, Union
import numpy as np
import tf_conversions
from geometry_msgs.msg import Pose, Quaternion
def calc_homogeneous_matrix(pose: Pose) -> np.ndarray:
angles = tf_conversions.transformations.euler_from_quaternion([
pose.orientation.x,
pose.orientation.y,
pose.orien... |
"""
DBSCAN Clustering
"""
import numpy as np
from sklearn.cluster import DBSCAN
from sklearn.neighbors import NearestNeighbors
def eps_est(data,n=4,verbose=True):
"""
Minimum data size is 1000
Methodology improvement opportunity: Better elbow locater
"""
if verbose:print("Calculating nearest n... |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: fetchScheduler
Description :
Author : JHao
date: 2019/8/6
-------------------------------------------------
Change Activity:
2019/08/06:
----------------------------------------... |
#!/usr/bin/env python
# Written by Eric Ziegast
# nxdomain.py - look at ch202 dnsqr data from a file and print out any
# qname / type / rcode for data that's not rcode 0 ("NOERROR").
# Forgive awkward key processing. Sometimes an rcode or qtype key
# doesn't exist and would cause the script to break if accessed th... |
lista = list()
while True:
lista.append(int(input("Digite um número inteiro:\t")))
while True:
p = str(input("Digitar mais números?\t").strip())[0].upper()
if p in 'SN':
break
else:
print("\033[31mDigite uma opção válida!\033[m")
if p == 'N':
break
par... |
""" A simple TCP echo server. """
import argparse
import socket
import time
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("listen_port",
help="The port this process will listen on.",
type=int)
args = parser.parse_args()
... |
import os
import io
import shutil
import base64
import subprocess
import platform
import logging
import numpy as np
import pandas as pd
from tqdm import tqdm
from glob import glob
from pathlib import Path as P
import wget
import urllib3, ftplib
from urllib.parse import urlparse
from bs4 import BeautifulSoup
import ... |
# Generated by Django 3.1.2 on 2020-11-09 15:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auctions', '0015_auto_20201106_1737'),
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
... |
# Copyright 2009 by Tiago Antao <tiagoantao@gmail.com>. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
import os
import unittest
from Bio import MissingExternalDependencyError... |
from zope.browserpage import ViewPageTemplateFile
import pkg_resources
import zeit.cms.related.interfaces
import zeit.cms.workflow.interfaces
import zeit.content.video.interfaces
class Details(zeit.cms.browser.objectdetails.Details):
index = ViewPageTemplateFile(pkg_resources.resource_filename(
'zeit.con... |
import requests
import os
import time
from datetime import datetime
def get_edgar_index_files(date_input, download_folder=None):
date = datetime.strptime(str(date_input), '%Y%m%d')
# Confirm that date format is correct
error = 'Date format should be in YYYYMMDD. '
if date > datetime.now():
... |
from pylab import *
import tensorflow as tf
from sklearn.datasets import make_moons
from sklearn.datasets import load_digits
import tensorflow as tf
import sys
sys.path.insert(0, '../utils')
from layers import *
from utils import *
import cPickle
import os
SAVE_DIR = os.environ['SAVE_DIR']
runnb=int(sys.argv[-4]... |
#!/usr/bin/env python3
import os
import unittest
import boto3
from moto import mock_kms
from psyml.awsutils import (
decrypt_with_psyml,
encrypt_with_psyml,
get_psyml_key_arn,
)
from psyml.settings import PSYML_KEY_REGION, PSYML_KEY_ALIAS
class TestAWSUtils(unittest.TestCase):
@mock_kms
def kms_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.