text string | size int64 | token_count int64 |
|---|---|---|
# -*- coding: utf-8 -*-
"""
Provides functions for data transformation (currently only LLS) and
normalization.
"""
import numpy as np
def transform(raw_data, mode, direction='direct', **kwargs):
"""
Apply mathematical transformations to data.
Parameters
----------
raw_data : ndarray
2D n... | 3,289 | 920 |
# Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
# The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for c... | 1,183 | 380 |
import torch
from utils2.torch import to_device
import numpy as np
import multiprocessing as mp
import math
def estimate_advantages(memories, value_net, gamma, tau, device='cpu', dtype=torch.double, queue=None, pid=None, num_agent=None):
advantages_list = []
states_list =[]
actions_list = []
returns_l... | 3,172 | 1,019 |
#Predictions performed by this module
#dependencies
import base64
import numpy as np
import io
from PIL import Image
import keras
from keras import backend as K
from keras.models import Sequential
from keras.models import load_model
from keras.preprocessing.image import ImageDataGenerator, img_to_array
from model imp... | 2,235 | 692 |
# @name: rdfizer.py
# @description: Script to generate RDF data
# @version: 1.0
# @date: 28-04-2021
# @author: Núria Queralt Rosinach
# @email: n.queralt_rosinach@lumc.nl
"""Script to generate RDF data for Beat-COVID cytokine clinical measurements"""
import sys, os
from rdflib import Namespace, Graph, BNode, Literal
... | 11,875 | 4,747 |
from typing import Any
import msgpack
from app.core.config import settings
from girder_client import GirderClient
from fastapi import HTTPException
from fastapi import Response
cache_settings = {
"directory": "/tmp/cache",
"eviction_policy": "least-frequently-used",
"size_limit": 2**20, # 1g
}
_gc = No... | 793 | 265 |
import collections
import glob
import json
import os
import random
import re
from typing import Tuple, Iterator, List, Dict, Optional
from src.data.preprocess.example import Example
_DEFAULT_STATS_BOUNDARIES = {
"Python": {"max_line_len": (37, 741), "content_len": (111, 42476)},
"Java": {"max_line_len": (56, ... | 8,838 | 2,507 |
class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
if not s :
return ""
s = list(s)
st = []
for i,n in enumerate(s):
if n == "(":
st.append(i)
elif n == ")" :
if st :
st.pop()... | 508 | 143 |
#!/usr/bin/python
# encoding: utf-8
from __future__ import print_function, unicode_literals, absolute_import
import functools
import re
import sys
from textwrap import wrap
from urllib import quote_plus
from algoliasearch.search_client import SearchClient
from config import Config
from workflow import Workflow3, ICO... | 4,021 | 1,281 |
"""Lambdata - a collection of Data Science helper functions"""
# import pandas as pd
import numpy as np
fav_numbers = [7,22,4.14]
colors = ['purple','cyan','dark blue','crimson']
def df_cleaner(df):
"""Cleans a dataframe"""
# TODO - implement df_cleaner
pass
def increment(x):
return x + 1
| 317 | 116 |
import glob,os,sys
class Path():
'''
>>> paths = Path(source,"*.txt")
>>> for path in paths:
lines = Stream(path)
for line in lines:
print(line)
'''
def __init__(self, source, pattern):
self.source = source
self.pattern = pattern ... | 3,335 | 920 |
import requests
from opbank.opbank_client import OPBankClient
def test_opbank():
requests.delete("http://localhost:8888/admin/storage")
client = OPBankClient()
client.API_URL = 'http://localhost:8000/https://sandbox.apis.op-palvelut.fi/'
payer_iban = 'FI3959986920207073'
receiver_iban = 'FI2350... | 1,188 | 423 |
from typing import Any, Dict, Generator, List, Optional
import torch
from torch import nn, optim
from torch.utils.data import DataLoader
from tensorboardX import SummaryWriter
from probnmn.config import Config
from probnmn.utils.checkpointing import CheckpointManager
class _Trainer(object):
r"""
A base clas... | 12,816 | 3,456 |
"""Utilities for exception handling."""
import logging
import functools
import inspect
LOGGER = logging.getLogger(__name__)
def should_raise(exception, item, args=None, kwargs=None, pattern=None):
"""
"Utility that validates callable should raise specific exception.
:param exception: Exception should b... | 3,334 | 959 |
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.types import DateTime
Base = declarative_base()
class Building(Base):
__tablename__ = "buildings"
id = Column(Integer, primary_key=True)
name = Column(String)
class MachineT... | 941 | 303 |
#Given a sorted array and a target value, return the index if the target is found. If not, return the index
#where it would be if it were inserted in order.
#You may assume no duplicates in the array.
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:... | 1,093 | 334 |
# Copyright (c) 2001-2022 Aspose Pty Ltd. All Rights Reserved.
#
# This file is part of Aspose.Words. The source code in this file
# is only intended as a supplement to the documentation, and is provided
# "as is", without warranty of any kind, either expressed or implied.
import unittest
import io
import os
import gl... | 104,760 | 31,596 |
import pytest
from ctrlibrary.core.utils import get_observables
from ctrlibrary.threatresponse.enrich import enrich_refer_observables
from tests.functional.tests.constants import (
MODULE_NAME,
PULSEDIVE_URL,
OBSERVABLE_HUMAN_READABLE_NAME
)
from urllib.parse import quote
@pytest.mark.parametrize(
'ob... | 2,865 | 890 |
from ...Fields import BoolField, ConditionalBlockStart
from ...Fields.Enums import ERecipe, ERecipeType
from ...Func import g
from . import Model, Int32Field, ArrayField
class AssemblerComponent(Model):
version = Int32Field()
id = Int32Field()
entityId = Int32Field()
pcId = Int32Field()
replicatin... | 857 | 281 |
import time
from sortedcontainers import SortedSet
from .exception import *
import traceback
import random
class Redis:
def __init__(self):
self.hash_table = {}
self.expire = {}
self.exp_queue = SortedSet()
self.changed = {}
self.z_map = {}
def __repr__(self):
r... | 13,612 | 4,089 |
import pygame
import constants
from player import *
from scene import *
from level01 import *
from level03 import *
from level02 import *
from customscene import *
import titlescene
class GameScene(Scene):
scr_w = constants.SCREENWIDTH
scr_h = constants.SCREENHEIGHT
def __init__(self, levelno):
sup... | 4,749 | 1,441 |
"""Exceptions Table
Revision ID: 6245d75fa12
Revises: e0a6af364a3f
Create Date: 2016-08-16 11:35:38.575026
"""
# revision identifiers, used by Alembic.
revision = '6245d75fa12'
down_revision = 'e0a6af364a3f'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic -... | 2,336 | 821 |
import pandas as pd
import math
import linecache
import numpy as np
from scipy import stats
from parameter_cal import cf
from dtw import dtw
from scipy.misc import *
from sdtw.config import sub_len, nBlocks
from sdtw.utils import cal_descriptor, samplingSequences, norm, get_link_graph
from parameter_cal.utils... | 4,422 | 1,783 |
from django.contrib import admin
class BaseModelAdmin(admin.ModelAdmin):
exclude = (
'created_time',
'modified_time',
'is_removed',
'removed_time',
)
| 193 | 61 |
# Generated by Django 3.2.6 on 2021-08-24 18:31
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='agentname',
fields=[
('name_id', models.Int... | 6,083 | 1,618 |
from __future__ import division
from __future__ import print_function
import numpy as np
import copy
from scipy import stats
class QuantizeLayer:
def __init__(self, name="None", num_bin=2001):
self.name = name
self.min = 0.0
self.max = 0.0
self.edge = 0.0
self.num_bins = nu... | 12,137 | 4,019 |
# Copyright (c) 2020 Huawei Technologies Co., Ltd.
# Licensed under CC BY-NC-SA 4.0 (Attribution-NonCommercial-ShareAlike 4.0 International) (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://creativecommons.org/licenses/by-nc-sa... | 5,484 | 2,103 |
import keras
import pandas as pd
import urllib2
from bs4 import BeautifulSoup
from pprint import pprint
from matplotlib import pyplot as plt
import sys
sys.path.append('/Users/BenJohnson/projects/what-is-this/wit/')
from wit import *
pd.set_option('display.max_rows', 50)
pd.set_option('display.max_columns', 500)
pd.... | 2,620 | 1,046 |
#!/usr/bin/env python3
import cereal.messaging as messaging
import os
import datetime
import signal
import threading
from common.realtime import Ratekeeper
# customisable values
GPX_LOG_PATH = '/data/media/0/gpx_logs/'
LOG_HERTZ = 10 # 10 hz = 0.1 sec, higher for higher accuracy, 10hz seems fine
LOG_LENGTH = 10 # mins... | 3,826 | 1,485 |
__version__ = """1.32.0""" | 26 | 14 |
#!/usr/bin/python
##############################################################################
#averager.py
#
#This code has been created by Enrico Anderlini (ea3g09@soton.ac.uk) for
#averaging the main readings required during the QinetiQ tests. These values
#averaged over one minute will be published to an externa... | 17,767 | 5,455 |
# Copyright 2019 Jetperch 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 agreed to in writing,... | 12,827 | 4,002 |
#!/usr/bin/env python3
#
# USB Camera - Simple
#
# Copyright (C) 2021-22 JetsonHacks (info@jetsonhacks.com)
#
# MIT License
#
import sys
import cv2
window_title = "USB Camera"
# ASSIGN CAMERA ADRESS to DEVICE HERE!
pipeline = " ! ".join(["v4l2src device=/dev/video0",
"video/x-raw, width=64... | 2,267 | 734 |
from django.contrib import admin
from .models import Index, Tag, Category, Post
# Register your models here.
admin.site.register(Index)
admin.site.register(Tag)
admin.site.register(Category)
admin.site.register(Post) | 219 | 65 |
from utils.math import primes
def rotate(num):
s = str(num)
l = len(s)
rot = set()
for i in range (l):
s = s[1:] + s[0]
if num > 9 and int(s[-1]) in [2, 4, 5, 6, 8, 0]:
return None
else:
rot.add(int(s))
return frozenset(rot)
p = primes(100)
prin... | 588 | 240 |
import itertools
import logging
import os
import statistics
from pathlib import WindowsPath
from typing import List, Union
import seaborn as sns
sns.set_theme()
import matplotlib.pyplot as plt
import pandas as pd
SEPARATOR = ","
HEADER = ["ID", "Mode", "Is Best", "Mean Query Time", "Query Ratio", "Mean Process Time"... | 10,227 | 3,040 |
from keras.models import Sequential
from keras.layers import Dense, Activation
model = Sequential()
model.add(Embedding(vocabulary_size, embedding_dim, input_shape=(90582, 517)))
model.add(GRU(512, return_sequences=True))
model.add(Dropout(0.2))
model.add(GRU(512, return_sequences=True))
model.add(Dropout(0.2))
mode... | 3,412 | 1,395 |
"""Gamma distribution."""
import numpy
from scipy import special
from ..baseclass import Dist
from ..operators.addition import Add
class gamma(Dist):
def __init__(self, a=1):
Dist.__init__(self, a=a)
def _pdf(self, x, a):
return x**(a-1)*numpy.e**(-x) / special.gamma(a)
def _cdf(self, ... | 2,901 | 1,122 |
###
# (C) Copyright [2019-2020] Hewlett Packard Enterprise Development LP
#
# 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 ... | 7,449 | 1,894 |
# Generated by Django 2.1.7 on 2019-09-17 12:09
from django.db import migrations, models
import django.db.models.deletion
import items.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Author',
... | 12,775 | 7,275 |
#!/usr/bin/env python3
import argparse
import sqlalchemy.exc
from workshops_api.app import app
from workshops_api.database import db
from workshops_api.auth import ACCESS_LEVELS
from workshops_api.models.user import UserModel
from workshops_api.config import config
class Setup():
def __init__(self, config):
... | 2,039 | 549 |
from distutils.core import setup
readme = """
# Nertivia4PY
A Python wrapper for the Nertivia API.
Support Nertivia server : https://nertivia.net/i/nertivia4py
> ### Install
> ```
> pip install nertivia4py
> ```
> ### Example
> ```python
> import nertivia4py
>
> token = "TOKEN_HERE"
> prefix = "... | 1,285 | 495 |
class PoolArgs:
def __init__(self, bankerBufCap, bankerMaxBufNumber, signerBufCap, signerBufMaxNumber, broadcasterBufCap, broadcasterMaxNumber, stakingBufCap, stakingMaxNumber, distributionBufCap, distributionMaxNumber, errorBufCap, errorMaxNumber):
self.BankerBufCap = bankerBufCap
self.BankerMaxBuf... | 7,867 | 2,266 |
import numpy as np
import torch
from scipy.stats import truncnorm
from pymoo.factory import get_sampling, get_crossover, get_mutation
from pymoo.operators.mixed_variable_operator import MixedVariableSampling, MixedVariableMutation, MixedVariableCrossover
from pymoo.model.sampling import Sampling
class TruncatedNormal... | 3,030 | 1,064 |
#!/usr/bin/env python
import sys
from distutils.core import setup
from distutils.extension import Extension
if sys.platform == 'darwin':
monoclock_libraries = []
else:
monoclock_libraries = ['rt']
setup(
name='Monoclock',
version='14.4.18',
description="Monotonic clock access for Python",
url="https://github.c... | 723 | 263 |
class UserModel(Table):
def __init__(self):
self.tableName = "User"
self.requiredFields = ['firstName', 'lastName', 'username', 'password']
self.optionalFields = ['email']
def check(self, data):
for req in self.requiredFields:
if req not in data:
return False
for opt in self.optionalFields:
if o... | 871 | 359 |
import numpy as np
import pandas as pd
import mrob
from test_utils import get_mc
from sys import platform
import matplotlib
if platform == "darwin":
matplotlib.use('PS')
import matplotlib.pyplot as plt
# Here the Cholesky decomposition for singular covariance matrix is implemented
def cholesky(sigma):
# o... | 9,844 | 3,920 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-04-17 00:30
from __future__ import unicode_literals
from django.db import migrations
def forwards(apps, schema_editor):
TFUser = apps.get_model('tf_auth.TFUser')
for user in TFUser.objects.all():
try:
user.username = user.playe... | 573 | 213 |
import config as cfg
import cv2
import numpy as np
from keras.models import load_model
from keras.preprocessing.image import img_to_array
from keras import backend as K
import tensorflow as tf
import keras
'''
esto es necesario para que no haya errores a la hora de exponer el servicio con flask
info --> https://github... | 1,947 | 630 |
# Generated by Django 2.2.1 on 2020-03-10 18:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('gui', '0013_auto_20200310_1742'),
]
operations = [
migrations.AddField(
model_name='feedback',
name='childprotection... | 455 | 161 |
import unittest
from TestUtils import TestAST
from AST import *
class ASTGenSuite(unittest.TestCase):
# Test variable declaration
def test_single_variable_declaration(self):
input = """int a;"""
expect = "Program([VarDecl(a,IntType)])"
self.assertTrue(TestAST.checkASTGen(input,expect,30... | 45,764 | 16,988 |
# Copyright 2008-2009 Owen Taylor
#
# This file is part of Reinteract and distributed under the terms
# of the BSD license. See the file COPYING in the Reinteract
# distribution for full details.
#
########################################################################
import gtk
import os
from base_notebook_window ... | 7,966 | 2,456 |
#!/usr/bin/env python
from __future__ import print_function
from __future__ import unicode_literals
import importlib
import os
import sys
# Try to load the settings module
try:
local_settings = importlib.import_module(
os.environ.get('REGML_SETTINGS_FILE', 'settings'))
globals().update(local_setti... | 573 | 167 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_send_payout_dlg.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_SendPayoutDlg(object):
def setupUi(self, SendPayoutDlg):
... | 16,968 | 5,774 |
from mongoengine import *
class MethodStep(EmbeddedDocument):
description = StringField(require=True)
images = ListField(ImageField(db_alias="miao"), null=True)
meta = {
"db_alias": "miao",
"collection": "method_steps"
} | 254 | 79 |
from dps.hyper import run_experiment
from dps.utils import copy_update
from dps.tf.updater import DummyUpdater
from silot.run import basic_config, alg_configs, env_configs
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--max-digits', type=int, choices=[6, 12], required=True)
args, _ = parser.p... | 1,579 | 642 |
# -*- coding: utf-8 -*-
"""Top level package for evo_utils utilities"""
from . import viz
from . import fitderiv
from . import model
__author__ = """Manuel Razo"""
__email__ = """mrazomej {at} caltech.edu"""
__version__ = '0.0.1'
name = 'evo_mwc'
| 251 | 104 |
"""Alconna 命令行入口"""
from arclet.alconna.builtin.commandline import main
if __name__ == "__main__":
main()
| 112 | 47 |
from django.contrib.auth import get_user_model
from rest_framework import viewsets, status, permissions
from rest_framework.response import Response
from profiles.models import Profile
from profiles.permissions import IsUserProfileOrAdmin
from profiles import serializers
User = get_user_model()
class ProfileViewSe... | 2,427 | 654 |
from setuptools import setup
# with open('README.rst') as readme_file:
# readme = readme_file.read()
# with open('HISTORY.rst') as history_file:
# history = history_file.read()
with open("requirements.txt") as requires_file:
requirements = requires_file.read().split("\n")
requirements = [requirement for... | 1,180 | 391 |
def onMessage(request, message, socket):
print "ON MESSAGE! :" + message
socket.sendToMe("Hello Back!")
pass
def onConnect(requestData):
#socket.sendToAll("Test All")
#socket.sendToAllButMe("Test Not Me")
#socket.sendToMe("Test Me")
return True
def onDisconnect():
pass | 307 | 102 |
import rclpy
import json,numpy
from numpy import clip
from rclpy.node import Node
from std_msgs.msg import Float64MultiArray
from sensor_msgs.msg import JointState
from diagnostic_msgs.msg import DiagnosticStatus, KeyValue
import can
from tinymovr import Tinymovr
from tinymovr.iface.can import CAN
from tinymovr.units... | 6,278 | 2,014 |
# Signal processing
SAMPLE_RATE = 16000
PREEMPHASIS_ALPHA = 0.97
FRAME_LEN = 0.025
FRAME_STEP = 0.01
NUM_FFT = 512
BUCKET_STEP = 1
MAX_SEC = 10
# Model
WEIGHTS_FILE = "data/model/weights.h5"
COST_METRIC = "cosine" # euclidean or cosine
INPUT_SHAPE=(NUM_FFT,None,1)
# IO
ENROLL_LIST_FILE = "cfg/enroll_list.csv"
TEST_L... | 383 | 203 |
import unittest
from pyramid.tests.test_scripts import dummy
class TestPRoutesCommand(unittest.TestCase):
def _getTargetClass(self):
from pyramid.scripts.proutes import PRoutesCommand
return PRoutesCommand
def _makeOne(self):
cmd = self._getTargetClass()([])
cmd.bootstrap = (du... | 6,351 | 1,926 |
# plot normal quadratic distribution overlay
# Plots the effects of theta in the 2D quadratic by showing the normal
# distribution on top of the regular quadratic
import numpy as np
from mpl_toolkits import mplot3d
import matplotlib
import matplotlib.pyplot as plt
import os
import sys
import errno
sys.path.insert(0, ... | 2,120 | 863 |
# 导入:
from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# 创建对象的基类:
Base = declarative_base()
# 定义Project对象:
class Project(Base):
# 表的名字:
__tablename__ = 'project'
# 表的结构:
id = Column(String(20), primar... | 518 | 207 |
import os
import sys
import math
# 3.1 using single array to implement 3 stacks
# 1) - using 3 indexes to for each stack pointers, and 3 size to set maximum of stack
# 2) - using 3 indexes, 1 begin at the first index and increase, 1 begin at the bottom and decrease, 1 at the bottom and re-balanced every time
class Ar... | 4,753 | 1,735 |
import socket
HOST = ""
PORT = ""
def address():
global HOST
print("What is the IP of the computer you want to connect to? ")
HOST = input(":")
global PORT
print("What is the PORT of the computer you want to connect to? ")
PORT = int(input(":"))
connector()
def connector():
... | 531 | 197 |
import json
import hashlib
from absl import app
from absl import flags
from google.cloud import storage
FLAGS = flags.FLAGS
flags.DEFINE_string(
"pipeline", None,
"Name of pipeline")
flags.DEFINE_string(
"job_id", "test",
"ID for job management.")
flags.DEFINE_string(
"bucket_name", "",
"GCS ... | 1,789 | 630 |
import re
import _pickle as cPickle
import logging
import argparse
#This script is not dependant on table of contents. It detects books and chapters based their titles
# Dictionary containing key and regex pattern to match the keys
pattern_dict = {
'blank_line': re.compile(r'^\s*$'),
'book_number': re.compile... | 10,236 | 2,730 |
class Mac_Address_Information:
par_id = ''
case_id = ''
evd_id = ''
mac_address = ''
description = ''
backup_flag = ''
source_location = []
def MACADDRESS(reg_system):
mac_address_list = []
mac_address_count = 0
reg_key = reg_system.find_key(r"ControlSet001\Control\Class\{4d3... | 1,420 | 475 |
from __future__ import print_function
from fileinput import filename
import os
import pandas as pd
import pdb
from datetime import timedelta
import datetime
import shutil
date_time_format = '%Y-%m-%dT%H:%M:%S.%f'
date_format = '%Y-%m-%d'
def make_dir(data_path):
if os.path.exists(data_path) is False:
os... | 4,819 | 1,707 |
from util_data_storage_and_load import *
import openpyxl
data_folder = '/home/jzh/Dropbox/Research/\
Data-driven_estimation_inverse_optimization/INRIX/Raw_data/'
########## extract tmc info for link_1
# load attribute table link_1 data
wb_link_1 = openpyxl.load_workbook(data_folder + 'filtered_INRIX_attribute_table... | 6,737 | 2,779 |
#!/usr/bin/python
from __future__ import print_function
from __future__ import absolute_import
from past.builtins import basestring
import sys
import numpy as np
import moby2
trace = moby2.util.log.logger.trace
# transitional...
_fp_formats = {
'det_uid': '%4d',
'ok': '%1d',
'x0': '%9.6f',
'x0_err':... | 26,777 | 9,397 |
from django.conf import settings
from django.db import models
# from django.template.defaultfilters import slugify
from django.utils.translation import ugettext_lazy as _
class KB (models.Model):
name = models.CharField(max_length=30, unique=True)
repository_url = models.CharField(max_length=100, blank=False)... | 2,864 | 957 |
"""export_as_bookmark migration script."""
| 43 | 13 |
#!/usr/bin/env python3
from plumbum import cli
class M(cli.Application):
subcommands = {}
@classmethod
def print_commands(cls, root=None, indent=0):
if root is None:
root = cls.subcommands
for name, (app, sub_cmds) in root.items():
print(" "*indent, "Name:", na... | 1,915 | 514 |
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.ERROR)
def generator_fn(noise, weight_decay=2.5e-5, is_training=True):
layers = tf.contrib.layers
framework = tf.contrib.framework
f1 = framework.arg_scope(
[layers.fully_connected, laye... | 4,523 | 1,624 |
"""This module contains all forms used by the Observer-Hive frontend.
"""
import os
import json
import logging
from bcrypt import checkpw
from flask_wtf import FlaskForm
from flask_login import current_user
from wtforms import StringField, PasswordField
from wtforms.validators import InputRequired, EqualTo, Length
lo... | 6,312 | 1,413 |
import typing as t
from py_ecc.bls import G2ProofOfPossession as bls
from lido.eth2deposit.utils.ssz import (
DepositMessage,
compute_deposit_domain,
compute_signing_root,
)
from lido.eth2deposit.settings import get_chain_setting
from lido.constants.chains import get_chain_name, get_eth2_chain_name
from li... | 7,151 | 2,148 |
from app.resources.resources import RESOURCES
from app.extensions.custom_gui import ResourceListView
from app.editor.data_editor import SingleResourceEditor
from app.editor.base_database_gui import DatabaseTab
from app.editor.animation_editor import animation_model, animation_properties
class AnimationDatabase(Datab... | 1,167 | 313 |
from .base import BaseUserView
class Dashboard(BaseUserView):
def index(self):
pass
| 98 | 31 |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import time
import math
import json
import gettext
import traceback
from decimal import *
from ikabot.config import *
from ikabot.helpers.gui import *
from ikabot.helpers.market import *
from ikabot.helpers.botComm import *
from ikabot.helpers.varios import addDot, wait
... | 12,070 | 4,676 |
# This file is part of the Data Cleaning Library (openclean).
#
# Copyright (C) 2018-2021 New York University.
#
# openclean is released under the Revised BSD License. See file LICENSE for
# full license details.
"""Helper functions for strings."""
from typing import Any
from openclean.data.types import Value
from o... | 2,576 | 697 |
#!/usr/bin/env python
import rospy
import tf
from gazebo_msgs.srv import SetModelState, DeleteModel, SpawnModel
from gazebo_msgs.msg import ModelState
from geometry_msgs.msg import Pose, Point, Quaternion
class ModelController(object):
def __init__(self):
rospy.wait_for_service("gazebo/delete_model")
rospy.wai... | 1,570 | 650 |
#! /usr/bin/python3
# -*- coding: utf-8 -*-
#
# redis_python_read.py
#
# Dec/09/2014
#
#
import sys
import json
import redis
#
# ----------------------------------------------------------------
rr = redis.Redis(host='host_dbase', port=6379, db=0)
#
keys = rr.keys ('t*')
dict_aa = {}
for key_bb in sorted (keys):
... | 604 | 245 |
"""Imagine you have a special keyboard with all keys in a single row. The layout of characters on a keyboard is denoted by a string S1 of length 26. S1 is indexed from 0 to 25. Initially, your finger is at index 0.
To type a character, you have to move your finger to the index of the desired character. The time taken t... | 1,015 | 374 |
# Generated by Django 3.2.6 on 2021-11-16 20:36
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('management', '0003_employee'),
]
operations = [
migrations.RemoveField(
model_name='employee',
name='employee_passcode',
... | 334 | 112 |
from typing import Any, Dict, Optional,List
from fastapi import APIRouter, Depends, HTTPException,Body,Request
from sqlalchemy.orm import Session,joinedload_all,contains_eager,Load
from fastapi.encoders import jsonable_encoder
from app import crud, models, schemas
from app.api import deps
from app.core.security import... | 8,933 | 3,108 |
"""
This is the qmmm driver module
"""
import pickle
from janus import Initializer
def run_janus(filename='input.json'):
"""
Drives the janus program.
Creates an instance of the Initializer class
and feeds wrappers to either :func:`~janus.driver.run_simulation` or
:func:`~janus.driver.run_single_... | 2,676 | 894 |
from teether.cfg.instruction import Instruction
from teether.cfg.opcodes import potentially_user_controlled
from teether.explorer.backward import traverse_back
from teether.util.intrange import Range
def slice_to_program(s):
pc = 0
program = {}
for ins in s:
program[pc] = ins
pc += ins.nex... | 7,632 | 2,515 |
# Copyright (c) 2013 Shotgun Software Inc.
#
# CONFIDENTIAL AND PROPRIETARY
#
# This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit
# Source Code License included in this distribution package. See LICENSE.
# By accessing, using, copying or modifying this work you indicate your
# agreement to t... | 8,229 | 2,233 |
'''
decorator to log functions executions
'''
from functools import wraps
import logging
import time
def log(logger, level='info'):
'''
@brief decorator implementing the logging of a function.
'''
def log_decorator(method):
'''
@brief decorator implementing the logging of a function.
... | 1,398 | 447 |
from numpy.random import seed
seed(5393)
from tensorflow import set_random_seed
set_random_seed(12011)
import os
import numpy as np
import pandas as pd
from scipy import sparse
from sklearn.preprocessing import LabelEncoder, LabelBinarizer
from sklearn.pipeline import FeatureUnion
from sklearn.feature_extraction.te... | 7,828 | 2,788 |
from .raiseload_col import raiseload_col
from .selectinquery import selectinquery
from .counting_query_wrapper import CountingQuery
from .reusable import Reusable
from .mongoquery_settings_handler import MongoQuerySettingsHandler
from .marker import Marker
from .settings_dict import MongoQuerySettingsDict, StrictCrudHe... | 337 | 88 |
#!/usr/bin/python3
# author mhakala
import json
import re
import subprocess
import tempfile
import os
import xml.etree.cElementTree as ET
import argparse
import os.path
import time
import random
from datetime import datetime
from datetime import timedelta
import traceback
import configparser
import glob
def jobs_runn... | 7,120 | 2,232 |
""" 参考自https://github.com/bojone/crf/ """
import tensorflow as tf
k = tf.keras
kl = tf.keras.layers
K = tf.keras.backend
from sklearn.model_selection import train_test_split
import numpy as np
import re
from tqdm import tqdm
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
class CRF(kl.L... | 10,567 | 5,119 |
# -*- coding: utf-8 -*-
r"""
Schedulers
==============
Leraning Rate schedulers used to train COMET models.
"""
from argparse import Namespace
from torch.optim import Optimizer
from torch.optim.lr_scheduler import LambdaLR
class ConstantPolicy:
"""Policy for updating the LR of the ConstantLR scheduler.
W... | 4,284 | 1,348 |
"""
Prediction
==========
"""
from .amici_predictor import AmiciPredictor
from .prediction import PredictionResult, PredictionConditionResult
| 144 | 42 |
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium import webdriver
import requests
def login():
driver = webdriver.Chrome()
driver.implicitly_wait(20)
driver.get("https://tixc... | 1,378 | 411 |