content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
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... | python |
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... | python |
from .nondet import Nondet
| python |
# 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... | python |
"""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... | python |
'''
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... | python |
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()
| python |
########################################################
# plot_norms.py #
# Matheus J. Castro #
# Version 1.2 #
# Last Modification: 11/11/2021 (month/day/year) #
# https://github.com/MatheusJCastro... | python |
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... | python |
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 = ... | python |
# 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:
... | python |
"""
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:
... | python |
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... | python |
"""
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... | python |
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... | python |
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... | python |
# 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_... | python |
# 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... | python |
# 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... | python |
# -*- 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... | python |
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... | python |
#!/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... | python |
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... | python |
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, ... | python |
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... | python |
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... | python |
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... | python |
#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... | python |
'''
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):
... | python |
#!/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... | python |
# -*- 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... | python |
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... | python |
# -*- 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... | python |
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... | python |
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 *
| python |
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... | python |
#! /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 ... | python |
"""
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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 ... | python |
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... | python |
"""
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... | python |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: fetchScheduler
Description :
Author : JHao
date: 2019/8/6
-------------------------------------------------
Change Activity:
2019/08/06:
----------------------------------------... | python |
#!/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... | python |
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... | python |
""" 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()
... | python |
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 ... | python |
# 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=[
... | python |
# 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... | python |
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... | python |
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():
... | python |
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]... | python |
#!/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_... | python |
import json
from job.model_template.utils import ModelTemplateDriver
DEBUG = False
class DeeFMTemplateDriver(ModelTemplateDriver):
def __init__(self, output_file=None, args=None, local=False):
super(DeeFMTemplateDriver, self).__init__("DeepFM model template" + ("(debuging)" if DEBUG else ""),
... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# __coconut_hash__ = 0x412948c
# Compiled with Coconut version 1.5.0-post_dev62 [Fish License]
# Coconut Header: -------------------------------------------------------------
from __future__ import print_function, absolute_import, unicode_literals, division
import sys as... | python |
"""
Feed File which implements the Hiven Feed type, which should contain social
media information of a specific user and their linked acccounts.
---
Under MIT License
Copyright © 2020 - 2021 Luna Klatzer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated doc... | python |
from .flownets import FlowNetS
__all__ = ['FlowNetS']
| python |
import torch
import torch.distributed as dist
class GatherLayer(torch.autograd.Function):
'''Gather tensors from all process, supporting backward propagation.
'''
@staticmethod
def forward(ctx, input):
ctx.save_for_backward(input)
output = [torch.zeros_like(input) \
... | python |
from abc import ABC
from typing import Callable, Dict, List, Optional, Sequence
from guardpost.authentication import Identity
class AuthorizationError(Exception):
pass
class AuthorizationConfigurationError(Exception):
pass
class PolicyNotFoundError(AuthorizationConfigurationError, RuntimeError):
def ... | python |
import warnings
import numpy as np
from tqdm import tqdm
from noise import pnoise3, snoise3
import vtk
from vtk.util.numpy_support import numpy_to_vtk
from vtk.numpy_interface import dataset_adapter as dsa
def add_noise_to_sphere(poly_data, octaves, offset=0, scale=0.5):
"""
Expects sphere with radius 1 cent... | python |
import logging
import os
import sys
from logging import fatal, debug, info, warning
from os import path
from . import utils
from .argument_parser import build_argument_parser
from .metadata_parser import MetadataParser
from .settings import Settings
def main():
# Read arguments
argument_parser = build_argume... | python |
import click
import questionary as q
import docker
import os
import time
import subprocess
from threading import Thread
from functools import wraps
from colorama import (Fore, Style)
from sqlalchemy.engine.url import make_url
from vantage6.common import (info, warning, error, debug as debug_msg,
... | python |
from django.conf.urls import url, include
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
urlpatterns = [
url(r'^rides/$', views.RideList.as_view(), name='ride_list'),
url(r'^rides/(?P<pk>\d+)/$', views.RideDetail.as_view(), name='ride_detail'),
url(r'^users/$', views.Us... | python |
#!/usr/bin/env python
# Demonstration GET friendships/lookup
# See https://dev.twitter.com/rest/reference/get/friendships/lookup
from secret import twitter_instance
from json import dump
import sys
tw = twitter_instance()
# [1]
ids = ','.join((str(i) for i in (577367985, 1220723053, 1288619659)))
response = tw.frie... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.BelongGreenMerchantInfo import BelongGreenMerchantInfo
class AlipayCommerceGreenItemenergySendModel(object):
def __init__(self):
self._alipay_uid = None
self.... | python |
import random
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data
import copy
from MTLCNN_single import MTLCNN_single
from MultitaskClassifier import MultitaskClassifier
from Util import Util
class Train_Classifier:
def train_classifier(self, train_arguments... | python |
"""
Name: jupyter.py
Purpose: Installs a jupyter notebook
Author: PNDA team
Created: 03/10/2016
Copyright (c) 2016 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Apache License, Version 2.0 (the "License").
You may obtain a copy of the License at http://www.apach... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" test_hdf5xltek.py
Description:
"""
# Package Header #
from src.hdf5objects.__header__ import *
# Header #
__author__ = __author__
__credits__ = __credits__
__maintainer__ = __maintainer__
__email__ = __email__
# Imports #
# Standard Libraries #
import datetime
import... | python |
"""
Provides basic logging functionality
"""
import logging
import inspect
from datetime import datetime
import os, sys
import traceback
class Logger:
"""
generic logger class
"""
def __init__(self, logname=None, project_name=None):
"""
:param level:
:param project_name: if pr... | python |
#!/usr/bin/env python3
import os
import unittest
import numpy as np
import torch
from pytorch_translate import rnn # noqa
from pytorch_translate import train
from pytorch_translate.tasks import pytorch_translate_task as tasks
from pytorch_translate.test import utils as test_utils
class TestRNNModel(unittest.TestCa... | python |
# -*- coding: utf-8 -*-
"""
CRUD operation for fan model
"""
import database
from DB import exception
from DB.models import Fan
from DB.api import dbutils as utils
RESP_FIELDS = ['id', 'resource', 'status', 'created_at']
SRC_EXISTED_FIELD = {
'id': 'id',
# 'uuid': 'uuid',
'status': 'status',
'resource_... | python |
#!/usr/bin/env python
from random import choice
temperaments = ["sanguine", "choleric", "melancholic", "phlegmatic"]
personalities = ["introvert", "extrovert"]
# Based on the former job will be the starting inventory
former_jobs = ["a fireman", "a policeman", "a medic", "unemployed", "a doctor", "a demolitions expert... | python |
import os
import traceback
from concurrent.futures import CancelledError
import numpy as np
import cv2
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg
import pyqtgraph.opengl as gl
import sklearn.cluster
from pebble import concurrent
from mss import mss
from src.constants import *
from src.cv_img impo... | python |
#!/usr/bin/env python
import argparse
from Toggl.togglApi import getTogglReport
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Obtain report from Toggl.')
parser.add_argument("--toggl-token", "-tt", help="Set Toggl token.")
parser.add_argument("--toggl-workspace", "-w", help="S... | python |
"""
Level generator utilities.
"""
import weakref
from math import floor
from random import randrange, choice
from .blt.nice_terminal import terminal
from .geom import Point, Rect, Size
from .draw import draw_rect
class BSPNode:
"""
Node in a binary space partitioning tree
.. py:attribute:: rect
... | python |
from shortcodes import Shortcode
# Allowed values for position options
ALLOWED_POSITION = ['right', 'left']
class BevelShortcode(Shortcode):
name = 'bevel'
same_tag_closes = True
standalone = True
render_empty = True
template = 'views/partials/bevel.j2'
def _get_position(self, options):
... | python |
# Generated by Django 4.0.3 on 2022-03-15 20:26
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0007_alter_category_options'),
]
operations = [
migrations.AlterField(
model_name='tick... | python |
import random
import math
def prime_factor_generator(n):
yield 2
for i in range(3, int(math.sqrt(n)) + 1, 2):
yield i
def prime_factors(n):
for i in prime_factor_generator(n):
if n % i == 0:
yield i
while True:
n //= i
if n % i != 0:
... | python |
def largest_palindrome_product(n):
up_digits = "1" + n * "0"
low_digits = "1" + (n-1) * "0"
num_up_digits = int(up_digits)
num_low_digits = int(low_digits)
x = range(num_low_digits, num_up_digits)
largest_num = 0
for i in x:
for j in x:
multi = i * j
... | python |
# 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... | python |
import sys
from importlib import import_module
from bumps.pymcfit import PyMCProblem
if len(sys.argv) != 2:
raise ValueError("Expected name of pymc file containing a model")
module =sys.argv[1]
__name__ = module.split('.')[-1]
model = import_module(module)
problem = PyMCProblem(model)
| python |
#!/usr/bin/env python
import numpy as np
from scipy.misc import imread, imresize
import matplotlib.pyplot as plt
import cv2
import scipy.io
import scipy.stats as st
from scipy import ndimage as ndi
from skimage import feature
from skimage.morphology import skeletonize
import pdb
def gkern(kernlen=21, nsig=3):
... | python |
"""Test a hydrogen-like atom."""
import jax
import numpy as np
import pytest
import vmcnet.examples.hydrogen_like_atom as hla
from vmcnet.mcmc.simple_position_amplitude import make_simple_position_amplitude_data
from .sgd_train import sgd_vmc_loop_with_logging
from .kfac_train import kfac_vmc_loop_with_logging
def ... | python |
from django.conf import settings
from cybox.objects.address_object import Address
from cybox.objects.uri_object import URI
cfg = settings.ACTIVE_CONFIG
LOCAL_ALIAS = cfg.by_key('company_alias')
OBJECT_FIELDS = {
'AddressObjectType': [['address_value']],
'DomainNameObjectType': [['value']],
'EmailMessageOb... | python |
# -*- coding: utf-8 -*-
"""
@Author: oisc <oisc@outlook.com>
@Date: 2018/5/4
@Description:
"""
import math
from collections import namedtuple
from copy import copy
from interface import Annotator
from transition import Session
from transition.shiftreduce import SRTransition, SRConfiguration
class SPINNTreeBuilder(A... | python |
import requests
import StringIO
import csv
import urllib
import json
import datetime
import md5
from time import sleep
from limit import Limit
from source_iterator import SourceIterator
from source_row_manager import SourceRowManager
class SourceReader:
def __init__(self, date, product, catalogue, url, index, lo... | python |
"""
A Python module for antenna array analysis
----------
AntArray - Antenna Array Analysis Module
Copyright (C) 2018 - 2019 Zhengyu Peng
E-mail: zpeng.me@gmail.com
Website: https://zpeng.me
` `
-:. -#:
-//:. -###:
-////:. ... | python |
# importacion de librerias
# constantes
# funciones y metodos
def es_primo(numero):
primo = True
for n in range(2, numero, 1):
if numero % n ==0:
primo = False
break
return primo
# mi programa principal
# ingreso de numero por teclado
numero = int(input('Ingrese un num... | python |
# -*- coding: utf-8 -*-
# vim: set fileencoding=utf-8:noet:tabstop=4:softtabstop=4:shiftwidth=8:expandtab
""" python3 class """
# Copyright (c) 2010 - 2020, © Badassops LLC / Luc Suryo
# All rights reserved.
# BSD 3-Clause License : http://www.freebsd.org/copyright/freebsd-license.html
from pprint import PrettyPrin... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2018 Taha Emre Demirkol
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... | python |
from itertools import combinations
class Edge:
def __init__(self, frm, to, weight):
self.from_vertex = frm
self.to_vertex = to
self.dist = weight
def _get_edges(graph):
edges = []
for a, b in combinations(range(len(graph)), 2):
if graph[a][b]:
edges.appen... | python |
# -*- coding: utf-8 -*-
# File generated according to Generator/ClassesRef/Simulation/OPslip.csv
# WARNING! All changes made in this file will be lost!
"""Method code available at https://github.com/Eomys/pyleecan/tree/master/pyleecan/Methods/Simulation/OPslip
"""
from os import linesep
from sys import getsizeo... | python |
#!C:/Python35/python.exe
# -*- coding: UTF-8 -*-
#
# belmih 2016
#
import threading
import queue
import argparse
import os
import time
import zipfile
import shutil
import xml.etree.cElementTree as ET
import csv
abspath = os.path.abspath(__file__)
workdir = os.path.dirname(abspath)
os.chdir(workdir)
CSV_ID_LEVEL = "... | python |
import itertools as it, operator as op, functools as ft
from collections import ChainMap, Mapping, OrderedDict, defaultdict
from pathlib import Path
from pprint import pprint
import os, sys, unittest, types, datetime, re, math
import tempfile, warnings, shutil, zipfile
import yaml # PyYAML module is required for tests... | python |
import aredis
from ddtrace import config
from ddtrace.vendor import wrapt
from ...internal.utils.wrappers import unwrap
from ...pin import Pin
from ..redis.util import _trace_redis_cmd
from ..redis.util import _trace_redis_execute_pipeline
from ..redis.util import format_command_args
config._add("aredis", dict(_def... | python |
import uuid
import datetime
import typing
from abc import ABC, abstractmethod
from sensory_cloud.config import Config
from sensory_cloud.services.crypto_service import CryptoService
import sensory_cloud.generated.common.common_pb2 as common_pb2
import sensory_cloud.generated.oauth.oauth_pb2_grpc as oauth_pb2_grpc
imp... | python |
import IPython.nbformat.v4 as nbformat
from IPython.nbformat import write as nbwrite
import numpy as np
def format_line(line):
"""
Format a line of Matlab into either a markdown line or a code line.
Parameters
----------
line : str
The line of code to be formatted. Formatting occurs accor... | python |
import os
import sys
from fabric.colors import cyan, red, yellow
from fabric.api import task, env, sudo, get, hide, execute
from dploy.context import ctx, get_project_dir
from dploy.commands import manage as django_manage
from dploy.utils import (
FabricException, version_supports_migrations, select_template,
... | python |
import IPython
from google.colab import output
display(
IPython.display.HTML('''<div class="container">
<div class="circle red" color="red"></div>
<div class="circle" color="yellow"></div>
<div class="circle" color="green"></div>
<div class="floating-text">
Intelligent Traffic Management System </div>
<styl... | python |
import rq
import numpy as np
import time
import subprocess
import shlex
import sys
import redis
import vislab.tests.testrqaux
def get_redis_client():
host, port = ["0.0.0.0", 6379]
try:
connection = redis.Redis(host, port)
connection.ping()
except redis.ConnectionError:
raise Except... | python |
import ctypes as ct
from .base import Object, Error, ccs_error, _ccs_get_function, ccs_context, ccs_binding, ccs_hyperparameter, ccs_datum, ccs_datum_fix, ccs_hash, ccs_int
from .hyperparameter import Hyperparameter
ccs_binding_get_context = _ccs_get_function("ccs_binding_get_context", [ccs_binding, ct.POINTER(ccs_con... | python |
"""Example implementation of the Lorenz forecast model.
References
----------
- Dutta, R., Corander, J., Kaski, S. and Gutmann, M.U., 2016.
Likelihood-free inference by ratio estimation. arXiv preprint arXiv:1611.10242.
https://arxiv.org/abs/1611.10242
"""
from functools import partial
import numpy as np
impor... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.