text stringlengths 3.07k 22.1k |
|---|
from xnat_dashboards.data_cleaning import data_formatter
class DataFilter:
"""
It first filter out the data based on project ids
that should not be visible to user based on role.
It then sends the data to data formatter which
format the data, then ordering is done using the
DataFilter
Ar... |
"""Helper class for building Siamese model for One-shot learning.
@description
For training, validating/evaluating & predictions with SiameseNetwork.
@author
<NAME>
Artificial Intelligence & Software Engineer.
Email: <EMAIL>
GitHub: https://github.com/victor-iyiola/
@project
Fi... |
"""
namecom: data_models.py
Defines data models for the api.
<NAME> [https://github.com/CtheSky]
License: MIT
"""
class DataModel(object):
"""
This is base class for data models.
It provides following utilities:
1. class method `from_dict` to construct model from a dict
2. instance method `... |
#############################################################################
##
## Copyright (C) 2013 Riverbank Computing Limited.
## Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
## All rights reserved.
##
## This file is part of the examples of PyQt.
##
## $QT_BEGIN_LICENSE:BSD$
## You may use th... |
from typing import List, Iterable
import itertools
import numpy as np
import graph_tool.all as gt
from sklearn.metrics import jaccard_score
from polarmine.alternative.alternative_solver import AlternativeSolver
from polarmine.alternative.utils import (
nc_graph,
select_contents,
densest_subgraph,
)
from po... |
"""
NOT SCALED
Source code: https://www.kaggle.com/scratchpad/kernel8be5628cbb/edit
"""
#-------------------------------------------#
# Import dependencies #
#-------------------------------------------#
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as... |
# 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
# d... |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import * # NOQA
import os
import unittest
import numpy as np
from obspy.core.preview import create_preview
from obspy.core.trace import Trace
from obspy.core.utcd... |
import argparse
import codecs
from PhishCanary import english_confusables
from PhishCanary.__init__ import __version__
import os
import dns.resolver
import tldextract
def is_ascii(name):
res = True
for i in name:
if ord(i) >= 128:
res = False
break
return res
def calc_min... |
import pygtk
pygtk.require('2.0')
import gtk
import pango
print("Using pygtk " + str(gtk.pygtk_version))
print("Using gtk " + str(gtk.gtk_version))
from DesktopFileCreatorConfig import Info
from DesktopFileCreatorConfig import Config
from DesktopFileCreatorConfig import Categories
from DesktopFileCreatorState import ... |
import json
import datetime
import pytz
import uuid
import copy
from rfc3987 import parse as parse_IRI
class WebAnnotationValidator(object):
def __init__(self):
self.accepted_types = ["Annotation", "AnnotationCollection", "AnnotationPage"]
def validate(self, annotation, annotation_type=None):
... |
#!/usr/bin/env python3
"""py3d
Library for reading Arma's .p3d files in their unbinarized (MLOD) form.
https://github.com/KoffeinFlummi/Chronyk
"""
import struct
import collections
def _read_asciiz(f, encoding="utf-8"):
pos = f.tell()
bts = b""
while b"\0" not in bts:
bts += f.read(1024)
... |
# -*- coding: utf-8 -*-
# Created by restran on 2017/1/21
from __future__ import unicode_literals, absolute_import
import os
import sys
import time
from collections import deque
import logging
import traceback
from tornado.httpclient import HTTPRequest, HTTPError
from future.moves.urllib.parse import urlunparse, urlpa... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 3 09:47:11 2019
@author: egomez
"""
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import skimage
## Define the exponential, n_gamma and distance function for the plots.
def func_exp_pure(x, a, c):
return a*np.exp(-c*(... |
import os
import os.path as op
import json
# import logging
import base64
import yaml
import errno
import io
import math
from PIL import Image, ImageDraw
from maskrcnn_benchmark.structures.bounding_box import BoxList
from .box_label_loader import LabelLoader
def load_linelist_file(linelist_file):
... |
#!/usr/bin/env python
from __future__ import print_function, absolute_import, division
# -*- coding: utf-8 -*-
"""
Copyright (c) 2011, <NAME> <<EMAIL>>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and ... |
from collections import defaultdict, deque
import torch
import numpy as np
from logger import log
from env.Flatland import get_new_position
from env.observations.TreeObsForRailEnv import TreeObsForRailEnv
from flatland.envs.agent_utils import RailAgentStatus
from env.RailGraph import RailGraph
# TreeObservation to v... |
import curses
import random
import numpy as np
from enum import Enum
from collections import defaultdict
class GameField:
actions = Enum('actions', ('Up', 'Down', 'Left', 'Right', 'Restart', 'Exit'))
valid_actions = [action for action in actions]
vaild_low_input = [ord(ch) for ch in 'wsadrq']
... |
# Copyright 2020 The ElasticDL 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 applicable law... |
from module.Unet_parts import *
from module.Attention_block import weights_init_normal
class UNet(nn.Module):
def __init__(self, n_channels, n_classes, downsize_nb_filters_factor=2):
super(UNet, self).__init__()
self.inc = inconv(n_channels, 64 // downsize_nb_filters_factor)
self.down1 = d... |
"""plotting tool for atmospheric structure
"""
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
def plottau(nus,dtauM,Tarr=None,Parr=None,unit=None,mode=None,vmin=-3,vmax=3):
"""plot tau
This function gives the color map of log10(tau) (or log10(dtau)), optionally w/ a T-P prof... |
import tensorflow as tf
from deprecation import deprecated
from tf_contextual_prediction_with_expert_advice import \
l1_projection_to_simplex, \
greedy_policy
from tf_kofn_robust_policy_optimization.utils.tensor import \
matrix_to_block_matrix_op as policy_block_matrix_op
def dual_action_value_policy_eval... |
import os
import itertools
#import cv2
import torch
import random
import numpy as np
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
from sklearn.manifold import TSNE
from torch.utils.data import DataLoader
from matplotlib.pyplot import cm
# import model
from resnet18 import resnet18
# impor... |
from itertools import chain
import hashlib
from django.db import models
from django.contrib.postgres.fields import JSONField, ArrayField
from django.core.serializers.json import DjangoJSONEncoder
from django.urls import reverse
from django.utils.translation import gettext as _, get_language
from dateutil.parser impo... |
# 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 applica... |
# 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 or agreed to in writing, ... |
import asyncio
import socket
import threading
import json
import logging
import websockets
from collections import defaultdict
from typing import Dict, List, Optional
from flask import Flask
from marshmallow import Schema, fields, INCLUDE, ValidationError
from . import util
from .config import configure_logger
from .... |
import sys
import os
import pickle
import shutil
from pathlib import Path
import pytest
import numpy as np
import Ska.DBI
import tables
from Chandra.Time import DateTime
from .. import fetch
from .. import update_client_archive, update_server_sync
from ..utils import STATS_DT, set_fetch_basedir
pytestmark = pytest.m... |
from environment import Environment
import numpy as np
from scipy.stats import norm
from scipy.optimize import minimize
from datetime import timedelta
from pandas._libs.tslibs.timestamps import Timestamp, Timedelta
class Instrument:
def __init__(self):
self.ccy = None
self.type = None
sel... |
import numpy as np
import cv2
from ...models.keypoint_detectors import SIFT_detect
def sample_homography(
shape, perspective=True, scaling=True, rotation=True, translation=True,
n_scales=5, n_angles=25, scaling_amplitude=0.1, perspective_amplitude_x=0.1,
perspective_amplitude_y=0.1, patch_rat... |
"""Async functions for interacting with the osu! api and prepping its data.
This uses the v1 endpoint because it is more stable. Use v2 when available or
necessary.
"""
import aiohttp
from enum import IntFlag
import os
import math
import db_manip
import db_get
api_key = os.getenv("osu_key")
class Mod... |
import os
import gc
import sys
sys.path.insert(0, "/home/phan.huy.hoang/phh_workspace/") # noqa
import time
import copy
import argparse
import cv2
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from models import DBTextModel
from utils import (read_img, test_preprocess, visuali... |
import collections
import math
from collections import OrderedDict
from concurrent import futures
from ordered_set import OrderedSet
from miniworld.Scenario import scenario_config
from miniworld.model.singletons.Resetable import Resetable
from miniworld.model.singletons.Singletons import singletons
from miniworld.uti... |
import inspect
import json
import os
import subprocess
from typing import List, Dict, Tuple, Set
import settings
class ModuleExtractor:
"""
Supported Languages
=====================
- Python
- Python(ipynb)
- Julia
- Julia(ipynb)
- Go
"""
def python(self, source: str) ->... |
import json
import logging
import threading
import pickle
from typing import Dict, List
from hh_page_clf.models import DefaultModel
import kafka.client
import pykafka
from pykafka.common import OffsetType
import pytest
from hh_deep_deep.service import (
Service, encode_model_data, decode_model_data, output_topic,... |
import os
import math
import json
import struct
import cv2
import imageio
import numpy as np
from sklearn.cluster import MiniBatchKMeans
from sklearn.metrics import pairwise_distances_argmin
class Utils:
@staticmethod
def bgr_to_rgb(colors):
length, channels = colors.shape
colors = colors.resh... |
import pytest
from fastapi.testclient import TestClient
from hashlib import sha512
from datetime import date, timedelta
from os import environ
from main import app
@pytest.fixture
def client():
"""Prepare FastAPI test client."""
return TestClient(app)
@pytest.fixture
def patient_payloads():
"""Prepare ... |
import locale
import logging
import re
from contextlib import contextmanager
from functools import partial
from pathlib import Path
from typing import Any, List, NamedTuple, Tuple
import cv2
import fitz
import numpy as np
import progressbar
from PIL import Image
from lxml import html
from ._super import Token, Tokeni... |
# annot_GENE.py
# Cleans up all gene ontology annotations based on the Gene Ontology Consortium's classification
# <NAME>, <EMAIL>, 29 January 2018
#
# Data sources: https://github.com/flaneuse/ntwk-explr/blob/master/datain/DATA_README.md
# [0] Setup -------------------------------------------------------------------... |
# IMPORTANT TO NOTE
'''
This Notepad is published by faizanscommunit.
This notepad has MIT License
Github: https://github.com/faizanscommunit
Fiverr: https://www.fiverr.com/faizanscommunit
'''
# Importing Modules
from tkinter import *
from tkinter import messagebox
from tk... |
import paper
import database
import numpy as np
from collections import defaultdict
"""
Notes
- This needs to be a separate thing from database? Not part of the main package
- Maybe same thing for the .csv and .gml writing and so on? idk
- How to integrate this into my graph objects?
Functions needed:
- Clear any Pap... |
from __future__ import print_function
from __future__ import division
import findcaffe
import caffe
import os, argparse
import os.path as osp
import numpy as np
import scipy.ndimage as nd
import pylab, png, pickle
from shutil import copyfile
from ipdb import set_trace
import matplotlib.pyplot as plt
plt.switch_backe... |
import pdb
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence
from torch.nn.utils.rnn import pad_packed_sequence
from torch.autograd import Variable
def build_model(src_vocab_size, tgt_vocab_size, args):
if args.bidirectional:
dec_nhid =... |
# -*- coding: utf-8 -*-
# Copyright CNRS 2012,
# <NAME> (LULI)
# This software is governed by the CeCILL-B license under French law and
# abiding by the rules of distribution of free software.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import... |
import io, json, os
from datetime import datetime
from pathlib import Path
from joblib import load
import smart_open
from PIL import Image
from skimage.feature import hog
import numpy as np
import cv2
from typing import Union
from werkzeug.utils import secure_filename
ROOT = Path(__file__).resolve(... |
from __future__ import absolute_import, print_function, division
import re
import warnings
import six
from six.moves import urllib
from netlib import utils
from netlib.http import cookies
from netlib.odict import ODict
from .. import encoding
from .headers import Headers
from .message import Message, _native, _alway... |
'''
SynST
--
Main entry point for evaluating SynST
'''
from __future__ import print_function
import os
import sys
import signal
import time
import pickle
import atexit
from contextlib import ExitStack
import torch
from torch import nn
from tqdm import tqdm
from watchdog.observers import Observer
from watchdog.obser... |
# -*- coding: utf-8 -*-
import logging
import ipaddress
import random
from polaris_health import Error, config, monitors
from polaris_common import topology
__all__ = [ 'PoolMember', 'Pool' ]
LOG = logging.getLogger(__name__)
LOG.addHandler(logging.NullHandler())
MAX_POOL_MEMBER_NAME_LEN = 256
MAX_POOL_MEMBER_WEI... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
import cv2
import numpy as np
from IPython import embed
EPSILON = 1e-6
def lg10(x):
return torch.div(torch.log(x), math.log(10))
def maxOfTwo(x, y):
z = x.clone()
maskYLarger = torch.lt(x, y)
z[maskYLarg... |
import getpass
import sys
import textwrap
import time
import webbrowser
import jwt
from six.moves import urllib
from six.moves.urllib.parse import urlparse
from dcos import config, http, util
from dcos.errors import (DCOSAuthenticationException, DCOSException,
DCOSHTTPException)
logger = uti... |
# -*- coding: utf-8 -*-
"""
Find similarity transformation parameters given a set of control points
A partial implementation of the algorithm described by Zeng et al.,
2018[1]_.
Given a set of 3-D control points, the algorithm solves an optimization
problem to find the parameters of the similarity transform... |
"""
Dataclasses; classes whose only purpose is to hold specific data.
"""
import typing
import math
from .. import constants
from .abc import JSONData, Settable, Block
from ..enums import Enchantments, TagType, CodeblockActionType, BlockType, BracketDirection, BracketType
from ..utils import remove_u200b_from_doc, all_... |
"""
Binary Ninja plugin that aids in analysis of UEFI PEI and DXE modules
"""
import os
import csv
import glob
import uuid
from binaryninja import (BackgroundTaskThread, SegmentFlag, SectionSemantics, BinaryReader, Symbol,
SymbolType, HighLevelILOperation, BinaryView)
from binaryninja.highleve... |
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import (
QWidget, QLabel, QFrame, QVBoxLayout, QHBoxLayout, QToolButton, QGridLayout, QCheckBox,
QLineEdit, QDialog, QPushButton, QSpinBox
)
import sys
import os
from argparse import ArgumentParser
import acconeer_utils
d... |
"""WIP, a class for modeling and manipulating bounding box data
"""
import math
import random
from dlib import rectangle as dlib_rectangle
import numpy as np
class BBoxPoint:
def __init__(self, x, y):
self._x = x
self._y = y
@property
def x(self):
return self._x
@property
def y(self):
... |
__author__ = 'Galileo'
from Classes import *
AllCountries = []
AllRegions = []
AllModifiers = []
AllIDs = {}
CIDMap = {}
RIDMap = {}
MIDMap = {}
CID = 0
RID = 0
MID = 0
IDD = {
"C": CID,
"R": RID,
"M": MID
}
def get_object(name):
type = AllIDs[name]
if type == 'Country':
oID = CIDMap[name]... |
# imports
# imports for GUI(Tkinter)
from tkinter import *
from tkinter import ttk
import tkinter as tk
# imports for background
from system_hotkey import SystemHotkey
import pyautogui
import time
import threading
# import for notifications
from plyer import notification
#-------------------------... |
import dash
import dash_html_components as html
import dash_core_components as dcc
import plotly.graph_objects as go
from dash.dependencies import Input, Output,State
import dash_bootstrap_components as dbc
from dash.exceptions import PreventUpdate
import pandas as pd
import createBarChart as cbc
import connectDb as c... |
import os, sys, inspect
import numpy as np
from copy import deepcopy
from ..mfbase import MFDataException
def get_first_val(arr):
while isinstance(arr, list) or isinstance(arr, np.ndarray):
arr = arr[0]
return arr
class TemplateGenerator(object):
"""
Abstract base class for bui... |
from contextlib import closing
from bitstring import Bits
from django.db import models
from django.db.backends.postgresql_psycopg2.base import DatabaseWrapper as PGDatabaseWrapper
from django.db.backends.signals import connection_created
from psycopg2 import extensions as ext
try:
from rest_framework import seria... |
import os
import argparse
from pathlib import Path
from pprint import pprint
import numpy as np
from tqdm import tqdm
import nibabel as nib
import h5py
from sklearn.model_selection import train_test_split
import add_uncertify_to_path
import uncertify
from uncertify.data.preprocessing.camcan import get_camcan_nii_samp... |
from collections import OrderedDict
import torch
import logging
import numpy as np
from mmskeleton.utils import call_obj, import_obj, load_checkpoint
from mmcv.runner import Runner
from mmcv import Config, ProgressBar
from mmcv.parallel import MMDataParallel
import os, re, copy
from sklearn.model_selection import KFold... |
from typing import List
import numpy as np
import torch
from config.autoresponder_config import * # TODO: move elsewhere?
from ml.sampling_params import SamplingParams, DEFAULT_SAMPLING_CONFIG
from transformers import LogitsProcessorList
from ml.sample_torch import BreakrunsLogitsProcessor
from util.util import co... |
import torch
import numpy as np
import torch.nn as nn
from torch.nn.parameter import Parameter
class MeshNet(nn.Module):
def __init__(self, n_class, mask_ratio=0.95, dropout=0.5):
super(MeshNet, self).__init__()
self.spatial_descriptor = SpatialDescriptor()
self.structural_descriptor = S... |
from root import MEASURE_RESULTS
import confmeasure
import measure_helpers as util
from measure_helpers import (
GUEST_JAVDEV,
GUEST_QEMUBLK,
GUEST_QEMU9P,
GUEST_JAVDEV_MOUNT,
GUEST_QEMUBLK_MOUNT,
HOST_SSD,
run,
)
from qemu import QemuVm
from typing import List, Any, Optional, Callable, Tup... |
#%%
import os
os.environ['MLFLOW_TRACKING_URI'] = 'http://localhost:9001'
import torch
torch.randn(10,10).cuda()
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import AdamW
from torch.optim.lr_scheduler import StepLR
from pathlib import Path
from torch.utils.data import Subset as DataSubset
from... |
"""This module defines the Version classes, and the related Manifest
implementations.
"""
from __future__ import with_statement
import os
import pickle
from webassets import six
from webassets.merge import FileHunk
from webassets.utils import md5_constructor, RegistryMetaclass, is_url
__all__ = ('get_versioner', '... |
import os
import errno
import os.path as osp
from configparser import ConfigParser
def get_parent_dir_path(path):
"""Returns the path to the parent directory in path. """
if osp.isfile(path):
return osp.dirname(path)
return osp.dirname(osp.abspath(path))
# Default file names
CONFIG_FILE_NAME = "... |
import numpy as np
import plotly.graph_objects as go
import dash
from dash.exceptions import PreventUpdate
from dash import dcc, Output, Input, State, html, dash_table
from dash.dash_table.Format import Format, Scheme
import dash_bootstrap_components as dbc
import dash_vtk
from dash_vtk.utils import to_mesh_state
from... |
import datetime
import time
import pandas as pd
from chmap.maps.util.map_manip import combine_maps
from chmap.settings.info import DTypes
from chmap.utilities.plotting import psi_plotting as Plotting
def create_combined_maps(db_session, map_data_dir, map_list, chd_map_list, methods_list,
da... |
#!/usr/bin/python
# coding: utf-8
import cx_Oracle
import getopt,os,sys
import pymysql
import petl as etl
import time,datetime
from tqdm import tqdm
from configparser import ConfigParser
# import warnings
# warnings.filterwarnings("ignore")
import platform
system=platform.system()
os.environ['NLS_DATE_FORMAT'] = 'yy... |
import numpy as np
import os, logging
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
logging.getLogger("tensorflow").setLevel(logging.CRITICAL)
logging.getLogger("tensorflow_hub").setLevel(logging.CRITICAL)
import keras as K
import tensorflow as tf
import copy
import warnings
class batchless_VanillaLSTM_keras(object):
"... |
# -*- coding: utf-8 -*-
"""
"""
from __future__ import absolute_import
import io
import itertools
import os
import sys
import unittest
if sys.version_info >= (3, 0): # pragma: no cover
unichr = chr
text_type = str
else:
text_type = unicode
class Test_xsendfile_middleware(unittest.TestCase):
def mak... |
"""
Utility functions for building neural networks in theano.
Most of these are taken from http://deeplearning.net/tutorial/.
"""
from __future__ import print_function
import os
import sys
import timeit
import gzip
import pickle
import numpy as np
import theano
import theano.tensor as T
def load_data(dataset):
... |
import logging
from dataclasses import dataclass
from typing import Any, Dict, List, Union
from ideal_learning_env.defs import ILEConfigurationException, ILEException
from ideal_learning_env.numerics import MinMaxFloat
from .choosers import choose_random
from .components import ILEComponent
from .decorators import il... |
from __future__ import unicode_literals
from decimal import Decimal
import datetime
from django.conf import settings
from django.core.urlresolvers import reverse
from django.core.validators import MinValueValidator, RegexValidator
from django.db.models import Manager, Q
from django.utils.encoding import python_2_unico... |
#! /usr/bin/env python
# coding=utf-8
import tensorflow as tf
def convolutional(input_data, filters_shape, trainable, name, downsample=False, activate=True, bn=True):
with tf.variable_scope(name):
if downsample:
pad_h, pad_w = (filters_shape[0] - 2) // 2 + 1, (filters_shape[1] - 2) // 2 + 1
... |
"""
Contains the following helper controllers:
- :class:`RemappedBlock`: a remapping of inputs/outputs into another block's
inputs and outputs.
- :class:`MultiBlock`: a block that runs many other sub-blocks on
each step. The I/O dictionaries are basically used as a blackboard
architecture.
- :class:`LambdaBlo... |
#!/usr/bin/env python3
# coding: utf-8
from wxpy import *
import config
import re
from wxpy.utils import start_new_thread
import time
import os
import platform
from importlib import reload
'''
使用 cache 来缓存登陆信息,同时使用控制台登陆
'''
console_qr = (False if platform.system() == 'Windows' else True)
bot = Bot('bot.pkl', console_q... |
# -*- coding: utf-8 -*-
# <nbformat>3</nbformat>
# <markdowncell>
# Calibration of Heston's Model on SPX data
# =======================================
#
# This notebook demonstrates the calibration of Heston's model on SPX data, using the QuantLib hestonmodel class.
# The code is adapted from the test suite writte... |
#!/usr/bin/python
"""
Functions to create output.
@author: <NAME>
"""
import os
import warnings
import numpy as np
from sklearn.metrics import matthews_corrcoef, log_loss
from helpers import round_labels
import plots
def is_inc_monotonic(lst):
"""
Check whether the the elements in the list increase monoto... |
import util
from functools import wraps
import re
import datetime
def check_function(function,message,bot):
match = None
if not message.message:
return (False,None)
check_attributes = list(set(Module.triggers).intersection(dir(function)))
if "direct" in check_attributes:
check_attributes.remove("direct")
che... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import sys
import argparse
import util
import numpy as np
import torch
import pycuda.autoinit # noqa
import pycuda.driver as cuda
from pycuda.compiler import SourceModule # noqa
impor... |
import board
import microcontroller
import pulseio
import supervisor
import sys
import time
import adafruit_bno055
from adafruit_motorkit import MotorKit
from digitalio import DigitalInOut, Direction, Pull
from time import sleep
# -- hardware-------------------------------------------------------------------
i2c = bo... |
import os
import dotenv
from flask import Flask, abort, jsonify, make_response, redirect, render_template, request, url_for
from flask_sqlalchemy import SQLAlchemy
from dotenv import load_dotenv
load_dotenv()
dbname = os.getenv('DBNAME')
password = os.getenv('PASSWORD')
user = os.getenv('USER')
url = os.getenv('URL')
a... |
import pandas as pd
import numpy as np
# Import libraries
import xgboost as xgb
from sklearn import decomposition
from sklearn.model_selection import GridSearchCV, cross_validate
from sklearn.preprocessing import LabelEncoder
#import data
tr_datapath = "data/train_users_2.csv"
te_datapath = "data/test_users.... |
from datetime import datetime
import offchain
from offchain import FundPullPreApprovalStatus
from flask import Response
from flask.testing import Client
from tests.wallet_tests.resources.seeds.one_funds_pull_pre_approval import TIMESTAMP
from wallet.services.offchain import (
offchain as offchain_service,
fund... |
#
# Karel.py
#
# Copyright (c) 2017 cpiehl
#
# A Python implementation of the educational programming language Karel
# https://en.wikipedia.org/wiki/Karel_(programming_language)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ... |
# -*- coding: utf-8 -*-
"""
Runs a NEB on all unique pathways within a structure.
The folder tree looks like...
```
simmate-task-12345/ # determined by simmate.utilities.get_directory
├── bulk_relaxation
├── bulk_static_energy
├── migration_hop_00
├── migration_hop_01
...
└── migration_hop_N... |
"""
This module provides basic functionality of scraping, retrieving and saving contact data (email addressess and phone numbers) from
a user provided query.
The usual execution proceeds as follows:
1. User inputs a query,
2. URL's are retrieved from google's search results,
3. These sites are then parsed for e-mails... |
# Precision/Recall (PR)
import os
import numpy as np
import tensorflow as tf
import dnnlib
import dnnlib.tflib as tflib
import glob
import PIL.Image
from metrics import metric_base
from training import misc
def batch_pairwise_distances(U, V):
# Compute pairwise distances between two batches of feature vectors
... |
import asyncio
import discord
from Data.Constants.import_const import Login, Ids, Main_bot
from Data.Constants.useful import Useful
Emojis = {}
class EmojisBot(discord.Client):
emojis = {}
emoji_connected = asyncio.Event()
def __init__(self):
super().__init__()
async def on_ready(self):
... |
import os
import json
import time
import importlib
import argparse
import numpy as np
from collections import OrderedDict
import torch
import torch.nn as nn
from torch.autograd import Variable
from PIL import Image
import torchvision.transforms as transforms
os.environ['CUDA_VISIBLE_DEVICES'] = '4'
def parse_args():
... |
# Copyright 2018 Google LLC
#
# 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 writing, ... |
#!/usr/bin/env python
import argparse
import getpass
import logging
import os
import shutil
import stat
from scisql import configure
from scisql import const
from scisql import utils
import sys
import tempfile
def parse_args():
parser = argparse.ArgumentParser(
description='''sciSQL deployment tool.... |
from operator import delitem
import sys
import os
import re
import json
import argparse
import cv2
import csv
import ffmpeg
from pathlib import Path
from pathvalidate.argparse import validate_filepath_arg
# IMPORTANT: Only add to the end of these lists. Doing otherwise could break the annotations.
weather_types = ['Dr... |
import json
import os
import random
import shutil
import string
from datetime import datetime
from os import environ
from celery import Celery
from celery.utils.log import get_task_logger
from flask import current_app, flash, render_template, session
from flask_mail import Mail, Message
from edurange_refactored.scena... |
"""
Ivory uses four classes for data presentation: `Data`, `Dataset`, `Datasets`,
and `DataLoaders`.
Basically, you only need to define a class that is a subclass of `Data`
and use original `Dataset` and `Datasets`. An example parameter YAML file is:
datasets:
data:
class: your.Data # a subclass of... |
'''
INSTANCE SELECTION-BASED BINARY FIREFLY ALGORITHM
'''
#IMPORT PACKAGES
import numpy as np
from numpy import linalg
import csv
import cvxopt
import cvxopt.solvers
#START OF FIREFLY ALGORITHM
#DEFINE OBJECTIVE FUNCTION
def objective_function(dataset, value):
idx = np.array([np.linalg.norm(x+y) for (x,y) in da... |
# coding: UTF-8
import os
from typing import List, Any, Tuple
import torch
import numpy as np
import pickle as pkl
from tqdm import tqdm
import time
from datetime import timedelta
MAX_VOCAB_SIZE = 10000 # 词表长度限制
UNK, PAD = '<UNK>', '<PAD>' # 未知字,padding符号
def build_vocab(file_path, tokenizer, max_size, min_freq)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.