text stringlengths 3.07k 12.6k |
|---|
############################################################################################
#
# Project: Peter Moss Acute Myeloid/Lymphoblastic Leukemia AI Research Project
# Repository: AML/ALL Detection System
# Project: Movidius NCS1 Classifier
#
# Author: <NAME> (<EMAIL>)
# Contributor... |
#!/usr/bin/env python3
"""
Created on 2019-04-17
@author: dillonshapiro
utility functions/classes
"""
import os
import keras.backend as K
import numpy as np
import pandas as pd
from keras.losses import binary_crossentropy
from skimage.io import imread
def dice_coef(y_true, y_pred):
"""
Calculates the Dice ... |
from matplotlib import pyplot as plt
from PIL import Image
import numpy as np
def make_daily_windT_plots(err):
# Loading data + setting up aux. iteration variables.
weeklyPlotsMain = np.load("outData/windT_9qty-7day-2dSpatial_profiles_9x7x73x144_.npy")
titles = ['at_Surface','_250mbar','_850mbar']
basic = np.linsp... |
import enum
from typing import Sequence, Dict
import pandas as pd
from sqlalchemy import Column, Integer, String, ForeignKey, Enum, Float, Boolean
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.session import Session
from sqlalchemy.engine.base import Connectable
Base = declarative_base()
... |
import sys
from typing import Dict, List, Union
from collections import OrderedDict
import pyxb
if 'komle.bindings.v20.witsml' in sys.modules:
#Due to namespace collision we can't import bindings at the same time
from komle.bindings.v20._eml import TimeStamp
timestamp = TimeStamp
elif 'komle.bindings.v141... |
from datetime import datetime
import calendar
import connexion
from services.bitshares_websocket_client import client as bitshares_ws_client
from services.bitshares_elasticsearch_client import client as bitshares_es_client
from services.cache import cache
import api.explorer
import config
def get_config():
retur... |
#!/usr/bin/env python
import os
import sys
import time
import traceback
import simplejson as jsmod
from datetime import datetime
from subprocess import Popen, PIPE
import logging
from logging.handlers import RotatingFileHandler
from constants import (
CLUSTER_INFO_FILE,
BACKUP_DIR,
LOG_DIR,
LOG_FILE,
... |
"""
The MIT License (MIT)
Copyright (c) 2016-2017 <NAME> <EMAIL>
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, modify,... |
""" A windows service that receives commands via tcp and executes them.
Install this service inside the VM::
$ vmserve install
$ vmserve start
The tcp sockets *must* not be exposed to loopback on the host or the
internet. Forward them to UNIX domain sockets on the host with
`vmcall.VMBuilder.add_command_sock... |
# coding: utf-8
# ==========================================================================
# Copyright (C) 2016-2022 All rights reserved.
#
# filename : text_utils.py
# author : chendian / <EMAIL>
# date : 2019-04-08
# desc : error detection model.
# n-gram database for Python2.x
# ... |
# Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
import mmcv
import pytest
import torch
from mmdet import digit_version
from mmdet.models.necks import FPN, YOLOV3Neck
from .utils import ort_validate
if digit_version(torch.__version__) <= digit_version('1.5.0'):
pytest.skip(
'ort back... |
import os
import torch
import sys
from torch import nn
from fastNLP.core.callback import Callback
from fastNLP.core.utils import _get_model_device
class MyCallback(Callback):
def __init__(self, args):
super(MyCallback, self).__init__()
self.args = args
self.real_step = 0
def on_step_e... |
# Problem: https://www.codechef.com/NOV20B/problems/FEMA2
# Editorial: https://discuss.codechef.com/t/fema2-editorial/79956
import inspect
import sys
Infinity = float('inf')
# Default is around 1000
sys.setrecursionlimit(110000)
def integer_array_input():
return MyList(map(int, input().split()))
def string_... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# <NAME> ©
# License MIT
import sys
import datetime
import socket
import argparse
import shelve
import logging
import logging.handlers
from datetime import timedelta
try:
import yaml
except ImportError:
print ("It looks like yaml module isn't installed. Please install... |
import sys
import common
import table_single_provers
def sumTotalStatus(prover_dict,stat,excluded_semantics = [], included_semantics=[]):
ret = {}
ret["mleancopcsarestricted"] = []
ret_alt = {}
for prover in prover_dict.keys():
if prover not in ret:
ret[prover] = []
if prove... |
# --------------------------------------------------------------------------
# The MIT License
#
# Copyright (c) 2018 aio-libs team https://github.com/aio-libs/
# Copyright (c) 2017 Ocean S. A. https://ocean.io/
# Copyright (c) 2016-2017 WikiBusiness Corporation http://wikibusiness.org/
#
# Permission is hereby granted... |
import os
from flask import flash, request, redirect
from flask_jwt_extended import jwt_required, get_jwt_identity
from flask_restful import Resource, reqparse
from werkzeug.utils import secure_filename
import pandas as pd
from resource.models import CompanyModel, CompanyDailyModel, CompanyHourlyModel
from datetime im... |
# Simplified blackjack game using https://deckofcardsapi.com/ API
# Not all rules are implemented
import justpy as jp
import asyncio
card_size = 0.5
card_width = int(226 * card_size)
card_height = int(card_width * 314/226)
button_classes = """
inline-flex items-center px-6 py-6 border border-gray-700 text-2xl leading... |
import logging
import pickle
from calendar import monthrange
from datetime import datetime, timezone
import numpy as np
import pandas as pd
from pymongo import MongoClient
from mtv import model
LOGGER = logging.getLogger(__name__)
# private methods
def _inverse_scale_transform(v, a0, b0, a1, b1):
""" return t... |
import gym
import torch
from src.util.collisions import feasible
import numpy as np
class OptionsEnv(gym.Wrapper):
def __init__(self, env, options=[(0, 5), (5, 5), (10, 5)], *args, **kwargs):
"""option 0 is treated as safe fallback"""
super().__init__(env, *args, **kwargs)
self.option... |
# -*- coding: utf-8 -*-
"""
Set of events of the bot
~~~~~~~~~~~~~~~~~~~~
:copyright: 2021-present Stellestia_Kasiwa
"""
import discord
import sqlite3
import yaml
from discord.ext import commands
from .. import EmojiUtils
from ..core import ConfigManager as cm
class Event(commands.Cog):
def __init__(self, b... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import logging
import sys
import os
import os.path
from pprint import pformat
from time import time
from shutil import copyfile
from urllib.parse import unquote
from datetime import datetime
from slcli.apis.reseplanerare3_1 import tripapi, journeydetailapi... |
# Copyright 2017 Canonical 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 in writing, s... |
# -*- coding: utf-8 -*-
"""
Source class implementation in Python
:Authors: mdelvallevaro
LucaZampier (modifications)
"""
# # Imports
# Global imports
import numpy as np
# Local imports
import constants as const
import frame_transformations as ft
from satellite import Satellite
import quaternion
def comp... |
# -*- coding: utf-8 -*-
"""
Created on Dec 14 2020
@author: Yi-Hui (<NAME>
Updated on May 10 2021
@author: I-Chun (Bronwin) Chen
"""
import sys
sys.path.append('../../CP')
import torch
import pickle
import argparse
import itertools
import numpy as np
import matplotlib.pyplot as plt
from model import SAN
from pop_da... |
#!/usr/bin/env python
""" Stream-based publishing and subscribing """
__author__ = '<NAME> <<EMAIL>>, <NAME>'
import gevent
from pyon.core.bootstrap import get_sys_name, CFG
from pyon.core.exception import BadRequest
from pyon.net.endpoint import Publisher, Subscriber
from pyon.ion.identifier import create_simple_u... |
# -*- coding: utf-8 -*-
import logging
from telegram.ext import CommandHandler, Filters, MessageHandler, Updater
from config.settings import TELEGRAM_TOKEN
from services.queries import (
get_city_data,
get_economic_data,
get_predict_data,
get_state_data,
)
# enable logging
logging.basicConfig(
f... |
#!/usr/bin/env python3
'''pymlock, a python program for locking a list of files into memory
In addition to being able to lock individual files into memory, it can
also recursively lock executables and all their library dependencies
into memory, and if passed a directory, will lock all the files under
that ... |
from util.dataset_io import *
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.optimizers import Adamax
from skimage.transform import resize
import random
import numpy as np
i... |
#! /bin/python
import os
import sys
import json
import luigi
import nifty.tools as nt
import cluster_tools.utils.volume_utils as vu
import cluster_tools.utils.function_utils as fu
from cluster_tools.cluster_tasks import SlurmTask, LocalTask, LSFTask
# this is a task called by multiple processes,
# so we need to res... |
"""
Python wrapper for `lapie`
"""
from os import path
import os
import subprocess
import database
import tempfile
import re
def run(commands, workdir=None):
"""Run a list of Tcl commands, returning the output as a string"""
rcmd_path = path.join(database.get_oxide_root(), "radiant_cmd.sh")
if workdir is N... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 30 02:36:02 2020
@author: PURUSHOTTAM
"""
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
from torch.autograd import Variable
#Import the dataset
movi... |
""" Official evaluation script for v1.1 of the SQuAD dataset. """
from __future__ import print_function
from collections import Counter
import argparse
import json
from bertserini.utils.utils import normalize_answer, init_logger
logger = init_logger("evluation")
def cover_score(prediction, ground_truth):
predic... |
# Copyright 2014 Google 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/LICENSE-2.0
#
# Unless required by applicable law or a... |
import ast
import functools
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import sys
objectives = 3 # amount of objectives to be plotted
weights = 11 # amount of weights
figsize = [12, 6] # figure size, inches
plotsize = [2, 7] # amount of subplots in plot
if len(sys.... |
import math
from collections import defaultdict
from typing import Any, Dict, Sequence, Optional, cast, Hashable
from coba.environments import Context, Action
from coba.statistics import OnlineVariance
from coba.learners.primitives import Learner, Probs, Info
class EpsilonBanditLearner(Learner):
"""A bandit lear... |
#!/usr/bin/env python
# coding: utf-8
# ###### Validation:
# 1. Generate all keys into excel - summary report (Read from code base - ejs files).
# 2. From figma extract keys ( Add / remove keys in excel based on new designs.(for dynamic keys - communicate with UI/UX) - is export from figma possible??? (value updation,... |
## python 3.6 > ##
from bs4 import BeautifulSoup
import requests
import datetime
import re
import sys
import math
import argparse
## validating arguments ##
parser = argparse.ArgumentParser(description='BT Phone Book to CSV web scraper')
parser.add_argument('-l','--location', help='Specify location', requir... |
import os
import pytest
import shutil
import six
import sys
import tempfile
import girder
from girder import logger, logprint, logStdoutStderr
from girder.utility import config
INFO_MSG = 'Log info message'
ERROR_MSG = 'Log error message'
@pytest.fixture
def tempLog():
logRoot = tempfile.mkdtemp()
infoFile ... |
#!/usr/bin/env python33
# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
import inspect
import matplotlib.pyplot as plt
_GO = "output"
_STOP = 0
# ====================
# ops
# ====================
# basic lstm cell (with dropout layer)
def LSTM(size, is_tuple=True, init=None, prob=1.0):
cell ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Subscribers for traversal events to ensure that the the proper
site is installed, including respecting global registered components.
.. caution:: :func:`zope.site.site.threadSiteSubscriber` also exists and is
configured by some packages like :mod:`zope.app.publicati... |
"""
Scrapper implementation
"""
from datetime import datetime
import json
from pathlib import Path
import random
import re
import shutil
from time import sleep
from bs4 import BeautifulSoup
import requests
from constants import ASSETS_PATH, CRAWLER_CONFIG_PATH, DOMAIN
from core_utils.article import Article
from core_... |
#!/usr/bin/python3
# HTTP Injector for Python3
# modded by <NAME>
# v1.0
# credit: https://github.com/mientz/python-http-injector
import socket
import select
import time
import argparse
import json
import logging
import sys
logging.basicConfig(filename='/tmp/http-injector.log',
filemode='w',
... |
from search import *
import heapq
class MapGraph(Graph):
"""This is an abstract class for graphs. It cannot be directly
instantiated. You should define a subclass of this class
(representing a particular problem) and implement the expected
methods."""
def __init__(self, string):
st... |
import numpy as np
from rdkit import Chem
from typing import List
# Symbols for different atoms
ATOM_LIST = ['C', 'N', 'O', 'S', 'F', 'Si', 'P', 'Cl', 'Br', 'Mg', 'Na', 'Ca', 'Fe',
'As', 'Al', 'I', 'B', 'V', 'K', 'Tl', 'Yb', 'Sb', 'Sn', 'Ag', 'Pd', 'Co', 'Se', 'Ti',
'Zn', 'H', 'Li', 'Ge', 'C... |
import argparse
import numpy as np
from src.animate_scatter import AnimateScatter
from src.whale_optimization import WhaleOptimization
def parse_cl_args():
parser = argparse.ArgumentParser()
parser.add_argument("-nsols", type=int, default=50, dest='nsols', help='number of solutions per generation, default: 5... |
#!/usr/bin/env python3
import os
import numpy as np
from baselines.common.cmd_util import mujoco_arg_parser
from baselines import bench, logger
from multiprocessing import Pool
import csv
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
def train(env_id, num_timesteps, seed, exp_scale):
... |
from bs4 import BeautifulSoup
import requests
import time
import lxml
import sys
import os
import re
import csv
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
FOLDER = os.path.join(CURRENT_DIR, 'podium-data')
def main():
# allEpisodes = get_episode_range(1,35)
# create_save_folder()
listfile = os.path.jo... |
import os
import json
import logging
import sys
from collections import defaultdict
import numpy as np
import tensorflow as tf
from sacred import Experiment
from sacred.observers import MongoObserver
import gnnbench.models
from gnnbench.data.make_dataset import get_dataset_and_split_planetoid, get_dataset, get_train_... |
#!/usr/bin/env python
# coding:utf-8
import argparse
import sqlite3
import community
import networkx as nx
import matplotlib.pyplot as plt
def getWeaponMain(weapon):
dict = {
"52gal": "52gal",
"52gal_deco": "52gal",
"96gal": "96gal",
"96gal_d... |
# SPDX-License-Identifier: MIT
import logging
import os.path
import textwrap
import typing
import warnings
import xml.etree.ElementTree as ET
from typing import Dict
import treelib
import dbus_objects.object
import dbus_objects.types
class _Introspectable(dbus_objects.object.DBusObject):
'''
https://dbus.... |
import time
from model import *
from utils import*
import DMaskRCNN as model
import coco
from extract import parse_annotation, resize_bbox
import skimage.io
# Root directory of the project
root_dir = os.getcwd()
# Directory to save logs and trained model
model_dir = os.path.join(root_dir, "domain_logs")
# Local pat... |
from __future__ import print_function
from __future__ import unicode_literals
import re
from email.header import decode_header
from email.parser import Parser
try:
from email.parser import BytesParser
except ImportError:
BytesParser = None
import chardet
try:
from nkf import nkf
except ImportError:
... |
# -*- coding: utf-8 -*-
import torch
import torch.optim as optim
import numpy as np
import models
import utils
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Deep Q-Network (DQN) #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ... |
"""
Eo-tilematcher package.
"""
import geopandas as gpd
import pandas as pd
import pygeos
from pathlib import Path
DATA_DIR = Path(__file__).parent / "data"
def _db_loader(file_name):
subdir = file_name.split("_")[0]
tiles_db = gpd.read_file(DATA_DIR / subdir / file_name, driver="ESRI Shapefile")
return... |
import sys
import os
from os import listdir
from os.path import join
from random import randint, shuffle
import pickle
from argparse import Namespace, ArgumentParser
from patent_parsing_tools import Downloader, Unzipper, Extractor
from patent_parsing_tools.utils.log import log
@log
class Supervisor:
download_url ... |
# coding : utf-8
import socket
import subprocess
import threading
from time import ctime, sleep
from util import *
import yaml
print('=========SDP应用服务器=========')
# 读取配置文件
try:
f = open('config.yaml', 'r')
global_config = yaml.load(f.read(), Loader=yaml.FullLoader)
# {'AuthServer': {'port': 6789, 'id': ... |
#!/usr/bin/env python3
"""
MIT License
Copyright (c) [year] [fullname]
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, ... |
import requests
import sys,os
import time
from datetime import datetime
import pytz
# 注意:pyttsx3一定要是2.72版本,高于2.72版本一定会出错!
import pyttsx3 # 语音输出
import webbrowser # 打开浏览器
# speaking_open:判断用户是否打开了语音输出功能
speaking_open=False
# 判断settings.txt是否存在
def setting_if_exist():
filename="settings.txt"
if not os.path.exist... |
__author__ = 'max'
from .instance import DependencyInstance, NERInstance
from .instance import Sentence
from .conllx_data import ROOT, ROOT_POS, ROOT_CHAR, ROOT_TYPE, END, END_POS, END_CHAR, END_TYPE
from . import utils
from ..io_multi import get_word_index_with_spec
class CoNLLXReader(object):
def __init__(self,... |
# !/usr/bin/env python
import argparse
import logging
import os
import sys
from scream import utils
from scream.commands import deploy_packages, install, init_monorepo, new_package, test, PackageInstallationException
from scream.monorepo import Monorepo
from scream.package import PackageDoesNotExistException, Package... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import division
import numpy as np
from scipy.constants import mu_0, pi, epsilon_0
from scipy.special import erf
from SimPEG import Utils
def Qfun(R, L, f, alpha=None):
if alpha is... |
from enum import Enum
import json
import matplotlib.pyplot as plt
import os
import pandas as pd
import re
import sys
from collections import defaultdict
from heapq import heapify, heappush, heappop
plt.style.use("dark_background")
# normal: base item
# good: base item with suffix
# great: base item with prefix and su... |
# Copyright 2021 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
import srcpath # noqa
import cv2
import numpy as np
import math
import time
import sys
import os
from omnicv import fisheyeImgConv
img_path = "./input/equirect.jpg"
def test_inputPath1():
assert os.path.isfile(img_path),"Wrong path... Run the tests.py code after changing the directory inside test folder"
param_fi... |
from __future__ import print_function
import keras
from keras import backend as K
import tensorflow as tf
import pandas as pd
import os
import pickle
import numpy as np
import scipy.sparse as sp
import scipy.io as spio
import isolearn.io as isoio
import isolearn.keras as iso
def iso_normalizer(t) :
iso = 0.0
... |
################################################################################################################
#
# Google Cloud Dataflow
#
# References:
# https://cloud.google.com/dataflow/docs/
#
# Usage:
'''
python gaming_dataflow.py \
--gcp_project gaming-demos \
--region us-central1 \
--job_... |
import numpy as np
#%matplotlib inline
bounds=np.array([[1.0,24.0]])
noise=0.0
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
def Oracle(x):
y=[]
for i in x:
y.append(6*gaussian(i,4,1)+4*gaussian(i,7,1.5)+9*gaussian(i,16,1.8))
return y
import... |
from django.shortcuts import render
from customers .models import Customer
from .serializers import NotificationSerializer
from rest_framework import viewsets
from rest_framework.decorators import api_view
from app . models import App,UserApp
from rest_framework.response import Response
from rest_framework import statu... |
import sys
import os
import textwrap
logo = "********************************************************************\n" \
"********************************************************************\n" \
"** $$$$$$$\ $$\ **\n" \
"** $$ __$$\ ... |
import os
import numpy as np
import openmc
from openmc.examples import slab_mg
from tests.testing_harness import PyAPITestHarness
def create_library():
# Instantiate the energy group data and file object
groups = openmc.mgxs.EnergyGroups(group_edges=[0.0, 0.625, 20.0e6])
n_dg = 2
mg_cross_sections... |
import numpy as np
import torch
import odl
import os
import shutil
from torch.utils.data import DataLoader
from torchvision import transforms
import torch_wrapper, mayo_utils
from skimage.measure import compare_psnr
device = 'cuda' if torch.cuda.is_available() else 'cpu'
##############specify geometry parameters####... |
from __future__ import absolute_import
from __future__ import unicode_literals
from collections import defaultdict
from xml.etree import cElementTree as ElementTree
from io import BytesIO
import six
from casexml.apps.phone.fixtures import FixtureProvider
from casexml.apps.phone.utils import ITEMS_COMMENT_PREFIX
from c... |
#Boost Software License - Version 1.0 - August 17th, 2003
#
#Permission is hereby granted, free of charge, to any person or organization
#obtaining a copy of the software and accompanying documentation covered by
#this license (the "Software") to use, reproduce, display, distribute,
#execute, and transmit the Soft... |
import h5py
from mock import Mock
from nexus_constructor.nexus.nexus_wrapper import (
NexusWrapper,
append_nxs_extension,
get_nx_class,
)
from tests.helpers import InMemoryFile
def test_GIVEN_nothing_WHEN_creating_nexus_wrapper_THEN_file_contains_entry_group_with_correct_nx_class():
wrapper = NexusWra... |
import parse
from pk import *
from move import *
from ability import *
import os
# XXX Hacks around bugs in Serebii's HTML is marked with a comment beginning with XXX
# TODO Some moves may be missing from the source I got the moves file from (esp. ones that do nothing)
# TODO Scrape hatch counter from another source, ... |
import json
import traceback
from django.core.exceptions import ObjectDoesNotExist
from django.urls import reverse
from django.db import transaction
from django.http import Http404
from django import http
from django.shortcuts import redirect
from django.views import generic
import reversion
from editor.forms import... |
import requests
import pandas as pd
import modules.constants as constants
from modules.constants import Ingredient, Recipe
import json
class RecipeRecommender:
"""
The RecipeRecommender class allows the user to interact with the
Spoonacular API and get recipes that meet the given requirements.
"""
... |
# Copyright 2018 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' file acc... |
from __future__ import absolute_import
from __future__ import print_function
from collections import namedtuple as _namedtuple
"""
Token sequences alignement and diffing based on the longest common substrings of
"high tokens". This essentially a non-optimal and reasonably fast single local
sequence alignment between ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import annotations
import contextlib
import math
import functools
import turtle
import enum
import typing
import pint
ureg = pint.UnitRegistry()
# Side Note: Yes, Python has enums !
class PenState(enum.Enum):
UP = -1
DOWN = 1
# nametuple b... |
from telethon import TelegramClient, events, sync
import os
import logging
import configparser
import json
from datetime import datetime
gRoot_path = os.path.abspath(os.path.dirname(__file__))+'/'
gSys_file_name = os.path.splitext(os.path.basename(__file__))[0]
#####################################################... |
from blockchain_parser.blockchain import Blockchain
from blockchain_parser.script import is_public_key
from blockchain_parser.address import Address
from multiprocessing import Pool
import address_reusing.conf as CFG
import blockchain
import datetime
import pickle
import time
import os
def compare_dictionary(main, t... |
"""
Print part-of-speech tagged, true-cased, (very roughly) sentence-separated
text, with each "sentence" on a newline, and spaces between tokens. Supports
multi-processing. Note: This script will only run in Python 3.
"""
from __future__ import print_function, unicode_literals, division
import io
import logging
from... |
import numpy as np
from datetime import datetime,timedelta
from os import path,makedirs,remove
from pathlib import Path
from ..utils.try_download import tqdm_request
def download_sw_nrlmsise00(direc=None):
'''
Download or update the space weather data from www.celestrak.com
Usage:
swfile = download_... |
#!/usr/bin/env python
import json
import os
import logging
import validictory
import xmlrpclib
import requests
import getopt
import sys
from threading import Lock
from flask import Flask, request, abort, Response
from socket import error as socket_err
class JsonProxy(object):
"""A simple proxy that sends JSON-enc... |
import numpy as np
from prettytable import PrettyTable
import matplotlib.pyplot as mpl
# --------------------------------ATENÇÃO--------------------------------#
# Estou usando uma biblioteca chamada: "Prettytable", para deixar a #
# tabela com uma aparência bonita. #
# ... |
"""Runs a cloudharmony iperf benchmark.
See https://github.com/cloudharmony/iperf for more info.
"""
import posixpath
from absl import flags
from perfkitbenchmarker import cloud_harmony_util
from perfkitbenchmarker import configs
from perfkitbenchmarker import vm_util
BENCHMARK_GIT_URL = 'https://github.com/cloudha... |
from peewee import *
database = MySQLDatabase('lab3', **{'charset': 'utf8', 'sql_mode': 'PIPES_AS_CONCAT', 'use_unicode': True, 'host': 'localhost', 'port': 3306, 'user': 'root', 'password': '<PASSWORD>'})
class UnknownField(object):
def __init__(self, *_, **__): pass
class BaseModel(Model):
class Meta:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 1 11:16:43 2021
@author: <NAME>
"""
"""
Experiment for comparing the performance of the network as a fucntion of numbers of neuron.
The code is for system of differential equations with two unknowns.
"""
# use the outgrad backage for the coputat... |
# -*- coding: utf-8 -*-
"""
==============================
1D Wasserstein barycenter demo
==============================
@author: rflamary
"""
import numpy as np
import matplotlib.pylab as pl
import ot
from mpl_toolkits.mplot3d import Axes3D #necessary for 3d plot even if not used
import scipy as sp
import scipy.sig... |
import pathlib
import os
from torchvision import transforms, datasets
from . import places365
_constructors = {
'MNIST': datasets.MNIST,
'CIFAR10': datasets.CIFAR10,
'CIFAR100': datasets.CIFAR100,
'ImageNet': datasets.ImageNet,
'Places365': places365.Places365
}
def dataset_path(dataset, path=N... |
# -*- coding: utf-8 -*-
# Author: <NAME> <<EMAIL>>, <NAME> <<EMAIL>>,
# License: TDG-Attribution-NonCommercial-NoDistrib
import argparse
import os
import time
from tqdm import tqdm
import torch
import open3d as o3d
from torch.utils.data import DataLoader
import opencood.hypes_yaml.yaml_utils as yaml_utils
from open... |
"""Simulation class for smoothed particle hydrodynamics simulations.
This class contains all information associated with a simulation. It
contains the snapshot as a list of Snap objects, and the global quantity
and sink quantity time series files an Evolution objects.
"""
from __future__ import annotations
from path... |
from importlib import import_module
import requests
from utils import rotation_utils as rot_utils
import torch
import random
import logging
logger = logging.getLogger(f"utils/util.py")
def get_object_from_path(path):
"""
The function returns the callable function from the path.
:param path: Path to the ... |
import pytest
import datetime as dt
from pathlib import Path
import numpy as np
from astropy.time import Time, TimeDelta
from oem import OrbitEphemerisMessage
from oem.components import State
from oem.interp import (
LagrangeStateInterpolator, HermiteStateInterpolator, EphemerisInterpolator)
THIS_DIR = Path(__f... |
import torch
from torch import nn
from torch.nn import CrossEntropyLoss, BCEWithLogitsLoss
from transformers.models.roberta.modeling_roberta import (
RobertaPreTrainedModel,
RobertaModel
)
from transformers.file_utils import(
add_start_docstrings,
add_code_sample_docstrings,
)
from transformers.model... |
from __future__ import (absolute_import, division, print_function)
import time
from six import string_types
from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleParserError
from ansible.plugins.lookup import LookupBase
from ansible.module_utils._text import to_text
from ansible.module_util... |
#!/usr/bin/env python3
"""
Implementation of the prediction procedure of the deep learning models.
This procedure is used to test a model on one specific input.
"""
###########
# Imports #
###########
import cv2
import math
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import time
import t... |
# ----------------------------------------------------------------------
# clex.py
#
# A lexer for ANSI C.
# ----------------------------------------------------------------------
import sys
sys.path.insert(0, "../..")
import ply.lex as lex
# Reserved words
reserved = (
'AUTO', 'BREAK', 'CASE', 'CHAR', 'CONST', ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.