content
stringlengths
0
894k
type
stringclasses
2 values
#!/usr/bin/env python # coding: utf-8 # In[2]: # In[6]: # In[16]: # In[18]: # In[21]: from __future__ import division, print_function # coding=utf-8 import streamlit as st import h5py from PIL import Image import os import numpy as np import json import predict3 from tensorflow.keras.models impor...
python
#!/usr/bin/env python3 from mpl_toolkits.mplot3d import Axes3D from rasterization import Rasterizer from transformation import multiply from transformation import TransformGenerator import argparse import DirectLinearTransform import json import math import matplotlib import matplotlib.image as mpimg import matplotlib....
python
#!/usr/bin/env python3 import argparse import gym import gym-minigrid from baselines import bench, logger from baselines.common import set_global_seeds from baselines.common.cmd_util import make_atari_env, atari_arg_parser from baselines.a2c.a2c import learn from baselines.ppo2.policies import MlpPolicy from baselines...
python
import os import torch from torch import tensor from typing import Optional, Tuple from dataclasses import dataclass from schemes import EventDetectorOutput from models import BaseComponent from models.event_detection.src.models.SingleLabelSequenceClassification import SingleLabelSequenceClassification from stores.onto...
python
"""test2 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based...
python
import xarray as xr import numpy as np from xrspatial import hillshade def _do_sparse_array(data_array): import random indx = list(zip(*np.where(data_array))) pos = random.sample(range(data_array.size), data_array.size//2) indx = np.asarray(indx)[pos] r = indx[:, 0] c = indx[:, 1] data_ha...
python
from django.test import TestCase from django.contrib.auth.models import User from .models import Profile,Procedure # Create your tests here. class ProfileTestClass(TestCase): def setUp(self): self.new_user = User.objects.create_user(username='user',password='password') self.new_profile = Profile(id...
python
'''Create a segmentation by thresholding a predicted probability map''' import os import logging from time import time as now import numpy as np import configargparse as argparse import daisy logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) # patch: suppre...
python
import os import time import pandas as pd import numpy as np import xgboost as xgb import lightgbm as lgb import warnings warnings.filterwarnings('ignore') from sklearn.metrics import log_loss from sklearn.model_selection import train_test_split, StratifiedKFold def lgb_foldrun(X, y, params, name): skf = Stratif...
python
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Session' db.create_table('django_session', ( ('session_key', self.gf('django.db....
python
# =============================================================================== # Copyright 2012 Jake Ross # # 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/licens...
python
import unittest from circleofgifts.dealer import Dealer class DealerTestCase(unittest.TestCase): def test_sorted_deal(self): """Test deal which uses sorted() as the sort method for both teams and players. This makes the results predicable.""" players = [['Pierre', 'Paul'], ['Jeanne', 'Jul...
python
from django.shortcuts import render from django.http import HttpResponse def explore(request): return HttpResponse('This will list all chemicals.') def my_chemicals(request): return HttpResponse('This will list MY chemicals!')
python
import re # Your puzzle input is 246540-787419. ## Part 1 pwords = [] for i in range(246540,787419): if(int(str(i)[0]) <= int(str(i)[1]) <= int(str(i)[2]) <= int(str(i)[3]) <= int(str(i)[4]) <= int(str(i)[5])): if((str(i)[0] == str(i)[1]) or (str(i)[1] == str(i)[2]) or (str(i)[2] == str(i)[3]) or (str(i)[...
python
class Server(object): def __init__(self, host, port): self.host = host self.port = port def get_host(self): return self.host def get_port(self): return self.port class MailType(object): def __init__(self): pass
python
from django import template import base64 from socialDistribution.models.post import Post, InboxPost from socialDistribution.utility import get_post_like_info, get_like_text register = template.Library() # Django Software Foundation, "Custom Template tags and Filters", 2021-10-10 # https://docs.djangoproject.com/en/3...
python
""" Setup of core python codebase Author: Jeff Mahler """ import os from setuptools import setup requirements = [ "numpy", "scipy", "scikit-image", "scikit-learn", "ruamel.yaml", "matplotlib", "multiprocess", "setproctitle", "opencv-python", "Pillow", "joblib", "colorlog...
python
from collections.abc import Iterable from itertools import chain, product import pprint import inspect from .nodes import * from .graph import * class GraphGenerator(): def __init__(self, specifications): """ Parameters ---------- specifications: Iterable[Specification] -- TODO ...
python
# -*- coding: utf-8 -*- # --------------------------------------------------------------------- # Allocated Blocks Report # --------------------------------------------------------------------- # Copyright (C) 2007-2019 The NOC Project # See LICENSE for details # --------------------------------------------------------...
python
from buildbot.config import BuilderConfig from buildbot.changes.gitpoller import GitPoller from buildbot.plugins import util, schedulers from buildbot.process.factory import BuildFactory from buildbot.process.properties import Interpolate from buildbot.process import results from buildbot.steps.source.git import Git fr...
python
import numpy as np # from crf import Sample, CRF from crf_bin import Sample, CRFBin trainCorpus = "/home/laboratory/github/homeWork/machineTranslation/data/train.txt" testCorpus = "/home/laboratory/github/homeWork/machineTranslation/data/test.txt" labelTableverse = {} print("cache label...") with open("/home/laborat...
python
# architecture.py --- # # Filename: architecture.py # Description: defines the architecture of the 3DSmoothNet # Author: Zan Gojcic, Caifa Zhou # # Project: 3DSmoothNet https://github.com/zgojcic/3DSmoothNet # Created: 04.04.2019 # Version: 1.0 # Copyright (C) # IGP @ ETHZ # Code: # Import python dependencies import...
python
from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): """ Extension of User model """ user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) # if vacation mode is set ...
python
# -*- coding: utf-8 -*- """DigitRecognizer.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/149_-4guTkO2Vzex8bjA402nPcJ_Z7G7W #***Digit Recognizer(MNIST) dataset using CNN*** """ import numpy as np import pandas as pd import matplotlib.pyplot as...
python
# See LICENSE file for full copyright and licensing details. #from . import models
python
import numpy as np import utils # class Piece: # def __init__(self,color = 0, pos=(-1,-1)): # self.color = color # self.pos = pos class Player: def __init__(self, collected_flag=np.zeros(9), collected_shape_dict={}, collected_num=0): self.collected_flag = np.zeros((9,2)) # 收集过...
python
"""Integration with nest devices.""" import json import logging import sys from google.appengine.api import urlfetch from google.appengine.ext import ndb from appengine import account, device, rest @device.register('nest_thermostat') class NestThermostat(device.Device): """Class represents a Nest thermostat.""" ...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os def run_tests(**options): import django import sys from django.conf import settings from ginger.conf.settings import template_settings defaults = dict( MIDDLEWARE_CLASSES=( 'django.contrib.sessions.middleware....
python
from __future__ import print_function import os from os.path import dirname, join, abspath, isdir import sys import json import requests try: from urlparse import urljoin except: from urllib.parse import urljoin # python 3.x # http://python-redmine.readthedocs.org/ from redmine import Redmine if __name...
python
import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * vertices = ( # ( x, y, z) ( 1, -1, -1), # A ( 1, 1, -1), # B (-1, 1, -1), # C (-1, -1, -1), # D ( 1, -1, 1), # E ( 1, 1, 1), # F (-1, -1, 1), # G (-1, 1, 1) # ...
python
#!/usr/bin/env python import argparse import math from collections import Counter from spawningtool.parser import parse_replay def map_replays(filenames, map_fn, results, update_fn, cache_dir=None, **kwargs): for filename in filenames: filename = filename.rstrip('\n') replay = parse_replay(filena...
python
import numpy as np class Exploration_Noise: def reset(self): """ Reset the noise generator. """ pass def process_action(self, a): """ Add noise to the given action. Args: a: the action to be processed Return: the proces...
python
from scrapy.http import Request from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector class HackernewsSpider(BaseSpider): name = 'hackernews' allowed_domains = [] start_urls = ['http://news.ycombinator.com'] def parse(self, response): if 'news.ycombinator.com' in response.url: ...
python
import sys sys.path.insert(0, '/home/vagrant/Integration-Testing-Framework/sikuli/examples') from sikuli import * from test_helper import TestHelper from flex_regions import * from Regionplus import * # Setup helper = TestHelper("drag_column") set_flex_helper(helper) # Opening ############# helper.Click("Lexicon.png...
python
# Copyright 2018 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...
python
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: yandex/cloud/logging/v1/log_ingestion_service.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflect...
python
""" Tests of simple 2-layer PCBs """ from . import plotting_test_utils import os import mmap import re import logging def expect_file_at(filename): assert(os.path.isfile(filename)) def get_gerber_filename(board_name, layer_slug, ext='.gbr'): return board_name + '-' + layer_slug + ext def find_gerber_ap...
python
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2019-01-09 07:00 from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('sass', '0003_auto_20190109_0659'), ] operation...
python
""" Fetch ads.txt files from URLs """ from datetime import datetime import logging import os import pandas as pd import requests logger = logging.getLogger(__name__) HEADERS = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36", "Accept...
python
## # Copyright 2021 IBM Corp. All Rights Reserved. # # SPDX-License-Identifier: Apache-2.0 ## import torch from ...._utils import val_clamp from ..node import _NodeActivation from ....constants import Direction from ...parameters.neuron import _NeuronParameters """ Dynamic activation function """ class _NeuronAct...
python
from PIL import Image import pytesseract def extractWords(): img1 = Image.open("Solution\images\img1.jpg") img2 = Image.open("Solution\images\img2.jpg") engText = pytesseract.image_to_string(img1, lang='eng') araText = pytesseract.image_to_string(img2, lang='ara') print(engText) print(araText) ...
python
import lab12 def createSomePlanets(): aPlanet=lab12.Planet("Zorks",2000,30000,100000,5,['Steve','Lou','The Grinch']) bPlanet=lab12.Planet("Zapps",1000,20000,200000,17,[]) print(aPlanet.getName() + " has a radius of " + str(aPlanet.getRadius())) planetList=[aPlanet,bPlanet] for planet in planetList:...
python
from .__init__ import * def home(request): return Http_Response("", "这是视频API", "") def url(request): # 获取视频URL query = request_query(request, "id", ["res", {"resolution": 1080}]) query["ids"] = '["{}"]'.format(query.pop("id")) data = send(query).POST("weapi/cloudvideo/playurl") return Http_R...
python
# # PySNMP MIB module BNET-ATM-TOPOLOGY-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BNET-ATM-TOPOLOGY-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:40:07 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
python
# -*- coding: utf-8 -*- """ Created on Mar 11, 2012 @author: moloch Copyright 2012 Root the Box 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/licen...
python
# License: BSD 3 clause from datetime import datetime from typing import Dict, Iterable from os.path import join from pyspark.sql import DataFrame from pyspark.sql.functions import col, datediff, floor, lit, months_between from scalpel.core.io import get_logger, read_data_frame from scalpel.core import io from scalp...
python
"""Bagging classifier trained on balanced bootstrap samples.""" # Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com> # Christos Aridas # License: MIT import numbers import numpy as np from sklearn.base import clone from sklearn.ensemble import BaggingClassifier from sklearn.tree import DecisionTreeClassi...
python
# import theano.sandbox.cuda # theano.sandbox.cuda.use('gpu0') import numpy as np import cPickle as cP import theano as TH import theano.tensor as T import scipy.misc as sm import nnet.lasagnenetsCFCNN as LN import lasagne as L import datetime def unpickle(file): import cPickle fo = open(file, 'rb') d...
python
import tequila as tq class QMBackend(): """ A class that holds information about a backend and can be given as a parameter to an algorithm. Attributes ---------- backend : str The name of the used backend (simulator). """ def __init__(self, backend: str = None): """ Creates a QMBackend o...
python
#!/usr/bin/env python3.7 """ The copyrights of this software are owned by Duke University. Please refer to the LICENSE and README.md files for licensing instructions. The source code can be found on the following GitHub repository: https://github.com/wmglab-duke/ascent """ import os import sys sys.path.append(os.pat...
python
# -*- coding: utf-8 -*- """ pygments.lexers.smv ~~~~~~~~~~~~~~~~~~~ Lexers for the SMV languages. :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.lexer import RegexLexer, words from pygments.token import Comment, Generic...
python
fahrenheit = float(input("Enter temperature in Fahrenheit: ")) print("The temperature in Celsius: ", (fahrenheit-32)*(5/9))
python
""" Tool for extending the label information with the chess game state, i.e. the camera piece color and square content. """ import argparse import cv2 as cv from rookowl.global_var import PIECE_DISPLAY_SHAPE from rookowl.label import load_labels, save_label # =≡=-=♔=-=≡=-=♕=-=≡=-=♖=-=≡=-=♗=-=≡=-=♘=-=≡=-=♙=-=≡=-=...
python
import torch import torch.nn as nn import torch.nn.functional as F # 한 Batch에서의 loss 값 def batch_loss(loss, images): return loss.item() * images.size(0) class FocalLoss(nn.Module): def __init__(self, weight=None, gamma=2.0, reduction="mean"): nn.Module.__init__(self) self.weight = weight ...
python
def spread_pixels(Nside_low, Nside_high, ID): from math import log Llow = int(log(Nside_low, 2)) Lhigh = int(log(Nside_high, 2)) print(Llow, Lhigh) b = bin(ID) DN = Lhigh-Llow a = [bin(i)[2:].zfill(2**DN) for i in range(4**DN)] pix_IDs = [] for i in a: x = (b[2:].zfill(...
python
#!/usr/bin/env python """Play a fixed frequency sound.""" from __future__ import division import math from pyaudio import PyAudio # sudo apt-get install python{,3}-pyaudio try: from itertools import izip except ImportError: # Python 3 izip = zip xrange = range def sine_tone(stream, frequency, duration, v...
python
#!/usr/bin/env python3 """Forward kinematic example using pinocchio Sends zero-torque commands to the robot and prints finger tip position. """ import os import numpy as np from ament_index_python.packages import get_package_share_directory import pinocchio import robot_interfaces import robot_fingers if __name__ == ...
python
if __name__ == '__main__' and __package__ is None: import sys from os import path sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) )) import os import torch from utils.model_serialization import strip_prefix_if_present from utils import zipreader import argparse from tqdm import tqdm i...
python
import datetime from termcolor import cprint import get_all_caches as caches def calculate_all_prices(fiat='EUR', coin='XMR', start='04-02-2020', high_low='high', coin_amount=int(42), fiat_amount_spent=int(0)): coin_amount = int(coin_amount) # double casting to int here prevents crashes later on historical_...
python
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, James Cammarata <jcammarata@ansible.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1...
python
#!/usr/bin/python # -*- coding: utf-8 -*- # make it possible to run as standalone program import sys import re import random import string sys.path.append('/srv/chemminetools') sys.path.append('/srv/chemminetools/sdftools') # allow tools.py to be imported from django.core.management import setup_environ import chemm...
python
import os import argparse import numpy as np class SceneGraphNode(object): def __init__(self): pass def set_attribute(self, attr, value): if attr not in self.__dict__.keys(): raise ValueError(f"Unknown attribute: {attr}") self.__dict__[attr] = value def get_attri...
python
c = {'z': '\033[m'} l = ['w', 'r', 'g', 'y', 'b', 'm', 'c', 'k'] i = j = 0 for lin in range(30, 38): c[l[i]] = f'\033[{lin}m' i += 1 i = j = 0 for lin in range(30, 38): for col in range(40, 48): c[l[i] + l[j]] = f'\033[{lin};{col}m' j += 1 i += 1 j = 0 def clr(text='', value='z')...
python
# Generated by Django 3.2.9 on 2022-01-15 21:28 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('api', '0002_auto_20220115_1425'), ] operations = [ migrations.AlterField( model_name='comments'...
python
import sys import os import configparser import tkinter as tk import tkinter.ttk as ttk from tkinter import messagebox from functools import partial from PIL import ImageTk, Image from tkinter import filedialog class Gui: """ This class represents a GUI for reading, changing and writing purposes. The...
python
""" Tests CoreML Imputer converter. """ import numpy as np import unittest try: from sklearn.impute import SimpleImputer as Imputer import sklearn.preprocessing if not hasattr(sklearn.preprocessing, 'Imputer'): # coremltools 3.1 does not work with scikit-learn 0.22 setattr(sklearn.preprocess...
python
from django.core.exceptions import ValidationError def following_changed(sender, action, instance, *args, **kwargs): """Raise an error if admin tries to assign User to the Users follow list""" # m2mchanged.connect specified in apps.py following = instance.following.all() creator = instance.user ...
python
from arcutils.settings import PrefixedSettings DEFAULTS = { 'default': { # Notes: # - There are two LDAP hosts, ldap-bulk and ldap-login; Elliot has # said that ldap-login "has more servers in the pool" and he # recommends using it over ldap-bulk (RT ticket #580686); n...
python
from django.contrib import admin from ledger.accounts.models import EmailUser from disturbance.components.proposals import models from disturbance.components.proposals import forms from disturbance.components.main.models import ActivityMatrix, SystemMaintenance, ApplicationType #from disturbance.components.main.models ...
python
# Copyright 2019 Belma Turkovic # TU Delft Embedded and Networked Systems Group. # NOTICE: THIS FILE IS BASED ON https://github.com/p4lang/behavioral-model/blob/master/mininet/p4_mininet.py, BUT WAS MODIFIED UNDER COMPLIANCE # WITH THE APACHE 2.0 LICENCE FROM THE ORIGINAL WORK. # Copyright 2013-present Barefoot Netw...
python
from rl.agent import DiscreteAgent from rl.environment import DiscreteEnvironment from rl.experience_tuple import ExperienceTupleSerializer class ExperimentConfiguration: """Configuration to run an Experiment.""" def __init__(self, agent: DiscreteAgent, environment: DiscreteEnvironment, num_...
python
""" DREAprep.py - Allows for inputs to be passed to multiple components """ from openmdao.main.api import Component, Slot from openmdao.lib.datatypes.api import Float from MEflows import MEflows class DREAprep(Component): """ Passes input variables to output variables so they can be passed to multi...
python
from multiprocessing import current_process, Value, Process from time import sleep from random import random from reader_writer_lock import MultiprocessingFactory from reader_writer_lock.MpFactory import Integer def test(option): test_name = ["No priority", "Read priority", "Write priority"] prin...
python
import numpy as np class FCM: """Fuzzy C-means Parameters ---------- n_clusters: int, optional (default=10) The number of clusters to form as well as the number of centroids to generate max_iter: int, optional (default=150) Hard limit on iterations within solver. m: f...
python
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 19-1-24 下午4:04 # @Author : Hubery # @File : helper.py # @Software: PyCharm import json import requests from django.core.cache import cache from HuberyBlog.settings import BASE_HEADERS def page_cache(timeout): def wrapper1(view_func): def wrapp...
python
import re #!/usr/bin/env python3 def getStarSystems(): starsfound = re.compile("\Stars Visited\": (\alnum+\.\alnum+)") result = starsfound.findall(content) stars = [] if result: for r in result: stars.append(r) print(result) return stars
python
import os import sys import tempfile import subprocess import contextlib import json import time # https://stackoverflow.com/questions/6194499/pushd-through-os-system @contextlib.contextmanager def pushd(new_dir): previous_dir = os.getcwd() os.chdir(new_dir) try: yield finally: os.chdi...
python
import pandas as pd import shutil from shareplum import Site from shareplum.site import Version from shareplum import Office365 # SharePoint user_name = '@eafit.edu.co' password = '' authcookie = Office365('https://eafit.sharepoint.com', username=user_name, password=password).GetCookies() site = Site('https://eafit.s...
python
# # Copyright (c) 2019, Corey Smith # # Distributed under the MIT License. # # See LICENCE file for full terms. # """ # Tests for the data examples. # """ # # import sys # import inspect # # import os # from pathlib import Path # import numpy as np # # import paramiko # # import pytest # # import sqlalchemy # # sy...
python
""" Helios Signals Effectively callbacks that other apps can wait and be notified about """ import django.dispatch # when an election is created election_created = django.dispatch.Signal(providing_args=["election"]) # when a vote is cast vote_cast = django.dispatch.Signal( providing_args=["user", "voter", "elec...
python
from setuptools import setup, find_packages import sys import os import re org = 'PEtab-dev' repo = 'petab_select' def read(fname): """Read a file.""" return open(fname).read() def absolute_links(txt): """Replace relative petab github links by absolute links.""" raw_base = \ f"(https://ra...
python
REGISTRY = {} from .episode_runner import EpisodeRunner REGISTRY["episode"] = EpisodeRunner from .parallel_runner import ParallelRunner REGISTRY["parallel"] = ParallelRunner from .episode_cross_runner import EpisodeCrossRunner REGISTRY["cross"] = EpisodeCrossRunner
python
import numpy as np import pandas as pd from sklearn.metrics.pairwise import euclidean_distances from scipy.io import loadmat from matplotlib import pyplot as plt from sklearn.metrics import normalized_mutual_info_score from sklearn.metrics import adjusted_rand_score def autoselect_dc(max_id, max_dis, min_dis, ...
python
from __future__ import print_function import math, types import numpy as N import matplotlib.pyplot as P def plotres(psr,deleted=False,group=None,**kwargs): """Plot residuals, compute unweighted rms residual.""" res, t, errs = psr.residuals(), psr.toas(), psr.toaerrs if (not deleted) and N.any(psr.d...
python
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the NiBabel package for the # copyright and license terms. # ### ### ### #...
python
import pathlib import shutil import argparse parser = argparse.ArgumentParser() parser.add_argument("--supplementary_pdf", type=str) args = parser.parse_args() supplementary = pathlib.Path(args.supplementary_pdf) if args.supplementary_pdf else None assert supplementary.exists() and supplementary.is_file() root = (pat...
python
import datetime import json from datetime import date,timedelta from selenium import webdriver from selenium.webdriver.common.keys import Keys from operis.log import log from ws4redis.redis_store import RedisMessage from ws4redis.publisher import RedisPublisher from selenium_tests.webdriver import PpfaWebDriver #from...
python
from flask import Flask from flask_assets import Bundle, Environment from flask_compress import Compress from flask_talisman import Talisman from flask_wtf.csrf import CSRFProtect from govuk_frontend_wtf.main import WTFormsHelpers from jinja2 import ChoiceLoader, PackageLoader, PrefixLoader from config import Config ...
python
def operate(operator, *args): return eval(operator.join([str(x) for x in args])) print(operate("+", 1, 2, 3)) print(operate("*", 3, 4))
python
# Generated by Django 2.0.8 on 2019-06-05 09:32 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('protein', '0007_proteingproteinpair_references'), ('structure', '0017_structure_contact_representative_score'), ('residue', '0002_auto_20180504_1417'...
python
# -*- coding: utf-8 -*- # Copyright 2019 Tomoki Hayashi # MIT License (https://opensource.org/licenses/MIT) """Utility functions.""" import fnmatch import logging import os import sys import tarfile from distutils.version import LooseVersion import numpy as np import torch import yaml def find...
python
from Attribute import Attribute from Distribution.DistributionFactory import DistributionFactory class AttributeFactory: """ Class to generate and deploy specific attributes that will share a distribution factory. Attributes types are: - custom - boolean - string - int or int64 ...
python
from django.core.management.base import BaseCommand, CommandError from charts.models import ChartConfig class Command(BaseCommand): help = "Delete all ChartConfig objects" def handle(self, *args, **options): all = ChartConfig.objects.all() self.stdout.write("{} ChartConfig Type objects will...
python
#!/usr/bin/env python # # Author: Qiming Sun <osirpt.sun@gmail.com> # ''' Dirac Hartree-Fock ''' import ctypes import time from functools import reduce import numpy import scipy.linalg from pyscf import lib from pyscf.lib import logger from pyscf.scf import hf from pyscf.scf import _vhf import pyscf.scf.chkfile def...
python
import sys import requests import time import datetime # API URLS URL_STATS_PROVIDER = 'https://api.nicehash.com/api?method=stats.provider&addr={}' URL_BTC_PRICE = 'https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC&tsyms={}' WALLET = '1P5PNW6Wd53QiZLdCs9EXNHmuPTX3rD6hW' #Dummy wallet. To be overwritten ##...
python
import copy import argparse import os from PIL import Image import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision.transforms as transforms import torchvision.models as models from LossFunction import ContentLoss, StyleLoss plt...
python
import os from dotenv import load_dotenv dirname = os.path.dirname(__file__) try: #print(os.path.join(dirname, '.env')) load_dotenv(dotenv_path=os.path.join(dirname, '.env')) except FileNotFoundError: pass
python
#!/home/alvaro/.miniconda3/envs/fazip/bin/python from fazip import fazip import sys import getpass def do_extraction(zipname): host, user, pwd = fazip.get_mysql_info() db = fazip.connect_to_db(user, pwd, host) fazip.unzip_files(db, zipname) db.close() def do_compression(zipname, files): host, u...
python
import sys, os sys.path.append(os.pardir) from lark import Lark, Token from parsing import grammar, cool_ast, preprocess from parsing.cool_transformer import ToCoolASTTransformer from checksemantic.checksemantics import CheckSemanticsVisitor from checksemantic.scope import Scope from cool import fetch_program ...
python
#!/usr/bin/env python # -*- animation -*- """ Visualize a complex-valued function """ import numpy as np import gr def domain_colors(w, n): H = np.mod(np.angle(w) / (2 * np.pi) + 1, 1) m = 0.7 M = 1 isol = m + (M - m) * (H * n - np.floor(H * n)) modul = np.absolute(w) Logm = np.log(modul) ...
python