text stringlengths 3.07k 12.6k |
|---|
from collections import defaultdict
"""
Module for generating DAG diagrams in Graphviz DOT language.
"""
# Helpers for DOT language generation
INVISIBLE = "invis" # "dashed" #"invis"
def attributes(**kwargs):
if not kwargs:
return ""
return "[" + " ".join(f"{name}={value}" for (name, value) in kwa... |
import argparse
import json
import os
from dipy.align.reslice import reslice
import nibabel as nib
import numpy as np
import pandas as pd
from scipy.ndimage.filters import gaussian_filter
import SimpleITK as sitk
def preprocess_img(inputfile, output_preprocessed, zooms):
img = nib.load(inputfile)
data = img.... |
import os
import time
import tempfile
import numpy as np
from csb.bio import structure
from csb.bio.utils import radius_of_gyration
from scipy.spatial.distance import pdist, squareform
from scipy.sparse.csgraph import connected_components
from .universe import Universe
def crosscorr(a, b):
"""Cross-correlation... |
import requests
import argparse
from datetime import datetime
import time
from pprint import pprint
import pymongo
import sys
sys.path.append("../utils/")
from preprocess_data import extract_quotation_content, query_trss_for_jenkins_output, extract_jenkins_link_and_testname
import os
def store_in_db(data, collection_... |
'''
Header:
Byte Type Description
0 int File code (0x1234, little endian)
4 double Minimum x (little endian)
12 double Minimum y (little endian)
20 double Maximum x (little endian)
28 double Maximum y (little endian)
36 int Number of polygons (little endian)
Record:
Byte Type Description
0 int Record length including ... |
from houdini.data import AbstractDataCollection, db
class Puffle(db.Model):
__tablename__ = 'puffle'
id = db.Column(db.Integer, primary_key=True)
parent_id = db.Column(db.ForeignKey('puffle.id', ondelete='CASCADE', onupdate='CASCADE'), nullable=False)
name = db.Column(db.String(50), nullable=False, s... |
"""
cargo/unix/accounting.py
Track resource usage.
@author: <NAME> <<EMAIL>>
"""
if __name__ == "__main__":
from cargo.unix.accounting import main
raise SystemExit(main())
import os
import re
import sys
import time
import errno
import select
import signal
from datetime import timedelta
from ite... |
import pandas as pd
import numpy as np
import pytest
from .context import (
gtfstk, slow, DATA_DIR, cairns, cairns_shapeless, cairns_dates,
cairns_trip_stats, HAS_FOLIUM
)
from gtfstk import *
if HAS_FOLIUM:
from folium import Map
def test_is_active_trip():
feed = cairns.copy()
trip_id = 'CNS2014-CNS... |
from __future__ import division
import numpy as np
from itertools import chain
from functools import reduce
from .base import Estimator
class Matching(Estimator):
"""
Dictionary-like class containing treatment effect estimates. Standard
errors are only computed when needed.
"""
def __init__(self, data, W, m, ... |
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sns
def plot_data():
(load_timestamp, avg_loads, exp_loads, raw_loads,
runtime_timestamps, runtimes) = (np.load("load_timestamp.npy"),
np.load("avg_loads.npy"), np.load("exp_loads.npy"),
np.load("raw_loads... |
import gym
import numpy as np
from mae_envs.wrappers.util import update_obs_space
from gym.spaces import Tuple, MultiDiscrete
class FoodHealthWrapper(gym.Wrapper):
'''
Adds food health to underlying env.
Manages food levels.
Args:
eat_thresh (float): radius within which food i... |
"""An example of training DQN against OpenAI Gym Envs.
This script is changed from chainerrl examples.
This script is an example of training a DQN agent against OpenAI Gym envs.
Both discrete and continuous action spaces are supported. For continuous action
spaces, A NAF (Normalized Advantage Function) is used to appr... |
#!/usr/bin/env python3
import argparse
import os
import stats
import time
UINT32_MAX = 4294967295 # max number of bytes that the router statistics page can display before it overflows
POLL_INTERVAL = 5 # seconds
# State variables
total_bytes_transferred = 0
last_num_hw_addresses = 0
outfile = None
outfile_last_ope... |
"""
This file contains methods and functions to generate a (low density) Latin Square (lsq) Matrix for use in LDLC.
Encodings of the matrix are as a pair (permutationMatris, signMatrix) which we can use to
easily store or build a lqs.
These encoding can store an 'n by n' redular lsq of weight d into two 'd by ... |
import inspect
from functools import wraps
from io import StringIO
from cProfile import Profile
from pstats import Stats
from itertools import chain
from random import randint
from typing import Any, Iterator, Literal, Tuple, List, Union, Callable
from .values import ANSI
from .globals import FINISHED_ONCE... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# <NAME>o model on a 2D lattice
# FvW 03/2018
import os
import numpy as np
import matplotlib.pyplot as plt
import cv2
def fhn2d(N, T, t0, dt, s, D, a, b, c, I0, stim, blocks):
c1 = 1/c
# initialize Fitz-Hugh Nagumo system
v, w = np.zeros((N,N)), np.zeros((N,N))
... |
import numpy as np
class Emissions:
def __init__(self, emissions):
self.emissions = emissions
self.year = emissions[:,0]
self.co2_fossil= emissions[:,1]
self.co2_land = emissions[:,2]
self.co2 = np.sum(emissions[:,1:3],axis=1)
self.ch4 = emissions[:... |
import logging
from collections import ChainMap
from itertools import compress
from typing import Dict, List
from scipy.spatial import cKDTree
from pathlib import Path
from joblib import Parallel, delayed
import numpy as np
import pandas as pd
from google.cloud.bigquery import TableReference
from gcputils.bqclient impo... |
import argparse
import glob
import os
import cv2
import numpy as np
from tqdm.contrib import tzip
from tqdm import tqdm
import torch
from PIL import Image
from cv2 import imwrite, imread
from core.raft import RAFT
from core.utils import flow_viz
from core.utils.utils import InputPadder
DEVICE = 'cuda'
def load_i... |
SIMPLE_TYPES = {
'c': 'char',
'i': 'int',
's': 'short',
'l': 'long',
'q': 'long long',
'C': 'unsigned char',
'I': 'unsigned int',
'S': 'unsigned short',
'L': 'unsigned long',
'Q': 'unsigned long long',
'f': 'float',
'd': 'double',
'B': 'BOOL',
'v': 'void',
'*'... |
import collections
import os
import six
import yaml
from okonomiyaki.versions import EnpkgVersion
from simplesat.constraints import PrettyPackageStringParser, Requirement
from simplesat.package import RepositoryInfo, RepositoryPackageMetadata
from simplesat.pool import Pool
from simplesat.repository import Repositor... |
#!/usr/bin/env python
# Copyright 2018 <NAME>
# Copyright (c) 2009-2010 <NAME>, Itaapy, Pierlis, Talend.
#
# 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... |
__source__ = 'https://leetcode.com/problems/is-subsequence/description/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/is-subsequence.py
# Time: O(n)
# Space: O(1)
#
# Description: Leetcode # 392. Is Subsequence
#
# Given a string s and a string t, check if s is subsequence of t.
#
# You may assume that th... |
from __future__ import print_function
import collections
import io
import math
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
from IPython import display
from sklearn import metrics
tf.logging.set_verbosity(tf.logging.ERROR)
train_url = 'https://storage.googleapis.com/... |
#!/usr/bin/env python
import os
import time
import unittest
import datetime
from config import Config
from api import global_config, db
from api.daos.user import UserDAO, User
from tests.unit_tests import BaseCase
class ConfigCase(unittest.TestCase):
"""
Ensure that the config works as expected
"""
... |
from mpi4py import *
from sensei import VTKDataAdaptor,ADIOS2DataAdaptor,ADIOS2AnalysisAdaptor
import sys,os
import numpy as np
import vtk, vtk.util.numpy_support as vtknp
from time import sleep
from random import seed,random
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
n_ranks = comm.Get_size()
def error_message(msg... |
#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from itertools import combinations
from collections import namedtuple, defaultdict
import re
from sagar.element.base import periodic_table_dict as ptd
all_eles = [key for key in... |
import os
import functools
import imageio
import numpy as np
from PIL import Image
import torch
from torch.utils.data import Dataset, TensorDataset
from torch import Tensor
from torch.autograd import Variable
import logging
def distance(x1, x2):
diff = torch.abs(x1 - x2)
return torch.pow(diff, 2).sum(dim=1)
d... |
from django.urls import reverse
from rest_framework.test import APIClient
import pytest
from account.models import User
from django.core import mail
from account.tasks import send_activation_code_async
from uuid import uuid4
from currency.tasks import _privat, _mono, _alfa, _otp, _pumb, _vkurse
def test_index_page(... |
from flask import Flask, session, redirect, url_for, render_template, request, abort
import wolframalpha
import requests
app = Flask(__name__)
app.secret_key = "any random string"
appId = "PYJPPL-7RXKKAPT62"
client = wolframalpha.Client(appId)
mathMLEndpoint = "https://api.mathmlcloud.org/equation"
mostRecentSt... |
import configparser
import os
from datetime import datetime
from pyspark.sql import SparkSession
from pyspark.sql.functions import col
from pyspark.sql.functions import dayofmonth
from pyspark.sql.functions import dayofweek
from pyspark.sql.functions import hour
from pyspark.sql.functions import monotonically_increasi... |
import os
import torch
import numpy as np
from torch import nn
import pytorch_lightning as pl
from torch.utils.data import DataLoader
from src.data.utils import _collate_fn, _collate_fn_multiclass
from src.models.model_helper import model_helper
from src.data.mixup import do_mixup, mixup_criterion
class ClassifierDat... |
import os
import shutil
import ctypes
def makepath(*args):
path = os.path.join(*args)
print('makepath:', path)
if not os.path.exists(path):
os.makedirs(path)
return path
def quotes(s):
return '"' + s + '"'
def cleanCopyTree(src, dst, **kwargs):
dirName = os.path.basename(src)
... |
# Copyright 2019 NVIDIA Corporation
#
# 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 wr... |
from Bio import Seq
import kleat.misc.settings as S
def reverse_complement(seq):
return str(Seq.Seq(seq).reverse_complement().upper())
# TODO: if prefer to drop dependency on biopython, test this function
# thoroughly
# return seq.translate(COMPLEMENT_DICT)[::-1]
def gen_clv_key_tuple(seqname, stra... |
import os
from io import StringIO
from textwrap import dedent
from unittest import mock
import unittest
from django.db import connections
from django.core.management import call_command
import pytest
from django_redshift_backend.base import BasePGDatabaseWrapper
from test_base import OperationTestBase
def norm_sql(... |
# Copyright 2008-2010 Nokia Siemens Networks Oyj
#
# 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... |
import torch
from type_system import INT, STRING, Arrow, Type
import type_system
from Predictions.models import RulesPredictor, BigramsPredictor
from pcfg import PCFG
from typing import Callable, List, Tuple
from dsl import DSL
from program import Program
def make_program_checker(dsl: DSL, examples) -> Callable[[Progr... |
# -*- coding: utf-8 -*-
"""This module provides access to planetary ephemerices in a manner consistent
with the rest of the brahe module.
"""
# Imports
import logging
import copy as copy
import math as math
import numpy as np
# Brahe Imports
from brahe.utils import logger
import brahe.constants as _constants
from... |
from django.db.models import Q, F
from django.shortcuts import get_object_or_404
from django.http import Http404
from .models import Anime, Survey, AnimeName
from datetime import datetime
from random import randint
from django.conf import settings
class AnimeUtil:
"""Class with various static utility methods rela... |
# Copyright 2017 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.
import os
import sys
_SHRINK_TO_FIT_CLONE = ('blink::ContiguousContainerBase::shrinkToFit() '
'[clone .part.1234] [clone .isra.2]')... |
# Copyright (c) 2020 Intel Corporation
#
# 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... |
from __future__ import absolute_import
import operator
from collections import OrderedDict, namedtuple
from functools import reduce
from ctypes import Structure, byref, c_double
from cgen import Struct, Value
from devito.ir.iet import (Expression, TimedList, FindNodes, Transformer,
FindAdj... |
import argparse
import os
import torch
import yaml
import numpy as np
import torch.nn.functional as F
import cv2
import config_folder as cf
from data_loaders.Chairs import Chairs
from data_loaders.kitti import KITTI
from data_loaders.sintel import Sintel
from data_loaders.KLens import KLens
from frame_utils import wr... |
"""
This file contains all MIDI Meta events.
Meta events are used in MIDI files to provide
metadata such as temp, track name, copyright info, ect.
TODO: Improve meta event descriptions!
"""
from ymidi.events.base import BaseMetaMesage
from ymidi.constants import CHANNEL_PREFIX, COPYRIGHT, CUE_POINT, INSTRUMENT, KEY_... |
from collections import deque
import sys
n = int(sys.stdin.readline())
graph = []
visited = [[False] * n for _ in range(n)]
for _ in range(n):
graph.append(list(map(int, sys.stdin.readline().split())))
x_coordinate = [-1, 0, 1, 0]
y_coordinate = [0, 1, 0, -1]
def bfs(x, y):
global count
queue = deque(... |
import config
import csv
import nav
import PyQt5.QtCore as QtCore
import PyQt5.QtWidgets as QtWidgets
class ExploreBar(QtWidgets.QLineEdit):
def __init__(self, explore_type):
super(ExploreBar, self).__init__()
self.setStyleSheet("background-color: rgba(0,0,0,0)")
self.setPlaceholderText(... |
"""Filters for assuring data integrity over an unreliable messaging channel.
Provides Filters which compute and check data integrity fields in headers
prepended to arbitrary data payloads (limited by payload length) to detect and
handle data corruption.
A CRCElement is defined as a data unit of the data integrity lay... |
import h5py
import numpy
import os
import scipy.linalg
import scipy.sparse
import unittest
from pyscf.pbc import gto, dft, df, tools
import afqmctools.hamiltonian.supercell as sc
from afqmctools.utils.linalg import get_ortho_ao
try:
from mpi4py import MPI
no_mpi = False
except ImportError:
no_mpi = True
cl... |
import keras
from keras import layers
from keras.layers import Input, Add, Dense, Activation, ZeroPadding2D
from keras.layers import BatchNormalization, Flatten, Conv2D
from keras.layers import MaxPooling2D, GlobalMaxPooling2D, AveragePooling2D
from keras.initializers import glorot_uniform
from keras.models import Mode... |
#!/usr/bin/env python3
import sys
import re
import json
import base64
import argparse
import urllib.request
class UnknowProtocolException(Exception):
pass
def get_host_ip():
# print("trying to get host ip address ...")
req = urllib.request.Request(url="https://www.cloudflare.com/cdn-cgi/trace")
with u... |
#!/usr/bin/env python3
import argparse
import glob
import json
import logging
import os
import platform
import struct
import sys
from datetime import datetime
from threading import Thread
sys.path.append(os.path.join(os.path.dirname(__file__), 'Porcupine/binding/python'))
from porcupine import Porcupine # noqa
log... |
"""
<NAME> Addon
Copyright (C) 2016 gujal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This pro... |
# -*- coding: utf-8 -*-
# Time : 2022/1/17 15:20
# Author : QIN2DIM
# Github : https://github.com/QIN2DIM
# Description:
import csv
from typing import List, Optional, Union, Dict
import cloudscraper
from bs4 import BeautifulSoup
from lxml import etree
from services.settings import logger
from services.u... |
"""
Metrics module
"""
from datetime import datetime, timezone
from typing import Dict, Union, Optional
from hopeit.server.logger import format_extra_values
from hopeit.app.context import EventContext
__all__ = ['metrics',
'stream_metrics',
'StreamStats']
def metrics(context: EventContext):
... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is govered by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
"""A servlet for project owners to create a new field def."""
import logging
import re
import t... |
import sys
# This module contains a variety of wrapper functions for miscellaneous test
# actions. This module may be deleted if the functions within all have a better
# location.
def wait_for_openstack_poller(cloud_name, args, wait=sys.maxsize, output=False):
import subprocess
from time import sleep
o... |
from django.template import Template, Context
from django.utils.translation import ugettext_lazy
from devilry.apps.core import models as core_models
class UserInfo(object):
def __init__(self, groupuserlookup, user):
self.groupuserlookup = groupuserlookup
self.user = user
@property
def ca... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
10a.py
~~~~~~
Advent of Code 2017 - Day 10: Knoth Hash
Part One
You come across some programs that are trying to implement a software
emulation of a hash based on knot-tying. The hash these programs are
implementing isn't very strong, but y... |
from database.models import PesticidalProteinDatabase, PesticidalProteinPrivateDatabase
from django.conf import settings
from django.core.files import File
from pathlib import Path
import os
import subprocess
import re
from naming_package import naming
import textwrap
import itertools
import tempfile
import shutil
NEE... |
import os
import sys
import time
import math
from lib.tools.other_tools import flat
from collections import OrderedDict
# This dictionary is to track the number of accepted and removed models at each Quality Control step
global_track_dt = OrderedDict()
def percentiles_from_counts(counts_dt, percentiles_range=None):
... |
from .base import BaseModel
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime
from info import db
# 用户收藏表,表示多对多关系
tb_user_collection = db.Table('info_user_collection',
db.Column('user_id', db.Integer, db.ForeignKey('blog_customer.id'), p... |
import pprint
import sys
from typing import Optional, Union
import cda_client
from cda_client.api.query_api import QueryApi
from cda_client.api_client import ApiClient
from cda_client.configuration import Configuration
from cda_client.model.query import Query
from cda_client.api.meta_api import MetaApi
__version__ = ... |
import argparse
import json
import os
import string
import time
import uuid
import boto3
greengrass_client = boto3.client("greengrassv2")
s3_client = boto3.client("s3")
sts_client = boto3.client("sts")
class ParseKwargs(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
... |
from random import random, randrange, choice
from math import exp
class Agent:
learning_rate = 0.1
discount_rate = 0.99
max_exploration_rate = 1
min_exploration_rate = 0.1
exploration_rate_decay = 0.001
def __init__(self):
self.action_space_size = None
self.state_space_size = ... |
#*- coding: utf-8 -*-
import unittest
import redis
from apps.oclib.client import Redis
from nose.tools import *
class RedisTestCase(unittest.TestCase):
def setUp(self):
self.r = Redis(host='localhost', port=6379)
self.setup_sorted_sets()
self.setup_sets()
def setup_so... |
# This file is part of Scapy
# Scapy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# any later version.
#
# Scapy is distributed in the hope that it will be useful,
# but ... |
# LXML required for CDATA tags
import lxml.etree as ET
# Used so we can say when the export was made in a user-readable way
import datetime
# Required to actually fetch the APPDATA directory
# We don't import all of os just because it has some dodgy methods
from os import getenv
from os.path import join
# Allow pe... |
#! /usr/bin/env python
from __future__ import print_function
import khmer
import screed
import argparse
from collections import OrderedDict
import sys
# graph settings
DEFAULT_KSIZE=31
NODEGRAPH_SIZE=8e8 # small, big is 2e8
# minhash settings
MH_SIZE_DIVISOR=50
MH_MIN_SIZE=5
MH_PRIME=9999999967
class Pathfinder(obje... |
from __future__ import unicode_literals
from django.db import models
from django.urls import reverse
class Settings(models.Model):
key = models.CharField(max_length=100, null=False, blank=False, primary_key=True)
value = models.TextField(blank=True, null=True)
class Meta:
ordering = ['key']
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020-2021 Alibaba Group Holding Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LI... |
import random
import os
import tensorflow.compat.v1 as tf
import tempfile
import twremat
def splice_op(op, input_map, control_inputs=None):
g = op.graph
node_def = tf.NodeDef()
node_def.CopyFrom(op.node_def)
node_def.name = g.unique_name(op.name + '_copy')
inputs = [input_map.get(x, x) for x in op... |
import os
import sys
import json
from glob import glob
from functools import wraps
from datetime import datetime
from flask import Flask, abort, flash, redirect, render_template, request, url_for, Response
from pymongo import MongoClient
from jinja2 import Markup
from forms import PageForm, LoginForm
if sys.version_... |
import numpy as np
import os
NUM_LABELS = {'ENZYMES':3, 'COLLAB':0, 'IMDBBINARY':0, 'IMDBMULTI':0, 'MUTAG':7, 'NCI1':37, 'NCI109':38, 'PROTEINS':3, 'PTC':22, 'DD':89}
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def load_dataset(ds_name):
"""
construct graphs and labels from datase... |
"""
Converts any type of FASTQ file to Sanger type and makes small adjustments if necessary.
usage: %prog [options]
-i, --input=i: Input FASTQ candidate file
-r, --origType=r: Original type
-a, --allOrNot=a: Whether or not to check all blocks
-b, --blocks=b: Number of blocks to check
-o, --output=o: Ou... |
import re
import sys
import glob
import serial
import subprocess
import time
from collections import namedtuple
#========================
# Utility functions
#========================
def sanitize_file_chars(string):
'''Quote a string so it can be used as an argument in a posix shell
According to: http... |
# Copyright 2017 phData Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
import pytest
from app import schemas, utils
@pytest.mark.parametrize(
"ip,allowed_networks,expected",
[
("192.168.1.2", [], True),
("192.168.1.2", ["192.168.1.0/24"], True),
("192.168.1", ["192.168.1.0/24"], False),
("192.168.1.4", ["192.168.2.0/24", "192.168.3.0/24"], False),... |
import numpy as np
import threading
import time
import LegTrajectory as lt
import IK
import TimerIMU as ti
import DynamixelController as dc
class quadrupedGait():
def __init__(self, _leg_centers, _leg_start_states, _body_h, _leg_up_h, _h_offset, _T, _dt, _classIMU):
self.leg_center = _leg_centers
... |
from math import sqrt, log
import numpy
import gzip
import sys
def read_fasta(fname, whole_id=True):
"""
Read a fasta file and return a hash.
If wholeId is set to false only the first part of the ID
(upto the first white space) is returned
"""
try:
if fname.endswith('.gz'):
... |
import numpy as np
import pandas as pd
import lightgbm as lgb
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, roc_auc_score
from sklearn.impute import SimpleImputer
from pandarallel import pandarallel
pandarallel.initialize()
df = pd.read_csv('/home/tonne/code/au... |
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring
"""
Sign CSRs using the ACMEv2 protocol
:depends: cryptography
:depends: acme
"""
import hashlib
import json
import logging
import os
from collections import defaultdict
from datetime import datetime, timedelta
from salt.exceptions import SaltConfiguration... |
#!/usr/bin/env python3
#
# 必要工具套件:
# * pylint
# * setuptools
# * wheel
# * virtualenv
# * twine
# * pyenv or pyenv-win
import configparser
import os
import re
import shutil
import subprocess
import sys
import platform
def get_wheel(platname='any', production=False):
""" 製作 wheel 檔案與取得檔名 """
wheel = False
... |
from http import HTTPStatus
from litespeed import add_websocket, App, register_error_page, render, route, serve, start_with_args, WebServer
from litespeed.error import ResponseError
from litespeed.utils import Request
"""Any function with a route decorator must follow one of the following return patterns:
render(file... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 10 11:46:58 2017
@author: yannwork
THIS CODE HAS THE DESCRIPTION OF THE IZHIKEVICH MODEL WITH 5 PARAMETERS or 9 PARAMETERS
"""
#Imports the print function from Python3.
from __future__ import print_function
#Imports the modf function.
from math im... |
import configparser
import datetime
import shutil
from dataclasses import dataclass
from pathlib import Path
from PIL import Image
from testfixtures import TempDirectory
import rivals_workshop_assistant.updating
from rivals_workshop_assistant import assistant_config_mod
from rivals_workshop_assistant.script_mod impor... |
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
#https://www.kaggle.com/tanumoynandy/sarcasm-detection-rnn-lstm <-- HOME WORK
import num... |
import sys
import time
import random
import numpy as np
from collections import deque
from gomoku import Gomoku
from mcts import MCTS
from neural_network import Residual_CNN, Simple_CNN
#======================
# Configuration
#======================
# 8x8
game_board_width = 8
mcts_playout_itermax_train = 400
mcts_play... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
# from https://amaarora.github.io/2020/08/30/gempool.html
class GeM(nn.Module):
def __init__(self, p=3):
super(GeM, self).__init__()
self.p = p
self.eps = 1e-6
def forward(self, x):
return self.gem... |
################################################################################
# The Sandbox Libraries (Python) Test Suite 0 (Dependencies) #
# #
# Copyright (C) 2004-2009, 2011-2013 <NAME>, <EMAIL> #
# All rights... |
import click, yaml, os, logging
from kedro.io import DataCatalog
from kedro.runner import SequentialRunner
from ffsc.pipeline.pipeline import get_pipeline as get_base_pipeline
from ffsc.flow.flow_pipeline import get_pipeline as get_flow_pipeline
from ffsc.communities.community_pipeline import get_pipeline as get_comm... |
import torch
import torch.nn as nn
from collections import namedtuple
import matplotlib.pyplot as plt
import numpy as np
from scipy import interpolate
BaseLayer = namedtuple('BaseLayer', ['kernel_size', 'stride', 'dilation', 'padding',
'input_size', 'output_size', 'receptive_field'... |
from typing import Callable
from typing import Dict
from typing import Iterable
from typing import List
from typing import Optional
from libcloud.storage.types import ObjectDoesNotExistError
from requests import RequestException
from requests import post as http_post
from opwen_email_server.constants import events
fr... |
import matplotlib.pyplot as plt
import os.path
import numpy as np
from numpy.testing import assert_allclose, assert_equal
import xdesign as xd
from xdesign.geometry import *
from xdesign.acquisition import beamcirc, beampoly, Probe
# Nonintersecting beams
def test_beamcirc_nonintersecting_top():
circ = Circle(Poi... |
#!/usr/bin/env python3
"""
Author: <NAME> (<EMAIL>)
"""
import multiprocessing.pool as mpp
import scipy.io as io
import numpy as np
from PIL import Image
import torch
import torch.nn.functional as F
import torch.nn as nn
import os
import glob
import shutil
import os.path as osp
import argparse
import sys
import time
... |
from django.core.management import CommandError
from pyfcm import FCMNotification
from .settings import FCM_DJANGO_SETTINGS as SETTINGS
def fcm_send_message(registration_id,
title=None,
body=None,
icon=None,
data=None,
... |
from dataclasses import dataclass
from datetime import datetime, timezone
import json
from django.contrib.auth import get_user_model
from django.db import models
from fernet_fields import EncryptedTextField
from aws_environments.constants import InfraStatus
from common.models import BaseModel
from infra_executors.uti... |
#!/usr/bin/env python3
import sys
if __name__ == "__main__":
# <https://github.com/python/cpython/blob/v3.9.5/Modules/main.c#L195>
# <https://github.com/python/cpython/blob/v3.9.5/Python/sysmodule.c#L2694-L2695>
# <https://github.com/python/cpython/blob/v3.9.5/Python/sysmodule.c#L2706-L2707>
print(f"Python {s... |
import pandas as pd
import os
import itertools
import numpy as np
from datetime import datetime
import logging
logging.getLogger('tensorflow').disabled = True
import tensorflow as tf
from load_data import DataLoader
from train import train
from config import EXPORT_DIR, SAMPLE_SETS
# Do not display info messages for... |
import time
import csv
from pathlib import Path
import spotipy
from flask import redirect, session
import os
from dotenv import load_dotenv
from spotipy import SpotifyOAuth
# read env variables from .env file
load_dotenv()
CLIENT_ID = os.getenv('CLIENT_ID')
CLIENT_SECRET = os.getenv('CLIENT_SECRET')
# spotify urls
S... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.