content stringlengths 5 1.05M |
|---|
from unittest import TestCase
from algotrader.app.backtest_runner import BacktestRunner
from algotrader.trading.config import Config, load_from_yaml
from algotrader.trading.context import ApplicationContext
from tests import test_override
class StrategyPersistenceTest(TestCase):
start_date = 19930101
intrim_... |
def ajuda(com):
help(com)
def titulo(msg, cor=0):
tam = len(msg) + 4
print('-' * tam)
print(f' {msg}')
print('-' * tam)
comando = ''
while True:
titulo('SISTEMA DE AJUDA PyHELP')
comando = str(input('Funca ou Biblioteca > '))
if comando.upper() == 'FIM':
break
else:
... |
from src.core.models import TimestampedModel
from src.users.managers import UserManager
from src.users.validators import (
validate_unique_username,
validate_username_valid_characters_only,
)
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.db import models
from django.util... |
from django import forms
from django.core.exceptions import ValidationError
from grandchallenge.publications.models import (
Publication,
identifier_validator,
)
from grandchallenge.publications.utils import get_identifier_csl
class PublicationForm(forms.ModelForm):
def clean_identifier(self):
id... |
class MorseCode():
def __init__(self):
self.__dic_plain = { 'A':'.-', 'B':'-...',
'C':'-.-.', 'D':'-..', 'E':'.',
'F':'..-.', 'G':'--.', 'H':'....',
'I':'..', 'J':'.---', 'K':'-.-',
'L':'.-..', 'M':'--', 'N':'-.',
'O':'---', 'P':'.--.', 'Q':'-... |
# -*- coding: utf-8 -*-
############################################################################
#
# Copyright © 2013, 2014 OnlineGroups.net and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany th... |
from .emojipedia import Emojipedia, Emoji
|
import re
import ssl
from retrying import retry
import urllib.request
wordlist_re = re.compile(
r'<a href="/wordlist/(\w+.shtml)" target="_top">\w+</a><BR>')
wordlist_name_re = re.compile(
r'<h1 class=body-title__title>(.+?)</h1>')
words_re = re.compile(
r'<div class=wordlist-item>([\w -\\\']+?)</div>')
... |
"""This module contains the general information for AdaptorHostEthIf ManagedObject."""
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class AdaptorHostEthIfConsts:
IF_TYPE_VIRTUAL = "virtual"
MAC_AUTO = "AUTO"
UPLINK_PORT_0 = "0"
... |
from PyQt5.QtGui import QImage
from PIL import Image
import numpy as np
def numpyQImage(image):
qImg = QImage()
if image.dtype == np.uint8:
if len(image.shape) == 2:
channels = 1
height, width = image.shape
bytesPerLine = channels * width
qImg ... |
#Copyright (c) 2014 Samsung Electronics Co., Ltd 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
#
# Unle... |
from src import Camera, Tracer, World, Stereo
|
import pygame
import random
import time
import sys
pygame.init()
# definicion de colores
blanco = pygame.Color(255,255,255)
negro = pygame.Color(0,0,0)
rojo = pygame.Color(255,0,0)
rojo_o = pygame.Color(100,0,0)
gris = pygame.Color(200,200,200)
verde = pygame.Color(0,250,100)
verde_o = pygame.Color(0,150,50)
morado = ... |
# 要添加一个新单元,输入 '# %%'
# 要添加一个新的标记单元,输入 '# %% [markdown]'
# %%
import numpy as np
from matplotlib import pyplot as plt
import os
from matplotlib import font_manager
import matplotlib as mpl
zhfont1 = font_manager.FontProperties(fname='SimHei.ttf')
from mpl_toolkits.axes_grid1 import make_axes_locatable
import pandas as ... |
# Corrigido
print('Exercício 010')
print()
# Bloco de entrada
carteira = float(input('Informe quanto você tem na sua carteira: '))
print()
# Bloco de cálculo
dólar = carteira / 5.47
# Bloco de saída
print('Você pode comprar $ {:.2f} dólares com R$ {} reais na carteira.'.format(
dólar, carteira))
print()
|
"""
Write an iterative function iterPower(base, exp) that calculates the exponential baseexp by simply using successive multiplication. For example, iterPower(base, exp) should compute baseexp by multiplying base times itself exp times. Write such a function below.
This function should take in two values - base can be... |
from SuperSafety.Utils.utils import limit_phi, load_conf
from SuperSafety.Supervisor.Dynamics import run_dynamics_update
import numpy as np
from matplotlib import pyplot as plt
import numpy as np
from numba import njit
class Modes:
def __init__(self, conf) -> None:
self.time_step = conf.kernel_time_st... |
import math
import re
from threading import Thread
import serial
from ...LightSkin import ForwardModel, LightSkin, EventHook
class ArduinoConnectorForwardModel(ForwardModel):
""" Connects to an Arduino running the Arduino Connector Script on the given port with the given baudrate
Parses the input in a n... |
# -------------------------------------------------------------------------------
# Copyright IBM Corp. 2016
#
# 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/licens... |
import numpy as np
from numpy.testing import assert_equal
from terrapin.flow_direction import aread8, convert_d8_directions
test_sets = [
# source:
# http://resources.arcgis.com/en/help/main/10.1/index.html#//009z00000051000000
# lower right corner of flow accumulation array is 2 in url but it should be 1... |
# Copyright 2019-2019 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" fil... |
# Copyright 2019 Adobe
# All Rights Reserved.
#
# NOTICE: Adobe permits you to use, modify, and distribute this file in
# accordance with the terms of the Adobe license agreement accompanying
# it. If you have received this file from a source other than Adobe,
# then your use, modification, or distribution of it ... |
import os
import sys
from time import sleep
# Logo do programa!
print('-' * 41)
print(' Calculadora Simples Version 1.0')
print('-' * 41)
print(' Seja bem-vindo!')
print('-' * 41)
sleep(3)
os.system('clear')
# Valores para usar na Opção!
n1 = int(input('1# Digite um valor: '))
n2 = int(input('2# Digit... |
from __future__ import division
import os, time, scipy.io
import tensorflow as tf
import numpy as np
from PIL import Image
tf.logging.set_verbosity(tf.logging.INFO)
# os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
from dataset import SID_dataset as SID_dataset
from network import Netowrk as Netowrk
###############
## Data
#... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
from hoppy.timing.timing import EventFits
__author__ = 'Teruaki Enoto'
__date__ = '2020 September 5'
__version__ = '0.01'
def get_parser():
"""
Creates a new argument parser.
"""
usage = """
plot event fits file (PULSE_PHASE)
"""
pa... |
from django.apps import AppConfig
class MainConfig(AppConfig):
name = 'main'
SOCIALS = {
'vk': 'https://vk.com/goto_msk',
'instagram': 'https://www.instagram.com/goto_goto_goto/',
'facebook': 'https://www.facebook.com/GoToCampPage/',
'telegram': 'https://t.me/goto_channel'
}
|
'''
Based on https://stackoverflow.com/questions/44164749/how-does-keras-handle-multilabel-classification
'''
import warnings
try:
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import SGD
def keras_fit(T, Y, **kwargs):
if Y.ndim == 1:
... |
from z3 import Implies
import numpy as np
from z3 import Implies
from quavl.lib.expressions.qbit import Qbits
from quavl.lib.models.circuit import Circuit, Method
from quavl.lib.operations.gates import Rx, Rz, V, CNOT, V_dag
def repair_toffoli():
# Initialize circuit
a, b, c = Qbits(['a', 'b', 'c'])
n =... |
from . import Base
from sqlalchemy import Column, String, Integer, Enum as EnumCol, Date, ForeignKey
from sqlalchemy.orm import relationship
from enum import Enum
class TaskType(Enum):
Note = "Note"
Task = "Task"
class Task(Base):
__tablename__ = "task"
id = Column(Integer, primary_key=True, autoin... |
"""Core Module
==============
This module includes the abstraction of a Simulation Model and the definition of a Path.
"""
from .base_model import BaseModel, ModelState
from .path import Path
|
import pulp
from graphviz import Digraph
from discord import Embed, File
from tabulate import tabulate
import math
import ada.emoji
from ada.result_message import ResultMessage
from ada.breadcrumbs import Breadcrumbs
class HelpResult:
def __str__(self):
return """
ADA is a bot for the videogame Satisfact... |
import numpy
import dask.dataframe as dd
import operator
import collections
import re
import logging
#logging.basicConfig(format='%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s', level=logging.NONE)
# build successor relation and edges among concepts
def successor(concepts,c1,c2):
return c1 < c2 an... |
import io, csv
from flask import (
Blueprint,
render_template,
request,
redirect,
url_for,
make_response,
session,
)
from helpers.hubspot import create_client
from helpers.session import SessionKey
from auth import auth_required
from hubspot.crm import ObjectType
from hubspot.crm.contacts im... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import importlib
import os
import sys
from io import StringIO
from PySide2.QtCore import Qt
from PySide2.QtGui import QKeyEvent
from PySide2.QtWidgets import QWidget, QMessageBox
from tensorflow.keras.models import Model, load_model
from MnistClassifier.Ui_MainWidget im... |
# DESCQA galaxy catalog interface. This defines the GalaxyCatalog base class
# and, on import, registers all of the available catalog readers. Convenience
# functions are defined that enable automatic detection of the appropriate
# catalog type.
# Note: right now we are working with galaxy properties as floats, with
#... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import getopt
import sys
from _datetime import datetime
from fmc_rest_client import FMCRestClient
from fmc_rest_client.resources import *
logging.basicConfig(level=logging.INFO)
fmc_server_url = None
username = None
password = None
obj_types = []
obj_name_prefix = None... |
from django.shortcuts import render
from .models import Portfolio
def portfolio(request):
portfolios = Portfolio.objects
return render(request, 'portfolio/portfolio.html', {'portfolios': portfolios})
|
from ...config import LennyBotSourceConfig
from .isource import ISource
from ..github import GitHubService
import re
import requests
class GithubSource(ISource):
def __init__(self, name, config: LennyBotSourceConfig, github: GitHubService) -> None:
self._name = name
self._github = github
... |
# -*- coding: utf-8; -*-
"""
Gui implementation for gui created via qt-designer.
"""
__author__ = "Christoph G. Keller"
__copyright__ = "Copyright 2017"
__credits__ = [""]
__license__ = "MIT"
__version__ = "2.0.0"
__maintainer__ = "Christoph G. Keller"
__email__ = "christoph.g.keller@gmail.com"
__status__ ... |
from flask_restful import Resource, reqparse, abort
from flask import request
from lista.models.service_model import ServiceModel
from lista.schemas.service_schema import ServiceSchema
class ServiceResource(Resource):
parser = reqparse.RequestParser()
parser.add_argument('name',
type=st... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from PIL import Image, ImageDraw
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
import seaborn as sns
import tqdm
class DetectionDataset(Dataset)... |
def _repr(mat,notes,dFrame):
from shutil import get_terminal_size as gts
old = None
d0,d1 = mat.dim
feats = mat.features
ind_level = mat.index.level
col_place_holder = mat.DISPLAY_OPTIONS["col_place_holder"]
row_place_holder = mat.DISPLAY_OPTIONS["row_place_holder"]
left_seperator ... |
import numpy as np
import tensorflow as tf
tensor_2d = np.array([(1, 2, 3, 4), (4, 5, 6, 7), (8, 9, 10, 11), (12, 13, 14, 15)])
print(tensor_2d)
print(tensor_2d[2][3])
print(tensor_2d[0:2, 0:2])
matrix1 = np.array([(2, 2, 2), (2, 2, 2), (2, 2, 2)], dtype='int32')
matrix2 = np.array([(1, 1, 1), (1, 1, 1), (1, 1, 1)], ... |
# Generated by Django 4.0.1 on 2022-01-06 14:01
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('verzelapp', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='modulo',
name='app_label',
),
... |
from . HaarClassifierFunctions import faceFinder as fd
from . HaarClassifierFunctions import haarTraining as tr
from . HaarClassifierFunctions import boundingBoxes as bd
import cv2
import os
import numpy as np
def classifierceleb(path):
test_img = cv2.imread(path)
print(test_img)
face_detected,... |
"""Simple watcher that prints wikipedia changes as they occur."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
import pprint
import argparse
import pywikibot
import requests
import sseclient
from googleapiclient import errors as google_api_er... |
#programa ainda não finalizado
n = []
for c in range(0, 5):
valor = int(input('Digite um valor: '))
if c == 0 or valor > n[-1]:
n.append(valor)
print('Valor adicionado ao final da lista.')
else:
pos = 0
while pos < len(n):
if valor <= n[pos]: #TypeError
... |
from collections import defaultdict
from typing import List, Any, Set, Tuple, Iterable
import pandas as pd
def printUniqueTokens(series: pd.Series):
unique_series = series.unique()
token_count = {}
for a in unique_series:
tokens = a.split(' ')
for t in tokens:
if t not in toke... |
from django.conf import settings
import django.contrib.postgres.fields
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('auth', '0011_update_proxy_permis... |
from unittest import TestCase
from src.chunker import Chunker
class TestChunker(TestCase) :
def test_chunker_yields_list_with_buffered_size(self) :
chunks = Chunker(range(5), 3)
chunk = next(chunks)
self.assertEqual(len(chunk), 3)
self.assertListEqual(chunk, [0,1,2])
... |
#!/usr/bin/env python3
import os
import sys
from setuptools import setup, find_packages
VERSION = os.environ.get('GITHUB_REF', '0.0.4').replace('refs/tags/v', '')
is_wheel = 'bdist_wheel' in sys.argv
_license = ""
if os.path.exists('LICENSE'):
with open('LICENSE') as lf:
_license = lf.readline().rstrip(... |
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from torchvision import transforms
import numpy as np
import cv2
from models.single_track import SiamRPNPP as base_model
from dataset.util import generate_anchor
class SiamRPNPP(nn.Module):
def __init__(self, tra... |
import argparse
from utils import levenshtein
import pdb
import re
def clean(label):
alphabet = [a for a in '0123456789abcdefghijklmnopqrstuvwxyz* ']
label = label.replace('-', '*')
nlabel = ""
for each in label.lower():
if each in alphabet:
nlabel += each
return nlabel
parse... |
"""
Create a pedestal file from an event file using the target_calib Pedestal
class
"""
from targetpipe.io.camera import Config
Config('checs')
from matplotlib.ticker import MultipleLocator, FormatStrFormatter, \
FuncFormatter, AutoMinorLocator
from traitlets import Dict, List
from ctapipe.core import Tool, Compon... |
import django_filters
import htmlgenerator as hg
from django import forms
from django.utils.html import mark_safe
from django.utils.translation import gettext as _
from django_countries.widgets import LazySelect
from .button import Button
from .notification import InlineNotification
class Form(hg.FORM):
@staticm... |
import sys
import pytest
sys.path.append(".")
sys.path.append("..")
sys.path.append("../..")
from Hologram.Network import Network
class TestNetwork(object):
def test_create_network(self):
network = Network()
def test_get_invalid_connection_status(self):
network = Network()
with pytes... |
from django.urls import path
from rest_framework_simplejwt import views as jwt_views
from . import views
from rest_framework_simplejwt.views import TokenRefreshView, TokenObtainPairView
urlpatterns = [
path('login/', views.loginView.as_view(), name='obtain_token'),
path('nlogin/', views.adminTokenObtainPairVie... |
"""The managers for the models
"""
from django.contrib.auth.models import UserManager as BaseUserManager
class UserManager(BaseUserManager):
"""The user manager
"""
def create_user(self, username, email=None, password=None, **extra_fields):
"""Create a user.
:param username: The user nam... |
"""
Project: RadarBook
File: ecef_to_lla.py
Created by: Lee A. Harrison
On: 3/18/2018
Created with: PyCharm
Copyright (C) 2019 Artech House (artech@artechhouse.com)
This file is part of Introduction to Radar Using Python and MATLAB
and can not be copied and/or distributed without the express permission of Artech House... |
x,y=map(int,input().split())
z=0
for j in range(x,y):
z=j
a=0
for i in range(len(str(j))):
r=j%10
a=a+r**3
j=j//10
if a==z:
print(a,end=" ")
print()
|
import os
from .base import *
API_DB_URL = os.environ.get("API_DB_URL", "sqlite+aiosqlite:///db.sqlite")
|
# -*- coding: utf-8 -*-
from django.conf.urls import url, patterns
from django.contrib import admin
from .views import ChatRoomTokenView, ChatRoomView
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^room/(?P<token>\w{32})$', ChatRoomView.as_view(), name='chat-room'),
url(r'^new-room/$', ChatRoomT... |
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 or agreed ... |
from panflute import run_filter, Header
def increase_header_level(elem, doc):
if type(elem)==Header:
if elem.level < 6:
elem.level += 1
else:
return []
def main(doc=None):
return run_filter(increase_header_level, doc=doc)
if __name__ == "__main__":
main() |
# -*- coding: utf-8 -*-
import time
import json
import requests
import logging
import pika
from config import PROXY
from twython import TwythonStreamer
class sampleStreamer(TwythonStreamer):
"""
Retrieve data from the Twitter Streaming API.
The streaming API requires
`OAuth 1.0 <http://en.wikipedia.... |
""" Package for cookie auth modules. """
__author__ = "William Tucker"
__date__ = "2020-02-14"
__copyright__ = "Copyright 2020 United Kingdom Research and Innovation"
__license__ = "BSD - see LICENSE file in top-level package directory"
|
"""
Tests scikit-learn's KNeighbours Classifier and Regressor converters.
"""
import unittest
from distutils.version import StrictVersion
import numpy
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsRegressor, KNeighborsClassifier
from sklearn.pi... |
7
8
9
10
|
import sys
# mode is one of 'left', 'right', 'center'
def horizontal_align_print(s, width, mode='left', offsetChar=' ', end='\n',
os=sys.stdout):
p = _print_to_file_func(os)
if mode[0] == 'l': # left
offset = width - len(s)
p(s, end='')
for _ in range(offs... |
from os.path import join, dirname
import datetime
# import pandas as pd
# from scipy.signal import savgol_filter
# from bokeh.io import curdoc
# from bokeh.layouts import row, column
# from bokeh.models import ColumnDataSource, DataRange1d, Select
# from bokeh.palettes import Blues4
# from bokeh.plotting import figur... |
#!/usr/bin/env python3
import requests
import os
import json
from requests.auth import HTTPBasicAuth
import requests_unixsocket
MFMODULE_RUNTIME_HOME = os.environ['MFMODULE_RUNTIME_HOME']
ADMIN_USERNAME = "admin"
ADMIN_PASSWORD = os.environ['MFADMIN_GRAFANA_ADMIN_PASSWORD']
GRAFANA_SOCKET = "%s/tmp/grafana.sock" % MF... |
import os
from dotenv import load_dotenv
load_dotenv()
AV_API_KEY = os.getenv("AV_API_KEY", "value does not exist")
AV_API_KEY_2 = os.getenv("AV_API_KEY_2", "value does not exist")
BINANCE_KEY = os.getenv("BINANCE_KEY", "Binance key not found")
BINANCE_SECRET = os.getenv("BINANCE_SECRET", "Binance secret not found") |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
# -*- coding: utf8 -*-
#
# 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 or agreed to in... |
"""
Lab jack GUI
"""
import datetime
import lab_jack_lib as lj
import PySimpleGUI as sg
def logprint(message=''):
"""
printing ='on'
print and return None
"""
form = '[{}, {}]'.format(datetime.datetime.now(), message)
print(form)
def now_datetime(type=1):
"""
typ... |
print("Hello Open Source")
|
def extractLightNovelsWorld(item):
"""
Light Novels World
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
# This comes first, because it occationally includes non-numbered chapters.
if 'Tsuki ga Michibiku Isekai Douchuu (POV)' in item['tags']:
if not postfix and '-' in item['titl... |
from torchvision import datasets, transforms
from core.data.data_loaders.base import BaseDataLoader
class CIFAR100Loader(BaseDataLoader):
""" CIFAR100 data loading + transformations """
def __init__(self, data_dir, batch_size,
shuffle=True, validation_split=0.0,
training=Tru... |
from pint import UnitRegistry
ureg = UnitRegistry()
ureg.define('kn_cm2 = kilonewton / centimeter ** 2 = kn_cm2')
ureg.define('kNcm = kilonewton * centimeter = kncm')
ureg.define('kNm = kilonewton * meter = knm')
_Q = ureg.Quantity
e = 0.00001 |
'''
Created on Jan 23, 2018
@author: kyao
'''
import numpy as np
import typing
from d3m.metadata import hyperparams, params
from d3m import container
from d3m.exceptions import InvalidArgumentValueError
import d3m.metadata.base as mbase
from sklearn.random_projection import johnson_lindenstrauss_min_dim, GaussianRa... |
"""IPs domain API."""
from ..base import ApiDomainResource
class IPs(ApiDomainResource):
"""
IPs domain resource.
"""
api_endpoint = "ips"
DOMAIN_NAMESPACE = True
def list(self):
"""
List the existing IPs on the domain.
"""
return self.request("GET")
def ... |
"""
pcolor: for plotting pcolor using matplotlib
"""
import matplotlib.pyplot as plt
import numpy as np
import os
import time
def is_linux():
import platform
s = platform.system()
return {
'Linux': True,
'Darwin': False,
'Windows': False,
}[s]
def is_mac():
import platform... |
from empire.python.typings import *
from empire.enums.base_enum import BaseEnum
class TimeUnits(BaseEnum):
NANOS: Final[int] = 0
MICROS: Final[int] = 1
MILLIS: Final[int] = 2
SECONDS: Final[int] = 3
MINUTES: Final[int] = 4
HOURS: Final[int] = 5
DAYS: Final[int] = 6
class TimeUtil:
@s... |
from __future__ import division
import numpy as np
from mpl_toolkits.axes_grid1 import make_axes_locatable
from numpy.random import rand
#import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import cPickle as pickle
import pylab as plb
import os, sys
def run():
'''
Read results of clash score servey... |
# 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 or agreed to in writing, software
# distributed under the... |
from utils.data_reader import prepare_data_for_feature, generate_vocab, read_data
from utils.features import get_feature
from utils.utils import getMetrics
from utils import constant
from baseline.baseline_classifier import get_classifier
from baseline.baseline_features import get_features_for_prediction
import numpy a... |
"""Users models."""
from django.contrib.auth.models import AbstractUser
from django.db import models
class User(AbstractUser):
"""Custom user.
This inherits all the fields from Django's basic user,
but also has an avatar.
"""
def __str__(self) -> str:
"""Represent the user by their full ... |
n1 = int(input('Digite o numero inicial: '))
razao = int(input('Digite sua razão: '))
contador = 10
while contador != 0:
n1 += razao
print(n1)
contador -= 1
termos = int(input('Se Você deseja adicionar mais termos, informe o numero, caso contrario, digite 0: '))
contador += termos
while termos > 0:
whil... |
import magicbot
import wpilib
import ctre
import wpilib.drive
from robotpy_ext.common_drivers import navx
class MyRobot(magicbot.MagicRobot):
def createObjects(self):
self.init_drive_train()
def init_drive_train(self):
fl, bl, fr, br = (30, 40, 50, 10) # practice bot
br, fr, bl, fl... |
from notipy_me import Notipy
from repairing_genomic_gaps import cae_200, build_synthetic_dataset_cae, train_model
if __name__ == "__main__":
with Notipy():
model = cae_200()
train, test = build_synthetic_dataset_cae(200)
model = train_model(model, train, test, path="single_gap")
|
"""Tornado handlers for security logging."""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from tornado import web
from . import csp_report_uri
from ...base.handlers import APIHandler
class CSPReportHandler(APIHandler):
"""Accepts a content security policy v... |
"""exercism bob module."""
def response(hey_bob):
"""
Model responses for input text.
:param hey_bob string - The input provided.
:return string - The respons.
"""
answer = 'Whatever.'
hey_bob = hey_bob.strip()
yelling = hey_bob.isupper()
asking_question = len(hey_bob) > 0 and he... |
import os
"""
Guild how to read your graph
Description:
I provided several methods to read graph-network data but not limit other formats, please implement your own format as your need
### Graph Kinds & Data Structure
UNDIRECTED-GRAPH <SYMMETRIC-MATRIX, UPPER-MATRIX>
DIRECTED-GRAPH ... |
## Fake Binary
## 8 kyu
## https://www.codewars.com/kata/57eae65a4321032ce000002d
def fake_bin(x):
num = ''
for char in x:
if int(char) < 5:
num += '0'
else:
num += '1'
return num |
#!/usr/bin/env python3
import datetime
import argparse
from pathlib import Path
import importlib
target = ''
technique_info = {
'blackbot_id': 'T1530',
'external_id': '',
'controller': 'lightsail_download_ssh_keys',
'services': ['Lightsail'],
'prerequisite_modules': [],
'arguments_to_autocomp... |
import abc
import argparse
import functools
import os
import pathlib
import shutil
import numpy as np
import pandas as pd
def parse_args():
parser = argparse.ArgumentParser(description="Client allocation")
parser.add_argument('-c', '--train-clients', default=100, type=int)
parser.add_argument('-t', '--test-cli... |
# coding=utf-8
import argparse
import os
import random
import numpy as np
import torch
from torch.utils.data import DataLoader
from torch import nn
import pandas as pd
from Source import utils
import time
import logging
logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s',
... |
"""
Module: mercadopago/__init__.py
"""
from .sdk import SDK
|
import cv2 as cv
from utilities import show_in_matplotlib
def get_channel(img, channel):
b = img[:, :, channel]
# g = img[:,:,1]
# r = img[:,:,2]
return b
def remove_channel(img, channel):
imgCopy = img.copy()
imgCopy[:, :, channel] = 0
return imgCopy
def remove_channel_v0(img, channe... |
map = [0 for i in range(8*2*4)]
while(True):
x = int(input("Please input the operation number:\n1:get\n2:free\n3:show\n0:quit\n"))
if (x==0):
break
if (x==1):
map_index = []
file_size = int(input("Please input the file size\n"))
for i in range(8*2*4):
if (map[i]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.