text stringlengths 3.07k 22.1k |
|---|
# -*- coding: utf-8 -*-
import os
import os.path
import glob
import multiprocessing
import nibabel as nib
from xlwt import Workbook
import argparse
import numpy as np
import math
import medpy
from medpy.metric.binary import hd
def nifti_to_array(filename):
nii = nib.load(filename)
return (nii.get_data())
... |
import re, pywikibot, requests
import toolforge
from datetime import datetime
site = pywikibot.Site('et', "wikipedia")
conn = toolforge.connect('etwiki_p')
def encode_if_necessary(b):
if type(b) is bytes:
return b.decode('utf8')
return b
def run_query(sqlquery):
#query = query.encode('utf-8')
#pr... |
import unittest
from hypothesis import given
import hypothesis.strategies as st
import pytest
import curver
from curver.kernel.decorators import memoize # Special import needed for decorating.
TRIANGULATIONS = {
(0, 3): '3_p',
(0, 4): '6_JDky1',
(0, 5): '9_ZFO4OuIV',
(0, 6): 'c_ZlgeM906o-354',
... |
# -*- coding: utf-8 -*-
import subprocess
import re
import codecs
import time
class WiFiScanner():
"""iw-based Wi-Fi networks scanner"""
def __init__(self, interface):
self.interface = interface
def scan(self, dump_only=False):
'''Parsing iw scan results'''
def handle_network(line... |
import numpy as np
import matplotlib.image as mpimg # read image
import matplotlib.pyplot as plt # plot image
import tkinter as tk # GUI design
from PIL import Image # used for save image
from numpy.fft import fft2, ifft2, fftshift, ifftshift # fourier transform
# Set information of GUI
window = tk.Tk()
w... |
"""Implementation of the OrthoANI algorithm for nucleotide identity measurement.
"""
import collections
import contextlib
import decimal
import io
import os
import shlex
import subprocess
import typing
from subprocess import PIPE, DEVNULL
from typing import Dict, List, Iterator, Iterable, Tuple, Union
try:
from o... |
import torch
from itertools import combinations
eps4log = 1e-16#eps to avoid log(0)
def log_prb_labels(x, ls):
"""
x=log(P) is the log probability tensor of shape
(number_of_classes + 1, other dimensions like height, width, time, ...)
ls is a list of distinct labels in range [0, number_of_classes... |
#!/usr/bin/env python3
#
# pre_commit.py
"""
Sphinx extension to show examples of ``.pre-commit-config.yaml`` configuration.
.. versionadded:: 1.6.0
.. extensions:: sphinx_toolbox.pre_commit
Usage
------
.. rst:directive:: pre-commit
Directive which shows an example snippet of ``.pre-commit-config.yaml``.
.. r... |
import unittest
from typing import cast, Generic, Optional, List, TypeVar
from crosshair.condition_parser import *
class Foo:
"""A thingy.
Examples::
>>> 'blah'
'blah'
inv:: self.x >= 0
inv:
# a blank line with no indent is ok:
self.y >= 0
notasection:
... |
import os
from random import randint
from libqtile import widget
from libqtile.config import Key, Match
from libqtile.lazy import lazy
home = os.path.expanduser('~')
#### Groups (Workspace like) ####
group_names = [
("WWW", {
'label': '\uf269',
'layout': 'monadtall',
'key':'1'}),
("W... |
from typing import Any, Callable, Dict, List, NoReturn, Optional, Union, cast
from ..language import (
DirectiveDefinitionNode,
DirectiveLocation,
DocumentNode,
EnumTypeDefinitionNode,
EnumValueDefinitionNode,
FieldDefinitionNode,
InputObjectTypeDefinitionNode,
InputValueDefinitionNode,... |
# =================================
# Main script for training a simple
# feed forward DNN
# =================================
import numpy as np
import tensorflow as tf
import argparse
import matplotlib.pyplot as plt
from util import name_and_path_util
from util.datahandler import DataHandler
from util.records impor... |
import time
import pytest
import subprocess
import boto3
from e2e.utils.config import metadata
from e2e.utils.cognito_bootstrap.common import load_cfg, write_cfg
from e2e.fixtures.kustomize import kustomize, configure_manifests
from e2e.conftest import region
from e2e.fixtures.cluster import cluster
from e2e.fixtures.... |
from lxml import etree
from enum import Enum
import sys
FileReaderStatus = Enum('FileReaderStatus', 'MODULE_FOUND MODULE_NOT_FOUND')
ParameterTypes = Enum('ParameterTypes', 'INTEGER FLOAT BOOLEAN STRING FUNCTION ENUMERATION')
ReferenceTypes = Enum('ReferenceTypes', 'SIMPLE_REFERENCE CHOICE_REFERENCE FOREIGN_REFERENCE ... |
import argparse
import json
import multiprocessing as mp
import os
import re
import shutil
import sys
import tarfile
import unicodedata
from dataclasses import dataclass
from datetime import date, timedelta, datetime
from os import path, makedirs, listdir
from typing import List, Dict, Any
import requests
def parse_... |
from transformers import pipeline
from sentence_transformers import SentenceTransformer, util
from SSIM_PIL import compare_ssim
from PIL import Image
import numpy as np
import pandas as pd
import random
import cv2
from pyjarowinkler import distance
from strsimpy.cosine import Cosine
from ux import outputHTML
from ml im... |
# -*- coding: utf-8 -*-
from __future__ import division, absolute_import, print_function, unicode_literals
from collections import defaultdict
from django.utils import six
from .util import DoesNotExist
from .mappings import OldValues
from .descriptors import _inject_descriptors
__all__ = ('SaveTheChange', 'Upda... |
import json
import os
import sys
import pandas.io.sql as psql
import requests
crypto_tools_dir = os.getcwd().split('/scripts/')[0] + '/scripts/'
sys.path.append(crypto_tools_dir)
from crypto_tools import *
class PopulateKraken(object):
"""
"""
def __init__(self):
"""
"""
self.po... |
import numpy as np
from scipy.optimize import check_grad
from deep_rlsp.solvers.value_iter import value_iter, evaluate_policy
from deep_rlsp.solvers.ppo import PPOSolver
from deep_rlsp.util.parameter_checks import check_in
def compute_g(mdp, policy, p_0, T, d_last_step_list, expected_features_list):
nS, nA, nF =... |
"""
Demonstration of the GazeTracking library.
Check the README.md for complete documentation.
"""
import cv2
try:
from EyeDear import gaze_tracking
except:
print("EyeDear folder not found")
from gaze_tracking import GazeTracking
from datetime import datetime
from datetime import timedelta
from tkinter import ... |
import argparse
import cv2
import datetime
import math
import numpy as np
import os
import PIL
import random
from scipy.spatial.distance import cdist
import shutil
import sys
import torch
import torch.nn.init
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision.datasets... |
# Copyright 2015 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, softw... |
##
#
# @author <NAME>, <NAME>, Annecy, FRANCE
# @brief a set of generic functions for data management
import numpy as np
from random import randrange
def average_above_zero(table):
"""
make average from a table of non-null positiv value
Arg:
table : a list of numeric values
return:
he... |
import math
from typing import Callable, Union, Dict, Tuple, Optional
import torch
import torch.utils.data
# import Dataset, DataLoader
class InpData(torch.utils.data.Dataset):
""""""
def __init__(self, X, Y):
# self.X = torch.from_numpy(X).float()
# self.Y = torch.from_numpy(Y).float()
... |
import numpy as np
import cv2
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.models import Model
import gc
tf.compat.v1.disable_eager_execution()
def normalize(x):
"""Utility function to normalize a tensor by its L2 norm"""
retu... |
import json
import logging
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import skfuzzy as fuzz
import sys
from cerberus import Validator
from types import SimpleNamespace
CONFIG_FILE = "./resources/config/config.json"
ANTE_CONFIG_FILE = "./resources/config/antecedent_config.json"
CONFIG_VALID... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020-2021 by <NAME>. All rights reserved. This file is part
# of the Robot Operating System project, released under the MIT License. Please
# see the LICENSE file included as part of this package.
#
# author: <NAME>
# created: 2020-03-16
# modified: 2020-0... |
from flask import Flask, render_template, request, redirect, make_response, send_from_directory, session, jsonify
from datetime import datetime, timezone
from pymongo import MongoClient
from bson.objectid import ObjectId
import logging
import bcrypt
app = Flask(__name__)
app.config['SECRET_KEY'] = '364S1947RO713085892... |
"""Resolwe models hydrate utils."""
import copy
import os
import re
from pathlib import Path
from django.core.exceptions import ValidationError
from resolwe.flow.utils import iterate_fields
def _hydrate_values(output, output_schema, data):
"""Hydrate basic:file and basic:json values.
Find fields with basic... |
from flask import Blueprint
from flask import render_template, redirect, url_for, jsonify, request
import requests, json
from nltk.corpus import stopwords
from nltk.tokenize import wordpunct_tokenize
from nltk.stem.snowball import SnowballStemmer
from nltk.stem.wordnet import WordNetLemmatizer
# Databases
from confi... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime, timedelta
from django.contrib.auth.models import User
from django.db import models
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
import operator
class UserProfile(models.Model):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ===============================================================
# Copyright (C) 2019 HuangYk.
# Licensed under The MIT Lincese.
#
# Filename : densenet3d.py
# Author : HuangYK
# Last Modified: 2019-05-30 11:00
# Description :
# ================================... |
"""
Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
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/L... |
"""[Unused] Test classificaiton using numpy to divide tiles.
Please use test_classification_speed.py in which tensorflow is used
to divide tiles.
This script is not deleted to serve as a reference on how to use
numpy to divide tiles when memory are constraints.
"""
from __future__ import absolute_import, division, pr... |
##############
# basic python
# v0.0.7
##############
##########################
# how to read this chapter
##########################
1 + 1
##########
# comments
##########
# print the result of 1 + 1
print(1 + 1)
###########
# variables
###########
pts_per_passing_td = 4
pts_per_passing_td
3*pts_per_passing_td
... |
# RevKit: A Toolkit for Reversible Circuit Design (www.revkit.org)
# Copyright (C) 2009-2011 The RevKit Developers <<EMAIL>>
#
# 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 o... |
# coding=utf-8
"""Application Definition"""
from os import fsdecode
from accelpy._common import yaml_read, yaml_write
from accelpy.exceptions import ConfigurationException
# Application definition format
FORMAT = {
'application': {
'_node': dict,
'name': dict(
required=True,
... |
"""
Build indexes for searching the Tool Shed.
Run this script from the root folder, example:
$ python scripts/tool_shed/build_ts_whoosh_index.py -c config/tool_shed.yml
Make sure you adjust your Toolshed config to:
* turn on searching with "toolshed_search_on"
* specify "whoosh_index_dir" where the indexes will be... |
import os
import argparse
import random
import numpy as np
import tensorflow as tf
from collections import namedtuple
from pathlib import Path
from model.model_manager import ModelManager
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
WordEmbedding = namedtuple(
'WordEmbedding',
['name', 'train_file', 'validatio... |
import time
import numpy as np
from numpy import mean
from numpy import std
from numpy import max
from numpy import min
from numpy import empty
from numpy import cov
from numpy import argmax
from numpy import argmin
import numpy.linalg as LA
import h5py
import math
from math import sqrt
import numba
from numba import j... |
# LEAVE TRAVEL COMPENSATION
from .utils import *
def handle_ltc_admin(request):
if 'ltc_assign_form' in request.POST:
app_id = request.POST.get('app_id')
status = request.POST.get('status')
reviewer = request.POST.get('reviewer_id')
designation = request.POST.get('reviewer_design'... |
import base64
import hashlib
import json
import logging
import requests
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.core.exceptions import SuspiciousOperation, ImproperlyConfigured
try:
from django.urls import reverse
except ImportError:
# Dj... |
"""
lsh.py
Algorithms based on 'Mining of Massive Datasets'
http://infolab.stanford.edu/~ullman/mmds/ch3.pdf - Section 3.4
"""
from collections import defaultdict
import multiprocessing as mp
import random
import pyhash
import Levenshtein
from jsonleveldb import JsonLevelDB
from .unionfind import UnionFind
class S... |
import argparse
import glob
from pathlib import Path
import rospy
from sensor_msgs.msg import PointCloud2, PointCloud
from sensor_msgs import point_cloud2
from visualization_msgs.msg import MarkerArray
from visualization_msgs.msg import Marker
from scipy.spatial.transform import Rotation as R
import time
try:
i... |
import math
import random
import os
import sys
import numpy as np
import torch
from torch import nn, autograd, optim
from torch.nn import functional as F
from torch.utils import data
import torch.distributed as dist
from torchvision import transforms, utils
from torchvision import utils as tvutils
from tq... |
# Copyright 2019, 2020 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... |
import numpy as np
import pytest
import rasterio
from rasterio import windows
DATA_WINDOW = ((3, 5), (2, 6))
def test_index():
with rasterio.open('tests/data/RGB.byte.tif') as src:
left, bottom, right, top = src.bounds
assert src.index(left, top) == (0, 0)
assert src.index(right, top) ==... |
"""
Shared ETL (extract, transform, load) code for fetching and loading data from HCA DSS.
The main entry point is the DSSExtractor.extract() function, which takes optional transform and load callbacks that
will be invoked for each bundle fetched.
Performance gains come from amortizing latency for network calls to retr... |
# -*- coding: latin-1 -*-
# This program is public domain
# Author: <NAME>
"""
Define unit conversion support for NeXus style units.
The unit format is somewhat complicated. There are variant spellings
and incorrect capitalization to worry about, as well as forms such as
"mili*metre" and "1e-7 seconds".
This is a mi... |
# -*- coding: utf-8 -*-
#####################################################################################################################
# #
# Парсер новостных разделов Ямальских СМИ. ... |
# author: Bartlomiej "furas" Burek (https://blog.furas.pl)
# date: 2022.05.10
# [python - OpenCV (-215:Assertion failed) !_src.empty() in function 'cvtColor - Stack Overflow](https://stackoverflow.com/questions/60551469/opencv-215assertion-failed-src-empty-in-function-cvtcolor/60551714)
# Google Colab: https://colab.r... |
"""Helpful functions for ATDA."""
import os
import random
from math import log
import torch
import torch.backends.cudnn as cudnn
import torch.optim as optim
from torch.autograd import Variable
from datasets import get_mnist, get_mnist_m, get_svhn, get_usps
from misc import config as cfg
def make_variable(tensor, v... |
import unittest
import math
import numpy as np
from nose.tools import assert_equal
from networkx.classes.digraph import DiGraph
from scipy.spatial.distance import euclidean
from .lst import lst_dag, dp_dag_general, \
round_edge_weights_by_multiplying, \
make_variance_cost_func,\
get_all_nodes
from .dag_uti... |
import os
import sys
BASE_DIR = os.path.dirname(__file__)
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, '../utils'))
#import tensorflow as tf
import numpy as np
import tf_util
from pointnet_util import pointnet_sa_module, pointnet_fp_module
from loss import *
import tensorflow.compat.v1 as tf
tf.dis... |
import numpy as np
import pandas as pd
from tkinter import *
from tkinter.ttk import *
from tkinter import filedialog
from cctbx import crystal, miller
from cctbx.array_family import flex
from iotbx.reflection_file_reader import any_reflection_file
class GroupReflectionsGUI(LabelFrame):
"""A GUI frame for reflec... |
# encoding: utf8
"""
SailUI - GPS data from serial port parsed and send to InfluxDB
MIT License
Copyright (c) 2021 HadrienLG
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, ... |
# Copyright (c) 2022. Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... |
import itertools
import json
import numpy as np
import scipy.stats as stats
import trilearn.graph.decomposable
import trilearn.graph.junction_tree as libj
import trilearn.auxiliary_functions as aux
from trilearn.distributions import dirichlet
def ll_complete_set_ratio(comp, alpha, counts, data, levels, cache):
... |
#!/bin/env python
# coding: utf-8
"""
KPHMMER でそれぞれの API を叩いた回数を表示するバージョン
$ python3 KPHMMER_API-access.py で普通の使い方
"""
import sys
import traceback
from collections import defaultdict
from KPHMMER import (Analysis, Config, Convert, Query, Search,
determine_submethod, get_args)
from .util import che... |
import itertools as it
import numpy as np
from vtk_parsing import parse_file_vtk
def voxel(edge_length, center):
"""
returns the data which is needed for plotting the faces of one voxel (a cube)
:param edge_length: edge length of the cube
:param center: center of gravity of the cube
:return: list ... |
#!/usr/bin/env python3
"""
01/02/2018 <NAME> - CertStuff Version 1.0
- Check AWS IAM imported certs
- Check AWS ACM issued certs
- Check Akamai production certs
"""
# TODO: Add expire date reminder
import boto3
import argparse
import cps
import os
import re
import datetime
import pytz
from tzlocal import... |
# Copyright 2021 Red Hat, 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 agre... |
import os
import sys
import requests as r
import time
import json
from signal import signal, SIGINT
import threading
from datetime import datetime
import math
import subprocess
import multiprocessing
from multiprocessing import Manager, Value
from ctypes import c_char_p
from cryptography.hazmat.primitive... |
#完成主题数据的维护和更新
import datetime
from flask import Blueprint, render_template,abort,request,redirect,url_for,flash,session,g
from sqlalchemy import join,outerjoin
from pythonnewbbs import db
from pythonnewbbs.auth import login_required
from pythonnewbbs.db import Categories,Topics,Posts,Users
#声明蓝图
bp =Blueprint("blog",... |
import glob, os
import numpy as np
import csv
from matplotlib import pyplot
import scipy.signal
from scipy.optimize import curve_fit
import peakutils
from lmfit.models import PseudoVoigtModel
import math
import traceback
from collections import OrderedDict
path_to_folder = "..\\CZTS_data\\CZTS_111116\\B"
... |
if __name__ == "__main__":
import sys
sys.path.append("..")
del sys
# note that this is actually used since importing it sets up the logging
# pylint: disable=unused-import
import fenalib.logging_setup as logging_setup
import os
import json
import logging
from types import MappingProxyType
fr... |
#!/usr/bin/env python3
import kornia as kn
import numpy as np
import torch
import torch.nn.functional as F
from scipy.spatial.transform import Rotation as R
from .utils import coord_list_grid_sample
class Projector():
@staticmethod
def pix2world(points, depth_map, poses, Ks):
"""Unprojects pixels t... |
import os
import logging
import time
from torch.backends import cudnn
from utils.logger import setup_logger
from datasets import make_dataloader
from model import make_model
from solver import make_optimizer, WarmupMultiStepLR
from loss import make_loss
import random
import torch
import numpy as np
import argparse
from... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/lic... |
"""Cloudify 6.2 to 6.3 DB migration
Revision ID: <KEY>
Revises: <PASSWORD>
Create Date: 2021-08-30 16:11:00
"""
import sqlalchemy as sa
from alembic import op
from manager_rest.storage.models_base import JSONString, UTCDateTime
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<PASSWORD>'... |
from __future__ import print_function
import argparse
import os
from os import mkdir
from os.path import exists
import numpy as np
import tensorflow as tf
from keras import backend as K
from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, TensorBoard
from keras.optimizers import Adam
import utils
from mol... |
#!/usr/bin/env python
"""
Small example of a library implementing interaction with Moscow Exchange ISS server.
Version: 1.2
Developed for Python 2.6
@copyright: 2016 by MOEX
"""
import urllib.request as urllib2
# import base64
import http.cookiejar as cookielib
import json
import requests as r
from ... |
import tensorflow as tf
from tensorflow.keras import Model
import nalp.utils.logging as l
logger = l.get_logger(__name__)
class Discriminator(Model):
"""A Discriminator class is responsible for easily-implementing the discriminative part of
a neural network, when custom training or additional sets are not n... |
# this script assumes the image have been brain extracted
import os.path
from os import path
# set number of threads - this should be optimized per compute instance
os.environ["TF_NUM_INTEROP_THREADS"] = "8"
os.environ["TF_NUM_INTRAOP_THREADS"] = "8"
os.environ["ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS"] = "8"
import ant... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Detection Training Script.
This scripts reads a given config file and runs the training or evaluation.
It is an entry point that is made to train standard models in detectron2.
In order to let one script support training of many models,
this s... |
"""
This car controls the linear acceleration and turning rate.
"""
import torch
import numpy as np
import scipy.integrate
import gurobipy
import neural_network_lyapunov.gurobi_torch_mip as gurobi_torch_mip
import neural_network_lyapunov.relu_to_optimization as relu_to_optimization
import neural_network_lyapunov.relu_s... |
"""
This module is to batch convert single band probability maps in S3 folder to
a RGB color-relief probability maps to another S3 folder before register them
to raster foundry.
Author: <NAME>
"""
import os
import yaml
import boto3
import tempfile
import subprocess
from subprocess import check_call
from matplotlib.cm i... |
"""
Written by Robik
"""
import torch, os
import numpy as np
def randint(max_val, num_samples):
rand_vals = {}
_num_samples = min(max_val, num_samples)
while True:
_rand_vals = np.random.randint(0, max_val, num_samples)
for r in _rand_vals:
rand_vals[r] = r
if len(r... |
import logging
import os.path
from datetime import timedelta
from os import walk
from random import random
from re import search
from string import letters
from yaml import safe_load
from coyote.utils.scheduler import schedule
# steal celery's log format, but change name for distinction in messages
logging.basicCon... |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http... |
from copy import deepcopy
from dataclasses import dataclass
from typing import Any, List, Optional
import pandas as pd
from cryptocompsdk.general.parse import (
from_int,
from_none,
from_union,
from_float,
from_str,
to_float,
from_bool,
from_list,
to_class,
)
from cryptocompsdk.res... |
import logging
from pathlib import Path
import numpy as np
from keras import backend as K
from keras.callbacks import Callback, EarlyStopping, CSVLogger, ModelCheckpoint, TensorBoard, LearningRateScheduler
from sklearn.metrics import f1_score, precision_score, recall_score, classification_report, confusion_matrix
imp... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import * # noqa: F401,F403 pylint: disable=redefined-builtin,wildcard-import,unused-wildcard-import
from future import standard_l... |
# import minpy.numpy as np
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from torch.autograd import Function
import cv2
class UnNormalizer(object):
def __init__(self, mean=None, std=None):
if mean == None:
self.mean = [0.485, 0.456, 0.406]
... |
import torch
from torch import nn
from torch.nn import init
from torch.nn import functional as F
from transformers import BertModel
from config import Baseline_LSTMConfig
from config import Baseline_BertConfig
from config import Baseline_CNNConfig
from tools import load_bert_vocab_embedding_vec
class Baseline_Model_B... |
# Purpose: Get starting funds or end game
# Parameters: CFG parser (ConfigParser), CFG file path (string), controller (module)
# Returns: Starting funds (integer)
def Start(parser, saveFile, controller):
# Read CFG
parser.read(saveFile)
# Retrieve value of funds left over from previous game
lastFunds = ... |
"Unit test for the game-board class"
import unittest
from .board import *
def place_stone(board, color, x, y):
board[x,y] = color
class TestBoard(unittest.TestCase):
def test_creation(self):
width = 20
height = 40
board = Board(height, width)
self.assertEqual(board.shape, (he... |
from __future__ import absolute_import, print_function
from __future__ import unicode_literals
from collections import defaultdict
from datetime import datetime
import six
from django.core.management.base import BaseCommand
from casexml.apps.case.xform import get_case_updates
from corehq.apps.commtrack.processing im... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------------------------
import unittest
import numpy as np... |
import json
import os
import random
from result import Err, Ok, Result
import time
from typing import Optional
import uuid
from lib.gluster.lib import run_command
from lib.gluster.peer import Peer
from lib.gluster.volume import volume_info
from charmhelpers.fetch import apt_install
from charmhelpers.core.host import s... |
#!/usr/bin/env python
"""
protoc plugin to render jsonschema & cerebus documents
"""
import itertools
import json
import os
import sys
from collections import OrderedDict
from google.protobuf.compiler import plugin_pb2 as plugin
from google.protobuf.descriptor_pb2 import DescriptorProto, EnumDescriptorProto
from goo... |
import locale
import os
import re
import urllib.request
import urllib.parse
from datetime import datetime
from tkinter import Tk, Menu, messagebox, END, Toplevel, Frame, TOP, Label, LEFT, Entry, Scrollbar, Y, RIGHT, Listbox, \
BOTTOM, BOTH, Spinbox
from bs4 import BeautifulSoup
from whoosh.fields import Schema, TE... |
import datetime
from datetime import date as std_date
from enum import Enum, auto
from typing import Dict, Optional
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models import F
from ctrack.caf.models import CAF
from ctrack.organisations.models import Person
from ctrack.us... |
from collections import namedtuple
from django.db import connection
from django.db.models import Max
from dateutil.relativedelta import relativedelta
from dateutil.parser import parse as parse_date
import numpy
from frontend.models import NCSOConcession, Presentation, TariffPrice
from matrixstore.db import get_db, g... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import config
import datapane as dp
import logging
import pandas as pd
import plotly.express as px
import plotly.figure_factory as ff
import plotly.graph_objs as go
import streamlit as st
import utils
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(mes... |
from hkube_python_wrapper.communication.streaming.StreamingManager import StreamingManager
from hkube_python_wrapper.communication.streaming.MessageListener import MessageListener
from hkube_python_wrapper.communication.streaming.MessageProducer import MessageProducer
import time
parsedFlows = {
'analyze': [{'sour... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# 项目基于https://github.com/Jack-Cherish/python-spider/blob/master/Netease/Netease.py
import os
import re
import sys
import json
import time
import codecs
import base64
import asyncio
import aiohttp
import chardet
import aiofiles
import binascii
from http import cookiejar
from... |
# GPLv3 License
#
# Copyright (C) 2020 Ubisoft
#
# 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 2 of the License, or
# (at your option) any later version.
#
# This program is dis... |
from . import user
from . import exception, utils
import requests
import re
import json
from .utils import Get, Post
import math
headers = utils.default_headers
apis = utils.get_apis()
class SendDynamic:
def __init__(self, text: str, verify: utils.Verify):
self.verify = verify
self._text = ""
... |
'''
REQUIREMENTS:
pip install requests
AUTHORS:
<NAME>
<NAME>
<NAME>
'''
import requests
import os
import json
import shutil
import traceback
CATEGORIES = {}
BATCHES = {}
# url = 'https://api.github.com/repos/cepdnaclk/projects/git/blobs/2166c8eba0801b62b539a23576a7b6fc46e7f4f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.