text stringlengths 3.07k 22.1k |
|---|
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 3 15:07:16 2017
@author: <NAME>
"""
from __future__ import division, print_function, unicode_literals, absolute_import
import unittest
import sys
sys.path.append("../../sidpy/")
from sidpy.base.string_utils import *
if sys.version_info.major == 3:
unicode = str
c... |
import logging
import random
import subprocess
import tempfile
import requests
import typing
import configparser
from sqlalchemy.orm import Session
import const
import models
import schemas
import os
import re
import ipaddress
import util
from database import SessionLocal
_LOGGER = logging.getLogger(__name__)
clas... |
import numpy as np
import os
from qtpy import QtGui, QtCore, QtWidgets
import sharppy.sharptab.params as params
import sharppy.sharptab.winds as winds
import sharppy.sharptab.interp as interp
import sharppy.databases.inset_data as inset_data
from sharppy.sharptab.constants import *
## routine written by <NAME> and <NA... |
import frappe
from latte.utils.caching import (
cache_in_local,
cache_in_mem,
cache_me_if_you_can,
get_args_for,
get_cache,
invalidate_by_key,
RedisWrapper,
INVALIDATION_ON,
)
from frappe.model.meta import Meta
from latte.database_utils.connection_pool import PatchedDatabase
from frappe import get_attr
from fra... |
import io
import os
import stat
import struct
from enum import IntEnum, unique
from pathlib import Path
from typing import Dict, Optional
from structlog import get_logger
from unblob.extractor import is_safe_path
from ...file_utils import Endian, InvalidInputFormat, read_until_past, round_up
from ...models import Ex... |
#!/usr/bin/env python
import pandas as pd
import numpy as np
from time import time
import os
import ipdb
import sys
sys.path.append('../utils')
sys.path.append('./pharma')
import preproc_utils
from pharmarec_processing import pivot_pharma_table
def LoadRawHDF5Values(tbl_name,
patient_id,
... |
import os
import shutil
import pytest
from leapp.exceptions import StopActorExecutionError
from leapp.libraries.actor import upgradeinitramfsgenerator
from leapp.libraries.common.config import architecture
from leapp.libraries.common.testutils import CurrentActorMocked, logger_mocked, produce_mocked
from leapp.models... |
"""Demo platform that offers a fake water heater device."""
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.core import callback
import logging
import json
from homeassistant.components.water_heater import (
SUPPORT_AW... |
"""
Routes and views for the flask application.
"""
import os
from datetime import datetime
import string
import random
from flask import render_template, request, jsonify
from werkzeug.utils import secure_filename
from AiSopp import app
from AiSopp.get_country_from_ip import get_country_from_ip
from AiSopp.image_label... |
import argparse
import json
from models.ner import *
from models.rel import *
from models.mrc import *
from models.fa_ner import *
from models.fa_rel import *
DATA_PATH = '/srv/share5/fbai31/ProcBERT/anno_data'
PubMed_DIR = {
'train': f'{DATA_PATH}/pubmed/train/',
'dev': f'{DATA_PATH}/pubmed/dev/',
'test... |
"""
The utils.settings module contains global settings about the backend to use,
what sampling method to use, the default device, and default datatype.
Backend
-------
Which backend to use. Can be either
`TensorFlow 2.0 <http://www.tensorflow.org/beta/>`_
or `PyTorch <http://pytorch.org/>`_.
* :func:`.get_backend`... |
import itertools
import sys
#import urlparse
from datetime import datetime, timedelta
from urllib.parse import urljoin, urlparse, urlsplit
import os
import re
import pickle
import zlib
from urllib.request import Request, urlopen, urlretrieve
from urllib.error import HTTPError
from urllib.error import URLError
from b... |
"""
Sugeno fuzzy model
==============================================================================
"""
import matplotlib.pyplot as plt
import numpy as np
from .core import plot_crisp_input
# #############################################################################
#
#
# Fuzzy Variable
#
#
# ################... |
# This script targets the client api version 0.4.0 and later
import labkey
import json
from pathlib import Path
import os.path
# saved labkey queryies
queries = [
{
'schema': 'ListManager',
'query_names': ['ListManager']
},
{
'schema': 'study',
'query_names': [
'admindemographics',
... |
import warnings
import numpy as np
import pandas as pd
from scipy import optimize
from autocnet.camera import camera
from autocnet.camera import utils as camera_utils
from autocnet.utils.utils import make_homogeneous, normalize_vector
try:
import cv2
cv2_avail = True
except: # pragma: no cover
cv_avail = ... |
import androidhelper
import urllib.request
import time
import requests
from bs4 import BeautifulSoup
import datetime
droid = androidhelper.Android()
republic1="Republic Day is a national holiday in India. It honours the date on which the Constitution of India came into effect on 26 January 1950 replacing the Govern... |
from vyper.exceptions import TypeMismatch
def test_concat(get_contract_with_gas_estimation):
test_concat = """
@external
def foo2(input1: Bytes[50], input2: Bytes[50]) -> Bytes[1000]:
return concat(input1, input2)
@external
def foo3(input1: Bytes[50], input2: Bytes[50], input3: Bytes[50]) -> Bytes[1000]:
... |
import torch
import torchaudio
import torch.nn as nn
import torch.nn.functional as F
from graphs.models.base import BaseModel, VoxModel
class ConvBnPool(nn.Module):
def __init__(self, in_channels, out_channels, conv_kernel_size, conv_strides, conv_pad,
pool_type='', pool_size=(2, 2), pool_strides... |
# Copyright 2014 Midokura SARL
# 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 appli... |
#!/usr/bin/env python
from setuptools import setup, Command, Extension
from setuptools.command.build_ext import build_ext
import distutils
from distutils.command import build
from subprocess import check_output, check_call
import sys, os
BUILD_MONO = True
BUILD_NETFX = True
PY_MAJOR = sys.version_info[0]
PY_MINOR =... |
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly
# import plotly.graph_objs as go
import colorlover as cl
import datetime as dt
import flask
import os
import pandas as pd
pd.core.common.is_list_like = pd.api.types.is_list_like
... |
#!/usr/bin/env python
"""
.. module::
:language: Python Version 3.6.8
:platform: Windows 10
:synopsis: utility functions and decorators
.. moduleauthor:: <NAME> <<EMAIL>>
"""
# ------------------------------------------------------------------------------
# EXCEPTIONS
# -----------------------------------... |
"""
The module is used for working with synchronous data flow graphs.
It implements a sequential execution algorithm.
"""
from typing import Tuple, Dict, List, Any, NamedTuple, Deque, Callable
from abc import ABC, abstractmethod
from functools import reduce
import logging
from sympy import Matrix, lcm, gcd, fraction ... |
import random
import numpy as np
from numpy.core.fromnumeric import std
from numpy.lib.function_base import median
import scipy
from random import choice
from scipy.optimize import least_squares
import librosa
import os
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import (LinearRegress... |
import sys
import os,json,codecs,unicodedata,tqdm
import pandas as pd
from keras_bert import load_trained_model_from_checkpoint,Tokenizer
from keras.layers import *
from keras.models import Model
from keras.optimizers import Adam
sys.path.append('..')
from src.utils import config
os.environ["CUDA_VISIBLE_DEVICES"] = "... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from collections import OrderedDict, namedtuple
import torch
import torch.nn as nn
import torch.nn.functional as F
import hyperbox.mutables.spaces as spaces
from hyperbox.networks.base_nas_network import BaseNASNetwork
from hyperbox.networks.da... |
from copy import deepcopy
from graph import Graph
from collection.priority_queue import PriorityQueue
def kruskals(adj_list):
'''Return a minimum spanning tree of adj_list using Kruskal's algo.'''
adj_list = deepcopy(adj_list) # Since we need to modify adj_list
expected_mst_edges = (len(adj_list.keys())... |
import argparse
from datetime import datetime
import json
import numpy as np
from pathlib import Path
import time
from tqdm import tqdm
import warnings
import torch
import torch.nn as nn
from torch.utils.tensorboard import SummaryWriter
from data import data_loaders
from model import RandLANet
from utils.tools import... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# king_phisher/ics.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of... |
"""Telegram bot for Elasticpath shop."""
import json
from typing import Callable, List
from geopy.distance import distance
from redis import Redis
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ParseMode, Update
from telegram.ext import CallbackContext, Filters, Updater
from telegram.ext import Callb... |
import base64
import json
import os
import requests
from .utilities import condor_str, retry
from .create_job_token import create_job_token
@retry(tries=2, delay=1, backoff=1)
def validate_presigned_url(url):
"""
Validate a presigned URL
"""
try:
response = requests.get(url, stream=True, timeo... |
import logging
import requests
from ruamel import yaml
import handle_k8s as k8s
import shutil,os
import pk_config
alerts = {}
dryrun_id = 'prometheus'
def is_subdict(subdict=dict(),maindict=dict()):
return all((k in maindict and maindict[k]==v) for k,v in subdict.items())
def extract_value_from_prometheus_response... |
# coding=utf-8
# Copyright (c) 2019 Uber Technologies, 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 applicabl... |
from __future__ import division
import logging
from time import time
from math import ceil, sqrt
from collections import defaultdict
from feemodel.util import StoppableThread, DataSample
from feemodel.simul import Simul
from feemodel.simul.stats import WaitFn
from feemodel.simul.transient import transientsim
from fee... |
from asyncio import sleep
from datetime import datetime
from glob import glob
from dotenv import load_dotenv
import os
from tzlocal import get_localzone
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from discord import Embed, File, DMChannel, Intents, Me... |
# Standard imports
import datetime
import io
import json
import os
# Django imports
from django import http
from rest_framework import viewsets
# Third-party imports
import piexif
from PIL import Image
# Local imports
from . import filters, models, serializers, utils
from .membership import permissions
# Provide A... |
import protodata.data_ops as do
from protodata.utils import save_pickle, create_dir, download_file
from protodata.image_ops import ImageCoder, process_image
import threading
from datetime import datetime
import scipy.misc
import tempfile
import os
from abc import ABCMeta
import abc
import numpy as np
import tensorflow... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Explanation:
This script collects files from the Recorded Future website.
It puts files into a local directory cache.
Finally, it provides several means to publish to Sumo Logic.
Usage:
$ python rfslsync [ options ]
Style:
Google Python Style Guide:
ht... |
"""Test the table widget."""
from operator import attrgetter
import pytest
from bui.specific.base.table import SpecificTable
from bui.widget.table import AbcRow, Table
from tests.widget.helpers import *
DEFAULT_LAYOUT = """
<window title="Just a test">
<table x=0 y=0 id=table>
<col>Name</col>
... |
#!/usr/bin/env python
"""Preferences for the opscore.RO.Wdg package.
Note: call
History:
2004-08-11 ROwen Split out from opscore.RO.Wdg.Label to make it more readily available.
2004-09-03 ROwen Bug fix; getWdgPrefDict was calling a nonexistent function if self.prefDict not set..
Modified for... |
import argparse
import copy
import random
from generator import makeBasicProject, addSpriteSheet, makeBackground, makeScene, makeActor, addSymmetricSceneConnections, makeMusic, reverse_direction, initializeGenerator, writeProjectToDisk
def SachitasGame():
"""
Create an empty world as an example to build future projec... |
from flask import Flask, jsonify, request, Response, make_response, send_file
import argparse, librosa, os, sys
import soundfile as sf
import copy
import numpy as np
import time
import re
sys.path.append('./tts')
sys.path.append('./waveglow')
bb = time.time()
import torch
import torch.nn as nn
from torch.autograd impo... |
#!/usr/bin/env python3
# testcases.py
import json
import math
import os.path
import sys
import traceback
from argparse import ArgumentParser
from typing import NamedTuple, List, Dict, Any, Optional
import logging
import hwsuite
_log = logging.getLogger(__name__)
_DEFAULT_CASE_ID_PRECISION = 2
_DEFAULT_DEFINITIONS_FI... |
import socket
import pickle
import struct
import sys
from typing import Iterable
import traceback
'''
ModelBridgeServer (MODEL SIDE):
- Receives:
- MOOSDB Subscribed to (mainly for state construction)
- Sends:
- Heartbeat?
- Actions:
- IvP function actions (speed, course)
- MOOSDB actions (... |
import json
import os
import re
import sys
import time
import pandas
import run_DCP
def parse_image_names(imlist,filter_in, filter_out="jibberish"):
image_dict = {}
for image in imlist:
if '.nd2' in image:
if filter_in.lower() in image.lower():
if filter_out.lower() not in... |
"""utils for interpreting variant effect prediction for Heritability
"""
import gzip
import os
import sys
from collections import defaultdict
import h5py
import numpy as np
import pandas as pd
def read_vep(vep_dir, check_sanity=False):
_label_fn = [x for x in os.listdir(vep_dir) if x.endswith("_row_labels.txt")... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
"""
(c) 2014-2018 <NAME>
Job Manager Client
:author: <NAME>
"""
import os
import signal
import tbx
import tbx.log
import tbx.text
import tbx.process
import tbx.service
import tbx.settings
from jobmanager.common.job import Job
from jobmanager.... |
import xml.etree.ElementTree as xmlet
from pathlib import Path
import numpy as np
import craamvert.utils.iso_time as time
from astropy.io import fits
from craamvert.instruments.sst import SST_FITS_FILE_NAME
from craamvert.utils import SST_INSTRUMENT, OBJECTS_NOT_FROM_SAME_INSTRUMENT, CONCATENATED_DATA, INVALID_FILE_N... |
import numpy as np
from deepneuro.models.dn_ops import DnConv, DnPixelNorm, DnUpsampling, DnMaxPooling, DnBatchNormalization, DnDropout, DnAveragePooling
from deepneuro.models.ops import leaky_relu, minibatch_state_concat
def generator(model, latent_var, depth=1, initial_size=(4, 4), max_size=None, reuse=False, tran... |
# Copyright (c) OpenMMLab. All rights reserved.
from typing import Optional
import torch
import torch.nn as nn
from mmcv.runner import BaseModule
from ..builder import DECODERS
from .raft_decoder import ConvGRU, RAFTDecoder
class RelPosEmb(BaseModule):
"""Relative position embedding.
Separate embedding vec... |
import datetime
import json
import os
import sys
import requests
import yaml
base_url = "https://api.github.com"
if os.getenv("GITHUB_TOKEN") != None:
req_headers = {"Authorization": f"Bearer {os.getenv('GITHUB_TOKEN')}"}
else:
req_headers = {}
def requests_API(method, link, datadict=None):
method = met... |
from http.cookies import CookieError
import numpy as np
import pandas as pd
from panel import state
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.multiclass import OneVsRestClassifier
from scipy.spar... |
#!/usr/bin/env python3
"""
Command Line Interface to brstores application
This module implements the command line interface to the brstores application.
It contains all of the argument parsing logic, and includes some basic variant
testing (although I think this will be moved once I finish the unittest code).
"""
im... |
# -*- coding: utf-8 -*-
# @Time : 2019-12-20
# @Author : mizxc
# @Email : <EMAIL>
import os
from flask import current_app, request, flash, render_template, redirect, url_for
from flask_login import login_required, current_user
from . import bpAdmin
from project.common.dataPreprocess import strLength
from project... |
import logging
import json
import codecs
import sys
import os
import re
import itertools
import warnings
from instagram_private_api.compat import compat_urllib_request
class TerminalColors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
END... |
# Copyright 2013 The Chromium 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 random
import unittest
from metrics import smoothness
from metrics import statistics
from metrics import rendering_stats
from telemetry.core.backends... |
#!/usr/bin/env python
# coding: utf-8
# # Visualising COVID-19 in Asia
# Visualising the impact of COVID-19 on the Asian nations on the basis of population, hospital beds available per 1000, tests done,confirmed cases and death rates
# In[1]:
import pandas as pd
import plotly.graph_objects as go
import plotly.exp... |
# -*- coding: utf-8 -*-
"""
Created on Sat 28/05/2021
@author: Group 1
"""
import os
import folium
from folium.plugins import HeatMap
import branca
import numpy as np
import pandas as pd
import geopandas as gp
from psycopg2 import connect
from folium.plugins import MarkerCluster
from datetime import datetime
import g... |
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2022 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... |
'''
Created on 20 jun. 2018
@author: fmplaza
'''
import os
from keras.datasets.imdb import get_word_index
from model.glove_word_embedings import GloveWordEmbednigs
import pandas as pd
from nltk.tokenize.casual import TweetTokenizer
import numpy as np
from keras.preprocessing.sequence import pad_sequences
from keras.m... |
# rkpython
# Python module containing various functions
# dependencies
import os
import operator
import sys
import csv
import chardet
import pandas as pd
import time
# rk.to_txt()
def to_txt(l, path = 'text_file.txt', overwrite = False, verbose = False):
#Docstring
'''
Saves a list to a .txt file.
-----... |
import typing
import bleach
# import markdown2
from nasse import config, logging
# Source: en.wikipedia.org/wiki/Whitespace_character
# Note: BRAILLE PATTERN BLANK, HANGUL FILLER, <NAME>, <NAME>LER and HALFWIDTH HANGUL FILLER are also refered here as "whitespaces" while they aren't according to the Unicode standard.
W... |
"""
Email: <EMAIL>
Date: 2018/9/28
"""
import datetime as dt
import numpy as np
import torch
import torch.nn as nn
from .loader import get_txt_data
class Timer():
"""计时器类"""
def start(self):
self.start_dt = dt.datetime.now()
def stop(self):
end_dt = dt.datetime.now()
spend = (... |
#######
# Dashboard of low and high yearly average temperatures given the country
# Data collected from Global Historical Climatology Network-Monthly (https://www.ncdc.noaa.gov/ghcnm/v3.php)
#######
# Import libraries
import dash
# https://dash.plot.ly/dash-core-components
import dash_core_components as dcc
# https://... |
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 21 14:51:28 2018
@author: yujika
"""
import pickle
import numpy as np
import cv2
import glob
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
#%matplotlib qt
import util
def corners_unwarp(img, nx, ny, mtx, dist):
img_und = cv2.undistort(img, mtx, d... |
# Authors: <NAME>, <NAME>
# Date: 1/15/2021
import csv
import re
import argparse
import sys
BooksDataSet = []
file_name = 'books.csv'
# This function populates the list BooksDataSet with title, publication year, and author(s) information from books.csv.
def fillBooksDataSet(file_name):
with open(file_name, newl... |
#encoding:utf-8
import re
import copy
from .loader import ResourceLoader
from .tools import StringHelper
from .word import Word
from .digital import is_chinese_number, chinese_to_number
class BaseSegmentProcess(object):
group_marker = re.compile(
'|'.join([
'%s{1,}?' % StringHelper.cjk_patter... |
import os.path as osp
import numpy as np
import torch
import torch.nn.functional as F
from model.trainer.base import Trainer
from model.trainer.SnaTCHer_helpers import (
get_dataloader, prepare_model,
)
from model.utils import (
count_acc,
)
from tqdm import tqdm
from sklearn.metrics import roc_curve, roc_auc... |
'''
Created on 9 jul. 2017
@author: david
'''
import rpyc
import time
import cv2
from engine.driver import Driver
import numpy as np
def show():
cap = cv2.VideoCapture(0)
done = False
while not done:
# Take each frame
_, frame = cap.read()
frame = cv2.bl... |
from functools import reduce
from typing import Any, List, Union, Tuple, cast
import itertools
from sweetpea.derivation_processor import DerivationProcessor
from sweetpea.internal import chunk, get_all_levels
from sweetpea.logic import to_cnf_tseitin
from sweetpea.blocks import Block, FullyCrossBlock
from sweetpea.bac... |
r"""
Implements a uniform distribution on an edge and a triangular distribution
on an edge.
The expected values of Z given X may be computed explicitly for these
distributions.
Some background mathematics:
* The moment generating function of a truncated normal distribution
..math ::
e^{\mu t + \sigma^2 t^2 / ... |
"""Baseline for comparability: linear svm by SAGA. Uses structured
format."""
import os
from hashlib import sha1
import warnings
from collections import Counter
import dill
import numpy as np
from sklearn.base import clone
from sklearn.metrics import f1_score
from sklearn.preprocessing import LabelEncoder
from sklea... |
"""
Build the various language SDK packages for release
"""
import argparse
import glob
import logging
import os
import platform
import shutil
import subprocess
from os.path import join, abspath, dirname, isdir, split, exists
from typing import Dict
from zipfile import ZipFile
try:
import requests
except:
os.s... |
"""Central GUI for Clue-less game"""
from PySide6 import QtCore # pylint: disable=no-name-in-module # GitHub Actions cant import Qt modules
from PySide6 import QtGui # pylint: disable=no-name-in-module # GitHub Actions cant import Qt modules
from PySide6 import QtWidgets # pylint: disable=no-name-in-module # GitHub ... |
from flask_restful import Resource, reqparse
import psycopg2
import pandas as pd
from pandas.io.json import json_normalize
import cx_Oracle
from sqlalchemy import create_engine
import datetime
import numpy as np
import json
import re
from flask_jwt_extended import (create_access_token, create_refresh_token, j... |
import numpy as np
import tensorflow as tf
# reproducible
np.random.seed(2)
tf.set_random_seed(2)
__all__ = ['PolicyGradient', 'Actor', 'Critic', 'ValueFunction']
""""REINFORCE"""
class PolicyGradient:
def __init__(
self,
n_actions,
n_features,
learning_rate=0.01,... |
import __main__
import random
name = 'iterate'
usage = 'ITERATE [Batches] [Batch size] [Nation]'
description = 'Simulate games of Diplomacy.'
def execute(query):
if __main__.active_board == None:
return 'No active map.'
batches = 10
if len(query) > 0:
try:
batches = int(query.pop(0))
except:
pass
bat... |
from django.conf import settings
from django.contrib import auth, messages
from django.contrib.auth.decorators import login_required, user_passes_test
from django.db.models import Case, Value, When
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.template.response i... |
# -*- coding: utf8 -*-
# My imports
from __future__ import division
import numpy as np
from scipy.interpolate import InterpolatedUnivariateSpline
import os
from astropy.io import fits
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
def mad(data, axis=None):
'''Function to calculate the... |
import os
from copy import deepcopy
import dill
import numpy as np
import pyspiel
from darkhex.utils.cell_state import cellState
def cell_connections(cell, num_cols, num_rows):
"""
Returns the neighbours of the given cell.
args:
cell - The location on the board to check the neighboring cells ... |
# Code modified from https://github.com/seungeunrho/minimalRL/blob/master/a3c.py
import gym
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Categorical
import torch.multiprocessing as mp
import time, sys
import gym_multi_car_racing
from gym_... |
# -*- coding: utf-8 -*-
'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2016, <NAME> <<EMAIL>>
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... |
import csv
from django.contrib.auth.models import User
from django.db.models import Sum, Count
from rest_framework import serializers
from api.models import Tongji, UserProfile
purple_book = list()
blue_book = list()
with open("api/aoapc.csv", encoding="gbk") as f:
print("Hello?")
csv_reader = csv.reader(f)
... |
import os
import os.path as osp
import sys
sys.path.append('../')
import numpy as np
import argparse
import cv2
import time
import configs
from preprocessing.dataset import preprocessing
from models import cpn as modellib
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from pycocotools impo... |
import traceback, turtle
#Takes as input a Square object node in a graph of Square nodes.
# This will always be the Square node representing (0,0), the start position
#Performs DFS until the goal Square is found (the Square with val == 2).
#Returns a list containing each Square node in the path from the start
# (0,0) ... |
from matplotlib import pyplot,gridspec,colors,patches
import numpy
import os
from diatom import Calculate
import warnings
from scipy import constants
h = constants.h
cwd = os.path.dirname(os.path.abspath(__file__))
def make_segments(x, y):
''' segment x and y points
Create list of line segments from x and y... |
import time
import os
import requests
import logging
import json
import ffmpeg
import re
import threading
from flask import Flask, Response, request, jsonify, abort, render_template, redirect
from logging.config import dictConfig
# URL format: <protocol>://<username>:<password>@<hostname>:<port>, example: https://test... |
# -*- coding: utf-8 -*-
"""
flask_xmlrpcre
===============
Adds support for creating XML-RPC APIs to Flask.
:copyright: (c) 2010 by Matthew "LeafStorm" Frazier.
:license: MIT, see LICENSE for more details.
"""
from flask import request, current_app
import sys
if sys.version_info[0] == 2:
from SimpleXMLRPCServer... |
import pdb
from .batching import BatchItems, make_collator
import pickle
from torch.utils.data import DataLoader
from .model import Tagger
from .loss import GroupedLoss
import torch
from collections import defaultdict
from torch.optim import AdamW
from torch.optim.lr_scheduler import LambdaLR
from torch.nn.utils impo... |
import collections
import copy
import datetime
import os
import pandas as pd
from .expectation_generators import generate
from .process_covariate_definitions import process_covariate_definitions
class StudyDefinition:
def __init__(self, population, **covariates):
covariates["population"] = population
... |
from distutils import dirname
from mgl2d.graphics.quad_drawable import QuadDrawable
from mgl2d.graphics.shader_program import ShaderProgram
from mgl2d.graphics.texture import Texture
from mgl2d.math.vector2 import Vector2
class CharDef:
def __init__(self):
self.id = 0
self.x = self.y = 0
... |
"""Lite local runtime runs agents locally with limited setup, like no MQ service and no defaults agents.
The local runtime requires Docker Swarm to run robust long-running services with a set of configured services.
"""
import logging
from typing import List
from typing import Optional
import click
import docker
impo... |
# Copyright 2015 datawire. 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 agr... |
'''
Copyright 2013 <NAME> and <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, softwa... |
from soap.expression import (
is_variable, is_expression, External, InputVariableTuple,
OutputVariableTuple, SelectExpr, FixExpr, Subscript
)
from soap.program.graph import DependenceGraph
from soap.semantics import is_numeral, Label, MetaState
def sorted_args(expr):
if any((expr is None, is_variable(expr... |
import os.path
import sys
from pathlib import Path
scriptpath = str(Path(os.path.dirname(os.path.abspath(__file__))).parent)
sys.path.insert(0, scriptpath)
pickle_path = os.path.join(scriptpath, r'geolocalisation', r'museums_.pkl')
import re
import pandas as pd
import pickle
from geopy.geocoders import BANFrance
from... |
import re
import json
import googlemaps
import bs4
import urllib.request
import requests
import numpy as np
import pandas as pd
import threading
import time
import random
gmaps = googlemaps.Client(key='<KEY>')
users = {}
def get_fb_id(req):
return req["originalDetectIntentRequest"]["payload"]["data"]["sender"]["... |
import ndjson as json
import matplotlib
matplotlib.use('qt5agg')
import pylab
import seaborn as sns
sns.set_style("whitegrid")
import pandas
import numpy as np
import scipy
#https://ipip.ori.org/New_IPIP-50-item-scale.htm
def get_confusion_matrix(scores, images):
def shrink(name):
return "$" + name[0] + n... |
#
# File: views.py
#
# views lists functions that are executed when an appointed url at index/urls.py
# is accessed, it will contain any logic necessary to provide data and also
# set which html file for rendered page
# Copyright (c) 2019 KukFight Group
# Authors:
# <NAME>
# <NAME>
# <NAME>
# This program is ... |
# -*- coding: utf-8 -*-
"""
Test the GenSchema API.
Created on Fri Sep 9 10:08:01 2016
@author: <NAME>
"""
import pytest
import mock
import ctip.entrypoint as cli
# intercept the args object
def sentry(intercepted_args):
global args
args = intercepted_args
##################### RUN COMMAND ############... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.