text stringlengths 3.07k 12.6k |
|---|
import time
start_all=time.time()
from pandas import read_csv
from pandas import concat
from pandas import DataFrame
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import MinMaxScaler
from numpy import concatenate
import numpy as np
fro... |
import os
import sys
import json
from typing import Tuple, Dict
import requests
config_file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data', 'config.json')
with open(config_file_path, 'r') as f:
config = json.load(f)
def are_credentials_valid(authentication: Tuple[str, str]) -> bool:
... |
# /usr/bin/env python2.7
# -*- mode: python -*-
# =============================================================================
# @@-COPYRIGHT-START-@@
#
# Copyright (c) 2020, Qualcomm Innovation Center, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification,... |
# ==============================================================================
# Purpose:
# Download Near-Real-Time (NRT) SMAP L4 soil moisture and CLDAS forcing data
#
# author: <NAME>, 8/9/2021
# ==============================================================================
import os
import numpy as np
import... |
import util
import numpy as np
import scipy.integrate
POS = slice(0,3)
VEL = slice(3,6)
EUL = slice(6,9)
OMG = slice(9,12)
# State space representation: [x y z x_dot y_dot z_dot theta phi gamma theta_dot phi_dot gamma_dot]
# From Quadcopter Dynamics, Simulation, and Control by <NAME>
def state_dot(time, state, quad)... |
import sys
from machine import Pin, SPI, UART
from .cc1101 import CC1101
from .configuration import *
from .strobes import *
import utime
import uos
import uasyncio
red_led = Pin(16, Pin.OUT) # extra
blue_led = Pin(2, Pin.OUT) # built-in
def init_spi():
chip = sys.platform
if chip == 'esp32':
return S... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from collections import namedtuple
from itertools import chain
from logging import getLogger
from .linked_data import linked_data
from .package_cache import PackageCache
from .repodata import collect_all_repodat... |
import os
import time
import logging
import numpy as np
from .fly import FlyScan
logger = logging.getLogger(__name__)
class Fly2D(FlyScan):
'''2D fly scan
Scan types:
* soft: uses trajectory generation and triggering via motion scripts
* pyramid: same method as soft, but acquires in both forward a... |
#!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "... |
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
import sys
from bes.common.check import check
from bes.common.string_util import string_util
from bes.key_value.key_value import key_value
from bes.key_value.key_value_list import key_value_list
from bes.system.log import logger... |
from flask_restx import Resource, Namespace, fields
from flask import current_app, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from flask_api import status
from mongoengine import errors as mongoengine_errors
from pymongo import errors as pymongo_errors
from werkzeug.security import generate_... |
import json
from typing import List
from ..exception import SectionSerialisationException
import os
from .constants import *
class Section():
"""Section
Section will contain subsections which are of type Section
"""
def __init__(self,name=None):
# Core Attributes
self.name = self.__cl... |
#!/usr/bin/env python
"""Loose port of the examples in `Kerflyn's Blog / Playing with Scala's
pattern matching
<http://kerflyn.wordpress.com/2011/02/14/playing-with-scalas-pattern-matching/>`_
"""
from __future__ import print_function
from pyfpm.matcher import Matcher
# Traditional approach
print('-'*80)
toYesOrNo =... |
#!/usr/bin/env python
#
# Looks up Google Maps
#
# Copyright (c) 2017 DevicePilot Ltd.
#
# 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 ... |
"""Some data cleansing helpers: categorical features, NaN values, datetime
"""
import pandas as pd
from fintulib import common
def cast_columns_categorical(dfs, col_categorical=[]):
"""Convert columns to categorical, considering their levels across many dataframes.
Dataframes passed to this function are modif... |
from typing import List, Tuple, Union
import numpy as np
def beta_posteriors_all(
totals: List[int],
positives: List[int],
sim_count: int,
a_priors_beta: List[Union[float, int]],
b_priors_beta: List[Union[float, int]],
seed: Union[int, np.random.bit_generator.SeedSequence] = None,
) -> np.nda... |
import sys
from typing import List
from math import inf
N, B = map(int, input().split())
MAX_ASKS = 150
UNKNOWN = 2
def eprint(*args, force=False, **kwargs):
ENFORCE_FORCING = True
if not ENFORCE_FORCING or force:
print(*args, file=sys.stderr, **kwargs)
def toggle_bytes(initial_bytes):
return ... |
# Copyright (c) 2020, DjaoDjin inc.
# 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 and t... |
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
import concurrent.futures
from concurrent.futures import Future
from azure.core.exceptions import (
HttpResponseError,
ClientAuthe... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
import multiprocessing as mp
from xmlrpc import client as xmlrpclib
from scriptconfig import URL, DB, UID, PSW, WORKERS
import logging.handlers
import os
import time
import multiprocessing_logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# ... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
Copyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
# Copyright 2021 Canonical 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 agreed to in writing, s... |
import numpy as np
import healpy as hp
import synth_gaussian as synth
from mpi4py import MPI
from enum import IntEnum
import h5py
class tags(IntEnum):
READY = 0
DONE = 1
EXIT = 2
START = 3
n_batches = 300
batchsize = 16
n_stars = n_batches * batchsize
nlambda = 150
def compute(star, nlambda):
al... |
import os
import difflib
import pytz
from datetime import datetime
from html_parser import DemoOutputParser
TIMEZONE = pytz.timezone("America/Toronto")
def parse_demo_outputs(filename):
"""Parse the outputs produced of a QML repo demonstration from file.
Args:
filename (str): The name of the demonst... |
from typing import Any, Dict, Iterable, List, NamedTuple, Optional, Sequence, Type, Union
from ConfigSpace.configuration_space import ConfigurationSpace
from ConfigSpace.hyperparameters import (
CategoricalHyperparameter,
Constant,
Hyperparameter,
UniformFloatHyperparameter,
UniformIntegerHyperpara... |
import click
from typing import IO
from stiff.data.fixes import fix_all
from stiff.data.constants import DEFAULT_SAMPLE_LINES, DEFAULT_SAMPLE_MAX
from stiff.writers import AnnWriter, man_ann_ann
from stiff.extract import FinExtractor
from stiff.corpus_read import read_opensubtitles2018
from stiff.utils import parse_q... |
'''
app.py
------
This file contains the logic for the back end of the housing-insights tool.
It does three things:
1. Auto loads data from Open Data DC (crime and permit) and creates the
zone facts table every morning. It emails reports of this to CNHED staff.
2. Allows CNHED staff to load other tables ... |
import operator
from datetime import datetime
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.db.models import IntegerField, OuterRef, Q, Subquery
from django.db.models.fields.json import KeyTransform
from django.db.models.functions import Cast
from django.utils.... |
# Copyright 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 writing, ... |
#!/usr/bin/env python
import os
import sys
import unittest
from tests.magictest import MagicTest as TestCase
from textwrap import dedent
import clevercss
from clevercss import convert
from clevercss.line_iterator import LineIterator
from clevercss.errors import *
def eigen_test():
filename = os.path.join(os.pa... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pickle as pkl
from scipy.special import logsumexp
from scipy.stats import pearsonr
from scipy.stats import norm
from compositional_lotka_volterra import CompositionalLotkaVolterra
from generalized_lotka_volterra import GeneralizedLotkaVolte... |
from hls import db, login_manager
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
@login_manager.user_loader
def load_user(user_id):
return User.query.get(user_id)
########################################################################### User
class Us... |
from django.shortcuts import render
# Create your views here.
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.shortcuts import render
from django.views import View
from addersses.models import Area,Address
from django.http import JsonResponse
fr... |
# Dependents:
# - Must be run with python3 for enums
# - Needs python-docx to build the word files
from enum import Enum
import math
import yaml
from term import Term
from term import Tag
from docx import Document
from docx.shared import Inches
headerEndChar = '<'
spaceToTab = 2
headerDone = False
yamlText = ""
doc... |
import numpy as np
from pyDOE import lhs
import dataset_creation
import utils
from definitions import input_upper_bound, input_lower_bound, valid_sampling_methods
# %% Initialization ---------------------------------------------
# These are the models used for N-1 analysis
Nm1_models = dataset_creation.NSWPH... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. moduleauthor:: hbldh <<EMAIL>>
Created: 2016-04-14
"""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import warnings
import logging
from functools import wraps
from ctypes import cast, POINTER, c_flo... |
import numpy as np
import xml.etree.ElementTree as ET
import torch
def get_gt_boxes(xmlfile):
'''get ground-truth bbox from VOC xml file'''
tree = ET.parse(xmlfile)
objs = tree.findall('object')
num_objs = len(objs)
gt_boxes = []
for obj in objs:
bbox = obj.find('bndbox')
x1 = fl... |
# Import libraries
from numpy import array, eye, vstack, sin, cos, sqrt, arctan2
from numpy.linalg import norm
# Directional Cosine Matrix (DCM)
# x-axis rotation
def Rx(rx):
return array([[1, 0, 0],
[0, cos(rx), -sin(rx)],
[0, sin(rx), cos(rx)]])
# y-axis rotation
def Ry(ry... |
# copy xmls from smp repo
# replace all `name="root` into `name="ignore` to make it readable to pybullet
# delete floor
from stable_baselines3.common.vec_env import DummyVecEnv, VecNormalize
from stable_baselines3 import PPO
import time
import pathlib
import gym
import pybullet as p
import cv2
from common import commo... |
from functools import reduce
from botlang.ast.ast_visitor import ASTVisitor
from botlang.evaluation.values import *
class ExecutionStack(list):
def print_trace(self):
from botlang.macros.default_macros import DefaultMacros
return reduce(
lambda a, n: a + n + '\n',
[
... |
from __init__ import db
from helper import helper, encryption
import time, json
from classes.user_details import UserDetailData
from classes.site_settings import site
class ConsultationData:
table = 'consultations'
def __init__(self, c_time=None, c_date=None, comments=None, block=None, unit=N... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007-2009 <NAME> ( <EMAIL> )
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
"""
Short functions for working with collections of raw reads.
"""
... |
#!/usr/bin/env python3
# Copyright 2018 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.
import os
import unittest
from cros.factory.hwid.v3.bom import BOM
from cros.factory.hwid.v3.common import HWIDException
from cros... |
import pytest
from dcicutils.misc_utils import ignored
from unittest import mock
from ..commands import load_data as load_data_module
from ..commands.load_data import load_data_should_proceed, main as load_data_main
def test_load_data_should_proceed():
cgap_envs = ['fourfront-cgap', 'fourfront-cgapdev', 'fourfr... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Run gtsrcmaps for a single energy plane for a single source
This is useful to parallize the production of the source maps
"""
from __future__ import absolute_import, division, print_function
import os
import math
import BinnedAnalysis as BinnedAnaly... |
import time
import sys
import datetime
import subprocess
import sys
import os
import datetime
import traceback
import math
import base64
import json
from time import gmtime, strftime
import random, string
import time
from time import gmtime, strftime
import random, string
import psutil
import base64
import uuid
# Impor... |
import os
import torch
import numpy as np
import scipy.misc as m
from torch.utils import data
from PIL import Image
import sys
sys.path.append('.')
import matplotlib.pyplot as plt
from collections import OrderedDict
import os
import numpy as np
import glob
from utils import *
labels = {'bottle_oil':4,
'cleaning_t... |
#!/usr/bin/env python
# Example: TAXON=homo CELL_COUNT=3000 S3_DIR=s3://biohub-spyros/data/10X_data/CK_Healthy/ ./10x_count.py
import argparse
import os
import sys
import subprocess
import tarfile
from utilities.log_util import get_logger, log_command
CELLRANGER = 'cellranger'
S3_RETRY = 5
S3_LOG_DIR = 's3://james... |
import collections
import sys
import pip
import json
import changelogs
import urllib.request
from packaging import version
from urllib.error import HTTPError, URLError
from distutils.version import LooseVersion
SECURITY_NOTICE_KEYWORDS = [
'security', 'vulnerability', 'cve', 'xss', 'sql injection',
]
DISPLAY_TAB... |
"""
ColECM: Collagen ExtraCellular Matrix Simulation
ANALYSIS ROUTINE
Created by: <NAME>
Created on: 09/03/2018
Last Modified: 19/04/2018
"""
import numpy as np
from skimage import draw
from skimage.transform import rotate
from skimage.color import label2rgb, grey2rgb, rgb2hsv, hsv2rgb
from skimage.exposure import ... |
#!/usr/bin/env python3
# -*- coding: utf8 -*-
import os
from concurrent import futures
import cv2 as cv
import numpy as np
import pandas as pd
from tqdm import tqdm
import lineutils as ut
from lineutils import r, t
def nubBy(predicate, iterable):
res = []
for e in iterable:
if not any([predicate(e... |
import numpy as np
import nixio
import matplotlib.pyplot as plt
import matplotlib.patches as patches
def create_example_data(nixfile):
sampling_interval = 0.001
total_duration = 3.0
time = np.arange(0., total_duration, sampling_interval)
stim = np.ones(time.shape)
stim_duration = 0.25
interval... |
from abc import abstractmethod
from collections import defaultdict
class MetricBase(object):
@abstractmethod
def evaluate(self, *args, **kwargs):
raise NotImplementedError
@abstractmethod
def get_metric(self, reset=True):
raise NotImplemented
def __call__(self, p_ids, pred, eval... |
import argparse
import os
from itertools import cycle
from time import sleep
import numpy as np
from PIL import Image
from tqdm import tqdm
from ..common_util.global_vars import PROJ_DIR
from ..common_util.image import cover_crop, invert_binary_image
from ..common_util.misc import makedirs, ThreadPool
def create_fr... |
"""Some handy diagnostic plots"""
from typing import List, Any
import numpy as np
import matplotlib.pyplot as plt
import astropy.stats
# would like to have these pass axes between each other to combine what's being plotted
# also want to accommodate multiple filters/bands of y
from justice.features import period_dis... |
import logging
import random
import torch
from torch import nn
from torch import optim
logger = logging.getLogger("experiment")
class TD_MC(nn.Module):
def __init__(self, args, config, device, backbone_config=None):
"""
#
:param args:
"""
super(TD_MC, self).__init__()
... |
# coding: utf-8
"""
RESTful API for SampleDB
"""
import collections
import base64
import flask
from flask_restful import Resource
import wtforms.validators
from .authentication import object_permissions_required, Permissions
from ...logic.actions import get_action
from ...logic.objects import get_object
from ...logi... |
"""
Train a GAN to generate images using the CIFAR10 Dataset using W-Loss and Gradient Penalty.
References:
https://www.coursera.org/learn/build-basic-generative-adversarial-networks-gans
https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html
"""
import os
import torch
from torch import nn
from torch... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 10 17:30:57 2019
@author: dennybritz, FritzD
"""
import time
import numpy as np
import CarRentalEnvironment as jack
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 22})
start_time = time.time()
print("start!")
#env = GridworldEnv... |
# author: clarkmatthew
'''
Example:
import lablogger
self.logger = lablogger.LabLogger(name='LABTEST')
self.log = self.logger.log
self.debug("This is a debug message")
self.critical("this is a critical message")
'''
import os
import sys
import logging
import time
class LabLogger(logging.Log... |
"""
Models for Scholarship app.
"""
import datetime
import re
from django.contrib.auth.models import User
from django.core import validators
from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ValidationError
from django.db import models
from django.core.validators import RegexVal... |
import subprocess
import os
import sys
import re
import glob
from io import StringIO
from argparse import ArgumentParser
import shutil
import itertools
import gc
import copy
import pandas as pd
from biopandas.pdb import PandasPdb
from collections import defaultdict
import numpy as np
from scipy import spatial
import... |
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
g_earth = 9.81
g_moon = 1.62
################ Functions ####################
def fallingtime(l,g,theta,theta2,dt):
'''Calculates angular acceleration, angular velocity, velocity, and falling time for an inverted pendulum between two angles(in degre... |
import os
from typing import List, Union, Optional, Any, Tuple
import asyncio
import aiohttp
import json
from configparser import ConfigParser
# import websocket
from slack.web.client import WebClient
from slack.signature.verifier import SignatureVerifier
from slack.web.slack_response import SlackResponse
from slack.... |
# -*- coding: utf-8 -*-
# This file is part of modulemd-zanata
# Copyright (C) 2018 <NAME>
#
# Fedora-License-Identifier: MIT
# SPDX-2.0-License-Identifier: MIT
# SPDX-3.0-License-Identifier: MIT
#
# This program is free software.
# For more information on the license, see COPYING.
# For more information on free softwa... |
"""Update entry in pythonup/versions. Only works with new styles installers.
"""
import argparse
import contextlib
import operator
import json
import os
import pathlib
import re
import sys
import urllib.parse
import requests
BLACKLISTED_IDS = {
287, # 3.7.2 has broken build tool discovery. (bpo-35699)
}
de... |
from flask import Flask, render_template, jsonify, request
from time import time
from flask_cors import CORS
import Crypto
import Crypto.Random
from Crypto.PublicKey import RSA
import binascii
from collections import OrderedDict
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
from uuid import uuid4
... |
from flask import request, make_response, send_from_directory
from functools import wraps
import jwt
import datetime
import os
from app import app, db
from app.models import JobPosts, JobPostsReqs, Talent
# from app.get_details import get_details
from app.utils import hash_file
from app.model_rank import model_rank
d... |
import pygame, os, random, numpy as np, glob, psychopy
import psychopy.event
import psychopy.core
import psychopy.visual
import pandas
from psychopy import visual
def probe_organizer(subject_ID='117', main_path='C:\\Users\\naama\\PycharmProjects\\untitled'):
#Organizes the probe comparisons. Output is the txt fil... |
"""Class for handling primary OCSP responses"""
from .utils.asn1parser import ASN1Parser
from .utils.cryptomath import bytesToNumber, numBytes, secureHash
from .x509 import X509
from .signed import SignedObject
from .errors import TLSIllegalParameterException
class OCSPRespStatus(object):
""" OCSP response status... |
import json
import time
from cryptography.fernet import Fernet
from django.http import HttpResponse
cipher_key = b'BxgJ3nXVtc8ErKdoD7gx7R0TkK1x4U8GYMSwcbHH7WE='
cipher = Fernet(cipher_key)
class RFSException(Exception):
def __init__(self, ret="-1", msg="Exception!"):
self.ret = ret
self.msg = ms... |
#!/usr/bin/env python3
# coding=utf-8
# Copyright 2019 YAM AI Machinery Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... |
from selenium import webdriver
from configparser import ConfigParser
import time
import os
CONFIG = ConfigParser()
CONFIG.read('config.ini')
EMAIL = CONFIG.get('LOGIN DETAILS', 'EMAIL')
PASSWORD = CONFIG.get('LOGIN DETAILS', 'PASSWORD')
PHONE = CONFIG.get('PAYMENT DETAILS', 'PHONE')
WEBSITE = CONFIG.get('U... |
"""
Custom integration to integrate irrigation_unlimited with Home Assistant.
For more details about this integration, please refer to
https://github.com/rgc99/irrigation_unlimited
"""
import logging
import voluptuous as vol
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.core imp... |
"""
clang_parser.py
Parse C code into a map which maps from (struct name) to
(base-class- and record-type- expanded fields list).
"""
from dataclasses import dataclass
from typing import List, Mapping
import clang.cindex
# Expected path of this file: "postgres/cmudb/tscout/"
# Path to the Postgres root.
CLANG_POST... |
from cashew.exceptions import InternalCashewException
from cashew.exceptions import UserFeedback
from cashew.plugin import Plugin, PluginMeta
from example.classes2 import Csv
from six import add_metaclass
from six import with_metaclass
import example.classes
class Data(example.classes.Data):
"""
Docstring goes... |
from tensor2tensor.visualization import attention
import h5py
import numpy as np
from sample_latent import visualize_latent_rep
from molecules.model import Transformer
from dataloader import SmilesToArray, MakeSmilesDict, MakeSmilesData
from keras.optimizers import Adam
from metakernel.display import display
from utils... |
################################################
# SIMPLE SOCKETS -- SimpleSockets.py #
# Author -- <NAME> #
# September 30, 2019 #
################################################
#import sys for unknown exception handlers
import sys
import socket
class Server... |
""" Module defining annotations.
This module contains two classes:
1. :class:`~pypet.annotations.Annotations`
Container class for annotations. There are no restrictions regarding what is considered
to be an annotation. In principle, this can be any python object. However,
if using the sta... |
import pytest
from urlfinderlib.tokenizer import UTF8Tokenizer
bytes_0_char = b"Test with 0 chars"
expected_0_char = []
bytes_1_char = b"%(char)sTest with 1 char"
expected_1_char = []
bytes_2_char = b"%(char)sTest%(char)s with 1 char"
expected_2_char = ["Test"]
bytes_3_char = b"%(char)sTest%(char)s with%(char)s ... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2019 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Tests for OpenAIRE dataset loaders and resolvers."""
from __future__ import absol... |
"""Script that tests the compiled TF-KDTree
"""
import sys
sys.path.append("../") #TODO: Hack
import os
import unittest
import numpy as np
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
assert(not tf.executing_eagerly())
from tf_nearest_neighbor import nn_distance, buildKDTree, searchKDTree
import sys
... |
import random
from abc import abstractmethod
import cv2
import numpy as np
from PIL import Image
from imageio import imread
from utils.Resize import resize, ResizeMode
from torch.utils.data import Dataset
TARGETS = 'targets'
IMAGES_ = 'images'
INFO = 'info'
def list_to_dict(list):
"""
:param list: input list
... |
import logging
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from ngw.core.models import Contact, ContactGroup, MatrixRoom
from ngw.extensions.matrix import matrix
FIELD_MATRIX_DISPLAYNAME = 99
FIELD_MATRIX_DISABLED = 100 # matrix users
MATRIX_ADMIN_ID = f'@adm... |
"""Core application object"""
import gws
import gws.common.api
import gws.common.auth
import gws.common.client
import gws.common.layer
import gws.common.metadata
import gws.common.project
import gws.common.search
import gws.common.template
import gws.gis.zoom
import gws.qgis.server
import gws.server.monitor
import gw... |
#!/usr/bin/env python3
import cv2
import numpy as np
from pathlib import Path
import histogram
from matplotlib import pyplot as plt
import os
import multiprocessing
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('clutter', help='directory containing clutter data')
parser.add_argument('out', he... |
#! /usr/bin/env python
# Copyright (c) 2018, Vienna University of Technology (TU Wien), Department of
# Geodesy and Geoinformation (GEO).
# 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. Re... |
# -*- coding: utf-8 -*-
import sys
import json
import datetime
import base64
try:
import http.client as httpclient
except ImportError:
import httplib as httpclient
import io
from time import time as stime
from hashlib import sha1
from hashlib import md5
import hmac
from collections import namedtuple
LINKHUB_S... |
"""
Basic classes and functions for semantic representations.
"""
from typing import (Optional, Mapping, Tuple, List, Union, Sequence)
from delphin.lnk import Lnk, LnkMixin
# Default modules need to import the PyDelphin version
from delphin.__about__ import __version__ # noqa: F401
# Basic Types
# Identifiers ar... |
import DFA.DFA as DFA
import dfa_grapher as dfg
from copy import deepcopy
import shutil
import os
def choose(dfa, states):
'''
Choose first from a set of states in standard order
'''
for state in get_state_order(dfa):
if state in states:
return state
def learn_dfa(teacher, num_exa... |
# <NAME> 2018-07-12
import numpy as np
import astropy.units as u
from multiprocessing import cpu_count
from joblib import Parallel, delayed
from astropy.table import Table, Column
def solar_midnight(site, time, which='nearest'):
return site.midnight(time, which=which)
def evening_twilight(site, time, which='ne... |
import arcade
from arcade.gui import TextButton, Theme
from buttons import PlayButton, ExitButton, ValueButton
class StartView(arcade.View):
"""Class to display the starting View for the game"""
def __init__(self, game, WIDTH, HEIGHT):
super().__init__()
self.game = game
self.WIDTH = WIDTH
self.HEI... |
# Copyright (c) 2020 by <NAME>.
import json
import uuid
import os
from socketserver import ThreadingMixIn
from http.server import HTTPServer, BaseHTTPRequestHandler
from .manager import Manager
class Server(ThreadingMixIn, HTTPServer):
daemon_threads = True
def __init__(self, max_running, bind_addr):
... |
from twitterscraper import query_tweets, query_tweets_from_user
import datetime as dt
import re
from requests_html import HTMLSession
import os
from collections import OrderedDict
import json
'''
조회 할 수 있는 목록..
# user name & id
self.screen_name = screen_name
self.username = username
self.user_i... |
# functions.py
# Copyright (c) 2013-2019 <NAME>
# See LICENSE for details
# pylint: disable=C0103,C0111,E1129,R0201,R0205,R0903,R1710,W0621
# Standard library imports
import os
import platform
import uuid
# PyPI imports
from pmisc import ignored, AE, AI, GET_EXMSG
import pytest
# Intra-package imports
import pplot
... |
'''
MIT License
Copyright (c) 2021 <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... |
import re
from unidecode import unidecode
import nick_names
import utils
class MalformedAuthorName(Exception):
pass
class Mention():
def __init__(self):
pass
def load_author_alias(self, name_str):
self.original_name = name_str
self.merged_name = name_str #this gets overwritten
... |
import re
DEBUG = False
class filethingy:
def __init__(self, filename):
self.values = []
f = open(filename, 'r')
for line in f:
self.values.append(line.strip())
print("input: ", self.values)
class bagStruct:
def __init__(self):
self.bagName = ''
... |
""" Voronoi Diagrams mini DB. """
# Standard Library
from typing import Optional, Dict, List, Any, Tuple
from datetime import datetime
import threading
# Voronoi Diagrams
from plots.plot_utils.voronoi_diagram import get_vd_html, get_html
from voronoi_diagrams.fortunes_algorithm import (
FortunesAlgorithm,
MAN... |
"""Runner script for non-RL simulations in flow.
Usage
python simulate.py EXP_CONFIG --no_render
"""
import argparse
import sys
import json
import os
import numpy as np
from flow.core.experiment import Experiment
from flow.core.params import AimsunParams
from flow.utils.rllib import FlowParamsEncoder
def parse_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.