text stringlengths 3.07k 12.6k |
|---|
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import dezero
import dezero.functions as F
from dezero import Variable
from dezero.models import VGG16
use_gpu = dezero.cuda.gpu_enable
lr = 5.0
iterations = 2001
model_input_size = (224, 224)
style_weight = 1.0
content_weight = 1e-4
total_varit... |
import itertools
from copy import deepcopy
from uuid import uuid4
import six
from eventsourcing.application.sqlalchemy import ProcessApplicationWithSnapshotting
from eventsourcing.application.system import System
from eventsourcing.contrib.paxos.composable import PaxosInstance, Resolution, PaxosMessage
from eventsourc... |
import tensorflow as tf
from config import args
def smooth_l1(x, y):
abs_diff = tf.abs(x-y)
return tf.reduce_sum(tf.where(abs_diff < 1, 0.5*abs_diff*abs_diff, abs_diff - 0.5), reduction_indices=-1)
def batch_iou(proposals, gt):
bboxes = tf.reshape(tf.transpose(proposals), [4, -1, 1])
bboxes_x1 = bbo... |
import random
from functools import reduce
import pyspark.sql.functions as F
from pyspark.sql import DataFrame
from pyspark.sql.window import Window
from pyspark.ml.linalg import VectorUDT
from pyspark.ml.feature import StringIndexer, VectorAssembler, BucketedRandomProjectionLSH
from pyspark.sql.functions import col
fr... |
'''
Created on Sep 12, 2019
@author: charlie_tharas
'''
import os
import csv
import matplotlib.pyplot as plt
from scipy.fftpack import fft
from scipy.fftpack import rfft
from scipy.io import wavfile
from numpy.core._multiarray_umath import arange
import numpy as np
# performs simple FFT
# fix normalization? this norm... |
# Copyright (c) 2019, 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... |
import torch
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KernelDensity
from sklearn.metrics import average_precision_score, confusion_matrix
#plt.rcParams.update({
# 'font.size': 24
#})
def loss_fn(recon_x, x, mean, log_var, pred_inv_score, y, alpha):
BCE = torch.nn.funct... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# 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 ... |
# -*- coding: utf-8 -*-
"""
@author: <NAME>
"""
from pickle import load
import streamlit as st
import pandas as pd
import sqlite3
from datetime import date
# Carregando modelo
pickle_model = open('modelo_iot_energia.pkl', 'rb')
modelo = load(pickle_model)
pickle_model.close()
# Carregando Scale
pickle_scale = open... |
import gym
import numpy as np
import gym_MAOC
from scipy.optimize import minimize
from scipy.optimize import NonlinearConstraint
from scipy.spatial import Voronoi, voronoi_plot_2d
import scipy.spatial
from skimage.draw import polygon_perimeter, polygon
from math import *
import matplotlib.pyplot as plt
env = gym.make(... |
import tensorflow as tf
import numpy as np
np.random.seed(1234)
class ENN_lambda_update(tf.keras.callbacks.Callback):
def __init__(self, lambda_t=0, max_t=1):
self.lambda_t = tf.Variable(initial_value=lambda_t, dtype=tf.float64)
self.max_t = tf.Variable(initial_value=max_t, dtype=tf.float64)
d... |
import flask
from flask import Flask, render_template, request, jsonify
from urllib.request import urlopen
from urllib.request import Request
from bs4 import BeautifulSoup as soup
import requests
import numpy as np
import re
app=Flask(__name__)
@app.route('/')
def index():
"""
Acceder a la portada ... |
import gym
import argparse
import torch
#from gym.envs.mujoco import HalfCheetahEnv
import rlkit.torch.pytorch_util as ptu
from rlkit.torch.sac.diayn.diayn_env_replay_buffer import DIAYNEnvReplayBuffer
from rlkit.envs.wrappers import NormalizedBoxEnv
from rlkit.launchers.launcher_util import setup_logger
from rlkit.to... |
# coding: utf-8
import pandas as pd
import pysam
import argparse
import sys
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context('talk')
# Group SAG reads into groups:
# 1. Reads that map to both SAG and MAG x
# 2. Reads that map to MAG but not to SAG x
# 3. Reads that map to metag... |
# tests_grasp_static.py
# This file tests grasp_static.py for errors.
# Author: <NAME>
from __future__ import print_function
import unittest
import grasp_static as grasp
import mop
import numpy as np
import pickle
from copy import deepcopy
from random import randint, sample
from items import makeitems
class GR... |
from pathlib import Path
import gym
import numpy as np
np.warnings.filterwarnings('ignore', category=np.VisibleDeprecationWarning)
import warnings
warnings.simplefilter('ignore', ResourceWarning)
import matplotlib.pyplot as plt
from ray.rllib.models import ModelCatalog
from ray.tune.registry import RLLIB_MODEL, RLLI... |
__author__ = 'Prateek'
import time
import math
import numpy as np
import copy
from decisiontree import DecisiontreeClassifier
from multiprocessing import Process, Queue
class BaggingClassifier():
'''
Bagging classifier is meta-algorithm that builds a number of estimators on bootstrapped(with replacement)
... |
import time
import os
import psutil
import torch
class time_sampler:
def __init__(self, minimizing=False):
self.minimizing = minimizing
if self.minimizing:
self.time = 1e10
else:
self.time = 0
self.ncalls = 0
def duration(self):
if self.mini... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Compilebutton
import sys
from PyQt5.QtCore import pyqtSignal, QObject
from PyQt5.QtWidgets import QMainWindow, QApplication, QAction, qApp, QWidget, QListWidget, QPushButton, QHBoxLayout, QVBoxLayout, QGridLayout, QLabel, QLineEdit, QCheckBox, QMessageBox
from PyQt... |
import keyboard
import librosa
import numpy as np
import os
import pyaudio
import soundfile as sf
import tensorflow as tf
import utils
import wave
class Recorder(object):
def __init__(self, channels=1, rate=44100, frames_per_buffer=1024):
self.channels = channels
self.rate = rate
self.frames_per_buffer ... |
# 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, software
# d... |
# The MIT License
#
# Copyright 2020 <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 restriction, including without limitation the rights
# to use, copy, modi... |
#
# Copyright 2019 <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 ... |
import time
import threading
import cv2
import os
import tensorflow as tf
import numpy as np
import logging
from flask import Flask, url_for, redirect, Response, jsonify
from flask_cors import CORS
# Global var before starting the API
camera = None
inference_engine = None
possible_models = []
current_model = ""
image_... |
import json
import logging
import os
import socket
import requests
from oauth2client.tools import (ClientRedirectServer,
ClientRedirectHandler)
muted_loggers = (
'googleapiclient.discovery',
'oauth2client', 'requests', 'urllib3',
'watchdog',
'PIL', 'chardet', 'pyppeteer... |
# Copyright 2018 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
################################################################
#
# <NAME>
# ECE351-52
# Lab #4
# 9/30/2021
#
#
################################################################
import numpy as np
import matplotlib.pyplot as plt
#import scipy.signal as sig
import math
#------------FUNCTIONS-----------... |
import os
import cv2
import tqdm
import numpy as np
import pdb
import json, argparse
txt_path="/nfs/neolix_data1/neolix_dataset/test_dataset/lane_detection/neolix_lane_3mm/百度标注结果_lane_test_3mm.txt"
json_path="/nfs/neolix_data1/neolix_dataset/test_dataset/lane_detection/neolix_lane_3mm/test_label_85.json"
h_samples=[37... |
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
def plot_training_data(X, Y):
plt.scatter(x=X[:, 0], y=X[:, 1], c=Y, cmap='bwr')
plt.xlabel('sepal leng... |
import os
import re
import subprocess
from django.conf import settings
def decode_vars(variables):
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
result = []
variables = variables[1:]
while len(variables) > 0:
current = variables[0:6]
variables = variables... |
import os
import random
from faker import Faker
import csv
import uuid
cur_dir = os.path.abspath(os.getcwd()) + "/data"
print(cur_dir)
COUNT = 3000
faker = Faker('ru')
category_names = ['подкасты', 'творчество',
'блог', 'еда', 'путешествия',
'разработка игр', 'музыка', "дизайн", '... |
import sys
import threading
import traceback
import ujson as json
from PyQt5.QtCore import QMetaObject, QObject, QUrl, Q_ARG, Qt, pyqtSignal, pyqtSlot
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtWebEngineWidgets import QWebEnginePage, QWebEngineView
from PyQt5.QtWidgets import QApplication
from pysaurus.a... |
#!/usr/bin/env python3.6
"""
Used by connexion to verify the JWT in Authorization header of the request.
"""
import base64
import functools
import logging
import typing
import jwt
import requests
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa
from fu... |
"""
Collection of solvers for systems of linear equations.
"""
import heat as ht
from ..dndarray import DNDarray
from typing import List, Dict, Any, TypeVar, Union, Tuple, Optional
import torch
__all__ = ["cg", "lanczos"]
def cg(A: DNDarray, b: DNDarray, x0: DNDarray, out: Optional[DNDarray] = None) -> DNDarray:
... |
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
from keras.preprocessing import sequence
import keras
import numpy as np
path_to_file = tf.keras.utils.get_file('shakespeare.txt', 'https://storage.googleapis.com/download.tensorflow.org'
... |
import os
import os.path as osp
import numpy as np
import torch
import random
import tarfile
import shutil
from torch.utils.data import Dataset
class ProteinDataset(Dataset):
'''
Protein dataset
'''
def __init__(self, feature_dir, label_dir, temp_dir, zipped):
'''
Construct protein dat... |
# emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# -*- coding: utf-8 -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 3 07:59:40 2016
@author: rlabbe
"""
from filterpy.kalman import UnscentedKalmanFilter as UKF, MerweScaledSigmaPoints
from math import tan, sin, cos, sqrt, atan2
import numpy as np
from numpy.random import randn
import matplotlib.pyplot as plt
from filterpy.stats import ... |
import arcade
import numpy as np
from typing import Optional, Union
import random
from assets.enemies import Enemy
SCALE = 4
class Tower(arcade.Sprite):
def __init__(self,
dmg: float,
cooldown: int,
radius: int,
sprite: str,
e... |
import numpy as np
from PIL import Image
import random
def read_image(path, dtype=np.float32, color=True):
# 读取图片,并将其转换成[C, H, W]的标准形式
f = Image.open(path)
try:
if color:
# 如果color为真,将BGR转为RGB
img = f.convert('RGB')
else:
img = f.convert('P')
img... |
from collections import OrderedDict
from copy import deepcopy
from types import FunctionType
from schematics.exceptions import UndefinedValueError, DataError
from schematics.undefined import Undefined
from .attributes import XmlAttributeBase
from .children import XmlChildBase
from .content import XmlContentBase
from ... |
"""Thread-local objects.
(Note that this module provides a Python version of the threading.local
class. Depending on the version of Python you're using, there may be a
faster one available. You should always import the `local` class from
`threading`.)
Thread-local objects support the management of thread-local dat... |
#
# Copyright (c) 2021 Project CHIP Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import pathlib
import pika
import os
from PIL import Image
from io import BytesIO
import matplotlib.pyplot as plt
import numpy as np
from mtcnn import MTCNN
from keras.models import load_model
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import LabelEncoder, Normalizer
from sklearn.svm impor... |
from collections import namedtuple
import re
class DesugaringError(Exception):
pass
class Empty:
def to_productions(self, builder):
return ((),)
def as_dict(self):
return {
'type': 'empty',
}
class StringTerminal(namedtuple('StringTerminal', ('string',))):
def ... |
import numpy as np
import pandas as pd
import json
import base64
def _check_inds_are_partition(inds, n_obs):
if len(inds) != n_obs:
return False
hit = np.zeros(n_obs, dtype=bool)
hit[inds] = True
if not np.all(hit):
return False
return True
def _get_cond_smpls(smpls, bin_var):
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 5 15:17:37 2020
@author: <NAME>, Biomedical Engineer
PhD candidate in Neuroscience
University of Salerno, Fisciano, Italy
"""
import os
import numpy as np
from expyriment_stash.extras.expyriment_io_extras import tbvnetworkinterface
from rtrsa.nfrsa import rtRSA
import ... |
"""
Implement the command-line tool interface.
"""
from __future__ import unicode_literals
import argparse
import os
import sys
from xml.etree import cElementTree
import diff_cover
from diff_cover.diff_reporter import GitDiffReporter
from diff_cover.git_diff import GitDiffTool
from diff_cover.git_path import GitPathToo... |
from collections import defaultdict
import seqeval.metrics
import torch
from tqdm import tqdm
from torch.utils.data import DataLoader, RandomSampler
from torch.utils.data.distributed import DistributedSampler
from examples.ner.eval import f1_score_span, precision_score_span, recall_score_span
from examples.ner.utils ... |
# Copyright (C) 2014-2019 <NAME>
# SPDX-License-Identifier: Apache-2.0
import numpy
import dolfin
from ocellaris.utils import ocellaris_error, cell_dofmap, facet_dofmap
from ocellaris.cpp import load_module
from .gradient_reconstruction import GradientReconstructor
_CONVECTION_SCHEMES = {}
def add_convection_schem... |
import sys
import arrow
import dateutil
import pkg_resources
import click
import logbook
import logbook.more
from infinisdk import Q
from infinisdk.infinibox import InfiniBox
from infinisdk.core.config import config
_logger = logbook.Logger('sdk-cli')
logbook.set_datetime_format('local')
_DEFAULT_CONSOLE_LEVEL = log... |
import cv2 as cv
import pygame as pg
import numpy as np
import random
from os import path
pg.init()
pixsz = 4
BLACK = (0,0,0)
WHITE = (255,255,255)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
data_dir = path.join(path.dirname(__file__),'data')
img = cv.imread(path.join(data_dir,"OpnS.png"), 1)
HEIGHT, WIDTH,... |
import re
import sys
from collections import defaultdict
import numpy as np
import pysam
from orfipy_core import orfs as find_orfs
def get_gtf_attribute(gtf_record, attribute):
try:
attr = re.search(f'{attribute} "(.+?)";', gtf_record[8]).group(1)
except AttributeError:
raise ValueError(
... |
# SPDX-License-Identifier: BSD-3-Clause
from io import StringIO
import random
from softfab.configlib import Task as ConfigTask
from softfab.frameworklib import Framework
from softfab.productdeflib import ProductDef
from softfab.resourcelib import RequestFactory
from softfab.resreq import ResourceSpec
from softfab.res... |
import os
import unittest
from unittest.mock import patch
from lxml import etree
from documentstore_migracao.utils import files, xml, request
from documentstore_migracao.utils.convert_html_body import Convert2SPSBody
from . import SAMPLES_PATH
class TestUtilsFiles(unittest.TestCase):
def test_list_dir(self):
... |
#!/usr/bin/env python
# coding: utf-8
import os
from bs4 import BeautifulSoup
from splinter import Browser
import requests
import pandas as pd
import time
# # 1. NASA Mars News
#
# ## Beware: Please put your own path to chromedriver.exe
# In[2]:
def init_browser():
"""This function open the Google Chrome br... |
from os import listdir, path
from glob import glob
from datetime import datetime
from subprocess import Popen, PIPE, run
from multiprocessing import cpu_count
from pathlib import Path
from typing import Dict
import pandas as pd
import torch
import logging
HOME_DIR = str(Path.home())
INIT_TIME = datetime.now().strftime... |
#!/usr/bin/env python3
# encoding: utf-8
# Copyright 2019 <NAME>
#
# This file is part of StDb.
#
# 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 limit... |
"""Read graph data and create corresponding data structures.
This module reads a graph from file, and creates a standardized data
structure that can be used to create Cplex models.
"""
import os
import numpy as np
class LinearThresholdGraph:
"""A graph with thresholds on the nodes and weights on arcs.
Att... |
import asyncio
import json
import pathlib
from urllib import parse
from contextlib import asynccontextmanager
import aiohttp
import time
import biodome
import pytest
import zmq
from zmq.asyncio import Context, Socket
import sqlite_server.zmain as zmain
from sqlite_server.util import printl
@asynccontextmanager
asy... |
import numpy
import uuid
import os
import requests
import json
from requests.auth import HTTPBasicAuth
from flask import current_app
from sqlalchemy import and_
from celery import chord
from app.docman.models.document import Document
from app.config import Config
from app.docman.models.import_now_submission_documents... |
#!/usr/bin/env python3
#
# Looks for other interesting compound words like
# "pen-island" and "penis-land".
#
# See: http://ucrel.lancs.ac.uk/bncfreq/flists.html for source data.
import os
import time
from argparse import ArgumentParser
import urllib.request
import zipfile
from typing import Callable, BinaryIO, Set, Li... |
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from... |
# Copyright 2022 The Symanto Research Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
import numpy as np
import math
from gym import spaces
from ..miniworld import MiniWorldEnv, Room
from ..entity import Box, ImageFrame
from ..params import DEFAULT_PARAMS
from scipy import ndimage
def find_grid(fplan): #2D floor plan for the maze, have to be binary, walls are 1, hallways are 0
labeled, nr_objects =... |
#!/usr/bin/python
import time
import requests
import json
import sys
#import logging
import os
#import traceback
import argparse
import datetime
import weather_conditions as wc
import app_ui as ui
#script_path = os.getcwd()
#log_path = script_path + "/circleci.log"
#print "logging to " + log_path
#logging.basicConfi... |
import sys
import multiprocessing
from . import helpers
import pybedtools
def _parallel_wrap(orig_bedtool, shuffle_kwargs, genome_fn, method,
method_args, method_kwargs, sort=False, shuffle=True,
reduce_func=None):
"""
Given a BedTool object `orig_bedtool`, call its `meth... |
#!/usr/bin/env python3
# coding: utf-8
import settings
from datetime import datetime, timedelta
from functools import lru_cache
from os import path
from pytz import timezone
import boto3
import json
import pypd
def timerange_for_report():
days = settings.DAYS_BACK
today = settings.END_DATE
start_day = to... |
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.test import Client, TestCase, override_settings
from django.test.client import RequestFactory
from django.urls import reverse
from ...acl.useracl import get_user_acl
from ...conf.dynamicsettings import DynamicSettings
from ... |
"""Run functional tests of the tool on all the examples."""
import argparse
import fnmatch
import os
import pathlib
import re
import shlex
import subprocess
import sys
from typing import List
def extract_linenums(text: str) -> List[int]:
r"""
Pull ordered line numbers out of crosshair output.
>>> extract... |
# Copyright 2018 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import matplotlib.pyplot as plt
import numpy as np
from EDAVisual import OptionsHist
from HelperFunctions import scale_convert, convert_thousands
class Hist(OptionsHist):
"""Predefined histogram with basic settings to quickly plot data
Arguments:
OptionsHist {class} -- Settings f... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
import numpy as np
import matplotlib.pyplot as plt
def euclidean(vector1,vector2):
return np.sqrt(np.sum(np.power(vector1-vector2,2)))
def randomcent(k):
n = dataset.shape[1]
cent = np.mat(np.zeros((k, n)))
for j in range(n):
lolimit = min(dataset[:, j])
datarange = float(max(dataset[... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
file : exp_check/data_manager.py
author : <NAME>
Description:
A class for managing json data for the food database.
"""
import json
import datetime
from exp_check.constants import empty_database
class DataManager():
def __init__(self, data_path):
s... |
import asyncio
import configparser
import importlib
import inspect
import logging
import os
from asyncorm.apps.app import App
from asyncorm.apps.app_config import AppConfig
from asyncorm.exceptions import AsyncOrmAppError, AsyncOrmConfigError, AsyncOrmModelError, AsyncOrmModelNotDefined
logger = logging.getLogger("as... |
#!/usr/bin/env python3
# vim:ts=8 sts=4 sw=4 expandtab ft=python
#
# Copyright (c) 2018, chys <<EMAIL>>
#
# 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 copyr... |
import pickle
import argparse
from collections import defaultdict
from nltk.tokenize import sent_tokenize
from nltk.tokenize import word_tokenize
import numpy as np
import time
# TODO put all these in a config file
data_folder = "../data/mydata/" # "../data/basic_data/"
dev_ratio = 0.1
test_ratio = 0.05
per_sentence ... |
# Copyright (c) 2015-2020 Cloudify Platform Ltd. 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 b... |
import maya.cmds as mc
import glTools.utils.base
def parentListUI():
'''
UI for parentList()
'''
# Window
window = 'parentListUI'
if mc.window(window,q=True,ex=1): mc.deleteUI(window)
window = mc.window(window,t='Parent List')
# Layout
fl = mc.formLayout(numberOfDivisions=100)
# UI Elements
childTXT = ... |
import numpy as np
import jax.numpy as jnp
from jax import grad, jit, vmap,jacfwd,jacrev,random,remat,value_and_grad
from jax.scipy.special import logsumexp, gammaln
from jax.scipy.stats import norm,t
from jax.lax import fori_loop,scan
from jax.ops import index, index_add, index_update
from jax.experimental import loop... |
import torch
from torch import nn
import torch.nn.functional as F
import numpy as np
import time
from problems import *
idx = 0
def bilinear(mosaick_img):
if mosaick_img.max() > 1:
mosaick_img /= 255
F_r = torch.FloatTensor([[1,2,1],[2,4,2],[1,2,1]])/4
F_b = F_r
F_g = torch.FloatTensor([[0,1,... |
import json
import pathlib
import re
import os
import asyncio
from bs4 import BeautifulSoup
from gql import gql, Client, AIOHTTPTransport
import requests
root = pathlib.Path(__file__).parent.resolve()
TOKEN = "bearer " + os.getenv("GH_GQL_API_TOKEN", "")
# Select your transport with a GitHub url endpoint
transport ... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib.ticker as mtick
from matplotlib.collections import LineCollection
###############################################################################
#Non-Standard Imports
#######################################... |
# -*- coding: UTF-8 -*-
from django.contrib.auth import get_user_model
from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django_extensions.db.models import TimeStampedModel
from model_utils import Choices
class Repository(Ti... |
import os
import shutil
import typing as t
from collections import defaultdict
from datetime import datetime
from datetime import timezone
from functools import lru_cache
import joblib
import pandas as pd
import typer
import yaml
from sklearn.base import BaseEstimator
from sklearn.model_selection import GridSearchCV
i... |
#!python
# -*- coding: utf-8 -*-
#
# Author : <NAME>; Physics Graduate Student, Ohio University
# Date : Aug 24, 2016
# Last update : Jan 24, 2018
# Runtime : 2 mins (redshift 1.0 and 216 files)
#
# Updates
# on jan 24, 2018 changed rg cut to 2.9.
"""
.. note::
This program creates P_gamma values (... |
from datetime import date
from quantAPP.config import Config
from sqlalchemy import create_engine
import pandas_datareader.data as web
from typing import Dict
import yfinance as yf
import pandas as pd
config = Config()
path = r"C:\Users\wwwes\Documents\wwweslei-quantApp\quantAPP\ext\profit\company_files"
engine = cre... |
# ======================================================================
# Copyright CERFACS (May 2018)
# Contributor: <NAME> (<EMAIL>)
#
# This software is governed by the CeCILL-B license under French law and
# abiding by the rules of distribution of free software. You can use,
# modify and/or redistribute the ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from ios_code_generator.maps import *
__author__ = 'banxi'
class Environment(object):
def __init__(self,model,fields):
self.model = model
self.fields = fields
self.fields_map = dict((field.name,field) for field in fields)
... |
import torch
def update(a, b, a_prev = None, b_prev = None, k = None):
"""
Recursively update dictionary `a` with dictionary `b`.
If some keys are missing in in `a` but present in `b`
then they will be created.
If key `k` exist in both `a` and `b` than
a[k] will be owerwritten with b[k... |
from django.conf import settings
from linebot import LineBotApi
from linebot.models import TextSendMessage, ImageSendMessage, LocationSendMessage, TemplateSendMessage,\
ButtonsTemplate, URITemplateAction, ConfirmTemplate, PostbackTemplateAction
# QnA Maker Host setting
import http.client, json
host ='' #[add... |
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# @author: <NAME> <<EMAIL>>
# @date: Thu May 24 10:41:42 CEST 2012
#
# Copyright (C) 2011-2012 Idiap Research Institute, Martigny, Switzerland
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Lic... |
import json
import os
from datetime import datetime, timezone
from typing import Mapping, NamedTuple, Tuple
from uuid import UUID
import jwt
from flask import Request
from requests import Session
from requests.exceptions import RequestException
from exceptions import InvalidNotifyKeyError, InvalidRequestError
NOTIFY... |
import numpy as np
from scipy.stats import norm, lognorm
from . import distribution
from . import gamma, cauchy
class Normal(distribution.Distribution):
"""
Univariate Normal Distribution using the following parameterization:
f(x | mu, sigma) = 1 / sqrt(2 * pi * sigma**2) * exp(-1/2 * (x - mu)**2 / sigma*... |
""" Object detection using Pretrained Tensorflow Model
Credits: This code is modified from the TensorFlow object detection tutorial available at:
https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb
"""
#Imports
import numpy as np
import os
import six.moves.urll... |
# Since this module depends on rules_nodejs, documentation using stardoc does not seem to be possible at the moment because of https://github.com/bazelbuild/rules_nodejs/issues/2874.
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load(
"@build_bazel_rules_nodejs//:index.bzl",
"node_repositories... |
# -*- coding: utf-8 -*-
try:
import brightway2 as bw2
from bw2io.importers.base_lci import LCIImporter
except ImportError:
bw2 = None
from ..transformations.utils import get_single_reference_product
def refinery_gas_is_the_bane_of_my_existence(exc):
return (exc['name'] != 'refinery gas' or exc.get('co... |
import logging
import math
import random
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
def lookup_dict(dict, inp):
ndim = len(inp.size())
if ndim == 1:
rt_seq = []
for t in range(inp.size()[0]):
idx = inp[t]
word = dict.idx2w... |
"""
Application Program for AS91896 Internal
"""
from tkinter import *
import tkinter as tk
from tkinter import ttk
from window import Root
import csv
def validate_input(tree, data, error_labels):
"""
Handles all input from user into treeview,
also saves treeview into data.csv file.
"""
validation... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.