content stringlengths 5 1.05M |
|---|
import torch
from torch.nn import Module
class SDFLoss(Module):
'''
Signed Distance Function
Points inside the domain have a norm < 1.0
Points outside the domain have a norm > 1.0
norm = ||x_i||_2^2
norm [norm < 1.0] = 0
mean(norm)
'''
def __init__(self)... |
# -*- coding: utf-8 -*-
# Learn more: https://github.com/kennethreitz/setup.py
import os, sys
from setuptools import setup, find_packages
def read_requirements():
"""parse requirements from requirements.txt."""
reqs_path = os.path.join("", "requirements.txt")
with open(reqs_path, "r") as f:
requi... |
import dash_core_components as dcc
import dash_html_components as html
import dash_table
from dash import Dash
from dash.dependencies import Input, Output
import stock_pattern_analyzer as spa
from dash_app_functions import get_search_window_sizes, get_symbols, search_most_recent
app = Dash(__name__, meta_tags=[{"name... |
from __future__ import print_function
from __future__ import absolute_import
from builtins import range
import time
import sys
import os
import re
from .commands import Command
from .cn_introspect_bgp import ControlNodeInspect
from .ssh_interactive_commnds import *
from netaddr import *
from datetime import datetime
fr... |
from datetime import date
from dateutil.relativedelta import relativedelta
from typing import Dict, Final
import pytest
from django.core.exceptions import ValidationError
from supply_chains.test.factories import (
SupplyChainFactory,
GovDepartmentFactory,
UserFactory,
StrategicActionFactory,
Strat... |
# Globals
def init():
global VERSION
VERSION = "1.3"
global APP_NAME
APP_NAME = "Raincoat"
global TORRENTS
TORRENTS = []
global APIKEY
APIKEY = ""
global JACKETT_URL
JACKETT_URL = ""
global JACKETT_INDEXER
JACKETT_INDEXER = ""
global DESC_LENGTH
DESC_LENGTH = ""
... |
#!/usr/bin/env python
import numpy
from distutils.core import setup, Extension
transformations_module = Extension(
'pybh.contrib._transformations',
#define_macros = [('MAJOR_VERSION', '1'),
# ('MINOR_VERSION', '0')],
include_dirs = [numpy.get_include()],
libraries = [],
library... |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow.compat.v1 as tf
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import Reco3D.lib.dataset as dataset
import Reco3D.lib.network as network
from Reco3D.lib import preprocessor
import Reco3D.lib.vis as vis
from Reco3D.lib import met... |
#*************************************************************************
#Copyright (C) 2015 by Arash Bakhtiari
#You may not use this file except in compliance with the License.
#You obtain a copy of the License in the LICENSE file.
#Unless required by applicable law or agreed to in writing, software
#distributed un... |
#!/usr/bin/env python
import os
import csv
import sys
writer = csv.DictWriter(sys.stdout, fieldnames=['photo_id', 'image'])
writer.writeheader()
for line in open('ocr/backing-images.urls.txt'):
image_file, url = line.strip().split('\t')
photo_id, _ = os.path.splitext(os.path.basename(image_file))
writer.w... |
from django.test import TestCase
from pages import display, models
class Fields(TestCase):
fixtures = []
def test_attribute_error(self):
# noinspection PyTypeChecker
page = display.Page(None, {})
with self.assertRaises(AttributeError):
_ = page.bad_attr
class Page(TestC... |
class Dummy:
def __str__(self) -> str:
return "dummy"
d1 = Dummy()
print(d1)
|
# decomposer.py
# ALS 2017/06/01
import os
from ..obsobj import Imager
from .. import spector
from .. import imgdownload
from ..filters import surveysetup
class Decomposer(Imager):
def __init__(self, **kwargs):
"""
Decomposer, an imager operator to do image decomposition
Imager Params
-------------
/e... |
from nltk.tag import pos_tag
import pandas as pd
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
import random
from NLPFunctions import remove_noise, get_sentence_for_model
dataset_Happy = pd.read_csv('Dataset/EmotionalHappy.csv')['Sentence']
dataset_Anger = pd.read_csv('Dataset/EmotionalAng... |
from flask_restful import Resource, Api, reqparse
import json
from model.motion import MotionModel
class MotionAPI(Resource):
def get(self):
model = MotionModel()
motion = model.get_motion()
return motion, 200
def post(self):
"""
Uses the houseguard db to make a motio... |
import os
import sys
current_dir = os.path.abspath(os.path.dirname(__file__))
sys.path.append('../utility')
from TimeUtility import TimeUtility
import MetaTrader5 as mt5
MINUTE = 'MINUTE'
HOUR = 'HOUR'
DAY = 'DAY'
# symbol : [(mt5 timeframe constants), number, unit]
TIMEFRAME = {'M1': [mt5.TIMEFRAME_M1, ... |
"""
Model observing, this module is built to simulate actual observing. The
object is known, and given sight parameters, the data is given. In particular,
these functions actually give the values of terms derived from the object
model also provided.
"""
import copy
import numpy as np
import scipy as sp
import matplot... |
# Generated by Django 2.0.3 on 2019-02-15 08:49
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Slic... |
def main():
money_received = int(input("Money received: "))
price = int(input("Price: "))
change = money_received - price
result = {100000: 0, 50000: 0, 20000: 0, 10000: 0, 5000: 0, 2000: 0, 1000: 0}
for key in result.keys():
calculation = int(change / key)
if calculation:
... |
import sys
import numpy as np
print("Python version: "+sys.version)
print("Numpy version: "+np.__version__)
|
'''
bilibili spider init file
'''
from .SpiderModule import bilibili_spider
from .ProcessRawModule import process_run_main
from .MasModule import mas_get_html
|
# -*- coding:utf-8; -*-
class Solution:
def removeDuplicates(self, nums):
lastUniq = 0 # 前面唯一序列的最后一个元素
for i, v in enumerate(nums[1:]):
if v != nums[lastUniq]:
lastUniq += 1
nums[lastUniq] = v
return lastUniq + 1
|
import time
import random
import sys
Wuerfel = ['1','2','3','4','5','6']
time.sleep(0.5)
ergebnis = random.choice(Wuerfel)
print (ergebnis)
|
# Copyright 2018, The TensorFlow Federated 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
##
# See the file COPYRIGHT for copyright information.
#
# 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 random
import os
import csv
from itertools import product
from pytest import fail
from tqdm import tqdm
from operator import itemgetter
from generate_entropy import *
from wordle import *
def generate_guess(previous_board, previous_guess, wordlist, turn, total_words, combs, guess, second_guess_scores, data):
... |
'''OpenGL extension NV.texture_barrier
This module customises the behaviour of the
OpenGL.raw.GL.NV.texture_barrier to provide a more
Python-friendly API
Overview (from the spec)
This extension relaxes the restrictions on rendering to a currently
bound texture and provides a mechanism to avoid read-after-write
... |
from .preprocess import (
read_raw_data,
read_processed_data,
preprocess_data,
get_label,
get_featues,
)
|
def count_primes2(num):
primes = [2]
x = 3
if num < 2:
return 0
while x <= num:
for y in primes: # use the primes list!
if x%y == 0:
x += 2
break
else:
primes.append(x)
x += 2
print(primes)
return len(pr... |
############### Stats #################
stats_params = {
# Read
"fragment_length" : 650,
"mapping_quality" : 20,
"base_quality" : 20,
# ALT
"dp_limit" : 5,
"alt_ratio_limit" : 0.2,
"sample_vote_limit" : 2,
"vote_ratio_limit" : 0.9,
"snp_read_limit" : 1,
# Indel
"indel_ratio" : 0.05,
# Bulk
"bulk_ref_limit" : 1, #thi... |
from collections import Counter
from collections import defaultdict
from nltk.corpus import stopwords
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from preprocess import process_text_data
from utils import load_epub
def get_word_frequency_information(book... |
# IPython log file
# cd ~/projects/play
# make sure cache.py is around
get_ipython().run_line_magic('run', '-i cache.py')
_correlate_sparse_offsets.inspect_types()
_correlate_sparse_offsets.inspect_types(pretty=True)
get_ipython().run_line_magic('run', '-i cache.py')
get_ipython().run_line_magic('pinfo', '_correlate_... |
# solutions.py
"""Introductory Labs: Intro to Matplotlib. Solutions file."""
import numpy as np
from matplotlib import pyplot as plt
def var_of_means(n):
"""Construct a random matrix A with values drawn from the standard normal
distribution. Calculate the mean value of each row, then calculate the
varianc... |
import numpy as np
import pandas as pd
pd.options.mode.chained_assignment = None #Turn off SettingWithCopyWarning
import os
import omnitool
import argparse
parser = argparse.ArgumentParser(description='Recalculate Bolometric Corrections for a given temperature perturbation')
parser.add_argument('tempdiff', default=0.... |
def rel_height(node, node_height):
return max(
node_height,
rel_height(node.left, node_height + 1),
rel_height(node.right, node_height + 1)
) if node else 0
def height(root):
return rel_height(root, 0) |
"""CLI command for "publish" command."""
import json
import click
import boto3
from botocore.exceptions import ClientError
from serverlessrepo import publish_application
from serverlessrepo.publish import CREATE_APPLICATION
from serverlessrepo.exceptions import ServerlessRepoError
from samcli.cli.main import pass_co... |
# Helper module used by the signed-off-by checker and email address
# checker.
#
# This module handles all the common code stuff between the various
# checkers.
import os
import sys
import logging
import argparse
from git import Repo
def run(checker_name, per_commit_callback, result_messages):
logging.basicConfi... |
import pytorch_lightning as pl
import torch
from xmuda.models.modules import Net2DFeat, Net3DFeat, FuseNet
from xmuda.models.LMSCNet import LMSCNet
from xmuda.common.utils.metrics import Metrics
import pickle
import numpy as np
import time
import os.path as osp
class RecNetLMSC(pl.LightningModule):
def __init__(s... |
from aiogram import Dispatcher
from app.handlers.private import default, start, help_
def setup(dp: Dispatcher):
for module in (start, default, help_):
module.setup(dp)
|
# -*- coding:utf-8 -*-
from beryllium.field import FieldList
from beryllium.tabsetup import TabSetup
from beryllium.listcssselector import ListCssSelector
from beryllium.mongodb import Mongodb
class Page(object):
def __init__(self, field_list: FieldList, name="", is_save=False, mongodb=Mongodb(),
... |
"""
The Monty Hall Problem [http://en.wikipedia.org/wiki/Monty_Hall_problem] is a probability brain teaser that has a
rather unintuitive solution.
The gist of it, taken from Wikipedia:
Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others,
goats. You pic... |
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
from email_phone_user import version
def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except IOError:
return ""
setup(
name="django-email-phone-user",
version=version,
... |
"""It's not needed to include <!-- mdpo-include-codeblock --> command in
Markdown files, only if code block contents are included in PO files will be
translated directly.
"""
from mdpo.po2md import pofile_to_markdown
def test_include_indented_codeblock(tmp_file):
markdown_input = '''
var hello = "world";
... |
from collections import defaultdict
from predict import Predictor
import pandas as pd
import numpy as np
from loaddata import Data_Reader
from IPython import embed
import baostock as bs
import numpy as np
def download_data(code, main):
"""
:param code: type:str ex:sh.600000
:return: type:list
"""
... |
from ariadne.contrib.django.views import GraphQLView
from django.contrib import admin
from django.urls import path
from example_project.api.graphql_config import schema
urlpatterns = [
path("admin/", admin.site.urls),
path("graphql/", GraphQLView.as_view(schema=schema), name="graphql"),
]
|
# -*- coding: utf-8 -*-
"""
Generate plots of exponential decay in the image reconstruction error when
using restarted NESTA.
The setup is to solve a smoothed analysis QCBP problem with a TV-Haar analysis
operator to recover an image from subsampled Fourier measurements.
"""
import math
import nestanet.operators as n... |
"""
Copyright 2013 Steven Diamond
This file is part of CVXPY.
CVXPY 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.
CVXPY is distributed i... |
import logging
import traceback
import requests
import urllib3
from gtin import GTIN, CheckDigitError
logger = logging.getLogger(__name__)
class ApiError(Exception):
pass
class ConnectionError(ApiError):
pass
def is_code_supported_by_gs1_api(code):
code = code.lstrip('0')
try:
GTIN(code... |
# Addition
print(10 + 5)
float1 = 13.65
float2 = 3.40
print(float1 + float2)
num = 20
flt = 10.5
print(num + flt)
# Subtraction
print(10 - 5)
float1 = -18.678
float2 = 3.55
print(float1 - float2)
num = 20
flt = 10.5
print(num - flt)
# Multiplication
print(40 * 10)
float1 = 5.5
float2 = 4.5
print(float1 * float2)... |
import FWCore.ParameterSet.Config as cms
# File: BeamHaloSummary_cfi.py
# Original Author: R. Remington, The University of Florida
# Description: Module to build BeamHaloSummary Object and put into the event
# Date: Oct. 15, 2009
BeamHaloSummary = cms.EDProducer("BeamHaloSummaryProducer",
... |
# https://leetcode.com/problems/edit-distance/
import sys
# import random
class Solution(object):
def _memoize(f):
memo = {}
def wrapper(self, *args):
if args not in memo:
memo[args] = f(self, *args)
return memo[args]
return wrapper
@_memoize
... |
# Generated by Django 3.1.13 on 2021-09-20 12:48
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('pokemon_entities', '0009_pokemon_evolution'),
]
operations = [
migrations.RenameField(
model_name='pokemon',
old_name='evol... |
import numpy as np
import matplotlib.pyplot as plt
import os, re, shutil
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import normalize as norm2
import tensorflow as tf
def get_minute_data(data):
return data.asfreq('T', method='bfill')
def read_data(filename, ... |
import os
import pytest
from ..conftest import read_json
from ..conftest import TESTING_CONFIG_DIR
test_config = read_json(
os.path.join(TESTING_CONFIG_DIR, "default/unit/test-config_robots-txt.json",)
)
class TestRobotsTxt:
@pytest.mark.v4_20
@pytest.mark.parametrize(
"test_input,expected", t... |
import os
from flask import send_from_directory
from api.app import create_app
settings_module = os.getenv("APP_SETTINGS_MODULE")
app = create_app(settings_module)
@app.route("/")
def serve():
return send_from_directory(app.static_folder, "index.html") |
#!/usr/bin/env python3
import os
import signal
import subprocess
import time
from threading import Timer
import atexit
import logging
import sys
timeout_sec = 30
logger = logging.getLogger('repeat_test')
hdlr = logging.FileHandler('./repeat_test.log', 'w')
formatter = logging.Formatter('%(asctime)s %(levelname)s %... |
from typing import (List,
Tuple)
from tests.utils import (RawPointsList,
RawPolygon,
enum_to_values)
from wagyu.bound import Bound as PortedBound
from wagyu.box import Box as PortedBox
from wagyu.edge import Edge as PortedEdge
from wagyu.enums impor... |
#! /usr/bin/env python
#
#
# @file: meta
# @time: 2022/01/29
# @author: Mori
#
import bson
from schema import Schema
from moreover.base.logger import gen_logger
from typing import Dict, List, Tuple, Union
from motor import MotorClient, MotorDatabase, MotorCollection
from motor.core import (
AgnosticClient,
Agn... |
def sql_format(sql, replaceDict):
for item in replaceDict.items():
sql = sql.replace(str(item[0]), str(item[1]))
return sql
def getBookConnect():
return pymysql.connect(host="xxx.com", user="xxx", password="xxx", database="xxx", charset='utf8')
import openpyxl
def read_isbn(file, colnames, she... |
# Copyright 2020 InterDigital Communications, 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 ... |
import sys
from htchirp import condor_chirp
def main():
return condor_chirp(sys.argv[1:], True)
|
from keras import backend as K
from keras.layers import Layer
from keras.initializers import Ones, Zeros
class LayerNormalization(Layer):
def __init__(self, eps=1e-6, **kwargs):
self._eps = eps
self._gamma = None
self._beta = None
super().__init__(**kwargs)
def build(self, inp... |
from pomdpy.discrete_pomdp import DiscreteObservation
from .util import observation_to_index, index_to_observation
class TrafficLightObservation(DiscreteObservation):
def __init__(self, measurements):
super().__init__(observation_to_index(measurements))
self.wavelength_observed = measurements[0]
... |
import logging
from datetime import datetime
from django.db.models import Q
from django.shortcuts import get_object_or_404
from rest_framework.permissions import IsAuthenticated
from rest_framework.exceptions import MethodNotAllowed
from rest_framework.response import Response
from rest_framework_json_api.views import... |
"""
Deletes records for participants who are missing from the person table.
Developed to assist drop_participants_without_ppi_or_ehr.py in removing records
"""
# Python imports
# Third party imports
# Project imports
import common
from cdr_cleaner.cleaning_rules.base_cleaning_rule import BaseCleaningRule
from const... |
from sample.player import Player
class Checker:
def __init__(self):
self.temp = Player()
def remainder(self, file):
time = self.temp.getTime()
if time > 17:
self.temp.playWavFile(file)
return self.temp.wavWasPlayed(file)
else:
return self.tem... |
import ast
from collections import defaultdict
from functools import reduce
from typing import ClassVar, DefaultDict, List, Mapping, Set, Type
from typing_extensions import Final, final
from wemake_python_styleguide.compat.aliases import ForNodes
from wemake_python_styleguide.logic import source, walk
from wemake_pyt... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" This file contains code that can scrape the Nation Weather Service (NWS) website and read the
river level data for both Markland and McAlpine dams. By using the mileage marker for Bushman's Lake
the level of the river at that point can be calculated.
"""
from NWS_Ri... |
# Import Python libraries
from dash import Dash, html
import dash_bootstrap_components as dbc
# Create a Dash application, pass in a stylesheet from Bootstrap
app = Dash( external_stylesheets=[dbc.themes.BOOTSTRAP] )
# Create the layout of the app
app.layout = dbc.Container([
# Row 1
... |
import contextlib
import json
from hashfs import HashFS
from pydantic.dataclasses import dataclass
from typing import List, Type, TypeVar, Generic, Generator
from .registerable import Registerable, Serializable
T = TypeVar('T', bound=Registerable)
class ArbitraryTypeConfig:
arbitrary_types_allowed = True
@d... |
import compiler
import build
import networkx as nx
from matplotlib import pyplot as plt
def main():
c = compiler.Compiler('i686-linux-gnu-g++-6')
b = build.Build('output', c)
exe = b.add_executable('myexe', ['myexe/main.cpp', 'myexe/other.cpp'])
lib = b.add_dynamic_library('mylib', ['mylib/mylib.cpp'])... |
import os
import sys
sys.path.append("../data")
import math
import torch
from torch import nn
from torch import optim
from tokenizer import ScriptTokenizer
import model
from logger import Logger
'''
ASSUMPTIONS:
1. len(pre_frag) == len(frag) == len(post_frag)
'''
device = "cuda" if torch.cuda.is_availa... |
import json
from text_filters import *
from classifier import *
from objects import *
def lexical_diversity(article_content):
flat_text = " "
flat_text = flat_text.join(article_content)
return len(flat_text) / len(set(flat_text))
def print_dict_content(dictionary, message=None):
if message != None: p... |
from __future__ import absolute_import, print_function
import json
import os
from builtins import object
import responses
from pypexels import PyPexels
from pypexels.src.settings import API_ROOT, API_VERSION
api_key = os.environ.get('API_KEY', None) or 'API_KEY'
class TestPopular(object):
# TODO: avoid code d... |
from ex115.lib.interface import *
from ex115.lib.arquivo import *
from time import sleep
arq = 'cursoemvideo.txt'
if not arquivoExiste(arq):
criarArquivo(arq)
while True:
resposta = menu(['ver pessoas cadastradas', 'Cadastrar pessoa', 'Sair Do Sistema'])
if resposta == 1:
#opção de listar o conteúd... |
import os
import numpy as np
from spirl.models.closed_loop_spirl_mdl import GoalClSPiRLMdl
from spirl.models.skill_prior_mdl import SkillSpaceLogger
from spirl.utils.general_utils import AttrDict
from spirl.configs.default_data_configs.antmaze import data_spec
from spirl.components.evaluator import TopOfNSequenceEvalu... |
import os
import glob
# from PIL import Image
import cv2
# def exist_file():
# if (filename.lower().endswith('.png') or filename.lower().endswith('.jpg') or filename.lower().endswith('.gif') or filename.lower().endswith('.bmp') or filename.lower().endswith('.pcx')):
# return True
if __name__ == "__main__":... |
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2021 Beartype authors.
# See "LICENSE" for further details.
'''
**Beartype code-based operator validation classes** (i.e.,
:mod:`beartype`-specific classes enabling callers to define PEP-complian... |
__author__ = 'kenjif'
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
from fastdtw import fastdtw
from scipy.spatial.distance import euclidean
import gensim
from gensim.corpora import Dictionary
from gensim.models.ldamodel import LdaModel
from gensim.models.coherencemodel import CoherenceModel
f... |
from django.urls import path
from .views import (SignUpView, SignInView)
app_name = 'authentication'
urlpatterns = [
path('signup/', SignUpView.as_view(), name='signup'),
path('signin/', SignInView.as_view(), name='signin'),
]
|
from scipy.misc import imread, imresize, imsave
from scipy.optimize import fmin_l_bfgs_b
from sklearn.preprocessing import normalize
import numpy as np
import time
import os
import argparse
import h5py
from keras.models import Sequential
from keras.layers.convolutional import Convolution2D, ZeroPadding2D, AveragePooli... |
from dataflows import Flow, update_resource, add_field, checkpoint
from midburn_dataflows.kubectl import kubectl, get_item_detailed_status
def kubectl_get_all_flow(resource_name='kubectl_get_all'):
def add_status(rows):
if rows.res.name == resource_name:
for row in rows:
statu... |
# MIT License.
# Copyright (c) 2021 by BioicDL. All rights reserved.
# Created by LiuXb on 2021/1/21
# -*- coding:utf-8 -*-
"""
@Modified:
@Description:
"""
import sys
import os
_root_path = os.path.dirname(os.path.abspath(__file__))
sys.path.append(_root_path)
|
from django.contrib import admin
from .models import Business,Post,Neighboorhood
# Register your models here.
admin.site.register(Business)
admin.site.register(Post)
admin.site.register(Neighboorhood) |
#-*- coding: utf-8 -*-
import sys
from optparse import OptionParser
from django.conf import settings, global_settings
if not settings.configured:
settings.configure(
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
},
INSTALLED_A... |
from bottle import route, run, get, post, request, static_file, abort, hook, response
from pyzem.dvid import dvidenv, dvidio
from pyzem.compute import skeletonizer, bodysplit
import flyem_data as fd
import json
import subprocess
import sys
import socket
import jsonschema
import os
import timer
import time
import threa... |
import os
import numpy as np
import pickle
import random
def getFileNameList(filePath):
fileNameList = os.listdir(filePath)
fileNameList = sorted(fileNameList, key=lambda x: x[:x.find('.')])
return fileNameList
def load_CT(ROOT):
""" load all of cifar """
xs = []
ys = []
us = []
fil... |
import sys
import numpy as np
import pandas as pd
from scipy import stats
from itertools import permutations
NUM_RANKING = 3
def calculate_weighted_kendall_tau(pred, label, rnk_lst, num_rnk):
"""
calcuate Weighted Kendall Tau Correlation
"""
total_count = 0
total_corr = 0
for i in... |
#!/usr/bin/env python
import os
import re
import sys
comment = re.compile('^\s*#')
assign = re.compile('^\s*([a-zA-Z_]+)\s*(\?)?=\s*([^#]*)')
args = os.environ.copy()
for arg in sys.argv:
m = assign.match(arg)
if m:
var = m.group(1).strip()
val = m.group(3).strip()
args[var] = val
# ... |
from torchvision import transforms
import torch
import urllib
from PIL import Image
from flask import Flask, jsonify, request
import io
from json import *
import json
app = Flask(__name__)
transform_test = transforms.Compose([
transforms.Resize((600, 600), Image.BILINEAR),
transforms.CenterCrop((448, 448)),
... |
import numpy as np
import tensorflow as tf
import pdb
import itertools
from collections import OrderedDict
from mopo.models.utils import get_required_argument
from mopo.utils.logging import Progress, Silent
import wandb
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
tf.compat.v1.logging.set_verbosity(tf.compat... |
# File: symanteccas_connector.py
#
# Copyright (c) 2016-2022 Splunk 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... |
class SnakeUtils:
def __init__(self, data):
self.data = data
def determine_state(self):
print("Head..")
print("X: {}".format(self.data.you.head.x))
print("Y: {}".format(self.data.you.head.y))
print("Body piece positions..")
for i in range(1, len(self.data.you.body)):
print("{} - ... |
# Generated by Django 3.2.7 on 2021-10-05 15:19
import json
from django.db import migrations
def update_fields_with_images(apps, schema_editor):
# We can't import the Person model directly as it may be a newer
# version than this migration expects. We use the historical version.
Convention = apps.get_m... |
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from openvino.tools.mo.front.kaldi.extractors.concat_ext import ConcatFrontExtractor
from openvino.tools.mo.ops.convolution import Convolution
from openvino.tools.mo.ops.op import Op
from unit_tests.mo.front.kaldi.extractors.common_ext_t... |
#!/usr/bin/python
import argparse, sys, os, random, re
from shutil import rmtree, copytree
# This will operate a pipeline to go from
# Pre:
# pacbio_raw .. the path to the bax.h5 or bas.h5 you want to process
# please keep in mind that in this requires the accordingly
# named xml fi... |
# We need to use the low-level library to interact with SageMaker since the SageMaker API
# is not available natively through Lambda.
import boto3
import json
# The SageMaker runtime is what allows us to invoke the endpoint that we've created.
from typing import Dict
runtime = boto3.Session().client('sagemaker-runtim... |
#create_tables.py
import psycopg2
# Create database connection
try:
conn = psycopg2.connect(database="postgres", user="postgres", password="password", host="127.0.0.1", port="5432")
except:
print("I am unable to connect to the database")
conn.autocommit = True
# Create a cursor
cur = conn.cursor()
# C... |
from flask import Flask, render_template, request
import webbrowser, json
import runner as r
import normalize as n
import time
app = Flask(__name__)
@app.route('/',methods=['POST','GET'])
def main():
return render_template('index.html')
@app.route('/url',methods=['POST','GET'])
def url():
if request.me... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.