text stringlengths 3.07k 12.6k |
|---|
#!/usr/bin/python3.9
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 LinYulong. All Rights Reserved
#
# @Time : 2021/11/14
# @Author : LinYulong
# @Descriptor: 混淆矩阵
class ConfusionMatrix:
tpr_ = 0.0
tnr_ = 0.0
accuracy_ = 0.0
precision_ = 0.0
recall_ = 0.0
f_measure_ = 0.0
def __init__... |
import os
import cv2
cv2.setNumThreads(0)
cv2.ocl.setUseOpenCL(False)
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
# torch.backends.cudnn.benchmark = True
import tqdm
from augmentations.tta import transforms as TTA
from augmentations.transforms import ToTensor
fro... |
""" A view containing the contents of a Python shell namespace. """
from __future__ import print_function
# Enthought library imports.
from envisage.plugins.python_shell.api import IPythonShell
from envisage.plugins.ipython_shell.api import INamespaceView
from pyface.workbench.api import View
from traits.api import P... |
import argparse
import time
import re
import os
import platform
import zipfile
import stat
import ssl
import wget
from tqdm import tqdm
from selenium import webdriver
from urllib.request import urlopen, Request
from urllib.parse import quote
DOWNLOAD_ROOT = 'downloaded_images'
def towards_end_of_scroll(browser):
... |
import sys
from _fatcore import ffi, lib
from ..handle import Handle
from .. import error
from . import signal
from . import stream
from . import pipe
uv_get_pyobj = lib.fatuv_get_pyobj
uv_set_pyobj = lib.fatuv_set_pyobj
uv_process_new = lib.fatuv_process_new
uv_process_delete = lib.fatuv_process_delete
... |
#!/usr/bin/python3
# encoding='utf-8'
# @time:2021/9/22 11:13
import random
print("*****************************")
print("* 中国工商银行 *")
print("* 账户管理系统 *")
print("* V1.0 *")
print("*****************************")
print("* *")
print("* 1.开户 ... |
#!/usr/bin/env python
"""
Classes:
Game: The game object which holds utility methods for printing the game board,
calculating winner, making moves
AI: The AI player
"""
from random import randint
from typing import List
import argparse
class Game():
"""
Class for the game itself
"""
# ... |
#!/usr/bin/env python
# coding: utf-8
"""
Marcel is a french wrapper around the docker CLI, intended as a drop-in
replacement of docker, for the future french sovereign operating system.
"""
import subprocess
import sys
import re
import os
import six
from os.path import exists, join
__version__ = '0.1.0'
TRANSLATI... |
from datetime import date
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.utils.timezone import now
class SideBarMenuExample(models.Model):
#HTML in help text is allowed in yawd-admin
title = models.CharField(... |
import re
from bs4 import BeautifulSoup
import logging
from crawl.connect_and_execute_script import ConnectAndExecuteScript
from parse.table import parse_tables
from crawl.drivers_manager import DriversManager
from util.common import merge_dict, to_strips
from parse.xpath import parse_by_xpath
from crawl.connect import... |
"""This module holds the embeddings ``Process``es."""
import os
from collections.abc import ValuesView
from copy import deepcopy
from dataclasses import dataclass, field
from typing import Dict, Optional
import numpy as np
from boltons.cacheutils import cachedproperty
from cltk.core.cltk_logger import logger
from cl... |
import matplotlib.pyplot as plt
import numpy as np
import math
from math import pi, factorial
from pprint import pprint
from numpy import absolute, vdot
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister, execute, Aer, transpile
#from qiskit.tools.visualization import circuit_drawer, plot_circuit_l... |
import r2pipe
import time
import sys
import os
search_scalar = '0x186' # TODO: currently HARD CODED, add argument parameter
def argument_parsing():
if len(sys.argv) < 2:
print('❌ Usage: python {} libflutter.so'.format(sys.argv[0]))
exit(-1)
if not os.path.exists(sys.argv[1]):
print... |
#!/usr/bin/env python3
# -*-coding:utf-8 -*-
# =============================================================================
"""
@Author : <NAME>
@File : rosbag_filter_gui.py
@Date created : 2021/11/16
@Maintainer : <NAME>
@Email : <EMAIL>
"""
# ====================================... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Description : 根据路网进一步细化网格
@Date : 2021/11/28 10:49:59
@Author : gz.gong
@Contact : <EMAIL>
@version : 1.0
'''
import numpy as np
from pandas.io import pickle
def path_match(real_roads, car_paths):
""" assign each catr_path one real road in a single grid
A... |
import nltk
from nltk import pos_tag
import pandas as pd
import spacy
from nltk.corpus import stopwords, wordnet, words, treebank
from spacy.lang.en.stop_words import STOP_WORDS
nlp = spacy.load("en_core_web_sm", disable=["tokenizer", "parser","ner", "textcat", "custom"])
df = pd.read_csv('./../data/SEM-2012-SharedTas... |
import logging
from collections import namedtuple
from functools import reduce
import numpy as np
import scipy.linalg as sla
TensorDescription = namedtuple("TensorDescription", "shape dtype")
"""namedtuple: Description of a tensor in terms of the tensor's shape and data type."""
def promote_dtype_of_tensors(*xs):
... |
"""Add access authority
Revision ID: a08b46e0172e
Revises: <PASSWORD>
Create Date: 2016-07-11 15:35:47.894579
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a08b46e0172e'
down_revision = '4b98c9<PASSWORD>a56'
LEVELS = {
'portal-revision': (5, 4, 2),
'... |
#!/usr/bin/env python
import time
import numpy as np
from safe_rl.utils.load_utils import load_policy, load_feasibiltiy
from safe_rl.utils.logx import EpochLogger
import matplotlib.pyplot as plt
import os.path as osp
import json
plt.rcParams.update({'font.size': 16})
def collect_obs(env, args, bound=2.5):
env.res... |
#!/usr/bin/python
############################################################
#Imports
from scapy.all import *
from termcolor import colored
import datetime
import string
import argparse
import platform
import binascii
# Static Configuration
# Default Broadcast MAC Address
broadcast_mac = 'ff:ff:ff:ff:ff:ff'
# To sto... |
import os
import logging
import torch
import torch.nn as nn
import baseline as bl
from eight_mile.pytorch.layers import (
CRF,
ViterbiBatchSize1,
TaggerGreedyDecoder,
ViterbiLogSoftmaxNormBatchSize1
)
from baseline.utils import (
exporter,
Offsets,
write_json,
load_vectorizers,
load_... |
import argparse
import check_time
from cfpq import *
from pyformlang.regular_expression import *
name_words = {'gr', 'connect', 's'}
def nullable(regexp):
if '(' in regexp:
brackets = list()
i = 0
for sym in regexp:
if sym == '(':
brackets.append(i)
... |
import xml.etree.ElementTree as ET
import javabridge
import bioformats
javabridge.start_vm(class_path=bioformats.JARS)
import numpy as np
from PIL import Image, ImageDraw
from skimage.filters import sobel
from skimage import morphology
from scipy import ndimage as ndi
def get_xml(path):
"""gets OMEXML metadata a... |
# -*- coding: utf-8 -*-
#
# Copyright 2019 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compli... |
#------------------------------------------------------------------
# Licensed under The Apache-2.0 License [see LICENSE for details]
# Inference Chip Generation Module for AutoFocus
# by <NAME> and <NAME>
# -----------------------------------------------------------------
import os
import cv2
import math
import numpy ... |
import abc
import hashlib
from urllib.parse import urlencode
from rest_framework.renderers import JSONRenderer
from w3lib.url import canonicalize_url
from wagtail.core.signals import page_published, page_unpublished
from wagtail.core.models import Page
from django.conf import settings
from django.core.cache import ca... |
"""
MIT License
Copyright (c) 2022 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distri... |
from django.apps import apps
import importlib
import factory
from rest_framework.test import APIRequestFactory
from rest_framework.request import Request
from rest_framework.authtoken.models import Token
from django.urls import reverse
import json
from functools import partial
from typing import Any, Dict
from facto... |
import os.path
import numpy as np
import pandas as pd
import typing
from typing import List
import sys
from nk_sent2vec import Sent2Vec as _Sent2Vec
from d3m import container, utils
from d3m.primitive_interfaces.transformer import TransformerPrimitiveBase
from d3m.primitive_interfaces.base import CallResult
from d3m... |
import os
import json
import base64
import hashlib
import requests
import urllib.parse
from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask
from flask import request
from main import *
import ini
app = Flask(__name__)
# 一个小小滴示例
# a little case:
'''
{
"Name" : "main.cpp",
... |
import logging
from typing import Tuple
from sugaroid.brain.constants import INTRODUCE
from sugaroid.brain.ooo import Emotion
from sugaroid.brain.postprocessor import random_response, any_in
from sugaroid.core.base_adapters import SugaroidLogicAdapter
from sugaroid.core.statement import SugaroidStatement
def about_p... |
# daily_data_read_format
#
# Read the format from the website of Sardegna Ambiente and
# write out CSV files with a table.
#
# Copyright 2021 Sustainable Sardinia
#
# 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 cop... |
from dataflow.multiwoz.execute_programs import exec_program_gen
from dataflow.multiwoz.create_belief_state_prediction_report import eval_state_report
from dataflow.multiwoz.evaluate_belief_state_predictions import evaluate
import jsons
import os
import glob
import jsonlines
import json
import collections
from tabulate ... |
#!/usr/bin/env python3
"""Check Android autoloader files."""
import sys # load arguments
import requests # session
from bbarchivist import argutils # arguments
from bbarchivist import decorators # Ctrl+C wrapping
from bbarchivist import jsonutils # json
from bbarchivist import networkutils # lookup
from bbarchi... |
import threading
import asyncio
import json
import base64
try:
import tornado.web
import tornado.websocket
from tornado.log import access_log
except ImportError:
raise ImportError('To use SDTmonitor, you need to install tornado: \n'
'\n > pip install tornado')
from srttools.... |
"""
Database Classes
Classes that save/load python content to/from the hard drive(or other means of non-volatile memory).
Make sure to provide pickle-able data, no objects, classes or anything that might be hard to convert to a string
Please do not use DatabaseEntry directly, nor DatabaseDictBase. Those are exposed... |
import unittest
from pyservices.data_descriptors.entity_codecs import *
from pyservices.utilities.exceptions import MetaTypeException
from test.data_descriptors.meta_models import *
class TestUtils(unittest.TestCase):
def setUp(self):
self.person_dict = {
'person_name': 'my_person_name',
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 8 14:43:34 2018
@author: sreimond
"""
import numpy as np
from copy import deepcopy
class Simplex( object ):
"""
The `Simplex` class holds vertices and optimizes the objective
function.
"""
def __init__( self, objective_function, initial_param... |
import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
import normalizing_flows.utils as utils
import normalizing_flows.flows as flows
import tensorflow.keras.backend as K
from tensorflow.keras import Model
from tqdm import tqdm
from typing import Callable
from .trackable_module import Trackabl... |
""" Energy Distributor
This module returns an amount of energy which satisfies a certain energy sharing policy.
energystats:
["ap.id", "ap.energystore", "ap.data_energyarrival", "ap.data_energyuse", "ap.servicedusers"]
energydistributed:
["id", "energyin"]
"""
from operator import itemgetter
from network_simulator... |
import argparse
import collections
import pandas
import numpy as np
import os
import gym
from keras.layers import Activation, Dense, Flatten
from keras.models import Sequential
from keras.optimizers import Adam
import tensorflow as tf
from rl.agents import SARSAAgent
from rl.core import Processor
from rl.policy impor... |
# -*- coding: utf-8 -*-
"""
Created on Mon June 13 12:22:40 2017
@author: bartosz
"""
from pathlib import Path
import json
import re
import csv
import os
####################33
####### INPUT
###############################
outputFileName = "3_med"
disciplineNumber = "3"
queries = ["aetiological ... |
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
from tabulate import tabulate
def Get_beamridg_and_perv(energy=5e3,current=0.0):
'''
Grab beam ridgidity
'''
# Parameters
e = 1.60217733E-19 #C
m = 9.1093897E-31 #kg
Energy = energy # eV
c ... |
"""
Functions that provide aid to calls to Spotify API
"""
import math
import random
import requests
from app import app
import json
BASE_URL = "https://api.spotify.com/v1"
def generateRandomString(length):
"""
Spotify's proposal to generate randomly generated strings, https://developer.spotify.com/documenta... |
import numpy as np
import theano,theano.tensor as T
from lasagne.layers import *
from lasagne.layers import Conv2DLayer as ConvLayer
from lasagne.layers import MaxPool2DLayer as PoolLayerDNN
from lasagne.layers import MaxPool2DLayer as PoolLayer
from lasagne.layers import LocalResponseNormalization2DLayer as LRNLayer... |
# -*- coding: utf-8 -*-
"""
DMRS-JSON serialization and deserialization.
"""
from pathlib import Path
import json
from delphin.lnk import Lnk
from delphin.dmrs import (
DMRS,
Node,
Link,
CVARSORT,
)
CODEC_INFO = {
'representation': 'dmrs',
}
HEADER = '['
JOINER = ','
FOOTER = ']'
def load(so... |
#! /usr/bin/env python3
import sys
import argparse
import uuid
uuids = {}
def generate_guid(guid):
try:
return uuids[guid]
except KeyError:
uuids[guid] = uuid.uuid4()
return uuids[guid]
def validate_guid(guid):
expected_lengths = [8, 4, 4, 4, 12]
if len(guid) != 36:
retur... |
import os
import sys
import scipy.misc
import numpy as np
import tensorflow as tf
import argparse
from datetime import datetime
import model
import utils
def main(args):
if not os.path.exists(args.checkpoint_dir):
os.makedirs(args.checkpoint_dir)
if not os.path.exists(args.sample_dir):
... |
# coding:utf-8
# Produced by <NAME>
# Start Data: 24_Aug_2020
# TensorFlow Version for Intent Extraction train pipeline.
#
# For GOD I Trust.
# 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
#
#... |
#!/usr/bin/env python3
from selenium import webdriver
import requests
from url_normalize import url_normalize
import pugsql
import os
import json
import time
from random import uniform
import argparse
import zlib
import logging
from newsSpiders import helpers
from newsSpiders.types import SiteConfig
logging.basicConf... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""=================================================================
@Project : Algorithm_YuweiYin/LeetCode-All-Solution/Python3
@File : LC-0994-Rotting-Oranges.py
@Author : [YuweiYin](https://github.com/YuweiYin)
@Date : 2022-01-09
===================================... |
import numpy as np
import tensorflow as tf
from nvtabular.dispatch import annotate, is_series_or_dataframe_object, HAS_GPU
from nvtabular.loader.tensorflow import KerasSequenceLoader
from toolz.itertoolz import sliding_window
from zenithml.preprocess import Preprocessor
from_dlpack = tf.experimental.dlpack.from_dlpac... |
"""
Quick Plot
----------
A tool to have quick and simple visualization from your data.
It can be use such as:
.. code-block:: console
$ deephyper-analytics quickplot nas_big_data/combo/exp_sc21/combo_1gpu_8_age/infos/results.csv
$ deephyper-analytics quickplot save/history/*.json --xy time val_r2
$ dee... |
# Copyright 2019, The Jelly Bean World Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... |
""" This script contains a number of functions used for interpolation of kinetic profiles and D,V profiles in STRAHL.
Refer to the STRAHL manual for details.
"""
# MIT License
#
# Copyright (c) 2021 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated... |
from pyteal import *
staking_token_id = App.globalGet(Bytes("staking_token_id"))
is_governance = Txn.sender() == App.globalGet(Bytes("governance_address"))
num_reports = Bytes("num_reports")
stake_amount = Bytes("stake_amount")
governance_address = Bytes("governance_address")
query_id = Bytes("query_id")
query_data =... |
import telepot
from datetime import datetime, date
from datetime import timedelta
from dateutil import parser
import json
from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj,... |
from random import shuffle
import cv2
import numpy as np
from PIL import Image
import os
def get_file_name(path):
"""
return filename
such as :[100.png,101.png]->[100,101]
"""
filename = os.listdir(path)
filename = [file.split(".")[0] for file in filename]
return np.array(filename)
def rand... |
#######################################################################
# Copyright (C) 2017 <NAME>(<EMAIL>) #
# Permission given to modify the code as long as you keep this #
# declaration at the top #
##############################################################... |
import numpy as np
import numpy.random as nr
import torch
import torch.nn as nn
import random
# Auxiliary function
def torch_vd(d, q):
# Compute the volume of unit l_q ball in d dimensional space
if (q == float('inf')):
return d * torch.log(torch.tensor(2))
return d * torch.log(2 * torch.special.torch.exp(torch.... |
#!../bin/python
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.regularizers import l2
from keras.optimizers import SGD ,Adagrad
from scipy.io import loadmat, savemat
from keras.models import model_from_json
import theano.tensor as T
import theano
import csv
import con... |
import json, os
from threading import Thread
from igdb.wrapper import IGDBWrapper
global wrapper #Global variable to reference wrapper so it can be used across all methods and getters
"""
Use formatted strings in getters
def example(str):
return f'my {str} is formatted'
def example2(str):
return 'my {0} ... |
# -*- coding: utf8 -*-
import random
from operator import itemgetter
from src.breadth_first_search import bfs
from src.graph import Graph
from src.heap import Heap
from src.union_find import UnionFind
def prims_suboptimal_mst(graph):
""" Computes minimum spanning tree using Prim's algorithm.
Running time: ... |
import dgl
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import pandas as pd
import dgl.function as fn
import dgl.nn.pytorch as dglnn
from tensorboardX import SummaryWriter
try:
import model.dgl_gcn_hete as dgl_gcn_hete
except Exception as e:
import dgl_gcn_hete
# SET LA... |
'''
Sample microservice to show some minimal skills.
'''
import sqlite3
import time
from typing import Optional
from uuid import uuid4
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from currencies import Currency, currency_decimals
from operations import Operation
from database import *
ap... |
from cf.util import *
from cf.classes import *
from cmd import Cmd
import urllib
from bs4 import BeautifulSoup
import textwrap
import pydoc
problems = []
probStat = []
def list_prob(p, ps):
print_c(p.name)
def det_prob(i):
p = problems[i]
ps = probStat[i]
print_head("Problem Details", 'red')
... |
import urllib
from urllib.request import Request, urlopen
import requests
from bs4 import BeautifulSoup
import re
import json
import math
import pandas as pd
import pickle
from fuzzywuzzy import process, fuzz
# drugs database
PATH_DRUGS_DATABASE = 'data/meds.csv'
PATH_ASSOCIATED_RULES = 'data/rules1.csv'
PATH_MEDFORMS... |
import numpy as np
import pandas as pd
import os
import re
import time
#Adjust parameters in generate_table_unpartitioned (bin and read count)
OUT_PATH = '<output directory of benchmark with bin_number directory, e.g. /dev/shm/username/1024'
#stores results in `OUTPATH/table.csv`
def process_output(path, bin_count, ... |
import argparse
import logging
import time
import os
import numpy as np
import matplotlib.pyplot as plt
import apex.amp as amp
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
from torch.utils.data.sampler import SubsetRandomSampler
from torchvision impo... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 8 22:14:37 2018
@author: JamesChiou
"""
import sys
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from xgboost import XGBClassifier
from catboost import CatBoostClassifier
def onehot_encoding(data)... |
import cv2
import numpy as np
import dlib
import graphviz
cap = cv2.VideoCapture(0)
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
font = cv2.FONT_HERSHEY_PLAIN
up_node_count = down_node_count = left_node_count = right_node_count = center_node_co... |
# coding=UTF-8
import math
import re
import pandas
class CorpusBuilder:
def __init__(self, inputPath):
self.corpusDocList = list(pandas.read_csv(inputPath)['NEWS_BODY'])
self.corpusText = ' '.join(self.corpusDocList)
temp = cleanText(self.corpusText).split(' ')
self.corpus... |
import numpy as np
from optparse import OptionParser
import AICIG as bagan
from batch_generator import BatchGenerator as BatchGenerator
import os
import tensorflow as tf
import keras.backend as K
import keras.backend.tensorflow_backend as ktf
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVI... |
#function to generate next iteration of the pattern
def new_gen(board, board_size):
#newboard is at the beginning full of dead cells
newboard = []
for i in range(board_size):
row = []
for j in range(board_size):
x = '□'
row.append(x)
newboard.append(row)
#for... |
#!/usr/bin/env python
#-------------------------------------------------------------------------------
#
# Image filters.
#
# Author: <NAME> <<EMAIL>>
#
#-------------------------------------------------------------------------------
# Copyright (C) 2016 EOX IT Services GmbH
#
# Permission is hereby granted, free of c... |
import json
import uuid
import publish
import auth
import strutil
import sqlite_backend
import pprint
import traceback
from multiprocessing import Lock
import funcs_application #for role import
def role_get_func(args):
try:
usertoken = args['userToken']
roleid = args['roleID']
if not usertoken or not strutil.... |
import six
import numbers
import logging
import numpy as np
from sklearn.metrics import log_loss
from sklearn.utils import check_consistent_length, check_array
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import LabelBinarizer
import mxnet as mx
from mxnet.metric import EvalMetric... |
import cv2
import numpy as np
from filter import OneEuroFilter
lk_params = dict(winSize=(40, 40), maxLevel=8, criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 5, 0.1))
def dist(a, b):
return np.sum(np.power(a - b, 2), 1)
class LKTracker:
def __init__(self):
self.prev_frame = None
... |
import json
import sys
from src.etl import *
from src.embedding import *
from src.utils import evaluate
from src.models import *
import os
from joblib import Parallel, delayed
from tqdm import tqdm
import pandas as pd
from p_tqdm import p_map
#==============================define configuration and file path===========... |
"""Python API for using Join by joaoapps."""
import requests
from flask import request, Response, Flask
import os
SEND_URL = "https://joinjoaomgcd.appspot.com/_ah/api/messaging/v1/sendPush?apikey="
LIST_URL = "https://joinjoaomgcd.appspot.com/_ah/api/registration/v1/listDevices?apikey="
REGISTER_URL = "https://joinjo... |
#! /usr/bin/python
import os
import sys
import json
import luigi
import nifty.tools as nt
# this is a task called by multiple processes,
# so we need to restrict the number of threads used by numpy
from elf.util import set_numpy_threads
set_numpy_threads(1)
import numpy as np
from elf.label_multiset import deseriali... |
import numpy as np
import tensorflow as tf
from utils import get_shape_list
_pad_mask_dict = {}
def get_pad_mask(relative_size, seq_length, heads):
key = (relative_size, seq_length)
if key in _pad_mask_dict:
pad_mask = _pad_mask_dict[key]
else:
pad_mask = [[1] * max(relative_size - i, 0)... |
"""BigNAS subnet searching: Coarse-to-fine Architecture Selection"""
import numpy as np
from itertools import product
import torch
import xnas.core.config as config
import xnas.logger.meter as meter
import xnas.logger.logging as logging
from xnas.core.builder import *
from xnas.core.config import cfg
from xnas.datas... |
from flask import abort, Blueprint, render_template, send_from_directory, \
jsonify, request, redirect, url_for, flash, current_app, send_file
from flask_login import login_required, current_user
import sqlalchemy as sa
from spreadsheetcompiler.extensions import login_manager, db
from .. import models
from .users impo... |
"""
Time-Distributed CNN + Bidirectional LSTMS on VOXELS
- extract_path is the where the extracted data samples are available.
- checkpoint_model_path is the path where to checkpoint the trained models during the training process
EXAMPLE: SPECIFICATION
extract_path = '/Users/sandeep/Research/Ti-mmWave/data/extract/... |
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import dgl
import dgl.function as fn
import random
"""
LiteGT network for node classification
"""
from layers.LiteGT_layer import LiteGTLayer
from layers.mlp_readout_layer import MLPReadout
# initialize edge attention score uni... |
#!/usr/bin/env python
# Dexter Industries line sensor python library
#
# This is and example to make the GoPiGo follow the line using the Dexter Industries Line follower
#
# Have a question about this example? Ask on the forums here: http://www.dexterindustries.com/forum/
#
# http://www.dexterindustries.com/
#
# Fixe... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError
class Project(models.Model):
_inherit = "project.project"
allow_timesheets = fields.Boolean("Timesheets", default=... |
"""
Advent of Code 2021: day 8
Reading this puzzle was a definate WAT! moment.
This looks like its going to be hard.
Part A I can do with just basic checking lengths, so stupidly doing this.
I doubt thats going to help in the overall scheme, just lets just clear A.
As expected part B is going to need a full solve, w... |
import requests
import re
import sys
import validators
from bs4 import BeautifulSoup as bs
from urllib.parse import urljoin
from pprint import pprint
from xml.dom import minidom
# initialize an HTTP session
s = requests.Session()
# s.headers["User-Agent"] = "Mozilla/5.0 (platform; rv:geckoversion) Gecko/geckotrail ap... |
"""Model from ``gabgoh.github.io/COVID``,
which uses a SEIR model elaborated with clinical dynamics.
"""
from corona.utils import *
from corona.maths import *
# TODO: from seminar w/ <NAME>:
# They use negative binomial distributions a lot.
@dcs.dataclass
class SEIR2:
# ------ Params SEI (transmission dyn... |
from __future__ import division
import shutil
import numpy as np
import torch
from path import Path
import datetime
from collections import OrderedDict
from matplotlib import cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
import os
def save_path_formatter(args, parser):
job_id = os.getenv... |
import PySimpleGUI as sg
import os.path
from PIL import Image
from io import BytesIO
from utils import back_event
def load_layout():
# First the window layout in 2 columns
file_list_column = [[sg.Text("Folder"),
sg.In(size=(28, 1), enable_events=True, key="-FOLDER-", readonly=True, fo... |
#!/usr/bin/env python
"""Script to retrieve the etc/test_lifecycle.yml tag file from the metadata repository that
corresponds to the current repository.
Usage:
python buildscsripts/fetch_test_lifecycle.py evergreen-project revision
"""
from __future__ import absolute_import
from __future__ import print_function
... |
#! usr/bin/env python3
# -*- coding:utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
import sys
import warnings
warnings.filterwarnings('ignore')
seed = 782
np.random.seed(seed)
data = pd .read_csv('./train.csv')
print(data.head())
train = data.as_matrix()
train... |
import argparse
import os
import shutil
import stat
import sys
import donkeycar as dk
from donkeycar.utils import *
PACKAGE_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
TEMPLATES_PATH = os.path.join(PACKAGE_PATH, 'templates')
HELP_CONFIG = 'location of config file to use. default: ./config.py... |
import pytesseract as pt
from pathlib import Path
from PIL import Image
import io
import re
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
from transformers import MBartForConditionalGeneration, MBart50Tokenizer
from textblob import TextBlob
import streamlit as st
pt.pytesseract.tesseract_cmd = 'C... |
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2018
# <NAME> <<EMAIL>>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either ... |
from os import makedirs
from os.path import join
import numpy as np
import torch
from torch import nn
from genre.models.netinterface import NetInterface
from genre.toolbox.cam_bp.cam_bp.functions import CameraBackProjection
import genre.util.util_img
class MarrnetBaseModel(NetInterface):
im_size = 256
rgb_jit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.