text stringlengths 3.07k 22.1k |
|---|
from typing import Optional, List, Tuple
import pygame
from . import item
from . import Tooltip
from .. import binds
from .. import constants as c
from .. import setup
class SlotTaken(Exception): pass
class AllSlotsTaken(Exception): pass
class Slot:
def __init__(self, pos: Tuple[int, int]) -> None:
s... |
"""Description of how opcodes affect the stack"""
import opcode
import dis
try:
from itertools import izip_longest as zip_longest
except ImportError:
from itertools import zip_longest
__all__ = (
'get_stack_change', 'create_instruction', 'reassemble', 'validate_bytecode',
'is_non_global_scope_getter'... |
from datetime import datetime
import pytz
from django.forms import formset_factory
from django.utils import timezone
from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404
from django.db import transaction
from django.contrib.auth.models import User
from .forms import make_... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import numpy as np
import pandas as pd
from shapely.geometry import Point
from mfsetup.fileio import check_source_files
from mfsetup.grid import get_ij
def read_observation_data(f=None, column_info=None,
column_mappings=None):
df = pd.read_csv(f)
df.columns = [s.lower() for s in df... |
# -*- coding: utf-8 -*-
"""Base for drivers
:copyright: Copyright (c) 2019 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from pykern import pkconfig, pkio, pkinspect, pkcollections, pkconfig, pkjson
from pykern.pkcollections import PKDict
from pykern.pkdebug import ... |
import numpy as np
from collections import namedtuple
from scipy.interpolate import interp1d
def cast_to_array(x, type_=float):
return np.array(x, dtype=type_)
def build_class_str(self, args_dic):
def generate():
yield type(self).__name__
yield '-' * 80
yield from (f'{key}: {val!r}'... |
import asyncio
import logging
import signal
from collections import defaultdict
from concurrent.futures.thread import ThreadPoolExecutor
from dataclasses import dataclass
from types import FrameType
from typing import Any, Callable, DefaultDict, Dict, List, Optional
from uuid import uuid4
from . import VERSION
from .a... |
"""Created on 6 Jan 2017.
@author: <NAME>
@description: mastermind tuning script for model
Attributes:
DEFAULT_FORMAT (str): Logging format
LOGFILE_NAME (str): Logging file name
OUTPUT_DIR (str): TensorBoard output directory
"""
# Basic Python
import logging
# Extended Python
from sigopt import Connectio... |
# Copyright 2016 The COMPEIT Consortium
#
# 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... |
from ..kernel import core
from ..kernel.core import VSkillModifier as V
from ..character import characterKernel as ck
from functools import partial
from ..status.ability import Ability_tool
from . import globalSkill
from .jobbranch import thieves
from . import contrib
class MesoStack(core.DamageSkillWrapper, core.Stac... |
""" Encapsulates RB results and dataset objects """
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government r... |
import os
import time
import json
import glob
import torch
import torch.optim as optim
from torch.autograd import grad
import torchvision.transforms as transforms
from easydict import EasyDict
from PIL import Image
from torch.utils.data import DataLoader, WeightedRandomSampler
from torchvision.utils import save_image
... |
from collada import Collada
import collada
from OpenGL.GL import *
from OpenGL.GLUT import *
from ctypes import c_float, c_void_p, sizeof
import numpy as np
from .transformations import quaternion_from_matrix, quaternion_matrix, quaternion_slerp
class Joint:
def __init__(self, id, inverse_transform_ma... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy import stats
import argparse
import sys
import pandas as pd
from matplotlib.patches import Rectangle
import uproot
import pandas as pd
import numpy as np
import argparse
import os, sys
from icecream import ic
import mat... |
"""Generate a diffusion map embedding
"""
import numpy as np
def compute_diffusion_map(L, alpha=0.5, n_components=None, diffusion_time=0,
skip_checks=False, overwrite=False):
"""Compute the diffusion maps of a symmetric similarity matrix
L : matrix N x N
L is symmetr... |
"""
TODO:
* settings? (extensions (tiff,bmp,etc), verbosity, path stuff?)
* bad pictures (low resolution, heavy jpeg compression) dont yield barcodes
"""
from beets import ui
from beets.autotag import hooks
from beets.plugins import BeetsPlugin
from beets.ui.commands import PromptChoice
from beets.mediafile imp... |
#!/usr/bin/env python3
'''
2021.12.09
通过exporter方式实现prometheus获取接口请求数据
'''
import os
import time
import random
import json
import sqlite3
import platform
import logging
import requests
from prometheus_client import start_http_server, Counter, Gauge
from prometheus_client.exposition import generate_latest
PY2 = pla... |
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
# base.py is derived from [3DMPPE_POSENET_RELEASE](https://github.com/mks0601/3DMPPE_POSENET_RELEASE.git)
# distributed under MIT License (c) 2019 <NAME>.
import os
import os.path as osp
import math
import time
import glob
import abc
import random
import torch
from torch.utils.data import DataLoader
from torch.nn.ut... |
from django.conf import settings
from django.utils.datastructures import MultiValueDictKeyError
from django.core.exceptions import ObjectDoesNotExist
from django.contrib import messages
from django.contrib.auth import login, logout, authenticate, update_session_auth_hash
from django.contrib.auth.hashers import make_pas... |
import sys, logging, os, random, math, arcade, open_color
#check to make sure we are running the right version of Python
version = (3,7)
assert sys.version_info >= version, "This script requires at least Python {0}.{1}".format(version[0],version[1])
#turn on logging, in case we have to leave ourselves debugging messa... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# SolidBlue III - Open source data manager.
#
# __author__ = "<NAME>"
# __copyright__ = "Copyright © 2020 by <NAME>"
# __credits__ = ["<NAME>"]
# __license__ = "Apache v2"
# __version__ = "1.0-ALPHA-4-SNAPSHOT"
# __maintainer__ = "<NAME>"
# __email__ = "<EMAIL>"
#... |
from django.shortcuts import get_object_or_404
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets, status, mixins
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from .filters... |
"""frosted/test/test_api.py.
Tests all major functionality of the Frosted API
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, ... |
from __future__ import absolute_import, division, print_function
import numpy as np
import pandas as pd
from datashape.predicates import isscalar
from toolz import concat, curry, partition_all
from collections import Iterator, Iterable
import datashape
from .core import NetworkDispatcher, ooc_types
from .chunks import... |
from pathlib import Path
from typing import List, Union
import re
import os
import random
from itertools import islice
from datetime import datetime
import subprocess
from multiprocessing import Pool
from uuid import uuid4
import pandas as pd
import tempfile
import platform
from MhcVizPipe.Tools.utils import convert_wi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import random
import matplotlib.pyplot as plt
class Player:
def __init__(self, name, level):
self.name = name
self.level = level
self.cards = []
self.timer = np.inf
self.aggresiveness = np.random.randint(low... |
"""Package for document classes
"""
import typing as tg
from abc import ABC, abstractmethod
from collections import UserDict
from itertools import chain
class DocumentSet(UserDict):
"""Class represents a set of documents."""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwar... |
import math
import random
from itertools import product
import numpy as np
import torch
from gym.spaces import Box, Discrete, Tuple
from sdriving.environments.intersection import (
MultiAgentRoadIntersectionBicycleKinematicsEnvironment,
)
from sdriving.tsim import (
BatchedVehicle,
FixedTrackAccelerationM... |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import sys
import random
import maya.cmds as cmds
# Definition des constantes
prefix = "Snowman_"
subDivisionsX = 13
subDivisionsY = 13
subDivisionsZ = 13
offset = [0, 2, 0]
snowmanID = random.randint(235, 846)
sets = []
# Definition des parties du corps
bodyParts = []
bodyRadius = [2, 1.7, 1.3]
bodyPositions = [(0, ... |
# Copyright 2020 Babylon Partners. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
import argparse
from pysam import VariantFile
import multiprocessing
from multiprocessing import Process, Pool, TimeoutError, Array, Manager
import time
from timeit import default_timer as timer
import sys
import os
import Pileup as SamPileupBMP
"""
This program takes an alignment file (bam) and a reference file
to cre... |
"""Utility functions for autoreject."""
# Authors: <NAME> <<EMAIL>>
import mne
from joblib import Memory
mem = Memory(cachedir='cachedir')
def set_matplotlib_defaults(plt):
"""Set publication quality defaults for matplotlib.
Parameters
----------
plt : instance of matplotlib.pyplot
The plt... |
import random
import numpy as np
import pandas as pd
import os
import json
import copy
from collections import defaultdict
from data import item_pools
class Wish:
def __init__(self, data_path="data"):
"""
Simulates wishes in Genshin Impact
"""
self.four_star_pity_counter = 0
... |
import sys
from os import listdir
from os.path import isdir, isfile, join
import math
import pandas as pd
import seaborn as sns
from mpl_toolkits.mplot3d import Axes3D
import matplotlib as mpl
import matplotlib.pyplot as plt
from scipy import stats
import argparse
import homoglyphs as hg
import statsmodels.api as sm
im... |
"""Common parameter parsing functions for the API controllers."""
def set_options(req_args, endpoint):
"""Return a dictionary with runtime options and config."""
from ..elc import config
from ast import literal_eval
# NEW RESOURCE: Optional. Add aditional formats and controls below
# The default ... |
import json
import logging
from typing import Optional, Sequence, Tuple, Union
import joblib
import numpy as np
from scipy import interpolate
from sklearn import neighbors
from sharetrace import model, util
Array = np.ndarray
Arrays = Sequence[Array]
Histories = Sequence[np.void]
# Source: https://nssdc.gsfc.nasa.g... |
import os
from typing import List, Tuple, Any
import pandas as pd
import tensorflow as tf
from tensorflow import feature_column as fc
# from algorithm.WideAndDeep.Wide_and_Deep import example_parser, train_input_fn, eval_input_fn, create_feature_columns, FLAGS
# 定义输入参数
flags = tf.app.flags
# 训练参数
flags.DEFINE_strin... |
# This must come first or it crashes when it tries to multi thread
import asyncio
from spec_checker.modules.spec_record import SpecRecord
from spec_checker.modules.utilities import truncate
from spec_checker.modules.submit_to_google_forms import google_submit
from spec_checker.windows.MainWindow import Ui_MainWindow
f... |
"""Loads a model from a checkpoint and samples the gradients of the encoder parameters."""
import os
import random
from argparse import ArgumentParser
from copy import copy
from typing import Dict, List, Optional, Set, Tuple
import numpy as np
import tensorflow as tf
from gpflow.training.monitor import restore_sessio... |
"""Circuits using implementation of a Python module (plugin) manager for Naali.
here is a Manager that the PythonScriptModule instanciates,
and which then loads the python modules that are to be autoloaded.
This handles their event registrations, passing incoming events to them etc.
"""
try:
import rexviewer as r... |
import torch
import torch.nn as nn
import math
import torch.nn.functional as F
class Conv_bn_relu(nn.Module):
def __init__(self, inp, oup, kernel_size=3, stride=1, pad=1,use_relu = True):
super(Conv_bn_relu, self).__init__()
self.use_relu = use_relu
if self.use_relu:
self.convs... |
import dash
import numpy as np
import pandas as pd
import dash_core_components as dcc
from dash.dependencies import Input, Output
import dash_html_components as html
import plotly.graph_objs as go
import os
app = dash.Dash(__name__)
server = app.server
server.secret_key = os.environ.get('SECRET_KEY', 'my-secret-key')
... |
#Author: YP
#Created: 2019-03-07
#Last updated: 2019-04-25
#A collection of functions used by GPS that interacts with pcs objects.
#Also includes some handy functions for modifying PCS files into formats better
#for GPS
import copy as cp
from PCS import pcsParser
def reparameterizePCS(pcsFile):
#Author: YP
#... |
import sys
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *
IdRole = Qt.UserRole
class PaintArea(QWidget):
points = QPolygon([
QPoint(10, 80),
QPoint(20, 10),
QPoint(80, 30),
QPoint(90, 70)
])
Line, Points, Polyline, Polygon, Rect,... |
"""
tests for ocd functions.
"""
# pylint: disable=E1101
# pylint: disable=unused-argument
# pylint: disable=unused-variable
# pylint: disable=missing-docstring
# pylint: disable=redefined-outer-name
import random
import torch
import pytest
import numpy as np
from ocd import OCD
@pytest.fixture(scope='module')
def fi... |
from random import sample
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
ROOT = "D:/02PHBS_G2/PHBS_m2/bigDataAnalysis/big-data-hft/project"
os.chdir(ROOT)
# 参考下面的写法写计算factor的函数
# 输入就是sample_data的样子,输出就是一个数字
# 下面这个函数就是计算这个股票当天分钟return的std
# 最后给我一个py文件 里面都是这种的函数就行
# by 汪子杰
def cal_... |
# Copyright 2021 ONDEWO GmbH
#
# 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, so... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
from six.moves import xrange
import tensorflow as tf
import tensorlayer as tl
from tensorflow.python.ops import array_ops
from tensorlayer import logging
from tensorlayer.decorators import deprecated_alias
from tensorlayer.layers.core import Layer
from ten... |
'''
This file contains all mathematical and trigonometric functions to check distances, intersections, calculate radii of curvature, etc;
'''
from math import *
def Intersection(point,angle,segment):
'''
Checks if an intersection between a segment and a vector occurs from a point with a max size
... |
import os
import torch
import torch.nn as nn
from torch.nn import init
from torchvision import models
from torch.autograd import Variable
from backbone import RGA_ResNet50_alpha
from torch.nn import functional as F
WEIGHT_PATH = os.path.join(os.path.dirname(__file__), '../') + '/weights/pre_train/resnet50-1... |
from os.path import join as pjoin
import os.path
import numpy.testing as npt
import numpy as np
import nibabel as nib
from nibabel.tmpdirs import TemporaryDirectory
from dipy.align.tests.test_imwarp import get_synthetic_warped_circle
from dipy.align.tests.test_parzenhist import setup_random_transform
from dipy.align... |
import numpy as np
import h5py
import scipy.io as io
import poppy
import sys
import scipy.special as sp
import pyfftw
from astropy import units as u
import matplotlib.pyplot as pl
from ipdb import set_trace as stop
def even(x):
return x%2 == 0
def zernike_parity(j, jp):
return even(j-jp)
def progressbar(curr... |
import fileinput
import subprocess
import pathlib
from utils import *
@all_files_in_dir('sim_0')
@all_available_simulators()
def test_sim_0(datafiles, simulator):
with datafiles.as_cwd():
subprocess.check_call(['create_unit_test.pl', '-overwrite', '-out', '-dut_unit_test.sv', 'dut.sv'])
subproce... |
# -*- coding: utf-8 -*-
"""
Copyright [2009-2018] EMBL-European Bioinformatics Institute
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... |
# -*- coding: utf-8 -*-
import json
import os
import requests
import urllib.request
import time
import re
from bs4 import BeautifulSoup
from slackclient import SlackClient
from flask import Flask, request, make_response, render_template, jsonify
from selenium import webdriver
# 바꼈지롱
app = Flask(__name__)
app.config['... |
"""Convert relation predicate to predicate-action diagram.
Reference
=========
<NAME>
"TLA in pictures"
IEEE Transactions on Software Engineering
Vol.21, No.9, pp.768--775, 1995
doi: 10.1109/32.464544
"""
# Copyright 2016 by California Institute of Technology
# All rights reserved. Licensed under BSD-... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:set ts=4 sw=4 et:
# Copyright 2018-2019 <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/LICEN... |
import numpy as np
from numpy.linalg import inv
from utils.JES3D_transform_utils import file_lines_to_list
import copy
def read_cam(str):
cam = {}
wrds=str.split(' ')
if not len(wrds)==14:
return cam
vals = [float(w) for w in wrds]
cam['id'] = vals[0]+1
cam['f'] = vals[1]
cam['R'] = ... |
# coding: utf-8
"""
This interface provides a simple way to declare and store parameters
in Modoboa's database.
Core components or extensions can register their own parameters, which
will be available and modifiable directly from the web interface.
Only super users will be able to access this part of the web interfa... |
#!/usr/bin/env python3
import argparse
import fnmatch
import functools
import glob
import os
import re
import subprocess
import sys
import textwrap
from dataclasses import dataclass
from typing import Callable, Optional
class InvalidArgument(Exception):
pass
@functools.total_ordering
class Version:
def __in... |
from turtle import back
from torchvision.ops.roi_align import roi_align
import torch
from maskrcnn import get_maskrcnn
import cv2
from MaskFormer.demo.demo import get_maskformer
import os
import numpy as np
import time
VIDEO_PATH = ['../../Anticipating-Accidents/dataset/videos/training','../../Anticipating-Accidents/d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
# Selenium Framework
A framework built around the Selenium WebDriver to simplify the basic capabilities that are
most frequently used (in my experience anyway).
'''
__title__ = 'Selenium Framework'
__version__ = '0.5.0'
__copyright__ = '2011 - 2020'
__author__ = '<NAME... |
import torch
def linear(*args):
"""
Un-hook the function to have its detailed behaviour
"""
return torch.nn.functional.native_linear(*args)
def dropout(input, p=0.5, training=True, inplace=False):
"""
Args:
p: probability of an element to be zeroed. Default: 0.5
training: If ... |
import numpy as np
from tools.utils import Helper
import matplotlib.pyplot as plt
from scipy.spatial.distance import cdist
import sys
import argparse
import tensorflow as tf
def tf_fake_iou(X: tf.Tensor, centroids: tf.Tensor) -> tf.Tensor:
""" calc the fake iou between x and centroids
Parameters
--------... |
"""Preprocessors.
Usage example:
# Create a preprocessor
preprocessor = Identity()
# Process data
preprocessed_data = preprocessor.fit_transform([[0, 1, 2], [0], [0, 1]])
"""
from __future__ import annotations
import abc
import collections
import itertools
import re
import typing
import numpy as np... |
import math
import dgl
import pytorch_lightning as pl
import torch as th
import torch.nn as nn
import torch.nn.functional as F
class NodeExplainerModule(nn.Module):
"""
A Pytorch module for explaining a node's prediction based on its computational graph and node features.
Use two masks: One mask on edges... |
"""adaptive LSTM
PyTorch implementation of the adaptive LSTM (https://arxiv.org/abs/1805.08574).
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Parameter
from torch.autograd import Variable
from torch.nn._functions.thnn import rnnFusedPointwise as fusedBackend
from .utils ... |
from __future__ import annotations
import dataclasses
import operator
import datetime
import itertools
import logging
import pathlib
import re
from typing import Any
import pystac
from pystac import (
CatalogType,
Collection,
Extent,
Item,
Provider,
ProviderRole,
SpatialExtent,
Tempora... |
import os
import os.path as osp
import math
from numbers import Number
from tqdm import tqdm
import torch
from torch.autograd import Variable
from torch_geometric.datasets import Planetoid
from torch_geometric.data import DataLoader
import models.dist as dist
import models.flows as flows
from models.infomax import Dee... |
"""
QUantum mechanics Enabled Simulation Toolset (QUEST) library is a
collection of C++ classes and functions for simulation and design of
nano-scaled devices using quantum mechanical tools such as Non-equilibrium
Green's Function (NEGF) formalism. This library provides a common framework
for NEGF so that it c... |
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import sklearn.metrics
from heptrkx import pairwise
fontsize=16
minor_size=14
def get_pos(Gp):
pos = {}
for node in Gp.nodes():
r, phi, z = Gp.node[node]['pos'][:3]
x = r * np.cos(phi)
y = r * np.sin(phi)
... |
import argparse
import json
import numpy as np
from tqdm import tqdm
from recsysrw import shared
from recsysrw.random_walk import MultipleRandomWalk
import datetime
from recsysrw.title_processing import TitleIndexer, expand_on_title
from recsysrw.playlist_model import HistogramPlaylist
def challenge_playlist_to_nodes... |
import os
import logging
from datetime import datetime, timedelta, timezone
from airflow.operators.python_operator import PythonOperator
from airflow.operators.mysql_operator import MySqlOperator
from airflow.jobs import BaseJob
from airflow.models import settings
from airflow.models import DAG, DagRun, TaskInstance,... |
import numpy as np
from numpy.testing import assert_equal
from trackpy.masks import slice_image, mask_image
from trackpy.tests.common import StrictTestCase
class TestSlicing(StrictTestCase):
def test_slicing_2D(self):
im = np.empty((9, 9))
# center
for radius in range(1, 5):
... |
# See LICENSE for licensing information.
#
# Copyright (c) 2016-2019 Regents of the University of California and The Board
# of Regents for the Oklahoma Agricultural and Mechanical College
# (acting for and on behalf of Oklahoma State University)
# All rights reserved.
#
import collections
import debug
from tech import... |
import os
import re
import sys
import time
import shutil
import subprocess
import datetime
import yaml
import getpass
# Import gslab_scons modules
import _exception_classes
from size_warning import issue_size_warnings
def scons_debrief(target, env):
'''Execute functions after SCons has built all targ... |
import json
import os
import pytz
from collections import defaultdict
from datetime import datetime
from dateutil.relativedelta import relativedelta
from django.conf import settings
from django.utils import timezone
from glob import glob
from urllib.parse import quote
from django.db import connection
from django.db.m... |
"""
This module is design to be called by command-line or subprocesses
to interact with SpiderPlugins, it is self-contained, so that
it can be used alone to test plugin or play with scrapy spiders
without scrapydd environment.
Scrapydd call this module in virtualenv or docker environment to isolate
plugins from main p... |
import os
import time
import uuid
from tornado import httputil, web
from nbexchange.database import scoped_session
from nbexchange.handlers.base import BaseHandler, authenticated
from nbexchange.models.actions import Action, AssignmentActions
from nbexchange.models.assignments import Assignment as AssignmentModel
fro... |
"""A Compile object (see compile_rule.py) for foo.handlebars files."""
from __future__ import absolute_import
import inspect
import json
import os
import re
import sys
import types
from kake.lib import compile_rule
from kake.lib import log
_PACKAGE_NAME_RE = re.compile(r'([^%s]+)-package' % os.sep)
def _extract_p... |
from typing import ValuesView
from lark import Lark, Transformer, v_args
import csv
import json
from lark.exceptions import ParseError
from lark.load_grammar import Grammar
"简化版,只包含生成代码的语法。非常不完全,自行添加需要的语法。"
pl0_grammar3 = """
start: stmt
?stmt: s | open_stmt
s: "if"i b_expr "then"i m s n "else"i m ... |
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from codes.models.modules import ScaledDotProductAttention, LayerNormalization
import math
from codes.utils import constants as Constants
import pdb
# select device automatically
device = torch.device("cuda:0" if torch.cuda... |
#!/usr/bin/env python3
import pytest
import io
from pathlib import PosixPath
from unittest.mock import MagicMock, patch
from list_changed_targets import (
Collection,
ElGrandeSeparator,
WhatHaveChanged,
list_pyimport,
parse_args,
read_collection_name,
)
my_module = """
from ..module_utils.core... |
#!python
import sys
import queue
from collections import deque
lower_string = "abcdefghijklmnopqrstuvwxyz"
class BinaryTreeNode(object):
def __init__(self, data):
"""
Initialize the tree with user expression(algebraic expression)
Args:
data(str): string representation of m... |
"""
Pure python inversion of small matrices, to avoid requiring numpy or similar in SimTK.
This is part of the OpenMM molecular simulation toolkit originating from
Simbios, the NIH National Center for Physics-Based Simulation of
Biological Structures at Stanford, funded under the NIH Roadmap for
Medical Research, gran... |
# pylint: disable=E1305
# -*- coding: utf-8 -*- #
# Copyright 2014 Google LLC. 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/LICEN... |
## Figuring out which hash decodes into which type/category is literal hell, because you cant read the manifest itself.
## To find out what a hash means, you need to write code to decode it with its specific definition, which is a pain in my
## ass.
## Manifest definition breakdown:
## DestinyInventoryItemDefinition -... |
import numpy as np
from parse_data import *
from PhraseBased import PhraseBased
import datetime
####################### INITIALIZATION ###########################
def create_word_translation_prob_dict(parallel_corpus,foreign_name='fr'):
'''
This will create a dictionary mapping each french word to correspondin... |
#
# Copyright 2018-2020 Clement
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
... |
"""Dropsort implementations.
Linear-time "sorting" algorithms that work by eliminating elements which appear
out of order."""
import util
from collections import deque
from heapq import merge
def _keyify(ls, key):
return [(key(v), v) for v in ls]
def _unkeyify(key_ls):
return [e[1] for e in key_ls]
def _curry... |
from rauth import OAuth1Service
from flask import url_for, request, redirect, session
from .config import CONSUMER_KEY, CONSUMER_SECRET
SERVER_URL = 'http://www.khanacademy.org'
class KhanAcademySignIn:
def __init__(self):
self.service = OAuth1Service(
name='test',
consumer_key=CON... |
"""A file which contains classes for the agents involved in the simulation."""
import random
import rhabm
RhinoEmoji = "🦏"
DeadRhinoEmoji = "💀"
PoacherEmoji = "🔪"
CaughtPoacherEmoji = "⛓️"
SecurityEmoji = "🚓"
def euclidean_distance(point_a, point_b):
"""
Returns the euclidean distance between two points ... |
"""
Class for encoding variable-length peptides to fixed-size numerical matrices
"""
from __future__ import (
print_function,
division,
absolute_import,
)
import math
from six import string_types
from functools import partial
import numpy
import pandas
from amino_acid import *
class EncodingError(Value... |
# BSD 3-Clause License; see https://github.com/scikit-hep/uproot4/blob/main/LICENSE
"""
This module provides an interface between Uproot and PyROOT.
PyROOT is a *complete* set of ROOT bindings generated automatically from ROOT's
reflected C++ code. Uproot is a pure Python reimplementation of ROOT I/O, with
incomplete... |
from __future__ import print_function
import os
import keras.models as models
from skimage.transform import resize
from skimage.io import imsave
import numpy as np
np.random.seed(256)
import tensorflow as tf
tf.set_random_seed(256)
import multiprocessing as mp
mp.set_start_method('spawn')
os.environ["C... |
#!/usr/bin/env python2
# coding: utf-8
# vim: set ts=4 sw=4 expandtab sts=4:
# Copyright (c) 2011-2014 <NAME> & contributors
#
# 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 restrict... |
import re
import random
import string
from random import randint
import secrets
import sqlalchemy
from sqlalchemy import inspect
from sqlalchemy.orm import session
from models import *
from utils import random_bank_name
from faker import Faker
#################################################
# DATABASE CONNECTOR
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.