text stringlengths 3.07k 12.6k |
|---|
# TODO: Can FuncX functions call each other like this?
# TODO: How to keep DataCite credentials secret on FuncX?
def citrine_upload(citrine_data, api_key, mdf_dataset, previous_id=None, public=True):
import os
from citrination_client import CitrinationClient
cit_client = CitrinationClient(api_key).data
... |
import re
import textwrap
from io import BytesIO, TextIOWrapper
from collections import OrderedDict
from glycopeptidepy.io.fasta import FastaFileParser, FastaFileWriter
from glycan_profiling.serialize.hypothesis.peptide import Protein
from .sequence_tree import SuffixTree
class ProteinFastaFileParser(FastaFilePars... |
import sys
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestRegressor
import pickle
import json
import datetime
import util
MAX_USER_DURATION = 30
MIN_REQUIRED_USER_DURATION = 7
MIN_DATE = datetime.date(2017, 3, 6)
MAX_DATE = datetime.date(2999, 12, 31)
class NotEnoughDataError(Except... |
#
# Copyright 2018-2020 IBM 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... |
# Copyright 2014 - Mirantis, Inc.
# 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 ... |
"""
CISIS COMMANDS
"""
import os
from dsm import configuration
from dsm.utils.files import (
create_temp_file, read_file, write_file,
date_now_as_folder_name,
)
from dsm import exceptions
def get_document_isis_db(pid):
"""
Consulta a base de dados ISIS artigo e retorna os pids atualizados
em um i... |
# Copyright 2020 <NAME> (<EMAIL>).
# Copyright 2018 The TensorFlow Authors All Rights Reserved.
"""A script with utility functions."""
import re
import numpy as np
import tensorflow as tf
from tensorflow.python.ops import variables
import cv2
from epos_lib import misc
def convert_px_indices_to_im_coords(px_indices,... |
from __future__ import division
import numpy as np
from openconcept.utilities.dvlabel import DVLabel
from openconcept.utilities.math import AddSubtractComp, ElementMultiplyDivideComp
from openmdao.api import Group, IndepVarComp, ExplicitComponent
from openmdao.api import Problem, IndepVarComp
class TurbofanPropulsion... |
from tqdm import tqdm
import csv
import pickle
import re
import random
import wordninja
from datetime import datetime, timedelta
merge_map = dict()
def output_logs(filename, logs):
with open(filename, 'w') as f:
for blk_logs in tqdm(logs, desc='output {}'.format(filename)):
for log ... |
import click
from curriculum_model.db import DB, table_map
from curriculum_model.db.schema import Base
from sqlalchemy.inspection import inspect
def dependency_chain(key_only=False):
c = ['curriculum',
'course',
'course_config',
'course_session',
'course_session_config',
... |
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
from abc import abstractclassmethod
from os import PathLike
from pathlib import Path
from typing import Dict, Optional, Union
from azure.ai... |
# Copyright (c) 2015, <NAME> and <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions ... |
# ----------------------------------------------------------------------
# Copyright (C) 2015 <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License as published by the Free Software Foundation.
#
# T... |
import csv
import logging
from deriva.core import get_credential, DerivaServer
import deriva.core.ermrest_model as em
from deriva.utils.catalog.manage.deriva_csv import DerivaCSV
from deriva.utils.catalog.components.configure_catalog import DerivaCatalogConfigure
from deriva.utils.catalog.components.deriva_model impo... |
# -*- coding:utf-8 -*-
import json
import time
import os
import requests
from django.contrib import admin
from django.urls import path, include
application = get_wsgi_application()
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTAL... |
import torch
import torch.nn as nn
import torch.nn.functional as F
def get_downstream_model(input_dim, output_dim, config):
model_cls = eval(config['select'])
model_conf = config.get(config['select'], {})
model = model_cls(input_dim, output_dim, **model_conf)
return model
class FrameLevel(nn.Module)... |
# Copyright (c) 2014 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 agreed to ... |
"""
Functions to aid with the demo notebook
W251 (Summer 2019) - <NAME>, <NAME>, <NAME>
"""
import os
import shutil
import pandas as pd
import librosa
import librosa.display
import urllib
import matplotlib.pyplot as plt
from scipy.io import wavfile
import database_parser
import orca_params
import mel_params
def ... |
from django.views.generic.base import TemplateView, View
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.utils.crypto import get_random_string
from django.... |
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... |
# Copyright 2016 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Unittests for loman.py"""
from __future__ import print_function
import os
import xml.etree.ElementTree as ElementTree
from chromite.lib import cros_... |
from __future__ import absolute_import, division, print_function, unicode_literals
import uuid
import tensorflow as tf
import PIL
import os
import numpy as np
from PIL import Image
from cleverhans.attacks import FastGradientMethod, optimize_linear
from cleverhans.compat import softmax_cross_entropy_with_logits, redu... |
"""
Quality control of Dual-Pol moments for radar data.
@creator: <NAME> <<EMAIL>>
@project: s3car-server
@institution: Bureau of Meteorology
@date: 01/03/2021
.. autosummary::
:toctree: generated/
buffer
check_file
check_field
driver
get_ground_radar_file
mkdir
main
"""
# Python Stan... |
import scipy.optimize
import numpy as np
import matplotlib.pyplot as plt
import constants as con
import WtFrac
def molPercentToWtPercent(percent, mw1, mw2): #percent Returns weight percent from mole percent.
return((percent*mw1)/(percent*mw1+(1-percent)*mw2))
#Calculation testing
print(WtFrac.WtFracCO2(... |
"""
Jahnke, Student ID: 0808831
<EMAIL> / <EMAIL>
CSCI 160, Spring 2022, Lecture Sect 02, Lab Sect L03
Program 06, Part A
Write the required functions with proper documentation, i.e., a
docstring with a descriptions of what it does, its parameters, and its
return value.
Test all the functions in the main code.
Func... |
#
#
from __future__ import print_function
import string
#### Global Variables
rtc_list={}
connections={}
nshost="localhost"
NS = None
#
#
def get_handle_list(hostname="localhost", ns=None):
global NS
if ns :
NS=ns
NS.list_obj()
hdls_names = NS.rtc_handles.keys()
n=1
res=[]
for name in hdls_names:
... |
import json
from logging import getLogger
from django.conf import settings
from drf_yasg.utils import swagger_auto_schema
from rest_framework import status
from rest_framework.generics import CreateAPIView
from rest_framework.permissions import AllowAny
from rest_framework.renderers import JSONRenderer
from rest_fram... |
import json
from drawhelper import draw_tree
from thedata import get_traindata, Model2Json, get_testdata
def attr_value(obj, attr):
if isinstance(obj, dict):
return obj[attr]
raise Exception('at attr_value: obj is not a dict')
def get_label(obj):
return attr_value(obj, 'label')
def uniquelist... |
"""Data-preprocessing functions for Kaggle House Price competition."""
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.neighbors import NearestNeighbors
# The max. amount of values we'd expect in a numeric column that actually contains ordinal values:
MAX_VALUES_ORD... |
# -*- coding: utf-8 -*-
import os
import torch
import JackFramework.SysBasic.define as sys_def
from JackFramework.SysBasic.loghander import LogHandler as log
from .filehandler import FileHandler
class ModelSaver(object):
"""docstring for ModelSaver"""
ROW_ONE = 1
FIST_SAVE_TIME = True
def __init__(s... |
import base64
import json
import logging
import math
import os
import redis
import requests
from flask import Flask, request, jsonify
from server.predict import get_prediction
if not os.getenv('GOOGLE_APPLICATION_CREDENTIALS', ''):
raise RuntimeError('GOOGLE_APPLICATION_CREDENTIALS must be set')
if not os.path... |
import requests as reqs
import json
import csv
import re
import time
import getopt
from datetime import datetime as dt
from bs4 import BeautifulSoup as soup
import bar_chart_race as bcr
import pandas as pd
import getopt
import subprocess
#import multiprocessing
#import threading
import asyncio
import httpx
#import scra... |
# stuffID => stuffName => PanopticName => PanopticID => PanopticIndex
# Do i need the panopticID? Maybe not
import json
from helpers import loadJson, loadStuffTextLabels
path_to_panoptic_classes = './dependencies/panopticapi/panoptic_coco_categories.json'
path_to_stuff_classes = './dependencies/deeplab-pytorch/data/d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/ConceptMap) on 2019-07-29.
# 2019, SMART Health IT.
import sys
from dataclasses import dataclass
from typing import ClassVar, Optional, List
from .fhirabstractbase import empty_list
from .b... |
"""
This file tests the epoll() implementation.
Target files:
- libdesock/src/epoll.c
"""
import os
import ctypes
import random
import helper
import desock
def _read(fd):
buf = ctypes.create_string_buffer(1024)
n = desock.recv(fd, buf, ctypes.sizeof(buf), 0)
return buf[:n]
def do_syscall(method, *a... |
#!/usr/bin/env python
"""
Create an irrigation computer that can control various solonoid type latching water valves.
"""
import math
from typing import List, Tuple
from simple_skidl_parts.analog.power import *
from simple_skidl_parts.analog.power import optocoupled_triac_switch
from simple_skidl_parts.analog.vdiv i... |
"""Includes the Product class, which coordinates a documentation build.
"""
import os
import logging
from io import BytesIO
import abc
import sh
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())
class BaseProduct(object):
"""Abstract base class specifying the minimum API for products clas... |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Utilities for manipulating blocks and transactions."""
from .mininode import *
from .script import CSc... |
import torch
import torch.nn as nn
import numpy as np
NORM_PPF_0_75 = 0.6745
class WeightQuantizer(nn.Module):
def __init__(self, nbit, num_filters, method='QEM'):
super().__init__()
self.nbit = nbit
if self.nbit == 0:
return
self.num_filters = num_filters
se... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 24 15:52:00 2020
@author: d.stewart
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as pat
import scipy.io as sio
from PIL import Image
im = Image.open('C:\\Users\\d.stewart\\NAVYREPO\\2020_NEON_Competition\\idtrees_competition_evaluatio... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as Data
import torchvision
import torch.optim as optim
import argparse
import sys
import os
from PIL import Image
import torchvision.transforms.functional as TF
from skimage import io, transform
from my_net import Ne... |
"""This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license.
"""
import hashlib
import logging
import os
import shutil
from copy import deepcopy
from datetime import datetime
import ujson as json
from core impor... |
#!/usr/bin/env python3
"""
Solves day 7 tasks of AoC 2020.
https://adventofcode.com/2020/day/7
The problem descriptions allow us to model the rules as a DAG (directed acyclic
graph) where a bag color is a node and directed edges point to all other color
bags that must be inside it.
References
----------
DAG: https:/... |
"""Tests for the basic, one dimensional binary and unary operations"""
import ad
import numpy as np
import pytest
def test_constant_addition():
a = ad.Constant(5)
b = ad.Variable('b')
c = a + b
assert c.eval({b: 5}) == 10
def test_constant_regular_addition():
b = ad.Variable('b')
c = b + 3
... |
import hashlib
from itertools import count
from typing import Dict, List, Tuple, Union
from pp.component import Component
class SequenceGenerator:
def __init__(
self, start_sequence="IL", repeated_sequence="ASASBSBS", end_sequence="LO"
):
"""
A simple sequence generator.
Main ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, io, sys, re
"""
This script goes over a running list of paired norm words and lemmas to find multiword expressions based on a list
of candidate expressions from a lexicon. Overlapping spans are prohibited and spans are detected up to a maximum
length (default=4).
"... |
# encoding: utf-8
"""
check.py
Created by <NAME> on 2013-03-18.
Copyright (c) 2009-2017 Exa Networks. All rights reserved.
License: 3-clause BSD. (See the COPYRIGHT file)
"""
class TYPE(object):
NULL = 0x01
BOOLEAN = 0x02
INTEGER = 0x04
STRING = 0x08
ARRAY = 0x10
HASH = 0x20
class PRESENCE(... |
import sqlite3
import time
from datetime import datetime
from typing import Dict, TYPE_CHECKING, Tuple
import dateutil.relativedelta
import requests
from configuration import config
if TYPE_CHECKING:
import telegram
import telegram.ext
conn = sqlite3.connect('/db/steam_id.db', check_same_thread=False)
curso... |
# This script subsets the human genome fasta and annotation gff file as well as bam files to some regions of interest, as a test case
# run with:
# python prepare_data.py --genome $hg38 --annotation $gff --out_prefix example
# python prepare_data.py --genome $hg38 --annotation ${sa}.bam --out_prefix example_${sa}
i... |
# For taking a books ISBN or ISSN and adding it to a spreadsheet with info
import isbnlib
import csv
# Refer to https://github.com/fabiobatalha/crossrefapi for documentation
# on using the crossref API for getting info from ISSNs and DOIs
from crossref.restful import Journals
def createISBNLibraryFile(filen... |
#
# (C) Copyright 2014 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmen... |
# Inspired from OpenAI Baselines. This uses the same design of having an easily
# substitutable generic policy that can be trained. This allows to easily
# substitute in the I2A policy as opposed to the basic CNN one.
import os
os.environ["CUDA_VISIBLE_DEVICES"]="1"
import numpy as np
import tensorflow as tf
from comm... |
import gym
from gym import wrappers
import random
import numpy as np
import tflearn
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.estimator import regression
# import keras
# from keras.layers.core import input_data, dropout, fully_connected
# from keras.layers.estimator impor... |
##
# Data of Red Nova
##
import numpy as np
import os
from pystella.rf import band
from pystella.rf.lc import SetLightCurve, LightCurve
from pystella.util.reader_table import read_table_header_float, table2curves
sn_path = os.path.expanduser('~/Sn/Release/svn_kepler/stella/branches/lucy/run/res/sncurve/rednovaM31')... |
import cypher
import tkinter as tk
import string
def encryptcompat():
global eTextGlobal
eTextGlobal = ""
str1 = cypher.encrypt(textEntry.get(), rotEntry.get())
n = 95
chunks = [str1[i:i + n] for i in range(0, len(str1), n)]
encryptedText.set('\n'.join(chunks))
eTextGlobal = '\... |
import os
import sys
import numpy as np
import h5py
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
# Download dataset for point cloud classification
DATA_DIR = os.path.join(BASE_DIR, 'data')
if not os.path.exists(DATA_DIR):
os.mkdir(DATA_DIR)
if not os.path.exists(os.path.join(DAT... |
"""
pytest ipython plugin modification
Authors: <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
"""
import os
import logging
from pprint import pformat
try:
from Queue import Empty
except:
from queue import Empty
# Kernel for jupyter notebooks
from jupyter_client.manager import KernelManager
from jupyter_client.ker... |
#! python3
# 0
# 0 000000 0 000000 0 0 000000000 00000000 00000000 0 000000
# 0 00 0 0 0 00 00 0 0 0 0 0 0
# 0 00 0 0 00000 00 000000 00 0 ... |
# Copyright (c) 2019 UAVCAN Consortium
# This software is distributed under the terms of the MIT License.
# Author: <NAME> <<EMAIL>>
import sys
import typing
import decimal
import contextlib
import click
import pyuavcan
import yakut
from yakut.helpers import EnumParam
from yakut.param.formatter import Formatter
from y... |
import sys
import hashlib
import os
import functools
import shutil
import json
def size_in_human_form(size):
#NOTE: 2**10 = 1024
power = 2**10
n = 0
Dic_powerN = {0 : '', 1: 'K', 2: 'M', 3: 'G', 4: 'T'}
while size > power:
size /= power
n += 1
#print("FileSize : " ,size, Dic_po... |
#!/usr/bin/env python
"""
Script that fixes some lint issues automatically.
"""
from __future__ import print_function
from collections import defaultdict
import os
import re
import sys
# Define the states.
FILE_BEGINNING, SUMMARY_SEEN, IN_VIOLATIONS_FOR_FILE, BETWEEN_FILES, DONE = range(5)
def handle_indentation(fil... |
#!/usr/bin/env python3
from subprocess import Popen, PIPE
import sys
import os
import json
import concurrent.futures
import time
import logging
import argparse
from influxdb import InfluxDBClient, line_protocol
import paho.mqtt.publish as publish
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__... |
import functools
import os
import sys
from collections import defaultdict, OrderedDict
from difflib import get_close_matches
import django
from django.apps import apps
from django.conf import settings
from django.core import management
from django.core.exceptions import ImproperlyConfigured
from django.core.management... |
# -*- coding: utf-8 -*-
"""Classes for calcs e wfls analysis."""
from __future__ import absolute_import
import numpy as np
from scipy.optimize import curve_fit
from matplotlib import pyplot as plt, style
import pandas as pd
import copy
from aiida_yambo.workflows.utils.helpers_aiida_yambo import *
from aiida_yambo.workf... |
from PIL import Image
import numpy as np
import heapq
# np.set_printoptions(threshold=np.inf)
def mode_to_img(mode,background=None):
if background:
mode = np.where(mode < 1, 0, background)
array_mode = np.array(mode).astype('uint8')
image = Image.fromarray(array_mode).convert('RGB')
return imag... |
from django.utils import timezone
from datetime import timedelta
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.list import ListView
from django.shortcuts import get_object_or_404
from accounts.models import CustomUser
from projects.models import Activity, Capacity, Leave, Project, ... |
'''
Created on 12 Aug 2020
@author: <NAME>
'''
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from typing import List, Tuple
def add_uni_time(snapshots: np.array, dt:float =1.0) -> np.array:
'''
Adds uniformely-spaced time dimension to snapshot matrix.
:param snapshots:... |
"""A module that defines Airflow DAGS for data workspace pipelines."""
from functools import partial
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID
from airflow.operators.python_operator import PythonOperator
from dataflow import config
from dataflow.dags import _PipelineDAG
from dataflow.ope... |
def transaction_write_to_table(conn, stage, table, pattern, purge=True):
conn.execute(
f"""COPY INTO {table} FROM @{stage}/{pattern}.gz FILE_FORMAT=(TYPE=CSV, FIELD_DELIMITER='|', NULL_IF='None') PURGE={purge}; """
)
return True
def merge_into_auction_table(conn, stage, table, pattern):
con... |
print("Keep Talking And Nobody Explodes - Kronorox Solvers")
print("On the Subject of Wires (Terminal Method)")
print("Version 1.0")
print(" ")
#Always start by asking the serial number
def makethedatabase():
wiredb = []
wirenum = 1
serialnumber = input("Is the last digit of the serial number odd? (y/n): ... |
import os
from PIL import Image
import cv2
import numpy as np
def img_cos_for_labels(basePath, checkPath, baseRoi=[],checkRoi=[]):
baseRoi=cut_roi_for_labels(basePath,baseRoi)
checkRoi=cut_roi_for_labels(checkPath,checkRoi)
baseGray=rgb2gray(baseRoi)
checkGray=rgb2gray(checkRoi)
return cos(... |
# Copyright (c) 2022, 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... |
""" Interface class for the LISP-based mReasoner implementation.
"""
import copy
import logging
import os
import platform
import queue
import subprocess
import multiprocessing
import time
import select
import urllib.request
import zipfile
import numpy as np
import scipy.optimize as so
FASL_ENDINGS = {
'Darwin... |
import math
def read_matrix(n, m):
matrix = [[] for _i in range(n)]
for row in range(n):
matrix[row] = list(map(float, input().split()))
return matrix
def matrix_addition(a, b):
n = len(a)
m = len(a[0])
result_matrix = [[0 for _i in range(m)] for _i in range(n)]
for row in range(n... |
# Copyright 2021 <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... |
import asyncio
import copy
import logging
from collections import OrderedDict
import aiohttp
import ujson as json
from cachetools import TTLCache
from sanic import Sanic
from sanic_cors import CORS
from tamarco.core.settings.settings import SettingNotFound
from tamarco.resources.bases import BaseResource
from tamarco... |
#!/usr/bin/env python3.7
# -*- coding: utf-8 -*-
import argparse
import os
import os.path
import posixpath
import shutil
import sys
import urllib.parse
import urllib.request
from typing import Any, Dict, Iterable, Iterator, Mapping, Optional, Tuple
import ffmpeg
import youtube_dl
from tqdm import tqdm
class VideoFi... |
import numpy as np
from functools import reduce
import torch
from .masked_body_builder import MaskedBodyBuilder
from .train_dojo import TrainDojo
def weight_prune_masks(network, sparsity_level):
""" Generate set of masks that 0-out smallest magnitude weights """
all_weights = []
# Construct list of all wei... |
# coding=utf-8
# @Time : 2020/12/4 9:42
# @Auto : zzf-jeff
import argparse
import os
import sys
import torch
import os.path as osp
import time
import copy
import torch.nn as nn
from torch.nn.parallel import DistributedDataParallel as DDP
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 2 11:22:11 2018
Course schedule fine tuning
- only considered swapping courses of the same homeroom, but swapping courses with
different homeroom e.g. from teacher's timetable or from subject room timetable should
also be possible
i.e. by swaping in-between two homeroom... |
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
from flask_cors import CORS, cross_origin
from requests import Session
from dotenv import load_dotenv
from flask import Flask, request
import json
import time
import os
load_dotenv()
api = Flask(__name__)
api.config['CORS_HEADERS'] = 'Content-... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 6 10:37:16 2019
@authors: <NAME>, <NAME>, <NAME>
File Description:
The utility file used to load and preprocess data, format results, and
save results.
"""
# Libraries
from time import time
from os.path import exists, join
from os import mkdir
f... |
import numpy as np
import math
import time
def historical_log_likelihood(pre, xs, lb, mu=None):
""" Log likelihood of matrix of data """
from sklearn.covariance._empirical_covariance import log_likelihood, empirical_covariance
if mu is None:
emp_cov = empirical_covariance(xs)
else:
em... |
import github
import nbformat
from .gisthub import gisthub, _hashtags
import nbx.compat as compat
def parse_tags(desc):
# real tags and not system-like tags
tags = _hashtags(desc)
if '#notebook' in tags:
tags.remove('#notebook')
if '#inactive' in tags:
tags.remove('#inactive')
ret... |
from .Calibration.CalibrationMain import *
from .DartDetection.DartLocation import *
from .DartDetection.DartDetection import *
from .Calibration.VideoCapture import *
import time
def one_camera_loop(websocket):
videoStream_L, snapshot_cam_L = getVideoStream(src=1)
videoStream_R, snapshot_cam_R = getVideoStre... |
# -*- coding: utf-8 -*-
"""Fourier analysis is a method for expressing a function as a sum of periodic components, and for recovering the signal from those components.
"""
import numpy as np
from scipy.fft import fft
import matplotlib.pyplot as plt
def fast_fourier_transform(signal, sampling_rate, plot=False, **kwarg... |
"""Functions for generating general quality control plots.
"""
import numpy as np
import plotly.graph_objs as go
from plotly import tools
from genometools.expression import ExpMatrix
from .. import util
def plot_cell_transcript_distribution(
matrix, name='', color='rgb(31, 119, 180)',
width=1350, ... |
import plotly.graph_objects as go
from dataclasses import dataclass, field
from typing import List, Tuple
from configuration_parameters import *
@dataclass
class Parameter:
"""Parameter used for decision making
Args:
value (float): Value of the parameter
is_increasing_better ... |
import unittest
from boozetools.support import interfaces
from boozetools.parsing import automata, context_free
class GrammarTester(unittest.TestCase):
def setUp(self):
print(self._testMethodName)
self.cfg = context_free.ContextFreeGrammar()
self.cfg.start.append('S')
self.pathological = False
def r(se... |
"""
This script can produce an index with today's date and update the alias to point to it.
There is also a function to populate the elasticsearch store with the contents of the local store.
When updating the index:
- new index must be created with new date - clone_index_and_update_alias function creates this, fills w... |
"""
### CODE OWNERS: <NAME>
### OBJECTIVE:
Module for the data type checks
### DEVELOPER NOTES:
"""
import re
import os
import string
import pandas as pd
import numpy as np
from dateutil.parser import parse
import logging
logging.basicConfig(
format="%(asctime)s - %(message)s", level=os.environ.get("LOGLEVEL",... |
from flask import Flask
from flask_mongoengine import MongoEngine
import json
import toml
import nltkmodules
# Classifier
from classifier import intent_identifier
# Symptoms-Disease
from symptoms_disease_predictor import symptoms_disease_predict
# Accompany-Disease
from accompany_disease_predictor import accompany_dise... |
import sys
import time
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from Bio import SeqIO
def check_arg():
conc = sys.argv[1:]
if '-f' and '-s1' and '-s2' and '-w' and '-t' not in conc:
text = 'DotPlot plotting script use it like this: \n\nsequence_dotplot.py -f fa... |
###############################################################################
# DO NOT MODIFY THIS FILE #
###############################################################################
import inspect
import logging
import time
from collections import namedtuple
f... |
"""
Random Forest Classifier to predict course completion
"""
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pickle
# from rfpimp import *
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import make_scorer, confusion_matrix, recall_score, roc_auc_score,... |
from keras.callbacks import History
from keras import models, layers
from skimage.transform import resize
from keras.optimizers import Adam
import json
from tensorflow.python.framework.ops import Tensor
from keras.utils import to_categorical
from keras.layers import Dense, Conv2D, Flatten, Input, MaxPooling2D, Layer, ... |
#!/usr/bin/env python
# coding: utf-8
import json
import os
import unittest
class TestGeohex(unittest.TestCase):
def setUp(self):
with open(os.path.join(os.path.dirname(__file__), 'hex_v3.2_test_code2HEX.json'), 'r') as f:
self.tests = json.load(f)
def test_consts(self):
from geo... |
from django.shortcuts import render # For rendering HTTP requests
from django.http import HttpResponse
from django.http import Http404 # For not found
from django.db.models import Q, Subquery, Count, DecimalField # For running complex queries
from django.db.models.functions import ExtractHour
from django.core.pagi... |
import numpy as np
def ssa(angle: np.ndarray) -> np.ndarray:
r"""
Express input angle between :math:`-\pi` and :math:`+\pi` rad
:param angle: input angle in rad
:return: angle in rad
"""
return (angle + np.pi) % (2 * np.pi) - np.pi
def Rzyx(phi: float, theta: float, psi: float) -> np.ndarra... |
#!/usr/bin/env python3
import argparse
import os.path as osp
from glob import iglob
import torch
import numpy as np
from skimage.io import imread, imsave
import core
import impl.builders
import impl.trainers
from core.misc import R
from core.config import parse_args
from core.factories import model_factory
from util... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.