content stringlengths 5 1.05M |
|---|
def sequences_to_one_hot(sequences, chars='ACGTN'):
"""
:param sequences:
:param chars:
:return:
"""
seqlen = len(sequences[0])
char_to_int = dict((c, i) for i, c in enumerate(chars))
one_hot_encoded = []
for seq in sequences:
onehot_seq = []
integer_encoded = ... |
# Generated by Django 3.2.9 on 2022-01-11 06:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('driver', '0003_driver_date'),
]
operations = [
migrations.RenameField(
model_name='driver',
old_name='contact',
... |
# This file is part of Pynguin.
#
# Pynguin 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) any later version.
#
# Pynguin is distributed in the ho... |
# copyright Caleb Michael Carlin (2018)
# Released uder Lesser Gnu Public License (LGPL)
# See LICENSE file for details.
import numpy as np
try:
from itertools import izip as zip
except ImportError: # will be 3.x series
pass
from itertools import cycle, count
from operator import add
import sys
class Hyperspiral(o... |
# Generated by Django 2.1.3 on 2018-12-05 21:02
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("core", "0002_auto_20181205_2102"),
("pokemongo", "0004_community"),
]
operations = [
migrations.Cre... |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import uuid
from azure_devtools.perfstress_tests import PerfStressTest
from azure.identity import DefaultAzureCredential
from azure.identity.aio import DefaultAzureCred... |
"""
Publisher node speed of a single Mobile Robot Wheel
"""
import rclpy
from rclpy.node import Node
from tf2_msgs.msg import TFMessage
from std_msgs.msg import Float32
class MinimalPublisher(Node):
def __init__(self):
super().__init__('minimal_publisher1')
self.publisher1 = self.create_publ... |
days = 256
def calculate(f, day, data):
if day == 0:
return 1
if (f,day) in data:
return data[(f,day)]
if f > 0:
result = calculate(f-1, day-1, data)
else:
result = calculate(8, day-1, data) + calculate(6, day-1, data)
data[(f,day)] = result
return result
with o... |
import re
class EventError(Exception):
pass
class Event(object):
"""
Signal-like object for Socket.IO events that supports
filtering on channels. Registering event handlers is
performed by using the Event instance as a decorator::
@on_message
def message(request, socket, message... |
"""例子兼测试工具."""
import aiofiles
import base64
from sanic import Sanic
from sanic_jinja2 import SanicJinja2
from sanic.response import json
from sanic_mail import Sanic_Mail
app = Sanic(__name__)
jinja = SanicJinja2(app)
Sanic_Mail.SetConfig(
app,
MAIL_SENDER=<你的发送邮箱>,
MAIL_SENDER_PASSWORD=<你的密码>,
MAIL_S... |
@bottle.get("/update/<db_name>/<doc_id>")
def update(db_name, doc_id):
b_path = os.path.join(bottle.data_store, db_name)
c = Connector(db_path)
new_data = request.get("row")
#data = c.format_data()
doc = c.data.update_one({"_id":doc_id}, {"$set":new_data})
if doc is not None:
return True... |
#!/usr/bin/env python
#########################################################################################
#
# Motion correction of fMRI data.
#
# ---------------------------------------------------------------------------------------
# Copyright (c) 2013 Polytechnique Montreal <www.neuro.polymtl.ca>
# Authors: Ka... |
"""Input pipeline for the U-Seg-Net dataset.
The filenames have format "{id}.png".
"""
import os
import sys
sys.path.extend(['..'])
import numpy as np
import tensorflow as tf
from utils.utils import get_args
from utils.config import process_config
appendix = '.png'
class USegNetLoader:
"""
Class that pro... |
#!/usr/bin/python
from os import walk
from os.path import join
import os
classCount = 0
labels = []
filesList = []
X0 = []
y = []
k = 0
root_path = "../images/"
#"""
for x in walk(join(root_path, "Train/")):
filescount = 0
fc = 0
if x[0].__contains__("missclassified"):
continue
if len(x[2]) ... |
# Make a plot of the "best fit" spectra to any object, of arbitrary
# template type. Only works for a single fiber.
#
# Tim Hutchinson, University of Utah, Oct 2014
# t.hutchinson@utah.edu
from time import gmtime, strftime
import numpy as n
from astropy.io import fits
import matplotlib.pyplot as p
p.interactive(True... |
"""
Model Training
Author: Gerald M
Trains the model by using clean-up, pre-processing and augmentation modules.
Can be run from command line with following,
ipython -- trainmodel.py Adam 1e-4 BCE elu 1 GM_UNet 6
to dictate the following:
- loss function
- learning rate
- optimizer
- activation fuction
- number ... |
##
# Copyright (c) 2009-2017 Apple Inc. All rights reserved.
#
# 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, mod... |
import os
import logging
import h5py
import numpy as np
from skimage.io import imread
from tqdm import tqdm
from constants import HEIGHT, WIDTH
logging.getLogger('tensorflow').setLevel(logging.WARNING)
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
... |
#!/opt/anaconda/bin/python
#Classe runSnap legge da una singola cartella i file in essa contenuti
#li ordina in modo decrescente per data e crea
#le coppie per lo start di SNAP
#infine crea il file name da associare all'output di SNAP
import subprocess
import os,sys
import cioppy
import string
ciop = cioppy.Cioppy(... |
#!/usr/bin/env python3
import sys
import lzma
import re
import msgpack
def parse_args(args):
if not args:
return {}
d = {}
args = args.split(',')
for arg in args:
k, v = arg.split('=', 1)
d[k] = v
return d
def parse_scope(scope):
RE = re.compile(r"^(?P<scope>[a-zA-... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 28 10:56:13 2019
@author: nico
"""
import os
import matplotlib.pyplot as plt
import numpy as np
import cmath
#%% Lipieza de gráficos
#os.system ("clear") # limpia la terminal de python
#plt.close("all") #cierra todos los graficos
#%% TRAB... |
"""Connector"""
from typing import Any, Dict, Optional
from .connector import Connector
from .generator import ConfigGenerator, ConfigGeneratorUI
__all__ = ["Connector", "ConfigGenerator", "ConfigGeneratorUI", "connect"]
def connect(
config_path: str,
*,
update: bool = False,
_auth: Optional[Dict[s... |
#
# PyNetlist is an open source framework
# for object-oriented electronic circuit synthesis,
# published under the MIT License (MIT).
#
# Copyright (c) 2015 Jonathan Binas
#
from base import File
import spice
|
from flask_restx import Namespace, fields
user_api = Namespace('user', description='access information about users')
user_dto = user_api.model('user', {
'id': fields.String,
'email': fields.String(required=True, description='the users email address'),
'email_verified': fields.Boolean(required=True),
'... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify ro... |
#!/usr/bin/python3
# model_generator.py
def generate_model():
# generate a keras model
return model
|
# (5A)###################################################
db.define_table(
'lab_tracking',
YES_NO_FIELD,
)
db.define_table(
'lab_tracking_chart',
Field('choose_file', 'upload', uploadfield='file_data'),
Field('file_data', 'blob'),
Field('file_description', re... |
from pyramid.security import Allow, Everyone, Authenticated
class ScorecardRecordFactory(object):
__acl__ = [(Allow, Everyone, "view"), (Allow, Authenticated, "create")]
def __init__(self, request):
pass
|
from django.apps import AppConfig
class ShopManagementConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "shop_management"
verbose_name = "مدیریت فروشگاهها"
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
from website.models import WikumUser
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
users = WikumUser.objects.all()
for user in users:
user.comments_read = ''
user.save() |
# Generated by Django 2.1.2 on 2018-10-16 08:29
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Cr... |
# -*- coding: utf-8 -*-
"""
Utilities for helping to plot cellpy-data.
"""
import os
from io import StringIO
import sys
import warnings
import importlib
import logging
import itertools
import collections
from pathlib import Path
from cellpy.parameters.internal_settings import (
get_headers_summary,
get_header... |
__author__ = 'upendrakumardevisetty'
import sys
accfile = sys.argv[1]
infile = sys.argv[2]
outfile = sys.argv[3]
AI_DICT = {}
with open(accfile, "rU") as acc_in:
for line in acc_in:
AI_DICT[line[:-1]] = 1
skip = 0
with open(infile, "rU") as fh_in:
with open(outfile, "w") as fh_out:
for lin... |
import sys
def magic(x, y):
return x + y * 2
x = sys.argv[1]
y = sys.argv[1]
answer = magic(x, y)
print('The answer is: {}'.format(answer))
|
from __future__ import print_function, division
from collections import namedtuple
import faulthandler
import yaml
import time
from src import *
if __name__ == "__main__":
print("Starting time: {}".format(time.asctime()))
# To have a more verbose output in case of an exception
faulthandler.enable()
... |
# utils init file
import predictors.ArimaAutoregressor
import predictors.RealAutoRegressor |
#!/bin/python
# -*- coding: utf-8 -*-
import numpy as np
from scipy.linalg import sqrtm
from grgrlib.la import tinv, nearest_psd
from numba import njit
from .stats import logpdf
try:
import chaospy
if hasattr(chaospy.distributions.kernel.baseclass, 'Dist'):
def init_mv_normal(self, loc=[0, 0], scale=... |
import States
class Context:
def __init__(self):
self.currentState = States.StateToDo()
def action(self):
self.currentState.action(self)
def actionBack(self):
self.currentState.actionBack(self) |
from typing import Tuple, Union
from scipy.stats import norm
from GPyOpt.util.general import get_quantiles
import numpy as np
from ...core.interfaces import IModel, IDifferentiable
from ...core.acquisition import Acquisition
class LogExpectedImprovement(Acquisition):
def __init__(self, model: Union[IModel, IDif... |
from __future__ import print_function
from cached_property import cached_property
import math
import numpy as np
from rllab import spaces
from rllab.misc import logger
from mme.envs import GridMap
BIG = 1e6
def get_state_block(state):
x = state[0].item()
y = state[1].item()
x_int = np.floor(x)
y_i... |
"""Promises, promises, promises."""
from __future__ import absolute_import, unicode_literals
import re
from collections import namedtuple
from .abstract import Thenable
from .promises import promise
from .synchronization import barrier
from .funtools import (
maybe_promise, ensure_promise,
ppartial, preplace... |
description = 'postion of Monitor: X in beam; Z may be motor'
group = 'lowlevel'
instrument_values = configdata('instrument.values')
tango_base = instrument_values['tango_base']
devices = dict(
prim_monitor_z = device('nicos.devices.generic.ManualMove',
description = 'Monitor axis motor',
abslimi... |
# -*- coding: utf-8 -*-
"""Enhanced E-Reader.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1ZsmtAW6mao5qps5tBq_-gyxBQCEYDDoO
"""
#This code takes a Project Gutenberg book and uses Wikify to add in links to make an enhanced e-Reader.
#NOTE: THIS... |
# -*- coding: utf-8 -*-
# @Date : 18-4-16 下午8:07
# @Author : hetao
# @Email : 18570367466@163.com
# 正在使用的环境 0: 开发环境, 1: 测试环境, 2: 生产环境
ENVIRONMENT = 0
# ===========================================================
# 本地调试
# ===========================================================
# mongodb
DATABASE_HOST = '192... |
# -*- coding: utf-8 -*-
'''
Custom theano class to query the search engine.
'''
import numpy as np
import theano
from theano import gof
from theano import tensor
import parameters as prm
import utils
import average_precision
import random
class Search(theano.Op):
__props__ = ()
def __init__(self,options):
... |
from pyautofinance.common.engine.components_assembly import ComponentsAssembly
from pyautofinance.common.engine.engine import Engine
|
import pika
import json
import psycopg2
CREATE_TABLE = "CREATE TABLE IF NOT EXISTS person (id SERIAL, name VARCHAR(80), gender VARCHAR(6), age integer);"
INSERT_SQL = "INSERT INTO person (name, gender, age) VALUES (%s, %s, %s);"
def callback(ch, method, properties, body):
"""
Method used to consume the messa... |
import re
import sys
def move_ship(from_pos: tuple, from_ori: tuple, cmds: list) -> tuple:
turns = [(1, 0), (0, 1), (-1, 0), (0, -1)]
posX, posY = from_pos
oriX, oriY = from_ori
for cmd, n in cmds:
if cmd == "F":
posX += oriX * n
posY += oriY * n
if cmd == "N... |
# Copyright 2015 The TensorFlow 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... |
from airflow.operators.dagrun_operator import TriggerDagRunOperator
from airflow.sensors.external_task_sensor import ExternalTaskSensor
from dag_checks.base import BaseCheck
class CheckOperatorsReferenceExistingDagTaskIds(BaseCheck):
def __init__(self, *args, **kwargs):
super( # pylint: disable=super-wi... |
strings = ""
integers = 9
floats = 99.09
booleans = False
|
class Mario(object):
def move(self):
print 'i am moving'
class Mushroom(object):
def eat(self):
print 'i am bigger!!'
class BiggerMario(Mario, Mushroom):
def flower(self):
print 'now i can shoot'
bm = BiggerMario()
bm.move()
bm.eat()
bm.flower()
# this shows ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.17 on 2020-11-30 12:37
from __future__ import unicode_literals
from django.db import migrations, connection
class Migration(migrations.Migration):
dependencies = [
('activities', '0034_auto_20201130_1316'),
]
operations = [
]
|
# -*- coding: utf-8 -*-
"""
run_optimization.py generated by WhatsOpt 1.10.4
"""
# DO NOT EDIT unless you know what you are doing
# analysis_id: 942
import sys
import numpy as np
# import matplotlib
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
from run_parameters_init import initialize
from openmdao.api i... |
from typing import List, Type
from .dict_unpacking import DictUnpackingTransformer
from .formatted_values import FormattedValuesTransformer
from .functions_annotations import FunctionsAnnotationsTransformer
from .starred_unpacking import StarredUnpackingTransformer
from .variables_annotations import VariablesAnnotation... |
import argparse
import dask_zarr as dz
import napari
def main(z_url):
# Test example, knowing that the file contains only 3 groups,
# and at most 10 scales
plane_names_scale = [['%s/%s' % (r, s) for r in [0]] for s in range(10)]
# Retrieve a list of stacks to form the pyramid representation of the ... |
"""Checks if RMSE of Model Prediction is as low as expected."""
import pandas as pd
from lifetimes import BetaGeoFitter
from sklearn.metrics import mean_squared_error
import pytest
@pytest.fixture
def load_data_and_model():
"""Loads Customer Lifetime Estimator Model"""
model = BetaGeoFitter(penalizer_coef=0.... |
from flask import render_template,request,redirect,url_for,abort
from . import main
from .forms import UpdateProfile
from ..models import User
from flask_login import login_required,current_user
from .. import db,photos
import markdown2
@main.route('/')
def index():
'''
View root page function that returns t... |
import pathlib
from setuptools import setup, find_packages
ROOT_DIR = pathlib.Path(__file__).parent
README = (ROOT_DIR / "README.md").read_text()
setup(
name="poem_parser",
version="0.0.4",
description="Parse poems into stressed and unstressed syllables.",
long_description=README,
long_descriptio... |
"""Build sql queries from template to retrieve info from the database"""
import os.path
import pathlib
from functools import lru_cache
from mako.template import Template
from ._constants import _DB_TABLE_NAMES
__all__ = ["get_query"]
QUERY_DIR = os.path.join(os.path.dirname(__file__), "queries")
def get_query(qu... |
"""Web tests for pixivpy3.api.BasePixivAPI."""
import pytest
from jsonschema import validate
from pixivpy3.api import BasePixivAPI, PixivError as PixivPyError
from .schemas import AUTH_RESPONSE_SCHEMA
from .secret import SECRET
class TestBasePixivAPI:
"""Web tests for pixivpy3.api.BasePixivAPI."""
@pytest.... |
from corehq.apps.userreports.extension_points import custom_ucr_expressions
@custom_ucr_expressions.extend()
def abt_ucr_expressions():
return [
('abt_supervisor', 'custom.abt.reports.expressions.abt_supervisor_expression'),
('abt_supervisor_v2', 'custom.abt.reports.expressions.abt_supervisor_v2_e... |
# using 60, 20, 20 split
import os
from sklearn.model_selection import train_test_split
NUM_CLASSES = 10
data_path = './original/'
for i in range(NUM_CLASSES):
curr_dir_path = data_path + 'c' + str(i) + '/'
xtrain = labels = os.listdir(curr_dir_path)
x, x_test, y, y_test = train_test_split... |
from django.db import models
from django.contrib.auth.models import AbstractUser, UserManager
from uuid import uuid4
# Create your models here.
class User(AbstractUser):
address = models.CharField(max_length=2000)
contactNumber = models.CharField(max_length=15)
object = UserManager()
# Products mod... |
from tkinter import *
from tkinter.ttk import *
from itertools import chain
def get_events(widget):
return set(chain.from_iterable(widget.bind_class(cls) for cls in widget.bindtags()))
root = Tk()
a = get_events(Button())
print(a)
root.destroy() |
from itertools import product
from typing import Dict, Tuple, Union, Any
from npsem.model import StructuralCausalModel
from npsem.utils import combinations
from npsem.where_do import POMISs, MISs
def SCM_to_bandit_machine(M: StructuralCausalModel, Y='Y') -> Tuple[Tuple, Dict[Union[int, Any], Dict]]:
G = M.G
... |
# -*- coding: utf8 -*-
from __future__ import absolute_import
from __future__ import division, print_function, unicode_literals
import unittest
from sumy.models.dom._sentence import Sentence
from sumy.summarizers.sum_basic import SumBasicSummarizer
from sumy._compat import to_unicode
from ..utils import build_docume... |
# import findspark
# findspark.init()
from pyspark import SparkConf
from pyspark.sql import SparkSession
# 构建SparkSession
class SparkSessionBase(object):
SPARK_APP_NAME = None
# SPARK_URL = "yarn"
SPARK_EXECUTOR_MEMORY = "16g"
SPARK_EXECUTOR_CORES = 6
SPARK_EXECUTOR_INSTANCES = 6
ENABLE_HIVE... |
from optparse import make_option
from django.core import exceptions
from django.core.management.base import BaseCommand
from django.utils.encoding import force_str
from django.db.utils import IntegrityError
from django.db import connection
from django_tenants.clone import CloneSchema
from django_tenants.utils import ge... |
# Copyright (c) 2010 Jeremy Thurgood <firxen+boto@gmail.com>
#
# 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, mod... |
import pytest
import sys
sys.path.insert(0, '..') # insert everything from .. to path search
import os
import pandas as pd
import numpy as np
import dash_bootstrap_components
from src.navbar import *
def test_Navbar():
'''
'''
navbar = Navbar()
assert navbar
assert isinstance(navbar, dash_bootstrap... |
def _is_windows(ctx):
return ctx.os.name.lower().find("windows") != -1
def _wrap_bash_cmd(ctx, cmd):
if _is_windows(ctx):
bazel_sh = _get_env_var(ctx, "BAZEL_SH")
if not bazel_sh:
fail("BAZEL_SH environment variable is not set")
cmd = [bazel_sh, "-l", "-c", " ".join(["\"%s\... |
import django
SECRET_KEY = 'stuffandnonsense'
APPS = [
'nano.activation',
'nano.badge',
'nano.blog',
'nano.chunk',
'nano.comments',
'nano.countries',
'nano.faq',
'nano.link',
'nano.mark',
'nano.privmsg',
'nano.tools',
'nano.user',
]
DATABASES = {
'default': {
... |
import nextcord
from nextcord.ext import commands
import config
import os
import motor.motor_asyncio
from utils.mongo import Document
# Dont forget to enable all intents in the developer portal.
async def get_prefix(bot, message):
if not message.guild:
return commands.when_mentioned_or(bot.DEFAULTPREFIX)(b... |
x = set()
print(type(x))
x.add(1)
print(x)
x.add(2)
print(x)
x.add(1)
print(x)
l = [1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4]
print(set(l))
# Booleans
a = True
print(a)
print(type(a))
print(11 > 2)
b = None
print(b)
print(type(b))
b = 'a'
print(b)
|
import torch
from hearline.models.transformers.attention import MultiHeadedAttention
from hearline.models.transformers.embedding import PositionalEncoding
from hearline.models.transformers.encoder_layer import EncoderLayer
from hearline.models.transformers.layer_norm import LayerNorm
from hearline.models.transformers.p... |
def mes(valor):
meses = {1: 'January',
2: 'February',
3: 'March',
4: 'April',
5: 'May',
6: 'June',
7: 'July',
8: 'August',
9: 'September',
10: 'October',
11: 'November',
12:... |
# -*- coding: utf-8 -*-
from denite import util
from .base import Base
import os
import site
# Add external modules
path_to_parent_dir = os.path.abspath(os.path.dirname(__file__) + '/../')
path_to_modules = os.path.join(path_to_parent_dir, 'modules')
site.addsitedir(path_to_modules)
site.addsitedir(os.path.join(path... |
import dataclasses
import mock
import pytest
from pca.domain.entity import (
AutoId,
Entity,
NaturalId,
SequenceId,
Uuid4Id,
)
@pytest.fixture(scope="session")
def data():
return {"frame_type": "gravel", "wheel_type": "road"}
def entity_constructor(id_field=None):
id_field = id_field o... |
from .models import Startup, Tag
from django.shortcuts import (get_object_or_404, render)
def homepage(request):
return render(
request,
'organizer/tag_list.html',
{'tag_list':Tag.objects.all()})
def tag_detail(request, slug):
tag = get_object_or_404(
Tag, slug__iexact=slug)
return render(
request, 'or... |
# Export data to an excel file. Use different sheets for different sections
|
import networkx as nx
import osmnx as ox
import json
data = {}
ox.config(use_cache=True, log_console=True)
G = ox.graph_from_place('Piedmont, California, USA', network_type='drive')
# G = ox.graph_from_place('beijing, china', network_type='drive', which_result=2)
# G = ox.graph_from_bbox(40.19, 39.70,116.75,116.05,net... |
objects = []
ans = 0
a = []
for i in objects:
if i not in a:
a.append(i)
ans += 1
print(ans)
|
# -*- coding: utf-8 -*-
"""
Created on Wed May 2 20:26:55 2018
@author: Ali Nasr
"""
# import important
import tensorflow as tf
import cv2
import numpy as np
import tensorflow_hub as hub
import os, os.path
from random import shuffle, sample
import re
data_path = "/home/ali/PycharmProjects/tensorHub/data/"
label_zer... |
#!/usr/local/bin/python3
# Make Shap.py
# imports
import sys
import pandas as pd
import numpy as np
np.random.seed(0)
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import Pipeline
f... |
from __future__ import print_function, division
import GLM.constants, os, pdb, pandas, numpy, logging, crop_stats
import pygeoutil.util as util
class CropFunctionalTypes:
"""
"""
def __init__(self, res='q'):
"""
:param res: Resolution of output dataset: q=quarter, h=half, o=one
:r... |
import numpy as np
import torch
import hexagdly as hex
import pytest
class TestConv2d(object):
def get_array(self):
return np.array(
[[j * 5 + 1 + i for j in range(8)] for i in range(5)], dtype=np.float32
)
def get_array_conv2d_size1_stride1(self):
return np.array(
... |
import cv2
import numpy as np
img = cv2.imread("simpsons.jpg")
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
template = cv2.imread("barts_face.jpg", cv2.IMREAD_GRAYSCALE)
w, h = template.shape[::-1]
result = cv2.matchTemplate(gray_img, template, cv2.TM_CCOEFF_NORMED)
loc = np.where(result >= 0.4)
fo... |
from flask import Flask,request, session, Response
import uuid
import boto3
from config import S3_BUCKET, S3_KEY, S3_SECRET, host, user, passwd, database, secret_key
from flask_cors import CORS
import json
from upload_to_ipfs import *
app = Flask(__name__)
CORS(app)
aws = boto3.resource(
's3... |
'''7. Agora faça uma função que recebe uma palavra e diz se ela é um
palíndromo, ou seja, se ela é igual a ela mesma ao contrário.
Dica: Use a função do exercício 5.'''
#Verificando se a palavra é um palindromo
#Receber palavra para verificar
palavra = input('Informe uma palavra: ').lower()
analise = palavra
x = li... |
from lib import requests
import uuid
import webbrowser
import threading
import httplib
import json
import time
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import urlparse
from workflow import Workflow
auth_url = "https://www.wunderlist.com/oauth/authorize"
callback = "http://127.0.0.1:8080"
class O... |
import matplotlib.pyplot as plt
from structure_factor.point_processes import HomogeneousPoissonPointProcess
from structure_factor.spatial_windows import BallWindow
from structure_factor.structure_factor import StructureFactor
from structure_factor.tapered_estimators_isotropic import (
allowed_k_norm_bartlett_isotr... |
# *********************************************************************************
# REopt, Copyright (c) 2019-2020, Alliance for Sustainable Energy, LLC.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions a... |
# Generated by Django 2.2.20 on 2021-07-09 17:32
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('invitations', '0010_invitation_meta'),
]
operations = [
migrations.AlterField(
model_name='inv... |
#! /usr/bin/env python
# Copyright (c) 2016 Zielezinski A, combio.pl
import argparse
import sys
from alfpy import word_vector
from alfpy import word_distance
from alfpy.utils import distmatrix
from alfpy.utils import seqrecords
from alfpy import word_pattern
from alfpy.version import __version__
def get_parser():
... |
import paste.urlmap
from hsm import flags
FLAGS = flags.FLAGS
def root_app_factory(loader, global_conf, **local_conf):
if not FLAGS.enable_v1_api:
del local_conf['/v1']
return paste.urlmap.urlmap_factory(loader, global_conf, **local_conf)
|
#-*- coding: utf-8 -*-
import os,shutil,time
import glob
import subprocess
from random import randint
import threading
import pdb
def geraNome():
a = randint(0,90000)
ext ='.avi'
nome_arquivo = str(a)+ext
return nome_arquivo
def retira_audio(video):
print(video)
sem_audio = video
nome_audi... |
from machine.plugins.base import MachineBasePlugin
from machine.plugins.decorators import respond_to, listen_to, process, on
import re, os
from datetime import datetime
from base.slack import Slack
from base.calendar_parser import Calendar, Event
from utils.command_descriptions import Command, CommandDescriptions
from... |
from .api import (PoloCurrencyPair,
Poloniex,
POLONIEX_DATA_TYPE_MAP,
timestamp_to_utc,
datetime, pd,
timestamp_from_utc,
DATE, requests,
polo_return_chart_data)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.