text stringlengths 3.07k 12.6k |
|---|
import datetime
import paho.mqtt.client as mqtt
import paho.mqtt.publish as mqttPub
import json
import logging
import logging.config
import yaml
import requests
import subprocess
from fit import FitEncoder_Weight
from garmin import GarminConnect, APIException
from body_metrics import bodyMetrics
CONFIG = 'config.yml... |
from __future__ import print_function
import torch
import torch.nn as nn
import torch.utils.data
from torch.autograd import Variable
import torch.nn.functional as F
import math
from .submodule import *
class hourglass(nn.Module):
def __init__(self, inplanes):
super(hourglass, self).__init__()
self... |
# core/operators/test_affine.py
"""Tests for rom_operator_inference.core.operators._affine."""
import pytest
import numpy as np
import rom_operator_inference as opinf
from .. import _get_operators
_module = opinf.core.operators._affine
_base = opinf.core.operators._base
class _OperatorDummy(_base._BaseNonparamet... |
"""
sphinx.ext.napoleon.iterators
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A collection of helpful iterators.
:copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import collections
if False:
# For type annotation
from typing import Any, Ite... |
"""Wrapper for the Docker SDK providing some basic utilities. Anything more complex should call the SDK itself."""
import docker
import os
from ruamel.yaml import YAML
from tempfile import NamedTemporaryFile
from subprocess import call
from .yamltools import * #had trouble importing
import logging
import stat
# Setup ... |
# Copyright 2017 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 applicab... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import os
from collections import defaultdict
logger = logging.getLogger(__name__)
FPS = 30
# AVA_VALID_FRAMES = range(902, 1799)
def load_image_lists(cfg, is_train):
"""
Loading image paths from c... |
#!/ usr/bin/env
# coding=utf-8
#
# Copyright 2019 ztosec & https://www.zto.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 r... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
from abc import abstractmethod
class ParserInput(object):
"""Input to a pcomb parser. This is basically just a simple cons-list interface
on top of whatever kind of input - streams, lists, files - you want to
read parser input from. You should not try to instantiate this directly;
instead, pick an implementati... |
#!/usr/bin/env python3
"""ROS node base class with a pythonic parameter interface."""
from typing import Any, Callable, Dict
import rospy
import yaml
from cachetools import TTLCache, cached
class NodeBase:
"""Abstract ROS Node class with additional functionality.
Args:
name (str): Name of the node
... |
"""
Unit test for Lambda Build Container management
"""
import json
import pathlib
from unittest import TestCase
from unittest.mock import patch
from parameterized import parameterized
from samcli.local.docker.lambda_build_container import LambdaBuildContainer
class TestLambdaBuildContainer_init(TestCase):
@p... |
from typing import Sequence
import argparse
from pathlib import Path
import cv2
import numpy as np
import pandas as pd
from tqdm import tqdm
import torch
from catalyst.contrib.data.cv import ImageReader
from catalyst.contrib.models.cv import ResnetEncoder
from catalyst.dl import utils
cv2.setNumThreads(0)
cv2.ocl.s... |
import sys
import os
import re
from enum import Enum
import refactoring # Note: refactoring.py need to be in the current working directory
## NOTE: update copyright year here
currentYear = 2021
excludespatterns = ["*/ext/*", "*moc_*", "*/proteindocking/*", "*/proteindocking2/*",
"*/genetree/*", "*.DS_Store",... |
import numpy as np
from collections import defaultdict
'''
tracking object for player's year-long performance over time
accepts dates in (year,month)
last_year contains last 12 months stats, most recent to least
'''
class stats_52():
def __init__(self,date):
self.most_recent = date
self.last_year =... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright 2011-2021, <NAME>
#
# 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 re... |
import time
from icp10125 import ICP10125
from mics6814 import MICS6814
import logging
import pulsar
import sys
import datetime
import subprocess
import os
import traceback
import math
import base64
import json
from time import gmtime, strftime
import random, string
import time
import psutil
import uuid
from time impor... |
from flask import Flask, request, render_template, make_response, redirect, url_for
from flask_wtf import FlaskForm, RecaptchaField
from wtforms import StringField, RadioField
from wtforms.validators import DataRequired, Regexp
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from wer... |
#!/usr/bin/env python
#
# Copyright 2017 <NAME> & <NAME>. 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 r... |
import requests
import dateutil.parser
from datetime import timedelta
import re
import numpy as np
import json
SERVICE_ENDPOINT = 'https://api.applicationinsights.io'
QUERY_ENDPOINT_PATH_TEMPLATE = 'beta/apps/{0}/query'
# Regex for TimeSpan
TIMESPAN_PATTERN = re.compile(r'((?P<d>[0-9]*).)?(?P<h>[0-9]{2}):(?P<m>[0-9]{... |
"""The alarmdotcom integration."""
from __future__ import annotations
import logging
from typing import Any
from homeassistant import config_entries
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.update_coordinato... |
#!/usr/bin/env python3
import textwrap
TEST_DELAY_SEC = 0.5
def common_imports():
print(textwrap.dedent("""\
use rand::Rng;
use test_deps::deps;
use tokio::time::{self, Duration};
"""))
def gen_serial_test(n="5"):
base_sleep_sec = TEST_DELAY_SEC / int(n)
print(textwrap.dedent... |
# -*- coding: utf-8 -*-
"""
ulmo.usace.swtwc.core
~~~~~~~~~~~~~~~~~~~~~
This module provides access to data provided by the `United States Army
Corps of Engineers`_ `Tulsa District Water Control`_ web site.
.. _United States Army Corps of Engineers: http://www.usace.army.mil/
.. _Tulsa Distric... |
# Copyright 2020 The FedLearner 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 applica... |
import pytest
from pandas import Categorical, DataFrame, Series
import pandas.util.testing as tm
def _assert_series_equal_both(a, b, **kwargs):
"""
Check that two Series equal.
This check is performed commutatively.
Parameters
----------
a : Series
The first Series to compare.
b... |
import psycopg2
import json
from django.shortcuts import get_object_or_404
from doobi.recc.models import Cal_result, Recc_result, Foods
from doobi.users.models import User
# from django.shortcuts import get_object_or_404
# from recc.models import Cal_result
# from doobi_0.users.models import Social_user
# 이친구는 왜 impor... |
from itertools import permutations, chain, product
"""
This solution will first parse the alphametic expression
grouping and counting letters buy digit ranks
then trace recursively all possible permutations starting from
the lowest rank and genrating additional permutations for new digits
at higer ranks as necessary.
T... |
#!/usr/bin/env python3
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Convert the ASCII download_file_types.asciipb proto into a binary resource.
We generate a separate variant of the binary proto ... |
import asyncio
import logging
import random
import signal
from asyncio import iscoroutinefunction
from typing import Type, List, Callable, Any
from fspider import context, signals
from fspider.downloadermiddlewares import DownloaderMiddlewareManager
from fspider.http.request import Request
from fspider.pipelines impor... |
from os.path import dirname
import numpy as np
import pytest
from pysme.abund import Abund
from pysme.atmosphere.krzfile import KrzFile
from pysme.linelist.linelist import LineList
from pysme.sme_synth import SME_DLL
# Create Objects to pass to library
# Their functionality is tested in other test files, so we assu... |
import asyncio
import json
import random
import logging
import hashlib
import inspect
from aiohttp import web, hdrs
from sockjs.session import SessionManager
from sockjs.protocol import IFRAME_HTML
from sockjs.transports import handlers
from sockjs.transports.utils import CACHE_CONTROL
from sockjs.transports.utils imp... |
"""Support for Ecovacs Ecovacs Vaccums."""
import logging
import sucks
from homeassistant.components.vacuum import (
SUPPORT_BATTERY,
SUPPORT_CLEAN_SPOT,
SUPPORT_FAN_SPEED,
SUPPORT_LOCATE,
SUPPORT_RETURN_HOME,
SUPPORT_SEND_COMMAND,
SUPPORT_STATUS,
SUPPORT_STOP,
SUPPORT_TURN_OFF,
... |
"""
this module is the only place where the templates will be kept in memory.
other services and class need to use this module method to load/access the templates
"""
import importlib.util
import os
import sys
from gevent.pool import Pool
from jumpscale import j
from zerorobot import service_collection as scol
from ... |
# %%
# Convert Instant Fuel Rate to Joules per Second (KGS and JS)
# <NAME>, Ph.D. Candidate
# %%
# Load required libraries
import pandas as pd
import matplotlib.pyplot as plt
# %%
# Load data from Excel to a pandas dataframe
def load_from_Excel(vehicle, settings):
directory = (
"../../../Google Drive/Ac... |
"""Implements the DCM Group API"""
from mixcoatl.resource import Resource
from mixcoatl.decorators.lazy import lazy_property
from mixcoatl.decorators.validations import required_attrs
from mixcoatl.utils import camelize, camel_keys, uncamel_keys
from mixcoatl.infrastructure.snapshot import Snapshot
from mixcoatl.infras... |
#!/usr/bin/env python
#--coding:utf-8 --
"""
getSigDist.py
check interaction signal distribution.
"""
__date__ = "2020-01-08"
__modified__ = ""
__email__ = "<EMAIL>"
#general library
import os
import argparse
from glob import glob
from datetime import datetime
from argparse import RawTextHelpFormatter
#3rd library
im... |
import importlib
from functools import partial
import numpy as np
from highway_env import utils
def finite_mdp(env,
time_quantization=1.,
horizon=10.):
"""
Time-To-Collision (TTC) representation of the state.
The state reward is defined from a occupancy grid over di... |
import logging
import numpy as np
from navicatGA.chemistry_selfies import (
sanitize_smiles,
timed_decoder,
get_structure_ff,
get_selfie_chars,
get_interatomic_distances,
get_ECFP4,
)
from rdkit import RDLogger
from rdkit.Chem import AllChem, Draw, Descriptors
from rdkit.DataStructs.cDataStructs... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
import numpy as np
import torch
import torchvision
__all__ = [
"filter_box",
"postprocess",
"bboxes_iou",
"matrix_iou",
"adjust_box_anns",
"xyxy2xywh",
"xyxy2cxcywh",
... |
'''
A command library help user upload their results to dashboard.
'''
#!/usr/bin/env python
import logging
import os
import os.path
import json
import argparse
import re
import shutil
import zipfile
import requests
from cotk._utils import file_utils
from cotk.scripts import _utils
from cotk.scripts import entry
def ... |
"""
model.py
architecture decisions
Copyright (C) 2016 <NAME>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any late... |
# coding:utf-8
from typing import Mapping, Any
import os
import functools
import io
import tempfile
import pytest
from itertools import chain, repeat
from copy import deepcopy
from sklearn.base import BaseEstimator
from multipledispatch import dispatch
from bourbaki.application.config import (
load_config,
dump... |
'''
/*
* Copyright 2010-2016 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 "... |
import requests
import openpyxl
import codecs
import os
import shutil
import jaconv
import re
import time
from io import BytesIO
from bs4 import BeautifulSoup
from json import dumps, loads
from datetime import datetime, timezone, timedelta
from typing import Union, Dict, List
base_url = "https://web.pref.hyogo.lg.jp... |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: janjvdv
#
# Created: 17-10-2012
# Copyright: (c) janjvdv 2012
# Licence: <your licence>
#-------------------------------------------------------------------------------
... |
#
# Copyright (c) 2015 nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/scancode-toolkit/
# The ScanCode software is licensed under the Apache License version 2.0.
# Data generated with ScanCode require an acknowledgment.
# ScanCode is a trademark of nexB Inc.
#
# You may not use... |
"""Generate .env files from .env.example templates."""
import io
import re
import sys
from pathlib import Path
import colorama
from faker import Faker
from jinja2 import Environment
VARIABLES = {}
VARIABLE_REGEX = r"""
^\s*
(
(?:export\s)? # Optional export command
\s*
... |
"""
Compare COVID-19 simulation outputs to data.
Used for spatial - covidregion - model
Allow comparison of multiple simulation experiments
"""
import argparse
import os
import pandas as pd
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import sys
sys.path.append('../')
from load_paths import l... |
"""
This file contains utilities for the model training.
"""
import os
import time
import numpy as np
import pandas as pd
from matplotlib import pyplot
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
from sklearn.externals import joblib
from keras.models import Se... |
import requests
import time
def analyse_tea_fight(log_id, api_key):
results = analyze_ultimate_fight(log_id, api_key, 1050)
if results is None:
return None
best_fight = results["best_fight"]
best_fight_time = time.strftime('%M:%S', time.gmtime(best_fight["length"]))
active_time = time.s... |
# ~*~ coding: utf-8 ~*~
from ansible.plugins.callback import CallbackBase
from ansible.plugins.callback.default import CallbackModule
class AdHocResultCallback(CallbackModule):
"""
Task result Callback
"""
def __init__(self, display=None, options=None):
# result_raw example: {
# "ok... |
"""
The results of a Cascade-AT model need to be saved to the IHME epi databases.
This module wrangles the draw files from a completed model and uploads summaries
to the epi databases for visualization in EpiViz.
Eventually, this module should be replaced by something like ``save_results_at``.
"""
import os
from path... |
import numpy as np
import matplotlib.pyplot as plt
plt.rc('font', family='NanumGothic')
plt.rc('axes', unicode_minus=False)
np.random.seed(seed=1)
X_min = 4
X_max = 30
X_n = 16
X = 5 + 25 * np.random.rand(X_n)
Prm_c = [170, 108, 0.2]
T = Prm_c[0] - Prm_c[1] * np.exp(-Prm_c[2] * X) \
+ 4 * np.random.randn(X_n)
d... |
# -*- coding: utf-8 -*-
"""
Wrapper for Graphics Files
This module is deprecated.
"""
import os
from sage.misc.temporary_file import tmp_filename
from sage.misc.superseded import deprecation
from sage.structure.sage_object import SageObject
import sage.doctest
deprecation(32988, 'the module sage.structure.graphics... |
import sqlalchemy as sa
import enum
import datetime as dt
import muffin_databases
import pytest
db = muffin_databases.Plugin(url='sqlite:///:memory:')
meta = sa.MetaData()
Role = sa.Table(
'role', meta,
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('name', sa.String(255), nullable=False),
)
... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, render_template, request, render_template,jsonify,redirect, url_for
import requests
import json
import os
import time
DEVELOPMENT_ENV = True
app = Flask(__name__)
app_data = {
"name": "Fake news tracker - Web App",
"description... |
# This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) <NAME> <<EMAIL>>
# This program is published under a GPLv2 license
# scapy.contrib.description = Socket Secure (SOCKS)
# scapy.contrib.status = loads
"""SOCKS4/5 Protocol
You can change the server ports that ... |
from bs4 import BeautifulSoup as bs
from splinter import Browser
import os
import pandas as pd
import time
def init_browser():
executable_path = {"executable_path":"webdriver/chromedriver"}
return Browser("chrome", **executable_path, headless = False)
def scrap_data_mongo():
browser = init_browser()
mars_scr... |
import numpy as np
from tensorflow.keras import layers, models
from kerasadf import layers as adflayers
# GLOBAL DEFAULT PARAMETERS
MODELPATH = 'stl10-vgg16-avgpool-weights.hdf5'
INPUT_SHAPE = (224, 224, 3) # channels last, 3 colors 224 x 224
# STANDARD TF-KERAS MODELS
def load_model(path=MODELPATH, softmax=Fals... |
#!/usr/bin/env python
from __future__ import print_function
import wandb
import time
import shutil
import os
import argparse
import requests
L = 10
PROJECT="standalone-sweep-check"
POKE_LOCAL = False
URL="http://localhost:9002/admin/early_stop"
def poke():
f = requests.get(URL)
data = f.text
print("GOT... |
from serverJiang import *
from constant import *
import requests, re, json, copy, traceback
# 企业id、key
CORP_ID = 'wwf1ea95a5532cbd56'
CORP_SECRET = '<KEY>'
AGENT_ID = 1000004
# 获取token
def get_token():
token_api = (
'https://qyapi.weixin.qq.com/cgi-bin/gettoken?' +
f'corpid={CORP_ID}&c... |
"""
_ _ _
| | | | | |
| |_ _ __ __ _ ___| | _____ _ __ _ __ ___ | |
| __| '__/ _` |/ __| |/ / _ \ '__| '_ ` _ \| |
| |_| | | (_| | (__| < __/ |_ | | | | | | |
\__|_| \__,_|\___|_|\_\___|_(_)|_| |_| |_|_|
Copyright 2018, trac... |
import os
import urllib.request
from PIL import Image
# This will create a page with the settings in default_site.py
from bs4 import BeautifulSoup
from django.contrib.auth.models import User
from django.core.files import File
from django.core.management.base import BaseCommand
from filer.models import Image as FilerIm... |
"""
Django Models for recording the status and progress of data synchronization between data sources.
The interaction between these models and Nautobot's native JobResult model deserves some examination.
- A JobResult is created each time a data sync is requested.
- This stores a reference to the specific sync oper... |
"""Stock market information from Alpha Vantage."""
from datetime import timedelta
import logging
from alpha_vantage.foreignexchange import ForeignExchange
from alpha_vantage.timeseries import TimeSeries
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassista... |
import json
import collections
import string
import time
import numpy as np
import re
import sys
from nltk.tokenize import TweetTokenizer
from nltk.stem.lancaster import LancasterStemmer
from nltk.corpus import stopwords
tknzr = TweetTokenizer(strip_handles=True, reduce_len=True, preserve_case=False)
st = LancasterSte... |
import os, imp
from flask import render_template, request, current_app
from emonitor.extensions import db, babel, scheduler
from emonitor.utils import Pagination
from emonitor.modules.mapitems.mapitem import MapItem, ItemLayout
from emonitor.modules.settings.settings import Settings
from emonitor.modules.streets.city i... |
import logging
from logging import CRITICAL # NOQA
from logging import DEBUG # NOQA
from logging import ERROR # NOQA
from logging import FATAL # NOQA
from logging import INFO # NOQA
from logging import WARN # NOQA
from logging import WARNING # NOQA
import threading
import colorlog
from optuna import type_check... |
from gym_minigrid.minigrid import *
from gym_minigrid.register import register
import itertools as itt
class CrossingEnv(MiniGridEnv):
"""
Environment with wall or lava obstacles, sparse reward.
"""
def __init__(self, size=9, num_crossings=1, obstacle_type=Lava, seed=None):
self.num_crossing... |
#! /usr/bin/env/ python
# Featurize trajectories several different ways to test in next step
import mdtraj as md
import pyemma.coordinates as coor
import numpy as np
import pickle
import pyemma
import os
#traj_num = [ '0000', '0020', '0040', '0060', '0080']
traj_num = [f'{i:04d}' for i in range(100)]
traj_path = '../... |
'''###########################################
CS221 Final Project: Deep Q-Learning Implementation
Authors:
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
<NAME> (<EMAIL>)
###########################################'''
import sys, math
import numpy as np
from collections import deque
import random
import co... |
# -*- coding: utf8 -*-
import json
try:
from urllib2 import urlopen # noqa
except ImportError:
from urllib.request import urlopen # noqa
from datetime import datetime
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.contrib.auth.models import User
from django.... |
from __future__ import absolute_import, division, print_function
import sys
import mmtbx.rotamer
from libtbx.utils import Sorry, Usage
def get_master_phil():
import libtbx.phil
return libtbx.phil.parse(
input_string="""
analyze_peptides {
pdb = None
.type = path
.multiple = True
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2021 Cloudera, Inc. 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/LIC... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019-2020 CERN.
#
# invenio-app-ils is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Patron indexer APIs."""
from datetime import datetime
from celery import shared_task
from elasticsearch ... |
import abc
from functools import wraps
from collections import OrderedDict
from pymtl import *
from lizard.bitutil import slice_len
def _escape(string):
return string.replace('_', '__')
class EntryGroup(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def size(s):
pass
@abc.abstractmethod
... |
# coding=utf-8
# Copyright (c) 2020, NVIDIA CORPORATION. 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 re... |
#!/usr/bin/env python
# encoding: utf-8
# The MIT License (MIT)
# Copyright (c) 2018 CNRS
# 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 ... |
"""Module containing convenient functions for plotting"""
__author__ = 'wittawat'
import fsic.ex.exglobal as exglo
import fsic.glo as glo
import matplotlib.pyplot as plt
import numpy as np
def plot_2d_data(pdata):
"""
pdata: an instance of PairedData
Return a figure handle
"""
X, Y = pdata.xy()
... |
import os
import numpy as np
import math
import pandas as pd
import time
import datetime
from tensorflow.python.keras import layers
from tensorflow.python.keras import models
from skimage.io import imsave
import network.image_generator as img_gen
import network.evaluation as eval
from network.architectures.unet imp... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# liftover.py
# made by <NAME>
# 2019-11-05 17:30:11
#########################
import tabix
from pyliftover import LiftOver
import proc_util
import file_util
import sys
import os
SVRNAME = os.uname()[1]
if "MBI" in SVRNAME.upper():
sys_path = "/Users/pcaso/bin/python_li... |
"""
This module provides various functions for assessing and calculating expsoures to traffic noise.
The functions are useful in calculating noise costs for quiet path route optimization and in
comparing exposures to noise between paths.
"""
from typing import List, Dict, Union
from collections import defaultdict
d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014 <NAME>
#
# 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... |
"""Modular aircraft concept"""
import pickle
import numpy as np
from gpkit import Model, Vectorize, parse_variables
class AircraftP(Model):
"""Aircraft flight physics: weight <= lift, fuel burn
Variables
---------
Wfuel [lbf] fuel weight
Wburn [lbf] segment fuel burn
Upper Unbounded
... |
import os
import torch
import schnetpack as spk
import logging
import pandas as pd
from schnetpack.datasets import OrganicMaterialsDatabase
from torch.optim import Adam
import numpy as np
import matplotlib.pyplot as plt
import shutil
from ase.units import kcal, mol
from ase.io import read
import schnetpack.train as tr... |
import torch
from torch import nn
import torch.nn.functional as F
from .utils import PI, SQRT2, deg2rad
from .filters import RampFilter
class Radon(nn.Module):
def __init__(self, in_size, theta=None, circle=True):
super(Radon, self).__init__()
self.circle = circle
self.theta = theta
... |
"""
Conjunto de classes para organizar os dados em formatos reconhecidos pelo banco de dados
"""
from __future__ import annotations
import numpy as np
import _pickle as pickle
import os
import mne
class Epochs:
def __init__(self, x, classe: str, subject_name: str, data_type=None) -> None:
# Epoca origina... |
from pandas import Series, DataFrame
from numpy import array, arange, log10, ndarray
from .expected import _get_expected_digits_
from .constants import DIGS, REV_DIGS
from .stats import Z_score
from .checks import _check_num_array_, _check_sign_, _check_decimals_
def _set_N_(len_df, limit_N):
""""""
# Assigni... |
from asyncio import sleep
from asyncio.events import get_event_loop
from asyncio.locks import Event
from datetime import datetime
from functools import wraps
from logging import getLogger
from typing import Any, Literal, Optional, cast
import aiohttp
from .decorator import strict_literal
from .errors import ERROR_MAP... |
import re
import functools
try:
from urllib.parse import quote
except ImportError:
# Python 2
from urllib import quote
from . import url
__all__ = ['Template', 'expand']
patterns = re.compile(r"{([^\}]+)}")
class Template(object):
def __init__(self, url_str):
self._base = url_str
d... |
# System libs
import os
import datetime
import argparse
from distutils.version import LooseVersion
# Numerical libs
import numpy as np
import torch
import torch.nn as nn
from scipy.io import loadmat
# Our libs
from dataset import TestDataset
from models import ModelBuilder, SegmentationModule
from utils import colorEnc... |
import os
import time
from sys import platform
import pytest
from jina.checker import NetworkChecker
from jina.flow import Flow
from jina.helper import random_name
from jina.parser import set_pea_parser, set_ping_parser
from jina.peapods.runtimes.container import ContainerRuntime
from tests import random_docs
cur_di... |
"""
Maintainer: Codenomicon <<EMAIL>>
"""
from abusehelper.core import bot, events
from abusehelper.bots.tailbot.tailbot import TailBot
import re
import time
from calendar import timegm
DATE_REX = re.compile(
r"^(\d{1,2}/.+?/\d{4}:\d{1,2}:\d{1,2}:\d{1,2})\s+([+-]\d{4})$")
def convert_date(datestring, to_forma... |
# -*- coding: utf-8 -*-
""" Tablib - ODF Support.
"""
import sys
import re
import tablib
if sys.version_info[0] > 2:
from io import BytesIO
else:
from cStringIO import StringIO as BytesIO
from tablib.compat import opendocument, style, table, text, unicode
title = 'ods'
extensions = ('ods',)
bold = style.S... |
import sys, os, logging
from collections import OrderedDict
import tensorflow as tf
from tensorboard import default
from tensorboard import program
import time
import datetime
import numpy as np
from subprocess import check_output
FLAGS = tf.app.flags.FLAGS
def get_define_flags():
""" FLAGS.flag_values_dict()
U... |
from sys import platform
from medspacy.visualization import visualize_ent
import spacy
DEFAULT_PIPENAMES = {
"sentencizer",
"target_matcher",
"context",
"tokenizer",
}
ALL_PIPE_NAMES = {
"sentencizer",
"target_matcher",
"context",
"tokenizer",
"preprocessor",
"postprocessor",
... |
#!/usr/bin/env python3
#needed for qira_config
import sys
import os
sys.path.insert(0, os.path.join('..','middleware'))
import qira_config
import struct
try:
from static2 import *
except ImportError as e:
print("Couldn't import static2 with error `{}'. Are you in the virtualenv?".format(e))
sys.exit()
import su... |
from zeep import Client
from zeep.cache import SqliteCache
from zeep.transports import Transport
from pathlib import Path
import configparser
import json
import logging
from allehelp import isAppEngine
logger = logging.getLogger('allebot')
if not isAppEngine():
logger.addHandler(logging.StreamHandler())
if lo... |
"""Wrapper around YARA analysis."""
import collections
import json
import os
import subprocess
from typing import Any, Dict, List
import yara
if __package__:
from lambda_functions.analyzer.common import LOGGER
else:
from common import LOGGER # type: ignore
# YARA matches from both yara-python and yextend a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.