text stringlengths 3.07k 22.1k |
|---|
import html
import random
import re
import nltk
import numpy as np
import pyspark
class Tokenizer:
'''The default tokenizer, follows the NLTK API.
This currently implements a regular expression tokenizer.
If we were allowed to, I'd prefer NLTK's `word_tokenize` function.
'''
def __init__(self)... |
# library doc string
'''
Author: goldin2008
Date: December, 2021
This module implements the main script for the customer churn project with clean code
'''
# import libraries
import os
import yaml
import shap
import joblib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# f... |
"""Playlist functions
"""
from collections import deque
import os
import time
from PyQt5.QtCore import QTimer, pyqtSlot
import settings
import screen
import functions
#Song structure is a dict:
songstructure_enum={
'index': 0,
'display': '',
'title': '',
'search': '', #search letter
'chars': '',... |
from lsh.lsh.lsh_base import LshBase
from lsh.utils.similarity import jaccard_similarity
from lsh.utils.similarity import compute_positive_hash
from lsh.models.documents.jaccard_document import JaccardDocument
import copy
def _get_documents(hash_code, band_dict):
if hash_code and band_dict:
return band_dic... |
# Copyright (c) 2015 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, using, copying or modifying this work you indicate your
# agreement to t... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import sy... |
# util.py (lciafmt)
# !/usr/bin/env python3
# coding=utf-8
"""
This module contains common functions for processing LCIA methods
"""
import uuid
import os
from os.path import join
import lciafmt
import logging as log
import pandas as pd
import numpy as np
import yaml
import pkg_resources
import subprocess
from esupy.pr... |
# coding: utf-8
#11,12,13
import numpy as np
from graphviz import Graph
import matplotlib.pyplot as plt
train_data = np.loadtxt('hw3_train.dat.txt')
test_data = np.loadtxt('hw3_test.dat.txt')
train_x = train_data[:,0:-1]
train_y = train_data[:,-1]
test_x = test_data[:,0:-1]
test_y = test_data[:,-1]
class node():
... |
import numpy as np
from sklearn.utils import shuffle as skshuffle
from sklearn.metrics import roc_auc_score
import scipy.sparse as sp
import networkx as nx
# Some Utilities
def get_minibatches(X, mb_size, shuffle=True):
"""
Generate minibatches from given dataset for training.
Params:
-------
X: n... |
import os
import tensorflow as tf
import tensorflow_datasets as tfds
from tqdm import tqdm
from dlex.datasets.builder import DatasetBuilder
from dlex.datasets.keras import KerasDataset
from dlex.utils.logging import logger
_R_MEAN = 123.68
_G_MEAN = 116.78
_B_MEAN = 103.94
_CHANNEL_MEANS = [_R_MEAN, _... |
import nextcord
from nextcord import Interaction, SlashOption, Role
from nextcord.ext import commands
from nextcord.utils import get
from os import getenv
import sys
from util.admin_check import admin_check
global task
import re
import pickle
import sys,os
sys.path.append('../')
from util import n_fc, mc_status
import ... |
import logging
import copy
from functools import partial
from pyramid import security
from pyramid.request import Request
from lovely.pyrest.rest import rpcmethod_route, rpcmethod_view
from ..errors import Errors
from ..endpoint import EndpointErrorMixin
from .swagger import swagger_reduce_response
from .extender i... |
""" TransSet model implementations.
"""
import ccobra
import numpy as np
# Constants
neg_quantifiers = ['E', 'O']
part_quantifiers = ['I', 'O']
def atmosphere_predictions(first, second):
""" Produces atmosphere predictions to a given tuple of premises.
Parameters
----------
premises : list(str)
... |
from __future__ import print_function, division, absolute_import
import numpy
import math
import sys
import itertools
from collections import namedtuple
from llvmlite.llvmpy import core as lc
from . import builtins, ufunc_db
from .imputils import implement, Registry
from .. import typing, types, cgutils, numpy_suppo... |
# The following script contains classes with necessary Blender operators
# for the Neural material approach in material generation and editing.
#
# Code from Neural Material paper is stored in neuralmaterial directory
# and is available on the following repository: https://github.com/henzler/neuralmaterial
import os
i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""""
This module contains tools for backend modeling and scoring
EDITED FOR UEF SUMMERSCHOOL
"""
__version__ = '1.1'
__author__ = '<NAME>, <NAME>'
__email__ = '<EMAIL>'
import numpy as np
from scipy.linalg import eigh, cholesky, inv, svd, solve
import time
class GPLDA:
... |
import logging
from io import BytesIO
from pdf_utils import generic
from fontTools import ttLib, subset
from pdf_utils.incremental_writer import IncrementalPdfFileWriter
from pdf_utils.misc import peek
logger = logging.getLogger(__name__)
pdf_name = generic.NameObject
pdf_string = generic.pdf_string
ALPHABET = 'ABC... |
"""
Rackspace CloudFiles Viewer
"""
from __future__ import print_function
import os
import json
import sys
import logging
import logging.config
import argparse
from rcbu.client.auth import Authentication
from rcbu.cloud.files import CloudFiles
def prompt_get_data_centers(auth_engine):
"""
Prompt the user t... |
import tensorflow as tf
import numpy as np
import glob, random, os
import tensornets as nets
import sys
# tensorboard --logdir logdir
class CNN_Lander(object):
def __init__(self):
with tf.name_scope('Input_img'):
self.input_image = tf.placeholder(tf.float32, [None, 200, 200... |
from conans.errors import ConanInvalidConfiguration, ConanException
from conans.model.version import Version
def check_min_cppstd(conanfile, cppstd, gnu_extensions=False):
""" Check if current cppstd fits the minimal version required.
In case the current cppstd doesn't fit the minimal version required
... |
from abc import ABC
from typing import IO, Any, Dict, List, Union, cast, Iterator
from pathlib import Path
import numpy as np
from iteration_utilities import duplicates
import re
import json
import fsspec
import pandas as pd
from sqlalchemy import Column, String
from PIL import Image
from datapipe.types import Data... |
# -*- coding: utf-8 -*-
"""Embeddings from the pre-trained STonKGs model."""
import logging
from pathlib import Path
from typing import Iterable, List, Optional, Tuple, Union
import pandas as pd
import torch
from tqdm import tqdm
from transformers import BertTokenizer, BertTokenizerFast
from stonkgs.constants impor... |
#!/usr/bin/python3
"""
This script exports all devices from an existing itsecorg installation.
It allows for migrating fortigate ssh devices into fortimanager installations
first add new fortimanager (via UI) and use its management id as parameter -f X
create csv from itsecorg postgresql (input files for this scrip... |
#standard
import math
import sys
import unittest
import time
import logging
import os
#get current directory of file
curdir = os.path.dirname(os.path.realpath(__file__)) + os.sep
def set_logger(console_level = logging.INFO, file_level = logging.DEBUG, include_file = True, append_file = False):
"""
Creates the... |
import os
import shutil
import subprocess
import click
import requests
from .common import __version__, isUserAdmin, get_parser, merge_video
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'], ignore_unknown_options=True)
@click.group(context_settings=CONTEXT_SETTINGS, invoke_without_command=True)
@click.op... |
# -*- coding: utf-8 -*-
'''
In this excercise we model the MNIST dataset using only linear layers.
In this exercise we'll use the same logic laid out in the ANN notebook.
We'll reshape the MNIST data from a 28x28 image to a flattened 1x784 vector
to mimic a single row of 784 features.
We used nn.module and nn.linear, b... |
# coding:utf-8
'''
https://finance.yahoo.com/quote/600000.SS/history?period1=1262275200&period2=1512921600&interval=1d&filter=history&frequency=1d
'''
# coding:utf-8
'''
@Function:取得上证50成分股的N年历史数据(价格数据和交易量数据或者其他备选数据)
定位爬取网址为(以浦发银行2017年4季度数据为例):http://quotes.money.163.com/trade/lsjysj_600000.html?year=2017&season=4
数据来自... |
import csv
import numpy
from sklearn import preprocessing
import pulp
seasons = [
"2020-21",
"2021-22",
]
teams = {}
players = {}
player_codes = []
positions = {
1: {
"type": "GKP",
"squad_select": 2,
},
2: {
"type": "DEF",
"squad_select": 5,
},
3: {
... |
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import torch
import pycuda.driver as cuda
import pycuda.autoinit
import numpy as np
import tensorrt as trt
import time
from torch.nn import functional as F
from utils import get_path_with_annotation,postprocess,DataIterator,DataGenerator
from multiprocessing import Po... |
# testscenarios: extensions to python unittest to allow declarative
# dependency injection ('scenarios') by tests.
#
# Copyright (c) 2009, <NAME> <<EMAIL>>
# Copyright (c) 2010, 2011 <NAME> <<EMAIL>>
#
# Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
# license at the users choice. A copy o... |
from django.conf import settings
from django.contrib.postgres.fields import JSONField
from django.db import models
from preboarding.models import Preboarding
from resources.models import Resource
from to_do.models import ToDo
from appointments.models import Appointment
from introductions.models import Introduction
fr... |
# coding=utf-8
"""
Run protocols using methods in `iocompare.py`.
The changes in persistence or frequency are specified in `config_stims.hoc`.
This is a holdover from shifting to python from pure hoc scripts.
"""
import numpy as np
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
... |
# ----------------------------------------------------------------------------
# Copyright (C) 2017 Verizon. 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
#
# ... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, <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 t... |
import gym
import numpy as np
import random
import tensorflow as tf
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import Dense, Activation, Dropout, Flatten, Conv2D, MaxPool2D
from tensorflow.keras.optimizers import Adam
from collections import deque
from collections import Co... |
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# 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/lice... |
# Python 3.6
from tensorflow.examples.tutorials.mnist import input_data
import mnist_loader # This is nielson
from network import Network as TF_Network
from np_network import Network as NP_Network # this is nielson
from time import time
# import numpy as np
import pandas as pd
# from itertools import product, tee, re... |
# @Author: <NAME> <gio>
# @Date: 10-Aug-2021
# @Email: <EMAIL>
# @Project: FeARLesS
# @Filename: 01_figurePositions.py
# @Last modified by: gio
# @Last modified time: 11-Aug-2021
# @License: MIT
import pandas as pd
import os
import tqdm
import struct
import matplotlib.pyplot as plt
import numpy as np
from iterto... |
"""
This method trains a pre-specified modeltype using data
from data/processed (corrupted Mnist data)
This method can be called using "make train <commands>"
<commands> are:
--lr (defualt=0.003)
--epochs (defualt=30)
--batchsize (defualt=64)
--modelType (defualt='ConvolutionModel_v... |
# -*- coding: utf-8 -*-
"""
celery.app.amqp
~~~~~~~~~~~~~~~
AMQ related functionality.
:copyright: (c) 2009 - 2012 by <NAME>.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from datetime import timedelta
from weakref import WeakValueDictionary
from kombu... |
import turtle
import winsound
import random
colors = ["red", "green", "blue", "orange", "purple", "pink", "yellow", "white"]
filename = 'assets/sound/PongSnakeSound.wav'
"""
<------>
ACROSS = X
UP AND DOWN = Y
x, y for position
350 for right and -350 for left
"""
wn = turtle.Screen() # This will make ... |
import numpy as np
import time
import torch
import torch.nn.functional as F
import torch.optim as optim
from constants import DATASET_BOSTON
from data_loaders import DataLoaders
from hyper_optimizer import get_hyper_train, train_loss_func, hyper_step, get_hyper_train_flat
from train_augment_net_graph import save_image... |
import unittest
from vasppy.vasprun import Vasprun, parse_varray, parse_structure
from vasppy.vasprun import structure_from_structure_data
from unittest.mock import Mock, patch, call, mock_open, PropertyMock
from lxml import etree
from io import BytesIO
from pymatgen.core import Lattice, Structure
import numpy as np
d... |
# Copyright (c) 2014-2018 Barnstormer Softworks, Ltd.
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import absolute_import
import datetime
from io ... |
import os
import subprocess
import asyncio
import re
async def create_directories():
arrest_csv = "./data/csv/arrest/"
case_csv = "./data/csv/case/"
incident_csv = "./data/csv/incident/"
if not os.path.isdir(incident_csv):
os.mkdir(incident_csv) ## create dir if it doesn't exit
#s... |
"""
This platform allows several climate devices to be grouped into one climate device.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/climate.group/
For more details on climate component, please refer to the documentation at
https://developers.home-ass... |
import os
import json
import requests
import warnings
from requests_toolbelt import MultipartEncoder
class MultiDimDocmentApi(object):
"""
一次只能针对一个飞书一个多维表格的一个数据表进行操作
"""
def __init__(self, user_id, app_id, app_secret, app_token, table_id) -> None:
"""
Args:
user_id (str): 用... |
import nose.tools
import cc.license
from cc.license import CCLicenseError
from cc.license._lib.classes import License
class TestAll:
def __init__(self):
self.stdsel = cc.license.selectors.choose('standard')
self.smpsel = cc.license.selectors.choose('recombo')
self.pdsel = cc.license.selec... |
import warnings
import inspect
import matplotlib.pyplot as plt
import IPython.display
import numpy as np
from cued_sf2_lab.familiarisation import load_mat_img, plot_image
from cued_sf2_lab.laplacian_pyramid import quantise
from cued_sf2_lab import laplacian_pyramid
import warnings
import inspect
import matplotlib.pyplo... |
#
# Copyright (c) 2019 UAVCAN Development Team
# This software is distributed under the terms of the MIT License.
# Author: <NAME> <<EMAIL>>
#
import copy
import typing
import asyncio
import logging
import dataclasses
import pyuavcan
from ._session import UDPInputSession, SelectiveUDPInputSession, PromiscuousUDPInputS... |
# -*-coding=utf-8-*-
"""
Created on Fri 7 Apr 2017
@author: <NAME>
Prepare data for RNN model.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import re
import sys
import tensorflow as tf
# Special vocabulary symbols - we always put them at... |
import logging
import json
import posixpath
from django.conf import settings
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.html import escape
from django.utils.translation import gettext
from django.utils.translation import gettext_lazy as _
from django.utils.tr... |
import numpy as np
import theano
import theano.tensor as T
from sklearn.utils import check_random_state
from .core import floath
from .core import cost_var
from .core import find_sigma
def movement_penalty(all_step_visible_data, N):
penalties = []
for t in range(len(all_step_visible_data) - 1):
pena... |
import pdb
import pandas as pd
from pathlib import Path
from torch import nn
from tokenizers import ByteLevelBPETokenizer
from tqdm import tqdm
from transformers import BertConfig, BertForPreTraining
from torch.utils.data import Dataset, DataLoader
import random
import numpy as np
import torch
## 读取数据
train = pd.rea... |
# Copyright 2019 Xilinx, 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,... |
# Copyright (c) 2016, The Bifrost Authors. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions a... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import json
from json import encoder
import random
import string
import time
import os
import pdb
import sys
from . import ... |
import os, random, time, json
import numpy as np
from functools import partial
try:
get_ipython()
from tqdm.notebook import tqdm
except:
from tqdm import tqdm
from copy import copy
from pymoo.model.problem import Problem
from pymoo.model.mutation import Mutation
from pymoo.model.crossover import Crossover
f... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020 <NAME>
# Adapted and modified from a MATLAB routine written by <NAME>
"""Functions to compute pseudo transfer entropy (pTE).
This module provides a set of functions to compute pTE between different
time series.
Functions
---------------------
* normalisa -- L2 normali... |
import numpy as np
from os.path import join as os_join
import matplotlib.pyplot as plt
import source.postprocess as post
from source.utilities import utilities as utils
from source.utilities import global_definitions as GD
from plot_settings import plot_settings
COLORS = ['tab:blue', 'tab:orange', 'tab:green', 'tab:... |
#!/usr/bin/python
import itertools, random
from utils.log import log
from bots.simpleBots import BasicBot, ObviousBot
class InterestingBot(BasicBot):
#this bot figures out how many of the highest cards it needs (decending) to win
#majority of the points, bidding low until it finds a card it "needs"
#knows what ot... |
from django.contrib.auth import get_user_model
from django.db.models import Count, Subquery, Q, Avg, F, Prefetch
from django.db.models import OuterRef
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.views.generic import DetailView, ... |
r"""HDF5 demultiplexed DDL
Attributes off of ./ for the full file:
n : int, the number of sequences
max : int, the max sequence length
min : int, the min sequence length
mean : float, the mean sequence length
std : float, the standard deviation of sequence length
... |
'''
use dot product instead of similarity layer
'''
import logging
import logging.config
import configparser as cp
import args
import numpy as np
from keras.preprocessing.sequence import pad_sequences
import pickle
import vectorizer
import load
import sample
#configurations
config = cp.ConfigParser(strict=False)
... |
import torch
from torch import nn, Tensor
from torch.nn import functional as F
from .layers import MLP, DropPath, trunc_normal_
class Attention(nn.Module):
def __init__(self, dim, head):
super().__init__()
self.head = head
self.scale = (dim // head) ** -0.5
self.qkv = nn.Linear(di... |
"""Tests for the rate network."""
import time
import numpy as np
from fake_spectra import rate_network
from fake_spectra import ratenetworkspectra
from fake_spectra._spectra_priv import _interpolate_2d
def _exact_alphaHp():
"""For hydrogen recombination we have an exact answer from Ferland et al 1992 (http://adsa... |
from django import forms
from django.conf import settings
from django.contrib.admin.widgets import AdminTextareaWidget
from django.core.exceptions import ValidationError
from django.core.validators import URLValidator
from django.utils import six
from taggit.forms import TagField, TagWidget
from taggit.utils import edi... |
# Copyright 2014-2015 ARM Limited
#
# 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 w... |
"""
// TODO: Write tests for retry_async
// TODO: Custom Viewer for Manhwa and Manhua
// TODO: redux integration
// TODO: Drive refresh every 35 minutes
// TODO: Mongo db implementation
TODO: async.run_in_exector for drive uploads.
TODO: site revamp
TODO: httpobject for drive auth
TODO: Add support for multiple sites
"... |
from cwbot.modules.BaseDungeonModule import BaseDungeonModule, eventDbMatch
def killPercent(n):
return int(max(0, min(99, 100*n / 500.0)))
def getTireDamage(n):
return int(round(0.1*n*n + 0.7*n))
UNKNOWN = 0
GUESSED = 1
KNOWN = 2
class BurnbarrelModule(BaseDungeonModule):
"""
A ... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 28 21:09:46 2017
@author: <NAME>
"""
import math
import time
import heapq
import numpy as np
from scipy import optimize
inputLocation = "Sioux Falls network/"
class Zone:
def __init__(self, _tmpIn):
self.zoneId = _tmpIn[0]
self.lat = 0
self.l... |
from collections import OrderedDict
import boto3
import sys
import argparse
def get_fleet_arn(robomaker, default_fleet_name):
rosbot_fleet_found = False
rosbot_fleet_arn = ''
print('Script will check if fleet named ' + default_fleet_name + ' exists.')
print('If found, it will be used for further devel... |
'''Multiple argument dispatching.
This module was inspired on <NAME>'s multimethod module in pypi.
Introduction
------------
Multiple argument dispatch is a technique in which different implementations of
a function can be used depending on the type and number of arguments. This module
provides the ``multifunction`... |
import numpy as np
import cv2
import torch
from skimage.feature import peak_local_max
from simnet.lib import color_stuff
from simnet.lib import camera
from simnet.lib import transform
from simnet.lib.net.post_processing.epnp import optimize_for_9D
from simnet.lib.net.post_processing import epnp
from simnet.lib.net.po... |
import PySimpleGUI as sg
import pyperclip, shutil, zipfile, pyAesCrypt, base64, os, io, re
def base64_d(b):
return base64.b64decode(b.encode('utf-8'))
def rmd(directory):
try:
shutil.rmtree(os.path.join(os.path.abspath(os.path.dirname(__file__)), directory))
except:
pass
def rm(file... |
# Provided under the CC-BY-SA license. Please cite the accompanying paper when using TOP dataset -
# @ARTICLE {
# author = "<NAME> and <NAME> and <NAME> and <NAME> and <NAME>",
# title = "Semantic Parsing for Task Oriented Dialog using Hierarchical Representations",
# journal = "Conference on Empirical M... |
# DYNA MAZE
#
# EXERCISE 8.4
#
# The exploration bonus described above actually changes the estimated values of states and actions. Is this necessary?
# Suppose the bonus k*sqrt(tau) was used not in updates, but solely in action selection. That is, suppose the action
# selected was always that for which Q(St, a) + k*sq... |
#!/usr/bin/env python3
# Test whether a broker handles cleansession and local_cleansession correctly on bridges
#
# Test cases (with settings for broker A (edge). The settings on broker B (core)
# are irrelevant, though you'll need persistence enabled to test, unless you
# can simulate network interruptions.
# Similarl... |
from dataclasses import dataclass, field
import re
from typing import List, Union
from RPA.Windows.keywords import (
ElementNotFound,
keyword,
LibraryContext,
WindowControlError,
)
from RPA.Windows import utils
if utils.is_windows():
import uiautomation as auto
from uiautomation.uiautomation im... |
#!/usr/bin/env python
"""
Project-wide application configuration.
DO NOT STORE SECRETS, PASSWORDS, ETC. IN THIS FILE.
They will be exposed to users. Use environment variables instead.
See get_secrets() below for a fast way to access them.
"""
import logging
import os
from authomatic.providers import oauth2
from aut... |
from PIL import Image, ImageOps
from enum import Enum
import numpy as np
from numpy import random as r
import cv2
import math
from matplotlib import pyplot as plt
import random
import torch
import albumentations
from albumentations import (
HorizontalFlip, IAAPerspective, ShiftScaleRotate, CLAHE, RandomRotate90,
... |
import datetime
from copy import deepcopy
import channels
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.permissions import IsAuthenticated
from backend.settings import r as r
from asgiref.sync import async_to_sync
from django.contrib.contenttypes.models import ContentType
from rest_framewo... |
from contextlib import contextmanager
from io import StringIO
from streamlit.report_thread import REPORT_CONTEXT_ATTR_NAME
from threading import current_thread
import streamlit as st
import sys
from time import sleep
from PIL import Image
import io
import numpy as np
import torch
import matplotlib.pyplot as plt
sys.p... |
# -*- coding: utf-8 -*-
"""
@Time : 2020/1/28 下午7:11
@File : rps.py
@author : pchaos
@license : Copyright(C), pchaos
@Contact : <EMAIL>
"""
import datetime
import pandas as pd
import numpy as np
from abc import ABC, abstractmethod
from abc import ABCMeta
import QUANTAXIS as qa
from .comm import str2date, date2... |
#!/usr/bin/env python3
"""
(C) 2019 <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
Wrappers for NLTK to JSON-NLP output format.
Licensed under the Apache License 2.0, see the file LICENSE for more details.
Brought to you by the NLP-Lab.org (https://nlp-lab.org/)!
"""
name = "nltkjsonnlp"
__version__ = "0.0.1"
i... |
import torch
import torchvision.models as models
from torchvision import transforms as trn
import torch.nn as nn
import numpy as np
from PIL import Image
import os
from tqdm import tqdm
import argparse
import warnings
warnings.filterwarnings('ignore', 'Possibly corrupt EXIF data*')
parser = argparse.Arg... |
# -*- coding: utf-8 -*-
"""
Zoidberg could be use in two different ways:
a) CL:
python zoidberg args
b) python module:
from zoidbderg import Zoidberg
"""
import os
import sys
HERE = os.path.abspath(os.path.dirname(__file__))
sys.path.append('..')
sys.path.append(HERE)
from twisted.internet... |
import urllib
from botocore.vendored import requests
import json
from html.parser import HTMLParser
BASE_API_URL = 'http://www.ebi.ac.uk/proteins/api/'
"""
The lambda_handler receives the request from the Alexa skill, identifies the type of intent and calls the appropriate function
"""
def lambda_handler(event, con... |
from datetime import date, datetime, time, timedelta, timezone
from decimal import Decimal
from enum import Enum
import pytest
import sqlalchemy as S
from dbcsv.marshalling import marshal_object, unmarshal_object
class RGBEnum(Enum):
RED = 1
GREEN = 2
BLUE = 3
me... |
from __future__ import print_function, division
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import torchvision
from torchvision import models, transforms, datasets
import numpy as np
import argparse
import time
import copy
import sys
import os
import analysis
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .mynn import Norm2d
def point_sample(input, point_coords, **kwargs):
"""
A wrapper around :function:`torch.nn.functional.grid_sample` to support 3D point_coords tensors.
Unlike :function:`torch.nn.functional.grid_sample` it assumes `p... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020-2021 TU Wien.
#
# Invenio-Utilities-TUW is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
"""Management commands for drafts."""
import json
import os
import sys
from os.path import basena... |
import os
import random
import time
import traceback
import numpy as np
from mpi4py import MPI
from mpi4py.futures import MPICommExecutor
from sklearn.metrics import mean_squared_error
from csv_modules.csv_writer import write_in_file
from experiment.utils_general import remove_get_dirs
from general_utils.database_uti... |
import inspect
import itertools
import logging
import sys
import os
import gc
from ryu import cfg
from ryu import utils
from ryu.app import wsgi
from ryu.controller.handler import register_instance, get_dependent_services
from ryu.controller.controller import Datapath
from ryu.controller import event
from ryu.controll... |
#!/usr/bin/env python
import logging
l = logging.getLogger("angr.surveyors.slicecutor")
from .surveyor import Surveyor
from ..errors import AngrExitError
from collections import defaultdict
# pylint: disable=W0212,
#
# HappyGraph is just here for testing. Please ignore it!
#
class HappyGraph(object):
def __ini... |
#!/usr/bin/env python
"""
Batch rename tv show episodes
- Episodes should be stored in the following way:
.../Show Name/Season 1/Episode 3
- Episodes must already be in the proper order
- Season Folders should contain 1 number that denotes the season
"""
from dataclasses import dataclass
import os
import arg... |
"""
Helper functions/classes for models.
"""
import re
from django.db import models
from django.db.models.aggregates import Max
from django.template.defaultfilters import slugify
from django.core.exceptions import ValidationError
from django.utils.text import capfirst, get_text_list
from django.utils.translation import... |
import os
import numpy as np
from easyidp.core.objects import ReconsProject, Sensor, Calibration, Photo
def _match_suffix(folder, ext):
"""
find the first file by given suffix, e.g. *.tif
Parameters
----------
folder: str
the path of folder want to find
ext: str | list
str -> e... |
import os
import re
import sys
import zipfile
import logging
import tempfile
from typing import List, Optional
import yara # type: ignore
from karton.core import Config, Karton, Task # type: ignore
from .__version__ import __version__
log = logging.getLogger(__name__)
def normalize_rule_name(match: str) -> str:
... |
########################
#
# Authour: <NAME>
# @: <EMAIL>
#
########################
########################
# Libraries used
from nltk.corpus import stopwords
from nltk.tokenize import sent_tokenize, word_tokenize
# sw contains the list of stopwords
sw = stopwords.words('english')
#the plan is to use wor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.