text stringlengths 3.07k 12.6k |
|---|
import sys
import urequests
import ujson
import time
import gc
from . import coinobject
from . import max7219
from . import helpvar
from . import ticker_worker
from machine import Pin, SPI
import uasyncio as asyncio
import network
wifissid = ''
wifipassword = ''
ssid = 'McMoes_CryptoTicker'
password = ... |
'''
This file contains functions for pruning vgg-like model in layer level
1. prune_conv_layer (vgg: conv layers)
Author: xuhuahuang as intern in YouTu 07/2018
'''
import torch
from torch.autograd import Variable
from torchvision import models
import cv2
cv2.setNumThreads(0) # pytorch issue 1355:... |
"""
Extensions of Python standard functions
"""
# pylint: disable=invalid-name
__all__ = [
"count",
"redirect_stdout",
"FreezableDict",
"cache",
"lazy_import",
"setitems",
"commonsuffix",
"raiseif",
]
import io
import os
import sys
import ctypes
import tempfile
import importlib
from fu... |
# coding=utf-8
# Copyright 2022 GradMax 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 law or ag... |
import unittest
import numpy as np
import numpy.testing as npt
from doatools.estimation.grid import FarField1DSearchGrid, FarField2DSearchGrid
from doatools.utils.math import cartesian
class Test1DGrids(unittest.TestCase):
def check_1d_grid_with_axes(self, grid, axis_expected, axis_names_expected,
... |
import base64
import logging
from cryptojwt.exception import Invalid
from cryptojwt.exception import MissingKey
from cryptojwt.jwt import utc_time_sans_frac
from cryptojwt.utils import as_bytes
from cryptojwt.utils import as_unicode
from cryptojwt.jwt import JWT
from oidcmsg.oidc import AuthnToken
from oidcendpoint ... |
#!/usr/bin/env python3
import argparse
import shutil
from pathlib import Path
from subprocess import run, call, check_call, check_output, TimeoutExpired, CalledProcessError, DEVNULL, PIPE, STDOUT
from datetime import datetime
import toml
from tempfile import TemporaryDirectory
def casename(name: str, i: int) -> str:
... |
# -*-coding:utf-8-*-
"""
业务逻辑
@author <NAME>
"""
import os
import time
from typing import List
import application as app
import args_definition as argsdef
import configurator as configr
import const_config as const
import dao
import utils
from vo import E, ConfigVO, StatusVO
def get_status():
""" 获取程序状态 """
... |
import ioutil
import numpy as np
import pandas as pd
import logging
# NB ERROR:
def check_dtypes(features, valid_dtypes=None):
# Encode dtypes
if valid_dtypes is None:
pass
def preprocessing_report():
# Generate a report describing preprocessing steps
# https://docs.python.org/3/howto/loggin... |
from collections import defaultdict
from anytree import RenderTree, NodeMixin, PreOrderIter
from anytree.exporter import DotExporter
from twee_utils import *
from narrative_reader import BasicVersionedReader, predicates_author
class PassageTree(NodeMixin):
# Static reader version
reader = None
def __init_... |
# Copyright 2021, <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
from abc import ABCMeta, abstractmethod
from base64 import b64decode, b64encode
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Any, Callable, Dict, FrozenSet, Iterable, Iterator, List, Optional, Set, Type
from uuid import UUID, uuid4
from .policies import CoalesceP... |
# Dữ liệu nằm ở E:\VLSP\VLSP-2021\Statistic\annotation
# Trong đó bao gồm các folder là tên file gốc (....conll)
# yêu cầu đầu vào : gồm 2 file: 1 file định dạng conll và 1 fild dữ liệu gốc chưa gán NER
import os
import re
import string
def merge_paragraph_ner(data):
state = True
# print(data)
# print(dat... |
from fastapi import APIRouter, Body, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer, OpenIdConnect
import requests
from app import models
from app.config import settings
# Use Authlib for ORCID OpenID Connect
from starlette.config import Config
from starlette.requests import Request
from sta... |
from typing import Union, List, Dict
from pathlib import Path
from io import StringIO
import pandas as pd
def load_table_from_file(
file_path: Union[str, Path],
sep=r"\s+|,",
**kwargs
) -> pd.DataFrame:
"""
Load data from table file using ``pd.read_table``.
Parameters
-------... |
import argparse
import os
import random
from time import time
import numpy as np
import sklearn.datasets
import sklearn.model_selection
import sklearn.preprocessing
import torch
import torch.backends.cudnn as cudnn
from tqdm import tqdm
import onlinehd
def index2alphabet(index):
'''
Convert index to alphabe... |
import torch.nn as nn
import math
from collections import OrderedDict
import torch.nn.functional as F
import torch
def conv3x3(in_planes, out_planes, stride=1):
# "3x3 convolution with padding"
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
class BasicBlock(nn.... |
'''
Functions for step 2 of ETL
#################################
Completes any data cleaning steps not solved during XML parsing
and readies data for csv export or database bulk upload
'''
import argparse
import pandas as pd
sponsor_col_names = [
'sponsor_ein',
'name',
'address_line_1',
... |
import numpy as np
import os
import subprocess
from sympy.combinatorics import Permutation
from nilabels.tools.aux_methods.sanity_checks import is_valid_permutation
# ---- List utils ----
def lift_list(input_list):
"""
List of nested lists becomes a list with the element exposed in the main list.
:para... |
import protobuf as ext
import struct
import itertools
import socket
import sys
import argparse
import logging
import coordinate
import singleton
logging.basicConfig()
logger = logging.getLogger("base")
logger.setLevel(logging.DEBUG)
class CommunicationError(Exception):
pass
class ParseError(Exception):
pass
@sin... |
#!/usr/bin/torify /usr/bin/python
import Tkinter
import tkFont
import requests
import html2text
import urllib2
class TkDND(object):
def __init__(self, master):
master.tk.eval('package require tkdnd')
self.master = master
self.tk = master.tk
self._subst_format = ('%A', '%a', '%b', '... |
# #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This module ...
__author__ = "<NAME>"
__copyright__ = "Copyright 2019, Sparkie Quadruped Robot"
__credits__ = ["<NAME>", "<NAME>", "<NAME>"]
__version__ = "1.0.0"
__license__ = "MIT"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Development"
"""
# ... |
#!/usr/bin/python3
example_grid = [
[1, 2, 3, 4, 5, 6, 7, 8, 0],
[4, 5, 6, 7, 8, 9, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[5, 6, 7, 8, 9, 0, 1, 2, 3],
[6, 7, 8, 9, 0, 1, 2, 3, 4],
[7, 8, 9, 0, 1, 2, 3, 4, 5],
[8, 9, 0, 1, 2, 3, 4, 5, 6],
[0, 0, ... |
import datetime as dt
import sys as s
from about import appinfo as mtdt
class color:
YELLOW = '\033[93m'
RED = '\033[91m'
BOLD = '\033[1m'
END = '\033[0m'
errcodes = {
"0x000": "INVALID_INPUT",
"0x001": "CANNOT_DIVIDE_BY_ZERO",
"0x002": "FS_ACCESS_DENIED",
"0x003": "APPLICATION_IS_COR... |
# import os
from decimal import Decimal
import pytest
# import shutil
from commonkit.types.library import *
from commonkit.constants import FALSE_VALUES, TRUE_VALUES
COUNT_2 = 2
# Tests
def test_is_bool():
"""Check that runtime boolean validation works as expected."""
for f in FALSE_VALUES:
assert i... |
# Copyright (c) 2017-2018 CRS4
#
# 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, distribut... |
import math
import numpy as np
import numpy.random as rand
from scipy import special
from scipy.misc import logsumexp
import logging
from . import loggers
from .wrappers import exp, log, gammaln
logger = logging.getLogger(__name__)
def sampleCatDist(wts):
"""Draw 0-based index from categorical distribution"""
... |
import logging
from django.contrib.auth import get_user_model
from django.db import IntegrityError
from django.forms import ValidationError
from django.http import Http404
# from django.utils.decorators import method_decorator
from django.utils.translation import ugettext_lazy as _
# from django.views.decorators.cach... |
import numpy as np
import torch
import random
from tqdm import tqdm
import copy
from bridgedata.utils.general_utils import AttrDict
# from bridgedata.data_sets.robonet_dataloader import FilteredRoboNetDataset
from bridgedata.utils.general_utils import Configurable
from bridgedata.data_sets.data_augmentation import get_... |
import datetime
import pytest
from moto import mock_iam
from tests import mock_config
from ec2userkeyd import clients, utils
from ec2userkeyd.methods import restricted_instance_role
@pytest.fixture
def sim_iam():
mock_iam_instance = mock_iam()
mock_iam_instance.start()
# Create a user and role with att... |
import torch
from torch import nn
from maskrcnn_benchmark.layers import ROIAlign
from .utils import cat
class LevelMapper(object):
"""根据FPN论文中的公式计算每个RoI属于哪个FPN feature map level
"""
def __init__(self, k_min, k_max, canonical_scale=224, canonical_level=4, eps=1e-6):
"""
Arguments:
... |
import random
def printeartablero(tableroajedrez):
contador_indice = 0
for tableroajedrez[contador_indice] in tableroajedrez:
print(tableroajedrez[contador_indice])
contador_indice += 1
print("\n") # Salto de linea para los futuros tableros, para que no salgan pegados los unos con los otr... |
#!/usr/bin/python3
# coding=utf-8
import MySQLdb
import argparse
import datetime
import eth_util
def determine_possible_compiler_versions(db, complete_compiler_list):
c = db.cursor()
query = f"""
SELECT hash, code, minCompilerVersion, maxCompilerVersion
FROM contractCode;
"""
c.ex... |
from decimal import Decimal, InvalidOperation
from django.utils.translation import gettext as _
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from .choices import *
from .models import *
from .validators import validate_number_in_board
class CommentSerializer(serialize... |
'''
Author: He,Yifan
Date: 2022-02-16 20:02:10
LastEditors: He,Yifan
LastEditTime: 2022-02-20 22:46:22
'''
from functools import partial
import os
import time
import numpy as np
import yaml
import sys
from pgsyn.gp.estimators import PushEstimator
from pgsyn.gp.genome import GeneSpawner
from pgsyn.knowledge.base impo... |
''' Tests for NWBFile '''
import unittest
import six
import numpy as np
from datetime import datetime
from pynwb import NWBFile, TimeSeries
from pynwb.file import Subject
from pynwb.ecephys import Device
class NWBFileTest(unittest.TestCase):
def setUp(self):
self.start = datetime(2017, 5, 1, 12, 0, 0)
... |
#!/usr/bin/env python
import sys
import json
def print_usage():
print('{} <Path to old test> <Name of the Test> <Fork>'.format(sys.argv[0]))
if len(sys.argv) == 2 and sys.argv[1] == '-h':
print_usage()
sys.exit()
elif len(sys.argv) != 4:
print_usage()
raise Exception('Incorrect number of arguments... |
import os
import keras
import numpy as np
from keras.utils import to_categorical
def read_labels_file(file_path: str) -> np.array:
"""Reads the labels from the csv file and returns it as an array
:param file_path: path to the csv file containing the labels to the files in the dataset
:return: labels as ... |
import pkg_resources
import cppyy
import platform
# Okay, we need to check if someone perhaps did already load the code...
try:
from cppyy.gbl import AliasSampler as AliasSamplerCpp
except ImportError:
# If not, load the code and try again
cppyy.cppdef("""#include "{0}" """.format(pkg_resources.resource_... |
import numpy as np
import cv2
import math
import time
from ardSerial import *
from Py_commander import *
from vision_commander import skin_col_range,getCentroid
def skin_finder2(cap):
'''
Puts a box on the image and asks the user to put their skin in it and press r or l depending on which arm to measu... |
# -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2021-05-28 12:42
from transformers import BertPreTrainedModel
import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import CrossEntropyLoss
import torch.nn.functional as F
import math
from elit.layers.transformers.pt_imports import BertModel
clas... |
#!/usr/bin/env python3
import xarray as xr
import numpy as np
def setup_building(h, w, l, overhang, angle, srfc_height, translation, materials):
roof_height = np.tan(np.deg2rad(angle)) * w/2.
roof_overhang_height = np.tan(np.deg2rad(angle)) * overhang
x=1000
verts = np.empty((20,3))
verts[0:4,:] =... |
"""
This module contains general purpose functions that are used throughout PBjam.
"""
from . import PACKAGEDIR
import os
import numpy as np
from scipy.special import erf
class references():
""" A class for managing references used when running PBjam.
This is inherited by session and star.
Attrib... |
"""
Main game loop
"""
import builtins
from typing import List, Optional, Dict, Any, Union
import the_lockdown_house.maps as maps
from the_lockdown_house.authenticate import login
from the_lockdown_house.commands import parse_command
from the_lockdown_house.maps import Mob, Player
from the_lockdown_house.payments impo... |
#!/usr/bin/env python
# coding=utf-8
"""
TBW
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import unicodedata
from ipapy.compatibility import to_unicode_string
from ipapy.compatibility import unicode_to_hex
from wiktts.lexicon import Lexicon
from wi... |
from flask_login import UserMixin
from datetime import datetime
from app import db, login
from werkzeug.security import generate_password_hash, check_password_hash
import uuid
like = db.Table('like',
db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
db.Column('post_id', db.Integer, db.ForeignKey('po... |
from django.db import models
from django.db.models import Q
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from djmoney.models.fields import MoneyField
from core.models import City, Pharmacy
from drug.utils import unique_slug_generator
from pms... |
import numpy as np
import datetime
import warnings
import logging
import xarray as xr
try:
import h5py
from skimage.util import view_as_windows
except ImportError as imp_err:
warnings.warn(f"Packages required for recreating dataset not installed: {imp_err}")
logger = logging.getLogger(__name__)
def date... |
import csv
import logging
import json
import math
import random
import re
import time
import urllib.request
from pathlib import Path
import sys
import pandas as pd
import get_edgar.common.my_csv as mc
logger = logging.getLogger(__name__)
EDGAR_PREFIX = "https://www.sec.gov/Archives/"
SEC_PREFIX = "https://www.sec.go... |
import json
import logging
import threading
import tekore as tk
import tornado.ioloop
import tornado.web
from lyricsgenius.utils import parse_redirected_url
from requests import HTTPError
from telegram import Bot
from telegram.utils.webhookhandler import WebhookServer
from tornado.web import RequestHandler, url
from ... |
import requests
import bs4
from bs4 import BeautifulSoup
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
import pandas as pd
# If comparing in browser, make sure to clear cookies.
# URL = "https://www.indeed.com/jobs?q=receptionist&l=Omaha%2C+NE"
# request the URL
# page = requ... |
import exponentialIntegrators
from mpi4py import MPI
import numpy as np
import sys
from scipy import integrate,interpolate
class solStruct:
def __init__(self,t,y):
self.t = t
self.y = y
class paraExpIntegrator:
def __init__(self,T,hompartDir,nonlinpartDir,hompartAdj,costIntegrand,costIntegranddq,equationdf,inho... |
#####################################################################
# #
# autocython.py #
# #
# Copyright 2018, <NAME> ... |
"""
File: babygraphics.py
Name:
--------------------------------
SC101 Baby Names Project
Adapted from <NAME>'s Baby Names assignment by
<NAME>.
"""
import tkinter
import babynames
import babygraphicsgui as gui
FILENAMES = [
'data/full/baby-1900.txt', 'data/full/baby-1910.txt',
'data/full/baby-1920.txt', 'da... |
#!/usr/bin/python
import sys
import os
import numpy as np
from scipy.signal import find_peaks
from scipy.constants import pi
import matplotlib.pyplot as plt
d = 10**-9 # FE oxide layer thickness (m)
def SortAndFilterDir(dataArray):
path = dataArray[0]
dataFilter = ['.csv', dataArray[1] if len(dataArray) > 1 ... |
#!/home/wli/env python3
# -*- coding: utf-8 -*-
"""
Title: patch aug
================
Created: 10-31-2019
Python-Version: 3.5
Description:
------------
This module includes the functions for image cropping and adding color noises.
These functions are included in Training_Patch_Pre.py
"""
import tensorflow as tf
i... |
"""
Visualization script. I used this to create the figures in the paper.
WARNING: I haven't tested this in a while. It's possible that some later features I added break things here, but hopefully there should be easy fixes. I'm uploading this in the off chance it might help someone. If you get it to work, let me know... |
from floodsystem.flood import stations_highest_rel_level, stations_level_over_threshold
from floodsystem.geo import stations_by_distance, haversine, stations_within_radius, rivers_with_station, stations_by_river, rivers_by_station_number
from floodsystem.station import MonitoringStation, inconsistent_typical_range_stat... |
from __future__ import division
import itertools as it
import os
import utils as ut
keys = "<KEY> Hs-Mm Hs-Nv Hs-Sp Hs-Sc Hs_uni-Ce_uni Ce-Dm Ce-Mm Ce-Nv Ce-Sp Sp-Dm Sp-Mm Sp-Nv Mm-Dm Dm-Nv Hs-Xl Hs-X2 Hs-X3 Hs-Pf Hs-Tg".split()
def odict(from_sp, to_sp):
"""
Load a dict from file, eg:
{HsProt1: set([CePr... |
from __future__ import print_function, division
### Multiprocessing and parallelization
# See file: PyDomanParallelizer.py
###
#########################################
### Exceptions ###
# Let's cause some errors just for fun, and see what happens:
# # Zero division:
# print(5/0)
# # Accessing non-existent e... |
# -*- coding: utf-8 -*-
import argparse
import json
import os
import re
import subprocess
import time
import tensorflow as tf
import tqdm
from absl import logging
logging.set_verbosity("INFO")
alphabets = "([A-Za-z])"
prefixes = "(Mr|St|Mrs|Ms|Dr)[.]"
suffixes = "(Inc|Ltd|Jr|Sr|Co)"
starters = "(Mr|Mrs|Ms|Dr|He\\s|... |
#!/usr/bin/env python3
import argparse
import subprocess
import requests
import json
import sys
import os
import requests
import uuid
import httpx
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixed, wait_exponential
import urllib3
import urllib3.exceptions
urllib3.disable_warnings(url... |
'''
Project: Predicting movie genres from movie posters
Course: COMPSCI 682 Neural Networks: A Modern Introduction
File: data_manage.py
Description: Manages each movie as an object with its distinct features.
Author: <NAME>
Adapted from: Vleminckx, Benoit. dnn-movie-posters. (2018). Github repository. https://github.... |
import json
from django.contrib.auth import authenticate
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.middleware.csrf import get_token
from django.views.decorators.csrf import csrf_exempt
from django.db.models import Q
from rest_framework import permissions
from rest_framework im... |
#!/usr/bin/python3
"""Slurmctld."""
import json
import logging
from ops.framework import (
EventBase, EventSource, Object, ObjectEvents, StoredState,
)
logger = logging.getLogger()
class MungeKeyAvailableEvent(EventBase):
"""Emitted when the munge key is acquired and saved."""
class RestartSlurmctldEvent... |
## Copyright (c) 2008, <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, distrib... |
# Copyright (c) The PyAMF Project.
# See LICENSE.txt for details.
"""
Meta data and helper functions for setup
"""
import sys
import os.path
import fnmatch
try:
from Cython.Distutils import build_ext
have_cython = True
except ImportError:
from setuptools.command.build_ext import build_ext
have_cyth... |
#!/usr/bin/env python
# Copyright 2013 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.
"""Pretty-prints the histograms.xml file, alphabetizing tags, wrapping text
at 80 chars, enforcing standard attribute ordering, and sta... |
# Copyright (c) 2020 PaddlePaddle 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 app... |
import stix2
import stix2.base
import stix2.custom
import stix2.properties
import stix2generator
import stix2generator.exceptions
import stix2generator.generation.object_generator
_JSON_SIMPLE_TYPE_STIX_PROPERTY_MAP = {
"string": stix2.properties.StringProperty,
"number": stix2.properties.FloatProperty,
"... |
# Copyright 2019 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
# coding:utf-8
from __future__ import absolute_import, unicode_literals
from collections import OrderedDict
import graphene
from graphene.types.objecttype import ObjectTypeOptions
from graphql_relay.node.node import from_global_id
from sqlalchemy.exc import SQLAlchemyError
from .types import SQLAlchemyObjectTypes, S... |
"""
Core eval alignment algorithms.
"""
from functools import partial, wraps
from typing import Dict, Optional, Sequence, Tuple, Type, Union
import warnings
import numpy as np
from pandas._typing import FrameOrSeries
from pandas.errors import PerformanceWarning
from pandas.core.dtypes.generic import ABCDataFrame, A... |
"""Support gathering system information of hosts which are running glances."""
from homeassistant.components.sensor import SensorEntity
from homeassistant.const import CONF_NAME, STATE_UNAVAILABLE
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .const ... |
# Copyright 2020-2022 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... |
import argparse
from utils import process_config
def get_eval_config():
parser = argparse.ArgumentParser("Visual Transformer Evaluation")
# basic config
parser.add_argument("--n-gpu", type=int, default=1, help="number of gpus to use")
parser.add_argument("--model-arch", type=str, default="b16", help=... |
#!/usr/bin/python
# Copyright: (c) 2020, <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: bgp_router
short_des... |
import csv
import datetime
import os
from io import BytesIO, StringIO
from flask import Blueprint, abort
from flask import current_app as app
from flask import (
redirect,
render_template,
render_template_string,
request,
send_file,
url_for,
)
admin = Blueprint("admin", __name__)
# isort:impo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Written by <NAME> and CBIG under MIT license:
https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md
"""
import os
import time
import random
import argparse
import numpy as np
from pathlib import PurePath
from keras import backend as K
from keras.optimizers impo... |
import pygame
pygame.init()
def line(winh,winw):
for j in range(0,winw,int(winh/3)):
pygame.draw.line(win,(0,0,0),[0,j],[300,j],1)
for i in range(0, winh, int(winh / 3)):
pygame.draw.line(win,(0,0,0),[i,0],[i,300],1)
def drawo(x,y):
x1=x-int(x%100)
y1=y-int(y%100)
cx=x1+5... |
import PySimpleGUIQt as g
from charlagui import Parser
import os, threading, logging, subprocess
from glob import iglob
import ntpath
import psutil
g.SetOptions(text_color='#545454', background_color='#f0f0f0', text_element_background_color='#f0f0f0', input_elements_background_color='#dbdbdb',
input_text_... |
#!/usr/bin/python
#
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
#
# Pyserini: Reproducible IR research with sparse and dense representations
#
# 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... |
import os
import multiprocessing
import sys
import threading
import tempfile
import time
import pytest
import prefect
from prefect.utilities.configuration import set_temporary_config
from prefect.utilities.executors import (
timeout_handler,
tail_recursive,
RecursiveCall,
)
def test_timeout_handler_time... |
'''
Function:
微博表情包爬取
Author:
Charles
微信公众号:
Charles的皮卡丘
'''
import os
import time
import random
import argparse
import requests
import prettytable
from tqdm import tqdm
from lxml import etree
from DecryptLogin import login
from fake_useragent import UserAgent
'''命令行参数解析'''
def parseArgs():
parser = argparse.Argu... |
#!/usr/bin/env python
from __future__ import print_function
"""
This script will use PyPI to identify a release of a package, and then search
through github to get a count of all of the issues and PRs closed/merged since
that release.
Usage:
python gh_issuereport.py astropy/astropy astropy/0.3
Note that it will prom... |
import os
import sys
import bcrypt
import sqlite3
import time
import random
from pathlib import Path
from sqlalchemy.orm import sessionmaker
from sqlalchemy import exc
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from base64 import b64encode, b64decode
from . import misc
from .models impor... |
import gc
import http.client
import os
import sys
import time
from enum import Enum
import PixivBrowserFactory
import PixivConstant
import PixivHelper
import PixivImageHandler
import PixivImage
class SearchType(Enum):
LIST_ONLY = 0
DOWNLOAD_ALL = 1
WEB_REPRINT_ARCHIVE = 2
def process_image(
image,
... |
import sys
import time
import os
import traceback
from js9 import j
WIPE=False # wipe all drives during cleanup
WIPE_KEY=True # wipe ssh key used for connecting to the VM
SHUTDOWN=False # shutdown host at cleanup
SHUTDOWN_VM=False # send shutdown action after VM was confirmed up and running
MAX_RETRIES = 10 #... |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
import collections
import pytest
try:
import numpy as np
except ImportError:
np, NumSysLin, NumSysLog = [None]*3
else:
from ..equilibria import EqSystem, NumSysLin, NumSysLog
from .ammonical_cupric_solution impo... |
import tiledb
import pandas as pd
from backend.wmg.data.ontology_labels import ontology_term_label, gene_term_label
from typing import Dict, List, Iterable, Set
import json
from backend.wmg.data.snapshot import (
CELL_TYPE_ORDERINGS_FILENAME,
EXPRESSION_SUMMARY_CUBE_NAME,
PRIMARY_FILTER_DIMENSIONS_FILENAM... |
#
# 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
# ... |
""" pandaspyomo: read data from coopr.pyomo models to pandas DataFrames
Pyomo is a GAMS-like model description language for mathematical
optimization problems. This module provides functions to read data from
Pyomo model instances and result objects. Use list_entities to get a list
of all entities (sets, params, vari... |
"""Define patches used for androidtv tests."""
from unittest.mock import mock_open, patch
from androidtv.constants import CMD_DEVICE_PROPERTIES, CMD_MAC_ETH0, CMD_MAC_WLAN0
KEY_PYTHON = "python"
KEY_SERVER = "server"
ADB_DEVICE_TCP_ASYNC_FAKE = "AdbDeviceTcpAsyncFake"
DEVICE_ASYNC_FAKE = "DeviceAsyncFake"
PROPS_DEV... |
# Software License Agreement (BSD License)
#
# Copyright (c) 2012, <NAME>, Inc.
# 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 copyri... |
#!/usr/bin/python3.9
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 LinYulong. All Rights Reserved
#
# @Time : 2021/10/27
# @Author : LinYulong
# @Descriptor:
# 参考
# https://www.cnblogs.com/listenfwind/p/11310924.html
# https://zhuanlan.zhihu.com/p/266880465?ivk_sa=1024320u
import pandas
import pandas as pd
from ... |
import os
import numpy as np
from experiment_src.base import GoalEnv
from gym.wrappers import TimeLimit
import gym
from gym.envs.robotics import utils
class Reach(GoalEnv):
TARGET_SIZE = None
ARENA_SPACE_LOW = None
ARENA_SPACE_HIGH = None
TARGET_DIM = None # The current location in ref to target is skil... |
from collections import Sequence
import numpy as np
import torch
import torch.nn as nn
from torch.nn import functional as F
from tqdm import tqdm
from pdb import set_trace as st
nnpara =False
class _BaseWrapper(object):
def __init__(self, model, layer):
super(_BaseWrapper, self).__init__()
self.d... |
import pytest
from offspect.cache.file import *
import tempfile
from pathlib import Path
import datetime
def test_cachefile_creation(cachefile0, cachefile1):
for cache in [cachefile0, cachefile1]:
cachefile, settings = cache
assert cachefile.exists()
cf = CacheFile(cachefile)
asser... |
# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
import os
from textw... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.