text
stringlengths
3.07k
12.6k
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 16 23:50:33 2019 @author: <NAME> (<EMAIL>) """ import numpy as np import matplotlib.pyplot as plt from scipy.special import ellipj, ellipkinc, ellipk, ellipe from scipy.optimize import root_scalar eps=0.1 r = 1.0 rp = r+eps def F(_phi,_ksq): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 13 14:49:41 2020 @author: <EMAIL> """ from flask import Blueprint, session, render_template, url_for, flash, redirect, request, jsonify, json, current_app from flask_login import login_required, current_user from pathlib import Path from .. import ...
#!/usr/bin/env python3 import argparse import gzip import pathlib import time import numpy as np import chainerx as chx class MLP(object): def __init__(self): self.W1, self.b1 = new_linear_params(784, 1000) self.W2, self.b2 = new_linear_params(1000, 1000) self.W3, self.b3 = new_linear_...
#!/usr/bin/env python3 ########################################################################################## # This script sends a slack notification based on a custom webhook, and can be run as a CLI # or included and used from another python script. Easy :) # Written by Farley <<EMAIL>> #######################...
import logging from django.core.urlresolvers import reverse, reverse_lazy from django.shortcuts import get_object_or_404 from django.views.generic import ListView, DetailView, TemplateView, View from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.http import HttpResponse, HttpResponseRe...
""" Install: PyCylon (Follow: https://cylondata.org/docs/) Run Program: mpirun -n 4 python3 pycylon_torch_example.py --backend nccl --epochs 20 """ import argparse import os import socket import numpy as np import pandas as pd import torch import torch.distributed as dist import torch.nn as nn import torch.nn.function...
#calculation.py from tkinter import * from tkinter import ttk import sympy as sp from tkinter import messagebox #import tkinter.ttk as t GUI = Tk() GUI.title('โปรแกรมคำนวน Beam') GUI.geometry('500x500') ############################ def math_addition(): GUI2 = Toplevel() GUI2.title('หน้าต่างคณิตศ...
from GPnet import RMSE, NLPD, logpdf import GPy import matplotlib.pyplot as plt import numpy as np import os plt.rc('font', size=18) plt.rc('legend', **{'fontsize': 12}) plt.rc('lines', linewidth=3) plt.rc('pdf', fonttype=42) # create figure directory if not existent yet os.makedirs('fig', exist_ok=True) # <NAME>'s...
from clarifai.rest import ClarifaiApp from clarifai.rest import Image as ClImage # from googleapiclient.discovery import build as google_build import pprint import json from PIL import Image import urllib.request import io import config from clsMySysImage import mysysImage from tool_lang import google_transla...
import datetime import json import logging import pathlib import time import uuid import docker import psycopg2 import pytest from dynamicannotationdb.annotation_client import DynamicAnnotationClient from dynamicannotationdb.materialization_client import DynamicMaterializationClient from materializationengine.app impo...
# -*- coding: utf-8 -*- """ cls for File/Image Downloading. """ import os from pathlib import Path from typing import Union, Optional from io import BytesIO from zipfile import ZipFile import requests from requests import Response from tqdm import tqdm from pyatom.base.io import IO from pyatom.base.log import L...
import base64 import hashlib import json import logging from os import urandom from typing import Union, List from fetchai.ledger.bitvector import BitVector from fetchai.ledger.crypto import Identity from fetchai.ledger.parser.etch_parser import EtchParser, UnparsableAddress, UseWildcardShardMask from fetchai.ledger.s...
import os import subprocess import time from dataclasses import dataclass from datetime import datetime from time import sleep from autoleagueplay.bubble_sort_overlay import BubbleSortOverlayData from autoleagueplay.ladder import Ladder from autoleagueplay.load_bots import load_all_bots_versioned from autoleagueplay.m...
# -*- coding: UTF-8 -*- __author__ = 'minhuaxu' import traceback import sys,os sys.path.append(os.path.abspath(os.path.join(os.getcwd(), ".."))) from wpyscripts.tools.baisc_operater import * from wetest_exceptions import * from decision_tree import * record_file_dir = "records/test.txt" class PlayBacker(object): ...
''' Copyright 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, distribute, sublicense,...
# 山灵M0播放器播放列表管理工具自动执行方法库 # ver.11 # By <NAME> import methods import config from random import shuffle from os import remove def auto_opt_combine(playlists, m0_device): # 自动合并列表 if config.AutoOptCombine.switch: print(config.AutoOptCombine.note + " 功能已启用,正在执行功能...") combined_lists = [] ...
import math import torch import torch.nn as nn import os EPS = {torch.float32: 1e-4, torch.float64: 1e-8} class Artanh(torch.autograd.Function): @staticmethod def forward(ctx, x): x = x.clamp(-1 + EPS[x.dtype], 1 - EPS[x.dtype]) ctx.save_for_backward(x) res = (torch.log(1 + x).sub(to...
"""A script for running an already trained SSD model on a video, saving the result as both a video file which can be inspected by humans, and also as a text file. Only uses imageio for video input/output which is nice for when OpenCV is built without video encoding support. """ import cv2 import imageio ...
""" Copyright 2018 <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, software distribut...
''' Lock and execution script ''' from __future__ import (absolute_import, division, print_function, unicode_literals) import atexit import os import signal import socket import subprocess import sys import time import click import psutil from kazoo.client import KazooClient, KazooState from kazoo.exceptions import...
""" 縦横断方向に値を線形補間 入力ポイント間は直線 """ import geopandas as gpd import numpy as np import pandas as pd from scipy import interpolate class PtOnEdge: def __init__(self, fp: str) -> None: """ 横断ラインの始点または終点を縦断方向に並べたポイントデータ Parameters -------- fp : str ポイントデータのファイルパス ...
"""Model managers.""" import warnings from functools import wraps from itertools import count from celery.utils.time import maybe_timedelta from django.db import connections, router, transaction from django.db import models from django.conf import settings from .utils import now W_ISOLATION_REP = """ Polling resu...
# from sqlalchemy import create_engine # from tqdm import tqdm # import pandas as pd def get_df(domain): '''Combine dataset metadatas into a dataframe.''' print('Checking domain...', domain) uids = get_keys(domain) # uids = uids[0:4] # testing names, times, rowCounts, columnCounts, columnNames, b...
# Copyright 2020 The 9nFL Authors. 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 la...
#!/usr/bin/env python # # DNATool - A program for DNA sequence manipulation # Copyright (C) 2012- <NAME> & <NAME> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Licens...
"""N-Dimensional Neighborhood Thresholding for any-dimensional data. Functions --------- ndnt Binarize data with N-Dimensional Neighborhood Thresholding. integral_image Compute the integral image of a n image or volume. integral_image_sum Compute the neighborhood sum of an integral image. Classes ------- ...
from functools import total_ordering import numpy as np class HistoricScoreTable: def __init__(self): self.last = None self.penultimate = None def __add__(self, other): """ a: HistoricScoreTable b: ScoreTable new: HistoricScoreTable """ new =...
# -*- coding: utf-8 -*- import simplejson as json import urllib2 as urllib import datetime, time import base64 import hashlib import random import utils from .env import logging, config logger = logging.getLogger('sms') def format_time(dt): ''':param dt: instance of datetime.datetime''' return time.strftime(...
import sympy import argparse import numpy as np import equations import data import pickle import sys import os from gplearn.genetic import SymbolicRegressor def get_grid(): n_population_size = [15000] p_crossover = [0.6, 0.7, 0.8] p_subtree_mutation = [0.05, 0.1, 0.15] p_hoist_mutation = [0.02, 0.0...
import os import sys import operator import itertools import tabulate sys.path.append(os.path.abspath(os.path.dirname(__file__))) import express_parser import nodes fn1, fn2, output = sys.argv[1:] print("Running difference", *sys.argv[1:]) def eq(a, b): if (type(a) != type(b)): return False elif i...
from functools import reduce from lemoncheesecake.helpers.time import humanize_duration from lemoncheesecake.helpers.text import ensure_single_line_text from lemoncheesecake.helpers.console import print_table from lemoncheesecake.cli.command import Command from lemoncheesecake.cli.utils import auto_detect_reporting_ba...
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Access the rainbow camera images """ # # This method is an a # import os import numpy as np from astropy import time from astropy.io import fits from . import io RAINBOW_DATA_SOURCE = "/scr2/sedm/raw/" SEDMPY_CODE_PATH = "/scr2/sedmdrp/sedmpy/" # READOUT_NOISE =...
# standart modules import zlib # blender modules import bpy import mathutils # addon modules from .. import utils from .. import version_utils plane_items = ( ('XY', 'XY', ''), ('XZ', 'XZ', '') ) place_objects_props = { 'plane': bpy.props.EnumProperty( name='Plane', default='XY', ...
import json from typing import Callable, List, Dict import random import string from unittest.mock import MagicMock from baseline.utils import get_metric_cmp from odin.model.selector import ExperimentRepoExportPolicy, BestOfBatchExportPolicy, BestExportPolicy from odin.store import MemoryStore, Store from xpclient.mod...
import io import numpy as np import tensorflow as tf import tensorflow_addons as tfa import tensorflow_datasets as tfds from tensorflow.keras import layers def _normalize_img(img, label): img = tf.cast(img, tf.float32) / 255. return (img, label) def get_data(data_type = 'mnist', data_kind='img'): train_d...
""" Adapted from PASTIS: https://github.com/hiclib/pastis """ import numpy as np from scipy import optimize from scipy import sparse from sklearn.utils import check_random_state from sklearn.metrics import euclidean_distances def compute_wish_distances(counts, alpha=-3., beta=1., bias=None): if beta == 0: ...
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2008, <NAME>, 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: # # * Redistributions of source code must r...
import numpy as np import random import collections import statistics import json import sys from keras.models import Sequential from keras.layers import * from keras.optimizers import * from environment import * class RandomAgent(object): def __init__(self): self.hand = [] self.hand_ids = [] ...
# !/usr/bin/env python # -*- coding:utf-8 -*- # author: jeremy.zhang(<EMAIL>, Shenzhen University, China) import six import numpy as np import SimpleITK as sitk from skradiomics.utils.modules import PREPROCESSORS @PREPROCESSORS.register_module(name='adjust') def adjust_image(image, mask, settings, **kwargs): wi...
#!/usr/bin/env python import gevent import gevent.monkey gevent.monkey.patch_all() import json from flask import Flask, render_template, session, request from flask_socketio import SocketIO, emit, join_room, leave_room, \ close_room, rooms, disconnect import sys import argparse parser = argparse.ArgumentParser...
from typing import Tuple # NOQA import chainer # NOQA from chainer import cuda from chainer import gradient_check import numpy import pytest from chainer_chemistry.config import MAX_ATOMIC_NUM from chainer_chemistry.links.connection.embed_atom_id import EmbedAtomID from chainer_chemistry.links.update.mpnn_update im...
import json import time import torch import torch.nn.functional as F import os import torch.nn as nn from collections import OrderedDict class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = nn.Conv2d( ...
"""Run DeepLab-ResNet on a given image. This script computes a segmentation mask for a given image. """ from __future__ import print_function import argparse from datetime import datetime import os import sys import time from pathlib import Path from PIL import Image import tensorflow as tf import numpy as np fro...
import os import json import time import traceback import subprocess from typing import Optional import click import requests from ..settings import module_version from .utils import get_nearest_value, read_command_type, forward_languages_config DATETIME_HEADER = "Date" class CommandNotExistError(Exception): "...
import telebot import logging from backend.orm import ( get_user, set_user, set_user_field, get_company_by_password ) from frontend.user_settings import ( ask_language, ask_link, ask_password, ask_name, success_initialization, get_user_settings_menu, success_initialization,...
import events import cProfile import pstats import io def drug_sales(a_stream): """Query a_stream for list of drug sales referenced by drug name. Use events database tool (Sangrey, 07/2018) with builtin modules sort and query for fast database searches. drug_sales uses hashed names for relational da...
# Copyright 2021 VMware, Inc. # SPDX-License-Identifier: Apache-2.0 import logging import os import pathlib from os import getenv from typing import Optional from vdk.api.plugin.hook_markers import hookimpl from vdk.internal.builtin_plugins.config.job_config import JobConfig from vdk.internal.builtin_plugins.config.jo...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import traceback from fastapi import APIRouter, Body, Path, Query, HTTPException from fastapi import File, WebSocket, WebSocketDisconnect from regex import E, FULLCASE from model.code import Code400 from service import pk_service,user_service from fastapi.encod...
"""Functions to make calls to Paypal's NVP API. API Reference: https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/howto_api_reference """ # TODO: Make this an object that gets its own settings (using _SharedBase?) import httplib2 import urllib import urllib2 from datetime import datetime fro...
import os import pathlib import sys from .logger import get_logger from .storage import Storage, LocalStorage from .scraper import MkScraper, AsahiScraper, YomiuriScraper, NewYorkerScraper, GuardianScraper concierge_mode = { 'new': 'fetch_new', 'all': 'fetch_all' } pdf_format = { 'a4': 'a4', 'kindle'...
import os import glob import json import typing import shutil try: import torch except ImportError: torch = None # type: ignore import cv2 import numpy as np import pandas as pd import typing_extensions as tx if typing.TYPE_CHECKING: from .detector import Detector from .. import metrics, core # pylint: ...
import os,sys import snakemake.report import argparse as ap from MAESTRO.scATAC_utility import is_gzip, get_fastqlist, ENV_PATH, SCRIPT_PATH, RSCRIPT_PATH def CommandLineParser(): parser = ap.ArgumentParser(description = "Generate scATAC result report. ") group_input = parser.add_argument_group("Input argum...
""" IBP Parameters BSD 2-Clause License Copyright (c) 2017, <NAME>, Firmlogics (<EMAIL>) All rights reserved. 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 copyrigh...
''' Taken from FantasyPremierLeague-Api.py by spinach and modified https://github.com/spinach/FantasyPremierLeague-Api.py/blob/master/playersPickedInLeague.py Use this to make calls to the FPL API ''' import requests import json import csv import argparse import os import pathlib import sys #load the env variables # ...
import os import re import requests import sys import yaml def check_white_list(k, white_list, filename): """ check white list :param k: yaml fields :param white_list: white list :param filename: path of yaml file :return: errors """ if k not in white_list: prin...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import unicode_literals import json from typing import Dict, Text, Any, TextIO, Type, Set, Union, List from cryptography.hazmat.backends.openssl import x509 from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePubl...
# coding: utf-8 # In[254]: import pandas as pd import numpy as np import os from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error # In[255]: #checking the path directory print("Previous directory",os.getcwd()) #Now changing the path directory path=r"C:\Users\Pavan\Desk...
import os import re import datetime import logging import textwrap import requests from bs4 import BeautifulSoup try: from version import __version__, useragentname, useragentcomment from util import StyledLazyBuilder, nowBerlin except ModuleNotFoundError: import sys include = os.path.relpath(os.path....
import torch import pickle from transformers import BartTokenizer, BartForConditionalGeneration, BartConfig, set_seed import random set_seed(0) def joint_pack_of_banned_words(pack_of_banned_words): concatenation_of_the_entire_banned_words = [] for each_banned_word in pack_of_banned_words: for type_of_...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import json import random import time import torch import torch.nn as nn import torch.optim import tqdm import os import speech import speech.loader as loader import speech.models as models # ...
# <NAME> # <EMAIL> from math import cos, sin, tan, pi from random import uniform def evaluate(solution_function, obs, verbose=False): # initialise environment env = Environment(obs=obs) # initialise car with that environment car = Car(env) # execute student's solution function controls, tim...
from math import sqrt import torch import torch.nn.functional as F from torch import nn, einsum from einops import rearrange, repeat from einops.layers.torch import Rearrange # constants TOKEN_ATTEND_SELF_VALUE = -5e-4 # helpers def exists(val): return val is not None def default(val, d): return val if ex...
# -*- coding: UTF-8 -*-# """Serializers to import/export, list the workflows.""" from builtins import object, str from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers from rest_framework.exceptions import APIException from ontask.action.serializers import ActionSerializer f...
# usb midi step sequencer for raspberry pi pico # written for circuitpython v6.2.0 # requires the following libs: # - adafruit_bus_device # - adafruit_dotstar # - adafruit_midi import board import time import random # led control import adafruit_dotstar from digitalio import DigitalInOut, Direction # button access i...
import cmd from minidump.minidumpfile import * from minidump.common_structs import hexdump def args2int(x): if isinstance(x, int): return x elif isinstance(x, str): if x[:2].lower() == '0x': return int(x[2:], 16) elif x[:2].lower() == '0b': return int(x[2:], 2) else: return int(x) else: raise E...
from nltk.corpus import treebank from nltk.tree import Tree from nltk.stem import WordNetLemmatizer wnl = WordNetLemmatizer() from nltk.corpus import wordnet as wn import VerbMorph import PTBdata import pickle #selects first synonym def defaultselectfunc(l): if len(l)>1: return l[1] return l[0] def c...
# from python from collections import Counter import random # from pypi from expects import ( be, be_true, contain_exactly, expect, raise_error, ) from pytest_bdd import ( given, scenarios, when, then ) import numpy # this testing from fixtures import katamari # software under t...
import base64 import hashlib import json import logging import os import sys import tempfile from time import sleep import boto3 from botocore.exceptions import ClientError from lib import main from pulse3D.excel_writer import write_xlsx from pulse3D.plate_recording import PlateRecording SQS_URL = os.environ.get("SQ...
import numpy as np from numpy.linalg import cholesky, det from scipy.linalg import solve_triangular from scipy.optimize import minimize from numpy.linalg import inv import pandas as pd import math import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import animation, cm #Prior functi...
# Copyright 2017. <NAME>. All rights reserved # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the # following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following # dis...
import pickle import torch import torch.nn as nn import numpy as np from .libs.Matrix import CNN import torch.backends.cudnn as cudnn from .libs.models import encoder3,encoder4 from .libs.models import decoder3,decoder4 # Modified from Original: https://github.com/sunshineatnoon/LinearStyleTransfer class MulLayer(nn...
import os from unittest.mock import ANY import pytest from dvc_objects.fs.implementations._memory import MemFS2 @pytest.fixture def m(): return MemFS2() def test_memfs_should_not_be_cached(): assert MemFS2() is not MemFS2() def test_1(m): m.touch("/somefile") # NB: is found with or without initial ...
# Copyright 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
from __future__ import annotations from typing import Any, Dict, List, Optional, Union import dataclasses import datetime from pywhmcs import base from pywhmcs import exceptions @dataclasses.dataclass class Order(base.BaseResource): id: int amount: float client_id: int contact_id: Optional[int] c...
#!/opt/local/bin/python """ This script analyzes morphometric data from a labeled cell image and extracts cell sizes, aspect ratios, orientations and shape factors. """ import os from copy import deepcopy import numpy as np import matplotlib.pyplot as plt from matplotlib import patches from matplotlib import color...
## Copyright 2018-2021 Intel Corporation ## SPDX-License-Identifier: Apache-2.0 import os import sys import struct import json import csv import zipfile import time import socket import numpy as np import torch import torch.nn as nn import torch.multiprocessing as mp import torch.distributed as dist WORKER_RANK = 0 ...
import re from colour import Color from django.contrib.admin.utils import lookup_field from django.core.exceptions import ObjectDoesNotExist from django.core.urlresolvers import NoReverseMatch, reverse from django.db.models import ForeignKey from django.template.defaulttags import NowNode from django.utils.safestring...
import numpy as np import torch from torch._six import int_classes as _int_classes from torch.utils.data import DataLoader from torch.utils.data.dataloader import default_collate from torch.utils.data.sampler import Sampler, SubsetRandomSampler class BaseDataLoader(DataLoader): """ Base class for all data loa...
import logging from argparse import ArgumentParser import pytest import pytorch_lightning as pl import torch from ride.core import AttributeDict, RideMixin, RideModule from ride.optimizers import SgdOptimizer from ride.utils.utils import DictLike from .dummy_dataset import DummyRegressionDataLoader pl.seed_everythi...
import argparse import base64 import configparser import io import json import logging import math import pathlib import sys import uuid __all__ = ['column_types', 'default_datetime_format', 'InternetNode'] # todo parametric columns column_types = { 'Numerical': '$num', 'Integer': '$num_int', 'Boolea...
# -*- encoding: utf-8 -*- import networkx as nx import numpy as np from model import MultiHSD, HSD from tools import evaluate, dataloader, rw, util def base_HSD_Test(graphName, hop=3, metric="wasserstein"): graph = nx.read_edgelist(f"data/graph/{graphName}.edgelist", create_using=nx.Graph, edgetype=float, ...
from __future__ import annotations from typing import TYPE_CHECKING, Any, Optional, Protocol, TypedDict if TYPE_CHECKING: from asyncpg import Pool from ..main import JDBot, JDBotContext class RecordType(Protocol): def get(self, key: str) -> Any: ... class TicketCacheData(TypedDi...
# import statements from PyQt5.QtCore import QEvent, QObject, QSize, QThread, Qt, pyqtSignal from PyQt5.QtGui import QPixmap from PyQt5.QtWidgets import QApplication, QHBoxLayout, QMainWindow, QLabel, QVBoxLayout, QWidget, QPushButton, QTextEdit import sys from gtts import gTTS from playsound import playsound from plat...
# coding=utf-8 # Copyright 2021 The TensorFlow Datasets 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 appl...
from pygame import * import pprint import covid import WebScrape import destination #global font variable font.init() title_font = font.SysFont('Calibri', 80) body_font = font.SysFont('Calibri', 50) testbodysurface = body_font.render("Test", False, (0,0,0)) '''Images''' icon_covid = image.load("I...
from __future__ import absolute_import import logging import numpy as np from . import numpy as npext from ..exceptions import ValidationError logger = logging.getLogger(__name__) def spikes2events(t, spikes): """Return an event-based representation of spikes (i.e. spike times)""" spikes = npext.array(spik...
#!/usr/bin/env python """ Author: <NAME> <<EMAIL>> 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...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import get_object_or_404, redirect from django.http import HttpResponseRedirect, Http404 from django.contrib.contenttypes.fields import ContentType from django.c...
import argparse import glob from os.path import join as path_join from os.path import abspath, basename, isfile from os import makedirs, pardir, remove, listdir, sep, urandom from subprocess import Popen, PIPE from tempfile import gettempdir from shutil import rmtree, copyfile import re import sys from locale import ge...
# -*- coding:utf-8 -*- """ Created on Wed Nov 21 12:43 2019 @author <NAME> - <EMAIL> Run - one or several simulations with all states of outputs """ from ABM_CE_PV_Model import * import matplotlib.pyplot as plt import time def run_model(number_run, number_steps): """ Run model several times and collect out...
from neo4j.v1 import types from .cypher import Cypher, Properties, Query from .db import driver from .exceptions import CypherError, CypherIdAlreadyUsed from .functions import fn from .utils import clone, split_id_args class Graph: def __init__(self): self.query = Query() def run(self): with...
""" Read a checkpoints and export its weights to a numpy variable """ # import os import sys import numpy as np import tensorflow as tf def getTensor(file_name, weight_name): try: reader = tf.train.NewCheckpointReader(file_name) print(reader.debug_string().decode("utf-8")) if(weight_na...
""" Adapted from the Pymanopt toolbox Copyright (c) 2015-2016, Pymanopt Developers. All rights reserved. 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 noti...
import sys import tempfile import atexit import shutil import sysconfig import pathlib import os import subprocess from setuptools import setup, Extension # as per https://stackoverflow.com/questions/19569557/pip-not-picking-up-a-custom-install-cmdclass from setuptools.command.install import install as setuptools__inst...
import cv2 import numpy as np import os import track_hands as TH class VideoCamera(): def __init__(self,overlay_image=[],draw_color =(255,200,100)): self.cap = cv2.VideoCapture(0,cv2.CAP_DSHOW) self.cap.set(3, 1280) self.cap.set(4,720) self.xp =0 self.yp =0 self.x1 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2019 Dubalu LLC # Copyright (c) 2017 Elasticsearch # # 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 owner...
import logging from random import randint from flask import Flask, render_template, send_file from flask_ask import Ask, request, session, context, question, statement app = Flask(__name__, static_url_path='/static') ask = Ask(app, "/") logging.getLogger("flask_ask").setLevel(logging.DEBUG) image_url = 'https://...
from django.conf import settings from zerver.lib.actions import set_default_streams, bulk_add_subscriptions, \ internal_prep_stream_message, internal_send_private_message, \ create_stream_if_needed, create_streams_if_needed, do_send_messages, \ do_add_reaction_legacy, create_users from zerver.models impor...
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016,2017 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Y...
import sys import os import toolshed as ts from cyvcf2 import VCF, Writer HERE = os.path.dirname(__file__) fname = os.path.join(HERE, "score-lookup.txt") lookup = {(d['from_short'], d['to_short']): d for d in ts.reader(fname)} maxg, maxmb, minb = 0, 0, 0 for v in lookup.values(): if v['Grantham']: v['Gra...