text stringlengths 3.07k 12.6k |
|---|
import tweepy
from tweepy.api import API
import json
import requests
import logging
import time
import random
import jokes
import Wallpaper
import pyjokes
from dotenv import load_dotenv
import os
load_dotenv()
consumer_key = os.getenv('consumer_key')
consumer_secret_key = os.getenv('consumer_secret'... |
from __future__ import print_function
import os
import random
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
from PIL import Image
from torch.autograd i... |
import mock
import pytest
from flexmock import flexmock
from os.path import join, dirname
from sportsipy import utils
from sportsipy.ncaaf.conferences import Conference, Conferences
YEAR = 2018
def read_file(filename):
filepath = join(dirname(__file__), 'ncaaf', filename)
return open(filepath, 'r', encoding... |
from django.http import HttpRequest, HttpResponse, response
from django.shortcuts import render, redirect
from .models import Alarm, User
from post.models import Post, Comment
from .forms import SignupForm
from django.core.paginator import Paginator
from django.contrib.auth import login as auth_login
from django.contri... |
# -*- coding:utf-8 -*-
import os
import mxnet as mx
from mxnet.gluon import nn
def _add_conv(out, channels=1, kernel=1, stride=1, pad=0, num_group=1, activation=True):
out.add(nn.Conv2D(channels, kernel, stride, pad, groups=num_group, use_bias=False))
out.add(nn.BatchNorm(scale=True))
if activation:
... |
from os.path import abspath, dirname, join
import sys
sys.path.insert(0, ".")
from probelib.io.fasta import read_fa
from probelib.io.fastq import write_fq, read_fq, fq2fa
from probelib.align.block import read_align_blocks
HERE = dirname(abspath(__file__))
fa_path = join(HERE, "data/lib.fa")
def test_read_fa():
f... |
from datetime import timezone
from entities import Sale
from logging import Logger
from decimal import Decimal
class Analyzer:
def __init__(self, **kwargs):
self.logger = Logger('Analyzer Logger', 1)
def handle_sale(self, sale):
pass
def analyze(self):
pass
class StarsChartAnaly... |
from app import app
from flask import render_template, request, send_file, redirect, Blueprint, url_for
from io import BytesIO
from Generator.generate import csv_laden, generate_mvd_from_array
from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED
import time
import requests
import base64
import pandas as pd
im... |
# -*- coding: utf-8 -*-
"""Parser for the Sleuthkit (TSK) bodyfile or mactime format.
The format specifications can be read here:
http://wiki.sleuthkit.org/index.php?title=Body_file
"""
import re
from plaso.events import time_events
from plaso.lib import eventdata
from plaso.parsers import manager
from plaso.parse... |
"""Mixture model for collaborative filtering"""
from typing import NamedTuple, Tuple
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.patches import Circle, Arc
class GaussianMixture(NamedTuple):
"""Tuple holding a gaussian mixture"""
mu: np.ndarray # (K, d) array - each row correspond... |
# pylint: disable=R0912,W0603
import os
import pprint
import shutil
import sys
DEBUG = False
try:
from django.conf import settings
try:
from django.core.exceptions import ImproperlyConfigured
DEBUG = settings.DEBUG
except ImproperlyConfigured:
pass
except ImportError:
pass
... |
# Helpers to resolve images when we don't have an image service
import email.utils
import hashlib
import json
import logging
import os
import re
import shutil
import urllib.request
from oslo_concurrency import processutils
from shakenfist import config
LOG = logging.getLogger(__file__)
LOG.setLevel(logging.DEBUG)
... |
"""Check Python docstrings validate as reStructuredText (RST).
This is a plugin for the tool flake8 tool for checking Python
source code.
"""
import ast
import restructuredtext_lint as rst_lint
__version__ = "0.2.3"
rst_prefix = "RST"
rst_fail_load = 900
# rst_fail_parse = 901
# rst_fail_all = 902
rst_fail_lint =... |
import os
from .base import TkDevice, SingletonMeta
from .base import PreciseMockTriggerPin, PreciseMockFactory, PreciseMockChargingPin
from gpiozero import Device
from gpiozero.pins.mock import MockPWMPin
from PIL import ImageEnhance, Image, ImageTk
from sounddevice import play, stop
import numpy
import scipy.signal
... |
# -*- coding: utf-8 -*-
#
# Author: <NAME>, Finland 2016-2018
#
# This file is part of Kunquat.
#
# CC0 1.0 Universal, http://creativecommons.org/publicdomain/zero/1.0/
#
# To the extent possible under law, Kunquat Affirmers have waived all
# copyright and related or neighboring rights to Kunquat.
#
import re
from k... |
# Copyright (c) 2021 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, ... |
import sys
import json
from typing import List, Dict
from relogic.logickit.scripts.squad20_eval import normalize_answer, compute_exact, compute_f1
from itertools import groupby
import argparse
import operator
def calculate_score(gold_answer_list: List, pred_answer_list: List):
if len(gold_answer_list) == 0:
if ... |
#
# datasets.py
#
from os.path import join, exists
from os import mkdir
from dataclasses import dataclass
import shutil
import warnings
from typing import Any, Iterator, List, Literal, Optional, Union
from glob import glob
import hashlib
from pathlib import Path
import json
import pandas as pd
from . import tables
... |
DEBUG = True
class User(object):
def __init__(self, name, email):
self.name = name
self.email = email
self.books = {}
self.rating = None
if DEBUG:
print("USER: {0}".format(self.__repr__()))
def get_email(self):
return self.email
def change_emai... |
# We can use any model timm models or torchvision models.
# Model should have AdaptiveAvgPool2d layer and then Linear Layer
# We will remove the Linear Layer and create a new Linear Layer with num_classes
import timm
import torchvision
import torch.nn as nn
__all__ = ["create_timm_model", "create_torchvision_model", ... |
from __future__ import annotations
from typing import Any, Callable, Iterable, Optional, Tuple, Union
import regex
from ._escaping import named_escape_inverse
from .exception import KDLEncodeTypeError
from .structure import Document, Node
IdentifierFormatter = Callable[[str], str]
ValueEncoderResult = Union[None, ... |
import os
import inspect
from getpass import getuser
import numpy as np
import pandas as pd
from .shared_utils.util import safe_symlink
class GenotypingManager:
def __init__(self, genotyping_spec_df, temp_dir):
self.genotyping_spec_df = genotyping_spec_df
self.temp_dir = temp_dir
sel... |
#!/usr/bin/env python
import os
import sys
import glob
import rospy
import re
import json
import cv2
import threading
import numpy as np
from cv_bridge import CvBridge
from sensor_msgs import msg as smsg
from geometry_msgs import msg as gmsg
from aist_depth_filter import DepthFilterClient
from tf import TransformBroad... |
import pytest
from graphapi.tests.utils import populate_db
from opencivicdata.core.models import Person
from opencivicdata.legislative.models import VoteEvent
@pytest.mark.django_db
def setup():
populate_db()
BILLS_QUERY_COUNT = 9
ALASKA_BILLS = 12
@pytest.mark.django_db
def test_bills_view_basics(client, dja... |
"""
Apply QuickSight Group/DataSet Permissions:
a. Get Manifest file from S3 containing QS Group Permissions for DataSets.
b. Update permissions based on manifest
Sample Asset Governance Manifest File:
{
"assets":[
{
"name": "dataset_example_1",
"category":"dataset",
"name... |
import os
import re
import glob
import csv
import subprocess
import tqdm
from datetime import datetime, timedelta, timezone
def get_date_str():
return datetime.now(timezone(timedelta(hours=+9), "JST")).strftime("%Y-%m-%d-%H-%M-%S")
def read_result(filename):
r_solved= re.compile(r"solved=(\d+)")
r_soc = r... |
''' Provides Python helper function to read Waymo Open Dataset dataset.
Author: <NAME>
Date: 2020
'''
import numpy as np
from pathlib import Path
import pickle
import gzip
import os
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, '../u... |
# A predator-prey model of mice and hawks
import os,sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..')) # 'rules' module
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..'))
from pram.data import GroupSizeProbe, ProbeMsgMode
from pram.entity import Group, GroupQry, GroupSplitSpec, S... |
r"""Mean Deviation Similarity Index (MDSI)
This module implements the MDSI in PyTorch.
Credits:
Inspired by the [official implementation](https://www.mathworks.com/matlabcentral/fileexchange/59809-mdsi-ref-dist-combmethod)
References:
[1] Mean Deviation Similarity Index:
Efficient and Reliable Full-Refer... |
import collections.abc
import functools
import teek
from teek._widgets.base import Widget, ChildMixin
from teek._structures import CgetConfigureConfigDict
# you can also make a list of canvas items instead of tagging, but there are
# things that are much easier with good support for tags, like bbox of multiple
# can... |
# 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, ... |
#!/usr/bin/env python3
'''
cca_command.py
Copyright 2012-2020 Codinuum Software Lab <https://codinuum.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/l... |
import csv
import re
import pandas as pd
from os.path import join, exists
from os import mkdir
from shutil import rmtree
from os import remove as remove_file
from sys import stdout
import zipfile
import ntpath
from .. enums import POSSIBLE_INPUTS, POSSIBLE_COMMANDS, INPUT_DEFAULTS, PATH_TO_STORAGE
from .. sys_functi... |
import os
import numpy as np
import tensorflow as tf
import keras
from keras.layers import Dense, Conv2D, BatchNormalization, Activation
from keras.layers import AveragePooling2D, Input, Flatten
from keras.regularizers import l2
from keras.models import Model
from ares.model import ClassifierWithLogits
from ares.utils... |
#!/usr/bin/env pybricks-micropython
"""
Example LEGO® MINDSTORMS® EV3 Elephant Program
----------------------------------------------
This program requires LEGO® EV3 MicroPython v2.0.
Download: https://education.lego.com/en-us/support/mindstorms-ev3/python-for-ev3
Building instructions can be found at:
https://educa... |
import time
from threading import Thread
import msgpack
import zmq
from netifaces import interfaces, ifaddresses, AF_INET
ALIVE_TOPIC = "_alive"
class Subscriber:
def __init__(self, ip, port, subjects):
"""
Creates a Subscriber wrapping a zmq.SUB socket listening to the given subjects
Ar... |
from __future__ import unicode_literals, print_function, division
import sys
import os
import uuid
import shutil
import zmq
import unittest
import xmlrunner
PY2 = sys.version_info.major == 2
if PY2:
str = unicode
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parent_di... |
# Copyright 2011 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... |
import sys
import pygame
pygame.init()
display = pygame.display.set_mode((300, 300))
pygame.display.set_caption("Tic Tac Toe")
board = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
def message(string, string2):
msg = pygame.font.SysFont(None, 20).render(string, True, (255, 0, 0))
msg2 = pygame.font.SysFo... |
import numpy
import six
from clpy import core
def sum(a, axis=None, dtype=None, out=None, keepdims=False):
"""Returns the sum of an array along given axes.
Args:
a (clpy.ndarray): Array to take sum.
axis (int or sequence of ints): Axes along which the sum is taken.
dtype: Data type s... |
import re
ncr_replacements = {
0x00: 0xFFFD,
0x0D: 0x000D,
0x80: 0x20AC,
0x81: 0x0081,
0x81: 0x0081,
0x82: 0x201A,
0x83: 0x0192,
0x84: 0x201E,
0x85: 0x2026,
0x86: 0x2020,
0x87: 0x2021,
0x88: 0x02C6,
0x89: 0x2030,
0x8A: 0x0160,
0x8B: 0x2039,
0x8C: 0x0152,... |
# Copyright (c) 2017 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
from pprint import pformat
from collections import defaultdict as ddict
from numbers import Number
import itertools
from collections.abc import Mapping
class _Vividict(dict... |
# coding:utf-8
from threading import Thread
import wx
import HostOps
import FileType
from transport import SSHExecuteError
from common import CmdID, PostEvent, my_EVT_COMMAND_EVENT, MessageBox
from Dialogs import DlgConnect
from CtrlWnd import myToolBar
from FileListWnd import FileListWnd
from TaskListWnd import TaskL... |
from __future__ import print_function
import os
import pandas as pd
from srrTomat0 import SRR_SUBPATH, FASTQ_SUBPATH, STAR_ALIGNMENT_SUBPATH, HTSEQ_ALIGNMENT_SUBPATH
from srrTomat0.processor.htseq_count import htseq_count_aligned
from srrTomat0.processor.matrix import pileup_raw_counts, normalize_matrix_to_fpkm, nor... |
from maya import mel
from maya import cmds
commandDict = {}
###################
# General Editors #
###################
def contentBrowserWindow():
cmds.ContentBrowserWindow()
def hypergraphHierarchyWindow():
cmds.HypergraphHierarchyWindow()
def hypergraphDGWindow():
cmds.HypergraphDGWindow()
de... |
# from ctypes import *
# lib = windll.mylib
# api = {
# # func name restype argtypes
# 'adder' : (c_int, [c_int, c_int]),
# 'subtractor': (c_float, [c_float, c_float]),
# 'factorial' : (c_int, [c_int]),
# 'hello' : (c_char_p, [c_char_p]),
# 'mystring' : (c_char_p, []),
# }
# for fun... |
import torch
import torch.nn as nn
import numpy as np
# pylint: disable=E1101
def hidden_init(layer):
"""Calculates the initialization parameters for the hidden layers
"""
fan_in = layer.weight.data.size()[0]
lim = 1. / np.sqrt(fan_in)
return (-lim, lim)
class Actor(nn.Module):
"""Actor (Pol... |
#!/usr/bin/env python
import sys,re,time,argparse
from multiprocessing import cpu_count,Pool
def main(args):
sys.stdout.write("Start analysis: " + time.strftime("%a,%d %b %Y %H:%M:%S") + "\n")
sys.stdout.flush()
gpd_file = args.output
p = Pool(processes=args.cpu)
csize = 1000
results = p.imap(func=convert,iterab... |
import os
import sys
import dask.array as da
import dask.dataframe as dd
import joblib
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from dask.distributed import Client
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
m... |
from unittest.mock import patch, call
import pytest
from psycopg2._psycopg import TimestampFromTicks
from csgo_analysis.ingestion.models import Player
@pytest.fixture
def player_info():
player_info = {
13: {
Player._GAME_ID: 1,
Player._TEAM_L_ID: 1,
Player._XUID: '7656... |
'''
This model.py python file is part of ReBack, licensed under the CC0 1.0 Universal.
Details of the license can be found in the LICENSE file.
The current version of the ReBack can be always found at https://github.com/joydeba/BackportingPR
'''
from Utils import load_dict_file, mini_batches, write_file
from padding i... |
"""TRUNAJOD lexico semantic norms module.
Lexico-Semantic norms do also require external knowledge to be computed. We compute
the following lexico-semantic variables:
* Arousal
* Concreteness
* Context Availability
* Familiarity
* Imageability
* Valence
We provide two downloadable models of these variables, which co... |
from django.contrib.auth.models import Permission
from django.db import models
from django.utils.translation import gettext_lazy as _
from .settings import MODEL_TREE, TREE_ITEMS_ALIASES
class CharFieldNullable(models.CharField):
"""We use custom char field to put nulls in SiteTreeItem 'alias' field.
That al... |
import collections
import datetime
import numbers
import statistics
import tempfile
import zipfile
from bottle import request, response, route, jinja2_template as template
from sqlalchemy import sql
import config
import web.db_schema as db_schema
def _imgs(trackrel):
return [p.relative_to(config.BASEDIR)
... |
import sys
import random
import argparse
import numpy as np
import sys
import os
import gc
import utils
from scipy.io import loadmat
from scipy import spatial
import meshio
from plyfile import PlyData
"""
Generate training data in the form of points for meshes in local neighborhoods.
"""
sys.setrecursionlimit(1000... |
'''
Copyright (c) 2013 by JustAMan at GitHub
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, merge, publish, dist... |
# This extension demonstrates some advanced features of the Python ISAPI
# framework.
# We demonstrate:
# * Reloading your Python module without shutting down IIS (eg, when your
# .py implementation file changes.)
# * Custom command-line handling - both additional options and commands.
# * Using a query string ... |
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.contrib.sessions.models import Session
from django.db import models
from django.db.models import Q
from django.db.models.signals import post_save
from... |
# coding=utf-8
# Author: SafetyCulture
# Copyright: © SafetyCulture 2016
import time
import sys
try:
from modules.exporters import export_audit_pdf_word, export_audit_json, export_audit_pandas, export_audit_csv, \
export_actions
from modules.global_variables import *
from modules.last_successful im... |
# Copyright 2016 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
"""Utilities for interacting with the Machine Provider catalog."""
import datetime
import json
import logging
from google.appengine.ext import n... |
#!/usr/bin/env python3
#
# Arm SCP/MCP Software
# Copyright (c) 2015-2021, Arm Limited and Contributors. All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
#
import check_copyright
import check_doc
import check_spacing
import check_tabs
import subprocess
import sys
import os
def banner(text):
columns... |
import pytest
from adam import PropagationParams, OpmParams
from adam.batch_propagation_results import ApsResults, MonteCarloResults
class TestAdamProcessingService:
def test_submit_batch(self, service):
keplerian_elements = {
'semi_major_axis_km': 448793612,
'eccentricity': 0.1,... |
from __future__ import absolute_import
from __future__ import unicode_literals
import json
import logging
import six
from docker.utils import split_command
from docker.utils.ports import split_port
from .cli.errors import UserError
from .config.serialize import denormalize_config
from .network import get_network_def... |
import json
import os
import platform
import random
import sys
import aiohttp
import discord
import yaml
from discord.ext import commands
if not os.path.isfile("config.yaml"):
sys.exit("'config.yaml' not found! Please add it and try again.")
else:
with open("config.yaml") as file:
config = yaml.load(f... |
import datetime
import random
from django.contrib.auth.models import User
from delab.corpus.download_conversations import save_tree_to_db
from delab.TwConversationTree import TreeNode
from delab.models import LANGUAGE, Tweet, TwTopic, SimpleRequest, PLATFORM, TWCandidateIntolerance, TWIntoleranceRating
from delab.nce... |
"""
Bablu
Combine portrait images and indoor dataset with augmentation.
Copyright (c) 2019 <NAME>.
Licensed under the MIT License (see LICENSE for details)
dataset: http://web.mit.edu/torralba/www/indoor.html
"""
import random
import scipy.ndimage
import skimage.color
import cv2
import numpy as np
from skimage.tran... |
# -*- coding: utf-8 -*-
"""media library"""
import itertools
import json
import os.path
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse, Http404
from django.shortcuts import render, get_... |
import numpy as np
import pickle
import matplotlib.pyplot as plt
import seaborn as sns
import os
import pandas as pd
from tqdm import trange, tqdm
from sklearn.metrics import accuracy_score
from activestateexploration.simple_lfm import MinimalLocalForwardModel
from abstractclasses.AbstractNeighborhoodPattern import Cro... |
import requests
import urllib3
import json
import sys
PLCnext = requests.Session()
DO1 = False
DO2 = False
DO3 = False
DO4 = False
DO5 = False
DO6 = False
DO7 = False
DO8 = False
DO9 = False
DO10 = False
DO11 = False
DO12 = False
DO13 = False
DO14 = False
DO15 = False
DO16 = False
def Pulll... |
#!/usr/bin/env python
# coding: utf-8
# # 1. Create V, C
# In[1]:
import nltk
import numpy as np
from nltk.corpus import brown, stopwords
from nltk.tokenize import word_tokenize
from math import log
# In[2]:
nltk.download('brown')
nltk.download('stopwords')
nltk.download('punkt')
# In[3]:
words = ' '.join(b... |
import time
from typing import Callable
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
import webdriver
from log import logger
from utils import fail
NULL = '请选择'
browser = webdriver.get()
def must_oper... |
#create embedded input sequence with elmo embedder
from keras.preprocessing import text, sequence
from keras.preprocessing.text import Tokenizer
from keras.utils import to_categorical
from allennlp.commands.elmo import ElmoEmbedder
from keras.preprocessing import text, sequence
from pathlib import Path
import torch
im... |
import struct
from typing import Union
import pytest
from hypothesis import given
from hypothesis import strategies as st
from . import _array_module as xp
from . import dtype_helpers as dh
from . import hypothesis_helpers as hh
from . import pytest_helpers as ph
from . import shape_helpers as sh
from . import xps
fr... |
"""A small set of simple vector manipulation/calculation functions.
"""
import math
from functools import reduce
from random_geometry_points.validation import check_vector, check_geometry_parameter, \
check_direction_vector, check_quaternion
def calc_magnitude(vec):
"""Calculate the magnitude of a 3D vector.
... |
# Taken from http://code.activestate.com/recipes/578353-code-to-source-and-back/
import __future__
import ast
import inspect
import re
from types import CodeType as code
PyCF_MASK = sum(v for k, v in vars(__future__).items() if k.startswith("CO_FUTURE"))
class SourceCodeNotFoundError(Exception):
pass
def unco... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 TH<NAME>, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in complianc... |
#!/usr/bin/env python
#
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Process Android resource directories to generate .resources.zip and R.txt
files."""
import argparse
import os
import shutil
i... |
from tensorflow.python.framework import ops, smart_cond
from tensorflow.python.keras import backend as K
from tensorflow.python.keras.losses import LossFunctionWrapper
from tensorflow.python.keras.utils import losses_utils
from tensorflow.python.ops import array_ops, math_ops
from tensorflow.python.util import dispatch... |
#argya.spaceimpact@
#Space Impact
#Image for Impact
#Image for Player
#Image for background
#Python on windows
import turtle
import os
import math
import random
import winsound
import sys
#Set up the screen
wn = turtle.Screen()
wn.bgcolor("blue")
wn.title("Space Impact")
wn.bgpic("space_impact_bac... |
"""
Compressed Barcode Encoding Methods
===================================
.. currentmodule:: sctools
This module defines several classes to encode DNA sequences in memory-efficient forms, using 2 bits
to encode bases of a 4-letter DNA alphabet (ACGT) or 3 bits to encode a 5-letter DNA alphabet
that includes the amb... |
from . import AUTO_GET_PARTICIPANTS, AUTO_GET_MATCHES
from .helpers import get_connection, assert_or_raise
from .tournament import Tournament, TournamentType
class User:
""" Representation of a Challonge user
Main entry point for using the async challonge library.
"""
def __init__(self, username: s... |
"""
Run code in background indefinitely
This module allows you to keep running a script in the background indefinitely.
A great usage of this is fetching data in background and sending notifications with :py:mod:`notifications`. You can also run a server or a Discord bot for example.
Note: Because of privacy, apps ca... |
import os
import cv2
import time
import tensornets as nets
import tensorflow as tf
import random
from skimage import color, transform
from keras.models import Model
from keras.layers import Input, LSTM
from keras.layers import Dense, TimeDistributed
from keras.callbacks import ModelCheckpoint
from sklearn.model_selecti... |
'''
USE yolov3 as the preprocess of hrnet model
USE sgfilter algorithm smooth the joints coordinate
DRAWBACK: 无法处理好快速移动的物体(cannot handle fast motion person)
'''
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import pprint
impo... |
import numpy as np
import re
import xml.etree.ElementTree
import logging
logger = logging.getLogger(__name__)
def readIowaSurfaces(fname):
"""Read the surfaces .xml file generated from OCTExplorer
Params:
fname - full path to the .xml file
Returns:
{'scan_size' - {'x','y','z'} - scan_size in v... |
"""Utilities for real-time data augmentation on image data.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import threading
import numpy as np
from keras_preprocessing import get_keras_submodule
try:
IteratorType = get_keras_submodule('u... |
import json
import pathlib
import pickle
import shutil
from collections import defaultdict
from multiprocessing.pool import Pool
from typing import Dict, List, Optional, Set, Tuple
import click
import pandas as pd
import requests
import zstandard
from tqdm import trange
from tqdm.auto import tqdm
from src.helpers imp... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 31 15:47:34 2019
@author: Mason
''' Code for the MAIN UI
'''
"""
import workout_thread as wt
import jump_classes as jc
import widget_classes as wc
import gui_manageevents as gui_me; from gui_me_code import setup_me
import gui_addspeed as gui_as; f... |
import torch
from torch import nn
import torchshard as ts
def get_loss(name):
if name == "cosface":
return CosFace()
elif name == "arcface":
return ArcFace()
elif name == "magface":
return MagFace()
elif name == "magcos":
return MagCos()
else:
raise ValueErr... |
import sys
from pypy.rlib.objectmodel import Symbolic, ComputedIntSymbolic
from pypy.rlib.objectmodel import CDefinedIntSymbolic
from pypy.rlib.rarithmetic import r_longlong, isinf, isnan
from pypy.rpython.lltypesystem.lltype import *
from pypy.rpython.lltypesystem import rffi
from pypy.rpython.lltypesystem.llmemory im... |
from __future__ import unicode_literals
from ..operators import IOperator, Operator
from decimal import Decimal
from gocept.reference.collection import InstrumentedSet
from icemac.addressbook.utils import create_and_add
from zope.container.folder import Folder
import pytest
import zope.component
import zope.component.... |
# NOTE: INSPIRED IN https://github.com/dbt-labs/dbt-core/blob/43edc887f97e359b02b6317a9f91898d3d66652b/core/dbt/lib.py
import six
from datetime import datetime
from dataclasses import dataclass
from uuid import uuid4
from typing import List, Tuple, Union
import dbt.version
import dbt.semver
import dbt.flags as flags
i... |
'''
Created on 8 mars 2022
@author: slinux
'''
from wxRavenGUI.application.pluginsframework import *
'''
This is a tentative of 2 side job with a transaction in between.
ClientRequest is the client side
ServerProcess is the server side
'''
#
#
# Client Side of the request
#
#
clas... |
import argparse
import datetime
import os
import sys
shape_count = {
'airplane': {
'train': 2832,
'test': 808,
'n_part': 4
},
'chair': {
'train': 4612,
'test': 1317,
'n_part': 8
},
'table': {
'train': 5876,
'test': 1679,
'n_part': 3
},
'animal': {
... |
import io
import json
import os
from http.cookies import SimpleCookie
from oidcop.configure import ASConfiguration
import pytest
import responses
import yaml
from cryptojwt import JWT
from cryptojwt import KeyJar
from cryptojwt.jwt import utc_time_sans_frac
from oidcmsg.oauth2 import AuthorizationRequest
from oidcmsg.... |
# coding=utf-8
# Copyright 2019 The Tensor2Robot Authors.
#
# 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 ... |
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import re
import os
from train_until import *
import spacy
import tensorflow as tf
from dnc.memory import KMemory
nlp = spacy.load('en')
anno_file = './dataset/MSR_en.csv'
dict_file = './dataset/... |
import matplotlib.pylab as plt
import numpy as np
import cv2
# montage of images
class Montage(object):
"""
example:
plt.figure()
montage = Montage((2500, 1600), (2, 3))
plt.imshow(montage.montage(list_of_images))
plt.grid(False)
plt.tight_layout(0)
plt.axis('off')
"""
def __... |
import argparse
import os
import torch
import torch.nn as nn
import torchvision.transforms as transforms
from torchvision.utils import save_image
from torchvision import datasets
class Generator(nn.Module):
def __init__(self, latent_dim):
super(Generator, self).__init__()
# Construct generator. ... |
import numpy as np
from latent_dialog.enc2dec.decoders import TEACH_FORCE, GEN, DecoderRNN, GEN_VALID
from collections import Counter
class UniquenessSentMetric(object):
"""Metric that evaluates the number of unique sentences."""
def __init__(self):
self.seen = set()
self.all_sents = []
d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.